third_party: move vanadium build monitor Jenkins plugin from infrastructure repo to third_party.
MultiPart: 1/2
Change-Id: I61b2bc70caa29dd624fcf2b73b5281d0067ef6a2
diff --git a/java/jenkins_plugins/build_monitor/.README/0_A_place_to_start.png b/java/jenkins_plugins/build_monitor/.README/0_A_place_to_start.png
new file mode 100644
index 0000000..1b2646b
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/.README/0_A_place_to_start.png
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/.README/1_Adding_jobs.png b/java/jenkins_plugins/build_monitor/.README/1_Adding_jobs.png
new file mode 100644
index 0000000..dce78a0
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/.README/1_Adding_jobs.png
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/.README/2_Three_columns_view.png b/java/jenkins_plugins/build_monitor/.README/2_Three_columns_view.png
new file mode 100644
index 0000000..3a178e5
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/.README/2_Three_columns_view.png
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/.README/3_Two_columns_view_with_claim_and_build_failure_analyzer_plugins.png b/java/jenkins_plugins/build_monitor/.README/3_Two_columns_view_with_claim_and_build_failure_analyzer_plugins.png
new file mode 100644
index 0000000..f2ced28
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/.README/3_Two_columns_view_with_claim_and_build_failure_analyzer_plugins.png
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/.README/4_Colour_blind_mode.png b/java/jenkins_plugins/build_monitor/.README/4_Colour_blind_mode.png
new file mode 100644
index 0000000..2bc8afc
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/.README/4_Colour_blind_mode.png
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/.README/Setting_up.png b/java/jenkins_plugins/build_monitor/.README/Setting_up.png
new file mode 100644
index 0000000..8e6b088
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/.README/Setting_up.png
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/.gitignore b/java/jenkins_plugins/build_monitor/.gitignore
new file mode 100644
index 0000000..14a7000
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/.gitignore
@@ -0,0 +1,13 @@
+# IntelliJ
+.idea
+*.iml
+
+# Eclipse
+.classpath
+.project
+.settings/
+
+target
+work*
+
+node_modules
diff --git a/java/jenkins_plugins/build_monitor/LICENSE b/java/jenkins_plugins/build_monitor/LICENSE
new file mode 100644
index 0000000..ad64692
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/LICENSE
@@ -0,0 +1,167 @@
+Following applies to:
+- The plugin itself
+- src/main/webapp/styles/normalize.css
+
+The MIT License
+
+Copyright (c) 2013-2014, Jan Molak, SmartCode Ltd http://smartcodeltd.co.uk
+
+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 NON-INFRINGEMENT. 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.
+
+--------------------------------------------------------------------------------
+
+Following applies to:
+- src/test/resources/vendor/angular-mocks.js
+- src/main/webapp/vendor/angular-1.1.5.min.js
+- src/main/webapp/vendor/angular-1.1.5.js
+
+The MIT License
+
+Copyright (c) 2010-2012 Google, Inc. http://angularjs.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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.
+
+--------------------------------------------------------------------------------
+
+Following applies to:
+- src/main/webapp/styles/normalize.css
+
+The MIT License
+
+Copyright (c) Nicolas Gallagher and Jonathan Neal
+
+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 NON-INFRINGEMENT. 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.
+
+--------------------------------------------------------------------------------
+
+Following applies to:
+- src/test/resources/vendor/yahoo-2.9.0.min.js
+- src/test/resources/vendor/yahoo-cookie-2.9.0.min.js
+
+The BSD License
+
+Copyright (c) 2013, Yahoo! Inc. All rights reserved.
+
+Redistribution and use of this software in source and binary forms, with or with
+out modification, are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this list
+of conditions and the following disclaimer.
+Redistributions in binary form must reproduce the above copyright notice, this
+list of conditions and the following disclaimer in the documentation and/or
+other materials provided with the distribution.
+Neither the name of Yahoo! Inc. nor the names of YUI's contributors may be used
+to endorse or promote products derived from this software without specific prior
+written permission of Yahoo! Inc.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+--------------------------------------------------------------------------------
+
+Following applies to:
+- src/test/resources/vendor/sinon-1.7.3.js
+
+The BSD License
+
+Copyright (c) 2010-2013, Christian Johansen, christian@cjohansen.no
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice,
+this list of conditions and the following disclaimer.
+Redistributions in binary form must reproduce the above copyright notice,
+this list of conditions and the following disclaimer in the documentation
+and/or other materials provided with the distribution.
+Neither the name of Christian Johansen nor the names of his contributors
+may be used to endorse or promote products derived from this software
+without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+--------------------------------------------------------------------------------
+
+Following applies to:
+- src/main/webapp/styles/bootstrap-combined.2.3.2.min.css
+
+The Apache License v2.0
+
+Copyright 2012 Twitter, Inc
+
+You may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/java/jenkins_plugins/build_monitor/README b/java/jenkins_plugins/build_monitor/README
new file mode 100644
index 0000000..688abed
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/README
@@ -0,0 +1,5 @@
+To build and use the plugin:
+- Run: mvn install -Dmaven.test.skip=true
+- Upload target/vanadium-build-monitor-plugin.hpi to Jenkins using "Upload Plugin" at:
+ http://dev.v.io/jenkins/pluginManager/advanced.
+
diff --git a/java/jenkins_plugins/build_monitor/README.google b/java/jenkins_plugins/build_monitor/README.google
new file mode 100644
index 0000000..7e6b8c2
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/README.google
@@ -0,0 +1,12 @@
+URL: https://github.com/jan-molak/jenkins-build-monitor-plugin/archive/a0d11af3aa20f3b71448085f26f8f9474eafd26b.zip
+Version: a0d11af3aa20f3b71448085f26f8f9474eafd26b
+License: MIT, portions BSD, Apache 2.0
+License File: LICENSE
+
+Description:
+Build Monitor Plugin provides a highly visible view of the status of selected
+Jenkins jobs.
+
+Local Modifications:
+UI tweaks to better serve our needs.
+Change name of the plugin to "vanadium build monitor".
diff --git a/java/jenkins_plugins/build_monitor/README.md b/java/jenkins_plugins/build_monitor/README.md
new file mode 100644
index 0000000..fd281ba
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/README.md
@@ -0,0 +1,122 @@
+# Jenkins CI Build Monitor Plugin
+
+Build Monitor Plugin provides a highly visible view of the status of selected Jenkins jobs.
+
+It easily accommodates different computer screen sizes and is ideal as an Extreme Feedback Device to be displayed on a screen on your office wall.
+(Inspired by the no longer maintained [RadiatorView](https://wiki.jenkins-ci.org/display/JENKINS/Radiator+View+Plugin) plugin).
+
+[![Build Status](https://smartcode-opensource.ci.cloudbees.com/buildStatus/icon?job=jenkins-build-monitor-plugin)](https://smartcode-opensource.ci.cloudbees.com/job/jenkins-build-monitor-plugin/)
+[![Acceptance Tests Status](https://saucelabs.com/buildstatus/build-monitor)](https://saucelabs.com/u/build-monitor)
+[![Stories in Backlog](https://badge.waffle.io/jan-molak/jenkins-build-monitor-plugin.png?label=backlog&title=Backlog)](https://waffle.io/jan-molak/jenkins-build-monitor-plugin)
+
+Have a question? Perhaps it's already been answered - check the [FAQ](#faq) section below.
+
+## Features
+
+I'd like to keep the plugin as simple as possible, yet useful and effective.
+
+Current functionality of the Build Monitor plugin:
+
+* Displays the status and progress of selected jobs. The view is updated automatically every couple of seconds using AJAX, so no "Enable Auto Refresh" needed.
+* Displays the names of people who might be responsible for "breaking the build".
+* Supports the [Claim plugin](https://wiki.jenkins-ci.org/display/JENKINS/Claim+plugin), so that you can see who's fixing a broken build
+* Supports [View Job Filters](https://wiki.jenkins-ci.org/display/JENKINS/View+Job+Filters), so that you can easily create Build Monitors for "slow builds", "only failing", etc.
+* Supports [Build Failure Analyzer](https://wiki.jenkins-ci.org/display/JENKINS/Build+Failure+Analyzer), so that you know not only *who*, but also *what* broke the build; [learn more](http://bit.ly/JBMBuild102)
+* Supports [CloudBees Folders Plugin](https://wiki.jenkins-ci.org/display/JENKINS/CloudBees+Folders+Plugin), so that you can have project- and team-specific nested Build Monitors; [learn more](http://bit.ly/JBMBuild117)
+* The number of columns and size of the font used is easily customisable, making it trivial to accommodate screens of different sizes.
+* UI configuration is stored in a cookie, making it possible to display different number of columns and using different font size on each of the screens at your office.
+* Can work in a colour-blind-friendly mode; [learn more](https://github.com/jan-molak/jenkins-build-monitor-plugin/issues/30#issuecomment-35849019)
+
+All the previous releases together with their change logs are [listed here](https://bitly.com/JBMReleases).
+
+## Your feedback matters!
+
+Do you find Build Monitor useful? Give it a star! ★
+
+Found a bug? Raise [an issue](https://github.com/jan-molak/jenkins-build-monitor-plugin/issues?state=open)
+or submit a pull request ([start with this mini-dev guide](https://github.com/jan-molak/jenkins-build-monitor-plugin/wiki/Development-Guide), it might come in handy).
+
+Have feedback? Let me know on twitter: [@JanMolak](https://twitter.com/JanMolak)
+
+[![Flattr Button](http://api.flattr.com/button/button-static-50x60.png "Flattr This!")](https://flattr.com/submit/auto?user_id=JanMolak&url=https%3A%2F%2Fgithub.com%2Fjan-molak%2Fjenkins-build-monitor-plugin "Jenkins Build Monitor Plugin")
+
+## Setting up
+
+![Setting up](.README/Setting_up.png)
+
+Simple, right? :-) You can have as many Build Monitor Views as you want - the most popular approach is to have one per team or one per project.
+
+# A picture is worth a thousand words
+
+![Adding jobs](.README/1_Adding_jobs.png)
+![Three columns view](.README/2_Three_columns_view.png)
+![Supports Claim and Build Failure Analyzer plugins](.README/3_Two_columns_view_with_claim_and_build_failure_analyzer_plugins.png)
+![Colour-blind mode](.README/4_Colour_blind_mode.png)
+
+## Roadmap and work in progress
+
+To stay up-to-date with the project news - [follow @JanMolak on twitter](https://twitter.com/JanMolak).
+
+If you'd like to know what's coming next - have a look at the project's [kanban board](https://waffle.io/jan-molak/jenkins-build-monitor-plugin).
+Here's how the columns work:
+
+* Ideas - ideas up for discussion. If you'd like to see any of them making it into the Build Monitor project - vote on them or submit a pull request.
+* Backlog - features most wanted by the Build Monitor Community. I'll get them done as soon as I have a spare moment. Feel free to help out! :-)
+* In progress - stuff I'm currently working on and will make it into the next release.
+* Done - done and deployed. Grab the latest version from your Jenkins Update Centre or the [Releases](https://bitly.com/JBMReleases) page.
+
+If you'd like to get hold of the latest and greatest build of the Build Monitor Plugin
+before it's available in the Jenkins Update Centre, you can [download it](http://bit.ly/JBMLatestBuild) from the [SmartCode Open-Source](http://bit.ly/SmartCodeOSCI) Jenkins CI server,
+kindly hosted by [CloudBees](http://bit.ly/JBMFOSS).
+
+[![built on dev@cloud](http://cloudbees.prod.acquia-sites.com/sites/default/files/styles/large/public/Button-Built-on-CB-1.png?itok=3Tnkun-C)](http://bit.ly/JBMFOSS)
+
+## (A)TDD
+
+If you'd like to understand more about the logic behind the Build Monitor Plugin,
+have a look at the [tests that drove the design](/src/test/java/com/smartcodeltd/jenkinsci/plugins/).
+
+## FAQ
+
+### How do I let my teammates know that I'm fixing a broken build?
+
+By claiming it. Build Monitor supports Jenkins [Claim Plugin](https://wiki.jenkins-ci.org/display/JENKINS/Claim+plugin), so once you have it installed, enable "Broken build claiming" in the "Post-build actions" of your Jenkins job. From now on you'll be able to claim any further broken builds and Build Monitor will pick it up.
+
+You might also be interested in a [script](https://wiki.jenkins-ci.org/display/JENKINS/Allow+broken+build+claiming+on+every+jobs) that enables claiming on all your Jenkins jobs.
+
+### How do I know what broke the build?
+
+Wouldn't it be great to know _what_ made your build fail? Well of course it would. Build Monitor supports Jenkins [Buld Failure Analyzer Plugin](https://wiki.jenkins-ci.org/display/JENKINS/Build+Failure+Analyzer) so get it, [teach it](https://wiki.jenkins-ci.org/display/JENKINS/Build+Failure+Analyzer#BuildFailureAnalyzer-Knowledgebase) and Build Monitor will tell you what the Failure Analyzer found out.
+
+### I have too many jobs on one screen, what should I do?
+
+You have several options here:
+
+1. **review the granularity of your jobs**: If you have too many low-level jobs displayed on one screen, consider consolidating them using [Promoted Builds Plugin](https://wiki.jenkins-ci.org/display/JENKINS/Promoted+Builds+Plugin) or [MultiJob Plugin](https://wiki.jenkins-ci.org/display/JENKINS/Multijob+Plugin)
+1. **use job filters**: Build Monitor supports Jenkins [View Job Filters Plugin](https://wiki.jenkins-ci.org/display/JENKINS/View+Job+Filters), if you have it installed
+1. get a bigger screen ...
+
+### Red and green colours are lovely, but I'm colour blind ...
+There's a colour blind mode you can [enable in the Settings](https://github.com/jan-molak/jenkins-build-monitor-plugin/issues/30#issuecomment-35849019)
+
+## Known Limitations
+
+### Browser support - Modern web browsers only
+
+To avoid unnecessary complexity when implementing the view layer I decided to use CSS 3 flexbox.
+The standard is currently supported by [most modern web browsers](http://caniuse.com/flexbox),
+so if your browser doesn't support this feature - [consider upgrading](http://browsehappy.com/) :)
+
+## License: MIT
+
+## Open Source Software Used
+
+* [Angular.js](http://angularjs.org/)
+* [Angular-slider](http://prajwalkman.github.io/angular-slider/)
+* Customised [Angular Bootstrap](http://angular-ui.github.io/bootstrap/)
+* [HTML5 Boilerplate](http://html5boilerplate.com/) normalize.css
+* [OpenSans font](http://www.google.com/fonts/specimen/Open+Sans) by Steve Matteson
+
+## Inspired by
+
+No longer maintained [Radiator View Plugin](https://wiki.jenkins-ci.org/display/JENKINS/Radiator+View+Plugin)
diff --git a/java/jenkins_plugins/build_monitor/package.json b/java/jenkins_plugins/build_monitor/package.json
new file mode 100644
index 0000000..4923f66
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/package.json
@@ -0,0 +1,19 @@
+{
+ "scripts": {
+ "test": "node_modules/karma/bin/karma start src/test/resources/karma.conf.js --auto-watch"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/jan-molak/build-monitor.git"
+ },
+ "devDependencies": {
+ "karma": "0.12.16",
+ "karma-coverage": "0.2.4",
+ "karma-jasmine": "0.1.5",
+ "karma-junit-reporter": "0.2.2",
+ "karma-phantomjs-launcher": "0.1.4"
+ },
+ "engines": {
+ "node": ">=0.10"
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/pom.xml b/java/jenkins_plugins/build_monitor/pom.xml
new file mode 100644
index 0000000..07dc1dd
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/pom.xml
@@ -0,0 +1,332 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.jenkins-ci.plugins</groupId>
+ <artifactId>plugin</artifactId>
+ <version>1.532</version>
+ </parent>
+
+ <groupId>org.jenkins-ci.plugins</groupId>
+ <artifactId>vanadium-build-monitor-plugin</artifactId>
+ <version>0.34</version>
+ <packaging>hpi</packaging>
+
+ <name>Vanadium Build Monitor</name>
+ <description>
+ Provides a highly visible view of the status of selected Jenkins jobs.
+ It easily accommodates different computer screen sizes and is ideal as an Extreme Feedback Device to be
+ displayed on a screen on your office wall.
+ </description>
+
+ <licenses>
+ <license>
+ <name>MIT license</name>
+ <comments>All source code is under the MIT license.</comments>
+ </license>
+ </licenses>
+
+ <url>http://wiki.jenkins-ci.org/display/JENKINS/Build+Monitor+Plugin</url>
+
+ <developers>
+ <developer>
+ <id>jan-molak</id>
+ <name>Jan Molak</name>
+ <email>jan.molak+build.monitor@smartcodeltd.co.uk</email>
+ <organization>smartcode ltd</organization>
+ <organizationUrl>http://smartcodeltd.co.uk</organizationUrl>
+ <timezone>Europe/London</timezone>
+ </developer>
+ </developers>
+
+ <!-- If you have contributed to the project, please feel free to add your details below! -->
+ <contributors>
+
+ </contributors>
+
+ <scm>
+ <connection>scm:git:ssh://github.com/jan-molak/jenkins-build-monitor-plugin.git</connection>
+ <developerConnection>scm:git:ssh://git@github.com/jan-molak/jenkins-build-monitor-plugin.git</developerConnection>
+ <url>https://github.com/jan-molak/jenkins-build-monitor-plugin</url>
+ </scm>
+
+ <properties>
+ <!--
+ Build Monitor has an optional dependency on the Build Failure Analyzer (BFA) plugin:
+ https://wiki.jenkins-ci.org/display/JENKINS/Build+Failure+Analyzer
+
+ Since BFA doesn't specify its dependency on the git plugin correctly:
+ https://issues.jenkins-ci.org/browse/JENKINS-18544,
+ the automatically generated test fails with NPE...
+
+ To work around this issue Build Monitor comes with other integration tests
+ you can find in com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptancetest package
+ -->
+ <maven-hpi-plugin.disabledTestInjection>true</maven-hpi-plugin.disabledTestInjection>
+
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+
+ <npm-executable>npm</npm-executable>
+ <selenium.version>2.37.0</selenium.version>
+ </properties>
+
+ <profiles>
+ <profile>
+ <id>windows</id>
+ <activation>
+ <os>
+ <family>Windows</family>
+ </os>
+ </activation>
+ <properties>
+ <npm-executable>npm.cmd</npm-executable>
+ </properties>
+ </profile>
+ </profiles>
+
+ <!-- get every artifact through repo.jenkins-ci.org, which proxies all the artifacts that we need -->
+ <repositories>
+ <repository>
+ <id>repo.jenkins-ci.org</id>
+ <url>http://repo.jenkins-ci.org/public/</url>
+ </repository>
+ <repository>
+ <id>saucelabs-repository</id>
+ <url>http://repository-saucelabs.forge.cloudbees.com/release</url>
+ <releases>
+ <enabled>true</enabled>
+ </releases>
+ <snapshots>
+ <enabled>true</enabled>
+ </snapshots>
+ </repository>
+ </repositories>
+
+ <pluginRepositories>
+ <pluginRepository>
+ <id>repo.jenkins-ci.org</id>
+ <url>http://repo.jenkins-ci.org/public/</url>
+ </pluginRepository>
+ </pluginRepositories>
+
+ <distributionManagement>
+ <repository>
+ <id>maven.jenkins-ci.org</id>
+ <url>http://maven.jenkins-ci.org:8081/content/repositories/releases/</url>
+ </repository>
+ </distributionManagement>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <version>3.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.codehaus.jackson</groupId>
+ <artifactId>jackson-mapper-asl</artifactId>
+ <version>1.9.12</version>
+ </dependency>
+
+ <dependency>
+ <groupId>com.github.sommeri</groupId>
+ <artifactId>less4j</artifactId>
+ <version>1.8.0</version>
+ </dependency>
+
+ <!-- Jenkins CI plugins supported by the Build Monitor -->
+ <dependency>
+ <groupId>org.jenkins-ci.plugins</groupId>
+ <artifactId>cloudbees-folder</artifactId>
+ <version>4.2.3</version>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.jenkins-ci.plugins</groupId>
+ <artifactId>credentials</artifactId>
+ <version>1.14</version>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>com.sonyericsson.jenkins.plugins.bfa</groupId>
+ <artifactId>build-failure-analyzer</artifactId>
+ <version>1.9.0</version>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.jenkins-ci.plugins</groupId>
+ <artifactId>claim</artifactId>
+ <version>2.1</version>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.jenkins-ci.plugins</groupId>
+ <artifactId>view-job-filters</artifactId>
+ <version>1.26</version>
+ <optional>true</optional>
+ </dependency>
+ <!-- /Jenkins CI plugins supported by the Build Monitor -->
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.11</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-all</artifactId>
+ <version>1.3</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <version>1.9.5</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-lang</groupId>
+ <artifactId>commons-lang</artifactId>
+ <version>2.6</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.github.detro.ghostdriver</groupId>
+ <artifactId>phantomjsdriver</artifactId>
+ <version>1.1.0</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.seleniumhq.selenium</groupId>
+ <artifactId>selenium-api</artifactId>
+ <version>${selenium.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.seleniumhq.selenium</groupId>
+ <artifactId>selenium-support</artifactId>
+ <version>${selenium.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpclient</artifactId>
+ <version>4.3.4</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.saucelabs</groupId>
+ <artifactId>sauce_junit</artifactId>
+ <version>1.0.19</version>
+ <scope>test</scope>
+ </dependency>
+ <!-- similar issue to https://code.google.com/p/selenium/issues/detail?id=5245 -->
+ <dependency>
+ <groupId>org.jenkins-ci.main</groupId>
+ <artifactId>jenkins-test-harness</artifactId>
+ <version>${project.parent.version}</version>
+ <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <artifactId>xml-apis</artifactId>
+ <groupId>xml-apis</groupId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>xml-apis</groupId>
+ <artifactId>xml-apis</artifactId>
+ <version>1.4.01</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>3.1</version>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.jenkins-ci.tools</groupId>
+ <artifactId>maven-hpi-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <disabledTestInjection>true</disabledTestInjection>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>exec-maven-plugin</artifactId>
+ <version>1.2.1</version>
+ <executions>
+ <execution>
+ <goals>
+ <goal>exec</goal>
+ </goals>
+ <phase>generate-test-resources</phase>
+ </execution>
+ </executions>
+ <configuration>
+ <executable>${npm-executable}</executable>
+ <arguments>
+ <argument>install</argument>
+ </arguments>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>com.kelveden</groupId>
+ <artifactId>maven-karma-plugin</artifactId>
+ <version>1.8</version>
+ <executions>
+ <execution>
+ <goals>
+ <goal>start</goal>
+ </goals>
+ <phase>test</phase>
+ </execution>
+ </executions>
+ <configuration>
+ <karmaExecutable>${project.basedir}/node_modules/karma/bin/karma</karmaExecutable>
+ <configFile>src/test/resources/karma.conf.js</configFile>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>versions-maven-plugin</artifactId>
+ <version>2.1</version>
+ </plugin>
+ <plugin>
+ <groupId>org.jacoco</groupId>
+ <artifactId>jacoco-maven-plugin</artifactId>
+ <version>0.6.4.201312101107</version>
+ <configuration>
+ <destFile>${project.build.directory}/coverage/jacoco-unit.exec</destFile>
+ <dataFile>${project.build.directory}/coverage/jacoco-unit.exec</dataFile>
+ </configuration>
+ <executions>
+ <execution>
+ <id>jacoco-initialize</id>
+ <goals>
+ <goal>prepare-agent</goal>
+ </goals>
+ </execution>
+ <execution>
+ <id>jacoco-site</id>
+ <phase>post-integration-test</phase>
+ <goals>
+ <goal>report</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugin/assetbundler/Dispatcher.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugin/assetbundler/Dispatcher.java
new file mode 100644
index 0000000..2357e14
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugin/assetbundler/Dispatcher.java
@@ -0,0 +1,37 @@
+package com.smartcodeltd.jenkinsci.plugin.assetbundler;
+
+import com.smartcodeltd.jenkinsci.plugin.assetbundler.filters.LessCSS;
+
+import hudson.Extension;
+import hudson.Plugin;
+import hudson.util.PluginServletFilter;
+
+import java.net.URISyntaxException;
+
+/*
+ * Based on: *
+ * https://github.com/jenkinsci/uithemes-plugin/blob/master/src/main/java/org/jenkinsci/plugins
+ * /uithemes/ * https://github.com/kiy0taka/filter_sample/
+ *
+ * and the conversation at *
+ * https://groups.google.com/forum/#!searchin/jenkinsci-dev/less/jenkinsci-
+ * dev/3AU7OcUxRFk/YNpFl2NS47QJ
+ */
+@Extension
+public class Dispatcher extends Plugin {
+
+ @Override
+ public void postInitialize() throws Exception {
+ super.postInitialize();
+
+ PluginServletFilter.addFilter(
+ new LessCSS("/vanadium-build-monitor-plugin/style.css", pathToIndexLess()));
+ }
+
+ private String pathToIndexLess() throws URISyntaxException {
+ String base = getWrapper().parent.getPlugin("vanadium-build-monitor-plugin").baseResourceURL
+ .toURI().toString();
+
+ return (base + "/less/index.less").replaceAll("/+", "/");
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugin/assetbundler/filters/LessCSS.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugin/assetbundler/filters/LessCSS.java
new file mode 100644
index 0000000..7f0a602
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugin/assetbundler/filters/LessCSS.java
@@ -0,0 +1,72 @@
+package com.smartcodeltd.jenkinsci.plugin.assetbundler.filters;
+
+import com.github.sommeri.less4j.Less4jException;
+import com.github.sommeri.less4j.LessCompiler;
+import com.github.sommeri.less4j.core.DefaultLessCompiler;
+import javax.servlet.Filter;
+
+import javax.servlet.*;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+public class LessCSS implements Filter {
+ private final File less;
+ private final String pathToCSS;
+
+ private String compiledCSS;
+
+ public LessCSS(String pathToCSS, String pathToLess) throws URISyntaxException {
+ this.pathToCSS = pathToCSS;
+ this.less = fileFrom(pathToLess);
+ }
+
+ @Override
+ public void init(FilterConfig filterConfig) throws ServletException {
+ try {
+ compiledCSS = cssFrom(less);
+ } catch (Less4jException e) {
+ throw new ServletException("Couldn't compile the CSS from LESS sources", e);
+ }
+ }
+
+ @Override
+ public void doFilter(final ServletRequest request, final ServletResponse response, FilterChain chain) throws IOException, ServletException {
+ String path = ((HttpServletRequest) request).getPathInfo();
+
+ if (path.matches(pathToCSS)) {
+ sendCSS(response);
+ } else {
+ chain.doFilter(request, response);
+ }
+ }
+
+ private File fileFrom(String path) throws URISyntaxException {
+ return new File(new URI(path));
+ }
+
+ private String cssFrom(File less) throws Less4jException {
+ LessCompiler compiler = new DefaultLessCompiler();
+ LessCompiler.Configuration config = new LessCompiler.Configuration();
+
+ config.setCompressing(false);
+ config.getSourceMapConfiguration().setLinkSourceMap(false);
+
+ return compiler.compile(less, config).getCss();
+ }
+
+ private void sendCSS(ServletResponse response) throws IOException {
+ HttpServletResponse httpResponse = (HttpServletResponse) response;
+
+ httpResponse.setStatus(HttpServletResponse.SC_OK);
+ httpResponse.setContentType("text/css;charset=UTF-8");
+ httpResponse.setContentLength(compiledCSS.length());
+ httpResponse.getWriter().write(compiledCSS);
+ }
+
+ @Override
+ public void destroy() {}
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView.java
new file mode 100644
index 0000000..77ff4c4
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView.java
@@ -0,0 +1,254 @@
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2013, Jan Molak, SmartCode Ltd http://smartcodeltd.co.uk
+ *
+ * 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
+ * NON-INFRINGEMENT. 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.
+ */
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor;
+
+import static hudson.Util.filter;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.order.ByName;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.JobView;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.BuildAugmentor;
+
+import net.sf.json.JSONObject;
+import net.sf.json.JSONSerializer;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.StringEscapeUtils;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.kohsuke.stapler.DataBoundConstructor;
+import org.kohsuke.stapler.QueryParameter;
+import org.kohsuke.stapler.StaplerRequest;
+import org.kohsuke.stapler.bind.JavaScriptMethod;
+
+import hudson.Extension;
+import hudson.Util;
+import hudson.model.AbstractProject;
+import hudson.model.ListView;
+import hudson.model.ViewDescriptor;
+import hudson.model.Descriptor.FormException;
+import hudson.util.FormValidation;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Random;
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
+
+import javax.servlet.ServletException;
+
+/**
+ * @author Jan Molak
+ */
+public class BuildMonitorView extends ListView {
+
+ private final static String EXPRESSION_FILE = "/usr/local/google/home/veyron/green_expressions";
+ private final static long TITLE_UPDATE_INTERVAL_MS = 300 * 1000;
+
+ private String lastSuccessfulTitle = "";
+ private long successfulTitleLastUpdateTime = 0;
+
+ /**
+ * @param name Name of the view
+ */
+ @DataBoundConstructor
+ public BuildMonitorView(String name) {
+ super(name);
+ }
+
+ @Extension
+ public static final class Descriptor extends ViewDescriptor {
+ public Descriptor() {
+ super(BuildMonitorView.class);
+ }
+
+ @Override
+ public String getDisplayName() {
+ return "Vanadium Build Monitor";
+ }
+
+ /**
+ * Cut-n-paste from ListView$Descriptor as we cannot inherit from that class
+ */
+ public FormValidation doCheckIncludeRegex(@QueryParameter String value) {
+ String v = Util.fixEmpty(value);
+ if (v != null) {
+ try {
+ Pattern.compile(v);
+ } catch (PatternSyntaxException pse) {
+ return FormValidation.error(pse.getMessage());
+ }
+ }
+ return FormValidation.ok();
+ }
+ }
+
+ @Override
+ protected void submit(StaplerRequest req) throws ServletException, IOException, FormException {
+ super.submit(req);
+
+ String requestedOrdering = req.getParameter("order");
+
+ try {
+ order = orderIn(requestedOrdering);
+ } catch (Exception e) {
+ throw new FormException("Can't order projects by " + requestedOrdering, "order");
+ }
+ }
+
+ // defensive coding to avoid issues when Jenkins instantiates the plugin without populating its
+ // fields
+ // https://github.com/jan-molak/jenkins-build-monitor-plugin/issues/43
+ private Comparator<AbstractProject> currentOrderOrDefault() {
+ return order == null ? new ByName() : order;
+ }
+
+ public String currentOrder() {
+ return currentOrderOrDefault().getClass().getSimpleName();
+ }
+
+ private Comparator<AbstractProject> order = new ByName();
+
+ @SuppressWarnings("unchecked")
+ private Comparator<AbstractProject> orderIn(String requestedOrdering)
+ throws ClassNotFoundException, IllegalAccessException, InstantiationException {
+ String packageName = this.getClass().getPackage().getName() + ".order.";
+
+ return (Comparator<AbstractProject>) Class.forName(packageName + requestedOrdering)
+ .newInstance();
+ }
+
+ /**
+ * Because of how org.kohsuke.stapler.HttpResponseRenderer is implemented it can only work with
+ * net.sf.JSONObject in order to produce correct application/json output
+ *
+ * @return
+ * @throws Exception
+ */
+ @JavaScriptMethod
+ public JSONObject fetchJobViews() throws Exception {
+ return jsonFrom(jobViews());
+ }
+
+ public boolean isEmpty() {
+ return jobViews().isEmpty();
+ }
+
+ private String getDashboardTitle(List<JobView> jobViews) {
+ boolean allSuccessful = true;
+ String title = "Build Monitor";
+ for (JobView jv : jobViews) {
+ if (!jv.status().startsWith("successful")) {
+ allSuccessful = false;
+ break;
+ }
+ }
+ if (allSuccessful) {
+ if (System.currentTimeMillis() - successfulTitleLastUpdateTime < TITLE_UPDATE_INTERVAL_MS) {
+ title = lastSuccessfulTitle;
+ } else {
+ // Read expressions file.
+ List<String> expressions = new ArrayList<String>();
+ BufferedReader br = null;
+ try {
+ br = new BufferedReader(new FileReader(EXPRESSION_FILE));
+ String line;
+ while ((line = br.readLine()) != null) {
+ if (!line.trim().equals("")) {
+ expressions.add(line);
+ }
+ }
+ } catch (Exception e) {
+ } finally {
+ if (br != null) {
+ IOUtils.closeQuietly(br);
+ }
+ }
+
+ if (expressions.size() != 0) {
+ Random rand = new Random();
+ int randomIndex = rand.nextInt(expressions.size());
+ title = expressions.get(randomIndex);
+ }
+
+ successfulTitleLastUpdateTime = System.currentTimeMillis();
+ lastSuccessfulTitle = title;
+ }
+ }
+ return title;
+ }
+
+ private String getOncall() {
+ ProcessBuilder ps = new ProcessBuilder("ssh", "veyron@git-mirror",
+ "JIRI_ROOT=/home/veyron/vanadium", "/home/veyron/vanadium/devtools/bin/jiri-oncall");
+ ps.redirectErrorStream(true);
+ String output = "";
+ BufferedReader in = null;
+ try {
+ Process pr = ps.start();
+ in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+ String line;
+ while ((line = in.readLine()) != null) {
+ output += line;
+ }
+ pr.waitFor();
+ } catch (Exception e) {
+ } finally {
+ if (in != null) {
+ IOUtils.closeQuietly(in);
+ }
+ }
+ if (output.split(" ").length != 1) {
+ return "unknown";
+ }
+ return output == "" ? "unknown" : output;
+ }
+
+ private JSONObject jsonFrom(List<JobView> jobViews) throws IOException {
+ ObjectMapper m = new ObjectMapper();
+
+ return (JSONObject) JSONSerializer.toJSON("{jobs:" + m.writeValueAsString(jobViews)
+ + ", 'title':'" + StringEscapeUtils.escapeEcmaScript(getDashboardTitle(jobViews))
+ + "', 'oncall':'" + getOncall() + "'}");
+ }
+
+ private List<JobView> jobViews() {
+ List<AbstractProject> projects = filter(super.getItems(), AbstractProject.class);
+ List<JobView> jobs = new ArrayList<JobView>();
+
+ Collections.sort(projects, currentOrderOrDefault());
+
+ for (AbstractProject project : projects) {
+ JobView jv = JobView.of(project, withAugmentationsIfTheyArePresent());
+ jobs.add(jv);
+ }
+
+ return jobs;
+ }
+
+ private BuildAugmentor withAugmentationsIfTheyArePresent() {
+ return BuildAugmentor.fromDetectedPlugins();
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/facade/RelativeLocation.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/facade/RelativeLocation.java
new file mode 100644
index 0000000..84110f3
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/facade/RelativeLocation.java
@@ -0,0 +1,40 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.facade;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.BuildMonitorView;
+import hudson.Functions;
+import hudson.model.ItemGroup;
+import hudson.model.Job;
+import hudson.model.View;
+import org.kohsuke.stapler.Ancestor;
+import org.kohsuke.stapler.Stapler;
+import org.kohsuke.stapler.StaplerRequest;
+
+public class RelativeLocation {
+ final private Job job;
+
+ public static RelativeLocation of(Job job) {
+ return new RelativeLocation(job);
+ }
+
+ public String name() {
+ ItemGroup ig = null;
+
+ StaplerRequest request = Stapler.getCurrentRequest();
+ for( Ancestor a : request.getAncestors() ) {
+ if(a.getObject() instanceof BuildMonitorView) {
+ ig = ((View) a.getObject()).getOwnerItemGroup();
+ }
+ }
+
+ return Functions.getRelativeDisplayNameFrom(job, ig);
+ }
+
+ public String url() {
+ return Functions.getRelativeLinkTo(job);
+ }
+
+
+ private RelativeLocation(Job job) {
+ this.job = job;
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/order/ByDisplayName.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/order/ByDisplayName.java
new file mode 100644
index 0000000..d284048
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/order/ByDisplayName.java
@@ -0,0 +1,12 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.order;
+
+import hudson.model.AbstractProject;
+
+import java.util.Comparator;
+
+public class ByDisplayName implements Comparator<AbstractProject> {
+ @Override
+ public int compare(AbstractProject a, AbstractProject b) {
+ return a.getDisplayName().compareToIgnoreCase(b.getDisplayName());
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/order/ByName.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/order/ByName.java
new file mode 100644
index 0000000..4721fe4
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/order/ByName.java
@@ -0,0 +1,12 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.order;
+
+import hudson.model.AbstractProject;
+
+import java.util.Comparator;
+
+public class ByName implements Comparator<AbstractProject> {
+ @Override
+ public int compare(AbstractProject a, AbstractProject b) {
+ return a.getName().compareToIgnoreCase(b.getName());
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/BuildView.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/BuildView.java
new file mode 100644
index 0000000..25011c7
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/BuildView.java
@@ -0,0 +1,184 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.facade.RelativeLocation;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.BuildAugmentor;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.bfa.Analysis;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.claim.Claim;
+
+import hudson.model.Result;
+import hudson.model.AbstractBuild;
+import hudson.model.Run;
+import hudson.model.User;
+
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+public class BuildView implements BuildViewModel {
+
+ private final Run<?, ?> build;
+ private final RelativeLocation parentJobLocation;
+ private final Date systemTime;
+ private final BuildAugmentor augmentor;
+
+ public static BuildView of(Run<?, ?> build) {
+ return new BuildView(build, new BuildAugmentor(), RelativeLocation.of(build.getParent()),
+ new Date());
+ }
+
+ public static BuildView of(Run<?, ?> build, BuildAugmentor augmentor, Date systemTime) {
+ return new BuildView(build, augmentor, RelativeLocation.of(build.getParent()), systemTime);
+ }
+
+ public static BuildView of(Run<?, ?> build, BuildAugmentor augmentor,
+ RelativeLocation parentJobLocation, Date systemTime) {
+ return new BuildView(build, augmentor, parentJobLocation, systemTime);
+ }
+
+
+ @Override
+ public String name() {
+ return build.getDisplayName();
+ }
+
+ @Override
+ public String url() {
+ return parentJobLocation.url() + "/" + build.getNumber() + "/";
+ }
+
+ @Override
+ public Result result() {
+ return build.getResult();
+ }
+
+ @Override
+ public boolean isRunning() {
+ return isRunning(this.build);
+ }
+
+ private boolean isRunning(Run<?, ?> build) {
+ return (build.hasntStartedYet() || build.isBuilding() || build.isLogUpdated());
+ }
+
+ @Override
+ public Duration elapsedTime() {
+ return new Duration(now() - whenTheBuildStarted());
+ }
+
+ @Override
+ public Duration duration() {
+ return new Duration(build.getDuration());
+ }
+
+ @Override
+ public Duration estimatedDuration() {
+ return new Duration(build.getEstimatedDuration());
+ }
+
+ @Override
+ public int progress() {
+ if (!isRunning()) {
+ return 0;
+ }
+
+ if (isTakingLongerThanUsual()) {
+ return 100;
+ }
+
+ long elapsedTime = now() - whenTheBuildStarted(),
+ estimatedDuration = build.getEstimatedDuration();
+
+ if (estimatedDuration > 0) {
+ return (int) ((float) elapsedTime / (float) estimatedDuration * 100);
+ }
+
+ return 100;
+ }
+
+ private boolean isTakingLongerThanUsual() {
+ return elapsedTime().greaterThan(estimatedDuration());
+ }
+
+ @Override
+ public boolean hasPreviousBuild() {
+ return null != build.getPreviousBuild();
+ }
+
+ @Override
+ public BuildViewModel previousBuild() {
+ return new BuildView(build.getPreviousBuild(), augmentor, this.parentJobLocation, systemTime);
+ }
+
+ @Override
+ public Set<String> culprits() {
+ Set<String> culprits = new HashSet<String>();
+
+ if (build instanceof AbstractBuild<?, ?>) {
+ AbstractBuild<?, ?> jenkinsBuild = (AbstractBuild<?, ?>) build;
+
+ if (!(isRunning(jenkinsBuild))) {
+ for (User culprit : jenkinsBuild.getCulprits()) {
+ culprits.add(culprit.getFullName());
+ }
+ }
+ }
+ return culprits;
+ }
+
+ @Override
+ public boolean isClaimed() {
+ return claim().wasMade();
+ }
+
+ @Override
+ public String claimant() {
+ return claim().author();
+ }
+
+ @Override
+ public String reasonForClaim() {
+ return claim().reason();
+ }
+
+ private Claim claim() {
+ return augmentor.detailsOf(build, Claim.class);
+ }
+
+ @Override
+ public boolean hasKnownFailures() {
+ return analysis().foundKnownFailures();
+ }
+
+ @Override
+ public List<String> knownFailures() {
+ return analysis().failures();
+ }
+
+ private Analysis analysis() {
+ return augmentor.detailsOf(build, Analysis.class);
+ }
+
+ @Override
+ public String toString() {
+ return name();
+ }
+
+
+ private long now() {
+ return systemTime.getTime();
+ }
+
+ private long whenTheBuildStarted() {
+ return build.getTimestamp().getTimeInMillis();
+ }
+
+
+ private BuildView(Run<?, ?> build, BuildAugmentor augmentor, RelativeLocation parentJobLocation,
+ Date systemTime) {
+ this.build = build;
+ this.augmentor = augmentor;
+ this.parentJobLocation = parentJobLocation;
+ this.systemTime = systemTime;
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/BuildViewModel.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/BuildViewModel.java
new file mode 100644
index 0000000..577e4b9
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/BuildViewModel.java
@@ -0,0 +1,31 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel;
+
+import hudson.model.Result;
+
+import java.util.List;
+import java.util.Set;
+
+public interface BuildViewModel {
+ public String name();
+ public String url();
+ public Result result();
+
+ public boolean isRunning();
+ public Duration elapsedTime();
+ public Duration duration();
+ public Duration estimatedDuration();
+ public int progress();
+
+ public boolean hasPreviousBuild();
+ public BuildViewModel previousBuild();
+
+ public Set<String> culprits();
+
+ boolean isClaimed();
+ String claimant();
+ String reasonForClaim();
+
+ boolean hasKnownFailures();
+
+ List<String> knownFailures();
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/Duration.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/Duration.java
new file mode 100644
index 0000000..22d1d40
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/Duration.java
@@ -0,0 +1,46 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel;
+
+class Duration {//todo: extract the Duration class, or move it to a BuildView class
+
+ private final long duration;
+
+ private final static long MILLISECOND = 1;
+ private final static long SECONDS = 1000 * MILLISECOND;
+ private final static long MINUTES = 60 * SECONDS;
+ private final static long HOURS = 60 * MINUTES;
+
+ public Duration(long milliseconds) {
+ this.duration = milliseconds;
+ }
+
+ public long hours() {
+ return duration / HOURS;
+ }
+
+ public long minutes() {
+ return (duration - (hours() * HOURS)) / MINUTES;
+ }
+
+ public long seconds() {
+ return (duration - (hours() * HOURS) - (minutes() * MINUTES)) / SECONDS;
+ }
+
+ public boolean greaterThan(Duration otherDuration) {
+ return duration > otherDuration.toLong();
+ }
+
+ public String toString() {
+ String formatted;
+
+ formatted = hours() > 0 ? hours() + "h " : "";
+ formatted += minutes() > 0 ? minutes() + "m " : "";
+ formatted += seconds() + "s";
+
+ return formatted;
+ }
+
+
+ private long toLong() {
+ return duration;
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/JobView.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/JobView.java
new file mode 100644
index 0000000..77b0ba1
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/JobView.java
@@ -0,0 +1,214 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel;
+
+import static hudson.model.Result.ABORTED;
+import static hudson.model.Result.FAILURE;
+import static hudson.model.Result.SUCCESS;
+import static hudson.model.Result.UNSTABLE;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.facade.RelativeLocation;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.BuildAugmentor;
+
+import org.codehaus.jackson.annotate.JsonProperty;
+
+import hudson.model.Result;
+import hudson.model.Job;
+import hudson.model.Run;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @author Jan Molak
+ */
+public class JobView {
+ private final Date systemTime;
+ private final Job<?, ?> job;
+ private final BuildAugmentor augmentor;
+ private final RelativeLocation relative;
+
+ private final static Map<Result, String> statuses = new HashMap<Result, String>() {
+ {
+ put(SUCCESS, "successful");
+ put(UNSTABLE, "unstable");
+ put(FAILURE, "failing");
+ put(ABORTED, "failing"); // if someone has aborted it then something is clearly not right,
+ // right? :)
+ }
+ };
+
+ public static JobView of(Job<?, ?> job) {
+ return new JobView(job, new BuildAugmentor(), RelativeLocation.of(job), new Date());
+ }
+
+ public static JobView of(Job<?, ?> job, BuildAugmentor augmentor) {
+ return new JobView(job, augmentor, RelativeLocation.of(job), new Date());
+ }
+
+ public static JobView of(Job<?, ?> job, RelativeLocation location) {
+ return new JobView(job, new BuildAugmentor(), location, new Date());
+ }
+
+ public static JobView of(Job<?, ?> job, Date systemTime) {
+ return new JobView(job, new BuildAugmentor(), RelativeLocation.of(job), systemTime);
+ }
+
+ @JsonProperty
+ public String name() {
+ return relative.name();
+ }
+
+ @JsonProperty
+ public String shortName() {
+ return relative.name().replace("vanadium-", "");
+ }
+
+ @JsonProperty
+ public String url() {
+ return relative.url();
+ }
+
+ private String statusOf(Result result) {
+ return statuses.containsKey(result) ? statuses.get(result) : "unknown";
+ }
+
+ @JsonProperty
+ public String status() {
+ String status = statusOf(lastCompletedBuild().result());
+ if (name().toLowerCase().indexOf("presubmit-test") > 0 &&
+ (lastCompletedBuild().result() == Result.ABORTED ||
+ lastCompletedBuild().result() == Result.UNSTABLE)) {
+ status = "successful";
+ }
+
+ if (lastBuild().isRunning()) {
+ status += " running";
+ }
+
+ if (lastCompletedBuild().isClaimed()) {
+ status += " claimed";
+ }
+
+ return status;
+ }
+
+ @JsonProperty
+ public String lastBuildName() {
+ return lastBuild().name();
+ }
+
+ @JsonProperty
+ public String lastBuildUrl() {
+ return lastBuild().url();
+ }
+
+ @JsonProperty
+ public String lastBuildDuration() {
+ if (lastBuild().isRunning()) {
+ return formatted(lastBuild().elapsedTime());
+ }
+
+ return formatted(lastBuild().duration());
+ }
+
+ @JsonProperty
+ public String estimatedDuration() {
+ return formatted(lastBuild().estimatedDuration());
+ }
+
+ private String formatted(Duration duration) {
+ return null != duration ? duration.toString() : "";
+ }
+
+ @JsonProperty
+ public int progress() {
+ return lastBuild().progress();
+ }
+
+ @JsonProperty
+ public boolean shouldIndicateCulprits() {
+ return !isClaimed() && culprits().size() > 0;
+ }
+
+ @JsonProperty
+ public Set<String> culprits() {
+ Set<String> culprits = new HashSet<String>();
+
+ BuildViewModel build = lastBuild();
+ // todo: consider introducing a BuildResultJudge to keep this logic in one place
+ while (!SUCCESS.equals(build.result())) {
+ culprits.addAll(build.culprits());
+
+ if (!build.hasPreviousBuild()) {
+ break;
+ }
+
+ build = build.previousBuild();
+ };
+
+ return culprits;
+ }
+
+ @JsonProperty
+ public boolean isClaimed() {
+ return lastCompletedBuild().isClaimed();
+ }
+
+ @JsonProperty
+ public String claimAuthor() {
+ return lastCompletedBuild().claimant();
+ }
+
+ @JsonProperty
+ public String claimReason() {
+ return lastCompletedBuild().reasonForClaim();
+ }
+
+ @JsonProperty
+ public boolean hasKnownFailures() {
+ return lastCompletedBuild().hasKnownFailures();
+ }
+
+ @JsonProperty
+ public List<String> knownFailures() {
+ return lastCompletedBuild().knownFailures();
+ }
+
+ @Override
+ public String toString() {
+ return name();
+ }
+
+
+ private JobView(Job<?, ?> job, BuildAugmentor augmentor, RelativeLocation relative,
+ Date systemTime) {
+ this.job = job;
+ this.augmentor = augmentor;
+ this.systemTime = systemTime;
+ this.relative = relative;
+ }
+
+ private BuildViewModel lastBuild() {
+ return buildViewOf(job.getLastBuild());
+ }
+
+ private BuildViewModel lastCompletedBuild() {
+ BuildViewModel previousBuild = lastBuild();
+ while (previousBuild.isRunning() && previousBuild.hasPreviousBuild()) {
+ previousBuild = previousBuild.previousBuild();
+ }
+
+ return previousBuild;
+ }
+
+ private BuildViewModel buildViewOf(Run<?, ?> build) {
+ if (null == build) {
+ return new NullBuildView();
+ }
+
+ return BuildView.of(job.getLastBuild(), augmentor, relative, systemTime);
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/NullBuildView.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/NullBuildView.java
new file mode 100644
index 0000000..6484e2e
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/NullBuildView.java
@@ -0,0 +1,90 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel;
+
+import hudson.model.Result;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+public class NullBuildView implements BuildViewModel {
+
+ @Override
+ public String name() {
+ return "";
+ }
+
+ @Override
+ public String url() {
+ return "";
+ }
+
+ @Override
+ public Result result() {
+ return Result.NOT_BUILT;
+ }
+
+ @Override
+ public boolean isRunning() {
+ return false;
+ }
+
+ @Override
+ public Duration elapsedTime() {
+ return null;
+ }
+
+ @Override
+ public Duration duration() {
+ return null;
+ }
+
+ @Override
+ public Duration estimatedDuration() {
+ return null;
+ }
+
+ @Override
+ public int progress() {
+ return 0;
+ }
+
+ @Override
+ public boolean hasPreviousBuild() {
+ return false;
+ }
+
+ @Override
+ public BuildViewModel previousBuild() {
+ return null;
+ }
+
+ @Override
+ public Set<String> culprits() {
+ return new HashSet<String>();
+ }
+
+ @Override
+ public boolean isClaimed() {
+ return false;
+ }
+
+ @Override
+ public String claimant() {
+ return null;
+ }
+
+ @Override
+ public String reasonForClaim() {
+ return null;
+ }
+
+ @Override
+ public boolean hasKnownFailures() {
+ return false;
+ }
+
+ @Override
+ public List<String> knownFailures() {
+ return null;
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/Augmentation.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/Augmentation.java
new file mode 100644
index 0000000..cb42aa9
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/Augmentation.java
@@ -0,0 +1,4 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins;
+
+public interface Augmentation {
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/BuildAugmentor.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/BuildAugmentor.java
new file mode 100644
index 0000000..033dfe5
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/BuildAugmentor.java
@@ -0,0 +1,83 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.bfa.Analysed;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.bfa.Analysis;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.bfa.NotAnalysed;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.claim.Claim;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.claim.Claimed;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.claim.NotClaimed;
+import com.sonyericsson.jenkins.plugins.bfa.model.FailureCauseBuildAction;
+import hudson.model.Hudson;
+import hudson.model.Run;
+import hudson.plugins.claim.ClaimBuildAction;
+
+import java.util.HashSet;
+import java.util.Set;
+
+// The pattern around Augmentation is a dubious and quite Poltergeisty. It can probably be
+// improved with something akin to a Visitor pattern
+public class BuildAugmentor {
+
+ public static String CLAIM_PLUGIN = "claim";
+ public static String ANALYSER_PLUGIN = "build-failure-analyzer";
+
+ public static BuildAugmentor fromDetectedPlugins() {
+ BuildAugmentor augmentor = new BuildAugmentor();
+
+ if (isInstalled(CLAIM_PLUGIN)) {
+ augmentor.support(Claim.class);
+ }
+ if (isInstalled(ANALYSER_PLUGIN)) {
+ augmentor.support(Analysis.class);
+ }
+ return augmentor;
+ }
+
+ private static boolean isInstalled(String plugin) {
+ return Hudson.getInstance().getPlugin(plugin) != null;
+ }
+
+ private Set<Class<? extends Augmentation>> recognisedAugmentations = new HashSet<Class<? extends Augmentation>>();
+
+ @SuppressWarnings("unchecked")
+ public <T extends Augmentation> T detailsOf(Run<?, ?> build, Class<T> augmentation) {
+ if (augmentation.isAssignableFrom(Claim.class)) {
+ return (T) detailsOfClaim(build);
+ } else {
+ assert augmentation.isAssignableFrom(Analysis.class) : "Unknown augmentation should never happen outside of development";
+ return (T) detailsOfAnalysis(build);
+ }
+ }
+
+ private <T extends Augmentation> boolean isSupported(Class<T> augmentation) {
+ return recognisedAugmentations.contains(augmentation);
+ }
+
+ private Claim detailsOfClaim(Run<?, ?> build) {
+ if (isSupported(Claim.class)) {
+ ClaimBuildAction action = build.getAction(ClaimBuildAction.class);
+
+ if (action != null) {
+ return new Claimed(action);
+ }
+ }
+ return new NotClaimed();
+ }
+
+ private Analysis detailsOfAnalysis(Run<?, ?> build) {
+ if (isSupported(Analysis.class)) {
+ FailureCauseBuildAction action = build.getAction(FailureCauseBuildAction.class);
+
+ if (action != null) {
+ // Should we also check if failures were found? is it "Analysed" or "HasKnownFailures"
+ return new Analysed(action);
+ }
+ }
+ return new NotAnalysed();
+ }
+
+ public void support(Class<? extends Augmentation> typeOfAugmentation) {
+ recognisedAugmentations.add(typeOfAugmentation);
+ }
+
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/bfa/Analysed.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/bfa/Analysed.java
new file mode 100644
index 0000000..21ad00a
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/bfa/Analysed.java
@@ -0,0 +1,34 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.bfa;
+
+import com.sonyericsson.jenkins.plugins.bfa.model.FailureCauseBuildAction;
+import com.sonyericsson.jenkins.plugins.bfa.model.FoundFailureCause;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Analysed implements Analysis {
+ private final FailureCauseBuildAction action;
+
+ public Analysed( FailureCauseBuildAction action ) {
+ this.action = action;
+ }
+
+ @Override
+ public boolean foundKnownFailures() {
+ return ! action.getFoundFailureCauses().isEmpty();
+ }
+
+ @Override
+ public List<String> failures() {
+ List<String> failures = new ArrayList<String>(action.getFoundFailureCauses().size());
+ for (FoundFailureCause failure : action.getFoundFailureCauses()) {
+ failures.add(failure.getName());
+ }
+ return failures;
+ }
+
+ public String toString() {
+ return String.format("Failed with %s",failures());
+ }
+
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/bfa/Analysis.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/bfa/Analysis.java
new file mode 100644
index 0000000..bb4c0d7
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/bfa/Analysis.java
@@ -0,0 +1,10 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.bfa;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.Augmentation;
+
+import java.util.List;
+
+public interface Analysis extends Augmentation {
+ boolean foundKnownFailures();
+ List<String> failures();
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/bfa/NotAnalysed.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/bfa/NotAnalysed.java
new file mode 100644
index 0000000..2a26b16
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/bfa/NotAnalysed.java
@@ -0,0 +1,20 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.bfa;
+
+import java.util.Collections;
+import java.util.List;
+
+public class NotAnalysed implements Analysis {
+ @Override
+ public boolean foundKnownFailures() {
+ return false;
+ }
+
+ @Override
+ public List<String> failures() {
+ return Collections.emptyList();
+ }
+
+ public String toString() {
+ return "No known failures";
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/claim/Claim.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/claim/Claim.java
new file mode 100644
index 0000000..06d6982
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/claim/Claim.java
@@ -0,0 +1,9 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.claim;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.Augmentation;
+
+public interface Claim extends Augmentation {
+ public boolean wasMade();
+ public String author();
+ public String reason();
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/claim/Claimed.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/claim/Claimed.java
new file mode 100644
index 0000000..dd73fe1
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/claim/Claimed.java
@@ -0,0 +1,30 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.claim;
+
+import hudson.plugins.claim.ClaimBuildAction;
+
+public class Claimed implements Claim {
+ private final ClaimBuildAction action;
+
+ public Claimed(ClaimBuildAction action) {
+ this.action = action;
+ }
+
+ @Override
+ public boolean wasMade() {
+ return action.isClaimed();
+ }
+
+ @Override
+ public String author() {
+ return action.getClaimedByName();
+ }
+
+ @Override
+ public String reason() {
+ return action.getReason();
+ }
+
+ public String toString() {
+ return String.format("Claimed by \"%s\": \"%s\"", author(), reason());
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/claim/NotClaimed.java b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/claim/NotClaimed.java
new file mode 100644
index 0000000..b6b68ae
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/claim/NotClaimed.java
@@ -0,0 +1,22 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.claim;
+
+public class NotClaimed implements Claim {
+ @Override
+ public boolean wasMade() {
+ return false;
+ }
+
+ @Override
+ public String author() {
+ return null;
+ }
+
+ @Override
+ public String reason() {
+ return null;
+ }
+
+ public String toString() {
+ return "Not claimed";
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/configure-entries.jelly b/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/configure-entries.jelly
new file mode 100644
index 0000000..3dad448
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/configure-entries.jelly
@@ -0,0 +1,77 @@
+<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define" xmlns:l="/lib/layout" xmlns:t="/lib/hudson" xmlns:f="/lib/form" xmlns:i="jelly:fmt">
+
+ <!-- BEGIN cut'n'paste from https://github.com/jenkinsci/jenkins/blob/jenkins-1.532/core/src/main/resources/hudson/model/ListView/configure-entries.jelly -->
+
+ <f:section title="${%Job Filters}">
+
+ <f:entry title="${%Status Filter}" help="/help/view-config/statusFilter.html">
+ <select name="statusFilter" class="setting-input">
+ <f:option value="" selected="${it.statusFilter==null}">${%All selected jobs}</f:option>
+ <f:option value="1" selected="${it.statusFilter==true}">${%Enabled jobs only}</f:option>
+ <f:option value="2" selected="${it.statusFilter==false}">${%Disabled jobs only}</f:option>
+ </select>
+ </f:entry>
+
+ <f:entry title="${%Recurse in subfolders}" field="recurse">
+ <f:checkbox id="recurse"/>
+ </f:entry>
+
+ <f:entry title="${%Jobs}">
+ <div class="listview-jobs">
+ <j:forEach var="job" items="${h.getAllTopLevelItems(it.ownerItemGroup)}">
+ <j:set var="spanClass" value=""/>
+ <j:set var="spanStyle" value=""/>
+ <j:if test="${job.parent!=it.ownerItemGroup}">
+ <j:set var="spanClass" value="nested"/>
+ <j:set var="spanStyle" value="${it.recurse?'':'display:none'}"/>
+ </j:if>
+ <span class="${spanClass}" style="${spanStyle}">
+ <f:checkbox name="${job.getRelativeNameFromGroup(it.ownerItemGroup)}" checked="${it.jobNamesContains(job)}" title="${h.getRelativeDisplayNameFrom(job,it.ownerItemGroup)}" tooltip="${job.fullName}" json="true"/>
+ <br/>
+ </span>
+ </j:forEach>
+ </div>
+ </f:entry>
+
+ <f:optionalBlock name="useincluderegex" title="${%Use a regular expression to include jobs into the view}"
+ checked="${it.includeRegex != null}" help="/help/view-config/includeregex.html">
+ <f:entry title="${%Regular expression}">
+ <f:textbox name="includeRegex" field="includeRegex" />
+ </f:entry>
+ </f:optionalBlock>
+
+ <j:if test="${it.hasJobFilterExtensions()}">
+ <f:block>
+ <f:repeatableHeteroProperty field="jobFilters" hasHeader="true" addCaption="${%Add Job Filter}" />
+ </f:block>
+ </j:if>
+
+ </f:section>
+
+ <!-- END cut'n'paste from https://github.com/jenkinsci/jenkins/blob/jenkins-1.532/core/src/main/resources/hudson/model/ListView/configure-entries.jelly -->
+
+ <f:section title="${%Build Monitor Settings}">
+
+ <f:entry title="${%Ordered by}">
+ <select name="order" class="setting-input">
+ <f:option value="ByName" selected='${it.currentOrder()=="ByName"}'>${%Name}</f:option>
+ <f:option value="ByDisplayName" selected="${it.currentOrder()=='ByDisplayName'}">${%Display name}</f:option>
+ </select>
+ </f:entry>
+
+ </f:section>
+
+ <script>
+ (function() {
+ Behaviour.specify("#recurse", 'ListView', 0, function(e) {
+ var nestedElements = $$('SPAN.nested')
+ e.onclick = function() {
+ nestedElements.each(function(el) {
+ e.checked ? el.show() : el.hide();
+ });
+ }
+ });
+ }());
+ </script>
+
+</j:jelly>
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/index.jelly b/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/index.jelly
new file mode 100644
index 0000000..1a0c02e
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/index.jelly
@@ -0,0 +1,108 @@
+<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:l="/lib/layout">
+
+ <l:layout norefresh="true">
+
+ <j:set var="resourcesURL" value="${resURL}/plugin/vanadium-build-monitor-plugin" />
+ <j:set var="jobsURL" value="${rootURL}/job" />
+ <j:set var="angularVersion" value="1.1.5" />
+
+ <l:header>
+ <link rel="stylesheet" href="${resourcesURL}/styles/normalize.css"/>
+ <link rel="stylesheet" href="${resourcesURL}/styles/bootstrap-combined.2.3.2.min.css"/>
+ <link rel="stylesheet" href="${resourcesURL}/styles/angular-slider.css"/>
+
+ <link rel="stylesheet" href="${resourcesURL}/themes/industrial.css"/>
+ <link rel="stylesheet" href="${rootURL}/vanadium-build-monitor-plugin/style.css"/>
+
+ <script src="${resURL}/scripts/yui/cookie/cookie-min.js"></script>
+
+ <script src="${resourcesURL}/vendor/modernizr.custom.27682.js"></script>
+ <script src="${resourcesURL}/vendor/angular-${angularVersion}.min.js"></script>
+ <script src="${resourcesURL}/vendor/ui-bootstrap-custom-tpls-0.4.0.js"></script>
+ <script src="${resourcesURL}/vendor/angular-slider-0.1.6.js"></script>
+ <script src="${resourcesURL}/vendor/angular-slugify-1.0.0.js"></script>
+ </l:header>
+
+ <l:main-panel>
+ <div class="build-monitor dashboard"
+ data-ng-app="buildMonitor"
+ data-ng-controller="JobViews">
+ <header>
+ <a class="oncall" href="${rootURL}/" title="Jenkins">{{oncall}}</a>
+ <h1><a href="configure" title="Configure the '${it.displayName}' view">{{title}}</a></h1>
+ </header>
+
+ <st:include page="main-settings.jelly"/>
+
+ <j:choose>
+ <j:when test="${it.isEmpty()}">
+ <st:include page="main-empty.jelly"/>
+ </j:when>
+ <j:otherwise>
+ <st:include page="main-jobViews.jelly"/>
+ </j:otherwise>
+ </j:choose>
+ </div>
+
+ <script>
+ /*
+ * todo: (13.08.2013) Replace the below workaround with a custom Jelly tag (ExposeBindTag)
+ * extending either org.kohsuke.stapler.jelly.BindTag or AbstractStaplerTag,
+ * that would supersede currently defective BindTag implementation:
+ * - https://groups.google.com/forum/#!topic/jenkinsci-dev/S9bhX4ts0g4
+ * - https://issues.jenkins-ci.org/browse/JENKINS-18641
+ *
+ * Defect in BindTag manifests itself by causing a JavaScript error and preventing scripts after
+ * the <st:bind> invocation from executing, which results in an "empty Build Monitor".
+ * The issue occurs on Jenkins 1.521-1.526, only if the jQuery plugin is used.
+ *
+ * Motivation behind a custom Jelly tag:
+ * Original implementation of the BindTag doesn't provide an easy way of handling AJAX errors,
+ * which may happen if a network connection is lost or when Jenkins is restarted (which then makes
+ * Stapler's binding hash obsolete and Jenkins return 404 for any subsequent requests).
+ *
+ * Custom Jelly tag should generate a JSON object exposing the binding, leaving the implementation
+ * of the proxy to the Developer. It makes more sense for a developer to require a binding adapter
+ * implementation specific to their JavaScript framework of choice, rather than for Stapler to try
+ * to predict what JavaScript libraries will ever be used with it in the future...
+ */
+ window.originalMakeStaplerProxy = window.makeStaplerProxy;
+ window.makeStaplerProxy = function(url, crumb, methods) {
+ return { url: url, crumb: crumb, methods: methods }
+ };
+ window.bindings={};
+ </script>
+ <st:bind var="window.bindings['buildMonitor']" value="${it}" />
+ <script>
+ window.makeStaplerProxy = window.originalMakeStaplerProxy;
+ delete window.originalMakeStaplerProxy;
+ </script>
+
+ <script src="${resourcesURL}/scripts/app.js"></script>
+ <script src="${resourcesURL}/scripts/cron.js"></script>
+ <script src="${resourcesURL}/scripts/services.js"></script>
+ <script src="${resourcesURL}/scripts/jenkins.js"></script>
+ <script src="${resourcesURL}/scripts/controllers.js"></script>
+ <script src="${resourcesURL}/scripts/templates.js"></script>
+ <script src="${resourcesURL}/scripts/settings.js"></script>
+ <script>
+ 'use strict';
+
+ angular.
+
+ module('buildMonitor').
+
+ config(function(proxyProvider, cookieJarProvider, hashCodeProvider) {
+ var hashCodeOf = hashCodeProvider.hashCodeOf;
+
+ proxyProvider.configureProxiesUsing(window.bindings);
+
+ cookieJarProvider.describe({
+ label: 'buildMonitor.' + hashCodeOf('${it.displayName}'),
+ shelfLife: 365
+ });
+ });
+ </script>
+ </l:main-panel>
+ </l:layout>
+</j:jelly>
diff --git a/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/main-empty.jelly b/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/main-empty.jelly
new file mode 100644
index 0000000..f002e2b
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/main-empty.jelly
@@ -0,0 +1,3 @@
+<div id="job-views" class="empty">
+ <em>It seems a bit empty here... Maybe you'd like to <a href="configure">add some jobs</a> to this monitor?</em>
+</div>
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/main-jobViews.jelly b/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/main-jobViews.jelly
new file mode 100644
index 0000000..85b0ed8
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/main-jobViews.jelly
@@ -0,0 +1,40 @@
+<ul id="job-views"
+ data-ng-class="{ 'colour-blind-mode': settings.colourBlind == 1 }"
+ style="font-size: {{ settings.fontSize }}em"
+ class="columns-{{ settings.numberOfColumns }}">
+
+ <li ng-repeat="job in jobs" class="{{job.status}}" id="{{ job.name | slugify }}">
+ <div class="progress" style="width: {{job.progress}}%">
+ <span>{{job.progress}}%</span>
+ </div>
+
+ <div class="meta">
+ <div class="latest-results">
+ <h2>
+ <a ng-if="settings.stripVanadium == 0" title="{{job.name}}" href="{{job.url}}">{{job.name}}</a>
+ <a ng-if="settings.stripVanadium == 1" title="{{job.name}}" href="{{job.url}}">{{job.shortName}}</a>
+ </h2>
+ <ul class="description">
+ <li data-ng-show="job.claimed">Claimed by <strong>{{ job.claimAuthor }}</strong>: {{ job.claimReason }}</li>
+ </ul>
+ <div ng-if="settings.showCulprits == 1">
+ <ul ng-if="job.shouldIndicateCulprits" class="culprits">
+ <li data-ng-repeat="name in job.culprits">{{name}}</li>
+ </ul>
+ </div>
+ <ul ng-if="job.hasKnownFailures" class="failures">
+ <li data-ng-repeat="name in job.knownFailures">{{name}}</li>
+ </ul>
+ </div>
+
+ <a data-ng-show="!!job.lastBuildName" class="build-name"
+ title="Details of {{job.name}}, build {{job.lastBuildName}}"
+ href="{{job.lastBuildUrl}}">{{job.lastBuildName}}</a>
+
+ <div data-ng-show="!!job.estimatedDuration" class="build-time">
+ <span class="elapsed" data-ng-show="job.progress > 0">{{job.lastBuildDuration}}</span>
+ <span class="estimated">{{job.estimatedDuration}}</span>
+ </div>
+ </div>
+ </li>
+</ul>
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/main-settings.jelly b/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/main-settings.jelly
new file mode 100644
index 0000000..21ca22a
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/main-settings.jelly
@@ -0,0 +1,45 @@
+<nav data-ng-class="{ showSettings:toggleSettings }" data-ng-controller="controlPanel">
+ <input id="settings-toggle" type="checkbox" class="settings" data-ng-model="toggleSettings" />
+ <label for="settings-toggle" title="Configure Build Monitor Settings">Settings</label>
+
+ <!-- workaround for angular-slider not working when initialised within a hidden element -->
+ <ul>
+ <li>
+ <span class="slider-label">Font size</span>
+ <slider floor="0.1" ceiling="2" step="0.02" precision="1" data-ng-model="settings.fontSize"></slider>
+ </li>
+ <li>
+ <span class="slider-label">Columns</span>
+ <slider floor="1" ceiling="8" step="1" precision="0" data-ng-model="settings.numberOfColumns"></slider>
+ </li>
+ <li>
+ <input data-ng-model="settings.colourBlind"
+ data-ng-false-value="0"
+ data-ng-true-value="1"
+ id="settings-colour-blind" type="checkbox" />
+ <label for="settings-colour-blind" title="Colour blind-friendly colour scheme">Colour blind mode?</label>
+ </li>
+ <li>
+ <input data-ng-model="settings.showCulprits"
+ data-ng-false-value="0"
+ data-ng-true-value="1"
+ id="settings-show-culprits" type="checkbox" />
+ <label for="settings-show-culprits" title="Whether to show culprits">Show culprits?</label>
+ </li>
+ <li>
+ <input data-ng-model="settings.stripVanadium"
+ data-ng-false-value="0"
+ data-ng-true-value="1"
+ id="settings-strip-vanadium" type="checkbox" />
+ <label for="settings-strip-vanadium" title="Whether to strip Vanadium prefix">Strip "vanadium-" prefix?</label>
+ </li>
+ <li>
+ <a class="btn"
+ href="configure"
+ title="Configure the '${it.displayName}' view">Add/Remove Jobs</a>
+ </li>
+ <li>
+ <button class="btn btn-primary" data-ng-click="toggleSettings=false">Done</button>
+ </li>
+ </ul>
+</nav>
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/newViewDetail.jelly b/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/newViewDetail.jelly
new file mode 100644
index 0000000..2d171b7
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/resources/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorView/newViewDetail.jelly
@@ -0,0 +1,4 @@
+<div>
+ Shows a highly visible status of selected jobs.
+ Ideal as an Extreme Feedback Device to be displayed on a screen on your office wall.
+</div>
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/resources/index.jelly b/java/jenkins_plugins/build_monitor/src/main/resources/index.jelly
new file mode 100644
index 0000000..94d4d48
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/resources/index.jelly
@@ -0,0 +1,5 @@
+<div>
+ Provides a highly visible view of the status of selected Jenkins jobs.
+ It easily accommodates different computer screen sizes and is ideal as an Extreme Feedback Device to be
+ displayed on a screen on your office wall.
+</div>
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/less/base/index.less b/java/jenkins_plugins/build_monitor/src/main/webapp/less/base/index.less
new file mode 100644
index 0000000..33c719d
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/less/base/index.less
@@ -0,0 +1 @@
+@import "jenkins_overrides.less";
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/less/base/jenkins_overrides.less b/java/jenkins_plugins/build_monitor/src/main/webapp/less/base/jenkins_overrides.less
new file mode 100644
index 0000000..94dc320
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/less/base/jenkins_overrides.less
@@ -0,0 +1,7 @@
+#header,
+#breadcrumbBar,
+#menuSelector,
+#side-panel,
+#footer-container {
+ display:none;
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/less/index.less b/java/jenkins_plugins/build_monitor/src/main/webapp/less/index.less
new file mode 100644
index 0000000..f2b6b11
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/less/index.less
@@ -0,0 +1,5 @@
+/* SMACSS model described at https://smacss.com/ */
+@import "base/index.less";
+@import "layout/index.less";
+@import "module/index.less";
+@import "state/index.less";
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/less/layout/index.less b/java/jenkins_plugins/build_monitor/src/main/webapp/less/layout/index.less
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/less/layout/index.less
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/less/module/index.less b/java/jenkins_plugins/build_monitor/src/main/webapp/less/module/index.less
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/less/module/index.less
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/less/state/index.less b/java/jenkins_plugins/build_monitor/src/main/webapp/less/state/index.less
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/less/state/index.less
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/app.js b/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/app.js
new file mode 100644
index 0000000..dcea060
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/app.js
@@ -0,0 +1,11 @@
+'use strict';
+
+angular.
+ module('buildMonitor', [ 'buildMonitor.controllers', 'buildMonitor.settings', 'slugifier' ]).
+ run(['$rootScope', 'notifyUser', function($rootScope, notifyUser) {
+ $rootScope.settings = { };
+
+ if (! Modernizr.flexbox) {
+ notifyUser.aboutInsufficientSupportOfCSS3('flexbox');
+ }
+ }]);
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/controllers.js b/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/controllers.js
new file mode 100644
index 0000000..abf6639
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/controllers.js
@@ -0,0 +1,120 @@
+'use strict';
+
+angular.
+ module('buildMonitor.controllers', [ 'buildMonitor.services', 'buildMonitor.cron', 'uiSlider', 'jenkins']).
+
+ controller('JobViews', ['$scope', '$rootScope', 'proxy', 'every', 'connectivityStrategist',
+ function ($scope, $rootScope, proxy, every, connectivityStrategist) {
+ var tryToRecover = connectivityStrategist.decideOnStrategy,
+ fetchJobViews = proxy.buildMonitor.fetchJobViews;
+
+ $scope.jobs = {};
+
+ every(5000, function () {
+
+ return fetchJobViews().then(function (response) {
+
+ $scope.jobs = response.data.jobs;
+ $scope.title = response.data.title;
+ $scope.oncall = response.data.oncall;
+
+ $rootScope.$broadcast('jenkins:data-fetched', {});
+
+ }, tryToRecover());
+ });
+ }]).
+
+ service('connectivityStrategist', ['$rootScope', '$q', 'counter',
+ function ($rootScope, $q, counter) {
+
+ var lostConnectionsCount = counter;
+
+ this.resetErrorCounter = function () {
+ if (lostConnectionsCount.value() > 0) {
+ $rootScope.$broadcast("jenkins:connection-reestablished", {});
+ }
+
+ lostConnectionsCount.reset();
+ }
+
+ this.decideOnStrategy = function () {
+
+ function handleLostConnection(error) {
+ lostConnectionsCount.increase();
+
+ $rootScope.$broadcast("jenkins:connection-lost", error);
+
+ return $q.when(error);
+ }
+
+ function handleJenkinsRestart(error) {
+ $rootScope.$broadcast("jenkins:restarted", error);
+ return $q.reject(error);
+ }
+
+ function handleInternalJenkins(error) {
+ $rootScope.$broadcast("jenkins:internal-error", error);
+ return $q.reject(error);
+ }
+
+ function handleUnknown(error) {
+ $rootScope.$broadcast("jenkins:unknown-communication-error", error);
+ return $q.reject(error);
+ }
+
+ return function (error) {
+ switch (error.status) {
+ case 0: return handleLostConnection(error);
+ case 404: return handleJenkinsRestart(error);
+ case 500: return handleInternalJenkins(error);
+ default: return handleUnknown(error);
+ }
+ }
+ }
+ }]).
+
+ directive('notifier', ['$timeout', function ($timeout) {
+ return {
+ restrict: 'E',
+ controller: function ($scope) {
+ $scope.message = '';
+
+ $scope.$on('jenkins:connection-lost', function () {
+ $scope.message = 'Communication with Jenkins mother ship is lost. Trying to reconnect...';
+ });
+
+ $scope.$on('jenkins:connection-reestablished', function () {
+ $scope.message = "... and we're back online, yay! :-)";
+
+ $timeout(function () {
+ $scope.message = "";
+ }, 3000);
+ });
+ },
+ replace: true,
+ template: '<span class="notifier" ' +
+ 'ng-show="message"' +
+ 'ng-animate="\'fade\'">' +
+ '{{ message }}' +
+ "</span>\n"
+ }
+ }]).
+
+ run(['$rootScope', '$window', '$log', 'notifyUser', 'connectivityStrategist',
+ function ($rootScope, $window, $log, notifyUser, connectivityStrategist) {
+ $rootScope.$on('jenkins:data-fetched', function (event) {
+ connectivityStrategist.resetErrorCounter();
+ });
+
+ $rootScope.$on('jenkins:internal-error', function (event, error) {
+ notifyUser.aboutInternalJenkins(error);
+ });
+
+ $rootScope.$on('jenkins:restarted', function (event, error) {
+ $window.location.reload();
+ });
+
+ $rootScope.$on('jenkins:unknown-communication-error', function (event, error) {
+ notifyUser.about(error.status);
+ });
+ }]);
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/cron.js b/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/cron.js
new file mode 100644
index 0000000..cb71f43
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/cron.js
@@ -0,0 +1,37 @@
+angular.
+ module('buildMonitor.cron', []).
+
+ provider('every', function () {
+ this.$get = ['$rootScope', '$window', '$q', '$timeout',
+ function ($rootScope, $window, $q, $timeout) {
+
+ function every(interval, command) {
+ var isDefined = angular.isDefined,
+ isFunction = angular.isFunction,
+ isDeferred = function (result) {
+ return (isDefined(result) && isFunction(result.then));
+ },
+ applyRootScope = function () {
+ $rootScope.$$phase || $rootScope.$apply();
+ };
+
+ function step() {
+ var result = command();
+
+ if (isDeferred(result)) {
+ result.then(function () {
+ $timeout(step, interval);
+ })
+ } else {
+ $timeout(step, interval);
+ }
+
+ applyRootScope();
+ }
+
+ step();
+ }
+
+ return every;
+ }];
+ });
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/jenkins.js b/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/jenkins.js
new file mode 100644
index 0000000..f705676
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/jenkins.js
@@ -0,0 +1,87 @@
+'use strict';
+
+angular.module('jenkins', []).
+
+ constant('STAPLER_CONTENT_TYPE', 'application/x-stapler-method-invocation;charset=UTF-8').
+
+ provider('proxy', function() {
+ this.bindings = {};
+
+ this.configureProxiesUsing = function(bindings) {
+ this.bindings = bindings;
+ };
+
+ this.$get = ['proxyFrom', function(proxyFrom) {
+ var proxies = {};
+
+ angular.forEach(this.bindings, function(binding, name) {
+ proxies[name] = proxyFrom(binding);
+ });
+
+ return proxies;
+ }];
+ }).
+
+ factory('stringified', function() {
+ return function (object) {
+ var stringified = angular.toJson(object);
+
+ stringified = stringified.replace(/^"/, '');
+ stringified = stringified.replace(/"$/, '');
+ stringified = stringified.replace(/\\"/g, '"');
+
+ return stringified;
+ };
+ }).
+
+ factory('proxyFrom', ['$http', 'stringified', 'STAPLER_CONTENT_TYPE', function($http, stringified, STAPLER_CONTENT_TYPE) {
+ return function(binding) {
+ var url = binding.url + '/',
+ proxy = {};
+
+ angular.forEach(binding.methods, function(method) {
+ proxy[method] = function() {
+ var parameters = Array.prototype.slice.apply(arguments);
+
+ return $http({
+ url: url + method,
+ method: 'POST',
+ data: stringified(parameters),
+ headers: {
+ 'Content-Type': STAPLER_CONTENT_TYPE,
+ 'Crumb': binding.crumb, // Crumb header is needed to get past Stapler
+ '.crumb': binding.crumb // .crumb header is needed to support CSRF protection (#46)
+ }
+ });
+ }
+ });
+
+ return proxy;
+ }
+ }]).
+
+ factory('responseCodeStandardsIntroducer', ['$q', 'STAPLER_CONTENT_TYPE', function($q, STAPLER_CONTENT_TYPE) {
+ function isAStapler(response) {
+ return (response.config.headers
+ && response.config.headers['Content-Type'] === STAPLER_CONTENT_TYPE);
+ }
+
+ return {
+ 'response': function(response) {
+ if (isAStapler(response) && response.data.stackTrace) {
+ // this is required to patch the incorrect behaviour of Stapler
+ // see https://issues.jenkins-ci.org/browse/JENKINS-21132
+ var augmentedResponse = angular.copy(response);
+ augmentedResponse.status = 500;
+
+ return $q.reject(augmentedResponse);
+ }
+
+ return response;
+ }
+ };
+ }]).
+
+ config(function ($httpProvider) {
+ $httpProvider.interceptors.push('responseCodeStandardsIntroducer');
+ });
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/services.js b/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/services.js
new file mode 100644
index 0000000..4099af6
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/services.js
@@ -0,0 +1,161 @@
+'use strict';
+
+angular.
+ module('buildMonitor.services', ['ui.bootstrap.dialog', 'buildMonitor.templates', 'template/dialog/message.html']).
+
+ value('YahooCookie', YAHOO.util.Cookie).
+
+ service('notifyUser',function ($dialog, $window) {
+ this.aboutInsufficientSupportOfCSS3 = function(feature) {
+ $dialog.dialog({
+ templateUrl: 'template/dialog/insufficient-css3-support.html',
+ controller: function($scope, dialog, model) {
+ $scope.feature = model.feature;
+ },
+ resolve: { model: function() {
+ return { feature: feature };
+ }},
+ keyboard: false,
+ backdrop: false
+ }).open().then();
+ }
+
+ this.aboutInternalJenkins = function(error) {
+ function stackTraceOf(error) {
+ var stackTrace = "";
+
+ if (! (error.data && angular.isArray(error.data.stackTrace))) {
+ return stackTrace;
+ }
+
+ angular.forEach(error.data.stackTrace, function(entry) {
+ stackTrace += "at " + entry.className + "(" + entry.fileName + ":" + entry.lineNumber + ")\n";
+ });
+
+ return stackTrace;
+ }
+
+ $dialog.dialog({
+ templateUrl: 'template/dialog/internal-jenkins-error.html',
+ controller: function($scope, dialog, model) {
+ $scope.error = model.error;
+ $scope.stackTrace = model.stackTrace;
+ },
+ resolve: { model: function() {
+ return {
+ error: JSON.stringify(error.data, undefined, 2),
+ stackTrace: stackTraceOf(error)
+ };
+ }},
+ keyboard: false,
+ backdrop: true,
+ backdropClick: false
+ }).open().then();
+ }
+
+ this.about = function (problemStatus) {
+
+ /*
+ var title = "Sorry to bother you, but there is a slight issue ...";
+ var message = "Jenkins returned a \"" + problemStatus + "\" response " +
+ "causing the last request to fail. " +
+ "This usually means a network connection problem " +
+ "or that Jenkins is being restarted. " +
+ "Don't worry, reloading the page should help :-)";
+
+ $dialog.messageBox(title, message, [
+ { result: "reload", label: "Reload the page"}
+ ]).open().then(function (result) {
+ $window.location.reload();
+ });
+ */
+ $window.location.reload();
+ }
+ }).
+
+ provider('cookieJar',function () {
+ var defaultAttributes = {
+ label: '',
+ shelfLife: 0
+ },
+ attributes = {};
+
+ this.describe = function (cookieJarAttributes) {
+ attributes = cookieJarAttributes;
+ }
+
+ this.$get = ['YahooCookie', function (YahooCookie) {
+ return new CookieJar(YahooCookie, angular.extend(defaultAttributes, attributes));
+ }];
+
+
+ function CookieJar(YahooCookie, attributes) {
+
+ function expiryDetailsBasedOn(days) {
+ if (days <= 0) {
+ return {};
+ }
+
+ return {
+ expires: new Date(+new Date() + (days * 1000 * 3600 * 24))
+ }
+ }
+
+ function prefixed(name) {
+ return attributes.label
+ ? attributes.label + '.' + name
+ : name;
+ }
+
+ return {
+ put: function (name, value) {
+ YahooCookie.set(prefixed(name), value, expiryDetailsBasedOn(attributes.shelfLife));
+ },
+ get: function (name, defaultValue) {
+ var value = YahooCookie.get(prefixed(name));
+
+ return (value !== null)
+ ? value
+ : defaultValue;
+ }
+ }
+ }
+ }).
+
+ provider('hashCode', function () {
+ this.hashCodeOf = hashCodeOf;
+
+ this.$get = function() {
+ return hashCodeOf
+ }
+
+ function hashCodeOf(name) {
+ var name = name || '',
+ hash = 0,
+ char;
+
+ if (name.length == 0) {
+ return hash;
+ }
+
+ for (var i = 0; i < name.length; i++) {
+ char = name.charCodeAt(i);
+ hash = ((hash << 5) - hash) + char;
+ hash = hash & hash; // Convert to 32bit integer
+ }
+
+ return hash;
+ }
+ }).
+
+
+ factory('counter', [function() {
+
+ var value = 0;
+
+ return {
+ reset: function() { value = 0; },
+ increase: function() { ++value; },
+ value: function() { return value; }
+ }
+ }]);
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/settings.js b/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/settings.js
new file mode 100644
index 0000000..c7054b3
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/settings.js
@@ -0,0 +1,19 @@
+angular.
+ module('buildMonitor.settings', [ 'buildMonitor.services', 'uiSlider']).
+
+ controller('controlPanel', ['$scope', 'cookieJar',
+ function ($scope, cookieJar) {
+ 'use strict';
+
+ $scope.settings.fontSize = cookieJar.get('fontSize', 1);
+ $scope.settings.numberOfColumns = cookieJar.get('numberOfColumns', 2);
+ $scope.settings.colourBlind = cookieJar.get('colourBlind', 0);
+ $scope.settings.showCulprits = cookieJar.get('showCulprits', 0);
+ $scope.settings.stripVanadium = cookieJar.get('stripVanadium', 0);
+
+ angular.forEach($scope.settings, function(value, name) {
+ $scope.$watch('settings.' + name, function(currentValue) {
+ cookieJar.put(name, currentValue);
+ });
+ });
+ }]);
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/templates.js b/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/templates.js
new file mode 100644
index 0000000..40e37d0
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/scripts/templates.js
@@ -0,0 +1,43 @@
+'use strict';
+
+angular.module("buildMonitor.templates", []).run(["$templateCache", function($templateCache) {
+ $templateCache.put("template/dialog/problem-with-jenkins.htm",
+ "<div class=\"modal-header\">\n" +
+ " <h1>{{ title }}</h1>\n" +
+ "</div>\n" +
+ "<div class=\"modal-body\">\n" +
+ " <p>{{ message }}</p>\n" +
+ "</div>\n" +
+ "<div class=\"modal-footer\">\n" +
+ " <button ng-repeat=\"btn in buttons\" ng-click=\"close(btn.result)\" class=btn ng-class=\"btn.cssClass\">{{ btn.namespace }}</button>\n" +
+ "</div>\n" +
+ "");
+
+ $templateCache.put("template/dialog/insufficient-css3-support.html",
+ "<div class=\"modal-header\">\n" +
+ " <h1>It seems like your browser is having problems with CSS3</h1>\n" +
+ "</div>\n" +
+ "<div class=\"modal-body\">\n" +
+ " <p>" +
+ " Your browser does not seem to understand <i>CSS3 {{ feature }}</i>.<br />" +
+ " Please <a href=\"http://caniuse.com/{{ feature }}\" target=\"_blank\">click here</a> " +
+ " to see which modern browsers support this feature and consider upgrading." +
+ " </p>\n" +
+ "</div>\n" +
+ "");
+
+ $templateCache.put("template/dialog/internal-jenkins-error.html",
+ "<div class=\"modal-header\">\n" +
+ " <h1>Sorry to bother you, but Jenkins is having a problem :-(</h1>\n" +
+ "</div>\n" +
+ "<div class=\"modal-body\">\n" +
+ " <p>Instead of an expected response I received the following, which usually means an internal Jenkins error:</p>" +
+ " <textarea rows='5'>{{ error }}</textarea>\n" +
+ " <div ng-show='{{ stackTrace.length }}'>\n" +
+ " <p>This translates to the following stack trace:</p>\n" +
+ " <textarea rows='5'>{{ stackTrace }}</textarea>\n" +
+ " </div>\n" +
+ " <p>Before <a href='https://issues.jenkins-ci.org/secure/Dashboard.jspa'>reporting a bug in Jenkins</a> it's usually worth trying to troubleshoot it using the information from your <a href='https://wiki.jenkins-ci.org/display/JENKINS/Logging'>Jenkins Error Log</a>.</p>\n" +
+ "</div>\n" +
+ "");
+}]);
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/styles/angular-slider.css b/java/jenkins_plugins/build_monitor/src/main/webapp/styles/angular-slider.css
new file mode 100755
index 0000000..baf418d
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/styles/angular-slider.css
@@ -0,0 +1,86 @@
+slider {
+ display: inline-block;
+ position: relative;
+ height: 7px;
+ width: 100%;
+ margin: 25px 5px 25px 5px;
+ vertical-align: middle;
+}
+slider span {
+ white-space: nowrap;
+ position: absolute;
+ display: inline-block;
+}
+slider span.base {
+ width: 100%;
+ height: 100%;
+ padding: 0;
+}
+slider span.bar {
+ width: 100%;
+ height: 100%;
+ z-index: 0;
+ -webkit-border-radius: 1em/1em;
+ border-radius: 1em/1em;
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #c0c0c0), color-stop(1, #8d8d8d));
+ background: -webkit-linear-gradient(top, #c0c0c0 0%, #8d8d8d 100%);
+ background: -moz-linear-gradient(top, #c0c0c0 0%, #8d8d8d 100%);
+ background: -o-linear-gradient(top, #c0c0c0 0%, #8d8d8d 100%);
+ background: -ms-linear-gradient(top, #c0c0c0 0%, #8d8d8d 100%);
+ background: linear-gradient(top, #c0c0c0 0%, #8d8d8d 100%);
+ -webkit-box-shadow: inset 2px 2px 5px;
+ box-shadow: inset 2px 2px 5px;
+}
+slider span.bar.selection {
+ width: 0%;
+ z-index: 1;
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #13b6ff), color-stop(1, #00a8f3));
+ background: -webkit-linear-gradient(top, #13b6ff 0%, #00a8f3 100%);
+ background: -moz-linear-gradient(top, #13b6ff 0%, #00a8f3 100%);
+ background: -o-linear-gradient(top, #13b6ff 0%, #00a8f3 100%);
+ background: -ms-linear-gradient(top, #13b6ff 0%, #00a8f3 100%);
+ background: linear-gradient(top, #13b6ff 0%, #00a8f3 100%);
+ -webkit-box-shadow: none;
+ box-shadow: none;
+}
+slider span.pointer {
+ cursor: pointer;
+ width: 20px;
+ height: 20px;
+ top: -8px;
+ background-color: #fff;
+ border: 1px solid #000;
+ z-index: 2;
+ -webkit-border-radius: 1em/1em;
+ border-radius: 1em/1em;
+}
+slider span.pointer:after {
+ content: '';
+ background-color: #808080;
+ width: 8px;
+ height: 8px;
+ position: absolute;
+ top: 6px;
+ left: 6px;
+ -webkit-border-radius: 1em/1em;
+ border-radius: 1em/1em;
+}
+slider span.pointer:hover:after {
+ background-color: #000;
+}
+slider span.pointer.active:after {
+ background-color: #f00;
+}
+slider span.bubble {
+ cursor: default;
+ top: -22px;
+ padding: 1px 3px 1px 3px;
+ font-size: 0.7em;
+ font-family: sans-serif;
+}
+slider span.bubble.selection {
+ top: 15px;
+}
+slider span.bubble.limit {
+ color: #808080;
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/styles/bootstrap-combined.2.3.2.min.css b/java/jenkins_plugins/build_monitor/src/main/webapp/styles/bootstrap-combined.2.3.2.min.css
new file mode 100644
index 0000000..afcd462
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/styles/bootstrap-combined.2.3.2.min.css
@@ -0,0 +1,121 @@
+/*!
+ * Bootstrap v2.3.2
+ *
+ * Copyright 2012 Twitter, Inc
+ * Licensed under the Apache License v2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Designed and built with all the love in the world @twitter by @mdo and @fat.
+ */
+.clearfix{*zoom:1;}.clearfix:before,.clearfix:after{display:table;content:"";line-height:0;}
+.clearfix:after{clear:both;}
+button,input,select,textarea{margin:0;font-size:100%;vertical-align:middle;}
+button,input{*overflow:visible;line-height:normal;}
+button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0;}
+button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer;}
+label,select,button,input[type="button"],input[type="reset"],input[type="submit"],input[type="radio"],input[type="checkbox"]{cursor:pointer;}
+.btn .label,.btn .badge{position:relative;top:-1px;}
+.btn-mini .label,.btn-mini .badge{top:0;}
+label,input,button,select,textarea{font-size:14px;font-weight:normal;line-height:20px;}
+input,button,select,textarea{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;}
+.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333333;text-shadow:0 1px 1px rgba(255, 255, 255, 0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top, #ffffff, #e6e6e6);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6));background-image:-webkit-linear-gradient(top, #ffffff, #e6e6e6);background-image:-o-linear-gradient(top, #ffffff, #e6e6e6);background-image:linear-gradient(to bottom, #ffffff, #e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #cccccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333333;background-color:#e6e6e6;*background-color:#d9d9d9;}
+.btn:active,.btn.active{background-color:#cccccc \9;}
+.btn:first-child{*margin-left:0;}
+.btn:hover,.btn:focus{color:#333333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position 0.1s linear;-moz-transition:background-position 0.1s linear;-o-transition:background-position 0.1s linear;transition:background-position 0.1s linear;}
+.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px;}
+.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);}
+.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:0.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;}
+.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;}
+.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px;}
+.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;}
+.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0;}
+.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px;}
+.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;}
+.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;}
+.btn-block+.btn-block{margin-top:5px;}
+input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%;}
+.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255, 255, 255, 0.75);}
+.btn-primary{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top, #0088cc, #0044cc);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc));background-image:-webkit-linear-gradient(top, #0088cc, #0044cc);background-image:-o-linear-gradient(top, #0088cc, #0044cc);background-image:linear-gradient(to bottom, #0088cc, #0044cc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#0044cc #0044cc #002a80;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#0044cc;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#ffffff;background-color:#0044cc;*background-color:#003bb3;}
+.btn-primary:active,.btn-primary.active{background-color:#003399 \9;}
+.btn-warning{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#faa732;background-image:-moz-linear-gradient(top, #fbb450, #f89406);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406));background-image:-webkit-linear-gradient(top, #fbb450, #f89406);background-image:-o-linear-gradient(top, #fbb450, #f89406);background-image:linear-gradient(to bottom, #fbb450, #f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#ffffff;background-color:#f89406;*background-color:#df8505;}
+.btn-warning:active,.btn-warning.active{background-color:#c67605 \9;}
+.btn-danger{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#da4f49;background-image:-moz-linear-gradient(top, #ee5f5b, #bd362f);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#bd362f));background-image:-webkit-linear-gradient(top, #ee5f5b, #bd362f);background-image:-o-linear-gradient(top, #ee5f5b, #bd362f);background-image:linear-gradient(to bottom, #ee5f5b, #bd362f);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffbd362f', GradientType=0);border-color:#bd362f #bd362f #802420;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#bd362f;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#ffffff;background-color:#bd362f;*background-color:#a9302a;}
+.btn-danger:active,.btn-danger.active{background-color:#942a25 \9;}
+.btn-success{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#5bb75b;background-image:-moz-linear-gradient(top, #62c462, #51a351);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#51a351));background-image:-webkit-linear-gradient(top, #62c462, #51a351);background-image:-o-linear-gradient(top, #62c462, #51a351);background-image:linear-gradient(to bottom, #62c462, #51a351);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff51a351', GradientType=0);border-color:#51a351 #51a351 #387038;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#51a351;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#ffffff;background-color:#51a351;*background-color:#499249;}
+.btn-success:active,.btn-success.active{background-color:#408140 \9;}
+.btn-info{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#49afcd;background-image:-moz-linear-gradient(top, #5bc0de, #2f96b4);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4));background-image:-webkit-linear-gradient(top, #5bc0de, #2f96b4);background-image:-o-linear-gradient(top, #5bc0de, #2f96b4);background-image:linear-gradient(to bottom, #5bc0de, #2f96b4);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f96b4', GradientType=0);border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#2f96b4;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#ffffff;background-color:#2f96b4;*background-color:#2a85a0;}
+.btn-info:active,.btn-info.active{background-color:#24748c \9;}
+.btn-inverse{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#363636;background-image:-moz-linear-gradient(top, #444444, #222222);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#444444), to(#222222));background-image:-webkit-linear-gradient(top, #444444, #222222);background-image:-o-linear-gradient(top, #444444, #222222);background-image:linear-gradient(to bottom, #444444, #222222);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444', endColorstr='#ff222222', GradientType=0);border-color:#222222 #222222 #000000;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#222222;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#ffffff;background-color:#222222;*background-color:#151515;}
+.btn-inverse:active,.btn-inverse.active{background-color:#080808 \9;}
+button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px;}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0;}
+button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px;}
+button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px;}
+button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px;}
+.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;}
+.btn-link{border-color:transparent;cursor:pointer;color:#0088cc;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;}
+.btn-link:hover,.btn-link:focus{color:#005580;text-decoration:underline;background-color:transparent;}
+.btn-link[disabled]:hover,.btn-link[disabled]:focus{color:#333333;text-decoration:none;}
+.btn-group{position:relative;display:inline-block;*display:inline;*zoom:1;font-size:0;vertical-align:middle;white-space:nowrap;*margin-left:.3em;}.btn-group:first-child{*margin-left:0;}
+.btn-group+.btn-group{margin-left:5px;}
+.btn-toolbar{font-size:0;margin-top:10px;margin-bottom:10px;}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group{margin-left:5px;}
+.btn-group>.btn{position:relative;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;}
+.btn-group>.btn+.btn{margin-left:-1px;}
+.btn-group>.btn,.btn-group>.dropdown-menu,.btn-group>.popover{font-size:14px;}
+.btn-group>.btn-mini{font-size:10.5px;}
+.btn-group>.btn-small{font-size:11.9px;}
+.btn-group>.btn-large{font-size:17.5px;}
+.btn-group>.btn:first-child{margin-left:0;-webkit-border-top-left-radius:4px;-moz-border-radius-topleft:4px;border-top-left-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px;}
+.btn-group>.btn:last-child,.btn-group>.dropdown-toggle{-webkit-border-top-right-radius:4px;-moz-border-radius-topright:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;}
+.btn-group>.btn.large:first-child{margin-left:0;-webkit-border-top-left-radius:6px;-moz-border-radius-topleft:6px;border-top-left-radius:6px;-webkit-border-bottom-left-radius:6px;-moz-border-radius-bottomleft:6px;border-bottom-left-radius:6px;}
+.btn-group>.btn.large:last-child,.btn-group>.large.dropdown-toggle{-webkit-border-top-right-radius:6px;-moz-border-radius-topright:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;-moz-border-radius-bottomright:6px;border-bottom-right-radius:6px;}
+.btn-group>.btn:hover,.btn-group>.btn:focus,.btn-group>.btn:active,.btn-group>.btn.active{z-index:2;}
+.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0;}
+.btn-group>.btn+.dropdown-toggle{padding-left:8px;padding-right:8px;-webkit-box-shadow:inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);*padding-top:5px;*padding-bottom:5px;}
+.btn-group>.btn-mini+.dropdown-toggle{padding-left:5px;padding-right:5px;*padding-top:2px;*padding-bottom:2px;}
+.btn-group>.btn-small+.dropdown-toggle{*padding-top:5px;*padding-bottom:4px;}
+.btn-group>.btn-large+.dropdown-toggle{padding-left:12px;padding-right:12px;*padding-top:7px;*padding-bottom:7px;}
+.btn-group.open .dropdown-toggle{background-image:none;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);}
+.btn-group.open .btn.dropdown-toggle{background-color:#e6e6e6;}
+.btn-group.open .btn-primary.dropdown-toggle{background-color:#0044cc;}
+.btn-group.open .btn-warning.dropdown-toggle{background-color:#f89406;}
+.btn-group.open .btn-danger.dropdown-toggle{background-color:#bd362f;}
+.btn-group.open .btn-success.dropdown-toggle{background-color:#51a351;}
+.btn-group.open .btn-info.dropdown-toggle{background-color:#2f96b4;}
+.btn-group.open .btn-inverse.dropdown-toggle{background-color:#222222;}
+.btn .caret{margin-top:8px;margin-left:0;}
+.btn-large .caret{margin-top:6px;}
+.btn-large .caret{border-left-width:5px;border-right-width:5px;border-top-width:5px;}
+.btn-mini .caret,.btn-small .caret{margin-top:8px;}
+.btn-primary .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret,.btn-success .caret,.btn-inverse .caret{border-top-color:#ffffff;border-bottom-color:#ffffff;}
+.btn-group-vertical{display:inline-block;*display:inline;*zoom:1;}
+.btn-group-vertical>.btn{display:block;float:none;max-width:100%;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;}
+.btn-group-vertical>.btn+.btn{margin-left:0;margin-top:-1px;}
+.btn-group-vertical>.btn:first-child{-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0;}
+.btn-group-vertical>.btn:last-child{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px;}
+.btn-group-vertical>.btn-large:first-child{-webkit-border-radius:6px 6px 0 0;-moz-border-radius:6px 6px 0 0;border-radius:6px 6px 0 0;}
+.btn-group-vertical>.btn-large:last-child{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;}
+.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000000;}.modal-backdrop.fade{opacity:0;}
+.modal-backdrop,.modal-backdrop.fade.in{opacity:0.8;filter:alpha(opacity=80);}
+.modal{position:fixed;top:10%;left:50%;z-index:1050;width:560px;margin-left:-280px;background-color:#ffffff;border:1px solid #999;border:1px solid rgba(0, 0, 0, 0.3);*border:1px solid #999;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 3px 7px rgba(0, 0, 0, 0.3);-moz-box-shadow:0 3px 7px rgba(0, 0, 0, 0.3);box-shadow:0 3px 7px rgba(0, 0, 0, 0.3);-webkit-background-clip:padding-box;-moz-background-clip:padding-box;background-clip:padding-box;outline:none;}.modal.fade{-webkit-transition:opacity .3s linear, top .3s ease-out;-moz-transition:opacity .3s linear, top .3s ease-out;-o-transition:opacity .3s linear, top .3s ease-out;transition:opacity .3s linear, top .3s ease-out;top:-25%;}
+.modal.fade.in{top:10%;}
+.modal-header{padding:9px 15px;border-bottom:1px solid #eee;}.modal-header .close{margin-top:2px;}
+.modal-header h3{margin:0;line-height:30px;}
+.modal-body{position:relative;overflow-y:auto;max-height:400px;padding:15px;}
+.modal-form{margin-bottom:0;}
+.modal-footer{padding:14px 15px 15px;margin-bottom:0;text-align:right;background-color:#f5f5f5;border-top:1px solid #ddd;-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;-webkit-box-shadow:inset 0 1px 0 #ffffff;-moz-box-shadow:inset 0 1px 0 #ffffff;box-shadow:inset 0 1px 0 #ffffff;*zoom:1;}.modal-footer:before,.modal-footer:after{display:table;content:"";line-height:0;}
+.modal-footer:after{clear:both;}
+.modal-footer .btn+.btn{margin-left:5px;margin-bottom:0;}
+.modal-footer .btn-group .btn+.btn{margin-left:-1px;}
+.modal-footer .btn-block+.btn-block{margin-left:0;}
+.close{float:right;font-size:20px;font-weight:bold;line-height:20px;color:#000000;text-shadow:0 1px 0 #ffffff;opacity:0.2;filter:alpha(opacity=20);}.close:hover,.close:focus{color:#000000;text-decoration:none;cursor:pointer;opacity:0.4;filter:alpha(opacity=40);}
+button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none;}
+.hide{display:none;}
+.show{display:block;}
+.invisible{visibility:hidden;}
+.affix{position:fixed;}
+.fade{opacity:0;-webkit-transition:opacity 0.15s linear;-moz-transition:opacity 0.15s linear;-o-transition:opacity 0.15s linear;transition:opacity 0.15s linear;}.fade.in{opacity:1;}
+.collapse{position:relative;height:0;overflow:hidden;-webkit-transition:height 0.35s ease;-moz-transition:height 0.35s ease;-o-transition:height 0.35s ease;transition:height 0.35s ease;}.collapse.in{height:auto;}
+.visible-phone{display:none !important;}
+.visible-tablet{display:none !important;}
+.hidden-desktop{display:none !important;}
+.visible-desktop{display:inherit !important;}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/styles/normalize.css b/java/jenkins_plugins/build_monitor/src/main/webapp/styles/normalize.css
new file mode 100644
index 0000000..74ec031
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/styles/normalize.css
@@ -0,0 +1,533 @@
+/*! normalize.css v1.1.1 | MIT License | git.io/normalize */
+
+/* ==========================================================================
+ HTML5 display definitions
+ ========================================================================== */
+
+/**
+ * Correct `block` display not defined in IE 6/7/8/9 and Firefox 3.
+ */
+
+article,
+aside,
+details,
+figcaption,
+figure,
+footer,
+header,
+hgroup,
+main,
+nav,
+section,
+summary {
+ display: block;
+}
+
+/**
+ * Correct `inline-block` display not defined in IE 6/7/8/9 and Firefox 3.
+ */
+
+audio,
+canvas,
+video {
+ display: inline-block;
+ *display: inline;
+ *zoom: 1;
+}
+
+/**
+ * Prevent modern browsers ofA displaying `audio` without controls.
+ * Remove excess height in iOS 5 devices.
+ */
+
+audio:not([controls]) {
+ display: none;
+ height: 0;
+}
+
+/**
+ * Address styling not present in IE 7/8/9, Firefox 3, and Safari 4.
+ * Known issue: no IE 6 support.
+ */
+
+[hidden] {
+ display: none;
+}
+
+/* ==========================================================================
+ Base
+ ========================================================================== */
+
+/**
+ * 1. Prevent system color scheme's background color being used in Firefox, IE,
+ * and Opera.
+ * 2. Prevent system color scheme's text color being used in Firefox, IE, and
+ * Opera.
+ * 3. Correct text resizing oddly in IE 6/7 when body `font-size` is set using
+ * `em` units.
+ * 4. Prevent iOS text size adjust after orientation change, without disabling
+ * user zoom.
+ */
+
+html {
+ background: #fff; /* 1 */
+ color: #000; /* 2 */
+ font-size: 100%; /* 3 */
+ -webkit-text-size-adjust: 100%; /* 4 */
+ -ms-text-size-adjust: 100%; /* 4 */
+}
+
+/**
+ * Address `font-family` inconsistency between `textarea` and other form
+ * elements.
+ */
+
+html,
+button,
+input,
+select,
+textarea {
+ font-family: sans-serif;
+}
+
+/**
+ * Address margins handled incorrectly in IE 6/7.
+ */
+
+body {
+ margin: 0;
+}
+
+/* ==========================================================================
+ Links
+ ========================================================================== */
+
+/**
+ * Address `outline` inconsistency between Chrome and other browsers.
+ */
+
+a:focus {
+ outline: thin dotted;
+}
+
+/**
+ * Improve readability when focused and also mouse hovered in all browsers.
+ */
+
+a:active,
+a:hover {
+ outline: 0;
+}
+
+/* ==========================================================================
+ Typography
+ ========================================================================== */
+
+/**
+ * Address font sizes and margins set differently in IE 6/7.
+ * Address font sizes within `section` and `article` in Firefox 4+, Safari 5,
+ * and Chrome.
+ */
+
+h1 {
+ font-size: 2em;
+ margin: 0.67em 0;
+}
+
+h2 {
+ font-size: 1.5em;
+ margin: 0.83em 0;
+}
+
+h3 {
+ font-size: 1.17em;
+ margin: 1em 0;
+}
+
+h4 {
+ font-size: 1em;
+ margin: 1.33em 0;
+}
+
+h5 {
+ font-size: 0.83em;
+ margin: 1.67em 0;
+}
+
+h6 {
+ font-size: 0.67em;
+ margin: 2.33em 0;
+}
+
+/**
+ * Address styling not present in IE 7/8/9, Safari 5, and Chrome.
+ */
+
+abbr[title] {
+ border-bottom: 1px dotted;
+}
+
+/**
+ * Address style set to `bolder` in Firefox 3+, Safari 4/5, and Chrome.
+ */
+
+b,
+strong {
+ font-weight: bold;
+}
+
+blockquote {
+ margin: 1em 40px;
+}
+
+/**
+ * Address styling not present in Safari 5 and Chrome.
+ */
+
+dfn {
+ font-style: italic;
+}
+
+/**
+ * Address differences between Firefox and other browsers.
+ * Known issue: no IE 6/7 normalization.
+ */
+
+hr {
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+ height: 0;
+}
+
+/**
+ * Address styling not present in IE 6/7/8/9.
+ */
+
+mark {
+ background: #ff0;
+ color: #000;
+}
+
+/**
+ * Address margins set differently in IE 6/7.
+ */
+
+p,
+pre {
+ margin: 1em 0;
+}
+
+/**
+ * Correct font family set oddly in IE 6, Safari 4/5, and Chrome.
+ */
+
+code,
+kbd,
+pre,
+samp {
+ font-family: monospace, serif;
+ _font-family: 'courier new', monospace;
+ font-size: 1em;
+}
+
+/**
+ * Improve readability of pre-formatted text in all browsers.
+ */
+
+pre {
+ white-space: pre;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+}
+
+/**
+ * Address CSS quotes not supported in IE 6/7.
+ */
+
+q {
+ quotes: none;
+}
+
+/**
+ * Address `quotes` property not supported in Safari 4.
+ */
+
+q:before,
+q:after {
+ content: '';
+ content: none;
+}
+
+/**
+ * Address inconsistent and variable font size in all browsers.
+ */
+
+small {
+ font-size: 80%;
+}
+
+/**
+ * Prevent `sub` and `sup` affecting `line-height` in all browsers.
+ */
+
+sub,
+sup {
+ font-size: 75%;
+ line-height: 0;
+ position: relative;
+ vertical-align: baseline;
+}
+
+sup {
+ top: -0.5em;
+}
+
+sub {
+ bottom: -0.25em;
+}
+
+/* ==========================================================================
+ Lists
+ ========================================================================== */
+
+/**
+ * Address margins set differently in IE 6/7.
+ */
+
+dl,
+menu,
+ol,
+ul {
+ margin: 1em 0;
+}
+
+dd {
+ margin: 0 0 0 40px;
+}
+
+/**
+ * Address paddings set differently in IE 6/7.
+ */
+
+menu,
+ol,
+ul {
+ padding: 0 0 0 40px;
+}
+
+/**
+ * Correct list images handled incorrectly in IE 7.
+ */
+
+nav ul,
+nav ol {
+ list-style: none;
+ list-style-image: none;
+}
+
+/* ==========================================================================
+ Embedded content
+ ========================================================================== */
+
+/**
+ * 1. Remove border when inside `a` element in IE 6/7/8/9 and Firefox 3.
+ * 2. Improve image quality when scaled in IE 7.
+ */
+
+img {
+ border: 0; /* 1 */
+ -ms-interpolation-mode: bicubic; /* 2 */
+}
+
+/**
+ * Correct overflow displayed oddly in IE 9.
+ */
+
+svg:not(:root) {
+ overflow: hidden;
+}
+
+/* ==========================================================================
+ Figures
+ ========================================================================== */
+
+/**
+ * Address margin not present in IE 6/7/8/9, Safari 5, and Opera 11.
+ */
+
+figure {
+ margin: 0;
+}
+
+/* ==========================================================================
+ Forms
+ ========================================================================== */
+
+/**
+ * Correct margin displayed oddly in IE 6/7.
+ */
+
+form {
+ margin: 0;
+}
+
+/**
+ * Define consistent border, margin, and padding.
+ */
+
+fieldset {
+ border: 1px solid #c0c0c0;
+ margin: 0 2px;
+ padding: 0.35em 0.625em 0.75em;
+}
+
+/**
+ * 1. Correct color not being inherited in IE 6/7/8/9.
+ * 2. Correct text not wrapping in Firefox 3.
+ * 3. Correct alignment displayed oddly in IE 6/7.
+ */
+
+legend {
+ border: 0; /* 1 */
+ padding: 0;
+ white-space: normal; /* 2 */
+ *margin-left: -7px; /* 3 */
+}
+
+/**
+ * 1. Correct font size not being inherited in all browsers.
+ * 2. Address margins set differently in IE 6/7, Firefox 3+, Safari 5,
+ * and Chrome.
+ * 3. Improve appearance and consistency in all browsers.
+ */
+
+button,
+input,
+select,
+textarea {
+ font-size: 100%; /* 1 */
+ margin: 0; /* 2 */
+ vertical-align: baseline; /* 3 */
+ *vertical-align: middle; /* 3 */
+}
+
+/**
+ * Address Firefox 3+ setting `line-height` on `input` using `!important` in
+ * the UA stylesheet.
+ */
+
+button,
+input {
+ line-height: normal;
+}
+
+/**
+ * Address inconsistent `text-transform` inheritance for `button` and `select`.
+ * All other form control elements do not inherit `text-transform` values.
+ * Correct `button` style inheritance in Chrome, Safari 5+, and IE 6+.
+ * Correct `select` style inheritance in Firefox 4+ and Opera.
+ */
+
+button,
+select {
+ text-transform: none;
+}
+
+/**
+ * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
+ * and `video` controls.
+ * 2. Correct inability to style clickable `input` types in iOS.
+ * 3. Improve usability and consistency of cursor style between image-type
+ * `input` and others.
+ * 4. Remove inner spacing in IE 7 without affecting normal text inputs.
+ * Known issue: inner spacing remains in IE 6.
+ */
+
+button,
+html input[type="button"], /* 1 */
+input[type="reset"],
+input[type="submit"] {
+ -webkit-appearance: button; /* 2 */
+ cursor: pointer; /* 3 */
+ *overflow: visible; /* 4 */
+}
+
+/**
+ * Re-set default cursor for disabled elements.
+ */
+
+button[disabled],
+html input[disabled] {
+ cursor: default;
+}
+
+/**
+ * 1. Address box sizing set to content-box in IE 8/9.
+ * 2. Remove excess padding in IE 8/9.
+ * 3. Remove excess padding in IE 7.
+ * Known issue: excess padding remains in IE 6.
+ */
+
+input[type="checkbox"],
+input[type="radio"] {
+ box-sizing: border-box; /* 1 */
+ padding: 0; /* 2 */
+ *height: 13px; /* 3 */
+ *width: 13px; /* 3 */
+}
+
+/**
+ * 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome.
+ * 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome
+ * (include `-moz` to future-proof).
+ */
+
+input[type="search"] {
+ -webkit-appearance: textfield; /* 1 */
+ -moz-box-sizing: content-box;
+ -webkit-box-sizing: content-box; /* 2 */
+ box-sizing: content-box;
+}
+
+/**
+ * Remove inner padding and search cancel button in Safari 5 and Chrome
+ * on OS X.
+ */
+
+input[type="search"]::-webkit-search-cancel-button,
+input[type="search"]::-webkit-search-decoration {
+ -webkit-appearance: none;
+}
+
+/**
+ * Remove inner padding and border in Firefox 3+.
+ */
+
+button::-moz-focus-inner,
+input::-moz-focus-inner {
+ border: 0;
+ padding: 0;
+}
+
+/**
+ * 1. Remove default vertical scrollbar in IE 6/7/8/9.
+ * 2. Improve readability and alignment in all browsers.
+ */
+
+textarea {
+ overflow: auto; /* 1 */
+ vertical-align: top; /* 2 */
+}
+
+/* ==========================================================================
+ Tables
+ ========================================================================== */
+
+/**
+ * Remove most spacing between table cells.
+ */
+
+table {
+ border-collapse: collapse;
+ border-spacing: 0;
+}
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial.css b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial.css
new file mode 100644
index 0000000..deef3d2
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial.css
@@ -0,0 +1,649 @@
+/*
+ * Industrial Theme for Jenkins Build Monitor Plugin
+ */
+
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2014, Jan Molak, SmartCode Ltd http://smartcodeltd.co.uk
+ *
+ * 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 NON-INFRINGEMENT. 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.
+ */
+
+
+/*
+ * Colours & Typography
+ */
+
+@font-face {
+ font-family: 'Open Sans';
+ font-style: normal;
+ font-weight: 400;
+ src: local('Open Sans'), local('OpenSans'), url("industrial/open-sans-normal.woff") format('woff');
+}
+@font-face {
+ font-family: 'Open Sans';
+ font-style: normal;
+ font-weight: 700;
+ src: local('Open Sans Bold'), local('OpenSans-Bold'), url("industrial/open-sans-bold.woff") format('woff');
+}
+
+html{color:#fff;font-family:'Open sans',sans-serif;font-size:16px;line-height:1.4;}
+h1,h2,h3,h4,h5,h6 {
+ text-align:center;
+ margin:0; padding:0;
+}
+h1,h2,h3,h4,h5,h6, li, a {
+ font-family: 'Open sans', Verdana, Helvetica, sans serif;
+}
+.build-monitor { color:#fff; }
+.build-monitor header>h1 {
+ text-shadow: 2px 2px rgba(0,0,0,0.5);
+}
+h2 {
+ text-shadow: 1px 1px rgba(0,0,0,0.5);
+}
+
+.build-monitor a {
+ color: #73BFFF;
+ text-decoration: none;
+}
+
+.build-monitor #job-views li a,
+.build-monitor #job-views li a:visited,
+.build-monitor header>h1>a{
+ color:white;
+}
+.build-monitor a:hover {
+ text-decoration: underline;
+}
+
+.build-monitor header h1 {
+ margin:12px auto 0 auto;
+ font-size: 3em;
+ letter-spacing: 0.0em;
+ display:block;
+}
+
+.build-monitor header a.home-link {
+ position: absolute;
+ top: 5px;
+ left: 8px;
+ z-index:2;
+ background: url('industrial/v-96x96.png') no-repeat;
+ background-size: 100%;
+ width: 50px; /* 100 */
+ height: 69px; /* 138 */
+ text-indent: -100%;
+ text-decoration: none;
+ white-space: nowrap;
+ overflow: hidden;
+}
+
+.build-monitor header .oncall {
+ position: absolute;
+ top: 8px;
+ left: 8px;
+ z-index:2;
+ background: url('industrial/police.png') no-repeat;
+ width: 600px;
+ height: 50px;
+ white-space: nowrap;
+ overflow: hidden;
+ line-height: 50px;
+ text-decoration: none;
+ font-size: 24px;
+ padding-left: 52px;
+ color: #ccc;
+}
+
+.build-monitor h2 {
+ font-weight: normal;
+ font-size: 3.5em;
+ margin-bottom: 0.1em;
+}
+
+.build-monitor p {
+ font-size: 1.2em;
+ margin: 0 0 0.5em 0;
+}
+
+.build-monitor .unknown { background-color:#474747; }
+.build-monitor .successful { background-color:darkgreen; }
+.build-monitor .unstable { background-color:#f59400; }
+.build-monitor .failing { background-color:darkred; }
+
+/*
+ * Striped background patterns inspired by Lea Verou
+ * http://lea.verou.me/2010/12/checkered-stripes-other-background-patterns-with-css3-gradients/
+ */
+.build-monitor .successful,
+.build-monitor .unstable,
+.build-monitor .failing {
+ -webkit-background-size: 50px 50px;
+ -moz-background-size: 50px 50px;
+ background-size: 50px 50px; /* Controls the size of the stripes */
+}
+
+
+.build-monitor .colour-blind-mode .unstable {
+ /* diamonds */
+ background-image: -webkit-gradient(linear, 0 0, 100% 100%, color-stop(.25, rgba(255, 255, 255, .2)), color-stop(.25, transparent), to(transparent)),
+ -webkit-gradient(linear, 0 100%, 100% 0, color-stop(.25, rgba(255, 255, 255, .2)), color-stop(.25, transparent), to(transparent)),
+ -webkit-gradient(linear, 0 0, 100% 100%, color-stop(.75, transparent), color-stop(.75, rgba(255, 255, 255, .2))),
+ -webkit-gradient(linear, 0 100%, 100% 0, color-stop(.75, transparent), color-stop(.75, rgba(255, 255, 255, .2)));
+ background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent),
+ -webkit-linear-gradient(-45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent),
+ -webkit-linear-gradient(45deg, transparent 75%, rgba(255, 255, 255, .2) 75%),
+ -webkit-linear-gradient(-45deg, transparent 75%, rgba(255, 255, 255, .2) 75%);
+ background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent),
+ -moz-linear-gradient(-45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent),
+ -moz-linear-gradient(45deg, transparent 75%, rgba(255, 255, 255, .2) 75%),
+ -moz-linear-gradient(-45deg, transparent 75%, rgba(255, 255, 255, .2) 75%);
+ background-image: -ms-linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent),
+ -ms-linear-gradient(-45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent),
+ -ms-linear-gradient(45deg, transparent 75%, rgba(255, 255, 255, .2) 75%),
+ -ms-linear-gradient(-45deg, transparent 75%, rgba(255, 255, 255, .2) 75%);
+ background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent),
+ -o-linear-gradient(-45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent),
+ -o-linear-gradient(45deg, transparent 75%, rgba(255, 255, 255, .2) 75%),
+ -o-linear-gradient(-45deg, transparent 75%, rgba(255, 255, 255, .2) 75%);
+ background-image: linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent),
+ linear-gradient(-45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent),
+ linear-gradient(45deg, transparent 75%, rgba(255, 255, 255, .2) 75%),
+ linear-gradient(-45deg, transparent 75%, rgba(255, 255, 255, .2) 75%);
+}
+
+.build-monitor .colour-blind-mode .failing {
+ background-image: -webkit-gradient(linear, 0 100%, 100% 0,
+ color-stop(.25, rgba(255, 255, 255, .2)), color-stop(.25, transparent),
+ color-stop(.5, transparent), color-stop(.5, rgba(255, 255, 255, .2)),
+ color-stop(.75, rgba(255, 255, 255, .2)), color-stop(.75, transparent),
+ to(transparent));
+ background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%,
+ transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%,
+ transparent 75%, transparent);
+ background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%,
+ transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%,
+ transparent 75%, transparent);
+ background-image: -ms-linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%,
+ transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%,
+ transparent 75%, transparent);
+ background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%,
+ transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%,
+ transparent 75%, transparent);
+ background-image: linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%,
+ transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%,
+ transparent 75%, transparent);
+}
+
+.build-monitor .unstable.claimed,
+.build-monitor .failing.claimed {
+ background-image: -webkit-gradient(linear, 0 0, 100% 100%,
+ color-stop(.25, rgba(255, 255, 255, .2)), color-stop(.25, transparent),
+ color-stop(.5, transparent), color-stop(.5, rgba(255, 255, 255, .2)),
+ color-stop(.75, rgba(255, 255, 255, .2)), color-stop(.75, transparent),
+ to(transparent));
+ background-image: -webkit-linear-gradient(-45deg, rgba(255, 255, 255, .2) 25%, transparent 25%,
+ transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%,
+ transparent 75%, transparent);
+ background-image: -moz-linear-gradient(-45deg, rgba(255, 255, 255, .2) 25%, transparent 25%,
+ transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%,
+ transparent 75%, transparent);
+ background-image: -ms-linear-gradient(-45deg, rgba(255, 255, 255, .2) 25%, transparent 25%,
+ transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%,
+ transparent 75%, transparent);
+ background-image: -o-linear-gradient(-45deg, rgba(255, 255, 255, .2) 25%, transparent 25%,
+ transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%,
+ transparent 75%, transparent);
+ background-image: linear-gradient(-45deg, rgba(255, 255, 255, .2) 25%, transparent 25%,
+ transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%,
+ transparent 75%, transparent);
+}
+
+
+.build-monitor #job-views .build-time,
+.build-monitor #job-views .build-name {
+ font-weight: bold;
+ color:rgba(255,255,255, 0.3);
+}
+.build-monitor #job-views .running .build-time,
+.build-monitor #job-views .running .build-name {
+ font-weight: bold;
+ color:rgba(255,255,255, 0.5);
+}
+.build-monitor #job-views .build-name { font-size: 2em; line-height: 1.75em; }
+.build-monitor #job-views .build-time { font-size: 2em; line-height: 1.75em; }
+.build-monitor #job-views .build-time>.elapsed { font-size: 1.0em; color:rgba(255,255,255,0.7); }
+.build-monitor #job-views .build-time>.elapsed:after { content:"|"; margin-left:0.1em; font-weight: normal; }
+
+.build-monitor footer {
+ padding: 0 8px;
+ color: #ddd;
+ clear: both;
+}
+
+.build-monitor footer span {
+ line-height: 150%;
+}
+
+.build-monitor footer .notifier {
+ float: left;
+ background: #ffcf85;
+ padding:0 10px;
+ border-radius: 10px;
+ color:#393939;
+}
+
+.build-monitor footer .plugin-author {
+ float: right;
+ font-size: 14px;
+ color: #aaa;
+}
+
+.build-monitor footer .build-cop {
+ font-size: 14px;
+ color: #aaa;
+}
+
+
+.build-monitor .latest-results ul,
+.build-monitor .latest-results ol {
+ list-style-type: none;
+ margin: 0 0 0.25em 1em; padding: 0;
+ font-size: 1.3em;
+}
+
+.build-monitor .meta li { display: inline-block; }
+.build-monitor .meta .culprits li { padding-right:0; margin-right:0.5em; }
+.build-monitor .meta .culprits li:after { content: ","; }
+.build-monitor .meta .culprits li:last-child:after { content: ""; }
+
+.build-monitor ul.culprits li:first-child:before {
+ content: "Possible Culprits: ";
+}
+
+.build-monitor .meta .failures li { margin-right:0.5em; }
+.build-monitor .meta .failures li:after { content: ","; }
+.build-monitor .meta .failures li:last-child:after { content: ""; }
+
+.build-monitor .failing ul.failures li:first-child:before {
+ content: "Identified Problems: ";
+}
+
+
+/*
+ * Layout
+ */
+.no-flexbox .build-monitor.dashboard * {
+ display:none;
+}
+
+.dashboard { background: url('industrial/background.png'); }
+
+.build-monitor.dashboard {
+ overflow: hidden;
+ position: fixed; left:0px; top:0px;
+ z-index: 9999;
+ height: 100%;
+ width: 100%;
+ margin:0; padding: 0;
+
+ display: -webkit-flex;
+ display: flex;
+ flex-flow: column;
+ -webkit-flex-flow: column;
+ -webkit-justify-content: space-around;
+ justify-content: space-around;
+}
+
+.build-monitor header {
+ /*-webkit-flex: 8;*/
+ /*flex: 8;*/
+
+ /*min-height:4em;*/
+ /*max-height:4em;*/
+ height:56px;
+
+ display: -webkit-flex;
+ display: flex;
+
+ align-items: center;
+ align-content: center;
+}
+
+.build-monitor #job-views {
+ -webkit-flex: 88;
+ flex: 88;
+
+ display: -webkit-flex;
+ display: flex;
+ -webkit-flex-flow: row wrap;
+ flex-flow: row wrap;
+ -webkit-justify-content: space-around;
+ justify-content: space-around;
+}
+
+.build-monitor #job-views.empty em {
+ padding:5em 0 0 0;
+}
+
+.build-monitor footer {
+ height:32px;
+}
+
+.build-monitor ul#job-views {
+ list-style-type: none;
+ margin: 4px;
+ padding:0;
+}
+
+/*
+ * Grid
+ */
+.build-monitor ul#job-views>li {
+ margin: 4px;
+}
+.build-monitor ul#job-views.columns-1 li {
+ -webkit-flex: 1 99%;
+ flex: 1 99%;
+}
+.build-monitor ul#job-views.columns-2 li {
+ -webkit-flex: 1 48%;
+ flex: 1 48%;
+}
+.build-monitor ul#job-views.columns-3 li {
+ -webkit-flex: 1 32%;
+ flex: 1 32%;
+}
+.build-monitor ul#job-views.columns-4 li {
+ -webkit-flex: 1 24%;
+ flex: 1 24%;
+}
+.build-monitor ul#job-views.columns-5 li {
+ -webkit-flex: 1 19%;
+ flex: 1 19%;
+}
+.build-monitor ul#job-views.columns-6 li {
+ -webkit-flex: 1 15.5%;
+ flex: 1 15.5%;
+}
+.build-monitor ul#job-views.columns-7 li {
+ -webkit-flex: 1 13%;
+ flex: 1 13%;
+}
+.build-monitor ul#job-views.columns-8 li {
+ -webkit-flex: 1 11.5%;
+ flex: 1 11.5%;
+}
+
+.build-monitor ul#job-views .meta {
+ display: -webkit-flex;
+ display: flex;
+ -webkit-justify-content: space-around;
+ justify-content: space-around;
+ align-content: center;
+ align-items:center;
+}
+
+.build-monitor ul#job-views .meta .latest-results {
+ width:90%; margin:0 auto;
+}
+.build-monitor ul#job-views .meta .latest-results * {
+ text-align: center;
+}
+
+.build-monitor ul#job-views .meta ul,
+.build-monitor ul#job-views .meta ol {
+ margin:0;
+ overflow: hidden;
+}
+.build-monitor ul#job-views .meta ul li,
+.build-monitor ul#job-views .meta ol li {
+ border-radius: 0;
+}
+
+.build-monitor #job-views .build-time,
+.build-monitor #job-views .build-name {
+ display:block;
+ position:absolute;
+}
+.build-monitor #job-views .build-time {
+ vertical-align: middle;
+}
+.build-monitor #job-views .build-name { bottom:0; left:0.3em; }
+.build-monitor #job-views .build-time { bottom:0; right:0.3em; }
+
+/*
+ * Job meta-data
+ */
+
+.build-monitor ul#job-views li .meta {
+ z-index: 10;
+ position:absolute; left:0; top:0;
+ width:100%; height:100%;
+}
+
+/*
+ * Progress bar
+ */
+
+.build-monitor ul#job-views>li {
+ position:relative;
+ border-radius:10px;
+ overflow: hidden;
+ -webkit-box-shadow: 2px 2px 1px rgba(0,0,0,0.5);
+ box-shadow: 2px 2px 1px rgba(0,0,0,0.5);
+}
+
+.build-monitor ul#job-views .progress {
+ z-index: 0;
+ position:absolute; left:0; top:0;
+ width:0%; height:100%;
+ text-align: right;
+ overflow: hidden;
+ border-radius:10px;
+}
+.build-monitor ul#job-views .progress span {
+ display:none;
+}
+
+.build-monitor ul#job-views .unknown > .progress {
+ -webkit-animation: forUnknown 2.25s 2 alternate;
+ -moz-animation: forUnknown 2.25s 2 alternate;
+ animation: forUnknown 2.25s 2 alternate;
+ background-color: #9D9D9D;
+}
+
+.build-monitor ul#job-views .successful > .progress {
+ -webkit-animation: forSuccessful 2.25s 2 alternate;
+ -moz-animation: forSuccessful 2.25s 2 alternate;
+ animation: forSuccessful 2.25s 2 alternate;
+ background-color: green;
+}
+
+.build-monitor ul#job-views .unstable > .progress {
+ -webkit-animation: forUnstable 2.25s 2 alternate;
+ -moz-animation: forUnstable 2.25s 2 alternate;
+ animation: forUnstable 2.25s 2 alternate;
+ background-color: #f9aa1c;
+}
+
+.build-monitor ul#job-views .failing > .progress {
+ -webkit-animation: forFailing 2.25s 2 alternate;
+ -moz-animation: forFailing 2.25s 2 alternate;
+ animation: forFailing 2.25s 2 alternate;
+ background-color: firebrick;
+}
+
+@-webkit-keyframes forUnknown { 0% {background-color: #9d9d9d;} 100% {background-color: grey;} }
+@-moz-keyframes forUnknown { 0% {background-color: #9d9d9d;} 100% {background-color: grey;} }
+@-keyframes forUnknown { 0% {background-color: #9d9d9d;} 100% {background-color: grey;} }
+@-webkit-keyframes forSuccessful { 0% {background-color: green;} 100% {background-color: limegreen;} }
+@-moz-keyframes forSuccessful { 0% {background-color: green;} 100% {background-color: limegreen;} }
+@-keyframes forSuccessful { 0% {background-color: green;} 100% {background-color: limegreen;} }
+@-webkit-keyframes forUnstable { 0% {background-color: #f9aa1c;} 100% {background-color: #ffc500;} }
+@-moz-keyframes forUnstable { 0% {background-color: #f9aa1c;} 100% {background-color: #ffc500;} }
+@-keyframes forUnstable { 0% {background-color: #f9aa1c;} 100% {background-color: #ffc500;} }
+@-webkit-keyframes forFailing { 0% {background-color: firebrick;} 100% {background-color: red;} }
+@-moz-keyframes forFailing { 0% {background-color: firebrick;} 100% {background-color: red;} }
+@-keyframes forFailing { 0% {background-color: firebrick;} 100% {background-color: red;} }
+
+/*
+ * Modal
+ */
+.modal {
+ width: 60%;
+ margin-left: -30%;
+ color: #000;
+ background: #fff;
+}
+.modal-header h1 {
+ text-align: left;
+ font-size:2.5em;
+}
+.modal-body p {
+ font-size:1.2em;
+}
+
+.modal textarea {
+ font-family: "Consolas", "Menlo", "Courier", monospace;
+ width: 100%;
+}
+
+
+/*
+ * Config nav
+ */
+
+.build-monitor nav {
+ border:1px solid white;
+ z-index: 999;
+ position:absolute;
+ top:10px;
+ right:8px;
+ width:32px;
+ overflow: hidden;
+ margin: 0; padding: 5px;
+ background: rgba(57, 57, 57, 0.9);
+ border-radius: 5px;
+ opacity:0.5;
+
+ -webkit-transition: all 0.25 ease-in;
+ transition: all 0.25s ease-in;
+ min-width: 48px;
+}
+.build-monitor nav:hover {
+ opacity:1.0;
+}
+.build-monitor .showSettings {
+ opacity: 1.0;
+ width:200px !important;
+}
+.build-monitor nav.showSettings ul {
+ height:auto;
+}
+
+.build-monitor nav ul {
+ height:0;
+ width:200px !important;
+ overflow: hidden;
+
+ list-style-type: none;
+ margin:0; padding:0;
+}
+.build-monitor nav li {
+ display: block;
+ margin:0 0.5em;
+ border-radius: 5px;
+}
+
+.build-monitor nav label {
+ width:100%;
+}
+.build-monitor nav li:nth-child(1),
+.build-monitor nav li:nth-child(6) {
+ margin-top:2em;
+}
+.build-monitor nav li:last-child {
+ padding:1em 0 1em 0;
+}
+
+.build-monitor nav li .slider-label {
+ width:100px;
+ margin-right:10px;
+}
+
+.build-monitor nav li a.btn {
+ width: 86%;
+ color: #000 !important;
+ text-decoration: none;
+}
+.build-monitor nav li button.btn {
+ width: 100%;
+}
+
+/*
+ * Angular slider
+ */
+slider {
+ width: 180px;
+}
+
+/*
+ * Inspired by WittySparks - (c) Sravan Kumar, WittySparks.com
+ */
+.build-monitor nav input[type='checkbox']#settings-toggle{opacity:0;position:absolute;filter:alpha(opacity=0);margin:5px 0 0 5px}
+.build-monitor nav input[type='checkbox']#settings-toggle+label {
+ background:url("industrial/glyphs.png") left top no-repeat;
+ background-size:32px 32px;
+ position:relative;
+ margin:0; padding:0 0 0 40px;
+ cursor:pointer;
+ line-height:32px;
+ min-height:32px;
+ display:inline-block;
+ z-index:0;
+ font-weight:bold;
+}
+
+.build-monitor nav input[type='checkbox']#settings-toggle+label { background-position:0 0}
+.build-monitor nav input[type='checkbox']#settings-toggle:checked+label { }
+.build-monitor nav input[type='checkbox']#settings-toggle:disabled+label { }
+.build-monitor nav input[type='checkbox']#settings-toggle:disabled:checked+label{ }
+
+.build-monitor nav label { font-size: 1em; }
+.build-monitor nav li input[type='checkbox'] { margin-right:0.5em; }
+
+
+/*
+ * Animations
+ */
+.fade-hide, .fade-show {
+ -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.75s;
+ -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.75s;
+ -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.75s;
+ transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.75s;
+}
+
+.fade-hide { opacity:1; }
+.fade-hide.fade-hide-active { opacity:0; }
+
+.fade-show { opacity:0; }
+.fade-show.fade-show-active { opacity:1; }
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/background.png b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/background.png
new file mode 100644
index 0000000..afe3d84
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/background.png
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/glyphs.png b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/glyphs.png
new file mode 100644
index 0000000..caaded3
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/glyphs.png
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/jenkins-logo.png b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/jenkins-logo.png
new file mode 100644
index 0000000..c0641d1
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/jenkins-logo.png
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/open-sans-bold.woff b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/open-sans-bold.woff
new file mode 100644
index 0000000..a8b5bc2
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/open-sans-bold.woff
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/open-sans-normal.woff b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/open-sans-normal.woff
new file mode 100644
index 0000000..58e6cb3
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/open-sans-normal.woff
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/police.png b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/police.png
new file mode 100644
index 0000000..ac9f723
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/police.png
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/v-96x96.png b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/v-96x96.png
new file mode 100644
index 0000000..fb6bbb7
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/themes/industrial/v-96x96.png
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/angular-1.1.5.js b/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/angular-1.1.5.js
new file mode 100644
index 0000000..5a732aa
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/angular-1.1.5.js
@@ -0,0 +1,16876 @@
+/**
+ * @license AngularJS v1.1.5
+ * (c) 2010-2012 Google, Inc. http://angularjs.org
+ * License: MIT
+ */
+(function(window, document, undefined) {
+'use strict';
+
+////////////////////////////////////
+
+/**
+ * @ngdoc function
+ * @name angular.lowercase
+ * @function
+ *
+ * @description Converts the specified string to lowercase.
+ * @param {string} string String to be converted to lowercase.
+ * @returns {string} Lowercased string.
+ */
+var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
+
+
+/**
+ * @ngdoc function
+ * @name angular.uppercase
+ * @function
+ *
+ * @description Converts the specified string to uppercase.
+ * @param {string} string String to be converted to uppercase.
+ * @returns {string} Uppercased string.
+ */
+var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
+
+
+var manualLowercase = function(s) {
+ return isString(s)
+ ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
+ : s;
+};
+var manualUppercase = function(s) {
+ return isString(s)
+ ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
+ : s;
+};
+
+
+// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
+// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
+// with correct but slower alternatives.
+if ('i' !== 'I'.toLowerCase()) {
+ lowercase = manualLowercase;
+ uppercase = manualUppercase;
+}
+
+
+var /** holds major version number for IE or NaN for real browsers */
+ msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]),
+ jqLite, // delay binding since jQuery could be loaded after us.
+ jQuery, // delay binding
+ slice = [].slice,
+ push = [].push,
+ toString = Object.prototype.toString,
+
+
+ _angular = window.angular,
+ /** @name angular */
+ angular = window.angular || (window.angular = {}),
+ angularModule,
+ nodeName_,
+ uid = ['0', '0', '0'];
+
+/**
+ * @ngdoc function
+ * @name angular.noConflict
+ * @function
+ *
+ * @description
+ * Restores the previous global value of angular and returns the current instance. Other libraries may already use the
+ * angular namespace. Or a previous version of angular is already loaded on the page. In these cases you may want to
+ * restore the previous namespace and keep a reference to angular.
+ *
+ * @return {Object} The current angular namespace
+ */
+function noConflict() {
+ var a = window.angular;
+ window.angular = _angular;
+ return a;
+}
+
+/**
+ * @private
+ * @param {*} obj
+ * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, ...)
+ */
+function isArrayLike(obj) {
+ if (!obj || (typeof obj.length !== 'number')) return false;
+
+ // We have on object which has length property. Should we treat it as array?
+ if (typeof obj.hasOwnProperty != 'function' &&
+ typeof obj.constructor != 'function') {
+ // This is here for IE8: it is a bogus object treat it as array;
+ return true;
+ } else {
+ return obj instanceof JQLite || // JQLite
+ (jQuery && obj instanceof jQuery) || // jQuery
+ toString.call(obj) !== '[object Object]' || // some browser native object
+ typeof obj.callee === 'function'; // arguments (on IE8 looks like regular obj)
+ }
+}
+
+/**
+ * @ngdoc function
+ * @name angular.forEach
+ * @function
+ *
+ * @description
+ * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
+ * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
+ * is the value of an object property or an array element and `key` is the object property key or
+ * array element index. Specifying a `context` for the function is optional.
+ *
+ * Note: this function was previously known as `angular.foreach`.
+ *
+ <pre>
+ var values = {name: 'misko', gender: 'male'};
+ var log = [];
+ angular.forEach(values, function(value, key){
+ this.push(key + ': ' + value);
+ }, log);
+ expect(log).toEqual(['name: misko', 'gender:male']);
+ </pre>
+ *
+ * @param {Object|Array} obj Object to iterate over.
+ * @param {Function} iterator Iterator function.
+ * @param {Object=} context Object to become context (`this`) for the iterator function.
+ * @returns {Object|Array} Reference to `obj`.
+ */
+function forEach(obj, iterator, context) {
+ var key;
+ if (obj) {
+ if (isFunction(obj)){
+ for (key in obj) {
+ if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) {
+ iterator.call(context, obj[key], key);
+ }
+ }
+ } else if (obj.forEach && obj.forEach !== forEach) {
+ obj.forEach(iterator, context);
+ } else if (isArrayLike(obj)) {
+ for (key = 0; key < obj.length; key++)
+ iterator.call(context, obj[key], key);
+ } else {
+ for (key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ iterator.call(context, obj[key], key);
+ }
+ }
+ }
+ }
+ return obj;
+}
+
+function sortedKeys(obj) {
+ var keys = [];
+ for (var key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ keys.push(key);
+ }
+ }
+ return keys.sort();
+}
+
+function forEachSorted(obj, iterator, context) {
+ var keys = sortedKeys(obj);
+ for ( var i = 0; i < keys.length; i++) {
+ iterator.call(context, obj[keys[i]], keys[i]);
+ }
+ return keys;
+}
+
+
+/**
+ * when using forEach the params are value, key, but it is often useful to have key, value.
+ * @param {function(string, *)} iteratorFn
+ * @returns {function(*, string)}
+ */
+function reverseParams(iteratorFn) {
+ return function(value, key) { iteratorFn(key, value) };
+}
+
+/**
+ * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
+ * characters such as '012ABC'. The reason why we are not using simply a number counter is that
+ * the number string gets longer over time, and it can also overflow, where as the nextId
+ * will grow much slower, it is a string, and it will never overflow.
+ *
+ * @returns an unique alpha-numeric string
+ */
+function nextUid() {
+ var index = uid.length;
+ var digit;
+
+ while(index) {
+ index--;
+ digit = uid[index].charCodeAt(0);
+ if (digit == 57 /*'9'*/) {
+ uid[index] = 'A';
+ return uid.join('');
+ }
+ if (digit == 90 /*'Z'*/) {
+ uid[index] = '0';
+ } else {
+ uid[index] = String.fromCharCode(digit + 1);
+ return uid.join('');
+ }
+ }
+ uid.unshift('0');
+ return uid.join('');
+}
+
+
+/**
+ * Set or clear the hashkey for an object.
+ * @param obj object
+ * @param h the hashkey (!truthy to delete the hashkey)
+ */
+function setHashKey(obj, h) {
+ if (h) {
+ obj.$$hashKey = h;
+ }
+ else {
+ delete obj.$$hashKey;
+ }
+}
+
+/**
+ * @ngdoc function
+ * @name angular.extend
+ * @function
+ *
+ * @description
+ * Extends the destination object `dst` by copying all of the properties from the `src` object(s)
+ * to `dst`. You can specify multiple `src` objects.
+ *
+ * @param {Object} dst Destination object.
+ * @param {...Object} src Source object(s).
+ * @returns {Object} Reference to `dst`.
+ */
+function extend(dst) {
+ var h = dst.$$hashKey;
+ forEach(arguments, function(obj){
+ if (obj !== dst) {
+ forEach(obj, function(value, key){
+ dst[key] = value;
+ });
+ }
+ });
+
+ setHashKey(dst,h);
+ return dst;
+}
+
+function int(str) {
+ return parseInt(str, 10);
+}
+
+
+function inherit(parent, extra) {
+ return extend(new (extend(function() {}, {prototype:parent}))(), extra);
+}
+
+var START_SPACE = /^\s*/;
+var END_SPACE = /\s*$/;
+function stripWhitespace(str) {
+ return isString(str) ? str.replace(START_SPACE, '').replace(END_SPACE, '') : str;
+}
+
+/**
+ * @ngdoc function
+ * @name angular.noop
+ * @function
+ *
+ * @description
+ * A function that performs no operations. This function can be useful when writing code in the
+ * functional style.
+ <pre>
+ function foo(callback) {
+ var result = calculateResult();
+ (callback || angular.noop)(result);
+ }
+ </pre>
+ */
+function noop() {}
+noop.$inject = [];
+
+
+/**
+ * @ngdoc function
+ * @name angular.identity
+ * @function
+ *
+ * @description
+ * A function that returns its first argument. This function is useful when writing code in the
+ * functional style.
+ *
+ <pre>
+ function transformer(transformationFn, value) {
+ return (transformationFn || identity)(value);
+ };
+ </pre>
+ */
+function identity($) {return $;}
+identity.$inject = [];
+
+
+function valueFn(value) {return function() {return value;};}
+
+/**
+ * @ngdoc function
+ * @name angular.isUndefined
+ * @function
+ *
+ * @description
+ * Determines if a reference is undefined.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is undefined.
+ */
+function isUndefined(value){return typeof value == 'undefined';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isDefined
+ * @function
+ *
+ * @description
+ * Determines if a reference is defined.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is defined.
+ */
+function isDefined(value){return typeof value != 'undefined';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isObject
+ * @function
+ *
+ * @description
+ * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
+ * considered to be objects.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is an `Object` but not `null`.
+ */
+function isObject(value){return value != null && typeof value == 'object';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isString
+ * @function
+ *
+ * @description
+ * Determines if a reference is a `String`.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `String`.
+ */
+function isString(value){return typeof value == 'string';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isNumber
+ * @function
+ *
+ * @description
+ * Determines if a reference is a `Number`.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `Number`.
+ */
+function isNumber(value){return typeof value == 'number';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isDate
+ * @function
+ *
+ * @description
+ * Determines if a value is a date.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `Date`.
+ */
+function isDate(value){
+ return toString.apply(value) == '[object Date]';
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isArray
+ * @function
+ *
+ * @description
+ * Determines if a reference is an `Array`.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is an `Array`.
+ */
+function isArray(value) {
+ return toString.apply(value) == '[object Array]';
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isFunction
+ * @function
+ *
+ * @description
+ * Determines if a reference is a `Function`.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `Function`.
+ */
+function isFunction(value){return typeof value == 'function';}
+
+
+/**
+ * Checks if `obj` is a window object.
+ *
+ * @private
+ * @param {*} obj Object to check
+ * @returns {boolean} True if `obj` is a window obj.
+ */
+function isWindow(obj) {
+ return obj && obj.document && obj.location && obj.alert && obj.setInterval;
+}
+
+
+function isScope(obj) {
+ return obj && obj.$evalAsync && obj.$watch;
+}
+
+
+function isFile(obj) {
+ return toString.apply(obj) === '[object File]';
+}
+
+
+function isBoolean(value) {
+ return typeof value == 'boolean';
+}
+
+
+function trim(value) {
+ return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
+}
+
+/**
+ * @ngdoc function
+ * @name angular.isElement
+ * @function
+ *
+ * @description
+ * Determines if a reference is a DOM element (or wrapped jQuery element).
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
+ */
+function isElement(node) {
+ return node &&
+ (node.nodeName // we are a direct element
+ || (node.bind && node.find)); // we have a bind and find method part of jQuery API
+}
+
+/**
+ * @param str 'key1,key2,...'
+ * @returns {object} in the form of {key1:true, key2:true, ...}
+ */
+function makeMap(str){
+ var obj = {}, items = str.split(","), i;
+ for ( i = 0; i < items.length; i++ )
+ obj[ items[i] ] = true;
+ return obj;
+}
+
+
+if (msie < 9) {
+ nodeName_ = function(element) {
+ element = element.nodeName ? element : element[0];
+ return (element.scopeName && element.scopeName != 'HTML')
+ ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
+ };
+} else {
+ nodeName_ = function(element) {
+ return element.nodeName ? element.nodeName : element[0].nodeName;
+ };
+}
+
+
+function map(obj, iterator, context) {
+ var results = [];
+ forEach(obj, function(value, index, list) {
+ results.push(iterator.call(context, value, index, list));
+ });
+ return results;
+}
+
+
+/**
+ * @description
+ * Determines the number of elements in an array, the number of properties an object has, or
+ * the length of a string.
+ *
+ * Note: This function is used to augment the Object type in Angular expressions. See
+ * {@link angular.Object} for more information about Angular arrays.
+ *
+ * @param {Object|Array|string} obj Object, array, or string to inspect.
+ * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
+ * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
+ */
+function size(obj, ownPropsOnly) {
+ var size = 0, key;
+
+ if (isArray(obj) || isString(obj)) {
+ return obj.length;
+ } else if (isObject(obj)){
+ for (key in obj)
+ if (!ownPropsOnly || obj.hasOwnProperty(key))
+ size++;
+ }
+
+ return size;
+}
+
+
+function includes(array, obj) {
+ return indexOf(array, obj) != -1;
+}
+
+function indexOf(array, obj) {
+ if (array.indexOf) return array.indexOf(obj);
+
+ for ( var i = 0; i < array.length; i++) {
+ if (obj === array[i]) return i;
+ }
+ return -1;
+}
+
+function arrayRemove(array, value) {
+ var index = indexOf(array, value);
+ if (index >=0)
+ array.splice(index, 1);
+ return value;
+}
+
+function isLeafNode (node) {
+ if (node) {
+ switch (node.nodeName) {
+ case "OPTION":
+ case "PRE":
+ case "TITLE":
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * @ngdoc function
+ * @name angular.copy
+ * @function
+ *
+ * @description
+ * Creates a deep copy of `source`, which should be an object or an array.
+ *
+ * * If no destination is supplied, a copy of the object or array is created.
+ * * If a destination is provided, all of its elements (for array) or properties (for objects)
+ * are deleted and then all elements/properties from the source are copied to it.
+ * * If `source` is not an object or array, `source` is returned.
+ *
+ * Note: this function is used to augment the Object type in Angular expressions. See
+ * {@link ng.$filter} for more information about Angular arrays.
+ *
+ * @param {*} source The source that will be used to make a copy.
+ * Can be any type, including primitives, `null`, and `undefined`.
+ * @param {(Object|Array)=} destination Destination into which the source is copied. If
+ * provided, must be of the same type as `source`.
+ * @returns {*} The copy or updated `destination`, if `destination` was specified.
+ */
+function copy(source, destination){
+ if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope");
+ if (!destination) {
+ destination = source;
+ if (source) {
+ if (isArray(source)) {
+ destination = copy(source, []);
+ } else if (isDate(source)) {
+ destination = new Date(source.getTime());
+ } else if (isObject(source)) {
+ destination = copy(source, {});
+ }
+ }
+ } else {
+ if (source === destination) throw Error("Can't copy equivalent objects or arrays");
+ if (isArray(source)) {
+ destination.length = 0;
+ for ( var i = 0; i < source.length; i++) {
+ destination.push(copy(source[i]));
+ }
+ } else {
+ var h = destination.$$hashKey;
+ forEach(destination, function(value, key){
+ delete destination[key];
+ });
+ for ( var key in source) {
+ destination[key] = copy(source[key]);
+ }
+ setHashKey(destination,h);
+ }
+ }
+ return destination;
+}
+
+/**
+ * Create a shallow copy of an object
+ */
+function shallowCopy(src, dst) {
+ dst = dst || {};
+
+ for(var key in src) {
+ if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
+ dst[key] = src[key];
+ }
+ }
+
+ return dst;
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.equals
+ * @function
+ *
+ * @description
+ * Determines if two objects or two values are equivalent. Supports value types, arrays and
+ * objects.
+ *
+ * Two objects or values are considered equivalent if at least one of the following is true:
+ *
+ * * Both objects or values pass `===` comparison.
+ * * Both objects or values are of the same type and all of their properties pass `===` comparison.
+ * * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal)
+ *
+ * During a property comparison, properties of `function` type and properties with names
+ * that begin with `$` are ignored.
+ *
+ * Scope and DOMWindow objects are being compared only by identify (`===`).
+ *
+ * @param {*} o1 Object or value to compare.
+ * @param {*} o2 Object or value to compare.
+ * @returns {boolean} True if arguments are equal.
+ */
+function equals(o1, o2) {
+ if (o1 === o2) return true;
+ if (o1 === null || o2 === null) return false;
+ if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
+ var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
+ if (t1 == t2) {
+ if (t1 == 'object') {
+ if (isArray(o1)) {
+ if ((length = o1.length) == o2.length) {
+ for(key=0; key<length; key++) {
+ if (!equals(o1[key], o2[key])) return false;
+ }
+ return true;
+ }
+ } else if (isDate(o1)) {
+ return isDate(o2) && o1.getTime() == o2.getTime();
+ } else {
+ if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false;
+ keySet = {};
+ for(key in o1) {
+ if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
+ if (!equals(o1[key], o2[key])) return false;
+ keySet[key] = true;
+ }
+ for(key in o2) {
+ if (!keySet[key] &&
+ key.charAt(0) !== '$' &&
+ o2[key] !== undefined &&
+ !isFunction(o2[key])) return false;
+ }
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+
+function concat(array1, array2, index) {
+ return array1.concat(slice.call(array2, index));
+}
+
+function sliceArgs(args, startIndex) {
+ return slice.call(args, startIndex || 0);
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.bind
+ * @function
+ *
+ * @description
+ * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
+ * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
+ * known as [function currying](http://en.wikipedia.org/wiki/Currying).
+ *
+ * @param {Object} self Context which `fn` should be evaluated in.
+ * @param {function()} fn Function to be bound.
+ * @param {...*} args Optional arguments to be prebound to the `fn` function call.
+ * @returns {function()} Function that wraps the `fn` with all the specified bindings.
+ */
+function bind(self, fn) {
+ var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
+ if (isFunction(fn) && !(fn instanceof RegExp)) {
+ return curryArgs.length
+ ? function() {
+ return arguments.length
+ ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
+ : fn.apply(self, curryArgs);
+ }
+ : function() {
+ return arguments.length
+ ? fn.apply(self, arguments)
+ : fn.call(self);
+ };
+ } else {
+ // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
+ return fn;
+ }
+}
+
+
+function toJsonReplacer(key, value) {
+ var val = value;
+
+ if (/^\$+/.test(key)) {
+ val = undefined;
+ } else if (isWindow(value)) {
+ val = '$WINDOW';
+ } else if (value && document === value) {
+ val = '$DOCUMENT';
+ } else if (isScope(value)) {
+ val = '$SCOPE';
+ }
+
+ return val;
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.toJson
+ * @function
+ *
+ * @description
+ * Serializes input into a JSON-formatted string.
+ *
+ * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
+ * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
+ * @returns {string} Jsonified string representing `obj`.
+ */
+function toJson(obj, pretty) {
+ return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.fromJson
+ * @function
+ *
+ * @description
+ * Deserializes a JSON string.
+ *
+ * @param {string} json JSON string to deserialize.
+ * @returns {Object|Array|Date|string|number} Deserialized thingy.
+ */
+function fromJson(json) {
+ return isString(json)
+ ? JSON.parse(json)
+ : json;
+}
+
+
+function toBoolean(value) {
+ if (value && value.length !== 0) {
+ var v = lowercase("" + value);
+ value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
+ } else {
+ value = false;
+ }
+ return value;
+}
+
+/**
+ * @returns {string} Returns the string representation of the element.
+ */
+function startingTag(element) {
+ element = jqLite(element).clone();
+ try {
+ // turns out IE does not let you set .html() on elements which
+ // are not allowed to have children. So we just ignore it.
+ element.html('');
+ } catch(e) {}
+ // As Per DOM Standards
+ var TEXT_NODE = 3;
+ var elemHtml = jqLite('<div>').append(element).html();
+ try {
+ return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) :
+ elemHtml.
+ match(/^(<[^>]+>)/)[1].
+ replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
+ } catch(e) {
+ return lowercase(elemHtml);
+ }
+
+}
+
+
+/////////////////////////////////////////////////
+
+/**
+ * Parses an escaped url query string into key-value pairs.
+ * @returns Object.<(string|boolean)>
+ */
+function parseKeyValue(/**string*/keyValue) {
+ var obj = {}, key_value, key;
+ forEach((keyValue || "").split('&'), function(keyValue){
+ if (keyValue) {
+ key_value = keyValue.split('=');
+ key = decodeURIComponent(key_value[0]);
+ obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true;
+ }
+ });
+ return obj;
+}
+
+function toKeyValue(obj) {
+ var parts = [];
+ forEach(obj, function(value, key) {
+ parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true)));
+ });
+ return parts.length ? parts.join('&') : '';
+}
+
+
+/**
+ * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
+ * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
+ * segments:
+ * segment = *pchar
+ * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
+ * pct-encoded = "%" HEXDIG HEXDIG
+ * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
+ * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
+ * / "*" / "+" / "," / ";" / "="
+ */
+function encodeUriSegment(val) {
+ return encodeUriQuery(val, true).
+ replace(/%26/gi, '&').
+ replace(/%3D/gi, '=').
+ replace(/%2B/gi, '+');
+}
+
+
+/**
+ * This method is intended for encoding *key* or *value* parts of query component. We need a custom
+ * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
+ * encoded per http://tools.ietf.org/html/rfc3986:
+ * query = *( pchar / "/" / "?" )
+ * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
+ * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
+ * pct-encoded = "%" HEXDIG HEXDIG
+ * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
+ * / "*" / "+" / "," / ";" / "="
+ */
+function encodeUriQuery(val, pctEncodeSpaces) {
+ return encodeURIComponent(val).
+ replace(/%40/gi, '@').
+ replace(/%3A/gi, ':').
+ replace(/%24/g, '$').
+ replace(/%2C/gi, ',').
+ replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
+}
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngApp
+ *
+ * @element ANY
+ * @param {angular.Module} ngApp an optional application
+ * {@link angular.module module} name to load.
+ *
+ * @description
+ *
+ * Use this directive to auto-bootstrap an application. Only
+ * one directive can be used per HTML document. The directive
+ * designates the root of the application and is typically placed
+ * at the root of the page.
+ *
+ * In the example below if the `ngApp` directive would not be placed
+ * on the `html` element then the document would not be compiled
+ * and the `{{ 1+2 }}` would not be resolved to `3`.
+ *
+ * `ngApp` is the easiest way to bootstrap an application.
+ *
+ <doc:example>
+ <doc:source>
+ I can add: 1 + 2 = {{ 1+2 }}
+ </doc:source>
+ </doc:example>
+ *
+ */
+function angularInit(element, bootstrap) {
+ var elements = [element],
+ appElement,
+ module,
+ names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
+ NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
+
+ function append(element) {
+ element && elements.push(element);
+ }
+
+ forEach(names, function(name) {
+ names[name] = true;
+ append(document.getElementById(name));
+ name = name.replace(':', '\\:');
+ if (element.querySelectorAll) {
+ forEach(element.querySelectorAll('.' + name), append);
+ forEach(element.querySelectorAll('.' + name + '\\:'), append);
+ forEach(element.querySelectorAll('[' + name + ']'), append);
+ }
+ });
+
+ forEach(elements, function(element) {
+ if (!appElement) {
+ var className = ' ' + element.className + ' ';
+ var match = NG_APP_CLASS_REGEXP.exec(className);
+ if (match) {
+ appElement = element;
+ module = (match[2] || '').replace(/\s+/g, ',');
+ } else {
+ forEach(element.attributes, function(attr) {
+ if (!appElement && names[attr.name]) {
+ appElement = element;
+ module = attr.value;
+ }
+ });
+ }
+ }
+ });
+ if (appElement) {
+ bootstrap(appElement, module ? [module] : []);
+ }
+}
+
+/**
+ * @ngdoc function
+ * @name angular.bootstrap
+ * @description
+ * Use this function to manually start up angular application.
+ *
+ * See: {@link guide/bootstrap Bootstrap}
+ *
+ * @param {Element} element DOM element which is the root of angular application.
+ * @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules}
+ * @returns {AUTO.$injector} Returns the newly created injector for this app.
+ */
+function bootstrap(element, modules) {
+ var resumeBootstrapInternal = function() {
+ element = jqLite(element);
+ modules = modules || [];
+ modules.unshift(['$provide', function($provide) {
+ $provide.value('$rootElement', element);
+ }]);
+ modules.unshift('ng');
+ var injector = createInjector(modules);
+ injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animator',
+ function(scope, element, compile, injector, animator) {
+ scope.$apply(function() {
+ element.data('$injector', injector);
+ compile(element)(scope);
+ });
+ animator.enabled(true);
+ }]
+ );
+ return injector;
+ };
+
+ var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
+
+ if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
+ return resumeBootstrapInternal();
+ }
+
+ window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
+ angular.resumeBootstrap = function(extraModules) {
+ forEach(extraModules, function(module) {
+ modules.push(module);
+ });
+ resumeBootstrapInternal();
+ };
+}
+
+var SNAKE_CASE_REGEXP = /[A-Z]/g;
+function snake_case(name, separator){
+ separator = separator || '_';
+ return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
+ return (pos ? separator : '') + letter.toLowerCase();
+ });
+}
+
+function bindJQuery() {
+ // bind to jQuery if present;
+ jQuery = window.jQuery;
+ // reset to jQuery or default to us.
+ if (jQuery) {
+ jqLite = jQuery;
+ extend(jQuery.fn, {
+ scope: JQLitePrototype.scope,
+ controller: JQLitePrototype.controller,
+ injector: JQLitePrototype.injector,
+ inheritedData: JQLitePrototype.inheritedData
+ });
+ JQLitePatchJQueryRemove('remove', true);
+ JQLitePatchJQueryRemove('empty');
+ JQLitePatchJQueryRemove('html');
+ } else {
+ jqLite = JQLite;
+ }
+ angular.element = jqLite;
+}
+
+/**
+ * throw error if the argument is falsy.
+ */
+function assertArg(arg, name, reason) {
+ if (!arg) {
+ throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required"));
+ }
+ return arg;
+}
+
+function assertArgFn(arg, name, acceptArrayAnnotation) {
+ if (acceptArrayAnnotation && isArray(arg)) {
+ arg = arg[arg.length - 1];
+ }
+
+ assertArg(isFunction(arg), name, 'not a function, got ' +
+ (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
+ return arg;
+}
+
+/**
+ * @ngdoc interface
+ * @name angular.Module
+ * @description
+ *
+ * Interface for configuring angular {@link angular.module modules}.
+ */
+
+function setupModuleLoader(window) {
+
+ function ensure(obj, name, factory) {
+ return obj[name] || (obj[name] = factory());
+ }
+
+ return ensure(ensure(window, 'angular', Object), 'module', function() {
+ /** @type {Object.<string, angular.Module>} */
+ var modules = {};
+
+ /**
+ * @ngdoc function
+ * @name angular.module
+ * @description
+ *
+ * The `angular.module` is a global place for creating and registering Angular modules. All
+ * modules (angular core or 3rd party) that should be available to an application must be
+ * registered using this mechanism.
+ *
+ *
+ * # Module
+ *
+ * A module is a collocation of services, directives, filters, and configuration information. Module
+ * is used to configure the {@link AUTO.$injector $injector}.
+ *
+ * <pre>
+ * // Create a new module
+ * var myModule = angular.module('myModule', []);
+ *
+ * // register a new service
+ * myModule.value('appName', 'MyCoolApp');
+ *
+ * // configure existing services inside initialization blocks.
+ * myModule.config(function($locationProvider) {
+ * // Configure existing providers
+ * $locationProvider.hashPrefix('!');
+ * });
+ * </pre>
+ *
+ * Then you can create an injector and load your modules like this:
+ *
+ * <pre>
+ * var injector = angular.injector(['ng', 'MyModule'])
+ * </pre>
+ *
+ * However it's more likely that you'll just use
+ * {@link ng.directive:ngApp ngApp} or
+ * {@link angular.bootstrap} to simplify this process for you.
+ *
+ * @param {!string} name The name of the module to create or retrieve.
+ * @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the
+ * the module is being retrieved for further configuration.
+ * @param {Function} configFn Optional configuration function for the module. Same as
+ * {@link angular.Module#config Module#config()}.
+ * @returns {module} new module with the {@link angular.Module} api.
+ */
+ return function module(name, requires, configFn) {
+ if (requires && modules.hasOwnProperty(name)) {
+ modules[name] = null;
+ }
+ return ensure(modules, name, function() {
+ if (!requires) {
+ throw Error('No module: ' + name);
+ }
+
+ /** @type {!Array.<Array.<*>>} */
+ var invokeQueue = [];
+
+ /** @type {!Array.<Function>} */
+ var runBlocks = [];
+
+ var config = invokeLater('$injector', 'invoke');
+
+ /** @type {angular.Module} */
+ var moduleInstance = {
+ // Private state
+ _invokeQueue: invokeQueue,
+ _runBlocks: runBlocks,
+
+ /**
+ * @ngdoc property
+ * @name angular.Module#requires
+ * @propertyOf angular.Module
+ * @returns {Array.<string>} List of module names which must be loaded before this module.
+ * @description
+ * Holds the list of modules which the injector will load before the current module is loaded.
+ */
+ requires: requires,
+
+ /**
+ * @ngdoc property
+ * @name angular.Module#name
+ * @propertyOf angular.Module
+ * @returns {string} Name of the module.
+ * @description
+ */
+ name: name,
+
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#provider
+ * @methodOf angular.Module
+ * @param {string} name service name
+ * @param {Function} providerType Construction function for creating new instance of the service.
+ * @description
+ * See {@link AUTO.$provide#provider $provide.provider()}.
+ */
+ provider: invokeLater('$provide', 'provider'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#factory
+ * @methodOf angular.Module
+ * @param {string} name service name
+ * @param {Function} providerFunction Function for creating new instance of the service.
+ * @description
+ * See {@link AUTO.$provide#factory $provide.factory()}.
+ */
+ factory: invokeLater('$provide', 'factory'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#service
+ * @methodOf angular.Module
+ * @param {string} name service name
+ * @param {Function} constructor A constructor function that will be instantiated.
+ * @description
+ * See {@link AUTO.$provide#service $provide.service()}.
+ */
+ service: invokeLater('$provide', 'service'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#value
+ * @methodOf angular.Module
+ * @param {string} name service name
+ * @param {*} object Service instance object.
+ * @description
+ * See {@link AUTO.$provide#value $provide.value()}.
+ */
+ value: invokeLater('$provide', 'value'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#constant
+ * @methodOf angular.Module
+ * @param {string} name constant name
+ * @param {*} object Constant value.
+ * @description
+ * Because the constant are fixed, they get applied before other provide methods.
+ * See {@link AUTO.$provide#constant $provide.constant()}.
+ */
+ constant: invokeLater('$provide', 'constant', 'unshift'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#animation
+ * @methodOf angular.Module
+ * @param {string} name animation name
+ * @param {Function} animationFactory Factory function for creating new instance of an animation.
+ * @description
+ *
+ * Defines an animation hook that can be later used with {@link ng.directive:ngAnimate ngAnimate}
+ * alongside {@link ng.directive:ngAnimate#Description common ng directives} as well as custom directives.
+ * <pre>
+ * module.animation('animation-name', function($inject1, $inject2) {
+ * return {
+ * //this gets called in preparation to setup an animation
+ * setup : function(element) { ... },
+ *
+ * //this gets called once the animation is run
+ * start : function(element, done, memo) { ... }
+ * }
+ * })
+ * </pre>
+ *
+ * See {@link ng.$animationProvider#register $animationProvider.register()} and
+ * {@link ng.directive:ngAnimate ngAnimate} for more information.
+ */
+ animation: invokeLater('$animationProvider', 'register'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#filter
+ * @methodOf angular.Module
+ * @param {string} name Filter name.
+ * @param {Function} filterFactory Factory function for creating new instance of filter.
+ * @description
+ * See {@link ng.$filterProvider#register $filterProvider.register()}.
+ */
+ filter: invokeLater('$filterProvider', 'register'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#controller
+ * @methodOf angular.Module
+ * @param {string} name Controller name.
+ * @param {Function} constructor Controller constructor function.
+ * @description
+ * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
+ */
+ controller: invokeLater('$controllerProvider', 'register'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#directive
+ * @methodOf angular.Module
+ * @param {string} name directive name
+ * @param {Function} directiveFactory Factory function for creating new instance of
+ * directives.
+ * @description
+ * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
+ */
+ directive: invokeLater('$compileProvider', 'directive'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#config
+ * @methodOf angular.Module
+ * @param {Function} configFn Execute this function on module load. Useful for service
+ * configuration.
+ * @description
+ * Use this method to register work which needs to be performed on module loading.
+ */
+ config: config,
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#run
+ * @methodOf angular.Module
+ * @param {Function} initializationFn Execute this function after injector creation.
+ * Useful for application initialization.
+ * @description
+ * Use this method to register work which should be performed when the injector is done
+ * loading all modules.
+ */
+ run: function(block) {
+ runBlocks.push(block);
+ return this;
+ }
+ };
+
+ if (configFn) {
+ config(configFn);
+ }
+
+ return moduleInstance;
+
+ /**
+ * @param {string} provider
+ * @param {string} method
+ * @param {String=} insertMethod
+ * @returns {angular.Module}
+ */
+ function invokeLater(provider, method, insertMethod) {
+ return function() {
+ invokeQueue[insertMethod || 'push']([provider, method, arguments]);
+ return moduleInstance;
+ }
+ }
+ });
+ };
+ });
+
+}
+
+/**
+ * @ngdoc property
+ * @name angular.version
+ * @description
+ * An object that contains information about the current AngularJS version. This object has the
+ * following properties:
+ *
+ * - `full` – `{string}` – Full version string, such as "0.9.18".
+ * - `major` – `{number}` – Major version number, such as "0".
+ * - `minor` – `{number}` – Minor version number, such as "9".
+ * - `dot` – `{number}` – Dot version number, such as "18".
+ * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
+ */
+var version = {
+ full: '1.1.5', // all of these placeholder strings will be replaced by grunt's
+ major: 1, // package task
+ minor: 1,
+ dot: 5,
+ codeName: 'triangle-squarification'
+};
+
+
+function publishExternalAPI(angular){
+ extend(angular, {
+ 'bootstrap': bootstrap,
+ 'copy': copy,
+ 'extend': extend,
+ 'equals': equals,
+ 'element': jqLite,
+ 'forEach': forEach,
+ 'injector': createInjector,
+ 'noop':noop,
+ 'bind':bind,
+ 'toJson': toJson,
+ 'fromJson': fromJson,
+ 'identity':identity,
+ 'isUndefined': isUndefined,
+ 'isDefined': isDefined,
+ 'isString': isString,
+ 'isFunction': isFunction,
+ 'isObject': isObject,
+ 'isNumber': isNumber,
+ 'isElement': isElement,
+ 'isArray': isArray,
+ 'version': version,
+ 'isDate': isDate,
+ 'lowercase': lowercase,
+ 'uppercase': uppercase,
+ 'callbacks': {counter: 0},
+ 'noConflict': noConflict
+ });
+
+ angularModule = setupModuleLoader(window);
+ try {
+ angularModule('ngLocale');
+ } catch (e) {
+ angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
+ }
+
+ angularModule('ng', ['ngLocale'], ['$provide',
+ function ngModule($provide) {
+ $provide.provider('$compile', $CompileProvider).
+ directive({
+ a: htmlAnchorDirective,
+ input: inputDirective,
+ textarea: inputDirective,
+ form: formDirective,
+ script: scriptDirective,
+ select: selectDirective,
+ style: styleDirective,
+ option: optionDirective,
+ ngBind: ngBindDirective,
+ ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective,
+ ngBindTemplate: ngBindTemplateDirective,
+ ngClass: ngClassDirective,
+ ngClassEven: ngClassEvenDirective,
+ ngClassOdd: ngClassOddDirective,
+ ngCsp: ngCspDirective,
+ ngCloak: ngCloakDirective,
+ ngController: ngControllerDirective,
+ ngForm: ngFormDirective,
+ ngHide: ngHideDirective,
+ ngIf: ngIfDirective,
+ ngInclude: ngIncludeDirective,
+ ngInit: ngInitDirective,
+ ngNonBindable: ngNonBindableDirective,
+ ngPluralize: ngPluralizeDirective,
+ ngRepeat: ngRepeatDirective,
+ ngShow: ngShowDirective,
+ ngSubmit: ngSubmitDirective,
+ ngStyle: ngStyleDirective,
+ ngSwitch: ngSwitchDirective,
+ ngSwitchWhen: ngSwitchWhenDirective,
+ ngSwitchDefault: ngSwitchDefaultDirective,
+ ngOptions: ngOptionsDirective,
+ ngView: ngViewDirective,
+ ngTransclude: ngTranscludeDirective,
+ ngModel: ngModelDirective,
+ ngList: ngListDirective,
+ ngChange: ngChangeDirective,
+ required: requiredDirective,
+ ngRequired: requiredDirective,
+ ngValue: ngValueDirective
+ }).
+ directive(ngAttributeAliasDirectives).
+ directive(ngEventDirectives);
+ $provide.provider({
+ $anchorScroll: $AnchorScrollProvider,
+ $animation: $AnimationProvider,
+ $animator: $AnimatorProvider,
+ $browser: $BrowserProvider,
+ $cacheFactory: $CacheFactoryProvider,
+ $controller: $ControllerProvider,
+ $document: $DocumentProvider,
+ $exceptionHandler: $ExceptionHandlerProvider,
+ $filter: $FilterProvider,
+ $interpolate: $InterpolateProvider,
+ $http: $HttpProvider,
+ $httpBackend: $HttpBackendProvider,
+ $location: $LocationProvider,
+ $log: $LogProvider,
+ $parse: $ParseProvider,
+ $route: $RouteProvider,
+ $routeParams: $RouteParamsProvider,
+ $rootScope: $RootScopeProvider,
+ $q: $QProvider,
+ $sniffer: $SnifferProvider,
+ $templateCache: $TemplateCacheProvider,
+ $timeout: $TimeoutProvider,
+ $window: $WindowProvider
+ });
+ }
+ ]);
+}
+
+//////////////////////////////////
+//JQLite
+//////////////////////////////////
+
+/**
+ * @ngdoc function
+ * @name angular.element
+ * @function
+ *
+ * @description
+ * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
+ * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if
+ * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite
+ * implementation (commonly referred to as jqLite).
+ *
+ * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded`
+ * event fired.
+ *
+ * jqLite is a tiny, API-compatible subset of jQuery that allows
+ * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality
+ * within a very small footprint, so only a subset of the jQuery API - methods, arguments and
+ * invocation styles - are supported.
+ *
+ * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never
+ * raw DOM references.
+ *
+ * ## Angular's jQuery lite provides the following methods:
+ *
+ * - [addClass()](http://api.jquery.com/addClass/)
+ * - [after()](http://api.jquery.com/after/)
+ * - [append()](http://api.jquery.com/append/)
+ * - [attr()](http://api.jquery.com/attr/)
+ * - [bind()](http://api.jquery.com/bind/) - Does not support namespaces
+ * - [children()](http://api.jquery.com/children/) - Does not support selectors
+ * - [clone()](http://api.jquery.com/clone/)
+ * - [contents()](http://api.jquery.com/contents/)
+ * - [css()](http://api.jquery.com/css/)
+ * - [data()](http://api.jquery.com/data/)
+ * - [eq()](http://api.jquery.com/eq/)
+ * - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name
+ * - [hasClass()](http://api.jquery.com/hasClass/)
+ * - [html()](http://api.jquery.com/html/)
+ * - [next()](http://api.jquery.com/next/) - Does not support selectors
+ * - [parent()](http://api.jquery.com/parent/) - Does not support selectors
+ * - [prepend()](http://api.jquery.com/prepend/)
+ * - [prop()](http://api.jquery.com/prop/)
+ * - [ready()](http://api.jquery.com/ready/)
+ * - [remove()](http://api.jquery.com/remove/)
+ * - [removeAttr()](http://api.jquery.com/removeAttr/)
+ * - [removeClass()](http://api.jquery.com/removeClass/)
+ * - [removeData()](http://api.jquery.com/removeData/)
+ * - [replaceWith()](http://api.jquery.com/replaceWith/)
+ * - [text()](http://api.jquery.com/text/)
+ * - [toggleClass()](http://api.jquery.com/toggleClass/)
+ * - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
+ * - [unbind()](http://api.jquery.com/unbind/) - Does not support namespaces
+ * - [val()](http://api.jquery.com/val/)
+ * - [wrap()](http://api.jquery.com/wrap/)
+ *
+ * ## In addition to the above, Angular provides additional methods to both jQuery and jQuery lite:
+ *
+ * - `controller(name)` - retrieves the controller of the current element or its parent. By default
+ * retrieves controller associated with the `ngController` directive. If `name` is provided as
+ * camelCase directive name, then the controller for this directive will be retrieved (e.g.
+ * `'ngModel'`).
+ * - `injector()` - retrieves the injector of the current element or its parent.
+ * - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
+ * element or its parent.
+ * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
+ * parent element is reached.
+ *
+ * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
+ * @returns {Object} jQuery object.
+ */
+
+var jqCache = JQLite.cache = {},
+ jqName = JQLite.expando = 'ng-' + new Date().getTime(),
+ jqId = 1,
+ addEventListenerFn = (window.document.addEventListener
+ ? function(element, type, fn) {element.addEventListener(type, fn, false);}
+ : function(element, type, fn) {element.attachEvent('on' + type, fn);}),
+ removeEventListenerFn = (window.document.removeEventListener
+ ? function(element, type, fn) {element.removeEventListener(type, fn, false); }
+ : function(element, type, fn) {element.detachEvent('on' + type, fn); });
+
+function jqNextId() { return ++jqId; }
+
+
+var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
+var MOZ_HACK_REGEXP = /^moz([A-Z])/;
+
+/**
+ * Converts snake_case to camelCase.
+ * Also there is special case for Moz prefix starting with upper case letter.
+ * @param name Name to normalize
+ */
+function camelCase(name) {
+ return name.
+ replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
+ return offset ? letter.toUpperCase() : letter;
+ }).
+ replace(MOZ_HACK_REGEXP, 'Moz$1');
+}
+
+/////////////////////////////////////////////
+// jQuery mutation patch
+//
+// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
+// $destroy event on all DOM nodes being removed.
+//
+/////////////////////////////////////////////
+
+function JQLitePatchJQueryRemove(name, dispatchThis) {
+ var originalJqFn = jQuery.fn[name];
+ originalJqFn = originalJqFn.$original || originalJqFn;
+ removePatch.$original = originalJqFn;
+ jQuery.fn[name] = removePatch;
+
+ function removePatch() {
+ var list = [this],
+ fireEvent = dispatchThis,
+ set, setIndex, setLength,
+ element, childIndex, childLength, children,
+ fns, events;
+
+ while(list.length) {
+ set = list.shift();
+ for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
+ element = jqLite(set[setIndex]);
+ if (fireEvent) {
+ element.triggerHandler('$destroy');
+ } else {
+ fireEvent = !fireEvent;
+ }
+ for(childIndex = 0, childLength = (children = element.children()).length;
+ childIndex < childLength;
+ childIndex++) {
+ list.push(jQuery(children[childIndex]));
+ }
+ }
+ }
+ return originalJqFn.apply(this, arguments);
+ }
+}
+
+/////////////////////////////////////////////
+function JQLite(element) {
+ if (element instanceof JQLite) {
+ return element;
+ }
+ if (!(this instanceof JQLite)) {
+ if (isString(element) && element.charAt(0) != '<') {
+ throw Error('selectors not implemented');
+ }
+ return new JQLite(element);
+ }
+
+ if (isString(element)) {
+ var div = document.createElement('div');
+ // Read about the NoScope elements here:
+ // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
+ div.innerHTML = '<div> </div>' + element; // IE insanity to make NoScope elements work!
+ div.removeChild(div.firstChild); // remove the superfluous div
+ JQLiteAddNodes(this, div.childNodes);
+ this.remove(); // detach the elements from the temporary DOM div.
+ } else {
+ JQLiteAddNodes(this, element);
+ }
+}
+
+function JQLiteClone(element) {
+ return element.cloneNode(true);
+}
+
+function JQLiteDealoc(element){
+ JQLiteRemoveData(element);
+ for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
+ JQLiteDealoc(children[i]);
+ }
+}
+
+function JQLiteUnbind(element, type, fn) {
+ var events = JQLiteExpandoStore(element, 'events'),
+ handle = JQLiteExpandoStore(element, 'handle');
+
+ if (!handle) return; //no listeners registered
+
+ if (isUndefined(type)) {
+ forEach(events, function(eventHandler, type) {
+ removeEventListenerFn(element, type, eventHandler);
+ delete events[type];
+ });
+ } else {
+ if (isUndefined(fn)) {
+ removeEventListenerFn(element, type, events[type]);
+ delete events[type];
+ } else {
+ arrayRemove(events[type], fn);
+ }
+ }
+}
+
+function JQLiteRemoveData(element) {
+ var expandoId = element[jqName],
+ expandoStore = jqCache[expandoId];
+
+ if (expandoStore) {
+ if (expandoStore.handle) {
+ expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
+ JQLiteUnbind(element);
+ }
+ delete jqCache[expandoId];
+ element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
+ }
+}
+
+function JQLiteExpandoStore(element, key, value) {
+ var expandoId = element[jqName],
+ expandoStore = jqCache[expandoId || -1];
+
+ if (isDefined(value)) {
+ if (!expandoStore) {
+ element[jqName] = expandoId = jqNextId();
+ expandoStore = jqCache[expandoId] = {};
+ }
+ expandoStore[key] = value;
+ } else {
+ return expandoStore && expandoStore[key];
+ }
+}
+
+function JQLiteData(element, key, value) {
+ var data = JQLiteExpandoStore(element, 'data'),
+ isSetter = isDefined(value),
+ keyDefined = !isSetter && isDefined(key),
+ isSimpleGetter = keyDefined && !isObject(key);
+
+ if (!data && !isSimpleGetter) {
+ JQLiteExpandoStore(element, 'data', data = {});
+ }
+
+ if (isSetter) {
+ data[key] = value;
+ } else {
+ if (keyDefined) {
+ if (isSimpleGetter) {
+ // don't create data in this case.
+ return data && data[key];
+ } else {
+ extend(data, key);
+ }
+ } else {
+ return data;
+ }
+ }
+}
+
+function JQLiteHasClass(element, selector) {
+ return ((" " + element.className + " ").replace(/[\n\t]/g, " ").
+ indexOf( " " + selector + " " ) > -1);
+}
+
+function JQLiteRemoveClass(element, cssClasses) {
+ if (cssClasses) {
+ forEach(cssClasses.split(' '), function(cssClass) {
+ element.className = trim(
+ (" " + element.className + " ")
+ .replace(/[\n\t]/g, " ")
+ .replace(" " + trim(cssClass) + " ", " ")
+ );
+ });
+ }
+}
+
+function JQLiteAddClass(element, cssClasses) {
+ if (cssClasses) {
+ forEach(cssClasses.split(' '), function(cssClass) {
+ if (!JQLiteHasClass(element, cssClass)) {
+ element.className = trim(element.className + ' ' + trim(cssClass));
+ }
+ });
+ }
+}
+
+function JQLiteAddNodes(root, elements) {
+ if (elements) {
+ elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
+ ? elements
+ : [ elements ];
+ for(var i=0; i < elements.length; i++) {
+ root.push(elements[i]);
+ }
+ }
+}
+
+function JQLiteController(element, name) {
+ return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
+}
+
+function JQLiteInheritedData(element, name, value) {
+ element = jqLite(element);
+
+ // if element is the document object work with the html element instead
+ // this makes $(document).scope() possible
+ if(element[0].nodeType == 9) {
+ element = element.find('html');
+ }
+
+ while (element.length) {
+ if (value = element.data(name)) return value;
+ element = element.parent();
+ }
+}
+
+//////////////////////////////////////////
+// Functions which are declared directly.
+//////////////////////////////////////////
+var JQLitePrototype = JQLite.prototype = {
+ ready: function(fn) {
+ var fired = false;
+
+ function trigger() {
+ if (fired) return;
+ fired = true;
+ fn();
+ }
+
+ // check if document already is loaded
+ if (document.readyState === 'complete'){
+ setTimeout(trigger);
+ } else {
+ this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9
+ // we can not use jqLite since we are not done loading and jQuery could be loaded later.
+ JQLite(window).bind('load', trigger); // fallback to window.onload for others
+ }
+ },
+ toString: function() {
+ var value = [];
+ forEach(this, function(e){ value.push('' + e);});
+ return '[' + value.join(', ') + ']';
+ },
+
+ eq: function(index) {
+ return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
+ },
+
+ length: 0,
+ push: push,
+ sort: [].sort,
+ splice: [].splice
+};
+
+//////////////////////////////////////////
+// Functions iterating getter/setters.
+// these functions return self on setter and
+// value on get.
+//////////////////////////////////////////
+var BOOLEAN_ATTR = {};
+forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
+ BOOLEAN_ATTR[lowercase(value)] = value;
+});
+var BOOLEAN_ELEMENTS = {};
+forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
+ BOOLEAN_ELEMENTS[uppercase(value)] = true;
+});
+
+function getBooleanAttrName(element, name) {
+ // check dom last since we will most likely fail on name
+ var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
+
+ // booleanAttr is here twice to minimize DOM access
+ return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
+}
+
+forEach({
+ data: JQLiteData,
+ inheritedData: JQLiteInheritedData,
+
+ scope: function(element) {
+ return JQLiteInheritedData(element, '$scope');
+ },
+
+ controller: JQLiteController ,
+
+ injector: function(element) {
+ return JQLiteInheritedData(element, '$injector');
+ },
+
+ removeAttr: function(element,name) {
+ element.removeAttribute(name);
+ },
+
+ hasClass: JQLiteHasClass,
+
+ css: function(element, name, value) {
+ name = camelCase(name);
+
+ if (isDefined(value)) {
+ element.style[name] = value;
+ } else {
+ var val;
+
+ if (msie <= 8) {
+ // this is some IE specific weirdness that jQuery 1.6.4 does not sure why
+ val = element.currentStyle && element.currentStyle[name];
+ if (val === '') val = 'auto';
+ }
+
+ val = val || element.style[name];
+
+ if (msie <= 8) {
+ // jquery weirdness :-/
+ val = (val === '') ? undefined : val;
+ }
+
+ return val;
+ }
+ },
+
+ attr: function(element, name, value){
+ var lowercasedName = lowercase(name);
+ if (BOOLEAN_ATTR[lowercasedName]) {
+ if (isDefined(value)) {
+ if (!!value) {
+ element[name] = true;
+ element.setAttribute(name, lowercasedName);
+ } else {
+ element[name] = false;
+ element.removeAttribute(lowercasedName);
+ }
+ } else {
+ return (element[name] ||
+ (element.attributes.getNamedItem(name)|| noop).specified)
+ ? lowercasedName
+ : undefined;
+ }
+ } else if (isDefined(value)) {
+ element.setAttribute(name, value);
+ } else if (element.getAttribute) {
+ // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
+ // some elements (e.g. Document) don't have get attribute, so return undefined
+ var ret = element.getAttribute(name, 2);
+ // normalize non-existing attributes to undefined (as jQuery)
+ return ret === null ? undefined : ret;
+ }
+ },
+
+ prop: function(element, name, value) {
+ if (isDefined(value)) {
+ element[name] = value;
+ } else {
+ return element[name];
+ }
+ },
+
+ text: extend((msie < 9)
+ ? function(element, value) {
+ if (element.nodeType == 1 /** Element */) {
+ if (isUndefined(value))
+ return element.innerText;
+ element.innerText = value;
+ } else {
+ if (isUndefined(value))
+ return element.nodeValue;
+ element.nodeValue = value;
+ }
+ }
+ : function(element, value) {
+ if (isUndefined(value)) {
+ return element.textContent;
+ }
+ element.textContent = value;
+ }, {$dv:''}),
+
+ val: function(element, value) {
+ if (isUndefined(value)) {
+ return element.value;
+ }
+ element.value = value;
+ },
+
+ html: function(element, value) {
+ if (isUndefined(value)) {
+ return element.innerHTML;
+ }
+ for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
+ JQLiteDealoc(childNodes[i]);
+ }
+ element.innerHTML = value;
+ }
+}, function(fn, name){
+ /**
+ * Properties: writes return selection, reads return first value
+ */
+ JQLite.prototype[name] = function(arg1, arg2) {
+ var i, key;
+
+ // JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
+ // in a way that survives minification.
+ if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) {
+ if (isObject(arg1)) {
+
+ // we are a write, but the object properties are the key/values
+ for(i=0; i < this.length; i++) {
+ if (fn === JQLiteData) {
+ // data() takes the whole object in jQuery
+ fn(this[i], arg1);
+ } else {
+ for (key in arg1) {
+ fn(this[i], key, arg1[key]);
+ }
+ }
+ }
+ // return self for chaining
+ return this;
+ } else {
+ // we are a read, so read the first child.
+ if (this.length)
+ return fn(this[0], arg1, arg2);
+ }
+ } else {
+ // we are a write, so apply to all children
+ for(i=0; i < this.length; i++) {
+ fn(this[i], arg1, arg2);
+ }
+ // return self for chaining
+ return this;
+ }
+ return fn.$dv;
+ };
+});
+
+function createEventHandler(element, events) {
+ var eventHandler = function (event, type) {
+ if (!event.preventDefault) {
+ event.preventDefault = function() {
+ event.returnValue = false; //ie
+ };
+ }
+
+ if (!event.stopPropagation) {
+ event.stopPropagation = function() {
+ event.cancelBubble = true; //ie
+ };
+ }
+
+ if (!event.target) {
+ event.target = event.srcElement || document;
+ }
+
+ if (isUndefined(event.defaultPrevented)) {
+ var prevent = event.preventDefault;
+ event.preventDefault = function() {
+ event.defaultPrevented = true;
+ prevent.call(event);
+ };
+ event.defaultPrevented = false;
+ }
+
+ event.isDefaultPrevented = function() {
+ return event.defaultPrevented || event.returnValue == false;
+ };
+
+ forEach(events[type || event.type], function(fn) {
+ fn.call(element, event);
+ });
+
+ // Remove monkey-patched methods (IE),
+ // as they would cause memory leaks in IE8.
+ if (msie <= 8) {
+ // IE7/8 does not allow to delete property on native object
+ event.preventDefault = null;
+ event.stopPropagation = null;
+ event.isDefaultPrevented = null;
+ } else {
+ // It shouldn't affect normal browsers (native methods are defined on prototype).
+ delete event.preventDefault;
+ delete event.stopPropagation;
+ delete event.isDefaultPrevented;
+ }
+ };
+ eventHandler.elem = element;
+ return eventHandler;
+}
+
+//////////////////////////////////////////
+// Functions iterating traversal.
+// These functions chain results into a single
+// selector.
+//////////////////////////////////////////
+forEach({
+ removeData: JQLiteRemoveData,
+
+ dealoc: JQLiteDealoc,
+
+ bind: function bindFn(element, type, fn){
+ var events = JQLiteExpandoStore(element, 'events'),
+ handle = JQLiteExpandoStore(element, 'handle');
+
+ if (!events) JQLiteExpandoStore(element, 'events', events = {});
+ if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
+
+ forEach(type.split(' '), function(type){
+ var eventFns = events[type];
+
+ if (!eventFns) {
+ if (type == 'mouseenter' || type == 'mouseleave') {
+ var contains = document.body.contains || document.body.compareDocumentPosition ?
+ function( a, b ) {
+ var adown = a.nodeType === 9 ? a.documentElement : a,
+ bup = b && b.parentNode;
+ return a === bup || !!( bup && bup.nodeType === 1 && (
+ adown.contains ?
+ adown.contains( bup ) :
+ a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
+ ));
+ } :
+ function( a, b ) {
+ if ( b ) {
+ while ( (b = b.parentNode) ) {
+ if ( b === a ) {
+ return true;
+ }
+ }
+ }
+ return false;
+ };
+
+ events[type] = [];
+
+ // Refer to jQuery's implementation of mouseenter & mouseleave
+ // Read about mouseenter and mouseleave:
+ // http://www.quirksmode.org/js/events_mouse.html#link8
+ var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"}
+ bindFn(element, eventmap[type], function(event) {
+ var ret, target = this, related = event.relatedTarget;
+ // For mousenter/leave call the handler if related is outside the target.
+ // NB: No relatedTarget if the mouse left/entered the browser window
+ if ( !related || (related !== target && !contains(target, related)) ){
+ handle(event, type);
+ }
+
+ });
+
+ } else {
+ addEventListenerFn(element, type, handle);
+ events[type] = [];
+ }
+ eventFns = events[type]
+ }
+ eventFns.push(fn);
+ });
+ },
+
+ unbind: JQLiteUnbind,
+
+ replaceWith: function(element, replaceNode) {
+ var index, parent = element.parentNode;
+ JQLiteDealoc(element);
+ forEach(new JQLite(replaceNode), function(node){
+ if (index) {
+ parent.insertBefore(node, index.nextSibling);
+ } else {
+ parent.replaceChild(node, element);
+ }
+ index = node;
+ });
+ },
+
+ children: function(element) {
+ var children = [];
+ forEach(element.childNodes, function(element){
+ if (element.nodeType === 1)
+ children.push(element);
+ });
+ return children;
+ },
+
+ contents: function(element) {
+ return element.childNodes || [];
+ },
+
+ append: function(element, node) {
+ forEach(new JQLite(node), function(child){
+ if (element.nodeType === 1 || element.nodeType === 11) {
+ element.appendChild(child);
+ }
+ });
+ },
+
+ prepend: function(element, node) {
+ if (element.nodeType === 1) {
+ var index = element.firstChild;
+ forEach(new JQLite(node), function(child){
+ if (index) {
+ element.insertBefore(child, index);
+ } else {
+ element.appendChild(child);
+ index = child;
+ }
+ });
+ }
+ },
+
+ wrap: function(element, wrapNode) {
+ wrapNode = jqLite(wrapNode)[0];
+ var parent = element.parentNode;
+ if (parent) {
+ parent.replaceChild(wrapNode, element);
+ }
+ wrapNode.appendChild(element);
+ },
+
+ remove: function(element) {
+ JQLiteDealoc(element);
+ var parent = element.parentNode;
+ if (parent) parent.removeChild(element);
+ },
+
+ after: function(element, newElement) {
+ var index = element, parent = element.parentNode;
+ forEach(new JQLite(newElement), function(node){
+ parent.insertBefore(node, index.nextSibling);
+ index = node;
+ });
+ },
+
+ addClass: JQLiteAddClass,
+ removeClass: JQLiteRemoveClass,
+
+ toggleClass: function(element, selector, condition) {
+ if (isUndefined(condition)) {
+ condition = !JQLiteHasClass(element, selector);
+ }
+ (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector);
+ },
+
+ parent: function(element) {
+ var parent = element.parentNode;
+ return parent && parent.nodeType !== 11 ? parent : null;
+ },
+
+ next: function(element) {
+ if (element.nextElementSibling) {
+ return element.nextElementSibling;
+ }
+
+ // IE8 doesn't have nextElementSibling
+ var elm = element.nextSibling;
+ while (elm != null && elm.nodeType !== 1) {
+ elm = elm.nextSibling;
+ }
+ return elm;
+ },
+
+ find: function(element, selector) {
+ return element.getElementsByTagName(selector);
+ },
+
+ clone: JQLiteClone,
+
+ triggerHandler: function(element, eventName) {
+ var eventFns = (JQLiteExpandoStore(element, 'events') || {})[eventName];
+ var event;
+
+ forEach(eventFns, function(fn) {
+ fn.call(element, {preventDefault: noop});
+ });
+ }
+}, function(fn, name){
+ /**
+ * chaining functions
+ */
+ JQLite.prototype[name] = function(arg1, arg2) {
+ var value;
+ for(var i=0; i < this.length; i++) {
+ if (value == undefined) {
+ value = fn(this[i], arg1, arg2);
+ if (value !== undefined) {
+ // any function which returns a value needs to be wrapped
+ value = jqLite(value);
+ }
+ } else {
+ JQLiteAddNodes(value, fn(this[i], arg1, arg2));
+ }
+ }
+ return value == undefined ? this : value;
+ };
+});
+
+/**
+ * Computes a hash of an 'obj'.
+ * Hash of a:
+ * string is string
+ * number is number as string
+ * object is either result of calling $$hashKey function on the object or uniquely generated id,
+ * that is also assigned to the $$hashKey property of the object.
+ *
+ * @param obj
+ * @returns {string} hash string such that the same input will have the same hash string.
+ * The resulting string key is in 'type:hashKey' format.
+ */
+function hashKey(obj) {
+ var objType = typeof obj,
+ key;
+
+ if (objType == 'object' && obj !== null) {
+ if (typeof (key = obj.$$hashKey) == 'function') {
+ // must invoke on object to keep the right this
+ key = obj.$$hashKey();
+ } else if (key === undefined) {
+ key = obj.$$hashKey = nextUid();
+ }
+ } else {
+ key = obj;
+ }
+
+ return objType + ':' + key;
+}
+
+/**
+ * HashMap which can use objects as keys
+ */
+function HashMap(array){
+ forEach(array, this.put, this);
+}
+HashMap.prototype = {
+ /**
+ * Store key value pair
+ * @param key key to store can be any type
+ * @param value value to store can be any type
+ */
+ put: function(key, value) {
+ this[hashKey(key)] = value;
+ },
+
+ /**
+ * @param key
+ * @returns the value for the key
+ */
+ get: function(key) {
+ return this[hashKey(key)];
+ },
+
+ /**
+ * Remove the key/value pair
+ * @param key
+ */
+ remove: function(key) {
+ var value = this[key = hashKey(key)];
+ delete this[key];
+ return value;
+ }
+};
+
+/**
+ * @ngdoc function
+ * @name angular.injector
+ * @function
+ *
+ * @description
+ * Creates an injector function that can be used for retrieving services as well as for
+ * dependency injection (see {@link guide/di dependency injection}).
+ *
+
+ * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
+ * {@link angular.module}. The `ng` module must be explicitly added.
+ * @returns {function()} Injector function. See {@link AUTO.$injector $injector}.
+ *
+ * @example
+ * Typical usage
+ * <pre>
+ * // create an injector
+ * var $injector = angular.injector(['ng']);
+ *
+ * // use the injector to kick off your application
+ * // use the type inference to auto inject arguments, or use implicit injection
+ * $injector.invoke(function($rootScope, $compile, $document){
+ * $compile($document)($rootScope);
+ * $rootScope.$digest();
+ * });
+ * </pre>
+ */
+
+
+/**
+ * @ngdoc overview
+ * @name AUTO
+ * @description
+ *
+ * Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
+ */
+
+var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
+var FN_ARG_SPLIT = /,/;
+var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
+var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
+function annotate(fn) {
+ var $inject,
+ fnText,
+ argDecl,
+ last;
+
+ if (typeof fn == 'function') {
+ if (!($inject = fn.$inject)) {
+ $inject = [];
+ fnText = fn.toString().replace(STRIP_COMMENTS, '');
+ argDecl = fnText.match(FN_ARGS);
+ forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
+ arg.replace(FN_ARG, function(all, underscore, name){
+ $inject.push(name);
+ });
+ });
+ fn.$inject = $inject;
+ }
+ } else if (isArray(fn)) {
+ last = fn.length - 1;
+ assertArgFn(fn[last], 'fn');
+ $inject = fn.slice(0, last);
+ } else {
+ assertArgFn(fn, 'fn', true);
+ }
+ return $inject;
+}
+
+///////////////////////////////////////
+
+/**
+ * @ngdoc object
+ * @name AUTO.$injector
+ * @function
+ *
+ * @description
+ *
+ * `$injector` is used to retrieve object instances as defined by
+ * {@link AUTO.$provide provider}, instantiate types, invoke methods,
+ * and load modules.
+ *
+ * The following always holds true:
+ *
+ * <pre>
+ * var $injector = angular.injector();
+ * expect($injector.get('$injector')).toBe($injector);
+ * expect($injector.invoke(function($injector){
+ * return $injector;
+ * }).toBe($injector);
+ * </pre>
+ *
+ * # Injection Function Annotation
+ *
+ * JavaScript does not have annotations, and annotations are needed for dependency injection. The
+ * following are all valid ways of annotating function with injection arguments and are equivalent.
+ *
+ * <pre>
+ * // inferred (only works if code not minified/obfuscated)
+ * $injector.invoke(function(serviceA){});
+ *
+ * // annotated
+ * function explicit(serviceA) {};
+ * explicit.$inject = ['serviceA'];
+ * $injector.invoke(explicit);
+ *
+ * // inline
+ * $injector.invoke(['serviceA', function(serviceA){}]);
+ * </pre>
+ *
+ * ## Inference
+ *
+ * In JavaScript calling `toString()` on a function returns the function definition. The definition can then be
+ * parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation
+ * tools since these tools change the argument names.
+ *
+ * ## `$inject` Annotation
+ * By adding a `$inject` property onto a function the injection parameters can be specified.
+ *
+ * ## Inline
+ * As an array of injection names, where the last item in the array is the function to call.
+ */
+
+/**
+ * @ngdoc method
+ * @name AUTO.$injector#get
+ * @methodOf AUTO.$injector
+ *
+ * @description
+ * Return an instance of the service.
+ *
+ * @param {string} name The name of the instance to retrieve.
+ * @return {*} The instance.
+ */
+
+/**
+ * @ngdoc method
+ * @name AUTO.$injector#invoke
+ * @methodOf AUTO.$injector
+ *
+ * @description
+ * Invoke the method and supply the method arguments from the `$injector`.
+ *
+ * @param {!function} fn The function to invoke. The function arguments come form the function annotation.
+ * @param {Object=} self The `this` for the invoked method.
+ * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
+ * the `$injector` is consulted.
+ * @returns {*} the value returned by the invoked `fn` function.
+ */
+
+/**
+ * @ngdoc method
+ * @name AUTO.$injector#has
+ * @methodOf AUTO.$injector
+ *
+ * @description
+ * Allows the user to query if the particular service exist.
+ *
+ * @param {string} Name of the service to query.
+ * @returns {boolean} returns true if injector has given service.
+ */
+
+/**
+ * @ngdoc method
+ * @name AUTO.$injector#instantiate
+ * @methodOf AUTO.$injector
+ * @description
+ * Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies
+ * all of the arguments to the constructor function as specified by the constructor annotation.
+ *
+ * @param {function} Type Annotated constructor function.
+ * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
+ * the `$injector` is consulted.
+ * @returns {Object} new instance of `Type`.
+ */
+
+/**
+ * @ngdoc method
+ * @name AUTO.$injector#annotate
+ * @methodOf AUTO.$injector
+ *
+ * @description
+ * Returns an array of service names which the function is requesting for injection. This API is used by the injector
+ * to determine which services need to be injected into the function when the function is invoked. There are three
+ * ways in which the function can be annotated with the needed dependencies.
+ *
+ * # Argument names
+ *
+ * The simplest form is to extract the dependencies from the arguments of the function. This is done by converting
+ * the function into a string using `toString()` method and extracting the argument names.
+ * <pre>
+ * // Given
+ * function MyController($scope, $route) {
+ * // ...
+ * }
+ *
+ * // Then
+ * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
+ * </pre>
+ *
+ * This method does not work with code minfication / obfuscation. For this reason the following annotation strategies
+ * are supported.
+ *
+ * # The `$inject` property
+ *
+ * If a function has an `$inject` property and its value is an array of strings, then the strings represent names of
+ * services to be injected into the function.
+ * <pre>
+ * // Given
+ * var MyController = function(obfuscatedScope, obfuscatedRoute) {
+ * // ...
+ * }
+ * // Define function dependencies
+ * MyController.$inject = ['$scope', '$route'];
+ *
+ * // Then
+ * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
+ * </pre>
+ *
+ * # The array notation
+ *
+ * It is often desirable to inline Injected functions and that's when setting the `$inject` property is very
+ * inconvenient. In these situations using the array notation to specify the dependencies in a way that survives
+ * minification is a better choice:
+ *
+ * <pre>
+ * // We wish to write this (not minification / obfuscation safe)
+ * injector.invoke(function($compile, $rootScope) {
+ * // ...
+ * });
+ *
+ * // We are forced to write break inlining
+ * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
+ * // ...
+ * };
+ * tmpFn.$inject = ['$compile', '$rootScope'];
+ * injector.invoke(tmpFn);
+ *
+ * // To better support inline function the inline annotation is supported
+ * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
+ * // ...
+ * }]);
+ *
+ * // Therefore
+ * expect(injector.annotate(
+ * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
+ * ).toEqual(['$compile', '$rootScope']);
+ * </pre>
+ *
+ * @param {function|Array.<string|Function>} fn Function for which dependent service names need to be retrieved as described
+ * above.
+ *
+ * @returns {Array.<string>} The names of the services which the function requires.
+ */
+
+
+
+
+/**
+ * @ngdoc object
+ * @name AUTO.$provide
+ *
+ * @description
+ *
+ * Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance.
+ * The providers share the same name as the instance they create with `Provider` suffixed to them.
+ *
+ * A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of
+ * a service. The Provider can have additional methods which would allow for configuration of the provider.
+ *
+ * <pre>
+ * function GreetProvider() {
+ * var salutation = 'Hello';
+ *
+ * this.salutation = function(text) {
+ * salutation = text;
+ * };
+ *
+ * this.$get = function() {
+ * return function (name) {
+ * return salutation + ' ' + name + '!';
+ * };
+ * };
+ * }
+ *
+ * describe('Greeter', function(){
+ *
+ * beforeEach(module(function($provide) {
+ * $provide.provider('greet', GreetProvider);
+ * }));
+ *
+ * it('should greet', inject(function(greet) {
+ * expect(greet('angular')).toEqual('Hello angular!');
+ * }));
+ *
+ * it('should allow configuration of salutation', function() {
+ * module(function(greetProvider) {
+ * greetProvider.salutation('Ahoj');
+ * });
+ * inject(function(greet) {
+ * expect(greet('angular')).toEqual('Ahoj angular!');
+ * });
+ * });
+ * </pre>
+ */
+
+/**
+ * @ngdoc method
+ * @name AUTO.$provide#provider
+ * @methodOf AUTO.$provide
+ * @description
+ *
+ * Register a provider for a service. The providers can be retrieved and can have additional configuration methods.
+ *
+ * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key.
+ * @param {(Object|function())} provider If the provider is:
+ *
+ * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
+ * {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created.
+ * - `Constructor`: a new instance of the provider will be created using
+ * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`.
+ *
+ * @returns {Object} registered provider instance
+ */
+
+/**
+ * @ngdoc method
+ * @name AUTO.$provide#factory
+ * @methodOf AUTO.$provide
+ * @description
+ *
+ * A short hand for configuring services if only `$get` method is required.
+ *
+ * @param {string} name The name of the instance.
+ * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for
+ * `$provide.provider(name, {$get: $getFn})`.
+ * @returns {Object} registered provider instance
+ */
+
+
+/**
+ * @ngdoc method
+ * @name AUTO.$provide#service
+ * @methodOf AUTO.$provide
+ * @description
+ *
+ * A short hand for registering service of given class.
+ *
+ * @param {string} name The name of the instance.
+ * @param {Function} constructor A class (constructor function) that will be instantiated.
+ * @returns {Object} registered provider instance
+ */
+
+
+/**
+ * @ngdoc method
+ * @name AUTO.$provide#value
+ * @methodOf AUTO.$provide
+ * @description
+ *
+ * A short hand for configuring services if the `$get` method is a constant.
+ *
+ * @param {string} name The name of the instance.
+ * @param {*} value The value.
+ * @returns {Object} registered provider instance
+ */
+
+
+/**
+ * @ngdoc method
+ * @name AUTO.$provide#constant
+ * @methodOf AUTO.$provide
+ * @description
+ *
+ * A constant value, but unlike {@link AUTO.$provide#value value} it can be injected
+ * into configuration function (other modules) and it is not interceptable by
+ * {@link AUTO.$provide#decorator decorator}.
+ *
+ * @param {string} name The name of the constant.
+ * @param {*} value The constant value.
+ * @returns {Object} registered instance
+ */
+
+
+/**
+ * @ngdoc method
+ * @name AUTO.$provide#decorator
+ * @methodOf AUTO.$provide
+ * @description
+ *
+ * Decoration of service, allows the decorator to intercept the service instance creation. The
+ * returned instance may be the original instance, or a new instance which delegates to the
+ * original instance.
+ *
+ * @param {string} name The name of the service to decorate.
+ * @param {function()} decorator This function will be invoked when the service needs to be
+ * instantiated. The function is called using the {@link AUTO.$injector#invoke
+ * injector.invoke} method and is therefore fully injectable. Local injection arguments:
+ *
+ * * `$delegate` - The original service instance, which can be monkey patched, configured,
+ * decorated or delegated to.
+ */
+
+
+function createInjector(modulesToLoad) {
+ var INSTANTIATING = {},
+ providerSuffix = 'Provider',
+ path = [],
+ loadedModules = new HashMap(),
+ providerCache = {
+ $provide: {
+ provider: supportObject(provider),
+ factory: supportObject(factory),
+ service: supportObject(service),
+ value: supportObject(value),
+ constant: supportObject(constant),
+ decorator: decorator
+ }
+ },
+ providerInjector = (providerCache.$injector =
+ createInternalInjector(providerCache, function() {
+ throw Error("Unknown provider: " + path.join(' <- '));
+ })),
+ instanceCache = {},
+ instanceInjector = (instanceCache.$injector =
+ createInternalInjector(instanceCache, function(servicename) {
+ var provider = providerInjector.get(servicename + providerSuffix);
+ return instanceInjector.invoke(provider.$get, provider);
+ }));
+
+
+ forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
+
+ return instanceInjector;
+
+ ////////////////////////////////////
+ // $provider
+ ////////////////////////////////////
+
+ function supportObject(delegate) {
+ return function(key, value) {
+ if (isObject(key)) {
+ forEach(key, reverseParams(delegate));
+ } else {
+ return delegate(key, value);
+ }
+ }
+ }
+
+ function provider(name, provider_) {
+ if (isFunction(provider_) || isArray(provider_)) {
+ provider_ = providerInjector.instantiate(provider_);
+ }
+ if (!provider_.$get) {
+ throw Error('Provider ' + name + ' must define $get factory method.');
+ }
+ return providerCache[name + providerSuffix] = provider_;
+ }
+
+ function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
+
+ function service(name, constructor) {
+ return factory(name, ['$injector', function($injector) {
+ return $injector.instantiate(constructor);
+ }]);
+ }
+
+ function value(name, value) { return factory(name, valueFn(value)); }
+
+ function constant(name, value) {
+ providerCache[name] = value;
+ instanceCache[name] = value;
+ }
+
+ function decorator(serviceName, decorFn) {
+ var origProvider = providerInjector.get(serviceName + providerSuffix),
+ orig$get = origProvider.$get;
+
+ origProvider.$get = function() {
+ var origInstance = instanceInjector.invoke(orig$get, origProvider);
+ return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
+ };
+ }
+
+ ////////////////////////////////////
+ // Module Loading
+ ////////////////////////////////////
+ function loadModules(modulesToLoad){
+ var runBlocks = [];
+ forEach(modulesToLoad, function(module) {
+ if (loadedModules.get(module)) return;
+ loadedModules.put(module, true);
+ if (isString(module)) {
+ var moduleFn = angularModule(module);
+ runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
+
+ try {
+ for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
+ var invokeArgs = invokeQueue[i],
+ provider = providerInjector.get(invokeArgs[0]);
+
+ provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
+ }
+ } catch (e) {
+ if (e.message) e.message += ' from ' + module;
+ throw e;
+ }
+ } else if (isFunction(module)) {
+ try {
+ runBlocks.push(providerInjector.invoke(module));
+ } catch (e) {
+ if (e.message) e.message += ' from ' + module;
+ throw e;
+ }
+ } else if (isArray(module)) {
+ try {
+ runBlocks.push(providerInjector.invoke(module));
+ } catch (e) {
+ if (e.message) e.message += ' from ' + String(module[module.length - 1]);
+ throw e;
+ }
+ } else {
+ assertArgFn(module, 'module');
+ }
+ });
+ return runBlocks;
+ }
+
+ ////////////////////////////////////
+ // internal Injector
+ ////////////////////////////////////
+
+ function createInternalInjector(cache, factory) {
+
+ function getService(serviceName) {
+ if (typeof serviceName !== 'string') {
+ throw Error('Service name expected');
+ }
+ if (cache.hasOwnProperty(serviceName)) {
+ if (cache[serviceName] === INSTANTIATING) {
+ throw Error('Circular dependency: ' + path.join(' <- '));
+ }
+ return cache[serviceName];
+ } else {
+ try {
+ path.unshift(serviceName);
+ cache[serviceName] = INSTANTIATING;
+ return cache[serviceName] = factory(serviceName);
+ } finally {
+ path.shift();
+ }
+ }
+ }
+
+ function invoke(fn, self, locals){
+ var args = [],
+ $inject = annotate(fn),
+ length, i,
+ key;
+
+ for(i = 0, length = $inject.length; i < length; i++) {
+ key = $inject[i];
+ args.push(
+ locals && locals.hasOwnProperty(key)
+ ? locals[key]
+ : getService(key)
+ );
+ }
+ if (!fn.$inject) {
+ // this means that we must be an array.
+ fn = fn[length];
+ }
+
+
+ // Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke
+ switch (self ? -1 : args.length) {
+ case 0: return fn();
+ case 1: return fn(args[0]);
+ case 2: return fn(args[0], args[1]);
+ case 3: return fn(args[0], args[1], args[2]);
+ case 4: return fn(args[0], args[1], args[2], args[3]);
+ case 5: return fn(args[0], args[1], args[2], args[3], args[4]);
+ case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]);
+ case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
+ case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
+ case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
+ case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]);
+ default: return fn.apply(self, args);
+ }
+ }
+
+ function instantiate(Type, locals) {
+ var Constructor = function() {},
+ instance, returnedValue;
+
+ // Check if Type is annotated and use just the given function at n-1 as parameter
+ // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
+ Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
+ instance = new Constructor();
+ returnedValue = invoke(Type, instance, locals);
+
+ return isObject(returnedValue) ? returnedValue : instance;
+ }
+
+ return {
+ invoke: invoke,
+ instantiate: instantiate,
+ get: getService,
+ annotate: annotate,
+ has: function(name) {
+ return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
+ }
+ };
+ }
+}
+
+/**
+ * @ngdoc function
+ * @name ng.$anchorScroll
+ * @requires $window
+ * @requires $location
+ * @requires $rootScope
+ *
+ * @description
+ * When called, it checks current value of `$location.hash()` and scroll to related element,
+ * according to rules specified in
+ * {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}.
+ *
+ * It also watches the `$location.hash()` and scroll whenever it changes to match any anchor.
+ * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
+ */
+function $AnchorScrollProvider() {
+
+ var autoScrollingEnabled = true;
+
+ this.disableAutoScrolling = function() {
+ autoScrollingEnabled = false;
+ };
+
+ this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
+ var document = $window.document;
+
+ // helper function to get first anchor from a NodeList
+ // can't use filter.filter, as it accepts only instances of Array
+ // and IE can't convert NodeList to an array using [].slice
+ // TODO(vojta): use filter if we change it to accept lists as well
+ function getFirstAnchor(list) {
+ var result = null;
+ forEach(list, function(element) {
+ if (!result && lowercase(element.nodeName) === 'a') result = element;
+ });
+ return result;
+ }
+
+ function scroll() {
+ var hash = $location.hash(), elm;
+
+ // empty hash, scroll to the top of the page
+ if (!hash) $window.scrollTo(0, 0);
+
+ // element with given id
+ else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
+
+ // first anchor with given name :-D
+ else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
+
+ // no element and hash == 'top', scroll to the top of the page
+ else if (hash === 'top') $window.scrollTo(0, 0);
+ }
+
+ // does not scroll when user clicks on anchor link that is currently on
+ // (no url change, no $location.hash() change), browser native does scroll
+ if (autoScrollingEnabled) {
+ $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
+ function autoScrollWatchAction() {
+ $rootScope.$evalAsync(scroll);
+ });
+ }
+
+ return scroll;
+ }];
+}
+
+
+/**
+ * @ngdoc object
+ * @name ng.$animationProvider
+ * @description
+ *
+ * The $AnimationProvider provider allows developers to register and access custom JavaScript animations directly inside
+ * of a module.
+ *
+ */
+$AnimationProvider.$inject = ['$provide'];
+function $AnimationProvider($provide) {
+ var suffix = 'Animation';
+
+ /**
+ * @ngdoc function
+ * @name ng.$animation#register
+ * @methodOf ng.$animationProvider
+ *
+ * @description
+ * Registers a new injectable animation factory function. The factory function produces the animation object which
+ * has these two properties:
+ *
+ * * `setup`: `function(Element):*` A function which receives the starting state of the element. The purpose
+ * of this function is to get the element ready for animation. Optionally the function returns an memento which
+ * is passed to the `start` function.
+ * * `start`: `function(Element, doneFunction, *)` The element to animate, the `doneFunction` to be called on
+ * element animation completion, and an optional memento from the `setup` function.
+ *
+ * @param {string} name The name of the animation.
+ * @param {function} factory The factory function that will be executed to return the animation object.
+ *
+ */
+ this.register = function(name, factory) {
+ $provide.factory(camelCase(name) + suffix, factory);
+ };
+
+ this.$get = ['$injector', function($injector) {
+ /**
+ * @ngdoc function
+ * @name ng.$animation
+ * @function
+ *
+ * @description
+ * The $animation service is used to retrieve any defined animation functions. When executed, the $animation service
+ * will return a object that contains the setup and start functions that were defined for the animation.
+ *
+ * @param {String} name Name of the animation function to retrieve. Animation functions are registered and stored
+ * inside of the AngularJS DI so a call to $animate('custom') is the same as injecting `customAnimation`
+ * via dependency injection.
+ * @return {Object} the animation object which contains the `setup` and `start` functions that perform the animation.
+ */
+ return function $animation(name) {
+ if (name) {
+ var animationName = camelCase(name) + suffix;
+ if ($injector.has(animationName)) {
+ return $injector.get(animationName);
+ }
+ }
+ };
+ }];
+}
+
+// NOTE: this is a pseudo directive.
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngAnimate
+ *
+ * @description
+ * The `ngAnimate` directive works as an attribute that is attached alongside pre-existing directives.
+ * It effects how the directive will perform DOM manipulation. This allows for complex animations to take place
+ * without burdening the directive which uses the animation with animation details. The built in directives
+ * `ngRepeat`, `ngInclude`, `ngSwitch`, `ngShow`, `ngHide` and `ngView` already accept `ngAnimate` directive.
+ * Custom directives can take advantage of animation through {@link ng.$animator $animator service}.
+ *
+ * Below is a more detailed breakdown of the supported callback events provided by pre-exisitng ng directives:
+ *
+ * | Directive | Supported Animations |
+ * |========================================================== |====================================================|
+ * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move |
+ * | {@link ng.directive:ngView#animations ngView} | enter and leave |
+ * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave |
+ * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave |
+ * | {@link ng.directive:ngIf#animations ngIf} | enter and leave |
+ * | {@link ng.directive:ngShow#animations ngShow & ngHide} | show and hide |
+ *
+ * You can find out more information about animations upon visiting each directive page.
+ *
+ * Below is an example of a directive that makes use of the ngAnimate attribute:
+ *
+ * <pre>
+ * <!-- you can also use data-ng-animate, ng:animate or x-ng-animate as well -->
+ * <ANY ng-directive ng-animate="{event1: 'animation-name', event2: 'animation-name-2'}"></ANY>
+ *
+ * <!-- you can also use a short hand -->
+ * <ANY ng-directive ng-animate=" 'animation' "></ANY>
+ * <!-- which expands to -->
+ * <ANY ng-directive ng-animate="{ enter: 'animation-enter', leave: 'animation-leave', ...}"></ANY>
+ *
+ * <!-- keep in mind that ng-animate can take expressions -->
+ * <ANY ng-directive ng-animate=" computeCurrentAnimation() "></ANY>
+ * </pre>
+ *
+ * The `event1` and `event2` attributes refer to the animation events specific to the directive that has been assigned.
+ *
+ * Keep in mind that if an animation is running, no child element of such animation can also be animated.
+ *
+ * <h2>CSS-defined Animations</h2>
+ * By default, ngAnimate attaches two CSS classes per animation event to the DOM element to achieve the animation.
+ * It is up to you, the developer, to ensure that the animations take place using cross-browser CSS3 transitions as
+ * well as CSS animations.
+ *
+ * The following code below demonstrates how to perform animations using **CSS transitions** with ngAnimate:
+ *
+ * <pre>
+ * <style type="text/css">
+ * /*
+ * The animate-enter CSS class is the event name that you
+ * have provided within the ngAnimate attribute.
+ * */
+ * .animate-enter {
+ * -webkit-transition: 1s linear all; /* Safari/Chrome */
+ * -moz-transition: 1s linear all; /* Firefox */
+ * -o-transition: 1s linear all; /* Opera */
+ * transition: 1s linear all; /* IE10+ and Future Browsers */
+ *
+ * /* The animation preparation code */
+ * opacity: 0;
+ * }
+ *
+ * /*
+ * Keep in mind that you want to combine both CSS
+ * classes together to avoid any CSS-specificity
+ * conflicts
+ * */
+ * .animate-enter.animate-enter-active {
+ * /* The animation code itself */
+ * opacity: 1;
+ * }
+ * </style>
+ *
+ * <div ng-directive ng-animate="{enter: 'animate-enter'}"></div>
+ * </pre>
+ *
+ * The following code below demonstrates how to perform animations using **CSS animations** with ngAnimate:
+ *
+ * <pre>
+ * <style type="text/css">
+ * .animate-enter {
+ * -webkit-animation: enter_sequence 1s linear; /* Safari/Chrome */
+ * -moz-animation: enter_sequence 1s linear; /* Firefox */
+ * -o-animation: enter_sequence 1s linear; /* Opera */
+ * animation: enter_sequence 1s linear; /* IE10+ and Future Browsers */
+ * }
+ * @-webkit-keyframes enter_sequence {
+ * from { opacity:0; }
+ * to { opacity:1; }
+ * }
+ * @-moz-keyframes enter_sequence {
+ * from { opacity:0; }
+ * to { opacity:1; }
+ * }
+ * @-o-keyframes enter_sequence {
+ * from { opacity:0; }
+ * to { opacity:1; }
+ * }
+ * @keyframes enter_sequence {
+ * from { opacity:0; }
+ * to { opacity:1; }
+ * }
+ * </style>
+ *
+ * <div ng-directive ng-animate="{enter: 'animate-enter'}"></div>
+ * </pre>
+ *
+ * ngAnimate will first examine any CSS animation code and then fallback to using CSS transitions.
+ *
+ * Upon DOM mutation, the event class is added first, then the browser is allowed to reflow the content and then,
+ * the active class is added to trigger the animation. The ngAnimate directive will automatically extract the duration
+ * of the animation to determine when the animation ends. Once the animation is over then both CSS classes will be
+ * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end
+ * immediately resulting in a DOM element that is at it's final state. This final state is when the DOM element
+ * has no CSS transition/animation classes surrounding it.
+ *
+ * <h2>JavaScript-defined Animations</h2>
+ * In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations to browsers that do not
+ * yet support them, then you can make use of JavaScript animations defined inside of your AngularJS module.
+ *
+ * <pre>
+ * var ngModule = angular.module('YourApp', []);
+ * ngModule.animation('animate-enter', function() {
+ * return {
+ * setup : function(element) {
+ * //prepare the element for animation
+ * element.css({ 'opacity': 0 });
+ * var memo = "..."; //this value is passed to the start function
+ * return memo;
+ * },
+ * start : function(element, done, memo) {
+ * //start the animation
+ * element.animate({
+ * 'opacity' : 1
+ * }, function() {
+ * //call when the animation is complete
+ * done()
+ * });
+ * }
+ * }
+ * });
+ * </pre>
+ *
+ * As you can see, the JavaScript code follows a similar template to the CSS3 animations. Once defined, the animation
+ * can be used in the same way with the ngAnimate attribute. Keep in mind that, when using JavaScript-enabled
+ * animations, ngAnimate will also add in the same CSS classes that CSS-enabled animations do (even if you're not using
+ * CSS animations) to animated the element, but it will not attempt to find any CSS3 transition or animation duration/delay values.
+ * It will instead close off the animation once the provided done function is executed. So it's important that you
+ * make sure your animations remember to fire off the done function once the animations are complete.
+ *
+ * @param {expression} ngAnimate Used to configure the DOM manipulation animations.
+ *
+ */
+
+var $AnimatorProvider = function() {
+ var NG_ANIMATE_CONTROLLER = '$ngAnimateController';
+ var rootAnimateController = {running:true};
+
+ this.$get = ['$animation', '$window', '$sniffer', '$rootElement', '$rootScope',
+ function($animation, $window, $sniffer, $rootElement, $rootScope) {
+ $rootElement.data(NG_ANIMATE_CONTROLLER, rootAnimateController);
+
+ /**
+ * @ngdoc function
+ * @name ng.$animator
+ * @function
+ *
+ * @description
+ * The $animator.create service provides the DOM manipulation API which is decorated with animations.
+ *
+ * @param {Scope} scope the scope for the ng-animate.
+ * @param {Attributes} attr the attributes object which contains the ngAnimate key / value pair. (The attributes are
+ * passed into the linking function of the directive using the `$animator`.)
+ * @return {object} the animator object which contains the enter, leave, move, show, hide and animate methods.
+ */
+ var AnimatorService = function(scope, attrs) {
+ var animator = {};
+
+ /**
+ * @ngdoc function
+ * @name ng.animator#enter
+ * @methodOf ng.$animator
+ * @function
+ *
+ * @description
+ * Injects the element object into the DOM (inside of the parent element) and then runs the enter animation.
+ *
+ * @param {jQuery/jqLite element} element the element that will be the focus of the enter animation
+ * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the enter animation
+ * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the enter animation
+ */
+ animator.enter = animateActionFactory('enter', insert, noop);
+
+ /**
+ * @ngdoc function
+ * @name ng.animator#leave
+ * @methodOf ng.$animator
+ * @function
+ *
+ * @description
+ * Runs the leave animation operation and, upon completion, removes the element from the DOM.
+ *
+ * @param {jQuery/jqLite element} element the element that will be the focus of the leave animation
+ * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the leave animation
+ */
+ animator.leave = animateActionFactory('leave', noop, remove);
+
+ /**
+ * @ngdoc function
+ * @name ng.animator#move
+ * @methodOf ng.$animator
+ * @function
+ *
+ * @description
+ * Fires the move DOM operation. Just before the animation starts, the animator will either append it into the parent container or
+ * add the element directly after the after element if present. Then the move animation will be run.
+ *
+ * @param {jQuery/jqLite element} element the element that will be the focus of the move animation
+ * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the move animation
+ * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the move animation
+ */
+ animator.move = animateActionFactory('move', move, noop);
+
+ /**
+ * @ngdoc function
+ * @name ng.animator#show
+ * @methodOf ng.$animator
+ * @function
+ *
+ * @description
+ * Reveals the element by setting the CSS property `display` to `block` and then starts the show animation directly after.
+ *
+ * @param {jQuery/jqLite element} element the element that will be rendered visible or hidden
+ */
+ animator.show = animateActionFactory('show', show, noop);
+
+ /**
+ * @ngdoc function
+ * @name ng.animator#hide
+ * @methodOf ng.$animator
+ *
+ * @description
+ * Starts the hide animation first and sets the CSS `display` property to `none` upon completion.
+ *
+ * @param {jQuery/jqLite element} element the element that will be rendered visible or hidden
+ */
+ animator.hide = animateActionFactory('hide', noop, hide);
+
+ /**
+ * @ngdoc function
+ * @name ng.animator#animate
+ * @methodOf ng.$animator
+ *
+ * @description
+ * Triggers a custom animation event to be executed on the given element
+ *
+ * @param {jQuery/jqLite element} element that will be animated
+ */
+ animator.animate = function(event, element) {
+ animateActionFactory(event, noop, noop)(element);
+ }
+ return animator;
+
+ function animateActionFactory(type, beforeFn, afterFn) {
+ return function(element, parent, after) {
+ var ngAnimateValue = scope.$eval(attrs.ngAnimate);
+ var className = ngAnimateValue
+ ? isObject(ngAnimateValue) ? ngAnimateValue[type] : ngAnimateValue + '-' + type
+ : '';
+ var animationPolyfill = $animation(className);
+ var polyfillSetup = animationPolyfill && animationPolyfill.setup;
+ var polyfillStart = animationPolyfill && animationPolyfill.start;
+ var polyfillCancel = animationPolyfill && animationPolyfill.cancel;
+
+ if (!className) {
+ beforeFn(element, parent, after);
+ afterFn(element, parent, after);
+ } else {
+ var activeClassName = className + '-active';
+
+ if (!parent) {
+ parent = after ? after.parent() : element.parent();
+ }
+ if ((!$sniffer.transitions && !polyfillSetup && !polyfillStart) ||
+ (parent.inheritedData(NG_ANIMATE_CONTROLLER) || noop).running) {
+ beforeFn(element, parent, after);
+ afterFn(element, parent, after);
+ return;
+ }
+
+ var animationData = element.data(NG_ANIMATE_CONTROLLER) || {};
+ if(animationData.running) {
+ (polyfillCancel || noop)(element);
+ animationData.done();
+ }
+
+ element.data(NG_ANIMATE_CONTROLLER, {running:true, done:done});
+ element.addClass(className);
+ beforeFn(element, parent, after);
+ if (element.length == 0) return done();
+
+ var memento = (polyfillSetup || noop)(element);
+
+ // $window.setTimeout(beginAnimation, 0); this was causing the element not to animate
+ // keep at 1 for animation dom rerender
+ $window.setTimeout(beginAnimation, 1);
+ }
+
+ function parseMaxTime(str) {
+ var total = 0, values = isString(str) ? str.split(/\s*,\s*/) : [];
+ forEach(values, function(value) {
+ total = Math.max(parseFloat(value) || 0, total);
+ });
+ return total;
+ }
+
+ function beginAnimation() {
+ element.addClass(activeClassName);
+ if (polyfillStart) {
+ polyfillStart(element, done, memento);
+ } else if (isFunction($window.getComputedStyle)) {
+ //one day all browsers will have these properties
+ var w3cAnimationProp = 'animation';
+ var w3cTransitionProp = 'transition';
+
+ //but some still use vendor-prefixed styles
+ var vendorAnimationProp = $sniffer.vendorPrefix + 'Animation';
+ var vendorTransitionProp = $sniffer.vendorPrefix + 'Transition';
+
+ var durationKey = 'Duration',
+ delayKey = 'Delay',
+ animationIterationCountKey = 'IterationCount',
+ duration = 0;
+
+ //we want all the styles defined before and after
+ var ELEMENT_NODE = 1;
+ forEach(element, function(element) {
+ if (element.nodeType == ELEMENT_NODE) {
+ var w3cProp = w3cTransitionProp,
+ vendorProp = vendorTransitionProp,
+ iterations = 1,
+ elementStyles = $window.getComputedStyle(element) || {};
+
+ //use CSS Animations over CSS Transitions
+ if(parseFloat(elementStyles[w3cAnimationProp + durationKey]) > 0 ||
+ parseFloat(elementStyles[vendorAnimationProp + durationKey]) > 0) {
+ w3cProp = w3cAnimationProp;
+ vendorProp = vendorAnimationProp;
+ iterations = Math.max(parseInt(elementStyles[w3cProp + animationIterationCountKey]) || 0,
+ parseInt(elementStyles[vendorProp + animationIterationCountKey]) || 0,
+ iterations);
+ }
+
+ var parsedDelay = Math.max(parseMaxTime(elementStyles[w3cProp + delayKey]),
+ parseMaxTime(elementStyles[vendorProp + delayKey]));
+
+ var parsedDuration = Math.max(parseMaxTime(elementStyles[w3cProp + durationKey]),
+ parseMaxTime(elementStyles[vendorProp + durationKey]));
+
+ duration = Math.max(parsedDelay + (iterations * parsedDuration), duration);
+ }
+ });
+ $window.setTimeout(done, duration * 1000);
+ } else {
+ done();
+ }
+ }
+
+ function done() {
+ if(!done.run) {
+ done.run = true;
+ afterFn(element, parent, after);
+ element.removeClass(className);
+ element.removeClass(activeClassName);
+ element.removeData(NG_ANIMATE_CONTROLLER);
+ }
+ }
+ };
+ }
+
+ function show(element) {
+ element.css('display', '');
+ }
+
+ function hide(element) {
+ element.css('display', 'none');
+ }
+
+ function insert(element, parent, after) {
+ if (after) {
+ after.after(element);
+ } else {
+ parent.append(element);
+ }
+ }
+
+ function remove(element) {
+ element.remove();
+ }
+
+ function move(element, parent, after) {
+ // Do not remove element before insert. Removing will cause data associated with the
+ // element to be dropped. Insert will implicitly do the remove.
+ insert(element, parent, after);
+ }
+ };
+
+ /**
+ * @ngdoc function
+ * @name ng.animator#enabled
+ * @methodOf ng.$animator
+ * @function
+ *
+ * @param {Boolean=} If provided then set the animation on or off.
+ * @return {Boolean} Current animation state.
+ *
+ * @description
+ * Globally enables/disables animations.
+ *
+ */
+ AnimatorService.enabled = function(value) {
+ if (arguments.length) {
+ rootAnimateController.running = !value;
+ }
+ return !rootAnimateController.running;
+ };
+
+ return AnimatorService;
+ }];
+};
+
+/**
+ * ! This is a private undocumented service !
+ *
+ * @name ng.$browser
+ * @requires $log
+ * @description
+ * This object has two goals:
+ *
+ * - hide all the global state in the browser caused by the window object
+ * - abstract away all the browser specific features and inconsistencies
+ *
+ * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
+ * service, which can be used for convenient testing of the application without the interaction with
+ * the real browser apis.
+ */
+/**
+ * @param {object} window The global window object.
+ * @param {object} document jQuery wrapped document.
+ * @param {function()} XHR XMLHttpRequest constructor.
+ * @param {object} $log console.log or an object with the same interface.
+ * @param {object} $sniffer $sniffer service
+ */
+function Browser(window, document, $log, $sniffer) {
+ var self = this,
+ rawDocument = document[0],
+ location = window.location,
+ history = window.history,
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ pendingDeferIds = {};
+
+ self.isMock = false;
+
+ var outstandingRequestCount = 0;
+ var outstandingRequestCallbacks = [];
+
+ // TODO(vojta): remove this temporary api
+ self.$$completeOutstandingRequest = completeOutstandingRequest;
+ self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
+
+ /**
+ * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
+ * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
+ */
+ function completeOutstandingRequest(fn) {
+ try {
+ fn.apply(null, sliceArgs(arguments, 1));
+ } finally {
+ outstandingRequestCount--;
+ if (outstandingRequestCount === 0) {
+ while(outstandingRequestCallbacks.length) {
+ try {
+ outstandingRequestCallbacks.pop()();
+ } catch (e) {
+ $log.error(e);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * @private
+ * Note: this method is used only by scenario runner
+ * TODO(vojta): prefix this method with $$ ?
+ * @param {function()} callback Function that will be called when no outstanding request
+ */
+ self.notifyWhenNoOutstandingRequests = function(callback) {
+ // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
+ // at some deterministic time in respect to the test runner's actions. Leaving things up to the
+ // regular poller would result in flaky tests.
+ forEach(pollFns, function(pollFn){ pollFn(); });
+
+ if (outstandingRequestCount === 0) {
+ callback();
+ } else {
+ outstandingRequestCallbacks.push(callback);
+ }
+ };
+
+ //////////////////////////////////////////////////////////////
+ // Poll Watcher API
+ //////////////////////////////////////////////////////////////
+ var pollFns = [],
+ pollTimeout;
+
+ /**
+ * @name ng.$browser#addPollFn
+ * @methodOf ng.$browser
+ *
+ * @param {function()} fn Poll function to add
+ *
+ * @description
+ * Adds a function to the list of functions that poller periodically executes,
+ * and starts polling if not started yet.
+ *
+ * @returns {function()} the added function
+ */
+ self.addPollFn = function(fn) {
+ if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
+ pollFns.push(fn);
+ return fn;
+ };
+
+ /**
+ * @param {number} interval How often should browser call poll functions (ms)
+ * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
+ *
+ * @description
+ * Configures the poller to run in the specified intervals, using the specified
+ * setTimeout fn and kicks it off.
+ */
+ function startPoller(interval, setTimeout) {
+ (function check() {
+ forEach(pollFns, function(pollFn){ pollFn(); });
+ pollTimeout = setTimeout(check, interval);
+ })();
+ }
+
+ //////////////////////////////////////////////////////////////
+ // URL API
+ //////////////////////////////////////////////////////////////
+
+ var lastBrowserUrl = location.href,
+ baseElement = document.find('base');
+
+ /**
+ * @name ng.$browser#url
+ * @methodOf ng.$browser
+ *
+ * @description
+ * GETTER:
+ * Without any argument, this method just returns current value of location.href.
+ *
+ * SETTER:
+ * With at least one argument, this method sets url to new value.
+ * If html5 history api supported, pushState/replaceState is used, otherwise
+ * location.href/location.replace is used.
+ * Returns its own instance to allow chaining
+ *
+ * NOTE: this api is intended for use only by the $location service. Please use the
+ * {@link ng.$location $location service} to change url.
+ *
+ * @param {string} url New url (when used as setter)
+ * @param {boolean=} replace Should new url replace current history record ?
+ */
+ self.url = function(url, replace) {
+ // setter
+ if (url) {
+ if (lastBrowserUrl == url) return;
+ lastBrowserUrl = url;
+ if ($sniffer.history) {
+ if (replace) history.replaceState(null, '', url);
+ else {
+ history.pushState(null, '', url);
+ // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
+ baseElement.attr('href', baseElement.attr('href'));
+ }
+ } else {
+ if (replace) location.replace(url);
+ else location.href = url;
+ }
+ return self;
+ // getter
+ } else {
+ // the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
+ return location.href.replace(/%27/g,"'");
+ }
+ };
+
+ var urlChangeListeners = [],
+ urlChangeInit = false;
+
+ function fireUrlChange() {
+ if (lastBrowserUrl == self.url()) return;
+
+ lastBrowserUrl = self.url();
+ forEach(urlChangeListeners, function(listener) {
+ listener(self.url());
+ });
+ }
+
+ /**
+ * @name ng.$browser#onUrlChange
+ * @methodOf ng.$browser
+ * @TODO(vojta): refactor to use node's syntax for events
+ *
+ * @description
+ * Register callback function that will be called, when url changes.
+ *
+ * It's only called when the url is changed by outside of angular:
+ * - user types different url into address bar
+ * - user clicks on history (forward/back) button
+ * - user clicks on a link
+ *
+ * It's not called when url is changed by $browser.url() method
+ *
+ * The listener gets called with new url as parameter.
+ *
+ * NOTE: this api is intended for use only by the $location service. Please use the
+ * {@link ng.$location $location service} to monitor url changes in angular apps.
+ *
+ * @param {function(string)} listener Listener function to be called when url changes.
+ * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
+ */
+ self.onUrlChange = function(callback) {
+ if (!urlChangeInit) {
+ // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
+ // don't fire popstate when user change the address bar and don't fire hashchange when url
+ // changed by push/replaceState
+
+ // html5 history api - popstate event
+ if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange);
+ // hashchange event
+ if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange);
+ // polling
+ else self.addPollFn(fireUrlChange);
+
+ urlChangeInit = true;
+ }
+
+ urlChangeListeners.push(callback);
+ return callback;
+ };
+
+ //////////////////////////////////////////////////////////////
+ // Misc API
+ //////////////////////////////////////////////////////////////
+
+ /**
+ * Returns current <base href>
+ * (always relative - without domain)
+ *
+ * @returns {string=}
+ */
+ self.baseHref = function() {
+ var href = baseElement.attr('href');
+ return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : '';
+ };
+
+ //////////////////////////////////////////////////////////////
+ // Cookies API
+ //////////////////////////////////////////////////////////////
+ var lastCookies = {};
+ var lastCookieString = '';
+ var cookiePath = self.baseHref();
+
+ /**
+ * @name ng.$browser#cookies
+ * @methodOf ng.$browser
+ *
+ * @param {string=} name Cookie name
+ * @param {string=} value Cookie value
+ *
+ * @description
+ * The cookies method provides a 'private' low level access to browser cookies.
+ * It is not meant to be used directly, use the $cookie service instead.
+ *
+ * The return values vary depending on the arguments that the method was called with as follows:
+ * <ul>
+ * <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li>
+ * <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li>
+ * <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li>
+ * </ul>
+ *
+ * @returns {Object} Hash of all cookies (if called without any parameter)
+ */
+ self.cookies = function(name, value) {
+ var cookieLength, cookieArray, cookie, i, index;
+
+ if (name) {
+ if (value === undefined) {
+ rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
+ } else {
+ if (isString(value)) {
+ cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1;
+
+ // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
+ // - 300 cookies
+ // - 20 cookies per unique domain
+ // - 4096 bytes per cookie
+ if (cookieLength > 4096) {
+ $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+
+ cookieLength + " > 4096 bytes)!");
+ }
+ }
+ }
+ } else {
+ if (rawDocument.cookie !== lastCookieString) {
+ lastCookieString = rawDocument.cookie;
+ cookieArray = lastCookieString.split("; ");
+ lastCookies = {};
+
+ for (i = 0; i < cookieArray.length; i++) {
+ cookie = cookieArray[i];
+ index = cookie.indexOf('=');
+ if (index > 0) { //ignore nameless cookies
+ var name = unescape(cookie.substring(0, index));
+ // the first value that is seen for a cookie is the most
+ // specific one. values for the same cookie name that
+ // follow are for less specific paths.
+ if (lastCookies[name] === undefined) {
+ lastCookies[name] = unescape(cookie.substring(index + 1));
+ }
+ }
+ }
+ }
+ return lastCookies;
+ }
+ };
+
+
+ /**
+ * @name ng.$browser#defer
+ * @methodOf ng.$browser
+ * @param {function()} fn A function, who's execution should be defered.
+ * @param {number=} [delay=0] of milliseconds to defer the function execution.
+ * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
+ *
+ * @description
+ * Executes a fn asynchronously via `setTimeout(fn, delay)`.
+ *
+ * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
+ * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
+ * via `$browser.defer.flush()`.
+ *
+ */
+ self.defer = function(fn, delay) {
+ var timeoutId;
+ outstandingRequestCount++;
+ timeoutId = setTimeout(function() {
+ delete pendingDeferIds[timeoutId];
+ completeOutstandingRequest(fn);
+ }, delay || 0);
+ pendingDeferIds[timeoutId] = true;
+ return timeoutId;
+ };
+
+
+ /**
+ * @name ng.$browser#defer.cancel
+ * @methodOf ng.$browser.defer
+ *
+ * @description
+ * Cancels a defered task identified with `deferId`.
+ *
+ * @param {*} deferId Token returned by the `$browser.defer` function.
+ * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully canceled.
+ */
+ self.defer.cancel = function(deferId) {
+ if (pendingDeferIds[deferId]) {
+ delete pendingDeferIds[deferId];
+ clearTimeout(deferId);
+ completeOutstandingRequest(noop);
+ return true;
+ }
+ return false;
+ };
+
+}
+
+function $BrowserProvider(){
+ this.$get = ['$window', '$log', '$sniffer', '$document',
+ function( $window, $log, $sniffer, $document){
+ return new Browser($window, $document, $log, $sniffer);
+ }];
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$cacheFactory
+ *
+ * @description
+ * Factory that constructs cache objects.
+ *
+ *
+ * @param {string} cacheId Name or id of the newly created cache.
+ * @param {object=} options Options object that specifies the cache behavior. Properties:
+ *
+ * - `{number=}` `capacity` — turns the cache into LRU cache.
+ *
+ * @returns {object} Newly created cache object with the following set of methods:
+ *
+ * - `{object}` `info()` — Returns id, size, and options of cache.
+ * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns it.
+ * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
+ * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
+ * - `{void}` `removeAll()` — Removes all cached values.
+ * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
+ *
+ */
+function $CacheFactoryProvider() {
+
+ this.$get = function() {
+ var caches = {};
+
+ function cacheFactory(cacheId, options) {
+ if (cacheId in caches) {
+ throw Error('cacheId ' + cacheId + ' taken');
+ }
+
+ var size = 0,
+ stats = extend({}, options, {id: cacheId}),
+ data = {},
+ capacity = (options && options.capacity) || Number.MAX_VALUE,
+ lruHash = {},
+ freshEnd = null,
+ staleEnd = null;
+
+ return caches[cacheId] = {
+
+ put: function(key, value) {
+ var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
+
+ refresh(lruEntry);
+
+ if (isUndefined(value)) return;
+ if (!(key in data)) size++;
+ data[key] = value;
+
+ if (size > capacity) {
+ this.remove(staleEnd.key);
+ }
+
+ return value;
+ },
+
+
+ get: function(key) {
+ var lruEntry = lruHash[key];
+
+ if (!lruEntry) return;
+
+ refresh(lruEntry);
+
+ return data[key];
+ },
+
+
+ remove: function(key) {
+ var lruEntry = lruHash[key];
+
+ if (!lruEntry) return;
+
+ if (lruEntry == freshEnd) freshEnd = lruEntry.p;
+ if (lruEntry == staleEnd) staleEnd = lruEntry.n;
+ link(lruEntry.n,lruEntry.p);
+
+ delete lruHash[key];
+ delete data[key];
+ size--;
+ },
+
+
+ removeAll: function() {
+ data = {};
+ size = 0;
+ lruHash = {};
+ freshEnd = staleEnd = null;
+ },
+
+
+ destroy: function() {
+ data = null;
+ stats = null;
+ lruHash = null;
+ delete caches[cacheId];
+ },
+
+
+ info: function() {
+ return extend({}, stats, {size: size});
+ }
+ };
+
+
+ /**
+ * makes the `entry` the freshEnd of the LRU linked list
+ */
+ function refresh(entry) {
+ if (entry != freshEnd) {
+ if (!staleEnd) {
+ staleEnd = entry;
+ } else if (staleEnd == entry) {
+ staleEnd = entry.n;
+ }
+
+ link(entry.n, entry.p);
+ link(entry, freshEnd);
+ freshEnd = entry;
+ freshEnd.n = null;
+ }
+ }
+
+
+ /**
+ * bidirectionally links two entries of the LRU linked list
+ */
+ function link(nextEntry, prevEntry) {
+ if (nextEntry != prevEntry) {
+ if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
+ if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
+ }
+ }
+ }
+
+
+ cacheFactory.info = function() {
+ var info = {};
+ forEach(caches, function(cache, cacheId) {
+ info[cacheId] = cache.info();
+ });
+ return info;
+ };
+
+
+ cacheFactory.get = function(cacheId) {
+ return caches[cacheId];
+ };
+
+
+ return cacheFactory;
+ };
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$templateCache
+ *
+ * @description
+ * Cache used for storing html templates.
+ *
+ * See {@link ng.$cacheFactory $cacheFactory}.
+ *
+ */
+function $TemplateCacheProvider() {
+ this.$get = ['$cacheFactory', function($cacheFactory) {
+ return $cacheFactory('templates');
+ }];
+}
+
+/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
+ *
+ * DOM-related variables:
+ *
+ * - "node" - DOM Node
+ * - "element" - DOM Element or Node
+ * - "$node" or "$element" - jqLite-wrapped node or element
+ *
+ *
+ * Compiler related stuff:
+ *
+ * - "linkFn" - linking fn of a single directive
+ * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
+ * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
+ * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
+ */
+
+
+var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: ';
+
+
+/**
+ * @ngdoc function
+ * @name ng.$compile
+ * @function
+ *
+ * @description
+ * Compiles a piece of HTML string or DOM into a template and produces a template function, which
+ * can then be used to link {@link ng.$rootScope.Scope scope} and the template together.
+ *
+ * The compilation is a process of walking the DOM tree and trying to match DOM elements to
+ * {@link ng.$compileProvider#directive directives}. For each match it
+ * executes corresponding template function and collects the
+ * instance functions into a single template function which is then returned.
+ *
+ * The template function can then be used once to produce the view or as it is the case with
+ * {@link ng.directive:ngRepeat repeater} many-times, in which
+ * case each call results in a view that is a DOM clone of the original template.
+ *
+ <doc:example module="compile">
+ <doc:source>
+ <script>
+ // declare a new module, and inject the $compileProvider
+ angular.module('compile', [], function($compileProvider) {
+ // configure new 'compile' directive by passing a directive
+ // factory function. The factory function injects the '$compile'
+ $compileProvider.directive('compile', function($compile) {
+ // directive factory creates a link function
+ return function(scope, element, attrs) {
+ scope.$watch(
+ function(scope) {
+ // watch the 'compile' expression for changes
+ return scope.$eval(attrs.compile);
+ },
+ function(value) {
+ // when the 'compile' expression changes
+ // assign it into the current DOM
+ element.html(value);
+
+ // compile the new DOM and link it to the current
+ // scope.
+ // NOTE: we only compile .childNodes so that
+ // we don't get into infinite loop compiling ourselves
+ $compile(element.contents())(scope);
+ }
+ );
+ };
+ })
+ });
+
+ function Ctrl($scope) {
+ $scope.name = 'Angular';
+ $scope.html = 'Hello {{name}}';
+ }
+ </script>
+ <div ng-controller="Ctrl">
+ <input ng-model="name"> <br>
+ <textarea ng-model="html"></textarea> <br>
+ <div compile="html"></div>
+ </div>
+ </doc:source>
+ <doc:scenario>
+ it('should auto compile', function() {
+ expect(element('div[compile]').text()).toBe('Hello Angular');
+ input('html').enter('{{name}}!');
+ expect(element('div[compile]').text()).toBe('Angular!');
+ });
+ </doc:scenario>
+ </doc:example>
+
+ *
+ *
+ * @param {string|DOMElement} element Element or HTML string to compile into a template function.
+ * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
+ * @param {number} maxPriority only apply directives lower then given priority (Only effects the
+ * root element(s), not their children)
+ * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
+ * (a DOM element/tree) to a scope. Where:
+ *
+ * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
+ * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
+ * `template` and call the `cloneAttachFn` function allowing the caller to attach the
+ * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
+ * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
+ *
+ * * `clonedElement` - is a clone of the original `element` passed into the compiler.
+ * * `scope` - is the current scope with which the linking function is working with.
+ *
+ * Calling the linking function returns the element of the template. It is either the original element
+ * passed in, or the clone of the element if the `cloneAttachFn` is provided.
+ *
+ * After linking the view is not updated until after a call to $digest which typically is done by
+ * Angular automatically.
+ *
+ * If you need access to the bound view, there are two ways to do it:
+ *
+ * - If you are not asking the linking function to clone the template, create the DOM element(s)
+ * before you send them to the compiler and keep this reference around.
+ * <pre>
+ * var element = $compile('<p>{{total}}</p>')(scope);
+ * </pre>
+ *
+ * - if on the other hand, you need the element to be cloned, the view reference from the original
+ * example would not point to the clone, but rather to the original template that was cloned. In
+ * this case, you can access the clone via the cloneAttachFn:
+ * <pre>
+ * var templateHTML = angular.element('<p>{{total}}</p>'),
+ * scope = ....;
+ *
+ * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
+ * //attach the clone to DOM document at the right place
+ * });
+ *
+ * //now we have reference to the cloned DOM via `clone`
+ * </pre>
+ *
+ *
+ * For information on how the compiler works, see the
+ * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
+ */
+
+
+/**
+ * @ngdoc service
+ * @name ng.$compileProvider
+ * @function
+ *
+ * @description
+ */
+$CompileProvider.$inject = ['$provide'];
+function $CompileProvider($provide) {
+ var hasDirectives = {},
+ Suffix = 'Directive',
+ COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
+ CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
+ MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ',
+ urlSanitizationWhitelist = /^\s*(https?|ftp|mailto|file):/;
+
+
+ /**
+ * @ngdoc function
+ * @name ng.$compileProvider#directive
+ * @methodOf ng.$compileProvider
+ * @function
+ *
+ * @description
+ * Register a new directives with the compiler.
+ *
+ * @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as
+ * <code>ng-bind</code>).
+ * @param {function} directiveFactory An injectable directive factory function. See {@link guide/directive} for more
+ * info.
+ * @returns {ng.$compileProvider} Self for chaining.
+ */
+ this.directive = function registerDirective(name, directiveFactory) {
+ if (isString(name)) {
+ assertArg(directiveFactory, 'directive');
+ if (!hasDirectives.hasOwnProperty(name)) {
+ hasDirectives[name] = [];
+ $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
+ function($injector, $exceptionHandler) {
+ var directives = [];
+ forEach(hasDirectives[name], function(directiveFactory) {
+ try {
+ var directive = $injector.invoke(directiveFactory);
+ if (isFunction(directive)) {
+ directive = { compile: valueFn(directive) };
+ } else if (!directive.compile && directive.link) {
+ directive.compile = valueFn(directive.link);
+ }
+ directive.priority = directive.priority || 0;
+ directive.name = directive.name || name;
+ directive.require = directive.require || (directive.controller && directive.name);
+ directive.restrict = directive.restrict || 'A';
+ directives.push(directive);
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ });
+ return directives;
+ }]);
+ }
+ hasDirectives[name].push(directiveFactory);
+ } else {
+ forEach(name, reverseParams(registerDirective));
+ }
+ return this;
+ };
+
+
+ /**
+ * @ngdoc function
+ * @name ng.$compileProvider#urlSanitizationWhitelist
+ * @methodOf ng.$compileProvider
+ * @function
+ *
+ * @description
+ * Retrieves or overrides the default regular expression that is used for whitelisting of safe
+ * urls during a[href] sanitization.
+ *
+ * The sanitization is a security measure aimed at prevent XSS attacks via html links.
+ *
+ * Any url about to be assigned to a[href] via data-binding is first normalized and turned into an
+ * absolute url. Afterwards the url is matched against the `urlSanitizationWhitelist` regular
+ * expression. If a match is found the original url is written into the dom. Otherwise the
+ * absolute url is prefixed with `'unsafe:'` string and only then it is written into the DOM.
+ *
+ * @param {RegExp=} regexp New regexp to whitelist urls with.
+ * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
+ * chaining otherwise.
+ */
+ this.urlSanitizationWhitelist = function(regexp) {
+ if (isDefined(regexp)) {
+ urlSanitizationWhitelist = regexp;
+ return this;
+ }
+ return urlSanitizationWhitelist;
+ };
+
+
+ this.$get = [
+ '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
+ '$controller', '$rootScope', '$document',
+ function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
+ $controller, $rootScope, $document) {
+
+ var Attributes = function(element, attr) {
+ this.$$element = element;
+ this.$attr = attr || {};
+ };
+
+ Attributes.prototype = {
+ $normalize: directiveNormalize,
+
+
+ /**
+ * Set a normalized attribute on the element in a way such that all directives
+ * can share the attribute. This function properly handles boolean attributes.
+ * @param {string} key Normalized key. (ie ngAttribute)
+ * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
+ * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
+ * Defaults to true.
+ * @param {string=} attrName Optional none normalized name. Defaults to key.
+ */
+ $set: function(key, value, writeAttr, attrName) {
+ var booleanKey = getBooleanAttrName(this.$$element[0], key),
+ $$observers = this.$$observers,
+ normalizedVal;
+
+ if (booleanKey) {
+ this.$$element.prop(key, value);
+ attrName = booleanKey;
+ }
+
+ this[key] = value;
+
+ // translate normalized key to actual key
+ if (attrName) {
+ this.$attr[key] = attrName;
+ } else {
+ attrName = this.$attr[key];
+ if (!attrName) {
+ this.$attr[key] = attrName = snake_case(key, '-');
+ }
+ }
+
+
+ // sanitize a[href] values
+ if (nodeName_(this.$$element[0]) === 'A' && key === 'href') {
+ urlSanitizationNode.setAttribute('href', value);
+
+ // href property always returns normalized absolute url, so we can match against that
+ normalizedVal = urlSanitizationNode.href;
+ if (!normalizedVal.match(urlSanitizationWhitelist)) {
+ this[key] = value = 'unsafe:' + normalizedVal;
+ }
+ }
+
+
+ if (writeAttr !== false) {
+ if (value === null || value === undefined) {
+ this.$$element.removeAttr(attrName);
+ } else {
+ this.$$element.attr(attrName, value);
+ }
+ }
+
+ // fire observers
+ $$observers && forEach($$observers[key], function(fn) {
+ try {
+ fn(value);
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ });
+ },
+
+
+ /**
+ * Observe an interpolated attribute.
+ * The observer will never be called, if given attribute is not interpolated.
+ *
+ * @param {string} key Normalized key. (ie ngAttribute) .
+ * @param {function(*)} fn Function that will be called whenever the attribute value changes.
+ * @returns {function(*)} the `fn` Function passed in.
+ */
+ $observe: function(key, fn) {
+ var attrs = this,
+ $$observers = (attrs.$$observers || (attrs.$$observers = {})),
+ listeners = ($$observers[key] || ($$observers[key] = []));
+
+ listeners.push(fn);
+ $rootScope.$evalAsync(function() {
+ if (!listeners.$$inter) {
+ // no one registered attribute interpolation function, so lets call it manually
+ fn(attrs[key]);
+ }
+ });
+ return fn;
+ }
+ };
+
+ var urlSanitizationNode = $document[0].createElement('a'),
+ startSymbol = $interpolate.startSymbol(),
+ endSymbol = $interpolate.endSymbol(),
+ denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
+ ? identity
+ : function denormalizeTemplate(template) {
+ return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
+ },
+ NG_ATTR_BINDING = /^ngAttr[A-Z]/;
+
+
+ return compile;
+
+ //================================
+
+ function compile($compileNodes, transcludeFn, maxPriority) {
+ if (!($compileNodes instanceof jqLite)) {
+ // jquery always rewraps, whereas we need to preserve the original selector so that we can modify it.
+ $compileNodes = jqLite($compileNodes);
+ }
+ // We can not compile top level text elements since text nodes can be merged and we will
+ // not be able to attach scope data to them, so we will wrap them in <span>
+ forEach($compileNodes, function(node, index){
+ if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
+ $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
+ }
+ });
+ var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority);
+ return function publicLinkFn(scope, cloneConnectFn){
+ assertArg(scope, 'scope');
+ // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
+ // and sometimes changes the structure of the DOM.
+ var $linkNode = cloneConnectFn
+ ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
+ : $compileNodes;
+
+ // Attach scope only to non-text nodes.
+ for(var i = 0, ii = $linkNode.length; i<ii; i++) {
+ var node = $linkNode[i];
+ if (node.nodeType == 1 /* element */ || node.nodeType == 9 /* document */) {
+ $linkNode.eq(i).data('$scope', scope);
+ }
+ }
+ safeAddClass($linkNode, 'ng-scope');
+ if (cloneConnectFn) cloneConnectFn($linkNode, scope);
+ if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
+ return $linkNode;
+ };
+ }
+
+ function wrongMode(localName, mode) {
+ throw Error("Unsupported '" + mode + "' for '" + localName + "'.");
+ }
+
+ function safeAddClass($element, className) {
+ try {
+ $element.addClass(className);
+ } catch(e) {
+ // ignore, since it means that we are trying to set class on
+ // SVG element, where class name is read-only.
+ }
+ }
+
+ /**
+ * Compile function matches each node in nodeList against the directives. Once all directives
+ * for a particular node are collected their compile functions are executed. The compile
+ * functions return values - the linking functions - are combined into a composite linking
+ * function, which is the a linking function for the node.
+ *
+ * @param {NodeList} nodeList an array of nodes or NodeList to compile
+ * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
+ * scope argument is auto-generated to the new child of the transcluded parent scope.
+ * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then the
+ * rootElement must be set the jqLite collection of the compile root. This is
+ * needed so that the jqLite collection items can be replaced with widgets.
+ * @param {number=} max directive priority
+ * @returns {?function} A composite linking function of all of the matched directives or null.
+ */
+ function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority) {
+ var linkFns = [],
+ nodeLinkFn, childLinkFn, directives, attrs, linkFnFound;
+
+ for(var i = 0; i < nodeList.length; i++) {
+ attrs = new Attributes();
+
+ // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
+ directives = collectDirectives(nodeList[i], [], attrs, maxPriority);
+
+ nodeLinkFn = (directives.length)
+ ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement)
+ : null;
+
+ childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || !nodeList[i].childNodes || !nodeList[i].childNodes.length)
+ ? null
+ : compileNodes(nodeList[i].childNodes,
+ nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
+
+ linkFns.push(nodeLinkFn);
+ linkFns.push(childLinkFn);
+ linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn);
+ }
+
+ // return a linking function if we have found anything, null otherwise
+ return linkFnFound ? compositeLinkFn : null;
+
+ function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
+ var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn, i, ii, n;
+
+ // copy nodeList so that linking doesn't break due to live list updates.
+ var stableNodeList = [];
+ for (i = 0, ii = nodeList.length; i < ii; i++) {
+ stableNodeList.push(nodeList[i]);
+ }
+
+ for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
+ node = stableNodeList[n];
+ nodeLinkFn = linkFns[i++];
+ childLinkFn = linkFns[i++];
+
+ if (nodeLinkFn) {
+ if (nodeLinkFn.scope) {
+ childScope = scope.$new(isObject(nodeLinkFn.scope));
+ jqLite(node).data('$scope', childScope);
+ } else {
+ childScope = scope;
+ }
+ childTranscludeFn = nodeLinkFn.transclude;
+ if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
+ nodeLinkFn(childLinkFn, childScope, node, $rootElement,
+ (function(transcludeFn) {
+ return function(cloneFn) {
+ var transcludeScope = scope.$new();
+ transcludeScope.$$transcluded = true;
+
+ return transcludeFn(transcludeScope, cloneFn).
+ bind('$destroy', bind(transcludeScope, transcludeScope.$destroy));
+ };
+ })(childTranscludeFn || transcludeFn)
+ );
+ } else {
+ nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn);
+ }
+ } else if (childLinkFn) {
+ childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Looks for directives on the given node and adds them to the directive collection which is
+ * sorted.
+ *
+ * @param node Node to search.
+ * @param directives An array to which the directives are added to. This array is sorted before
+ * the function returns.
+ * @param attrs The shared attrs object which is used to populate the normalized attributes.
+ * @param {number=} maxPriority Max directive priority.
+ */
+ function collectDirectives(node, directives, attrs, maxPriority) {
+ var nodeType = node.nodeType,
+ attrsMap = attrs.$attr,
+ match,
+ className;
+
+ switch(nodeType) {
+ case 1: /* Element */
+ // use the node name: <directive>
+ addDirective(directives,
+ directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority);
+
+ // iterate over the attributes
+ for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes,
+ j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
+ attr = nAttrs[j];
+ if (attr.specified) {
+ name = attr.name;
+ // support ngAttr attribute binding
+ ngAttrName = directiveNormalize(name);
+ if (NG_ATTR_BINDING.test(ngAttrName)) {
+ name = ngAttrName.substr(6).toLowerCase();
+ }
+ nName = directiveNormalize(name.toLowerCase());
+ attrsMap[nName] = name;
+ attrs[nName] = value = trim((msie && name == 'href')
+ ? decodeURIComponent(node.getAttribute(name, 2))
+ : attr.value);
+ if (getBooleanAttrName(node, nName)) {
+ attrs[nName] = true; // presence means true
+ }
+ addAttrInterpolateDirective(node, directives, value, nName);
+ addDirective(directives, nName, 'A', maxPriority);
+ }
+ }
+
+ // use class as directive
+ className = node.className;
+ if (isString(className) && className !== '') {
+ while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
+ nName = directiveNormalize(match[2]);
+ if (addDirective(directives, nName, 'C', maxPriority)) {
+ attrs[nName] = trim(match[3]);
+ }
+ className = className.substr(match.index + match[0].length);
+ }
+ }
+ break;
+ case 3: /* Text Node */
+ addTextInterpolateDirective(directives, node.nodeValue);
+ break;
+ case 8: /* Comment */
+ try {
+ match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
+ if (match) {
+ nName = directiveNormalize(match[1]);
+ if (addDirective(directives, nName, 'M', maxPriority)) {
+ attrs[nName] = trim(match[2]);
+ }
+ }
+ } catch (e) {
+ // turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value.
+ // Just ignore it and continue. (Can't seem to reproduce in test case.)
+ }
+ break;
+ }
+
+ directives.sort(byPriority);
+ return directives;
+ }
+
+
+ /**
+ * Once the directives have been collected, their compile functions are executed. This method
+ * is responsible for inlining directive templates as well as terminating the application
+ * of the directives if the terminal directive has been reached.
+ *
+ * @param {Array} directives Array of collected directives to execute their compile function.
+ * this needs to be pre-sorted by priority order.
+ * @param {Node} compileNode The raw DOM node to apply the compile functions to
+ * @param {Object} templateAttrs The shared attribute function
+ * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
+ * scope argument is auto-generated to the new child of the transcluded parent scope.
+ * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
+ * argument has the root jqLite array so that we can replace nodes on it.
+ * @returns linkFn
+ */
+ function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection) {
+ var terminalPriority = -Number.MAX_VALUE,
+ preLinkFns = [],
+ postLinkFns = [],
+ newScopeDirective = null,
+ newIsolateScopeDirective = null,
+ templateDirective = null,
+ $compileNode = templateAttrs.$$element = jqLite(compileNode),
+ directive,
+ directiveName,
+ $template,
+ transcludeDirective,
+ childTranscludeFn = transcludeFn,
+ controllerDirectives,
+ linkFn,
+ directiveValue;
+
+ // executes all directives on the current element
+ for(var i = 0, ii = directives.length; i < ii; i++) {
+ directive = directives[i];
+ $template = undefined;
+
+ if (terminalPriority > directive.priority) {
+ break; // prevent further processing of directives
+ }
+
+ if (directiveValue = directive.scope) {
+ assertNoDuplicate('isolated scope', newIsolateScopeDirective, directive, $compileNode);
+ if (isObject(directiveValue)) {
+ safeAddClass($compileNode, 'ng-isolate-scope');
+ newIsolateScopeDirective = directive;
+ }
+ safeAddClass($compileNode, 'ng-scope');
+ newScopeDirective = newScopeDirective || directive;
+ }
+
+ directiveName = directive.name;
+
+ if (directiveValue = directive.controller) {
+ controllerDirectives = controllerDirectives || {};
+ assertNoDuplicate("'" + directiveName + "' controller",
+ controllerDirectives[directiveName], directive, $compileNode);
+ controllerDirectives[directiveName] = directive;
+ }
+
+ if (directiveValue = directive.transclude) {
+ assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode);
+ transcludeDirective = directive;
+ terminalPriority = directive.priority;
+ if (directiveValue == 'element') {
+ $template = jqLite(compileNode);
+ $compileNode = templateAttrs.$$element =
+ jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' '));
+ compileNode = $compileNode[0];
+ replaceWith(jqCollection, jqLite($template[0]), compileNode);
+ childTranscludeFn = compile($template, transcludeFn, terminalPriority);
+ } else {
+ $template = jqLite(JQLiteClone(compileNode)).contents();
+ $compileNode.html(''); // clear contents
+ childTranscludeFn = compile($template, transcludeFn);
+ }
+ }
+
+ if (directive.template) {
+ assertNoDuplicate('template', templateDirective, directive, $compileNode);
+ templateDirective = directive;
+
+ directiveValue = (isFunction(directive.template))
+ ? directive.template($compileNode, templateAttrs)
+ : directive.template;
+
+ directiveValue = denormalizeTemplate(directiveValue);
+
+ if (directive.replace) {
+ $template = jqLite('<div>' +
+ trim(directiveValue) +
+ '</div>').contents();
+ compileNode = $template[0];
+
+ if ($template.length != 1 || compileNode.nodeType !== 1) {
+ throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue);
+ }
+
+ replaceWith(jqCollection, $compileNode, compileNode);
+
+ var newTemplateAttrs = {$attr: {}};
+
+ // combine directives from the original node and from the template:
+ // - take the array of directives for this element
+ // - split it into two parts, those that were already applied and those that weren't
+ // - collect directives from the template, add them to the second group and sort them
+ // - append the second group with new directives to the first group
+ directives = directives.concat(
+ collectDirectives(
+ compileNode,
+ directives.splice(i + 1, directives.length - (i + 1)),
+ newTemplateAttrs
+ )
+ );
+ mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
+
+ ii = directives.length;
+ } else {
+ $compileNode.html(directiveValue);
+ }
+ }
+
+ if (directive.templateUrl) {
+ assertNoDuplicate('template', templateDirective, directive, $compileNode);
+ templateDirective = directive;
+ nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i),
+ nodeLinkFn, $compileNode, templateAttrs, jqCollection, directive.replace,
+ childTranscludeFn);
+ ii = directives.length;
+ } else if (directive.compile) {
+ try {
+ linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
+ if (isFunction(linkFn)) {
+ addLinkFns(null, linkFn);
+ } else if (linkFn) {
+ addLinkFns(linkFn.pre, linkFn.post);
+ }
+ } catch (e) {
+ $exceptionHandler(e, startingTag($compileNode));
+ }
+ }
+
+ if (directive.terminal) {
+ nodeLinkFn.terminal = true;
+ terminalPriority = Math.max(terminalPriority, directive.priority);
+ }
+
+ }
+
+ nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope;
+ nodeLinkFn.transclude = transcludeDirective && childTranscludeFn;
+
+ // might be normal or delayed nodeLinkFn depending on if templateUrl is present
+ return nodeLinkFn;
+
+ ////////////////////
+
+ function addLinkFns(pre, post) {
+ if (pre) {
+ pre.require = directive.require;
+ preLinkFns.push(pre);
+ }
+ if (post) {
+ post.require = directive.require;
+ postLinkFns.push(post);
+ }
+ }
+
+
+ function getControllers(require, $element) {
+ var value, retrievalMethod = 'data', optional = false;
+ if (isString(require)) {
+ while((value = require.charAt(0)) == '^' || value == '?') {
+ require = require.substr(1);
+ if (value == '^') {
+ retrievalMethod = 'inheritedData';
+ }
+ optional = optional || value == '?';
+ }
+ value = $element[retrievalMethod]('$' + require + 'Controller');
+ if (!value && !optional) {
+ throw Error("No controller: " + require);
+ }
+ return value;
+ } else if (isArray(require)) {
+ value = [];
+ forEach(require, function(require) {
+ value.push(getControllers(require, $element));
+ });
+ }
+ return value;
+ }
+
+
+ function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
+ var attrs, $element, i, ii, linkFn, controller;
+
+ if (compileNode === linkNode) {
+ attrs = templateAttrs;
+ } else {
+ attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
+ }
+ $element = attrs.$$element;
+
+ if (newIsolateScopeDirective) {
+ var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
+
+ var parentScope = scope.$parent || scope;
+
+ forEach(newIsolateScopeDirective.scope, function(definiton, scopeName) {
+ var match = definiton.match(LOCAL_REGEXP) || [],
+ attrName = match[3] || scopeName,
+ optional = (match[2] == '?'),
+ mode = match[1], // @, =, or &
+ lastValue,
+ parentGet, parentSet;
+
+ scope.$$isolateBindings[scopeName] = mode + attrName;
+
+ switch (mode) {
+
+ case '@': {
+ attrs.$observe(attrName, function(value) {
+ scope[scopeName] = value;
+ });
+ attrs.$$observers[attrName].$$scope = parentScope;
+ if( attrs[attrName] ) {
+ // If the attribute has been provided then we trigger an interpolation to ensure the value is there for use in the link fn
+ scope[scopeName] = $interpolate(attrs[attrName])(parentScope);
+ }
+ break;
+ }
+
+ case '=': {
+ if (optional && !attrs[attrName]) {
+ return;
+ }
+ parentGet = $parse(attrs[attrName]);
+ parentSet = parentGet.assign || function() {
+ // reset the change, or we will throw this exception on every $digest
+ lastValue = scope[scopeName] = parentGet(parentScope);
+ throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] +
+ ' (directive: ' + newIsolateScopeDirective.name + ')');
+ };
+ lastValue = scope[scopeName] = parentGet(parentScope);
+ scope.$watch(function parentValueWatch() {
+ var parentValue = parentGet(parentScope);
+
+ if (parentValue !== scope[scopeName]) {
+ // we are out of sync and need to copy
+ if (parentValue !== lastValue) {
+ // parent changed and it has precedence
+ lastValue = scope[scopeName] = parentValue;
+ } else {
+ // if the parent can be assigned then do so
+ parentSet(parentScope, parentValue = lastValue = scope[scopeName]);
+ }
+ }
+ return parentValue;
+ });
+ break;
+ }
+
+ case '&': {
+ parentGet = $parse(attrs[attrName]);
+ scope[scopeName] = function(locals) {
+ return parentGet(parentScope, locals);
+ };
+ break;
+ }
+
+ default: {
+ throw Error('Invalid isolate scope definition for directive ' +
+ newIsolateScopeDirective.name + ': ' + definiton);
+ }
+ }
+ });
+ }
+
+ if (controllerDirectives) {
+ forEach(controllerDirectives, function(directive) {
+ var locals = {
+ $scope: scope,
+ $element: $element,
+ $attrs: attrs,
+ $transclude: boundTranscludeFn
+ };
+
+ controller = directive.controller;
+ if (controller == '@') {
+ controller = attrs[directive.name];
+ }
+
+ $element.data(
+ '$' + directive.name + 'Controller',
+ $controller(controller, locals));
+ });
+ }
+
+ // PRELINKING
+ for(i = 0, ii = preLinkFns.length; i < ii; i++) {
+ try {
+ linkFn = preLinkFns[i];
+ linkFn(scope, $element, attrs,
+ linkFn.require && getControllers(linkFn.require, $element));
+ } catch (e) {
+ $exceptionHandler(e, startingTag($element));
+ }
+ }
+
+ // RECURSION
+ childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn);
+
+ // POSTLINKING
+ for(i = 0, ii = postLinkFns.length; i < ii; i++) {
+ try {
+ linkFn = postLinkFns[i];
+ linkFn(scope, $element, attrs,
+ linkFn.require && getControllers(linkFn.require, $element));
+ } catch (e) {
+ $exceptionHandler(e, startingTag($element));
+ }
+ }
+ }
+ }
+
+
+ /**
+ * looks up the directive and decorates it with exception handling and proper parameters. We
+ * call this the boundDirective.
+ *
+ * @param {string} name name of the directive to look up.
+ * @param {string} location The directive must be found in specific format.
+ * String containing any of theses characters:
+ *
+ * * `E`: element name
+ * * `A': attribute
+ * * `C`: class
+ * * `M`: comment
+ * @returns true if directive was added.
+ */
+ function addDirective(tDirectives, name, location, maxPriority) {
+ var match = false;
+ if (hasDirectives.hasOwnProperty(name)) {
+ for(var directive, directives = $injector.get(name + Suffix),
+ i = 0, ii = directives.length; i<ii; i++) {
+ try {
+ directive = directives[i];
+ if ( (maxPriority === undefined || maxPriority > directive.priority) &&
+ directive.restrict.indexOf(location) != -1) {
+ tDirectives.push(directive);
+ match = true;
+ }
+ } catch(e) { $exceptionHandler(e); }
+ }
+ }
+ return match;
+ }
+
+
+ /**
+ * When the element is replaced with HTML template then the new attributes
+ * on the template need to be merged with the existing attributes in the DOM.
+ * The desired effect is to have both of the attributes present.
+ *
+ * @param {object} dst destination attributes (original DOM)
+ * @param {object} src source attributes (from the directive template)
+ */
+ function mergeTemplateAttributes(dst, src) {
+ var srcAttr = src.$attr,
+ dstAttr = dst.$attr,
+ $element = dst.$$element;
+
+ // reapply the old attributes to the new element
+ forEach(dst, function(value, key) {
+ if (key.charAt(0) != '$') {
+ if (src[key]) {
+ value += (key === 'style' ? ';' : ' ') + src[key];
+ }
+ dst.$set(key, value, true, srcAttr[key]);
+ }
+ });
+
+ // copy the new attributes on the old attrs object
+ forEach(src, function(value, key) {
+ if (key == 'class') {
+ safeAddClass($element, value);
+ dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
+ } else if (key == 'style') {
+ $element.attr('style', $element.attr('style') + ';' + value);
+ } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
+ dst[key] = value;
+ dstAttr[key] = srcAttr[key];
+ }
+ });
+ }
+
+
+ function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs,
+ $rootElement, replace, childTranscludeFn) {
+ var linkQueue = [],
+ afterTemplateNodeLinkFn,
+ afterTemplateChildLinkFn,
+ beforeTemplateCompileNode = $compileNode[0],
+ origAsyncDirective = directives.shift(),
+ // The fact that we have to copy and patch the directive seems wrong!
+ derivedSyncDirective = extend({}, origAsyncDirective, {
+ controller: null, templateUrl: null, transclude: null, scope: null
+ }),
+ templateUrl = (isFunction(origAsyncDirective.templateUrl))
+ ? origAsyncDirective.templateUrl($compileNode, tAttrs)
+ : origAsyncDirective.templateUrl;
+
+ $compileNode.html('');
+
+ $http.get(templateUrl, {cache: $templateCache}).
+ success(function(content) {
+ var compileNode, tempTemplateAttrs, $template;
+
+ content = denormalizeTemplate(content);
+
+ if (replace) {
+ $template = jqLite('<div>' + trim(content) + '</div>').contents();
+ compileNode = $template[0];
+
+ if ($template.length != 1 || compileNode.nodeType !== 1) {
+ throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content);
+ }
+
+ tempTemplateAttrs = {$attr: {}};
+ replaceWith($rootElement, $compileNode, compileNode);
+ collectDirectives(compileNode, directives, tempTemplateAttrs);
+ mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
+ } else {
+ compileNode = beforeTemplateCompileNode;
+ $compileNode.html(content);
+ }
+
+ directives.unshift(derivedSyncDirective);
+ afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn);
+ afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
+
+
+ while(linkQueue.length) {
+ var scope = linkQueue.shift(),
+ beforeTemplateLinkNode = linkQueue.shift(),
+ linkRootElement = linkQueue.shift(),
+ controller = linkQueue.shift(),
+ linkNode = compileNode;
+
+ if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
+ // it was cloned therefore we have to clone as well.
+ linkNode = JQLiteClone(compileNode);
+ replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
+ }
+
+ afterTemplateNodeLinkFn(function() {
+ beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller);
+ }, scope, linkNode, $rootElement, controller);
+ }
+ linkQueue = null;
+ }).
+ error(function(response, code, headers, config) {
+ throw Error('Failed to load template: ' + config.url);
+ });
+
+ return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) {
+ if (linkQueue) {
+ linkQueue.push(scope);
+ linkQueue.push(node);
+ linkQueue.push(rootElement);
+ linkQueue.push(controller);
+ } else {
+ afterTemplateNodeLinkFn(function() {
+ beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller);
+ }, scope, node, rootElement, controller);
+ }
+ };
+ }
+
+
+ /**
+ * Sorting function for bound directives.
+ */
+ function byPriority(a, b) {
+ return b.priority - a.priority;
+ }
+
+
+ function assertNoDuplicate(what, previousDirective, directive, element) {
+ if (previousDirective) {
+ throw Error('Multiple directives [' + previousDirective.name + ', ' +
+ directive.name + '] asking for ' + what + ' on: ' + startingTag(element));
+ }
+ }
+
+
+ function addTextInterpolateDirective(directives, text) {
+ var interpolateFn = $interpolate(text, true);
+ if (interpolateFn) {
+ directives.push({
+ priority: 0,
+ compile: valueFn(function textInterpolateLinkFn(scope, node) {
+ var parent = node.parent(),
+ bindings = parent.data('$binding') || [];
+ bindings.push(interpolateFn);
+ safeAddClass(parent.data('$binding', bindings), 'ng-binding');
+ scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
+ node[0].nodeValue = value;
+ });
+ })
+ });
+ }
+ }
+
+
+ function addAttrInterpolateDirective(node, directives, value, name) {
+ var interpolateFn = $interpolate(value, true);
+
+ // no interpolation found -> ignore
+ if (!interpolateFn) return;
+
+
+ directives.push({
+ priority: 100,
+ compile: valueFn(function attrInterpolateLinkFn(scope, element, attr) {
+ var $$observers = (attr.$$observers || (attr.$$observers = {}));
+
+ // we need to interpolate again, in case the attribute value has been updated
+ // (e.g. by another directive's compile function)
+ interpolateFn = $interpolate(attr[name], true);
+
+ // if attribute was updated so that there is no interpolation going on we don't want to
+ // register any observers
+ if (!interpolateFn) return;
+
+ attr[name] = interpolateFn(scope);
+ ($$observers[name] || ($$observers[name] = [])).$$inter = true;
+ (attr.$$observers && attr.$$observers[name].$$scope || scope).
+ $watch(interpolateFn, function interpolateFnWatchAction(value) {
+ attr.$set(name, value);
+ });
+ })
+ });
+ }
+
+
+ /**
+ * This is a special jqLite.replaceWith, which can replace items which
+ * have no parents, provided that the containing jqLite collection is provided.
+ *
+ * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
+ * in the root of the tree.
+ * @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell,
+ * but replace its DOM node reference.
+ * @param {Node} newNode The new DOM node.
+ */
+ function replaceWith($rootElement, $element, newNode) {
+ var oldNode = $element[0],
+ parent = oldNode.parentNode,
+ i, ii;
+
+ if ($rootElement) {
+ for(i = 0, ii = $rootElement.length; i < ii; i++) {
+ if ($rootElement[i] == oldNode) {
+ $rootElement[i] = newNode;
+ break;
+ }
+ }
+ }
+
+ if (parent) {
+ parent.replaceChild(newNode, oldNode);
+ }
+
+ newNode[jqLite.expando] = oldNode[jqLite.expando];
+ $element[0] = newNode;
+ }
+ }];
+}
+
+var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
+/**
+ * Converts all accepted directives format into proper directive name.
+ * All of these will become 'myDirective':
+ * my:DiRective
+ * my-directive
+ * x-my-directive
+ * data-my:directive
+ *
+ * Also there is special case for Moz prefix starting with upper case letter.
+ * @param name Name to normalize
+ */
+function directiveNormalize(name) {
+ return camelCase(name.replace(PREFIX_REGEXP, ''));
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$compile.directive.Attributes
+ * @description
+ *
+ * A shared object between directive compile / linking functions which contains normalized DOM element
+ * attributes. The the values reflect current binding state `{{ }}`. The normalization is needed
+ * since all of these are treated as equivalent in Angular:
+ *
+ * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
+ */
+
+/**
+ * @ngdoc property
+ * @name ng.$compile.directive.Attributes#$attr
+ * @propertyOf ng.$compile.directive.Attributes
+ * @returns {object} A map of DOM element attribute names to the normalized name. This is
+ * needed to do reverse lookup from normalized name back to actual name.
+ */
+
+
+/**
+ * @ngdoc function
+ * @name ng.$compile.directive.Attributes#$set
+ * @methodOf ng.$compile.directive.Attributes
+ * @function
+ *
+ * @description
+ * Set DOM element attribute value.
+ *
+ *
+ * @param {string} name Normalized element attribute name of the property to modify. The name is
+ * revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
+ * property to the original name.
+ * @param {string} value Value to set the attribute to. The value can be an interpolated string.
+ */
+
+
+
+/**
+ * Closure compiler type information
+ */
+
+function nodesetLinkingFn(
+ /* angular.Scope */ scope,
+ /* NodeList */ nodeList,
+ /* Element */ rootElement,
+ /* function(Function) */ boundTranscludeFn
+){}
+
+function directiveLinkingFn(
+ /* nodesetLinkingFn */ nodesetLinkingFn,
+ /* angular.Scope */ scope,
+ /* Node */ node,
+ /* Element */ rootElement,
+ /* function(Function) */ boundTranscludeFn
+){}
+
+/**
+ * @ngdoc object
+ * @name ng.$controllerProvider
+ * @description
+ * The {@link ng.$controller $controller service} is used by Angular to create new
+ * controllers.
+ *
+ * This provider allows controller registration via the
+ * {@link ng.$controllerProvider#register register} method.
+ */
+function $ControllerProvider() {
+ var controllers = {},
+ CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
+
+
+ /**
+ * @ngdoc function
+ * @name ng.$controllerProvider#register
+ * @methodOf ng.$controllerProvider
+ * @param {string} name Controller name
+ * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
+ * annotations in the array notation).
+ */
+ this.register = function(name, constructor) {
+ if (isObject(name)) {
+ extend(controllers, name)
+ } else {
+ controllers[name] = constructor;
+ }
+ };
+
+
+ this.$get = ['$injector', '$window', function($injector, $window) {
+
+ /**
+ * @ngdoc function
+ * @name ng.$controller
+ * @requires $injector
+ *
+ * @param {Function|string} constructor If called with a function then it's considered to be the
+ * controller constructor function. Otherwise it's considered to be a string which is used
+ * to retrieve the controller constructor using the following steps:
+ *
+ * * check if a controller with given name is registered via `$controllerProvider`
+ * * check if evaluating the string on the current scope returns a constructor
+ * * check `window[constructor]` on the global `window` object
+ *
+ * @param {Object} locals Injection locals for Controller.
+ * @return {Object} Instance of given controller.
+ *
+ * @description
+ * `$controller` service is responsible for instantiating controllers.
+ *
+ * It's just a simple call to {@link AUTO.$injector $injector}, but extracted into
+ * a service, so that one can override this service with {@link https://gist.github.com/1649788
+ * BC version}.
+ */
+ return function(expression, locals) {
+ var instance, match, constructor, identifier;
+
+ if(isString(expression)) {
+ match = expression.match(CNTRL_REG),
+ constructor = match[1],
+ identifier = match[3];
+ expression = controllers.hasOwnProperty(constructor)
+ ? controllers[constructor]
+ : getter(locals.$scope, constructor, true) || getter($window, constructor, true);
+
+ assertArgFn(expression, constructor, true);
+ }
+
+ instance = $injector.instantiate(expression, locals);
+
+ if (identifier) {
+ if (typeof locals.$scope !== 'object') {
+ throw new Error('Can not export controller as "' + identifier + '". ' +
+ 'No scope object provided!');
+ }
+
+ locals.$scope[identifier] = instance;
+ }
+
+ return instance;
+ };
+ }];
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$document
+ * @requires $window
+ *
+ * @description
+ * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document`
+ * element.
+ */
+function $DocumentProvider(){
+ this.$get = ['$window', function(window){
+ return jqLite(window.document);
+ }];
+}
+
+/**
+ * @ngdoc function
+ * @name ng.$exceptionHandler
+ * @requires $log
+ *
+ * @description
+ * Any uncaught exception in angular expressions is delegated to this service.
+ * The default implementation simply delegates to `$log.error` which logs it into
+ * the browser console.
+ *
+ * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
+ * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
+ *
+ * @param {Error} exception Exception associated with the error.
+ * @param {string=} cause optional information about the context in which
+ * the error was thrown.
+ *
+ */
+function $ExceptionHandlerProvider() {
+ this.$get = ['$log', function($log) {
+ return function(exception, cause) {
+ $log.error.apply($log, arguments);
+ };
+ }];
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$interpolateProvider
+ * @function
+ *
+ * @description
+ *
+ * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
+ */
+function $InterpolateProvider() {
+ var startSymbol = '{{';
+ var endSymbol = '}}';
+
+ /**
+ * @ngdoc method
+ * @name ng.$interpolateProvider#startSymbol
+ * @methodOf ng.$interpolateProvider
+ * @description
+ * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
+ *
+ * @param {string=} value new value to set the starting symbol to.
+ * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
+ */
+ this.startSymbol = function(value){
+ if (value) {
+ startSymbol = value;
+ return this;
+ } else {
+ return startSymbol;
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name ng.$interpolateProvider#endSymbol
+ * @methodOf ng.$interpolateProvider
+ * @description
+ * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
+ *
+ * @param {string=} value new value to set the ending symbol to.
+ * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
+ */
+ this.endSymbol = function(value){
+ if (value) {
+ endSymbol = value;
+ return this;
+ } else {
+ return endSymbol;
+ }
+ };
+
+
+ this.$get = ['$parse', '$exceptionHandler', function($parse, $exceptionHandler) {
+ var startSymbolLength = startSymbol.length,
+ endSymbolLength = endSymbol.length;
+
+ /**
+ * @ngdoc function
+ * @name ng.$interpolate
+ * @function
+ *
+ * @requires $parse
+ *
+ * @description
+ *
+ * Compiles a string with markup into an interpolation function. This service is used by the
+ * HTML {@link ng.$compile $compile} service for data binding. See
+ * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
+ * interpolation markup.
+ *
+ *
+ <pre>
+ var $interpolate = ...; // injected
+ var exp = $interpolate('Hello {{name}}!');
+ expect(exp({name:'Angular'}).toEqual('Hello Angular!');
+ </pre>
+ *
+ *
+ * @param {string} text The text with markup to interpolate.
+ * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
+ * embedded expression in order to return an interpolation function. Strings with no
+ * embedded expression will return null for the interpolation function.
+ * @returns {function(context)} an interpolation function which is used to compute the interpolated
+ * string. The function has these parameters:
+ *
+ * * `context`: an object against which any expressions embedded in the strings are evaluated
+ * against.
+ *
+ */
+ function $interpolate(text, mustHaveExpression) {
+ var startIndex,
+ endIndex,
+ index = 0,
+ parts = [],
+ length = text.length,
+ hasInterpolation = false,
+ fn,
+ exp,
+ concat = [];
+
+ while(index < length) {
+ if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
+ ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
+ (index != startIndex) && parts.push(text.substring(index, startIndex));
+ parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
+ fn.exp = exp;
+ index = endIndex + endSymbolLength;
+ hasInterpolation = true;
+ } else {
+ // we did not find anything, so we have to add the remainder to the parts array
+ (index != length) && parts.push(text.substring(index));
+ index = length;
+ }
+ }
+
+ if (!(length = parts.length)) {
+ // we added, nothing, must have been an empty string.
+ parts.push('');
+ length = 1;
+ }
+
+ if (!mustHaveExpression || hasInterpolation) {
+ concat.length = length;
+ fn = function(context) {
+ try {
+ for(var i = 0, ii = length, part; i<ii; i++) {
+ if (typeof (part = parts[i]) == 'function') {
+ part = part(context);
+ if (part == null || part == undefined) {
+ part = '';
+ } else if (typeof part != 'string') {
+ part = toJson(part);
+ }
+ }
+ concat[i] = part;
+ }
+ return concat.join('');
+ }
+ catch(err) {
+ var newErr = new Error('Error while interpolating: ' + text + '\n' + err.toString());
+ $exceptionHandler(newErr);
+ }
+ };
+ fn.exp = text;
+ fn.parts = parts;
+ return fn;
+ }
+ }
+
+
+ /**
+ * @ngdoc method
+ * @name ng.$interpolate#startSymbol
+ * @methodOf ng.$interpolate
+ * @description
+ * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
+ *
+ * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change
+ * the symbol.
+ *
+ * @returns {string} start symbol.
+ */
+ $interpolate.startSymbol = function() {
+ return startSymbol;
+ }
+
+
+ /**
+ * @ngdoc method
+ * @name ng.$interpolate#endSymbol
+ * @methodOf ng.$interpolate
+ * @description
+ * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
+ *
+ * Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change
+ * the symbol.
+ *
+ * @returns {string} start symbol.
+ */
+ $interpolate.endSymbol = function() {
+ return endSymbol;
+ }
+
+ return $interpolate;
+ }];
+}
+
+var SERVER_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,
+ PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
+ DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
+
+
+/**
+ * Encode path using encodeUriSegment, ignoring forward slashes
+ *
+ * @param {string} path Path to encode
+ * @returns {string}
+ */
+function encodePath(path) {
+ var segments = path.split('/'),
+ i = segments.length;
+
+ while (i--) {
+ segments[i] = encodeUriSegment(segments[i]);
+ }
+
+ return segments.join('/');
+}
+
+function matchUrl(url, obj) {
+ var match = SERVER_MATCH.exec(url);
+
+ obj.$$protocol = match[1];
+ obj.$$host = match[3];
+ obj.$$port = int(match[5]) || DEFAULT_PORTS[match[1]] || null;
+}
+
+function matchAppUrl(url, obj) {
+ var match = PATH_MATCH.exec(url);
+
+ obj.$$path = decodeURIComponent(match[1]);
+ obj.$$search = parseKeyValue(match[3]);
+ obj.$$hash = decodeURIComponent(match[5] || '');
+
+ // make sure path starts with '/';
+ if (obj.$$path && obj.$$path.charAt(0) != '/') obj.$$path = '/' + obj.$$path;
+}
+
+
+function composeProtocolHostPort(protocol, host, port) {
+ return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port);
+}
+
+/**
+ *
+ * @param {string} begin
+ * @param {string} whole
+ * @param {string} otherwise
+ * @returns {string} returns text from whole after begin or otherwise if it does not begin with expected string.
+ */
+function beginsWith(begin, whole, otherwise) {
+ return whole.indexOf(begin) == 0 ? whole.substr(begin.length) : otherwise;
+}
+
+
+function stripHash(url) {
+ var index = url.indexOf('#');
+ return index == -1 ? url : url.substr(0, index);
+}
+
+
+function stripFile(url) {
+ return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
+}
+
+/* return the server only */
+function serverBase(url) {
+ return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
+}
+
+
+/**
+ * LocationHtml5Url represents an url
+ * This object is exposed as $location service when HTML5 mode is enabled and supported
+ *
+ * @constructor
+ * @param {string} appBase application base URL
+ * @param {string} basePrefix url path prefix
+ */
+function LocationHtml5Url(appBase, basePrefix) {
+ basePrefix = basePrefix || '';
+ var appBaseNoFile = stripFile(appBase);
+ /**
+ * Parse given html5 (regular) url string into properties
+ * @param {string} newAbsoluteUrl HTML5 url
+ * @private
+ */
+ this.$$parse = function(url) {
+ var parsed = {}
+ matchUrl(url, parsed);
+ var pathUrl = beginsWith(appBaseNoFile, url);
+ if (!isString(pathUrl)) {
+ throw Error('Invalid url "' + url + '", missing path prefix "' + appBaseNoFile + '".');
+ }
+ matchAppUrl(pathUrl, parsed);
+ extend(this, parsed);
+ if (!this.$$path) {
+ this.$$path = '/';
+ }
+
+ this.$$compose();
+ };
+
+ /**
+ * Compose url and update `absUrl` property
+ * @private
+ */
+ this.$$compose = function() {
+ var search = toKeyValue(this.$$search),
+ hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
+
+ this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
+ this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
+ };
+
+ this.$$rewrite = function(url) {
+ var appUrl, prevAppUrl;
+
+ if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
+ prevAppUrl = appUrl;
+ if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
+ return appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
+ } else {
+ return appBase + prevAppUrl;
+ }
+ } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
+ return appBaseNoFile + appUrl;
+ } else if (appBaseNoFile == url + '/') {
+ return appBaseNoFile;
+ }
+ }
+}
+
+
+/**
+ * LocationHashbangUrl represents url
+ * This object is exposed as $location service when html5 history api is disabled or not supported
+ *
+ * @constructor
+ * @param {string} appBase application base URL
+ * @param {string} hashPrefix hashbang prefix
+ */
+function LocationHashbangUrl(appBase, hashPrefix) {
+ var appBaseNoFile = stripFile(appBase);
+
+ /**
+ * Parse given hashbang url into properties
+ * @param {string} url Hashbang url
+ * @private
+ */
+ this.$$parse = function(url) {
+ matchUrl(url, this);
+ var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
+ if (!isString(withoutBaseUrl)) {
+ throw new Error('Invalid url "' + url + '", does not start with "' + appBase + '".');
+ }
+ var withoutHashUrl = withoutBaseUrl.charAt(0) == '#' ? beginsWith(hashPrefix, withoutBaseUrl) : withoutBaseUrl;
+ if (!isString(withoutHashUrl)) {
+ throw new Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '".');
+ }
+ matchAppUrl(withoutHashUrl, this);
+ this.$$compose();
+ };
+
+ /**
+ * Compose hashbang url and update `absUrl` property
+ * @private
+ */
+ this.$$compose = function() {
+ var search = toKeyValue(this.$$search),
+ hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
+
+ this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
+ this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
+ };
+
+ this.$$rewrite = function(url) {
+ if(stripHash(appBase) == stripHash(url)) {
+ return url;
+ }
+ }
+}
+
+
+/**
+ * LocationHashbangUrl represents url
+ * This object is exposed as $location service when html5 history api is enabled but the browser
+ * does not support it.
+ *
+ * @constructor
+ * @param {string} appBase application base URL
+ * @param {string} hashPrefix hashbang prefix
+ */
+function LocationHashbangInHtml5Url(appBase, hashPrefix) {
+ LocationHashbangUrl.apply(this, arguments);
+
+ var appBaseNoFile = stripFile(appBase);
+
+ this.$$rewrite = function(url) {
+ var appUrl;
+
+ if ( appBase == stripHash(url) ) {
+ return url;
+ } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
+ return appBase + hashPrefix + appUrl;
+ } else if ( appBaseNoFile === url + '/') {
+ return appBaseNoFile;
+ }
+ }
+}
+
+
+LocationHashbangInHtml5Url.prototype =
+ LocationHashbangUrl.prototype =
+ LocationHtml5Url.prototype = {
+
+ /**
+ * Has any change been replacing ?
+ * @private
+ */
+ $$replace: false,
+
+ /**
+ * @ngdoc method
+ * @name ng.$location#absUrl
+ * @methodOf ng.$location
+ *
+ * @description
+ * This method is getter only.
+ *
+ * Return full url representation with all segments encoded according to rules specified in
+ * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}.
+ *
+ * @return {string} full url
+ */
+ absUrl: locationGetter('$$absUrl'),
+
+ /**
+ * @ngdoc method
+ * @name ng.$location#url
+ * @methodOf ng.$location
+ *
+ * @description
+ * This method is getter / setter.
+ *
+ * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
+ *
+ * Change path, search and hash, when called with parameter and return `$location`.
+ *
+ * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
+ * @return {string} url
+ */
+ url: function(url, replace) {
+ if (isUndefined(url))
+ return this.$$url;
+
+ var match = PATH_MATCH.exec(url);
+ if (match[1]) this.path(decodeURIComponent(match[1]));
+ if (match[2] || match[1]) this.search(match[3] || '');
+ this.hash(match[5] || '', replace);
+
+ return this;
+ },
+
+ /**
+ * @ngdoc method
+ * @name ng.$location#protocol
+ * @methodOf ng.$location
+ *
+ * @description
+ * This method is getter only.
+ *
+ * Return protocol of current url.
+ *
+ * @return {string} protocol of current url
+ */
+ protocol: locationGetter('$$protocol'),
+
+ /**
+ * @ngdoc method
+ * @name ng.$location#host
+ * @methodOf ng.$location
+ *
+ * @description
+ * This method is getter only.
+ *
+ * Return host of current url.
+ *
+ * @return {string} host of current url.
+ */
+ host: locationGetter('$$host'),
+
+ /**
+ * @ngdoc method
+ * @name ng.$location#port
+ * @methodOf ng.$location
+ *
+ * @description
+ * This method is getter only.
+ *
+ * Return port of current url.
+ *
+ * @return {Number} port
+ */
+ port: locationGetter('$$port'),
+
+ /**
+ * @ngdoc method
+ * @name ng.$location#path
+ * @methodOf ng.$location
+ *
+ * @description
+ * This method is getter / setter.
+ *
+ * Return path of current url when called without any parameter.
+ *
+ * Change path when called with parameter and return `$location`.
+ *
+ * Note: Path should always begin with forward slash (/), this method will add the forward slash
+ * if it is missing.
+ *
+ * @param {string=} path New path
+ * @return {string} path
+ */
+ path: locationGetterSetter('$$path', function(path) {
+ return path.charAt(0) == '/' ? path : '/' + path;
+ }),
+
+ /**
+ * @ngdoc method
+ * @name ng.$location#search
+ * @methodOf ng.$location
+ *
+ * @description
+ * This method is getter / setter.
+ *
+ * Return search part (as object) of current url when called without any parameter.
+ *
+ * Change search part when called with parameter and return `$location`.
+ *
+ * @param {string|object<string,string>=} search New search params - string or hash object
+ * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a
+ * single search parameter. If the value is `null`, the parameter will be deleted.
+ *
+ * @return {string} search
+ */
+ search: function(search, paramValue) {
+ if (isUndefined(search))
+ return this.$$search;
+
+ if (isDefined(paramValue)) {
+ if (paramValue === null) {
+ delete this.$$search[search];
+ } else {
+ this.$$search[search] = paramValue;
+ }
+ } else {
+ this.$$search = isString(search) ? parseKeyValue(search) : search;
+ }
+
+ this.$$compose();
+ return this;
+ },
+
+ /**
+ * @ngdoc method
+ * @name ng.$location#hash
+ * @methodOf ng.$location
+ *
+ * @description
+ * This method is getter / setter.
+ *
+ * Return hash fragment when called without any parameter.
+ *
+ * Change hash fragment when called with parameter and return `$location`.
+ *
+ * @param {string=} hash New hash fragment
+ * @return {string} hash
+ */
+ hash: locationGetterSetter('$$hash', identity),
+
+ /**
+ * @ngdoc method
+ * @name ng.$location#replace
+ * @methodOf ng.$location
+ *
+ * @description
+ * If called, all changes to $location during current `$digest` will be replacing current history
+ * record, instead of adding new one.
+ */
+ replace: function() {
+ this.$$replace = true;
+ return this;
+ }
+};
+
+function locationGetter(property) {
+ return function() {
+ return this[property];
+ };
+}
+
+
+function locationGetterSetter(property, preprocess) {
+ return function(value) {
+ if (isUndefined(value))
+ return this[property];
+
+ this[property] = preprocess(value);
+ this.$$compose();
+
+ return this;
+ };
+}
+
+
+/**
+ * @ngdoc object
+ * @name ng.$location
+ *
+ * @requires $browser
+ * @requires $sniffer
+ * @requires $rootElement
+ *
+ * @description
+ * The $location service parses the URL in the browser address bar (based on the
+ * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL
+ * available to your application. Changes to the URL in the address bar are reflected into
+ * $location service and changes to $location are reflected into the browser address bar.
+ *
+ * **The $location service:**
+ *
+ * - Exposes the current URL in the browser address bar, so you can
+ * - Watch and observe the URL.
+ * - Change the URL.
+ * - Synchronizes the URL with the browser when the user
+ * - Changes the address bar.
+ * - Clicks the back or forward button (or clicks a History link).
+ * - Clicks on a link.
+ * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
+ *
+ * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
+ * Services: Using $location}
+ */
+
+/**
+ * @ngdoc object
+ * @name ng.$locationProvider
+ * @description
+ * Use the `$locationProvider` to configure how the application deep linking paths are stored.
+ */
+function $LocationProvider(){
+ var hashPrefix = '',
+ html5Mode = false;
+
+ /**
+ * @ngdoc property
+ * @name ng.$locationProvider#hashPrefix
+ * @methodOf ng.$locationProvider
+ * @description
+ * @param {string=} prefix Prefix for hash part (containing path and search)
+ * @returns {*} current value if used as getter or itself (chaining) if used as setter
+ */
+ this.hashPrefix = function(prefix) {
+ if (isDefined(prefix)) {
+ hashPrefix = prefix;
+ return this;
+ } else {
+ return hashPrefix;
+ }
+ };
+
+ /**
+ * @ngdoc property
+ * @name ng.$locationProvider#html5Mode
+ * @methodOf ng.$locationProvider
+ * @description
+ * @param {string=} mode Use HTML5 strategy if available.
+ * @returns {*} current value if used as getter or itself (chaining) if used as setter
+ */
+ this.html5Mode = function(mode) {
+ if (isDefined(mode)) {
+ html5Mode = mode;
+ return this;
+ } else {
+ return html5Mode;
+ }
+ };
+
+ this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
+ function( $rootScope, $browser, $sniffer, $rootElement) {
+ var $location,
+ LocationMode,
+ baseHref = $browser.baseHref(),
+ initialUrl = $browser.url(),
+ appBase;
+
+ if (html5Mode) {
+ appBase = baseHref ? serverBase(initialUrl) + baseHref : initialUrl;
+ LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
+ } else {
+ appBase = stripHash(initialUrl);
+ LocationMode = LocationHashbangUrl;
+ }
+ $location = new LocationMode(appBase, '#' + hashPrefix);
+ $location.$$parse($location.$$rewrite(initialUrl));
+
+ $rootElement.bind('click', function(event) {
+ // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
+ // currently we open nice url link and redirect then
+
+ if (event.ctrlKey || event.metaKey || event.which == 2) return;
+
+ var elm = jqLite(event.target);
+
+ // traverse the DOM up to find first A tag
+ while (lowercase(elm[0].nodeName) !== 'a') {
+ // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
+ if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
+ }
+
+ var absHref = elm.prop('href');
+ var rewrittenUrl = $location.$$rewrite(absHref);
+
+ if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) {
+ event.preventDefault();
+ if (rewrittenUrl != $browser.url()) {
+ // update location manually
+ $location.$$parse(rewrittenUrl);
+ $rootScope.$apply();
+ // hack to work around FF6 bug 684208 when scenario runner clicks on links
+ window.angular['ff-684208-preventDefault'] = true;
+ }
+ }
+ });
+
+
+ // rewrite hashbang url <> html5 url
+ if ($location.absUrl() != initialUrl) {
+ $browser.url($location.absUrl(), true);
+ }
+
+ // update $location when $browser url changes
+ $browser.onUrlChange(function(newUrl) {
+ if ($location.absUrl() != newUrl) {
+ if ($rootScope.$broadcast('$locationChangeStart', newUrl, $location.absUrl()).defaultPrevented) {
+ $browser.url($location.absUrl());
+ return;
+ }
+ $rootScope.$evalAsync(function() {
+ var oldUrl = $location.absUrl();
+
+ $location.$$parse(newUrl);
+ afterLocationChange(oldUrl);
+ });
+ if (!$rootScope.$$phase) $rootScope.$digest();
+ }
+ });
+
+ // update browser
+ var changeCounter = 0;
+ $rootScope.$watch(function $locationWatch() {
+ var oldUrl = $browser.url();
+ var currentReplace = $location.$$replace;
+
+ if (!changeCounter || oldUrl != $location.absUrl()) {
+ changeCounter++;
+ $rootScope.$evalAsync(function() {
+ if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
+ defaultPrevented) {
+ $location.$$parse(oldUrl);
+ } else {
+ $browser.url($location.absUrl(), currentReplace);
+ afterLocationChange(oldUrl);
+ }
+ });
+ }
+ $location.$$replace = false;
+
+ return changeCounter;
+ });
+
+ return $location;
+
+ function afterLocationChange(oldUrl) {
+ $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
+ }
+}];
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$log
+ * @requires $window
+ *
+ * @description
+ * Simple service for logging. Default implementation writes the message
+ * into the browser's console (if present).
+ *
+ * The main purpose of this service is to simplify debugging and troubleshooting.
+ *
+ * @example
+ <example>
+ <file name="script.js">
+ function LogCtrl($scope, $log) {
+ $scope.$log = $log;
+ $scope.message = 'Hello World!';
+ }
+ </file>
+ <file name="index.html">
+ <div ng-controller="LogCtrl">
+ <p>Reload this page with open console, enter text and hit the log button...</p>
+ Message:
+ <input type="text" ng-model="message"/>
+ <button ng-click="$log.log(message)">log</button>
+ <button ng-click="$log.warn(message)">warn</button>
+ <button ng-click="$log.info(message)">info</button>
+ <button ng-click="$log.error(message)">error</button>
+ </div>
+ </file>
+ </example>
+ */
+
+/**
+ * @ngdoc object
+ * @name ng.$logProvider
+ * @description
+ * Use the `$logProvider` to configure how the application logs messages
+ */
+function $LogProvider(){
+ var debug = true,
+ self = this;
+
+ /**
+ * @ngdoc property
+ * @name ng.$logProvider#debugEnabled
+ * @methodOf ng.$logProvider
+ * @description
+ * @param {string=} flag enable or disable debug level messages
+ * @returns {*} current value if used as getter or itself (chaining) if used as setter
+ */
+ this.debugEnabled = function(flag) {
+ if (isDefined(flag)) {
+ debug = flag;
+ return this;
+ } else {
+ return debug;
+ }
+ };
+
+ this.$get = ['$window', function($window){
+ return {
+ /**
+ * @ngdoc method
+ * @name ng.$log#log
+ * @methodOf ng.$log
+ *
+ * @description
+ * Write a log message
+ */
+ log: consoleLog('log'),
+
+ /**
+ * @ngdoc method
+ * @name ng.$log#warn
+ * @methodOf ng.$log
+ *
+ * @description
+ * Write a warning message
+ */
+ warn: consoleLog('warn'),
+
+ /**
+ * @ngdoc method
+ * @name ng.$log#info
+ * @methodOf ng.$log
+ *
+ * @description
+ * Write an information message
+ */
+ info: consoleLog('info'),
+
+ /**
+ * @ngdoc method
+ * @name ng.$log#error
+ * @methodOf ng.$log
+ *
+ * @description
+ * Write an error message
+ */
+ error: consoleLog('error'),
+
+ /**
+ * @ngdoc method
+ * @name ng.$log#debug
+ * @methodOf ng.$log
+ *
+ * @description
+ * Write a debug message
+ */
+ debug: (function () {
+ var fn = consoleLog('debug');
+
+ return function() {
+ if (debug) {
+ fn.apply(self, arguments);
+ }
+ }
+ }())
+ };
+
+ function formatError(arg) {
+ if (arg instanceof Error) {
+ if (arg.stack) {
+ arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
+ ? 'Error: ' + arg.message + '\n' + arg.stack
+ : arg.stack;
+ } else if (arg.sourceURL) {
+ arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
+ }
+ }
+ return arg;
+ }
+
+ function consoleLog(type) {
+ var console = $window.console || {},
+ logFn = console[type] || console.log || noop;
+
+ if (logFn.apply) {
+ return function() {
+ var args = [];
+ forEach(arguments, function(arg) {
+ args.push(formatError(arg));
+ });
+ return logFn.apply(console, args);
+ };
+ }
+
+ // we are IE which either doesn't have window.console => this is noop and we do nothing,
+ // or we are IE where console.log doesn't have apply so we log at least first 2 args
+ return function(arg1, arg2) {
+ logFn(arg1, arg2);
+ }
+ }
+ }];
+}
+
+var OPERATORS = {
+ 'null':function(){return null;},
+ 'true':function(){return true;},
+ 'false':function(){return false;},
+ undefined:noop,
+ '+':function(self, locals, a,b){
+ a=a(self, locals); b=b(self, locals);
+ if (isDefined(a)) {
+ if (isDefined(b)) {
+ return a + b;
+ }
+ return a;
+ }
+ return isDefined(b)?b:undefined;},
+ '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);},
+ '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
+ '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
+ '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
+ '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
+ '=':noop,
+ '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
+ '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
+ '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
+ '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
+ '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
+ '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
+ '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
+ '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
+ '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
+ '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
+ '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
+// '|':function(self, locals, a,b){return a|b;},
+ '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
+ '!':function(self, locals, a){return !a(self, locals);}
+};
+var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
+
+function lex(text, csp){
+ var tokens = [],
+ token,
+ index = 0,
+ json = [],
+ ch,
+ lastCh = ':'; // can start regexp
+
+ while (index < text.length) {
+ ch = text.charAt(index);
+ if (is('"\'')) {
+ readString(ch);
+ } else if (isNumber(ch) || is('.') && isNumber(peek())) {
+ readNumber();
+ } else if (isIdent(ch)) {
+ readIdent();
+ // identifiers can only be if the preceding char was a { or ,
+ if (was('{,') && json[0]=='{' &&
+ (token=tokens[tokens.length-1])) {
+ token.json = token.text.indexOf('.') == -1;
+ }
+ } else if (is('(){}[].,;:?')) {
+ tokens.push({
+ index:index,
+ text:ch,
+ json:(was(':[,') && is('{[')) || is('}]:,')
+ });
+ if (is('{[')) json.unshift(ch);
+ if (is('}]')) json.shift();
+ index++;
+ } else if (isWhitespace(ch)) {
+ index++;
+ continue;
+ } else {
+ var ch2 = ch + peek(),
+ ch3 = ch2 + peek(2),
+ fn = OPERATORS[ch],
+ fn2 = OPERATORS[ch2],
+ fn3 = OPERATORS[ch3];
+ if (fn3) {
+ tokens.push({index:index, text:ch3, fn:fn3});
+ index += 3;
+ } else if (fn2) {
+ tokens.push({index:index, text:ch2, fn:fn2});
+ index += 2;
+ } else if (fn) {
+ tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')});
+ index += 1;
+ } else {
+ throwError("Unexpected next character ", index, index+1);
+ }
+ }
+ lastCh = ch;
+ }
+ return tokens;
+
+ function is(chars) {
+ return chars.indexOf(ch) != -1;
+ }
+
+ function was(chars) {
+ return chars.indexOf(lastCh) != -1;
+ }
+
+ function peek(i) {
+ var num = i || 1;
+ return index + num < text.length ? text.charAt(index + num) : false;
+ }
+ function isNumber(ch) {
+ return '0' <= ch && ch <= '9';
+ }
+ function isWhitespace(ch) {
+ return ch == ' ' || ch == '\r' || ch == '\t' ||
+ ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0
+ }
+ function isIdent(ch) {
+ return 'a' <= ch && ch <= 'z' ||
+ 'A' <= ch && ch <= 'Z' ||
+ '_' == ch || ch == '$';
+ }
+ function isExpOperator(ch) {
+ return ch == '-' || ch == '+' || isNumber(ch);
+ }
+
+ function throwError(error, start, end) {
+ end = end || index;
+ throw Error("Lexer Error: " + error + " at column" +
+ (isDefined(start)
+ ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]"
+ : " " + end) +
+ " in expression [" + text + "].");
+ }
+
+ function readNumber() {
+ var number = "";
+ var start = index;
+ while (index < text.length) {
+ var ch = lowercase(text.charAt(index));
+ if (ch == '.' || isNumber(ch)) {
+ number += ch;
+ } else {
+ var peekCh = peek();
+ if (ch == 'e' && isExpOperator(peekCh)) {
+ number += ch;
+ } else if (isExpOperator(ch) &&
+ peekCh && isNumber(peekCh) &&
+ number.charAt(number.length - 1) == 'e') {
+ number += ch;
+ } else if (isExpOperator(ch) &&
+ (!peekCh || !isNumber(peekCh)) &&
+ number.charAt(number.length - 1) == 'e') {
+ throwError('Invalid exponent');
+ } else {
+ break;
+ }
+ }
+ index++;
+ }
+ number = 1 * number;
+ tokens.push({index:start, text:number, json:true,
+ fn:function() {return number;}});
+ }
+ function readIdent() {
+ var ident = "",
+ start = index,
+ lastDot, peekIndex, methodName, ch;
+
+ while (index < text.length) {
+ ch = text.charAt(index);
+ if (ch == '.' || isIdent(ch) || isNumber(ch)) {
+ if (ch == '.') lastDot = index;
+ ident += ch;
+ } else {
+ break;
+ }
+ index++;
+ }
+
+ //check if this is not a method invocation and if it is back out to last dot
+ if (lastDot) {
+ peekIndex = index;
+ while(peekIndex < text.length) {
+ ch = text.charAt(peekIndex);
+ if (ch == '(') {
+ methodName = ident.substr(lastDot - start + 1);
+ ident = ident.substr(0, lastDot - start);
+ index = peekIndex;
+ break;
+ }
+ if(isWhitespace(ch)) {
+ peekIndex++;
+ } else {
+ break;
+ }
+ }
+ }
+
+
+ var token = {
+ index:start,
+ text:ident
+ };
+
+ if (OPERATORS.hasOwnProperty(ident)) {
+ token.fn = token.json = OPERATORS[ident];
+ } else {
+ var getter = getterFn(ident, csp);
+ token.fn = extend(function(self, locals) {
+ return (getter(self, locals));
+ }, {
+ assign: function(self, value) {
+ return setter(self, ident, value);
+ }
+ });
+ }
+
+ tokens.push(token);
+
+ if (methodName) {
+ tokens.push({
+ index:lastDot,
+ text: '.',
+ json: false
+ });
+ tokens.push({
+ index: lastDot + 1,
+ text: methodName,
+ json: false
+ });
+ }
+ }
+
+ function readString(quote) {
+ var start = index;
+ index++;
+ var string = "";
+ var rawString = quote;
+ var escape = false;
+ while (index < text.length) {
+ var ch = text.charAt(index);
+ rawString += ch;
+ if (escape) {
+ if (ch == 'u') {
+ var hex = text.substring(index + 1, index + 5);
+ if (!hex.match(/[\da-f]{4}/i))
+ throwError( "Invalid unicode escape [\\u" + hex + "]");
+ index += 4;
+ string += String.fromCharCode(parseInt(hex, 16));
+ } else {
+ var rep = ESCAPE[ch];
+ if (rep) {
+ string += rep;
+ } else {
+ string += ch;
+ }
+ }
+ escape = false;
+ } else if (ch == '\\') {
+ escape = true;
+ } else if (ch == quote) {
+ index++;
+ tokens.push({
+ index:start,
+ text:rawString,
+ string:string,
+ json:true,
+ fn:function() { return string; }
+ });
+ return;
+ } else {
+ string += ch;
+ }
+ index++;
+ }
+ throwError("Unterminated quote", start);
+ }
+}
+
+/////////////////////////////////////////
+
+function parser(text, json, $filter, csp){
+ var ZERO = valueFn(0),
+ value,
+ tokens = lex(text, csp),
+ assignment = _assignment,
+ functionCall = _functionCall,
+ fieldAccess = _fieldAccess,
+ objectIndex = _objectIndex,
+ filterChain = _filterChain;
+
+ if(json){
+ // The extra level of aliasing is here, just in case the lexer misses something, so that
+ // we prevent any accidental execution in JSON.
+ assignment = logicalOR;
+ functionCall =
+ fieldAccess =
+ objectIndex =
+ filterChain =
+ function() { throwError("is not valid json", {text:text, index:0}); };
+ value = primary();
+ } else {
+ value = statements();
+ }
+ if (tokens.length !== 0) {
+ throwError("is an unexpected token", tokens[0]);
+ }
+ value.literal = !!value.literal;
+ value.constant = !!value.constant;
+ return value;
+
+ ///////////////////////////////////
+ function throwError(msg, token) {
+ throw Error("Syntax Error: Token '" + token.text +
+ "' " + msg + " at column " +
+ (token.index + 1) + " of the expression [" +
+ text + "] starting at [" + text.substring(token.index) + "].");
+ }
+
+ function peekToken() {
+ if (tokens.length === 0)
+ throw Error("Unexpected end of expression: " + text);
+ return tokens[0];
+ }
+
+ function peek(e1, e2, e3, e4) {
+ if (tokens.length > 0) {
+ var token = tokens[0];
+ var t = token.text;
+ if (t==e1 || t==e2 || t==e3 || t==e4 ||
+ (!e1 && !e2 && !e3 && !e4)) {
+ return token;
+ }
+ }
+ return false;
+ }
+
+ function expect(e1, e2, e3, e4){
+ var token = peek(e1, e2, e3, e4);
+ if (token) {
+ if (json && !token.json) {
+ throwError("is not valid json", token);
+ }
+ tokens.shift();
+ return token;
+ }
+ return false;
+ }
+
+ function consume(e1){
+ if (!expect(e1)) {
+ throwError("is unexpected, expecting [" + e1 + "]", peek());
+ }
+ }
+
+ function unaryFn(fn, right) {
+ return extend(function(self, locals) {
+ return fn(self, locals, right);
+ }, {
+ constant:right.constant
+ });
+ }
+
+ function ternaryFn(left, middle, right){
+ return extend(function(self, locals){
+ return left(self, locals) ? middle(self, locals) : right(self, locals);
+ }, {
+ constant: left.constant && middle.constant && right.constant
+ });
+ }
+
+ function binaryFn(left, fn, right) {
+ return extend(function(self, locals) {
+ return fn(self, locals, left, right);
+ }, {
+ constant:left.constant && right.constant
+ });
+ }
+
+ function statements() {
+ var statements = [];
+ while(true) {
+ if (tokens.length > 0 && !peek('}', ')', ';', ']'))
+ statements.push(filterChain());
+ if (!expect(';')) {
+ // optimize for the common case where there is only one statement.
+ // TODO(size): maybe we should not support multiple statements?
+ return statements.length == 1
+ ? statements[0]
+ : function(self, locals){
+ var value;
+ for ( var i = 0; i < statements.length; i++) {
+ var statement = statements[i];
+ if (statement)
+ value = statement(self, locals);
+ }
+ return value;
+ };
+ }
+ }
+ }
+
+ function _filterChain() {
+ var left = expression();
+ var token;
+ while(true) {
+ if ((token = expect('|'))) {
+ left = binaryFn(left, token.fn, filter());
+ } else {
+ return left;
+ }
+ }
+ }
+
+ function filter() {
+ var token = expect();
+ var fn = $filter(token.text);
+ var argsFn = [];
+ while(true) {
+ if ((token = expect(':'))) {
+ argsFn.push(expression());
+ } else {
+ var fnInvoke = function(self, locals, input){
+ var args = [input];
+ for ( var i = 0; i < argsFn.length; i++) {
+ args.push(argsFn[i](self, locals));
+ }
+ return fn.apply(self, args);
+ };
+ return function() {
+ return fnInvoke;
+ };
+ }
+ }
+ }
+
+ function expression() {
+ return assignment();
+ }
+
+ function _assignment() {
+ var left = ternary();
+ var right;
+ var token;
+ if ((token = expect('='))) {
+ if (!left.assign) {
+ throwError("implies assignment but [" +
+ text.substring(0, token.index) + "] can not be assigned to", token);
+ }
+ right = ternary();
+ return function(scope, locals){
+ return left.assign(scope, right(scope, locals), locals);
+ };
+ } else {
+ return left;
+ }
+ }
+
+ function ternary() {
+ var left = logicalOR();
+ var middle;
+ var token;
+ if((token = expect('?'))){
+ middle = ternary();
+ if((token = expect(':'))){
+ return ternaryFn(left, middle, ternary());
+ }
+ else {
+ throwError('expected :', token);
+ }
+ }
+ else {
+ return left;
+ }
+ }
+
+ function logicalOR() {
+ var left = logicalAND();
+ var token;
+ while(true) {
+ if ((token = expect('||'))) {
+ left = binaryFn(left, token.fn, logicalAND());
+ } else {
+ return left;
+ }
+ }
+ }
+
+ function logicalAND() {
+ var left = equality();
+ var token;
+ if ((token = expect('&&'))) {
+ left = binaryFn(left, token.fn, logicalAND());
+ }
+ return left;
+ }
+
+ function equality() {
+ var left = relational();
+ var token;
+ if ((token = expect('==','!=','===','!=='))) {
+ left = binaryFn(left, token.fn, equality());
+ }
+ return left;
+ }
+
+ function relational() {
+ var left = additive();
+ var token;
+ if ((token = expect('<', '>', '<=', '>='))) {
+ left = binaryFn(left, token.fn, relational());
+ }
+ return left;
+ }
+
+ function additive() {
+ var left = multiplicative();
+ var token;
+ while ((token = expect('+','-'))) {
+ left = binaryFn(left, token.fn, multiplicative());
+ }
+ return left;
+ }
+
+ function multiplicative() {
+ var left = unary();
+ var token;
+ while ((token = expect('*','/','%'))) {
+ left = binaryFn(left, token.fn, unary());
+ }
+ return left;
+ }
+
+ function unary() {
+ var token;
+ if (expect('+')) {
+ return primary();
+ } else if ((token = expect('-'))) {
+ return binaryFn(ZERO, token.fn, unary());
+ } else if ((token = expect('!'))) {
+ return unaryFn(token.fn, unary());
+ } else {
+ return primary();
+ }
+ }
+
+
+ function primary() {
+ var primary;
+ if (expect('(')) {
+ primary = filterChain();
+ consume(')');
+ } else if (expect('[')) {
+ primary = arrayDeclaration();
+ } else if (expect('{')) {
+ primary = object();
+ } else {
+ var token = expect();
+ primary = token.fn;
+ if (!primary) {
+ throwError("not a primary expression", token);
+ }
+ if (token.json) {
+ primary.constant = primary.literal = true;
+ }
+ }
+
+ var next, context;
+ while ((next = expect('(', '[', '.'))) {
+ if (next.text === '(') {
+ primary = functionCall(primary, context);
+ context = null;
+ } else if (next.text === '[') {
+ context = primary;
+ primary = objectIndex(primary);
+ } else if (next.text === '.') {
+ context = primary;
+ primary = fieldAccess(primary);
+ } else {
+ throwError("IMPOSSIBLE");
+ }
+ }
+ return primary;
+ }
+
+ function _fieldAccess(object) {
+ var field = expect().text;
+ var getter = getterFn(field, csp);
+ return extend(
+ function(scope, locals, self) {
+ return getter(self || object(scope, locals), locals);
+ },
+ {
+ assign:function(scope, value, locals) {
+ return setter(object(scope, locals), field, value);
+ }
+ }
+ );
+ }
+
+ function _objectIndex(obj) {
+ var indexFn = expression();
+ consume(']');
+ return extend(
+ function(self, locals){
+ var o = obj(self, locals),
+ i = indexFn(self, locals),
+ v, p;
+
+ if (!o) return undefined;
+ v = o[i];
+ if (v && v.then) {
+ p = v;
+ if (!('$$v' in v)) {
+ p.$$v = undefined;
+ p.then(function(val) { p.$$v = val; });
+ }
+ v = v.$$v;
+ }
+ return v;
+ }, {
+ assign:function(self, value, locals){
+ return obj(self, locals)[indexFn(self, locals)] = value;
+ }
+ });
+ }
+
+ function _functionCall(fn, contextGetter) {
+ var argsFn = [];
+ if (peekToken().text != ')') {
+ do {
+ argsFn.push(expression());
+ } while (expect(','));
+ }
+ consume(')');
+ return function(scope, locals){
+ var args = [],
+ context = contextGetter ? contextGetter(scope, locals) : scope;
+
+ for ( var i = 0; i < argsFn.length; i++) {
+ args.push(argsFn[i](scope, locals));
+ }
+ var fnPtr = fn(scope, locals, context) || noop;
+ // IE stupidity!
+ return fnPtr.apply
+ ? fnPtr.apply(context, args)
+ : fnPtr(args[0], args[1], args[2], args[3], args[4]);
+ };
+ }
+
+ // This is used with json array declaration
+ function arrayDeclaration () {
+ var elementFns = [];
+ var allConstant = true;
+ if (peekToken().text != ']') {
+ do {
+ var elementFn = expression();
+ elementFns.push(elementFn);
+ if (!elementFn.constant) {
+ allConstant = false;
+ }
+ } while (expect(','));
+ }
+ consume(']');
+ return extend(function(self, locals){
+ var array = [];
+ for ( var i = 0; i < elementFns.length; i++) {
+ array.push(elementFns[i](self, locals));
+ }
+ return array;
+ }, {
+ literal:true,
+ constant:allConstant
+ });
+ }
+
+ function object () {
+ var keyValues = [];
+ var allConstant = true;
+ if (peekToken().text != '}') {
+ do {
+ var token = expect(),
+ key = token.string || token.text;
+ consume(":");
+ var value = expression();
+ keyValues.push({key:key, value:value});
+ if (!value.constant) {
+ allConstant = false;
+ }
+ } while (expect(','));
+ }
+ consume('}');
+ return extend(function(self, locals){
+ var object = {};
+ for ( var i = 0; i < keyValues.length; i++) {
+ var keyValue = keyValues[i];
+ object[keyValue.key] = keyValue.value(self, locals);
+ }
+ return object;
+ }, {
+ literal:true,
+ constant:allConstant
+ });
+ }
+}
+
+//////////////////////////////////////////////////
+// Parser helper functions
+//////////////////////////////////////////////////
+
+function setter(obj, path, setValue) {
+ var element = path.split('.');
+ for (var i = 0; element.length > 1; i++) {
+ var key = element.shift();
+ var propertyObj = obj[key];
+ if (!propertyObj) {
+ propertyObj = {};
+ obj[key] = propertyObj;
+ }
+ obj = propertyObj;
+ }
+ obj[element.shift()] = setValue;
+ return setValue;
+}
+
+/**
+ * Return the value accessible from the object by path. Any undefined traversals are ignored
+ * @param {Object} obj starting object
+ * @param {string} path path to traverse
+ * @param {boolean=true} bindFnToScope
+ * @returns value as accessible by path
+ */
+//TODO(misko): this function needs to be removed
+function getter(obj, path, bindFnToScope) {
+ if (!path) return obj;
+ var keys = path.split('.');
+ var key;
+ var lastInstance = obj;
+ var len = keys.length;
+
+ for (var i = 0; i < len; i++) {
+ key = keys[i];
+ if (obj) {
+ obj = (lastInstance = obj)[key];
+ }
+ }
+ if (!bindFnToScope && isFunction(obj)) {
+ return bind(lastInstance, obj);
+ }
+ return obj;
+}
+
+var getterFnCache = {};
+
+/**
+ * Implementation of the "Black Hole" variant from:
+ * - http://jsperf.com/angularjs-parse-getter/4
+ * - http://jsperf.com/path-evaluation-simplified/7
+ */
+function cspSafeGetterFn(key0, key1, key2, key3, key4) {
+ return function(scope, locals) {
+ var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
+ promise;
+
+ if (pathVal === null || pathVal === undefined) return pathVal;
+
+ pathVal = pathVal[key0];
+ if (pathVal && pathVal.then) {
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+ if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
+
+ pathVal = pathVal[key1];
+ if (pathVal && pathVal.then) {
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+ if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
+
+ pathVal = pathVal[key2];
+ if (pathVal && pathVal.then) {
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+ if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
+
+ pathVal = pathVal[key3];
+ if (pathVal && pathVal.then) {
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+ if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
+
+ pathVal = pathVal[key4];
+ if (pathVal && pathVal.then) {
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+ return pathVal;
+ };
+}
+
+function getterFn(path, csp) {
+ if (getterFnCache.hasOwnProperty(path)) {
+ return getterFnCache[path];
+ }
+
+ var pathKeys = path.split('.'),
+ pathKeysLength = pathKeys.length,
+ fn;
+
+ if (csp) {
+ fn = (pathKeysLength < 6)
+ ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4])
+ : function(scope, locals) {
+ var i = 0, val;
+ do {
+ val = cspSafeGetterFn(
+ pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++]
+ )(scope, locals);
+
+ locals = undefined; // clear after first iteration
+ scope = val;
+ } while (i < pathKeysLength);
+ return val;
+ }
+ } else {
+ var code = 'var l, fn, p;\n';
+ forEach(pathKeys, function(key, index) {
+ code += 'if(s === null || s === undefined) return s;\n' +
+ 'l=s;\n' +
+ 's='+ (index
+ // we simply dereference 's' on any .dot notation
+ ? 's'
+ // but if we are first then we check locals first, and if so read it first
+ : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
+ 'if (s && s.then) {\n' +
+ ' if (!("$$v" in s)) {\n' +
+ ' p=s;\n' +
+ ' p.$$v = undefined;\n' +
+ ' p.then(function(v) {p.$$v=v;});\n' +
+ '}\n' +
+ ' s=s.$$v\n' +
+ '}\n';
+ });
+ code += 'return s;';
+ fn = Function('s', 'k', code); // s=scope, k=locals
+ fn.toString = function() { return code; };
+ }
+
+ return getterFnCache[path] = fn;
+}
+
+///////////////////////////////////
+
+/**
+ * @ngdoc function
+ * @name ng.$parse
+ * @function
+ *
+ * @description
+ *
+ * Converts Angular {@link guide/expression expression} into a function.
+ *
+ * <pre>
+ * var getter = $parse('user.name');
+ * var setter = getter.assign;
+ * var context = {user:{name:'angular'}};
+ * var locals = {user:{name:'local'}};
+ *
+ * expect(getter(context)).toEqual('angular');
+ * setter(context, 'newValue');
+ * expect(context.user.name).toEqual('newValue');
+ * expect(getter(context, locals)).toEqual('local');
+ * </pre>
+ *
+ *
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ *
+ * The returned function also has the following properties:
+ * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
+ * literal.
+ * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
+ * constant literals.
+ * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
+ * set to a function to change its value on the given context.
+ *
+ */
+function $ParseProvider() {
+ var cache = {};
+ this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
+ return function(exp) {
+ switch(typeof exp) {
+ case 'string':
+ return cache.hasOwnProperty(exp)
+ ? cache[exp]
+ : cache[exp] = parser(exp, false, $filter, $sniffer.csp);
+ case 'function':
+ return exp;
+ default:
+ return noop;
+ }
+ };
+ }];
+}
+
+/**
+ * @ngdoc service
+ * @name ng.$q
+ * @requires $rootScope
+ *
+ * @description
+ * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
+ *
+ * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
+ * interface for interacting with an object that represents the result of an action that is
+ * performed asynchronously, and may or may not be finished at any given point in time.
+ *
+ * From the perspective of dealing with error handling, deferred and promise APIs are to
+ * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
+ *
+ * <pre>
+ * // for the purpose of this example let's assume that variables `$q` and `scope` are
+ * // available in the current lexical scope (they could have been injected or passed in).
+ *
+ * function asyncGreet(name) {
+ * var deferred = $q.defer();
+ *
+ * setTimeout(function() {
+ * // since this fn executes async in a future turn of the event loop, we need to wrap
+ * // our code into an $apply call so that the model changes are properly observed.
+ * scope.$apply(function() {
+ * if (okToGreet(name)) {
+ * deferred.resolve('Hello, ' + name + '!');
+ * } else {
+ * deferred.reject('Greeting ' + name + ' is not allowed.');
+ * }
+ * });
+ * }, 1000);
+ *
+ * return deferred.promise;
+ * }
+ *
+ * var promise = asyncGreet('Robin Hood');
+ * promise.then(function(greeting) {
+ * alert('Success: ' + greeting);
+ * }, function(reason) {
+ * alert('Failed: ' + reason);
+ * });
+ * </pre>
+ *
+ * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
+ * comes in the way of
+ * [guarantees that promise and deferred APIs make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md).
+ *
+ * Additionally the promise api allows for composition that is very hard to do with the
+ * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
+ * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
+ * section on serial or parallel joining of promises.
+ *
+ *
+ * # The Deferred API
+ *
+ * A new instance of deferred is constructed by calling `$q.defer()`.
+ *
+ * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
+ * that can be used for signaling the successful or unsuccessful completion of the task.
+ *
+ * **Methods**
+ *
+ * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
+ * constructed via `$q.reject`, the promise will be rejected instead.
+ * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
+ * resolving it with a rejection constructed via `$q.reject`.
+ *
+ * **Properties**
+ *
+ * - promise – `{Promise}` – promise object associated with this deferred.
+ *
+ *
+ * # The Promise API
+ *
+ * A new promise instance is created when a deferred instance is created and can be retrieved by
+ * calling `deferred.promise`.
+ *
+ * The purpose of the promise object is to allow for interested parties to get access to the result
+ * of the deferred task when it completes.
+ *
+ * **Methods**
+ *
+ * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved
+ * or rejected calls one of the success or error callbacks asynchronously as soon as the result
+ * is available. The callbacks are called with a single argument the result or rejection reason.
+ *
+ * This method *returns a new promise* which is resolved or rejected via the return value of the
+ * `successCallback` or `errorCallback`.
+ *
+ * - `always(callback)` – allows you to observe either the fulfillment or rejection of a promise,
+ * but to do so without modifying the final value. This is useful to release resources or do some
+ * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
+ * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
+ * more information.
+ *
+ * # Chaining promises
+ *
+ * Because calling `then` api of a promise returns a new derived promise, it is easily possible
+ * to create a chain of promises:
+ *
+ * <pre>
+ * promiseB = promiseA.then(function(result) {
+ * return result + 1;
+ * });
+ *
+ * // promiseB will be resolved immediately after promiseA is resolved and its value will be
+ * // the result of promiseA incremented by 1
+ * </pre>
+ *
+ * It is possible to create chains of any length and since a promise can be resolved with another
+ * promise (which will defer its resolution further), it is possible to pause/defer resolution of
+ * the promises at any point in the chain. This makes it possible to implement powerful apis like
+ * $http's response interceptors.
+ *
+ *
+ * # Differences between Kris Kowal's Q and $q
+ *
+ * There are three main differences:
+ *
+ * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
+ * mechanism in angular, which means faster propagation of resolution or rejection into your
+ * models and avoiding unnecessary browser repaints, which would result in flickering UI.
+ * - $q promises are recognized by the templating engine in angular, which means that in templates
+ * you can treat promises attached to a scope as if they were the resulting values.
+ * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
+ * all the important functionality needed for common async tasks.
+ *
+ * # Testing
+ *
+ * <pre>
+ * it('should simulate promise', inject(function($q, $rootScope) {
+ * var deferred = $q.defer();
+ * var promise = deferred.promise;
+ * var resolvedValue;
+ *
+ * promise.then(function(value) { resolvedValue = value; });
+ * expect(resolvedValue).toBeUndefined();
+ *
+ * // Simulate resolving of promise
+ * deferred.resolve(123);
+ * // Note that the 'then' function does not get called synchronously.
+ * // This is because we want the promise API to always be async, whether or not
+ * // it got called synchronously or asynchronously.
+ * expect(resolvedValue).toBeUndefined();
+ *
+ * // Propagate promise resolution to 'then' functions using $apply().
+ * $rootScope.$apply();
+ * expect(resolvedValue).toEqual(123);
+ * });
+ * </pre>
+ */
+function $QProvider() {
+
+ this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
+ return qFactory(function(callback) {
+ $rootScope.$evalAsync(callback);
+ }, $exceptionHandler);
+ }];
+}
+
+
+/**
+ * Constructs a promise manager.
+ *
+ * @param {function(function)} nextTick Function for executing functions in the next turn.
+ * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
+ * debugging purposes.
+ * @returns {object} Promise manager.
+ */
+function qFactory(nextTick, exceptionHandler) {
+
+ /**
+ * @ngdoc
+ * @name ng.$q#defer
+ * @methodOf ng.$q
+ * @description
+ * Creates a `Deferred` object which represents a task which will finish in the future.
+ *
+ * @returns {Deferred} Returns a new instance of deferred.
+ */
+ var defer = function() {
+ var pending = [],
+ value, deferred;
+
+ deferred = {
+
+ resolve: function(val) {
+ if (pending) {
+ var callbacks = pending;
+ pending = undefined;
+ value = ref(val);
+
+ if (callbacks.length) {
+ nextTick(function() {
+ var callback;
+ for (var i = 0, ii = callbacks.length; i < ii; i++) {
+ callback = callbacks[i];
+ value.then(callback[0], callback[1]);
+ }
+ });
+ }
+ }
+ },
+
+
+ reject: function(reason) {
+ deferred.resolve(reject(reason));
+ },
+
+
+ promise: {
+ then: function(callback, errback) {
+ var result = defer();
+
+ var wrappedCallback = function(value) {
+ try {
+ result.resolve((callback || defaultCallback)(value));
+ } catch(e) {
+ exceptionHandler(e);
+ result.reject(e);
+ }
+ };
+
+ var wrappedErrback = function(reason) {
+ try {
+ result.resolve((errback || defaultErrback)(reason));
+ } catch(e) {
+ exceptionHandler(e);
+ result.reject(e);
+ }
+ };
+
+ if (pending) {
+ pending.push([wrappedCallback, wrappedErrback]);
+ } else {
+ value.then(wrappedCallback, wrappedErrback);
+ }
+
+ return result.promise;
+ },
+ always: function(callback) {
+
+ function makePromise(value, resolved) {
+ var result = defer();
+ if (resolved) {
+ result.resolve(value);
+ } else {
+ result.reject(value);
+ }
+ return result.promise;
+ }
+
+ function handleCallback(value, isResolved) {
+ var callbackOutput = null;
+ try {
+ callbackOutput = (callback ||defaultCallback)();
+ } catch(e) {
+ return makePromise(e, false);
+ }
+ if (callbackOutput && callbackOutput.then) {
+ return callbackOutput.then(function() {
+ return makePromise(value, isResolved);
+ }, function(error) {
+ return makePromise(error, false);
+ });
+ } else {
+ return makePromise(value, isResolved);
+ }
+ }
+
+ return this.then(function(value) {
+ return handleCallback(value, true);
+ }, function(error) {
+ return handleCallback(error, false);
+ });
+ }
+ }
+ };
+
+ return deferred;
+ };
+
+
+ var ref = function(value) {
+ if (value && value.then) return value;
+ return {
+ then: function(callback) {
+ var result = defer();
+ nextTick(function() {
+ result.resolve(callback(value));
+ });
+ return result.promise;
+ }
+ };
+ };
+
+
+ /**
+ * @ngdoc
+ * @name ng.$q#reject
+ * @methodOf ng.$q
+ * @description
+ * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
+ * used to forward rejection in a chain of promises. If you are dealing with the last promise in
+ * a promise chain, you don't need to worry about it.
+ *
+ * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
+ * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
+ * a promise error callback and you want to forward the error to the promise derived from the
+ * current promise, you have to "rethrow" the error by returning a rejection constructed via
+ * `reject`.
+ *
+ * <pre>
+ * promiseB = promiseA.then(function(result) {
+ * // success: do something and resolve promiseB
+ * // with the old or a new result
+ * return result;
+ * }, function(reason) {
+ * // error: handle the error if possible and
+ * // resolve promiseB with newPromiseOrValue,
+ * // otherwise forward the rejection to promiseB
+ * if (canHandle(reason)) {
+ * // handle the error and recover
+ * return newPromiseOrValue;
+ * }
+ * return $q.reject(reason);
+ * });
+ * </pre>
+ *
+ * @param {*} reason Constant, message, exception or an object representing the rejection reason.
+ * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
+ */
+ var reject = function(reason) {
+ return {
+ then: function(callback, errback) {
+ var result = defer();
+ nextTick(function() {
+ result.resolve((errback || defaultErrback)(reason));
+ });
+ return result.promise;
+ }
+ };
+ };
+
+
+ /**
+ * @ngdoc
+ * @name ng.$q#when
+ * @methodOf ng.$q
+ * @description
+ * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
+ * This is useful when you are dealing with an object that might or might not be a promise, or if
+ * the promise comes from a source that can't be trusted.
+ *
+ * @param {*} value Value or a promise
+ * @returns {Promise} Returns a promise of the passed value or promise
+ */
+ var when = function(value, callback, errback) {
+ var result = defer(),
+ done;
+
+ var wrappedCallback = function(value) {
+ try {
+ return (callback || defaultCallback)(value);
+ } catch (e) {
+ exceptionHandler(e);
+ return reject(e);
+ }
+ };
+
+ var wrappedErrback = function(reason) {
+ try {
+ return (errback || defaultErrback)(reason);
+ } catch (e) {
+ exceptionHandler(e);
+ return reject(e);
+ }
+ };
+
+ nextTick(function() {
+ ref(value).then(function(value) {
+ if (done) return;
+ done = true;
+ result.resolve(ref(value).then(wrappedCallback, wrappedErrback));
+ }, function(reason) {
+ if (done) return;
+ done = true;
+ result.resolve(wrappedErrback(reason));
+ });
+ });
+
+ return result.promise;
+ };
+
+
+ function defaultCallback(value) {
+ return value;
+ }
+
+
+ function defaultErrback(reason) {
+ return reject(reason);
+ }
+
+
+ /**
+ * @ngdoc
+ * @name ng.$q#all
+ * @methodOf ng.$q
+ * @description
+ * Combines multiple promises into a single promise that is resolved when all of the input
+ * promises are resolved.
+ *
+ * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
+ * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
+ * each value corresponding to the promise at the same index/key in the `promises` array/hash. If any of
+ * the promises is resolved with a rejection, this resulting promise will be resolved with the
+ * same rejection.
+ */
+ function all(promises) {
+ var deferred = defer(),
+ counter = 0,
+ results = isArray(promises) ? [] : {};
+
+ forEach(promises, function(promise, key) {
+ counter++;
+ ref(promise).then(function(value) {
+ if (results.hasOwnProperty(key)) return;
+ results[key] = value;
+ if (!(--counter)) deferred.resolve(results);
+ }, function(reason) {
+ if (results.hasOwnProperty(key)) return;
+ deferred.reject(reason);
+ });
+ });
+
+ if (counter === 0) {
+ deferred.resolve(results);
+ }
+
+ return deferred.promise;
+ }
+
+ return {
+ defer: defer,
+ reject: reject,
+ when: when,
+ all: all
+ };
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$routeProvider
+ * @function
+ *
+ * @description
+ *
+ * Used for configuring routes. See {@link ng.$route $route} for an example.
+ */
+function $RouteProvider(){
+ var routes = {};
+
+ /**
+ * @ngdoc method
+ * @name ng.$routeProvider#when
+ * @methodOf ng.$routeProvider
+ *
+ * @param {string} path Route path (matched against `$location.path`). If `$location.path`
+ * contains redundant trailing slash or is missing one, the route will still match and the
+ * `$location.path` will be updated to add or drop the trailing slash to exactly match the
+ * route definition.
+ *
+ * * `path` can contain named groups starting with a colon (`:name`). All characters up
+ * to the next slash are matched and stored in `$routeParams` under the given `name`
+ * when the route matches.
+ * * `path` can contain named groups starting with a star (`*name`). All characters are
+ * eagerly stored in `$routeParams` under the given `name` when the route matches.
+ *
+ * For example, routes like `/color/:color/largecode/*largecode/edit` will match
+ * `/color/brown/largecode/code/with/slashs/edit` and extract:
+ *
+ * * `color: brown`
+ * * `largecode: code/with/slashs`.
+ *
+ *
+ * @param {Object} route Mapping information to be assigned to `$route.current` on route
+ * match.
+ *
+ * Object properties:
+ *
+ * - `controller` – `{(string|function()=}` – Controller fn that should be associated with newly
+ * created scope or the name of a {@link angular.Module#controller registered controller}
+ * if passed as a string.
+ * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be
+ * published to scope under the `controllerAs` name.
+ * - `template` – `{string=|function()=}` – html template as a string or function that returns
+ * an html template as a string which should be used by {@link ng.directive:ngView ngView} or
+ * {@link ng.directive:ngInclude ngInclude} directives.
+ * This property takes precedence over `templateUrl`.
+ *
+ * If `template` is a function, it will be called with the following parameters:
+ *
+ * - `{Array.<Object>}` - route parameters extracted from the current
+ * `$location.path()` by applying the current route
+ *
+ * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
+ * template that should be used by {@link ng.directive:ngView ngView}.
+ *
+ * If `templateUrl` is a function, it will be called with the following parameters:
+ *
+ * - `{Array.<Object>}` - route parameters extracted from the current
+ * `$location.path()` by applying the current route
+ *
+ * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
+ * be injected into the controller. If any of these dependencies are promises, they will be
+ * resolved and converted to a value before the controller is instantiated and the
+ * `$routeChangeSuccess` event is fired. The map object is:
+ *
+ * - `key` – `{string}`: a name of a dependency to be injected into the controller.
+ * - `factory` - `{string|function}`: If `string` then it is an alias for a service.
+ * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected}
+ * and the return value is treated as the dependency. If the result is a promise, it is resolved
+ * before its value is injected into the controller.
+ *
+ * - `redirectTo` – {(string|function())=} – value to update
+ * {@link ng.$location $location} path with and trigger route redirection.
+ *
+ * If `redirectTo` is a function, it will be called with the following parameters:
+ *
+ * - `{Object.<string>}` - route parameters extracted from the current
+ * `$location.path()` by applying the current route templateUrl.
+ * - `{string}` - current `$location.path()`
+ * - `{Object}` - current `$location.search()`
+ *
+ * The custom `redirectTo` function is expected to return a string which will be used
+ * to update `$location.path()` and `$location.search()`.
+ *
+ * - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search()
+ * changes.
+ *
+ * If the option is set to `false` and url in the browser changes, then
+ * `$routeUpdate` event is broadcasted on the root scope.
+ *
+ * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive
+ *
+ * If the option is set to `true`, then the particular route can be matched without being
+ * case sensitive
+ *
+ * @returns {Object} self
+ *
+ * @description
+ * Adds a new route definition to the `$route` service.
+ */
+ this.when = function(path, route) {
+ routes[path] = extend({reloadOnSearch: true, caseInsensitiveMatch: false}, route);
+
+ // create redirection for trailing slashes
+ if (path) {
+ var redirectPath = (path[path.length-1] == '/')
+ ? path.substr(0, path.length-1)
+ : path +'/';
+
+ routes[redirectPath] = {redirectTo: path};
+ }
+
+ return this;
+ };
+
+ /**
+ * @ngdoc method
+ * @name ng.$routeProvider#otherwise
+ * @methodOf ng.$routeProvider
+ *
+ * @description
+ * Sets route definition that will be used on route change when no other route definition
+ * is matched.
+ *
+ * @param {Object} params Mapping information to be assigned to `$route.current`.
+ * @returns {Object} self
+ */
+ this.otherwise = function(params) {
+ this.when(null, params);
+ return this;
+ };
+
+
+ this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache',
+ function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) {
+
+ /**
+ * @ngdoc object
+ * @name ng.$route
+ * @requires $location
+ * @requires $routeParams
+ *
+ * @property {Object} current Reference to the current route definition.
+ * The route definition contains:
+ *
+ * - `controller`: The controller constructor as define in route definition.
+ * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
+ * controller instantiation. The `locals` contain
+ * the resolved values of the `resolve` map. Additionally the `locals` also contain:
+ *
+ * - `$scope` - The current route scope.
+ * - `$template` - The current route template HTML.
+ *
+ * @property {Array.<Object>} routes Array of all configured routes.
+ *
+ * @description
+ * Is used for deep-linking URLs to controllers and views (HTML partials).
+ * It watches `$location.url()` and tries to map the path to an existing route definition.
+ *
+ * You can define routes through {@link ng.$routeProvider $routeProvider}'s API.
+ *
+ * The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView}
+ * directive and the {@link ng.$routeParams $routeParams} service.
+ *
+ * @example
+ This example shows how changing the URL hash causes the `$route` to match a route against the
+ URL, and the `ngView` pulls in the partial.
+
+ Note that this example is using {@link ng.directive:script inlined templates}
+ to get it working on jsfiddle as well.
+
+ <example module="ngView">
+ <file name="index.html">
+ <div ng-controller="MainCntl">
+ Choose:
+ <a href="Book/Moby">Moby</a> |
+ <a href="Book/Moby/ch/1">Moby: Ch1</a> |
+ <a href="Book/Gatsby">Gatsby</a> |
+ <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
+ <a href="Book/Scarlet">Scarlet Letter</a><br/>
+
+ <div ng-view></div>
+ <hr />
+
+ <pre>$location.path() = {{$location.path()}}</pre>
+ <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
+ <pre>$route.current.params = {{$route.current.params}}</pre>
+ <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
+ <pre>$routeParams = {{$routeParams}}</pre>
+ </div>
+ </file>
+
+ <file name="book.html">
+ controller: {{name}}<br />
+ Book Id: {{params.bookId}}<br />
+ </file>
+
+ <file name="chapter.html">
+ controller: {{name}}<br />
+ Book Id: {{params.bookId}}<br />
+ Chapter Id: {{params.chapterId}}
+ </file>
+
+ <file name="script.js">
+ angular.module('ngView', [], function($routeProvider, $locationProvider) {
+ $routeProvider.when('/Book/:bookId', {
+ templateUrl: 'book.html',
+ controller: BookCntl,
+ resolve: {
+ // I will cause a 1 second delay
+ delay: function($q, $timeout) {
+ var delay = $q.defer();
+ $timeout(delay.resolve, 1000);
+ return delay.promise;
+ }
+ }
+ });
+ $routeProvider.when('/Book/:bookId/ch/:chapterId', {
+ templateUrl: 'chapter.html',
+ controller: ChapterCntl
+ });
+
+ // configure html5 to get links working on jsfiddle
+ $locationProvider.html5Mode(true);
+ });
+
+ function MainCntl($scope, $route, $routeParams, $location) {
+ $scope.$route = $route;
+ $scope.$location = $location;
+ $scope.$routeParams = $routeParams;
+ }
+
+ function BookCntl($scope, $routeParams) {
+ $scope.name = "BookCntl";
+ $scope.params = $routeParams;
+ }
+
+ function ChapterCntl($scope, $routeParams) {
+ $scope.name = "ChapterCntl";
+ $scope.params = $routeParams;
+ }
+ </file>
+
+ <file name="scenario.js">
+ it('should load and compile correct template', function() {
+ element('a:contains("Moby: Ch1")').click();
+ var content = element('.doc-example-live [ng-view]').text();
+ expect(content).toMatch(/controller\: ChapterCntl/);
+ expect(content).toMatch(/Book Id\: Moby/);
+ expect(content).toMatch(/Chapter Id\: 1/);
+
+ element('a:contains("Scarlet")').click();
+ sleep(2); // promises are not part of scenario waiting
+ content = element('.doc-example-live [ng-view]').text();
+ expect(content).toMatch(/controller\: BookCntl/);
+ expect(content).toMatch(/Book Id\: Scarlet/);
+ });
+ </file>
+ </example>
+ */
+
+ /**
+ * @ngdoc event
+ * @name ng.$route#$routeChangeStart
+ * @eventOf ng.$route
+ * @eventType broadcast on root scope
+ * @description
+ * Broadcasted before a route change. At this point the route services starts
+ * resolving all of the dependencies needed for the route change to occurs.
+ * Typically this involves fetching the view template as well as any dependencies
+ * defined in `resolve` route property. Once all of the dependencies are resolved
+ * `$routeChangeSuccess` is fired.
+ *
+ * @param {Route} next Future route information.
+ * @param {Route} current Current route information.
+ */
+
+ /**
+ * @ngdoc event
+ * @name ng.$route#$routeChangeSuccess
+ * @eventOf ng.$route
+ * @eventType broadcast on root scope
+ * @description
+ * Broadcasted after a route dependencies are resolved.
+ * {@link ng.directive:ngView ngView} listens for the directive
+ * to instantiate the controller and render the view.
+ *
+ * @param {Object} angularEvent Synthetic event object.
+ * @param {Route} current Current route information.
+ * @param {Route|Undefined} previous Previous route information, or undefined if current is first route entered.
+ */
+
+ /**
+ * @ngdoc event
+ * @name ng.$route#$routeChangeError
+ * @eventOf ng.$route
+ * @eventType broadcast on root scope
+ * @description
+ * Broadcasted if any of the resolve promises are rejected.
+ *
+ * @param {Route} current Current route information.
+ * @param {Route} previous Previous route information.
+ * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
+ */
+
+ /**
+ * @ngdoc event
+ * @name ng.$route#$routeUpdate
+ * @eventOf ng.$route
+ * @eventType broadcast on root scope
+ * @description
+ *
+ * The `reloadOnSearch` property has been set to false, and we are reusing the same
+ * instance of the Controller.
+ */
+
+ var forceReload = false,
+ $route = {
+ routes: routes,
+
+ /**
+ * @ngdoc method
+ * @name ng.$route#reload
+ * @methodOf ng.$route
+ *
+ * @description
+ * Causes `$route` service to reload the current route even if
+ * {@link ng.$location $location} hasn't changed.
+ *
+ * As a result of that, {@link ng.directive:ngView ngView}
+ * creates new scope, reinstantiates the controller.
+ */
+ reload: function() {
+ forceReload = true;
+ $rootScope.$evalAsync(updateRoute);
+ }
+ };
+
+ $rootScope.$on('$locationChangeSuccess', updateRoute);
+
+ return $route;
+
+ /////////////////////////////////////////////////////
+
+ /**
+ * @param on {string} current url
+ * @param when {string} route when template to match the url against
+ * @param whenProperties {Object} properties to define when's matching behavior
+ * @return {?Object}
+ */
+ function switchRouteMatcher(on, when, whenProperties) {
+ // TODO(i): this code is convoluted and inefficient, we should construct the route matching
+ // regex only once and then reuse it
+
+ // Escape regexp special characters.
+ when = '^' + when.replace(/[-\/\\^$:*+?.()|[\]{}]/g, "\\$&") + '$';
+
+ var regex = '',
+ params = [],
+ dst = {};
+
+ var re = /\\([:*])(\w+)/g,
+ paramMatch,
+ lastMatchedIndex = 0;
+
+ while ((paramMatch = re.exec(when)) !== null) {
+ // Find each :param in `when` and replace it with a capturing group.
+ // Append all other sections of when unchanged.
+ regex += when.slice(lastMatchedIndex, paramMatch.index);
+ switch(paramMatch[1]) {
+ case ':':
+ regex += '([^\\/]*)';
+ break;
+ case '*':
+ regex += '(.*)';
+ break;
+ }
+ params.push(paramMatch[2]);
+ lastMatchedIndex = re.lastIndex;
+ }
+ // Append trailing path part.
+ regex += when.substr(lastMatchedIndex);
+
+ var match = on.match(new RegExp(regex, whenProperties.caseInsensitiveMatch ? 'i' : ''));
+ if (match) {
+ forEach(params, function(name, index) {
+ dst[name] = match[index + 1];
+ });
+ }
+ return match ? dst : null;
+ }
+
+ function updateRoute() {
+ var next = parseRoute(),
+ last = $route.current;
+
+ if (next && last && next.$$route === last.$$route
+ && equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) {
+ last.params = next.params;
+ copy(last.params, $routeParams);
+ $rootScope.$broadcast('$routeUpdate', last);
+ } else if (next || last) {
+ forceReload = false;
+ $rootScope.$broadcast('$routeChangeStart', next, last);
+ $route.current = next;
+ if (next) {
+ if (next.redirectTo) {
+ if (isString(next.redirectTo)) {
+ $location.path(interpolate(next.redirectTo, next.params)).search(next.params)
+ .replace();
+ } else {
+ $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search()))
+ .replace();
+ }
+ }
+ }
+
+ $q.when(next).
+ then(function() {
+ if (next) {
+ var locals = extend({}, next.resolve),
+ template;
+
+ forEach(locals, function(value, key) {
+ locals[key] = isString(value) ? $injector.get(value) : $injector.invoke(value);
+ });
+
+ if (isDefined(template = next.template)) {
+ if (isFunction(template)) {
+ template = template(next.params);
+ }
+ } else if (isDefined(template = next.templateUrl)) {
+ if (isFunction(template)) {
+ template = template(next.params);
+ }
+ if (isDefined(template)) {
+ next.loadedTemplateUrl = template;
+ template = $http.get(template, {cache: $templateCache}).
+ then(function(response) { return response.data; });
+ }
+ }
+ if (isDefined(template)) {
+ locals['$template'] = template;
+ }
+ return $q.all(locals);
+ }
+ }).
+ // after route change
+ then(function(locals) {
+ if (next == $route.current) {
+ if (next) {
+ next.locals = locals;
+ copy(next.params, $routeParams);
+ }
+ $rootScope.$broadcast('$routeChangeSuccess', next, last);
+ }
+ }, function(error) {
+ if (next == $route.current) {
+ $rootScope.$broadcast('$routeChangeError', next, last, error);
+ }
+ });
+ }
+ }
+
+
+ /**
+ * @returns the current active route, by matching it against the URL
+ */
+ function parseRoute() {
+ // Match a route
+ var params, match;
+ forEach(routes, function(route, path) {
+ if (!match && (params = switchRouteMatcher($location.path(), path, route))) {
+ match = inherit(route, {
+ params: extend({}, $location.search(), params),
+ pathParams: params});
+ match.$$route = route;
+ }
+ });
+ // No route matched; fallback to "otherwise" route
+ return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
+ }
+
+ /**
+ * @returns interpolation of the redirect path with the parameters
+ */
+ function interpolate(string, params) {
+ var result = [];
+ forEach((string||'').split(':'), function(segment, i) {
+ if (i == 0) {
+ result.push(segment);
+ } else {
+ var segmentMatch = segment.match(/(\w+)(.*)/);
+ var key = segmentMatch[1];
+ result.push(params[key]);
+ result.push(segmentMatch[2] || '');
+ delete params[key];
+ }
+ });
+ return result.join('');
+ }
+ }];
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$routeParams
+ * @requires $route
+ *
+ * @description
+ * Current set of route parameters. The route parameters are a combination of the
+ * {@link ng.$location $location} `search()`, and `path()`. The `path` parameters
+ * are extracted when the {@link ng.$route $route} path is matched.
+ *
+ * In case of parameter name collision, `path` params take precedence over `search` params.
+ *
+ * The service guarantees that the identity of the `$routeParams` object will remain unchanged
+ * (but its properties will likely change) even when a route change occurs.
+ *
+ * @example
+ * <pre>
+ * // Given:
+ * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
+ * // Route: /Chapter/:chapterId/Section/:sectionId
+ * //
+ * // Then
+ * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
+ * </pre>
+ */
+function $RouteParamsProvider() {
+ this.$get = valueFn({});
+}
+
+/**
+ * DESIGN NOTES
+ *
+ * The design decisions behind the scope are heavily favored for speed and memory consumption.
+ *
+ * The typical use of scope is to watch the expressions, which most of the time return the same
+ * value as last time so we optimize the operation.
+ *
+ * Closures construction is expensive in terms of speed as well as memory:
+ * - No closures, instead use prototypical inheritance for API
+ * - Internal state needs to be stored on scope directly, which means that private state is
+ * exposed as $$____ properties
+ *
+ * Loop operations are optimized by using while(count--) { ... }
+ * - this means that in order to keep the same order of execution as addition we have to add
+ * items to the array at the beginning (shift) instead of at the end (push)
+ *
+ * Child scopes are created and removed often
+ * - Using an array would be slow since inserts in middle are expensive so we use linked list
+ *
+ * There are few watches then a lot of observers. This is why you don't want the observer to be
+ * implemented in the same way as watch. Watch requires return of initialization function which
+ * are expensive to construct.
+ */
+
+
+/**
+ * @ngdoc object
+ * @name ng.$rootScopeProvider
+ * @description
+ *
+ * Provider for the $rootScope service.
+ */
+
+/**
+ * @ngdoc function
+ * @name ng.$rootScopeProvider#digestTtl
+ * @methodOf ng.$rootScopeProvider
+ * @description
+ *
+ * Sets the number of digest iterations the scope should attempt to execute before giving up and
+ * assuming that the model is unstable.
+ *
+ * The current default is 10 iterations.
+ *
+ * @param {number} limit The number of digest iterations.
+ */
+
+
+/**
+ * @ngdoc object
+ * @name ng.$rootScope
+ * @description
+ *
+ * Every application has a single root {@link ng.$rootScope.Scope scope}.
+ * All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide
+ * event processing life-cycle. See {@link guide/scope developer guide on scopes}.
+ */
+function $RootScopeProvider(){
+ var TTL = 10;
+
+ this.digestTtl = function(value) {
+ if (arguments.length) {
+ TTL = value;
+ }
+ return TTL;
+ };
+
+ this.$get = ['$injector', '$exceptionHandler', '$parse',
+ function( $injector, $exceptionHandler, $parse) {
+
+ /**
+ * @ngdoc function
+ * @name ng.$rootScope.Scope
+ *
+ * @description
+ * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
+ * {@link AUTO.$injector $injector}. Child scopes are created using the
+ * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
+ * compiled HTML template is executed.)
+ *
+ * Here is a simple scope snippet to show how you can interact with the scope.
+ * <pre>
+ * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
+ * </pre>
+ *
+ * # Inheritance
+ * A scope can inherit from a parent scope, as in this example:
+ * <pre>
+ var parent = $rootScope;
+ var child = parent.$new();
+
+ parent.salutation = "Hello";
+ child.name = "World";
+ expect(child.salutation).toEqual('Hello');
+
+ child.salutation = "Welcome";
+ expect(child.salutation).toEqual('Welcome');
+ expect(parent.salutation).toEqual('Hello');
+ * </pre>
+ *
+ *
+ * @param {Object.<string, function()>=} providers Map of service factory which need to be provided
+ * for the current scope. Defaults to {@link ng}.
+ * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
+ * append/override services provided by `providers`. This is handy when unit-testing and having
+ * the need to override a default service.
+ * @returns {Object} Newly created scope.
+ *
+ */
+ function Scope() {
+ this.$id = nextUid();
+ this.$$phase = this.$parent = this.$$watchers =
+ this.$$nextSibling = this.$$prevSibling =
+ this.$$childHead = this.$$childTail = null;
+ this['this'] = this.$root = this;
+ this.$$destroyed = false;
+ this.$$asyncQueue = [];
+ this.$$listeners = {};
+ this.$$isolateBindings = {};
+ }
+
+ /**
+ * @ngdoc property
+ * @name ng.$rootScope.Scope#$id
+ * @propertyOf ng.$rootScope.Scope
+ * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
+ * debugging.
+ */
+
+
+ Scope.prototype = {
+ /**
+ * @ngdoc function
+ * @name ng.$rootScope.Scope#$new
+ * @methodOf ng.$rootScope.Scope
+ * @function
+ *
+ * @description
+ * Creates a new child {@link ng.$rootScope.Scope scope}.
+ *
+ * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
+ * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope
+ * hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
+ *
+ * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for
+ * the scope and its child scopes to be permanently detached from the parent and thus stop
+ * participating in model change detection and listener notification by invoking.
+ *
+ * @param {boolean} isolate if true then the scope does not prototypically inherit from the
+ * parent scope. The scope is isolated, as it can not see parent scope properties.
+ * When creating widgets it is useful for the widget to not accidentally read parent
+ * state.
+ *
+ * @returns {Object} The newly created child scope.
+ *
+ */
+ $new: function(isolate) {
+ var Child,
+ child;
+
+ if (isFunction(isolate)) {
+ // TODO: remove at some point
+ throw Error('API-CHANGE: Use $controller to instantiate controllers.');
+ }
+ if (isolate) {
+ child = new Scope();
+ child.$root = this.$root;
+ } else {
+ Child = function() {}; // should be anonymous; This is so that when the minifier munges
+ // the name it does not become random set of chars. These will then show up as class
+ // name in the debugger.
+ Child.prototype = this;
+ child = new Child();
+ child.$id = nextUid();
+ }
+ child['this'] = child;
+ child.$$listeners = {};
+ child.$parent = this;
+ child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null;
+ child.$$prevSibling = this.$$childTail;
+ if (this.$$childHead) {
+ this.$$childTail.$$nextSibling = child;
+ this.$$childTail = child;
+ } else {
+ this.$$childHead = this.$$childTail = child;
+ }
+ return child;
+ },
+
+ /**
+ * @ngdoc function
+ * @name ng.$rootScope.Scope#$watch
+ * @methodOf ng.$rootScope.Scope
+ * @function
+ *
+ * @description
+ * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
+ *
+ * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and
+ * should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()}
+ * reruns when it detects changes the `watchExpression` can execute multiple times per
+ * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
+ * - The `listener` is called only when the value from the current `watchExpression` and the
+ * previous call to `watchExpression` are not equal (with the exception of the initial run,
+ * see below). The inequality is determined according to
+ * {@link angular.equals} function. To save the value of the object for later comparison, the
+ * {@link angular.copy} function is used. It also means that watching complex options will
+ * have adverse memory and performance implications.
+ * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This
+ * is achieved by rerunning the watchers until no changes are detected. The rerun iteration
+ * limit is 10 to prevent an infinite loop deadlock.
+ *
+ *
+ * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
+ * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
+ * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is
+ * detected, be prepared for multiple calls to your listener.)
+ *
+ * After a watcher is registered with the scope, the `listener` fn is called asynchronously
+ * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
+ * watcher. In rare cases, this is undesirable because the listener is called when the result
+ * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
+ * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
+ * listener was called due to initialization.
+ *
+ *
+ * # Example
+ * <pre>
+ // let's assume that scope was dependency injected as the $rootScope
+ var scope = $rootScope;
+ scope.name = 'misko';
+ scope.counter = 0;
+
+ expect(scope.counter).toEqual(0);
+ scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; });
+ expect(scope.counter).toEqual(0);
+
+ scope.$digest();
+ // no variable change
+ expect(scope.counter).toEqual(0);
+
+ scope.name = 'adam';
+ scope.$digest();
+ expect(scope.counter).toEqual(1);
+ * </pre>
+ *
+ *
+ *
+ * @param {(function()|string)} watchExpression Expression that is evaluated on each
+ * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a
+ * call to the `listener`.
+ *
+ * - `string`: Evaluated as {@link guide/expression expression}
+ * - `function(scope)`: called with current `scope` as a parameter.
+ * @param {(function()|string)=} listener Callback called whenever the return value of
+ * the `watchExpression` changes.
+ *
+ * - `string`: Evaluated as {@link guide/expression expression}
+ * - `function(newValue, oldValue, scope)`: called with current and previous values as parameters.
+ *
+ * @param {boolean=} objectEquality Compare object for equality rather than for reference.
+ * @returns {function()} Returns a deregistration function for this listener.
+ */
+ $watch: function(watchExp, listener, objectEquality) {
+ var scope = this,
+ get = compileToFn(watchExp, 'watch'),
+ array = scope.$$watchers,
+ watcher = {
+ fn: listener,
+ last: initWatchVal,
+ get: get,
+ exp: watchExp,
+ eq: !!objectEquality
+ };
+
+ // in the case user pass string, we need to compile it, do we really need this ?
+ if (!isFunction(listener)) {
+ var listenFn = compileToFn(listener || noop, 'listener');
+ watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
+ }
+
+ if (typeof watchExp == 'string' && get.constant) {
+ var originalFn = watcher.fn;
+ watcher.fn = function(newVal, oldVal, scope) {
+ originalFn.call(this, newVal, oldVal, scope);
+ arrayRemove(array, watcher);
+ };
+ }
+
+ if (!array) {
+ array = scope.$$watchers = [];
+ }
+ // we use unshift since we use a while loop in $digest for speed.
+ // the while loop reads in reverse order.
+ array.unshift(watcher);
+
+ return function() {
+ arrayRemove(array, watcher);
+ };
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name ng.$rootScope.Scope#$watchCollection
+ * @methodOf ng.$rootScope.Scope
+ * @function
+ *
+ * @description
+ * Shallow watches the properties of an object and fires whenever any of the properties change
+ * (for arrays this implies watching the array items, for object maps this implies watching the properties).
+ * If a change is detected the `listener` callback is fired.
+ *
+ * - The `obj` collection is observed via standard $watch operation and is examined on every call to $digest() to
+ * see if any items have been added, removed, or moved.
+ * - The `listener` is called whenever anything within the `obj` has changed. Examples include adding new items
+ * into the object or array, removing and moving items around.
+ *
+ *
+ * # Example
+ * <pre>
+ $scope.names = ['igor', 'matias', 'misko', 'james'];
+ $scope.dataCount = 4;
+
+ $scope.$watchCollection('names', function(newNames, oldNames) {
+ $scope.dataCount = newNames.length;
+ });
+
+ expect($scope.dataCount).toEqual(4);
+ $scope.$digest();
+
+ //still at 4 ... no changes
+ expect($scope.dataCount).toEqual(4);
+
+ $scope.names.pop();
+ $scope.$digest();
+
+ //now there's been a change
+ expect($scope.dataCount).toEqual(3);
+ * </pre>
+ *
+ *
+ * @param {string|Function(scope)} obj Evaluated as {@link guide/expression expression}. The expression value
+ * should evaluate to an object or an array which is observed on each
+ * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the collection will trigger
+ * a call to the `listener`.
+ *
+ * @param {function(newCollection, oldCollection, scope)} listener a callback function that is fired with both
+ * the `newCollection` and `oldCollection` as parameters.
+ * The `newCollection` object is the newly modified data obtained from the `obj` expression and the
+ * `oldCollection` object is a copy of the former collection data.
+ * The `scope` refers to the current scope.
+ *
+ * @returns {function()} Returns a de-registration function for this listener. When the de-registration function is executed
+ * then the internal watch operation is terminated.
+ */
+ $watchCollection: function(obj, listener) {
+ var self = this;
+ var oldValue;
+ var newValue;
+ var changeDetected = 0;
+ var objGetter = $parse(obj);
+ var internalArray = [];
+ var internalObject = {};
+ var oldLength = 0;
+
+ function $watchCollectionWatch() {
+ newValue = objGetter(self);
+ var newLength, key;
+
+ if (!isObject(newValue)) {
+ if (oldValue !== newValue) {
+ oldValue = newValue;
+ changeDetected++;
+ }
+ } else if (isArrayLike(newValue)) {
+ if (oldValue !== internalArray) {
+ // we are transitioning from something which was not an array into array.
+ oldValue = internalArray;
+ oldLength = oldValue.length = 0;
+ changeDetected++;
+ }
+
+ newLength = newValue.length;
+
+ if (oldLength !== newLength) {
+ // if lengths do not match we need to trigger change notification
+ changeDetected++;
+ oldValue.length = oldLength = newLength;
+ }
+ // copy the items to oldValue and look for changes.
+ for (var i = 0; i < newLength; i++) {
+ if (oldValue[i] !== newValue[i]) {
+ changeDetected++;
+ oldValue[i] = newValue[i];
+ }
+ }
+ } else {
+ if (oldValue !== internalObject) {
+ // we are transitioning from something which was not an object into object.
+ oldValue = internalObject = {};
+ oldLength = 0;
+ changeDetected++;
+ }
+ // copy the items to oldValue and look for changes.
+ newLength = 0;
+ for (key in newValue) {
+ if (newValue.hasOwnProperty(key)) {
+ newLength++;
+ if (oldValue.hasOwnProperty(key)) {
+ if (oldValue[key] !== newValue[key]) {
+ changeDetected++;
+ oldValue[key] = newValue[key];
+ }
+ } else {
+ oldLength++;
+ oldValue[key] = newValue[key];
+ changeDetected++;
+ }
+ }
+ }
+ if (oldLength > newLength) {
+ // we used to have more keys, need to find them and destroy them.
+ changeDetected++;
+ for(key in oldValue) {
+ if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) {
+ oldLength--;
+ delete oldValue[key];
+ }
+ }
+ }
+ }
+ return changeDetected;
+ }
+
+ function $watchCollectionAction() {
+ listener(newValue, oldValue, self);
+ }
+
+ return this.$watch($watchCollectionWatch, $watchCollectionAction);
+ },
+
+ /**
+ * @ngdoc function
+ * @name ng.$rootScope.Scope#$digest
+ * @methodOf ng.$rootScope.Scope
+ * @function
+ *
+ * @description
+ * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children.
+ * Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the
+ * `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are
+ * firing. This means that it is possible to get into an infinite loop. This function will throw
+ * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10.
+ *
+ * Usually you don't call `$digest()` directly in
+ * {@link ng.directive:ngController controllers} or in
+ * {@link ng.$compileProvider#directive directives}.
+ * Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a
+ * {@link ng.$compileProvider#directive directives}) will force a `$digest()`.
+ *
+ * If you want to be notified whenever `$digest()` is called,
+ * you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()}
+ * with no `listener`.
+ *
+ * You may have a need to call `$digest()` from within unit-tests, to simulate the scope
+ * life-cycle.
+ *
+ * # Example
+ * <pre>
+ var scope = ...;
+ scope.name = 'misko';
+ scope.counter = 0;
+
+ expect(scope.counter).toEqual(0);
+ scope.$watch('name', function(newValue, oldValue) {
+ scope.counter = scope.counter + 1;
+ });
+ expect(scope.counter).toEqual(0);
+
+ scope.$digest();
+ // no variable change
+ expect(scope.counter).toEqual(0);
+
+ scope.name = 'adam';
+ scope.$digest();
+ expect(scope.counter).toEqual(1);
+ * </pre>
+ *
+ */
+ $digest: function() {
+ var watch, value, last,
+ watchers,
+ asyncQueue = this.$$asyncQueue,
+ length,
+ dirty, ttl = TTL,
+ next, current, target = this,
+ watchLog = [],
+ logIdx, logMsg;
+
+ beginPhase('$digest');
+
+ do { // "while dirty" loop
+ dirty = false;
+ current = target;
+
+ while(asyncQueue.length) {
+ try {
+ current.$eval(asyncQueue.shift());
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ }
+
+ do { // "traverse the scopes" loop
+ if ((watchers = current.$$watchers)) {
+ // process our watches
+ length = watchers.length;
+ while (length--) {
+ try {
+ watch = watchers[length];
+ // Most common watches are on primitives, in which case we can short
+ // circuit it with === operator, only when === fails do we use .equals
+ if ((value = watch.get(current)) !== (last = watch.last) &&
+ !(watch.eq
+ ? equals(value, last)
+ : (typeof value == 'number' && typeof last == 'number'
+ && isNaN(value) && isNaN(last)))) {
+ dirty = true;
+ watch.last = watch.eq ? copy(value) : value;
+ watch.fn(value, ((last === initWatchVal) ? value : last), current);
+ if (ttl < 5) {
+ logIdx = 4 - ttl;
+ if (!watchLog[logIdx]) watchLog[logIdx] = [];
+ logMsg = (isFunction(watch.exp))
+ ? 'fn: ' + (watch.exp.name || watch.exp.toString())
+ : watch.exp;
+ logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
+ watchLog[logIdx].push(logMsg);
+ }
+ }
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ }
+ }
+
+ // Insanity Warning: scope depth-first traversal
+ // yes, this code is a bit crazy, but it works and we have tests to prove it!
+ // this piece should be kept in sync with the traversal in $broadcast
+ if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
+ while(current !== target && !(next = current.$$nextSibling)) {
+ current = current.$parent;
+ }
+ }
+ } while ((current = next));
+
+ if(dirty && !(ttl--)) {
+ clearPhase();
+ throw Error(TTL + ' $digest() iterations reached. Aborting!\n' +
+ 'Watchers fired in the last 5 iterations: ' + toJson(watchLog));
+ }
+ } while (dirty || asyncQueue.length);
+
+ clearPhase();
+ },
+
+
+ /**
+ * @ngdoc event
+ * @name ng.$rootScope.Scope#$destroy
+ * @eventOf ng.$rootScope.Scope
+ * @eventType broadcast on scope being destroyed
+ *
+ * @description
+ * Broadcasted when a scope and its children are being destroyed.
+ */
+
+ /**
+ * @ngdoc function
+ * @name ng.$rootScope.Scope#$destroy
+ * @methodOf ng.$rootScope.Scope
+ * @function
+ *
+ * @description
+ * Removes the current scope (and all of its children) from the parent scope. Removal implies
+ * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
+ * propagate to the current scope and its children. Removal also implies that the current
+ * scope is eligible for garbage collection.
+ *
+ * The `$destroy()` is usually used by directives such as
+ * {@link ng.directive:ngRepeat ngRepeat} for managing the
+ * unrolling of the loop.
+ *
+ * Just before a scope is destroyed a `$destroy` event is broadcasted on this scope.
+ * Application code can register a `$destroy` event handler that will give it chance to
+ * perform any necessary cleanup.
+ */
+ $destroy: function() {
+ // we can't destroy the root scope or a scope that has been already destroyed
+ if ($rootScope == this || this.$$destroyed) return;
+ var parent = this.$parent;
+
+ this.$broadcast('$destroy');
+ this.$$destroyed = true;
+
+ if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
+ if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
+ if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
+ if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
+
+ // This is bogus code that works around Chrome's GC leak
+ // see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
+ this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
+ this.$$childTail = null;
+ },
+
+ /**
+ * @ngdoc function
+ * @name ng.$rootScope.Scope#$eval
+ * @methodOf ng.$rootScope.Scope
+ * @function
+ *
+ * @description
+ * Executes the `expression` on the current scope returning the result. Any exceptions in the
+ * expression are propagated (uncaught). This is useful when evaluating Angular expressions.
+ *
+ * # Example
+ * <pre>
+ var scope = ng.$rootScope.Scope();
+ scope.a = 1;
+ scope.b = 2;
+
+ expect(scope.$eval('a+b')).toEqual(3);
+ expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
+ * </pre>
+ *
+ * @param {(string|function())=} expression An angular expression to be executed.
+ *
+ * - `string`: execute using the rules as defined in {@link guide/expression expression}.
+ * - `function(scope)`: execute the function with the current `scope` parameter.
+ *
+ * @returns {*} The result of evaluating the expression.
+ */
+ $eval: function(expr, locals) {
+ return $parse(expr)(this, locals);
+ },
+
+ /**
+ * @ngdoc function
+ * @name ng.$rootScope.Scope#$evalAsync
+ * @methodOf ng.$rootScope.Scope
+ * @function
+ *
+ * @description
+ * Executes the expression on the current scope at a later point in time.
+ *
+ * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that:
+ *
+ * - it will execute in the current script execution context (before any DOM rendering).
+ * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
+ * `expression` execution.
+ *
+ * Any exceptions from the execution of the expression are forwarded to the
+ * {@link ng.$exceptionHandler $exceptionHandler} service.
+ *
+ * @param {(string|function())=} expression An angular expression to be executed.
+ *
+ * - `string`: execute using the rules as defined in {@link guide/expression expression}.
+ * - `function(scope)`: execute the function with the current `scope` parameter.
+ *
+ */
+ $evalAsync: function(expr) {
+ this.$$asyncQueue.push(expr);
+ },
+
+ /**
+ * @ngdoc function
+ * @name ng.$rootScope.Scope#$apply
+ * @methodOf ng.$rootScope.Scope
+ * @function
+ *
+ * @description
+ * `$apply()` is used to execute an expression in angular from outside of the angular framework.
+ * (For example from browser DOM events, setTimeout, XHR or third party libraries).
+ * Because we are calling into the angular framework we need to perform proper scope life-cycle
+ * of {@link ng.$exceptionHandler exception handling},
+ * {@link ng.$rootScope.Scope#$digest executing watches}.
+ *
+ * ## Life cycle
+ *
+ * # Pseudo-Code of `$apply()`
+ * <pre>
+ function $apply(expr) {
+ try {
+ return $eval(expr);
+ } catch (e) {
+ $exceptionHandler(e);
+ } finally {
+ $root.$digest();
+ }
+ }
+ * </pre>
+ *
+ *
+ * Scope's `$apply()` method transitions through the following stages:
+ *
+ * 1. The {@link guide/expression expression} is executed using the
+ * {@link ng.$rootScope.Scope#$eval $eval()} method.
+ * 2. Any exceptions from the execution of the expression are forwarded to the
+ * {@link ng.$exceptionHandler $exceptionHandler} service.
+ * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression
+ * was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
+ *
+ *
+ * @param {(string|function())=} exp An angular expression to be executed.
+ *
+ * - `string`: execute using the rules as defined in {@link guide/expression expression}.
+ * - `function(scope)`: execute the function with current `scope` parameter.
+ *
+ * @returns {*} The result of evaluating the expression.
+ */
+ $apply: function(expr) {
+ try {
+ beginPhase('$apply');
+ return this.$eval(expr);
+ } catch (e) {
+ $exceptionHandler(e);
+ } finally {
+ clearPhase();
+ try {
+ $rootScope.$digest();
+ } catch (e) {
+ $exceptionHandler(e);
+ throw e;
+ }
+ }
+ },
+
+ /**
+ * @ngdoc function
+ * @name ng.$rootScope.Scope#$on
+ * @methodOf ng.$rootScope.Scope
+ * @function
+ *
+ * @description
+ * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of
+ * event life cycle.
+ *
+ * The event listener function format is: `function(event, args...)`. The `event` object
+ * passed into the listener has the following attributes:
+ *
+ * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or `$broadcast`-ed.
+ * - `currentScope` - `{Scope}`: the current scope which is handling the event.
+ * - `name` - `{string}`: Name of the event.
+ * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel further event
+ * propagation (available only for events that were `$emit`-ed).
+ * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag to true.
+ * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
+ *
+ * @param {string} name Event name to listen on.
+ * @param {function(event, args...)} listener Function to call when the event is emitted.
+ * @returns {function()} Returns a deregistration function for this listener.
+ */
+ $on: function(name, listener) {
+ var namedListeners = this.$$listeners[name];
+ if (!namedListeners) {
+ this.$$listeners[name] = namedListeners = [];
+ }
+ namedListeners.push(listener);
+
+ return function() {
+ namedListeners[indexOf(namedListeners, listener)] = null;
+ };
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name ng.$rootScope.Scope#$emit
+ * @methodOf ng.$rootScope.Scope
+ * @function
+ *
+ * @description
+ * Dispatches an event `name` upwards through the scope hierarchy notifying the
+ * registered {@link ng.$rootScope.Scope#$on} listeners.
+ *
+ * The event life cycle starts at the scope on which `$emit` was called. All
+ * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
+ * Afterwards, the event traverses upwards toward the root scope and calls all registered
+ * listeners along the way. The event will stop propagating if one of the listeners cancels it.
+ *
+ * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
+ * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
+ *
+ * @param {string} name Event name to emit.
+ * @param {...*} args Optional set of arguments which will be passed onto the event listeners.
+ * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
+ */
+ $emit: function(name, args) {
+ var empty = [],
+ namedListeners,
+ scope = this,
+ stopPropagation = false,
+ event = {
+ name: name,
+ targetScope: scope,
+ stopPropagation: function() {stopPropagation = true;},
+ preventDefault: function() {
+ event.defaultPrevented = true;
+ },
+ defaultPrevented: false
+ },
+ listenerArgs = concat([event], arguments, 1),
+ i, length;
+
+ do {
+ namedListeners = scope.$$listeners[name] || empty;
+ event.currentScope = scope;
+ for (i=0, length=namedListeners.length; i<length; i++) {
+
+ // if listeners were deregistered, defragment the array
+ if (!namedListeners[i]) {
+ namedListeners.splice(i, 1);
+ i--;
+ length--;
+ continue;
+ }
+ try {
+ namedListeners[i].apply(null, listenerArgs);
+ if (stopPropagation) return event;
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ }
+ //traverse upwards
+ scope = scope.$parent;
+ } while (scope);
+
+ return event;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name ng.$rootScope.Scope#$broadcast
+ * @methodOf ng.$rootScope.Scope
+ * @function
+ *
+ * @description
+ * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
+ * registered {@link ng.$rootScope.Scope#$on} listeners.
+ *
+ * The event life cycle starts at the scope on which `$broadcast` was called. All
+ * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
+ * Afterwards, the event propagates to all direct and indirect scopes of the current scope and
+ * calls all registered listeners along the way. The event cannot be canceled.
+ *
+ * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
+ * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
+ *
+ * @param {string} name Event name to broadcast.
+ * @param {...*} args Optional set of arguments which will be passed onto the event listeners.
+ * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
+ */
+ $broadcast: function(name, args) {
+ var target = this,
+ current = target,
+ next = target,
+ event = {
+ name: name,
+ targetScope: target,
+ preventDefault: function() {
+ event.defaultPrevented = true;
+ },
+ defaultPrevented: false
+ },
+ listenerArgs = concat([event], arguments, 1),
+ listeners, i, length;
+
+ //down while you can, then up and next sibling or up and next sibling until back at root
+ do {
+ current = next;
+ event.currentScope = current;
+ listeners = current.$$listeners[name] || [];
+ for (i=0, length = listeners.length; i<length; i++) {
+ // if listeners were deregistered, defragment the array
+ if (!listeners[i]) {
+ listeners.splice(i, 1);
+ i--;
+ length--;
+ continue;
+ }
+
+ try {
+ listeners[i].apply(null, listenerArgs);
+ } catch(e) {
+ $exceptionHandler(e);
+ }
+ }
+
+ // Insanity Warning: scope depth-first traversal
+ // yes, this code is a bit crazy, but it works and we have tests to prove it!
+ // this piece should be kept in sync with the traversal in $digest
+ if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
+ while(current !== target && !(next = current.$$nextSibling)) {
+ current = current.$parent;
+ }
+ }
+ } while ((current = next));
+
+ return event;
+ }
+ };
+
+ var $rootScope = new Scope();
+
+ return $rootScope;
+
+
+ function beginPhase(phase) {
+ if ($rootScope.$$phase) {
+ throw Error($rootScope.$$phase + ' already in progress');
+ }
+
+ $rootScope.$$phase = phase;
+ }
+
+ function clearPhase() {
+ $rootScope.$$phase = null;
+ }
+
+ function compileToFn(exp, name) {
+ var fn = $parse(exp);
+ assertArgFn(fn, name);
+ return fn;
+ }
+
+ /**
+ * function used as an initial value for watchers.
+ * because it's unique we can easily tell it apart from other values
+ */
+ function initWatchVal() {}
+ }];
+}
+
+/**
+ * !!! This is an undocumented "private" service !!!
+ *
+ * @name ng.$sniffer
+ * @requires $window
+ * @requires $document
+ *
+ * @property {boolean} history Does the browser support html5 history api ?
+ * @property {boolean} hashchange Does the browser support hashchange event ?
+ * @property {boolean} transitions Does the browser support CSS transition events ?
+ * @property {boolean} animations Does the browser support CSS animation events ?
+ *
+ * @description
+ * This is very simple implementation of testing browser's features.
+ */
+function $SnifferProvider() {
+ this.$get = ['$window', '$document', function($window, $document) {
+ var eventSupport = {},
+ android = int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
+ document = $document[0] || {},
+ vendorPrefix,
+ vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
+ bodyStyle = document.body && document.body.style,
+ transitions = false,
+ animations = false,
+ match;
+
+ if (bodyStyle) {
+ for(var prop in bodyStyle) {
+ if(match = vendorRegex.exec(prop)) {
+ vendorPrefix = match[0];
+ vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
+ break;
+ }
+ }
+ transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
+ animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
+ }
+
+
+ return {
+ // Android has history.pushState, but it does not update location correctly
+ // so let's not use the history API at all.
+ // http://code.google.com/p/android/issues/detail?id=17471
+ // https://github.com/angular/angular.js/issues/904
+ history: !!($window.history && $window.history.pushState && !(android < 4)),
+ hashchange: 'onhashchange' in $window &&
+ // IE8 compatible mode lies
+ (!document.documentMode || document.documentMode > 7),
+ hasEvent: function(event) {
+ // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
+ // it. In particular the event is not fired when backspace or delete key are pressed or
+ // when cut operation is performed.
+ if (event == 'input' && msie == 9) return false;
+
+ if (isUndefined(eventSupport[event])) {
+ var divElm = document.createElement('div');
+ eventSupport[event] = 'on' + event in divElm;
+ }
+
+ return eventSupport[event];
+ },
+ csp: document.securityPolicy ? document.securityPolicy.isActive : false,
+ vendorPrefix: vendorPrefix,
+ transitions : transitions,
+ animations : animations
+ };
+ }];
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$window
+ *
+ * @description
+ * A reference to the browser's `window` object. While `window`
+ * is globally available in JavaScript, it causes testability problems, because
+ * it is a global variable. In angular we always refer to it through the
+ * `$window` service, so it may be overridden, removed or mocked for testing.
+ *
+ * All expressions are evaluated with respect to current scope so they don't
+ * suffer from window globality.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope, $window) {
+ $scope.$window = $window;
+ $scope.greeting = 'Hello, World!';
+ }
+ </script>
+ <div ng-controller="Ctrl">
+ <input type="text" ng-model="greeting" />
+ <button ng-click="$window.alert(greeting)">ALERT</button>
+ </div>
+ </doc:source>
+ <doc:scenario>
+ it('should display the greeting in the input box', function() {
+ input('greeting').enter('Hello, E2E Tests');
+ // If we click the button it will block the test runner
+ // element(':button').click();
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+function $WindowProvider(){
+ this.$get = valueFn(window);
+}
+
+/**
+ * Parse headers into key value object
+ *
+ * @param {string} headers Raw headers as a string
+ * @returns {Object} Parsed headers as key value object
+ */
+function parseHeaders(headers) {
+ var parsed = {}, key, val, i;
+
+ if (!headers) return parsed;
+
+ forEach(headers.split('\n'), function(line) {
+ i = line.indexOf(':');
+ key = lowercase(trim(line.substr(0, i)));
+ val = trim(line.substr(i + 1));
+
+ if (key) {
+ if (parsed[key]) {
+ parsed[key] += ', ' + val;
+ } else {
+ parsed[key] = val;
+ }
+ }
+ });
+
+ return parsed;
+}
+
+
+var IS_SAME_DOMAIN_URL_MATCH = /^(([^:]+):)?\/\/(\w+:{0,1}\w*@)?([\w\.-]*)?(:([0-9]+))?(.*)$/;
+
+
+/**
+ * Parse a request and location URL and determine whether this is a same-domain request.
+ *
+ * @param {string} requestUrl The url of the request.
+ * @param {string} locationUrl The current browser location url.
+ * @returns {boolean} Whether the request is for the same domain.
+ */
+function isSameDomain(requestUrl, locationUrl) {
+ var match = IS_SAME_DOMAIN_URL_MATCH.exec(requestUrl);
+ // if requestUrl is relative, the regex does not match.
+ if (match == null) return true;
+
+ var domain1 = {
+ protocol: match[2],
+ host: match[4],
+ port: int(match[6]) || DEFAULT_PORTS[match[2]] || null,
+ // IE8 sets unmatched groups to '' instead of undefined.
+ relativeProtocol: match[2] === undefined || match[2] === ''
+ };
+
+ match = SERVER_MATCH.exec(locationUrl);
+ var domain2 = {
+ protocol: match[1],
+ host: match[3],
+ port: int(match[5]) || DEFAULT_PORTS[match[1]] || null
+ };
+
+ return (domain1.protocol == domain2.protocol || domain1.relativeProtocol) &&
+ domain1.host == domain2.host &&
+ (domain1.port == domain2.port || (domain1.relativeProtocol &&
+ domain2.port == DEFAULT_PORTS[domain2.protocol]));
+}
+
+
+/**
+ * Returns a function that provides access to parsed headers.
+ *
+ * Headers are lazy parsed when first requested.
+ * @see parseHeaders
+ *
+ * @param {(string|Object)} headers Headers to provide access to.
+ * @returns {function(string=)} Returns a getter function which if called with:
+ *
+ * - if called with single an argument returns a single header value or null
+ * - if called with no arguments returns an object containing all headers.
+ */
+function headersGetter(headers) {
+ var headersObj = isObject(headers) ? headers : undefined;
+
+ return function(name) {
+ if (!headersObj) headersObj = parseHeaders(headers);
+
+ if (name) {
+ return headersObj[lowercase(name)] || null;
+ }
+
+ return headersObj;
+ };
+}
+
+
+/**
+ * Chain all given functions
+ *
+ * This function is used for both request and response transforming
+ *
+ * @param {*} data Data to transform.
+ * @param {function(string=)} headers Http headers getter fn.
+ * @param {(function|Array.<function>)} fns Function or an array of functions.
+ * @returns {*} Transformed data.
+ */
+function transformData(data, headers, fns) {
+ if (isFunction(fns))
+ return fns(data, headers);
+
+ forEach(fns, function(fn) {
+ data = fn(data, headers);
+ });
+
+ return data;
+}
+
+
+function isSuccess(status) {
+ return 200 <= status && status < 300;
+}
+
+
+function $HttpProvider() {
+ var JSON_START = /^\s*(\[|\{[^\{])/,
+ JSON_END = /[\}\]]\s*$/,
+ PROTECTION_PREFIX = /^\)\]\}',?\n/,
+ CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
+
+ var defaults = this.defaults = {
+ // transform incoming response data
+ transformResponse: [function(data) {
+ if (isString(data)) {
+ // strip json vulnerability protection prefix
+ data = data.replace(PROTECTION_PREFIX, '');
+ if (JSON_START.test(data) && JSON_END.test(data))
+ data = fromJson(data, true);
+ }
+ return data;
+ }],
+
+ // transform outgoing request data
+ transformRequest: [function(d) {
+ return isObject(d) && !isFile(d) ? toJson(d) : d;
+ }],
+
+ // default headers
+ headers: {
+ common: {
+ 'Accept': 'application/json, text/plain, */*'
+ },
+ post: CONTENT_TYPE_APPLICATION_JSON,
+ put: CONTENT_TYPE_APPLICATION_JSON,
+ patch: CONTENT_TYPE_APPLICATION_JSON
+ },
+
+ xsrfCookieName: 'XSRF-TOKEN',
+ xsrfHeaderName: 'X-XSRF-TOKEN'
+ };
+
+ /**
+ * Are order by request. I.E. they are applied in the same order as
+ * array on request, but revers order on response.
+ */
+ var interceptorFactories = this.interceptors = [];
+ /**
+ * For historical reasons, response interceptors ordered by the order in which
+ * they are applied to response. (This is in revers to interceptorFactories)
+ */
+ var responseInterceptorFactories = this.responseInterceptors = [];
+
+ this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
+ function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
+
+ var defaultCache = $cacheFactory('$http');
+
+ /**
+ * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
+ * The reversal is needed so that we can build up the interception chain around the
+ * server request.
+ */
+ var reversedInterceptors = [];
+
+ forEach(interceptorFactories, function(interceptorFactory) {
+ reversedInterceptors.unshift(isString(interceptorFactory)
+ ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
+ });
+
+ forEach(responseInterceptorFactories, function(interceptorFactory, index) {
+ var responseFn = isString(interceptorFactory)
+ ? $injector.get(interceptorFactory)
+ : $injector.invoke(interceptorFactory);
+
+ /**
+ * Response interceptors go before "around" interceptors (no real reason, just
+ * had to pick one.) But they are already revesed, so we can't use unshift, hence
+ * the splice.
+ */
+ reversedInterceptors.splice(index, 0, {
+ response: function(response) {
+ return responseFn($q.when(response));
+ },
+ responseError: function(response) {
+ return responseFn($q.reject(response));
+ }
+ });
+ });
+
+
+ /**
+ * @ngdoc function
+ * @name ng.$http
+ * @requires $httpBackend
+ * @requires $browser
+ * @requires $cacheFactory
+ * @requires $rootScope
+ * @requires $q
+ * @requires $injector
+ *
+ * @description
+ * The `$http` service is a core Angular service that facilitates communication with the remote
+ * HTTP servers via the browser's {@link https://developer.mozilla.org/en/xmlhttprequest
+ * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}.
+ *
+ * For unit testing applications that use `$http` service, see
+ * {@link ngMock.$httpBackend $httpBackend mock}.
+ *
+ * For a higher level of abstraction, please check out the {@link ngResource.$resource
+ * $resource} service.
+ *
+ * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
+ * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
+ * it is important to familiarize yourself with these APIs and the guarantees they provide.
+ *
+ *
+ * # General usage
+ * The `$http` service is a function which takes a single argument — a configuration object —
+ * that is used to generate an HTTP request and returns a {@link ng.$q promise}
+ * with two $http specific methods: `success` and `error`.
+ *
+ * <pre>
+ * $http({method: 'GET', url: '/someUrl'}).
+ * success(function(data, status, headers, config) {
+ * // this callback will be called asynchronously
+ * // when the response is available
+ * }).
+ * error(function(data, status, headers, config) {
+ * // called asynchronously if an error occurs
+ * // or server returns response with an error status.
+ * });
+ * </pre>
+ *
+ * Since the returned value of calling the $http function is a `promise`, you can also use
+ * the `then` method to register callbacks, and these callbacks will receive a single argument –
+ * an object representing the response. See the API signature and type info below for more
+ * details.
+ *
+ * A response status code between 200 and 299 is considered a success status and
+ * will result in the success callback being called. Note that if the response is a redirect,
+ * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
+ * called for such responses.
+ *
+ * # Shortcut methods
+ *
+ * Since all invocations of the $http service require passing in an HTTP method and URL, and
+ * POST/PUT requests require request data to be provided as well, shortcut methods
+ * were created:
+ *
+ * <pre>
+ * $http.get('/someUrl').success(successCallback);
+ * $http.post('/someUrl', data).success(successCallback);
+ * </pre>
+ *
+ * Complete list of shortcut methods:
+ *
+ * - {@link ng.$http#get $http.get}
+ * - {@link ng.$http#head $http.head}
+ * - {@link ng.$http#post $http.post}
+ * - {@link ng.$http#put $http.put}
+ * - {@link ng.$http#delete $http.delete}
+ * - {@link ng.$http#jsonp $http.jsonp}
+ *
+ *
+ * # Setting HTTP Headers
+ *
+ * The $http service will automatically add certain HTTP headers to all requests. These defaults
+ * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
+ * object, which currently contains this default configuration:
+ *
+ * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
+ * - `Accept: application/json, text/plain, * / *`
+ * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
+ * - `Content-Type: application/json`
+ * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
+ * - `Content-Type: application/json`
+ *
+ * To add or overwrite these defaults, simply add or remove a property from these configuration
+ * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
+ * with the lowercased HTTP method name as the key, e.g.
+ * `$httpProvider.defaults.headers.get['My-Header']='value'`.
+ *
+ * Additionally, the defaults can be set at runtime via the `$http.defaults` object in the same
+ * fashion.
+ *
+ *
+ * # Transforming Requests and Responses
+ *
+ * Both requests and responses can be transformed using transform functions. By default, Angular
+ * applies these transformations:
+ *
+ * Request transformations:
+ *
+ * - If the `data` property of the request configuration object contains an object, serialize it into
+ * JSON format.
+ *
+ * Response transformations:
+ *
+ * - If XSRF prefix is detected, strip it (see Security Considerations section below).
+ * - If JSON response is detected, deserialize it using a JSON parser.
+ *
+ * To globally augment or override the default transforms, modify the `$httpProvider.defaults.transformRequest` and
+ * `$httpProvider.defaults.transformResponse` properties. These properties are by default an
+ * array of transform functions, which allows you to `push` or `unshift` a new transformation function into the
+ * transformation chain. You can also decide to completely override any default transformations by assigning your
+ * transformation functions to these properties directly without the array wrapper.
+ *
+ * Similarly, to locally override the request/response transforms, augment the `transformRequest` and/or
+ * `transformResponse` properties of the configuration object passed into `$http`.
+ *
+ *
+ * # Caching
+ *
+ * To enable caching, set the configuration property `cache` to `true`. When the cache is
+ * enabled, `$http` stores the response from the server in local cache. Next time the
+ * response is served from the cache without sending a request to the server.
+ *
+ * Note that even if the response is served from cache, delivery of the data is asynchronous in
+ * the same way that real requests are.
+ *
+ * If there are multiple GET requests for the same URL that should be cached using the same
+ * cache, but the cache is not populated yet, only one request to the server will be made and
+ * the remaining requests will be fulfilled using the response from the first request.
+ *
+ * A custom default cache built with $cacheFactory can be provided in $http.defaults.cache.
+ * To skip it, set configuration property `cache` to `false`.
+ *
+ *
+ * # Interceptors
+ *
+ * Before you start creating interceptors, be sure to understand the
+ * {@link ng.$q $q and deferred/promise APIs}.
+ *
+ * For purposes of global error handling, authentication, or any kind of synchronous or
+ * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
+ * able to intercept requests before they are handed to the server and
+ * responses before they are handed over to the application code that
+ * initiated these requests. The interceptors leverage the {@link ng.$q
+ * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
+ *
+ * The interceptors are service factories that are registered with the `$httpProvider` by
+ * adding them to the `$httpProvider.interceptors` array. The factory is called and
+ * injected with dependencies (if specified) and returns the interceptor.
+ *
+ * There are two kinds of interceptors (and two kinds of rejection interceptors):
+ *
+ * * `request`: interceptors get called with http `config` object. The function is free to modify
+ * the `config` or create a new one. The function needs to return the `config` directly or as a
+ * promise.
+ * * `requestError`: interceptor gets called when a previous interceptor threw an error or resolved
+ * with a rejection.
+ * * `response`: interceptors get called with http `response` object. The function is free to modify
+ * the `response` or create a new one. The function needs to return the `response` directly or as a
+ * promise.
+ * * `responseError`: interceptor gets called when a previous interceptor threw an error or resolved
+ * with a rejection.
+ *
+ *
+ * <pre>
+ * // register the interceptor as a service
+ * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
+ * return {
+ * // optional method
+ * 'request': function(config) {
+ * // do something on success
+ * return config || $q.when(config);
+ * },
+ *
+ * // optional method
+ * 'requestError': function(rejection) {
+ * // do something on error
+ * if (canRecover(rejection)) {
+ * return responseOrNewPromise
+ * }
+ * return $q.reject(rejection);
+ * },
+ *
+ *
+ *
+ * // optional method
+ * 'response': function(response) {
+ * // do something on success
+ * return response || $q.when(response);
+ * },
+ *
+ * // optional method
+ * 'responseError': function(rejection) {
+ * // do something on error
+ * if (canRecover(rejection)) {
+ * return responseOrNewPromise
+ * }
+ * return $q.reject(rejection);
+ * };
+ * }
+ * });
+ *
+ * $httpProvider.interceptors.push('myHttpInterceptor');
+ *
+ *
+ * // register the interceptor via an anonymous factory
+ * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
+ * return {
+ * 'request': function(config) {
+ * // same as above
+ * },
+ * 'response': function(response) {
+ * // same as above
+ * }
+ * });
+ * </pre>
+ *
+ * # Response interceptors (DEPRECATED)
+ *
+ * Before you start creating interceptors, be sure to understand the
+ * {@link ng.$q $q and deferred/promise APIs}.
+ *
+ * For purposes of global error handling, authentication or any kind of synchronous or
+ * asynchronous preprocessing of received responses, it is desirable to be able to intercept
+ * responses for http requests before they are handed over to the application code that
+ * initiated these requests. The response interceptors leverage the {@link ng.$q
+ * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
+ *
+ * The interceptors are service factories that are registered with the $httpProvider by
+ * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
+ * injected with dependencies (if specified) and returns the interceptor — a function that
+ * takes a {@link ng.$q promise} and returns the original or a new promise.
+ *
+ * <pre>
+ * // register the interceptor as a service
+ * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
+ * return function(promise) {
+ * return promise.then(function(response) {
+ * // do something on success
+ * }, function(response) {
+ * // do something on error
+ * if (canRecover(response)) {
+ * return responseOrNewPromise
+ * }
+ * return $q.reject(response);
+ * });
+ * }
+ * });
+ *
+ * $httpProvider.responseInterceptors.push('myHttpInterceptor');
+ *
+ *
+ * // register the interceptor via an anonymous factory
+ * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
+ * return function(promise) {
+ * // same as above
+ * }
+ * });
+ * </pre>
+ *
+ *
+ * # Security Considerations
+ *
+ * When designing web applications, consider security threats from:
+ *
+ * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
+ * JSON vulnerability}
+ * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}
+ *
+ * Both server and the client must cooperate in order to eliminate these threats. Angular comes
+ * pre-configured with strategies that address these issues, but for this to work backend server
+ * cooperation is required.
+ *
+ * ## JSON Vulnerability Protection
+ *
+ * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
+ * JSON vulnerability} allows third party website to turn your JSON resource URL into
+ * {@link http://en.wikipedia.org/wiki/JSONP JSONP} request under some conditions. To
+ * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
+ * Angular will automatically strip the prefix before processing it as JSON.
+ *
+ * For example if your server needs to return:
+ * <pre>
+ * ['one','two']
+ * </pre>
+ *
+ * which is vulnerable to attack, your server can return:
+ * <pre>
+ * )]}',
+ * ['one','two']
+ * </pre>
+ *
+ * Angular will strip the prefix, before processing the JSON.
+ *
+ *
+ * ## Cross Site Request Forgery (XSRF) Protection
+ *
+ * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which
+ * an unauthorized site can gain your user's private data. Angular provides a mechanism
+ * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
+ * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
+ * JavaScript that runs on your domain could read the cookie, your server can be assured that
+ * the XHR came from JavaScript running on your domain. The header will not be set for
+ * cross-domain requests.
+ *
+ * To take advantage of this, your server needs to set a token in a JavaScript readable session
+ * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
+ * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
+ * that only JavaScript running on your domain could have sent the request. The token must be
+ * unique for each user and must be verifiable by the server (to prevent the JavaScript from making
+ * up its own tokens). We recommend that the token is a digest of your site's authentication
+ * cookie with a {@link https://en.wikipedia.org/wiki/Salt_(cryptography) salt} for added security.
+ *
+ * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
+ * properties of either $httpProvider.defaults, or the per-request config object.
+ *
+ *
+ * @param {object} config Object describing the request to be made and how it should be
+ * processed. The object has following properties:
+ *
+ * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
+ * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
+ * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to
+ * `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified.
+ * - **data** – `{string|Object}` – Data to be sent as the request message data.
+ * - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server.
+ * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
+ * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
+ * - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
+ * transform function or an array of such functions. The transform function takes the http
+ * request body and headers and returns its transformed (typically serialized) version.
+ * - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
+ * transform function or an array of such functions. The transform function takes the http
+ * response body and headers and returns its transformed (typically deserialized) version.
+ * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
+ * GET request, otherwise if a cache instance built with
+ * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
+ * caching.
+ * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
+ * that should abort the request when resolved.
+ * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the
+ * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
+ * requests with credentials} for more information.
+ * - **responseType** - `{string}` - see {@link
+ * https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}.
+ *
+ * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
+ * standard `then` method and two http specific methods: `success` and `error`. The `then`
+ * method takes two arguments a success and an error callback which will be called with a
+ * response object. The `success` and `error` methods take a single argument - a function that
+ * will be called when the request succeeds or fails respectively. The arguments passed into
+ * these functions are destructured representation of the response object passed into the
+ * `then` method. The response object has these properties:
+ *
+ * - **data** – `{string|Object}` – The response body transformed with the transform functions.
+ * - **status** – `{number}` – HTTP status code of the response.
+ * - **headers** – `{function([headerName])}` – Header getter function.
+ * - **config** – `{Object}` – The configuration object that was used to generate the request.
+ *
+ * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
+ * requests. This is primarily meant to be used for debugging purposes.
+ *
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <div ng-controller="FetchCtrl">
+ <select ng-model="method">
+ <option>GET</option>
+ <option>JSONP</option>
+ </select>
+ <input type="text" ng-model="url" size="80"/>
+ <button ng-click="fetch()">fetch</button><br>
+ <button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
+ <button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button>
+ <button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button>
+ <pre>http status code: {{status}}</pre>
+ <pre>http response data: {{data}}</pre>
+ </div>
+ </file>
+ <file name="script.js">
+ function FetchCtrl($scope, $http, $templateCache) {
+ $scope.method = 'GET';
+ $scope.url = 'http-hello.html';
+
+ $scope.fetch = function() {
+ $scope.code = null;
+ $scope.response = null;
+
+ $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
+ success(function(data, status) {
+ $scope.status = status;
+ $scope.data = data;
+ }).
+ error(function(data, status) {
+ $scope.data = data || "Request failed";
+ $scope.status = status;
+ });
+ };
+
+ $scope.updateModel = function(method, url) {
+ $scope.method = method;
+ $scope.url = url;
+ };
+ }
+ </file>
+ <file name="http-hello.html">
+ Hello, $http!
+ </file>
+ <file name="scenario.js">
+ it('should make an xhr GET request', function() {
+ element(':button:contains("Sample GET")').click();
+ element(':button:contains("fetch")').click();
+ expect(binding('status')).toBe('200');
+ expect(binding('data')).toMatch(/Hello, \$http!/);
+ });
+
+ it('should make a JSONP request to angularjs.org', function() {
+ element(':button:contains("Sample JSONP")').click();
+ element(':button:contains("fetch")').click();
+ expect(binding('status')).toBe('200');
+ expect(binding('data')).toMatch(/Super Hero!/);
+ });
+
+ it('should make JSONP request to invalid URL and invoke the error handler',
+ function() {
+ element(':button:contains("Invalid JSONP")').click();
+ element(':button:contains("fetch")').click();
+ expect(binding('status')).toBe('0');
+ expect(binding('data')).toBe('Request failed');
+ });
+ </file>
+ </example>
+ */
+ function $http(requestConfig) {
+ var config = {
+ transformRequest: defaults.transformRequest,
+ transformResponse: defaults.transformResponse
+ };
+ var headers = {};
+
+ extend(config, requestConfig);
+ config.headers = headers;
+ config.method = uppercase(config.method);
+
+ extend(headers,
+ defaults.headers.common,
+ defaults.headers[lowercase(config.method)],
+ requestConfig.headers);
+
+ var xsrfValue = isSameDomain(config.url, $browser.url())
+ ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
+ : undefined;
+ if (xsrfValue) {
+ headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
+ }
+
+
+ var serverRequest = function(config) {
+ var reqData = transformData(config.data, headersGetter(headers), config.transformRequest);
+
+ // strip content-type if data is undefined
+ if (isUndefined(config.data)) {
+ delete headers['Content-Type'];
+ }
+
+ if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
+ config.withCredentials = defaults.withCredentials;
+ }
+
+ // send request
+ return sendReq(config, reqData, headers).then(transformResponse, transformResponse);
+ };
+
+ var chain = [serverRequest, undefined];
+ var promise = $q.when(config);
+
+ // apply interceptors
+ forEach(reversedInterceptors, function(interceptor) {
+ if (interceptor.request || interceptor.requestError) {
+ chain.unshift(interceptor.request, interceptor.requestError);
+ }
+ if (interceptor.response || interceptor.responseError) {
+ chain.push(interceptor.response, interceptor.responseError);
+ }
+ });
+
+ while(chain.length) {
+ var thenFn = chain.shift();
+ var rejectFn = chain.shift();
+
+ promise = promise.then(thenFn, rejectFn);
+ }
+
+ promise.success = function(fn) {
+ promise.then(function(response) {
+ fn(response.data, response.status, response.headers, config);
+ });
+ return promise;
+ };
+
+ promise.error = function(fn) {
+ promise.then(null, function(response) {
+ fn(response.data, response.status, response.headers, config);
+ });
+ return promise;
+ };
+
+ return promise;
+
+ function transformResponse(response) {
+ // make a copy since the response must be cacheable
+ var resp = extend({}, response, {
+ data: transformData(response.data, response.headers, config.transformResponse)
+ });
+ return (isSuccess(response.status))
+ ? resp
+ : $q.reject(resp);
+ }
+ }
+
+ $http.pendingRequests = [];
+
+ /**
+ * @ngdoc method
+ * @name ng.$http#get
+ * @methodOf ng.$http
+ *
+ * @description
+ * Shortcut method to perform `GET` request.
+ *
+ * @param {string} url Relative or absolute URL specifying the destination of the request
+ * @param {Object=} config Optional configuration object
+ * @returns {HttpPromise} Future object
+ */
+
+ /**
+ * @ngdoc method
+ * @name ng.$http#delete
+ * @methodOf ng.$http
+ *
+ * @description
+ * Shortcut method to perform `DELETE` request.
+ *
+ * @param {string} url Relative or absolute URL specifying the destination of the request
+ * @param {Object=} config Optional configuration object
+ * @returns {HttpPromise} Future object
+ */
+
+ /**
+ * @ngdoc method
+ * @name ng.$http#head
+ * @methodOf ng.$http
+ *
+ * @description
+ * Shortcut method to perform `HEAD` request.
+ *
+ * @param {string} url Relative or absolute URL specifying the destination of the request
+ * @param {Object=} config Optional configuration object
+ * @returns {HttpPromise} Future object
+ */
+
+ /**
+ * @ngdoc method
+ * @name ng.$http#jsonp
+ * @methodOf ng.$http
+ *
+ * @description
+ * Shortcut method to perform `JSONP` request.
+ *
+ * @param {string} url Relative or absolute URL specifying the destination of the request.
+ * Should contain `JSON_CALLBACK` string.
+ * @param {Object=} config Optional configuration object
+ * @returns {HttpPromise} Future object
+ */
+ createShortMethods('get', 'delete', 'head', 'jsonp');
+
+ /**
+ * @ngdoc method
+ * @name ng.$http#post
+ * @methodOf ng.$http
+ *
+ * @description
+ * Shortcut method to perform `POST` request.
+ *
+ * @param {string} url Relative or absolute URL specifying the destination of the request
+ * @param {*} data Request content
+ * @param {Object=} config Optional configuration object
+ * @returns {HttpPromise} Future object
+ */
+
+ /**
+ * @ngdoc method
+ * @name ng.$http#put
+ * @methodOf ng.$http
+ *
+ * @description
+ * Shortcut method to perform `PUT` request.
+ *
+ * @param {string} url Relative or absolute URL specifying the destination of the request
+ * @param {*} data Request content
+ * @param {Object=} config Optional configuration object
+ * @returns {HttpPromise} Future object
+ */
+ createShortMethodsWithData('post', 'put');
+
+ /**
+ * @ngdoc property
+ * @name ng.$http#defaults
+ * @propertyOf ng.$http
+ *
+ * @description
+ * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
+ * default headers, withCredentials as well as request and response transformations.
+ *
+ * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
+ */
+ $http.defaults = defaults;
+
+
+ return $http;
+
+
+ function createShortMethods(names) {
+ forEach(arguments, function(name) {
+ $http[name] = function(url, config) {
+ return $http(extend(config || {}, {
+ method: name,
+ url: url
+ }));
+ };
+ });
+ }
+
+
+ function createShortMethodsWithData(name) {
+ forEach(arguments, function(name) {
+ $http[name] = function(url, data, config) {
+ return $http(extend(config || {}, {
+ method: name,
+ url: url,
+ data: data
+ }));
+ };
+ });
+ }
+
+
+ /**
+ * Makes the request.
+ *
+ * !!! ACCESSES CLOSURE VARS:
+ * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
+ */
+ function sendReq(config, reqData, reqHeaders) {
+ var deferred = $q.defer(),
+ promise = deferred.promise,
+ cache,
+ cachedResp,
+ url = buildUrl(config.url, config.params);
+
+ $http.pendingRequests.push(config);
+ promise.then(removePendingReq, removePendingReq);
+
+
+ if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') {
+ cache = isObject(config.cache) ? config.cache
+ : isObject(defaults.cache) ? defaults.cache
+ : defaultCache;
+ }
+
+ if (cache) {
+ cachedResp = cache.get(url);
+ if (cachedResp) {
+ if (cachedResp.then) {
+ // cached request has already been sent, but there is no response yet
+ cachedResp.then(removePendingReq, removePendingReq);
+ return cachedResp;
+ } else {
+ // serving from cache
+ if (isArray(cachedResp)) {
+ resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2]));
+ } else {
+ resolvePromise(cachedResp, 200, {});
+ }
+ }
+ } else {
+ // put the promise for the non-transformed response into cache as a placeholder
+ cache.put(url, promise);
+ }
+ }
+
+ // if we won't have the response in cache, send the request to the backend
+ if (!cachedResp) {
+ $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
+ config.withCredentials, config.responseType);
+ }
+
+ return promise;
+
+
+ /**
+ * Callback registered to $httpBackend():
+ * - caches the response if desired
+ * - resolves the raw $http promise
+ * - calls $apply
+ */
+ function done(status, response, headersString) {
+ if (cache) {
+ if (isSuccess(status)) {
+ cache.put(url, [status, response, parseHeaders(headersString)]);
+ } else {
+ // remove promise from the cache
+ cache.remove(url);
+ }
+ }
+
+ resolvePromise(response, status, headersString);
+ if (!$rootScope.$$phase) $rootScope.$apply();
+ }
+
+
+ /**
+ * Resolves the raw $http promise.
+ */
+ function resolvePromise(response, status, headers) {
+ // normalize internal statuses to 0
+ status = Math.max(status, 0);
+
+ (isSuccess(status) ? deferred.resolve : deferred.reject)({
+ data: response,
+ status: status,
+ headers: headersGetter(headers),
+ config: config
+ });
+ }
+
+
+ function removePendingReq() {
+ var idx = indexOf($http.pendingRequests, config);
+ if (idx !== -1) $http.pendingRequests.splice(idx, 1);
+ }
+ }
+
+
+ function buildUrl(url, params) {
+ if (!params) return url;
+ var parts = [];
+ forEachSorted(params, function(value, key) {
+ if (value == null || value == undefined) return;
+ if (!isArray(value)) value = [value];
+
+ forEach(value, function(v) {
+ if (isObject(v)) {
+ v = toJson(v);
+ }
+ parts.push(encodeUriQuery(key) + '=' +
+ encodeUriQuery(v));
+ });
+ });
+ return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
+ }
+
+
+ }];
+}
+
+var XHR = window.XMLHttpRequest || function() {
+ try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
+ try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
+ try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
+ throw new Error("This browser does not support XMLHttpRequest.");
+};
+
+
+/**
+ * @ngdoc object
+ * @name ng.$httpBackend
+ * @requires $browser
+ * @requires $window
+ * @requires $document
+ *
+ * @description
+ * HTTP backend used by the {@link ng.$http service} that delegates to
+ * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
+ *
+ * You should never need to use this service directly, instead use the higher-level abstractions:
+ * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
+ *
+ * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
+ * $httpBackend} which can be trained with responses.
+ */
+function $HttpBackendProvider() {
+ this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
+ return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks,
+ $document[0], $window.location.protocol.replace(':', ''));
+ }];
+}
+
+function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) {
+ // TODO(vojta): fix the signature
+ return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
+ var status;
+ $browser.$$incOutstandingRequestCount();
+ url = url || $browser.url();
+
+ if (lowercase(method) == 'jsonp') {
+ var callbackId = '_' + (callbacks.counter++).toString(36);
+ callbacks[callbackId] = function(data) {
+ callbacks[callbackId].data = data;
+ };
+
+ var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
+ function() {
+ if (callbacks[callbackId].data) {
+ completeRequest(callback, 200, callbacks[callbackId].data);
+ } else {
+ completeRequest(callback, status || -2);
+ }
+ delete callbacks[callbackId];
+ });
+ } else {
+ var xhr = new XHR();
+ xhr.open(method, url, true);
+ forEach(headers, function(value, key) {
+ if (value) xhr.setRequestHeader(key, value);
+ });
+
+ // In IE6 and 7, this might be called synchronously when xhr.send below is called and the
+ // response is in the cache. the promise api will ensure that to the app code the api is
+ // always async
+ xhr.onreadystatechange = function() {
+ if (xhr.readyState == 4) {
+ var responseHeaders = xhr.getAllResponseHeaders();
+
+ // TODO(vojta): remove once Firefox 21 gets released.
+ // begin: workaround to overcome Firefox CORS http response headers bug
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=608735
+ // Firefox already patched in nightly. Should land in Firefox 21.
+
+ // CORS "simple response headers" http://www.w3.org/TR/cors/
+ var value,
+ simpleHeaders = ["Cache-Control", "Content-Language", "Content-Type",
+ "Expires", "Last-Modified", "Pragma"];
+ if (!responseHeaders) {
+ responseHeaders = "";
+ forEach(simpleHeaders, function (header) {
+ var value = xhr.getResponseHeader(header);
+ if (value) {
+ responseHeaders += header + ": " + value + "\n";
+ }
+ });
+ }
+ // end of the workaround.
+
+ // responseText is the old-school way of retrieving response (supported by IE8 & 9)
+ // response and responseType properties were introduced in XHR Level2 spec (supported by IE10)
+ completeRequest(callback,
+ status || xhr.status,
+ (xhr.responseType ? xhr.response : xhr.responseText),
+ responseHeaders);
+ }
+ };
+
+ if (withCredentials) {
+ xhr.withCredentials = true;
+ }
+
+ if (responseType) {
+ xhr.responseType = responseType;
+ }
+
+ xhr.send(post || '');
+ }
+
+ if (timeout > 0) {
+ var timeoutId = $browserDefer(timeoutRequest, timeout);
+ } else if (timeout && timeout.then) {
+ timeout.then(timeoutRequest);
+ }
+
+
+ function timeoutRequest() {
+ status = -1;
+ jsonpDone && jsonpDone();
+ xhr && xhr.abort();
+ }
+
+ function completeRequest(callback, status, response, headersString) {
+ // URL_MATCH is defined in src/service/location.js
+ var protocol = (url.match(SERVER_MATCH) || ['', locationProtocol])[1];
+
+ // cancel timeout and subsequent timeout promise resolution
+ timeoutId && $browserDefer.cancel(timeoutId);
+ jsonpDone = xhr = null;
+
+ // fix status code for file protocol (it's always 0)
+ status = (protocol == 'file') ? (response ? 200 : 404) : status;
+
+ // normalize IE bug (http://bugs.jquery.com/ticket/1450)
+ status = status == 1223 ? 204 : status;
+
+ callback(status, response, headersString);
+ $browser.$$completeOutstandingRequest(noop);
+ }
+ };
+
+ function jsonpReq(url, done) {
+ // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
+ // - fetches local scripts via XHR and evals them
+ // - adds and immediately removes script elements from the document
+ var script = rawDocument.createElement('script'),
+ doneWrapper = function() {
+ rawDocument.body.removeChild(script);
+ if (done) done();
+ };
+
+ script.type = 'text/javascript';
+ script.src = url;
+
+ if (msie) {
+ script.onreadystatechange = function() {
+ if (/loaded|complete/.test(script.readyState)) doneWrapper();
+ };
+ } else {
+ script.onload = script.onerror = doneWrapper;
+ }
+
+ rawDocument.body.appendChild(script);
+ return doneWrapper;
+ }
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$locale
+ *
+ * @description
+ * $locale service provides localization rules for various Angular components. As of right now the
+ * only public api is:
+ *
+ * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
+ */
+function $LocaleProvider(){
+ this.$get = function() {
+ return {
+ id: 'en-us',
+
+ NUMBER_FORMATS: {
+ DECIMAL_SEP: '.',
+ GROUP_SEP: ',',
+ PATTERNS: [
+ { // Decimal Pattern
+ minInt: 1,
+ minFrac: 0,
+ maxFrac: 3,
+ posPre: '',
+ posSuf: '',
+ negPre: '-',
+ negSuf: '',
+ gSize: 3,
+ lgSize: 3
+ },{ //Currency Pattern
+ minInt: 1,
+ minFrac: 2,
+ maxFrac: 2,
+ posPre: '\u00A4',
+ posSuf: '',
+ negPre: '(\u00A4',
+ negSuf: ')',
+ gSize: 3,
+ lgSize: 3
+ }
+ ],
+ CURRENCY_SYM: '$'
+ },
+
+ DATETIME_FORMATS: {
+ MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December'
+ .split(','),
+ SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
+ DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
+ SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
+ AMPMS: ['AM','PM'],
+ medium: 'MMM d, y h:mm:ss a',
+ short: 'M/d/yy h:mm a',
+ fullDate: 'EEEE, MMMM d, y',
+ longDate: 'MMMM d, y',
+ mediumDate: 'MMM d, y',
+ shortDate: 'M/d/yy',
+ mediumTime: 'h:mm:ss a',
+ shortTime: 'h:mm a'
+ },
+
+ pluralCat: function(num) {
+ if (num === 1) {
+ return 'one';
+ }
+ return 'other';
+ }
+ };
+ };
+}
+
+function $TimeoutProvider() {
+ this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
+ function($rootScope, $browser, $q, $exceptionHandler) {
+ var deferreds = {};
+
+
+ /**
+ * @ngdoc function
+ * @name ng.$timeout
+ * @requires $browser
+ *
+ * @description
+ * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
+ * block and delegates any exceptions to
+ * {@link ng.$exceptionHandler $exceptionHandler} service.
+ *
+ * The return value of registering a timeout function is a promise, which will be resolved when
+ * the timeout is reached and the timeout function is executed.
+ *
+ * To cancel a timeout request, call `$timeout.cancel(promise)`.
+ *
+ * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
+ * synchronously flush the queue of deferred functions.
+ *
+ * @param {function()} fn A function, whose execution should be delayed.
+ * @param {number=} [delay=0] Delay in milliseconds.
+ * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
+ * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
+ * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
+ * promise will be resolved with is the return value of the `fn` function.
+ */
+ function timeout(fn, delay, invokeApply) {
+ var deferred = $q.defer(),
+ promise = deferred.promise,
+ skipApply = (isDefined(invokeApply) && !invokeApply),
+ timeoutId, cleanup;
+
+ timeoutId = $browser.defer(function() {
+ try {
+ deferred.resolve(fn());
+ } catch(e) {
+ deferred.reject(e);
+ $exceptionHandler(e);
+ }
+
+ if (!skipApply) $rootScope.$apply();
+ }, delay);
+
+ cleanup = function() {
+ delete deferreds[promise.$$timeoutId];
+ };
+
+ promise.$$timeoutId = timeoutId;
+ deferreds[timeoutId] = deferred;
+ promise.then(cleanup, cleanup);
+
+ return promise;
+ }
+
+
+ /**
+ * @ngdoc function
+ * @name ng.$timeout#cancel
+ * @methodOf ng.$timeout
+ *
+ * @description
+ * Cancels a task associated with the `promise`. As a result of this, the promise will be
+ * resolved with a rejection.
+ *
+ * @param {Promise=} promise Promise returned by the `$timeout` function.
+ * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
+ * canceled.
+ */
+ timeout.cancel = function(promise) {
+ if (promise && promise.$$timeoutId in deferreds) {
+ deferreds[promise.$$timeoutId].reject('canceled');
+ return $browser.defer.cancel(promise.$$timeoutId);
+ }
+ return false;
+ };
+
+ return timeout;
+ }];
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$filterProvider
+ * @description
+ *
+ * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To
+ * achieve this a filter definition consists of a factory function which is annotated with dependencies and is
+ * responsible for creating a filter function.
+ *
+ * <pre>
+ * // Filter registration
+ * function MyModule($provide, $filterProvider) {
+ * // create a service to demonstrate injection (not always needed)
+ * $provide.value('greet', function(name){
+ * return 'Hello ' + name + '!';
+ * });
+ *
+ * // register a filter factory which uses the
+ * // greet service to demonstrate DI.
+ * $filterProvider.register('greet', function(greet){
+ * // return the filter function which uses the greet service
+ * // to generate salutation
+ * return function(text) {
+ * // filters need to be forgiving so check input validity
+ * return text && greet(text) || text;
+ * };
+ * });
+ * }
+ * </pre>
+ *
+ * The filter function is registered with the `$injector` under the filter name suffixe with `Filter`.
+ * <pre>
+ * it('should be the same instance', inject(
+ * function($filterProvider) {
+ * $filterProvider.register('reverse', function(){
+ * return ...;
+ * });
+ * },
+ * function($filter, reverseFilter) {
+ * expect($filter('reverse')).toBe(reverseFilter);
+ * });
+ * </pre>
+ *
+ *
+ * For more information about how angular filters work, and how to create your own filters, see
+ * {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer
+ * Guide.
+ */
+/**
+ * @ngdoc method
+ * @name ng.$filterProvider#register
+ * @methodOf ng.$filterProvider
+ * @description
+ * Register filter factory function.
+ *
+ * @param {String} name Name of the filter.
+ * @param {function} fn The filter factory function which is injectable.
+ */
+
+
+/**
+ * @ngdoc function
+ * @name ng.$filter
+ * @function
+ * @description
+ * Filters are used for formatting data displayed to the user.
+ *
+ * The general syntax in templates is as follows:
+ *
+ * {{ expression [| filter_name[:parameter_value] ... ] }}
+ *
+ * @param {String} name Name of the filter function to retrieve
+ * @return {Function} the filter function
+ */
+$FilterProvider.$inject = ['$provide'];
+function $FilterProvider($provide) {
+ var suffix = 'Filter';
+
+ function register(name, factory) {
+ return $provide.factory(name + suffix, factory);
+ }
+ this.register = register;
+
+ this.$get = ['$injector', function($injector) {
+ return function(name) {
+ return $injector.get(name + suffix);
+ }
+ }];
+
+ ////////////////////////////////////////
+
+ register('currency', currencyFilter);
+ register('date', dateFilter);
+ register('filter', filterFilter);
+ register('json', jsonFilter);
+ register('limitTo', limitToFilter);
+ register('lowercase', lowercaseFilter);
+ register('number', numberFilter);
+ register('orderBy', orderByFilter);
+ register('uppercase', uppercaseFilter);
+}
+
+/**
+ * @ngdoc filter
+ * @name ng.filter:filter
+ * @function
+ *
+ * @description
+ * Selects a subset of items from `array` and returns it as a new array.
+ *
+ * Note: This function is used to augment the `Array` type in Angular expressions. See
+ * {@link ng.$filter} for more information about Angular arrays.
+ *
+ * @param {Array} array The source array.
+ * @param {string|Object|function()} expression The predicate to be used for selecting items from
+ * `array`.
+ *
+ * Can be one of:
+ *
+ * - `string`: Predicate that results in a substring match using the value of `expression`
+ * string. All strings or objects with string properties in `array` that contain this string
+ * will be returned. The predicate can be negated by prefixing the string with `!`.
+ *
+ * - `Object`: A pattern object can be used to filter specific properties on objects contained
+ * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
+ * which have property `name` containing "M" and property `phone` containing "1". A special
+ * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
+ * property of the object. That's equivalent to the simple substring match with a `string`
+ * as described above.
+ *
+ * - `function`: A predicate function can be used to write arbitrary filters. The function is
+ * called for each element of `array`. The final result is an array of those elements that
+ * the predicate returned true for.
+ *
+ * @param {function(expected, actual)|true|undefined} comparator Comparator which is used in
+ * determining if the expected value (from the filter expression) and actual value (from
+ * the object in the array) should be considered a match.
+ *
+ * Can be one of:
+ *
+ * - `function(expected, actual)`:
+ * The function will be given the object value and the predicate value to compare and
+ * should return true if the item should be included in filtered result.
+ *
+ * - `true`: A shorthand for `function(expected, actual) { return angular.equals(expected, actual)}`.
+ * this is essentially strict comparison of expected and actual.
+ *
+ * - `false|undefined`: A short hand for a function which will look for a substring match in case
+ * insensitive way.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <div ng-init="friends = [{name:'John', phone:'555-1276'},
+ {name:'Mary', phone:'800-BIG-MARY'},
+ {name:'Mike', phone:'555-4321'},
+ {name:'Adam', phone:'555-5678'},
+ {name:'Julie', phone:'555-8765'},
+ {name:'Juliette', phone:'555-5678'}]"></div>
+
+ Search: <input ng-model="searchText">
+ <table id="searchTextResults">
+ <tr><th>Name</th><th>Phone</th></tr>
+ <tr ng-repeat="friend in friends | filter:searchText">
+ <td>{{friend.name}}</td>
+ <td>{{friend.phone}}</td>
+ </tr>
+ </table>
+ <hr>
+ Any: <input ng-model="search.$"> <br>
+ Name only <input ng-model="search.name"><br>
+ Phone only <input ng-model="search.phone"><br>
+ Equality <input type="checkbox" ng-model="strict"><br>
+ <table id="searchObjResults">
+ <tr><th>Name</th><th>Phone</th></tr>
+ <tr ng-repeat="friend in friends | filter:search:strict">
+ <td>{{friend.name}}</td>
+ <td>{{friend.phone}}</td>
+ </tr>
+ </table>
+ </doc:source>
+ <doc:scenario>
+ it('should search across all fields when filtering with a string', function() {
+ input('searchText').enter('m');
+ expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
+ toEqual(['Mary', 'Mike', 'Adam']);
+
+ input('searchText').enter('76');
+ expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
+ toEqual(['John', 'Julie']);
+ });
+
+ it('should search in specific fields when filtering with a predicate object', function() {
+ input('search.$').enter('i');
+ expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
+ toEqual(['Mary', 'Mike', 'Julie', 'Juliette']);
+ });
+ it('should use a equal comparison when comparator is true', function() {
+ input('search.name').enter('Julie');
+ input('strict').check();
+ expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
+ toEqual(['Julie']);
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+function filterFilter() {
+ return function(array, expression, comperator) {
+ if (!isArray(array)) return array;
+ var predicates = [];
+ predicates.check = function(value) {
+ for (var j = 0; j < predicates.length; j++) {
+ if(!predicates[j](value)) {
+ return false;
+ }
+ }
+ return true;
+ };
+ switch(typeof comperator) {
+ case "function":
+ break;
+ case "boolean":
+ if(comperator == true) {
+ comperator = function(obj, text) {
+ return angular.equals(obj, text);
+ }
+ break;
+ }
+ default:
+ comperator = function(obj, text) {
+ text = (''+text).toLowerCase();
+ return (''+obj).toLowerCase().indexOf(text) > -1
+ };
+ }
+ var search = function(obj, text){
+ if (typeof text == 'string' && text.charAt(0) === '!') {
+ return !search(obj, text.substr(1));
+ }
+ switch (typeof obj) {
+ case "boolean":
+ case "number":
+ case "string":
+ return comperator(obj, text);
+ case "object":
+ switch (typeof text) {
+ case "object":
+ return comperator(obj, text);
+ break;
+ default:
+ for ( var objKey in obj) {
+ if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
+ return true;
+ }
+ }
+ break;
+ }
+ return false;
+ case "array":
+ for ( var i = 0; i < obj.length; i++) {
+ if (search(obj[i], text)) {
+ return true;
+ }
+ }
+ return false;
+ default:
+ return false;
+ }
+ };
+ switch (typeof expression) {
+ case "boolean":
+ case "number":
+ case "string":
+ expression = {$:expression};
+ case "object":
+ for (var key in expression) {
+ if (key == '$') {
+ (function() {
+ if (!expression[key]) return;
+ var path = key
+ predicates.push(function(value) {
+ return search(value, expression[path]);
+ });
+ })();
+ } else {
+ (function() {
+ if (!expression[key]) return;
+ var path = key;
+ predicates.push(function(value) {
+ return search(getter(value,path), expression[path]);
+ });
+ })();
+ }
+ }
+ break;
+ case 'function':
+ predicates.push(expression);
+ break;
+ default:
+ return array;
+ }
+ var filtered = [];
+ for ( var j = 0; j < array.length; j++) {
+ var value = array[j];
+ if (predicates.check(value)) {
+ filtered.push(value);
+ }
+ }
+ return filtered;
+ }
+}
+
+/**
+ * @ngdoc filter
+ * @name ng.filter:currency
+ * @function
+ *
+ * @description
+ * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
+ * symbol for current locale is used.
+ *
+ * @param {number} amount Input to filter.
+ * @param {string=} symbol Currency symbol or identifier to be displayed.
+ * @returns {string} Formatted number.
+ *
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.amount = 1234.56;
+ }
+ </script>
+ <div ng-controller="Ctrl">
+ <input type="number" ng-model="amount"> <br>
+ default currency symbol ($): {{amount | currency}}<br>
+ custom currency identifier (USD$): {{amount | currency:"USD$"}}
+ </div>
+ </doc:source>
+ <doc:scenario>
+ it('should init with 1234.56', function() {
+ expect(binding('amount | currency')).toBe('$1,234.56');
+ expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
+ });
+ it('should update', function() {
+ input('amount').enter('-1234');
+ expect(binding('amount | currency')).toBe('($1,234.00)');
+ expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+currencyFilter.$inject = ['$locale'];
+function currencyFilter($locale) {
+ var formats = $locale.NUMBER_FORMATS;
+ return function(amount, currencySymbol){
+ if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
+ return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
+ replace(/\u00A4/g, currencySymbol);
+ };
+}
+
+/**
+ * @ngdoc filter
+ * @name ng.filter:number
+ * @function
+ *
+ * @description
+ * Formats a number as text.
+ *
+ * If the input is not a number an empty string is returned.
+ *
+ * @param {number|string} number Number to format.
+ * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to.
+ * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.val = 1234.56789;
+ }
+ </script>
+ <div ng-controller="Ctrl">
+ Enter number: <input ng-model='val'><br>
+ Default formatting: {{val | number}}<br>
+ No fractions: {{val | number:0}}<br>
+ Negative number: {{-val | number:4}}
+ </div>
+ </doc:source>
+ <doc:scenario>
+ it('should format numbers', function() {
+ expect(binding('val | number')).toBe('1,234.568');
+ expect(binding('val | number:0')).toBe('1,235');
+ expect(binding('-val | number:4')).toBe('-1,234.5679');
+ });
+
+ it('should update', function() {
+ input('val').enter('3374.333');
+ expect(binding('val | number')).toBe('3,374.333');
+ expect(binding('val | number:0')).toBe('3,374');
+ expect(binding('-val | number:4')).toBe('-3,374.3330');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+
+
+numberFilter.$inject = ['$locale'];
+function numberFilter($locale) {
+ var formats = $locale.NUMBER_FORMATS;
+ return function(number, fractionSize) {
+ return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
+ fractionSize);
+ };
+}
+
+var DECIMAL_SEP = '.';
+function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
+ if (isNaN(number) || !isFinite(number)) return '';
+
+ var isNegative = number < 0;
+ number = Math.abs(number);
+ var numStr = number + '',
+ formatedText = '',
+ parts = [];
+
+ var hasExponent = false;
+ if (numStr.indexOf('e') !== -1) {
+ var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
+ if (match && match[2] == '-' && match[3] > fractionSize + 1) {
+ numStr = '0';
+ } else {
+ formatedText = numStr;
+ hasExponent = true;
+ }
+ }
+
+ if (!hasExponent) {
+ var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
+
+ // determine fractionSize if it is not specified
+ if (isUndefined(fractionSize)) {
+ fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
+ }
+
+ var pow = Math.pow(10, fractionSize);
+ number = Math.round(number * pow) / pow;
+ var fraction = ('' + number).split(DECIMAL_SEP);
+ var whole = fraction[0];
+ fraction = fraction[1] || '';
+
+ var pos = 0,
+ lgroup = pattern.lgSize,
+ group = pattern.gSize;
+
+ if (whole.length >= (lgroup + group)) {
+ pos = whole.length - lgroup;
+ for (var i = 0; i < pos; i++) {
+ if ((pos - i)%group === 0 && i !== 0) {
+ formatedText += groupSep;
+ }
+ formatedText += whole.charAt(i);
+ }
+ }
+
+ for (i = pos; i < whole.length; i++) {
+ if ((whole.length - i)%lgroup === 0 && i !== 0) {
+ formatedText += groupSep;
+ }
+ formatedText += whole.charAt(i);
+ }
+
+ // format fraction part.
+ while(fraction.length < fractionSize) {
+ fraction += '0';
+ }
+
+ if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
+ }
+
+ parts.push(isNegative ? pattern.negPre : pattern.posPre);
+ parts.push(formatedText);
+ parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
+ return parts.join('');
+}
+
+function padNumber(num, digits, trim) {
+ var neg = '';
+ if (num < 0) {
+ neg = '-';
+ num = -num;
+ }
+ num = '' + num;
+ while(num.length < digits) num = '0' + num;
+ if (trim)
+ num = num.substr(num.length - digits);
+ return neg + num;
+}
+
+
+function dateGetter(name, size, offset, trim) {
+ offset = offset || 0;
+ return function(date) {
+ var value = date['get' + name]();
+ if (offset > 0 || value > -offset)
+ value += offset;
+ if (value === 0 && offset == -12 ) value = 12;
+ return padNumber(value, size, trim);
+ };
+}
+
+function dateStrGetter(name, shortForm) {
+ return function(date, formats) {
+ var value = date['get' + name]();
+ var get = uppercase(shortForm ? ('SHORT' + name) : name);
+
+ return formats[get][value];
+ };
+}
+
+function timeZoneGetter(date) {
+ var zone = -1 * date.getTimezoneOffset();
+ var paddedZone = (zone >= 0) ? "+" : "";
+
+ paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
+ padNumber(Math.abs(zone % 60), 2);
+
+ return paddedZone;
+}
+
+function ampmGetter(date, formats) {
+ return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
+}
+
+var DATE_FORMATS = {
+ yyyy: dateGetter('FullYear', 4),
+ yy: dateGetter('FullYear', 2, 0, true),
+ y: dateGetter('FullYear', 1),
+ MMMM: dateStrGetter('Month'),
+ MMM: dateStrGetter('Month', true),
+ MM: dateGetter('Month', 2, 1),
+ M: dateGetter('Month', 1, 1),
+ dd: dateGetter('Date', 2),
+ d: dateGetter('Date', 1),
+ HH: dateGetter('Hours', 2),
+ H: dateGetter('Hours', 1),
+ hh: dateGetter('Hours', 2, -12),
+ h: dateGetter('Hours', 1, -12),
+ mm: dateGetter('Minutes', 2),
+ m: dateGetter('Minutes', 1),
+ ss: dateGetter('Seconds', 2),
+ s: dateGetter('Seconds', 1),
+ // while ISO 8601 requires fractions to be prefixed with `.` or `,`
+ // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
+ sss: dateGetter('Milliseconds', 3),
+ EEEE: dateStrGetter('Day'),
+ EEE: dateStrGetter('Day', true),
+ a: ampmGetter,
+ Z: timeZoneGetter
+};
+
+var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
+ NUMBER_STRING = /^\d+$/;
+
+/**
+ * @ngdoc filter
+ * @name ng.filter:date
+ * @function
+ *
+ * @description
+ * Formats `date` to a string based on the requested `format`.
+ *
+ * `format` string can be composed of the following elements:
+ *
+ * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
+ * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
+ * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
+ * * `'MMMM'`: Month in year (January-December)
+ * * `'MMM'`: Month in year (Jan-Dec)
+ * * `'MM'`: Month in year, padded (01-12)
+ * * `'M'`: Month in year (1-12)
+ * * `'dd'`: Day in month, padded (01-31)
+ * * `'d'`: Day in month (1-31)
+ * * `'EEEE'`: Day in Week,(Sunday-Saturday)
+ * * `'EEE'`: Day in Week, (Sun-Sat)
+ * * `'HH'`: Hour in day, padded (00-23)
+ * * `'H'`: Hour in day (0-23)
+ * * `'hh'`: Hour in am/pm, padded (01-12)
+ * * `'h'`: Hour in am/pm, (1-12)
+ * * `'mm'`: Minute in hour, padded (00-59)
+ * * `'m'`: Minute in hour (0-59)
+ * * `'ss'`: Second in minute, padded (00-59)
+ * * `'s'`: Second in minute (0-59)
+ * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
+ * * `'a'`: am/pm marker
+ * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
+ *
+ * `format` string can also be one of the following predefined
+ * {@link guide/i18n localizable formats}:
+ *
+ * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
+ * (e.g. Sep 3, 2010 12:05:08 pm)
+ * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
+ * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
+ * (e.g. Friday, September 3, 2010)
+ * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010
+ * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
+ * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
+ * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
+ * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
+ *
+ * `format` string can contain literal values. These need to be quoted with single quotes (e.g.
+ * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
+ * (e.g. `"h o''clock"`).
+ *
+ * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
+ * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its
+ * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
+ * specified in the string input, the time is considered to be in the local timezone.
+ * @param {string=} format Formatting rules (see Description). If not specified,
+ * `mediumDate` is used.
+ * @returns {string} Formatted string or the input if input is not recognized as date/millis.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
+ {{1288323623006 | date:'medium'}}<br>
+ <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
+ {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>
+ <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
+ {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br>
+ </doc:source>
+ <doc:scenario>
+ it('should format date', function() {
+ expect(binding("1288323623006 | date:'medium'")).
+ toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
+ expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
+ toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
+ expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
+ toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+dateFilter.$inject = ['$locale'];
+function dateFilter($locale) {
+
+
+ var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
+ // 1 2 3 4 5 6 7 8 9 10 11
+ function jsonStringToDate(string) {
+ var match;
+ if (match = string.match(R_ISO8601_STR)) {
+ var date = new Date(0),
+ tzHour = 0,
+ tzMin = 0,
+ dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
+ timeSetter = match[8] ? date.setUTCHours : date.setHours;
+
+ if (match[9]) {
+ tzHour = int(match[9] + match[10]);
+ tzMin = int(match[9] + match[11]);
+ }
+ dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
+ var h = int(match[4]||0) - tzHour;
+ var m = int(match[5]||0) - tzMin
+ var s = int(match[6]||0);
+ var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
+ timeSetter.call(date, h, m, s, ms);
+ return date;
+ }
+ return string;
+ }
+
+
+ return function(date, format) {
+ var text = '',
+ parts = [],
+ fn, match;
+
+ format = format || 'mediumDate';
+ format = $locale.DATETIME_FORMATS[format] || format;
+ if (isString(date)) {
+ if (NUMBER_STRING.test(date)) {
+ date = int(date);
+ } else {
+ date = jsonStringToDate(date);
+ }
+ }
+
+ if (isNumber(date)) {
+ date = new Date(date);
+ }
+
+ if (!isDate(date)) {
+ return date;
+ }
+
+ while(format) {
+ match = DATE_FORMATS_SPLIT.exec(format);
+ if (match) {
+ parts = concat(parts, match, 1);
+ format = parts.pop();
+ } else {
+ parts.push(format);
+ format = null;
+ }
+ }
+
+ forEach(parts, function(value){
+ fn = DATE_FORMATS[value];
+ text += fn ? fn(date, $locale.DATETIME_FORMATS)
+ : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
+ });
+
+ return text;
+ };
+}
+
+
+/**
+ * @ngdoc filter
+ * @name ng.filter:json
+ * @function
+ *
+ * @description
+ * Allows you to convert a JavaScript object into JSON string.
+ *
+ * This filter is mostly useful for debugging. When using the double curly {{value}} notation
+ * the binding is automatically converted to JSON.
+ *
+ * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
+ * @returns {string} JSON string.
+ *
+ *
+ * @example:
+ <doc:example>
+ <doc:source>
+ <pre>{{ {'name':'value'} | json }}</pre>
+ </doc:source>
+ <doc:scenario>
+ it('should jsonify filtered objects', function() {
+ expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/);
+ });
+ </doc:scenario>
+ </doc:example>
+ *
+ */
+function jsonFilter() {
+ return function(object) {
+ return toJson(object, true);
+ };
+}
+
+
+/**
+ * @ngdoc filter
+ * @name ng.filter:lowercase
+ * @function
+ * @description
+ * Converts string to lowercase.
+ * @see angular.lowercase
+ */
+var lowercaseFilter = valueFn(lowercase);
+
+
+/**
+ * @ngdoc filter
+ * @name ng.filter:uppercase
+ * @function
+ * @description
+ * Converts string to uppercase.
+ * @see angular.uppercase
+ */
+var uppercaseFilter = valueFn(uppercase);
+
+/**
+ * @ngdoc function
+ * @name ng.filter:limitTo
+ * @function
+ *
+ * @description
+ * Creates a new array or string containing only a specified number of elements. The elements
+ * are taken from either the beginning or the end of the source array or string, as specified by
+ * the value and sign (positive or negative) of `limit`.
+ *
+ * Note: This function is used to augment the `Array` type in Angular expressions. See
+ * {@link ng.$filter} for more information about Angular arrays.
+ *
+ * @param {Array|string} input Source array or string to be limited.
+ * @param {string|number} limit The length of the returned array or string. If the `limit` number
+ * is positive, `limit` number of items from the beginning of the source array/string are copied.
+ * If the number is negative, `limit` number of items from the end of the source array/string
+ * are copied. The `limit` will be trimmed if it exceeds `array.length`
+ * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
+ * had less than `limit` elements.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.numbers = [1,2,3,4,5,6,7,8,9];
+ $scope.letters = "abcdefghi";
+ $scope.numLimit = 3;
+ $scope.letterLimit = 3;
+ }
+ </script>
+ <div ng-controller="Ctrl">
+ Limit {{numbers}} to: <input type="integer" ng-model="numLimit">
+ <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
+ Limit {{letters}} to: <input type="integer" ng-model="letterLimit">
+ <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
+ </div>
+ </doc:source>
+ <doc:scenario>
+ it('should limit the number array to first three items', function() {
+ expect(element('.doc-example-live input[ng-model=numLimit]').val()).toBe('3');
+ expect(element('.doc-example-live input[ng-model=letterLimit]').val()).toBe('3');
+ expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3]');
+ expect(binding('letters | limitTo:letterLimit')).toEqual('abc');
+ });
+
+ it('should update the output when -3 is entered', function() {
+ input('numLimit').enter(-3);
+ input('letterLimit').enter(-3);
+ expect(binding('numbers | limitTo:numLimit')).toEqual('[7,8,9]');
+ expect(binding('letters | limitTo:letterLimit')).toEqual('ghi');
+ });
+
+ it('should not exceed the maximum size of input array', function() {
+ input('numLimit').enter(100);
+ input('letterLimit').enter(100);
+ expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3,4,5,6,7,8,9]');
+ expect(binding('letters | limitTo:letterLimit')).toEqual('abcdefghi');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+function limitToFilter(){
+ return function(input, limit) {
+ if (!isArray(input) && !isString(input)) return input;
+
+ limit = int(limit);
+
+ if (isString(input)) {
+ //NaN check on limit
+ if (limit) {
+ return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
+ } else {
+ return "";
+ }
+ }
+
+ var out = [],
+ i, n;
+
+ // if abs(limit) exceeds maximum length, trim it
+ if (limit > input.length)
+ limit = input.length;
+ else if (limit < -input.length)
+ limit = -input.length;
+
+ if (limit > 0) {
+ i = 0;
+ n = limit;
+ } else {
+ i = input.length + limit;
+ n = input.length;
+ }
+
+ for (; i<n; i++) {
+ out.push(input[i]);
+ }
+
+ return out;
+ }
+}
+
+/**
+ * @ngdoc function
+ * @name ng.filter:orderBy
+ * @function
+ *
+ * @description
+ * Orders a specified `array` by the `expression` predicate.
+ *
+ * Note: this function is used to augment the `Array` type in Angular expressions. See
+ * {@link ng.$filter} for more information about Angular arrays.
+ *
+ * @param {Array} array The array to sort.
+ * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
+ * used by the comparator to determine the order of elements.
+ *
+ * Can be one of:
+ *
+ * - `function`: Getter function. The result of this function will be sorted using the
+ * `<`, `=`, `>` operator.
+ * - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
+ * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
+ * ascending or descending sort order (for example, +name or -name).
+ * - `Array`: An array of function or string predicates. The first predicate in the array
+ * is used for sorting, but when two items are equivalent, the next predicate is used.
+ *
+ * @param {boolean=} reverse Reverse the order the array.
+ * @returns {Array} Sorted copy of the source array.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.friends =
+ [{name:'John', phone:'555-1212', age:10},
+ {name:'Mary', phone:'555-9876', age:19},
+ {name:'Mike', phone:'555-4321', age:21},
+ {name:'Adam', phone:'555-5678', age:35},
+ {name:'Julie', phone:'555-8765', age:29}]
+ $scope.predicate = '-age';
+ }
+ </script>
+ <div ng-controller="Ctrl">
+ <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
+ <hr/>
+ [ <a href="" ng-click="predicate=''">unsorted</a> ]
+ <table class="friend">
+ <tr>
+ <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
+ (<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th>
+ <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
+ <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
+ </tr>
+ <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
+ <td>{{friend.name}}</td>
+ <td>{{friend.phone}}</td>
+ <td>{{friend.age}}</td>
+ </tr>
+ </table>
+ </div>
+ </doc:source>
+ <doc:scenario>
+ it('should be reverse ordered by aged', function() {
+ expect(binding('predicate')).toBe('-age');
+ expect(repeater('table.friend', 'friend in friends').column('friend.age')).
+ toEqual(['35', '29', '21', '19', '10']);
+ expect(repeater('table.friend', 'friend in friends').column('friend.name')).
+ toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
+ });
+
+ it('should reorder the table when user selects different predicate', function() {
+ element('.doc-example-live a:contains("Name")').click();
+ expect(repeater('table.friend', 'friend in friends').column('friend.name')).
+ toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
+ expect(repeater('table.friend', 'friend in friends').column('friend.age')).
+ toEqual(['35', '10', '29', '19', '21']);
+
+ element('.doc-example-live a:contains("Phone")').click();
+ expect(repeater('table.friend', 'friend in friends').column('friend.phone')).
+ toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);
+ expect(repeater('table.friend', 'friend in friends').column('friend.name')).
+ toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+orderByFilter.$inject = ['$parse'];
+function orderByFilter($parse){
+ return function(array, sortPredicate, reverseOrder) {
+ if (!isArray(array)) return array;
+ if (!sortPredicate) return array;
+ sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
+ sortPredicate = map(sortPredicate, function(predicate){
+ var descending = false, get = predicate || identity;
+ if (isString(predicate)) {
+ if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
+ descending = predicate.charAt(0) == '-';
+ predicate = predicate.substring(1);
+ }
+ get = $parse(predicate);
+ }
+ return reverseComparator(function(a,b){
+ return compare(get(a),get(b));
+ }, descending);
+ });
+ var arrayCopy = [];
+ for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
+ return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
+
+ function comparator(o1, o2){
+ for ( var i = 0; i < sortPredicate.length; i++) {
+ var comp = sortPredicate[i](o1, o2);
+ if (comp !== 0) return comp;
+ }
+ return 0;
+ }
+ function reverseComparator(comp, descending) {
+ return toBoolean(descending)
+ ? function(a,b){return comp(b,a);}
+ : comp;
+ }
+ function compare(v1, v2){
+ var t1 = typeof v1;
+ var t2 = typeof v2;
+ if (t1 == t2) {
+ if (t1 == "string") v1 = v1.toLowerCase();
+ if (t1 == "string") v2 = v2.toLowerCase();
+ if (v1 === v2) return 0;
+ return v1 < v2 ? -1 : 1;
+ } else {
+ return t1 < t2 ? -1 : 1;
+ }
+ }
+ }
+}
+
+function ngDirective(directive) {
+ if (isFunction(directive)) {
+ directive = {
+ link: directive
+ }
+ }
+ directive.restrict = directive.restrict || 'AC';
+ return valueFn(directive);
+}
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:a
+ * @restrict E
+ *
+ * @description
+ * Modifies the default behavior of html A tag, so that the default action is prevented when href
+ * attribute is empty.
+ *
+ * The reasoning for this change is to allow easy creation of action links with `ngClick` directive
+ * without changing the location or causing page reloads, e.g.:
+ * `<a href="" ng-click="model.$save()">Save</a>`
+ */
+var htmlAnchorDirective = valueFn({
+ restrict: 'E',
+ compile: function(element, attr) {
+
+ if (msie <= 8) {
+
+ // turn <a href ng-click="..">link</a> into a stylable link in IE
+ // but only if it doesn't have name attribute, in which case it's an anchor
+ if (!attr.href && !attr.name) {
+ attr.$set('href', '');
+ }
+
+ // add a comment node to anchors to workaround IE bug that causes element content to be reset
+ // to new attribute content if attribute is updated with value containing @ and element also
+ // contains value with @
+ // see issue #1949
+ element.append(document.createComment('IE fix'));
+ }
+
+ return function(scope, element) {
+ element.bind('click', function(event){
+ // if we have no href url, then don't navigate anywhere.
+ if (!element.attr('href')) {
+ event.preventDefault();
+ }
+ });
+ }
+ }
+});
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngHref
+ * @restrict A
+ *
+ * @description
+ * Using Angular markup like {{hash}} in an href attribute makes
+ * the page open to a wrong URL, if the user clicks that link before
+ * angular has a chance to replace the {{hash}} with actual URL, the
+ * link will be broken and will most likely return a 404 error.
+ * The `ngHref` directive solves this problem.
+ *
+ * The buggy way to write it:
+ * <pre>
+ * <a href="http://www.gravatar.com/avatar/{{hash}}"/>
+ * </pre>
+ *
+ * The correct way to write it:
+ * <pre>
+ * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
+ * </pre>
+ *
+ * @element A
+ * @param {template} ngHref any string which can contain `{{}}` markup.
+ *
+ * @example
+ * This example uses `link` variable inside `href` attribute:
+ <doc:example>
+ <doc:source>
+ <input ng-model="value" /><br />
+ <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
+ <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
+ <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
+ <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
+ <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
+ <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
+ </doc:source>
+ <doc:scenario>
+ it('should execute ng-click but not reload when href without value', function() {
+ element('#link-1').click();
+ expect(input('value').val()).toEqual('1');
+ expect(element('#link-1').attr('href')).toBe("");
+ });
+
+ it('should execute ng-click but not reload when href empty string', function() {
+ element('#link-2').click();
+ expect(input('value').val()).toEqual('2');
+ expect(element('#link-2').attr('href')).toBe("");
+ });
+
+ it('should execute ng-click and change url when ng-href specified', function() {
+ expect(element('#link-3').attr('href')).toBe("/123");
+
+ element('#link-3').click();
+ expect(browser().window().path()).toEqual('/123');
+ });
+
+ it('should execute ng-click but not reload when href empty string and name specified', function() {
+ element('#link-4').click();
+ expect(input('value').val()).toEqual('4');
+ expect(element('#link-4').attr('href')).toBe('');
+ });
+
+ it('should execute ng-click but not reload when no href but name specified', function() {
+ element('#link-5').click();
+ expect(input('value').val()).toEqual('5');
+ expect(element('#link-5').attr('href')).toBe(undefined);
+ });
+
+ it('should only change url when only ng-href', function() {
+ input('value').enter('6');
+ expect(element('#link-6').attr('href')).toBe('6');
+
+ element('#link-6').click();
+ expect(browser().location().url()).toEqual('/6');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngSrc
+ * @restrict A
+ *
+ * @description
+ * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
+ * work right: The browser will fetch from the URL with the literal
+ * text `{{hash}}` until Angular replaces the expression inside
+ * `{{hash}}`. The `ngSrc` directive solves this problem.
+ *
+ * The buggy way to write it:
+ * <pre>
+ * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
+ * </pre>
+ *
+ * The correct way to write it:
+ * <pre>
+ * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
+ * </pre>
+ *
+ * @element IMG
+ * @param {template} ngSrc any string which can contain `{{}}` markup.
+ */
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngSrcset
+ * @restrict A
+ *
+ * @description
+ * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
+ * work right: The browser will fetch from the URL with the literal
+ * text `{{hash}}` until Angular replaces the expression inside
+ * `{{hash}}`. The `ngSrcset` directive solves this problem.
+ *
+ * The buggy way to write it:
+ * <pre>
+ * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
+ * </pre>
+ *
+ * The correct way to write it:
+ * <pre>
+ * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
+ * </pre>
+ *
+ * @element IMG
+ * @param {template} ngSrcset any string which can contain `{{}}` markup.
+ */
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngDisabled
+ * @restrict A
+ *
+ * @description
+ *
+ * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
+ * <pre>
+ * <div ng-init="scope = { isDisabled: false }">
+ * <button disabled="{{scope.isDisabled}}">Disabled</button>
+ * </div>
+ * </pre>
+ *
+ * The HTML specs do not require browsers to preserve the special attributes such as disabled.
+ * (The presence of them means true and absence means false)
+ * This prevents the angular compiler from correctly retrieving the binding expression.
+ * To solve this problem, we introduce the `ngDisabled` directive.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
+ <button ng-model="button" ng-disabled="checked">Button</button>
+ </doc:source>
+ <doc:scenario>
+ it('should toggle button', function() {
+ expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy();
+ input('checked').check();
+ expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();
+ });
+ </doc:scenario>
+ </doc:example>
+ *
+ * @element INPUT
+ * @param {expression} ngDisabled Angular expression that will be evaluated.
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngChecked
+ * @restrict A
+ *
+ * @description
+ * The HTML specs do not require browsers to preserve the special attributes such as checked.
+ * (The presence of them means true and absence means false)
+ * This prevents the angular compiler from correctly retrieving the binding expression.
+ * To solve this problem, we introduce the `ngChecked` directive.
+ * @example
+ <doc:example>
+ <doc:source>
+ Check me to check both: <input type="checkbox" ng-model="master"><br/>
+ <input id="checkSlave" type="checkbox" ng-checked="master">
+ </doc:source>
+ <doc:scenario>
+ it('should check both checkBoxes', function() {
+ expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy();
+ input('master').check();
+ expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();
+ });
+ </doc:scenario>
+ </doc:example>
+ *
+ * @element INPUT
+ * @param {expression} ngChecked Angular expression that will be evaluated.
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngMultiple
+ * @restrict A
+ *
+ * @description
+ * The HTML specs do not require browsers to preserve the special attributes such as multiple.
+ * (The presence of them means true and absence means false)
+ * This prevents the angular compiler from correctly retrieving the binding expression.
+ * To solve this problem, we introduce the `ngMultiple` directive.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ Check me check multiple: <input type="checkbox" ng-model="checked"><br/>
+ <select id="select" ng-multiple="checked">
+ <option>Misko</option>
+ <option>Igor</option>
+ <option>Vojta</option>
+ <option>Di</option>
+ </select>
+ </doc:source>
+ <doc:scenario>
+ it('should toggle multiple', function() {
+ expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy();
+ input('checked').check();
+ expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy();
+ });
+ </doc:scenario>
+ </doc:example>
+ *
+ * @element SELECT
+ * @param {expression} ngMultiple Angular expression that will be evaluated.
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngReadonly
+ * @restrict A
+ *
+ * @description
+ * The HTML specs do not require browsers to preserve the special attributes such as readonly.
+ * (The presence of them means true and absence means false)
+ * This prevents the angular compiler from correctly retrieving the binding expression.
+ * To solve this problem, we introduce the `ngReadonly` directive.
+ * @example
+ <doc:example>
+ <doc:source>
+ Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
+ <input type="text" ng-readonly="checked" value="I'm Angular"/>
+ </doc:source>
+ <doc:scenario>
+ it('should toggle readonly attr', function() {
+ expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy();
+ input('checked').check();
+ expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy();
+ });
+ </doc:scenario>
+ </doc:example>
+ *
+ * @element INPUT
+ * @param {string} expression Angular expression that will be evaluated.
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngSelected
+ * @restrict A
+ *
+ * @description
+ * The HTML specs do not require browsers to preserve the special attributes such as selected.
+ * (The presence of them means true and absence means false)
+ * This prevents the angular compiler from correctly retrieving the binding expression.
+ * To solve this problem, we introduced the `ngSelected` directive.
+ * @example
+ <doc:example>
+ <doc:source>
+ Check me to select: <input type="checkbox" ng-model="selected"><br/>
+ <select>
+ <option>Hello!</option>
+ <option id="greet" ng-selected="selected">Greetings!</option>
+ </select>
+ </doc:source>
+ <doc:scenario>
+ it('should select Greetings!', function() {
+ expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
+ input('selected').check();
+ expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
+ });
+ </doc:scenario>
+ </doc:example>
+ *
+ * @element OPTION
+ * @param {string} expression Angular expression that will be evaluated.
+ */
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngOpen
+ * @restrict A
+ *
+ * @description
+ * The HTML specs do not require browsers to preserve the special attributes such as open.
+ * (The presence of them means true and absence means false)
+ * This prevents the angular compiler from correctly retrieving the binding expression.
+ * To solve this problem, we introduce the `ngOpen` directive.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ Check me check multiple: <input type="checkbox" ng-model="open"><br/>
+ <details id="details" ng-open="open">
+ <summary>Show/Hide me</summary>
+ </details>
+ </doc:source>
+ <doc:scenario>
+ it('should toggle open', function() {
+ expect(element('#details').prop('open')).toBeFalsy();
+ input('open').check();
+ expect(element('#details').prop('open')).toBeTruthy();
+ });
+ </doc:scenario>
+ </doc:example>
+ *
+ * @element DETAILS
+ * @param {string} expression Angular expression that will be evaluated.
+ */
+
+var ngAttributeAliasDirectives = {};
+
+
+// boolean attrs are evaluated
+forEach(BOOLEAN_ATTR, function(propName, attrName) {
+ var normalized = directiveNormalize('ng-' + attrName);
+ ngAttributeAliasDirectives[normalized] = function() {
+ return {
+ priority: 100,
+ compile: function() {
+ return function(scope, element, attr) {
+ scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
+ attr.$set(attrName, !!value);
+ });
+ };
+ }
+ };
+ };
+});
+
+
+// ng-src, ng-srcset, ng-href are interpolated
+forEach(['src', 'srcset', 'href'], function(attrName) {
+ var normalized = directiveNormalize('ng-' + attrName);
+ ngAttributeAliasDirectives[normalized] = function() {
+ return {
+ priority: 99, // it needs to run after the attributes are interpolated
+ link: function(scope, element, attr) {
+ attr.$observe(normalized, function(value) {
+ if (!value)
+ return;
+
+ attr.$set(attrName, value);
+
+ // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
+ // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
+ // to set the property as well to achieve the desired effect.
+ // we use attr[attrName] value since $set can sanitize the url.
+ if (msie) element.prop(attrName, attr[attrName]);
+ });
+ }
+ };
+ };
+});
+
+var nullFormCtrl = {
+ $addControl: noop,
+ $removeControl: noop,
+ $setValidity: noop,
+ $setDirty: noop,
+ $setPristine: noop
+};
+
+/**
+ * @ngdoc object
+ * @name ng.directive:form.FormController
+ *
+ * @property {boolean} $pristine True if user has not interacted with the form yet.
+ * @property {boolean} $dirty True if user has already interacted with the form.
+ * @property {boolean} $valid True if all of the containing forms and controls are valid.
+ * @property {boolean} $invalid True if at least one containing control or form is invalid.
+ *
+ * @property {Object} $error Is an object hash, containing references to all invalid controls or
+ * forms, where:
+ *
+ * - keys are validation tokens (error names) — such as `required`, `url` or `email`),
+ * - values are arrays of controls or forms that are invalid with given error.
+ *
+ * @description
+ * `FormController` keeps track of all its controls and nested forms as well as state of them,
+ * such as being valid/invalid or dirty/pristine.
+ *
+ * Each {@link ng.directive:form form} directive creates an instance
+ * of `FormController`.
+ *
+ */
+//asks for $scope to fool the BC controller module
+FormController.$inject = ['$element', '$attrs', '$scope'];
+function FormController(element, attrs) {
+ var form = this,
+ parentForm = element.parent().controller('form') || nullFormCtrl,
+ invalidCount = 0, // used to easily determine if we are valid
+ errors = form.$error = {},
+ controls = [];
+
+ // init state
+ form.$name = attrs.name;
+ form.$dirty = false;
+ form.$pristine = true;
+ form.$valid = true;
+ form.$invalid = false;
+
+ parentForm.$addControl(form);
+
+ // Setup initial state of the control
+ element.addClass(PRISTINE_CLASS);
+ toggleValidCss(true);
+
+ // convenience method for easy toggling of classes
+ function toggleValidCss(isValid, validationErrorKey) {
+ validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
+ element.
+ removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
+ addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
+ }
+
+ form.$addControl = function(control) {
+ controls.push(control);
+
+ if (control.$name && !form.hasOwnProperty(control.$name)) {
+ form[control.$name] = control;
+ }
+ };
+
+ form.$removeControl = function(control) {
+ if (control.$name && form[control.$name] === control) {
+ delete form[control.$name];
+ }
+ forEach(errors, function(queue, validationToken) {
+ form.$setValidity(validationToken, true, control);
+ });
+
+ arrayRemove(controls, control);
+ };
+
+ form.$setValidity = function(validationToken, isValid, control) {
+ var queue = errors[validationToken];
+
+ if (isValid) {
+ if (queue) {
+ arrayRemove(queue, control);
+ if (!queue.length) {
+ invalidCount--;
+ if (!invalidCount) {
+ toggleValidCss(isValid);
+ form.$valid = true;
+ form.$invalid = false;
+ }
+ errors[validationToken] = false;
+ toggleValidCss(true, validationToken);
+ parentForm.$setValidity(validationToken, true, form);
+ }
+ }
+
+ } else {
+ if (!invalidCount) {
+ toggleValidCss(isValid);
+ }
+ if (queue) {
+ if (includes(queue, control)) return;
+ } else {
+ errors[validationToken] = queue = [];
+ invalidCount++;
+ toggleValidCss(false, validationToken);
+ parentForm.$setValidity(validationToken, false, form);
+ }
+ queue.push(control);
+
+ form.$valid = false;
+ form.$invalid = true;
+ }
+ };
+
+ form.$setDirty = function() {
+ element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
+ form.$dirty = true;
+ form.$pristine = false;
+ parentForm.$setDirty();
+ };
+
+ /**
+ * @ngdoc function
+ * @name ng.directive:form.FormController#$setPristine
+ * @methodOf ng.directive:form.FormController
+ *
+ * @description
+ * Sets the form to its pristine state.
+ *
+ * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
+ * state (ng-pristine class). This method will also propagate to all the controls contained
+ * in this form.
+ *
+ * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
+ * saving or resetting it.
+ */
+ form.$setPristine = function () {
+ element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
+ form.$dirty = false;
+ form.$pristine = true;
+ forEach(controls, function(control) {
+ control.$setPristine();
+ });
+ };
+}
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngForm
+ * @restrict EAC
+ *
+ * @description
+ * Nestable alias of {@link ng.directive:form `form`} directive. HTML
+ * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
+ * sub-group of controls needs to be determined.
+ *
+ * @param {string=} name|ngForm Name of the form. If specified, the form controller will be published into
+ * related scope, under this name.
+ *
+ */
+
+ /**
+ * @ngdoc directive
+ * @name ng.directive:form
+ * @restrict E
+ *
+ * @description
+ * Directive that instantiates
+ * {@link ng.directive:form.FormController FormController}.
+ *
+ * If `name` attribute is specified, the form controller is published onto the current scope under
+ * this name.
+ *
+ * # Alias: {@link ng.directive:ngForm `ngForm`}
+ *
+ * In angular forms can be nested. This means that the outer form is valid when all of the child
+ * forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this
+ * reason angular provides {@link ng.directive:ngForm `ngForm`} alias
+ * which behaves identical to `<form>` but allows form nesting.
+ *
+ *
+ * # CSS classes
+ * - `ng-valid` Is set if the form is valid.
+ * - `ng-invalid` Is set if the form is invalid.
+ * - `ng-pristine` Is set if the form is pristine.
+ * - `ng-dirty` Is set if the form is dirty.
+ *
+ *
+ * # Submitting a form and preventing default action
+ *
+ * Since the role of forms in client-side Angular applications is different than in classical
+ * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
+ * page reload that sends the data to the server. Instead some javascript logic should be triggered
+ * to handle the form submission in application specific way.
+ *
+ * For this reason, Angular prevents the default action (form submission to the server) unless the
+ * `<form>` element has an `action` attribute specified.
+ *
+ * You can use one of the following two ways to specify what javascript method should be called when
+ * a form is submitted:
+ *
+ * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
+ * - {@link ng.directive:ngClick ngClick} directive on the first
+ * button or input field of type submit (input[type=submit])
+ *
+ * To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This
+ * is because of the following form submission rules coming from the html spec:
+ *
+ * - If a form has only one input field then hitting enter in this field triggers form submit
+ * (`ngSubmit`)
+ * - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter
+ * doesn't trigger submit
+ * - if a form has one or more input fields and one or more buttons or input[type=submit] then
+ * hitting enter in any of the input fields will trigger the click handler on the *first* button or
+ * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
+ *
+ * @param {string=} name Name of the form. If specified, the form controller will be published into
+ * related scope, under this name.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.userType = 'guest';
+ }
+ </script>
+ <form name="myForm" ng-controller="Ctrl">
+ userType: <input name="input" ng-model="userType" required>
+ <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
+ <tt>userType = {{userType}}</tt><br>
+ <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
+ <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
+ </form>
+ </doc:source>
+ <doc:scenario>
+ it('should initialize to model', function() {
+ expect(binding('userType')).toEqual('guest');
+ expect(binding('myForm.input.$valid')).toEqual('true');
+ });
+
+ it('should be invalid if empty', function() {
+ input('userType').enter('');
+ expect(binding('userType')).toEqual('');
+ expect(binding('myForm.input.$valid')).toEqual('false');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+var formDirectiveFactory = function(isNgForm) {
+ return ['$timeout', function($timeout) {
+ var formDirective = {
+ name: 'form',
+ restrict: 'E',
+ controller: FormController,
+ compile: function() {
+ return {
+ pre: function(scope, formElement, attr, controller) {
+ if (!attr.action) {
+ // we can't use jq events because if a form is destroyed during submission the default
+ // action is not prevented. see #1238
+ //
+ // IE 9 is not affected because it doesn't fire a submit event and try to do a full
+ // page reload if the form was destroyed by submission of the form via a click handler
+ // on a button in the form. Looks like an IE9 specific bug.
+ var preventDefaultListener = function(event) {
+ event.preventDefault
+ ? event.preventDefault()
+ : event.returnValue = false; // IE
+ };
+
+ addEventListenerFn(formElement[0], 'submit', preventDefaultListener);
+
+ // unregister the preventDefault listener so that we don't not leak memory but in a
+ // way that will achieve the prevention of the default action.
+ formElement.bind('$destroy', function() {
+ $timeout(function() {
+ removeEventListenerFn(formElement[0], 'submit', preventDefaultListener);
+ }, 0, false);
+ });
+ }
+
+ var parentFormCtrl = formElement.parent().controller('form'),
+ alias = attr.name || attr.ngForm;
+
+ if (alias) {
+ scope[alias] = controller;
+ }
+ if (parentFormCtrl) {
+ formElement.bind('$destroy', function() {
+ parentFormCtrl.$removeControl(controller);
+ if (alias) {
+ scope[alias] = undefined;
+ }
+ extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
+ });
+ }
+ }
+ };
+ }
+ };
+
+ return isNgForm ? extend(copy(formDirective), {restrict: 'EAC'}) : formDirective;
+ }];
+};
+
+var formDirective = formDirectiveFactory();
+var ngFormDirective = formDirectiveFactory(true);
+
+var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
+var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
+var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
+
+var inputType = {
+
+ /**
+ * @ngdoc inputType
+ * @name ng.directive:input.text
+ *
+ * @description
+ * Standard HTML text input with angular data binding.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} required Adds `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
+ * minlength.
+ * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
+ * maxlength.
+ * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
+ * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
+ * patterns defined as scope expressions.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trimming the
+ * input.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.text = 'guest';
+ $scope.word = /^\s*\w*\s*$/;
+ }
+ </script>
+ <form name="myForm" ng-controller="Ctrl">
+ Single word: <input type="text" name="input" ng-model="text"
+ ng-pattern="word" required ng-trim="false">
+ <span class="error" ng-show="myForm.input.$error.required">
+ Required!</span>
+ <span class="error" ng-show="myForm.input.$error.pattern">
+ Single word only!</span>
+
+ <tt>text = {{text}}</tt><br/>
+ <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
+ <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ </form>
+ </doc:source>
+ <doc:scenario>
+ it('should initialize to model', function() {
+ expect(binding('text')).toEqual('guest');
+ expect(binding('myForm.input.$valid')).toEqual('true');
+ });
+
+ it('should be invalid if empty', function() {
+ input('text').enter('');
+ expect(binding('text')).toEqual('');
+ expect(binding('myForm.input.$valid')).toEqual('false');
+ });
+
+ it('should be invalid if multi word', function() {
+ input('text').enter('hello world');
+ expect(binding('myForm.input.$valid')).toEqual('false');
+ });
+
+ it('should not be trimmed', function() {
+ input('text').enter('untrimmed ');
+ expect(binding('text')).toEqual('untrimmed ');
+ expect(binding('myForm.input.$valid')).toEqual('true');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+ 'text': textInputType,
+
+
+ /**
+ * @ngdoc inputType
+ * @name ng.directive:input.number
+ *
+ * @description
+ * Text input with number validation and transformation. Sets the `number` validation
+ * error if not a valid number.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
+ * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
+ * minlength.
+ * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
+ * maxlength.
+ * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
+ * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
+ * patterns defined as scope expressions.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.value = 12;
+ }
+ </script>
+ <form name="myForm" ng-controller="Ctrl">
+ Number: <input type="number" name="input" ng-model="value"
+ min="0" max="99" required>
+ <span class="error" ng-show="myForm.list.$error.required">
+ Required!</span>
+ <span class="error" ng-show="myForm.list.$error.number">
+ Not valid number!</span>
+ <tt>value = {{value}}</tt><br/>
+ <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
+ <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ </form>
+ </doc:source>
+ <doc:scenario>
+ it('should initialize to model', function() {
+ expect(binding('value')).toEqual('12');
+ expect(binding('myForm.input.$valid')).toEqual('true');
+ });
+
+ it('should be invalid if empty', function() {
+ input('value').enter('');
+ expect(binding('value')).toEqual('');
+ expect(binding('myForm.input.$valid')).toEqual('false');
+ });
+
+ it('should be invalid if over max', function() {
+ input('value').enter('123');
+ expect(binding('value')).toEqual('');
+ expect(binding('myForm.input.$valid')).toEqual('false');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+ 'number': numberInputType,
+
+
+ /**
+ * @ngdoc inputType
+ * @name ng.directive:input.url
+ *
+ * @description
+ * Text input with URL validation. Sets the `url` validation error key if the content is not a
+ * valid URL.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
+ * minlength.
+ * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
+ * maxlength.
+ * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
+ * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
+ * patterns defined as scope expressions.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.text = 'http://google.com';
+ }
+ </script>
+ <form name="myForm" ng-controller="Ctrl">
+ URL: <input type="url" name="input" ng-model="text" required>
+ <span class="error" ng-show="myForm.input.$error.required">
+ Required!</span>
+ <span class="error" ng-show="myForm.input.$error.url">
+ Not valid url!</span>
+ <tt>text = {{text}}</tt><br/>
+ <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
+ <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
+ </form>
+ </doc:source>
+ <doc:scenario>
+ it('should initialize to model', function() {
+ expect(binding('text')).toEqual('http://google.com');
+ expect(binding('myForm.input.$valid')).toEqual('true');
+ });
+
+ it('should be invalid if empty', function() {
+ input('text').enter('');
+ expect(binding('text')).toEqual('');
+ expect(binding('myForm.input.$valid')).toEqual('false');
+ });
+
+ it('should be invalid if not url', function() {
+ input('text').enter('xxx');
+ expect(binding('myForm.input.$valid')).toEqual('false');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+ 'url': urlInputType,
+
+
+ /**
+ * @ngdoc inputType
+ * @name ng.directive:input.email
+ *
+ * @description
+ * Text input with email validation. Sets the `email` validation error key if not a valid email
+ * address.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
+ * minlength.
+ * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
+ * maxlength.
+ * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
+ * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
+ * patterns defined as scope expressions.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.text = 'me@example.com';
+ }
+ </script>
+ <form name="myForm" ng-controller="Ctrl">
+ Email: <input type="email" name="input" ng-model="text" required>
+ <span class="error" ng-show="myForm.input.$error.required">
+ Required!</span>
+ <span class="error" ng-show="myForm.input.$error.email">
+ Not valid email!</span>
+ <tt>text = {{text}}</tt><br/>
+ <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
+ <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
+ </form>
+ </doc:source>
+ <doc:scenario>
+ it('should initialize to model', function() {
+ expect(binding('text')).toEqual('me@example.com');
+ expect(binding('myForm.input.$valid')).toEqual('true');
+ });
+
+ it('should be invalid if empty', function() {
+ input('text').enter('');
+ expect(binding('text')).toEqual('');
+ expect(binding('myForm.input.$valid')).toEqual('false');
+ });
+
+ it('should be invalid if not email', function() {
+ input('text').enter('xxx');
+ expect(binding('myForm.input.$valid')).toEqual('false');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+ 'email': emailInputType,
+
+
+ /**
+ * @ngdoc inputType
+ * @name ng.directive:input.radio
+ *
+ * @description
+ * HTML radio button.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string} value The value to which the expression should be set when selected.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.color = 'blue';
+ }
+ </script>
+ <form name="myForm" ng-controller="Ctrl">
+ <input type="radio" ng-model="color" value="red"> Red <br/>
+ <input type="radio" ng-model="color" value="green"> Green <br/>
+ <input type="radio" ng-model="color" value="blue"> Blue <br/>
+ <tt>color = {{color}}</tt><br/>
+ </form>
+ </doc:source>
+ <doc:scenario>
+ it('should change state', function() {
+ expect(binding('color')).toEqual('blue');
+
+ input('color').select('red');
+ expect(binding('color')).toEqual('red');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+ 'radio': radioInputType,
+
+
+ /**
+ * @ngdoc inputType
+ * @name ng.directive:input.checkbox
+ *
+ * @description
+ * HTML checkbox.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} ngTrueValue The value to which the expression should be set when selected.
+ * @param {string=} ngFalseValue The value to which the expression should be set when not selected.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.value1 = true;
+ $scope.value2 = 'YES'
+ }
+ </script>
+ <form name="myForm" ng-controller="Ctrl">
+ Value1: <input type="checkbox" ng-model="value1"> <br/>
+ Value2: <input type="checkbox" ng-model="value2"
+ ng-true-value="YES" ng-false-value="NO"> <br/>
+ <tt>value1 = {{value1}}</tt><br/>
+ <tt>value2 = {{value2}}</tt><br/>
+ </form>
+ </doc:source>
+ <doc:scenario>
+ it('should change state', function() {
+ expect(binding('value1')).toEqual('true');
+ expect(binding('value2')).toEqual('YES');
+
+ input('value1').check();
+ input('value2').check();
+ expect(binding('value1')).toEqual('false');
+ expect(binding('value2')).toEqual('NO');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+ 'checkbox': checkboxInputType,
+
+ 'hidden': noop,
+ 'button': noop,
+ 'submit': noop,
+ 'reset': noop
+};
+
+
+function isEmpty(value) {
+ return isUndefined(value) || value === '' || value === null || value !== value;
+}
+
+
+function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
+
+ var listener = function() {
+ var value = element.val();
+
+ // By default we will trim the value
+ // If the attribute ng-trim exists we will avoid trimming
+ // e.g. <input ng-model="foo" ng-trim="false">
+ if (toBoolean(attr.ngTrim || 'T')) {
+ value = trim(value);
+ }
+
+ if (ctrl.$viewValue !== value) {
+ scope.$apply(function() {
+ ctrl.$setViewValue(value);
+ });
+ }
+ };
+
+ // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
+ // input event on backspace, delete or cut
+ if ($sniffer.hasEvent('input')) {
+ element.bind('input', listener);
+ } else {
+ var timeout;
+
+ var deferListener = function() {
+ if (!timeout) {
+ timeout = $browser.defer(function() {
+ listener();
+ timeout = null;
+ });
+ }
+ };
+
+ element.bind('keydown', function(event) {
+ var key = event.keyCode;
+
+ // ignore
+ // command modifiers arrows
+ if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
+
+ deferListener();
+ });
+
+ // if user paste into input using mouse, we need "change" event to catch it
+ element.bind('change', listener);
+
+ // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
+ if ($sniffer.hasEvent('paste')) {
+ element.bind('paste cut', deferListener);
+ }
+ }
+
+
+ ctrl.$render = function() {
+ element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
+ };
+
+ // pattern validator
+ var pattern = attr.ngPattern,
+ patternValidator,
+ match;
+
+ var validate = function(regexp, value) {
+ if (isEmpty(value) || regexp.test(value)) {
+ ctrl.$setValidity('pattern', true);
+ return value;
+ } else {
+ ctrl.$setValidity('pattern', false);
+ return undefined;
+ }
+ };
+
+ if (pattern) {
+ match = pattern.match(/^\/(.*)\/([gim]*)$/);
+ if (match) {
+ pattern = new RegExp(match[1], match[2]);
+ patternValidator = function(value) {
+ return validate(pattern, value)
+ };
+ } else {
+ patternValidator = function(value) {
+ var patternObj = scope.$eval(pattern);
+
+ if (!patternObj || !patternObj.test) {
+ throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj);
+ }
+ return validate(patternObj, value);
+ };
+ }
+
+ ctrl.$formatters.push(patternValidator);
+ ctrl.$parsers.push(patternValidator);
+ }
+
+ // min length validator
+ if (attr.ngMinlength) {
+ var minlength = int(attr.ngMinlength);
+ var minLengthValidator = function(value) {
+ if (!isEmpty(value) && value.length < minlength) {
+ ctrl.$setValidity('minlength', false);
+ return undefined;
+ } else {
+ ctrl.$setValidity('minlength', true);
+ return value;
+ }
+ };
+
+ ctrl.$parsers.push(minLengthValidator);
+ ctrl.$formatters.push(minLengthValidator);
+ }
+
+ // max length validator
+ if (attr.ngMaxlength) {
+ var maxlength = int(attr.ngMaxlength);
+ var maxLengthValidator = function(value) {
+ if (!isEmpty(value) && value.length > maxlength) {
+ ctrl.$setValidity('maxlength', false);
+ return undefined;
+ } else {
+ ctrl.$setValidity('maxlength', true);
+ return value;
+ }
+ };
+
+ ctrl.$parsers.push(maxLengthValidator);
+ ctrl.$formatters.push(maxLengthValidator);
+ }
+}
+
+function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
+ textInputType(scope, element, attr, ctrl, $sniffer, $browser);
+
+ ctrl.$parsers.push(function(value) {
+ var empty = isEmpty(value);
+ if (empty || NUMBER_REGEXP.test(value)) {
+ ctrl.$setValidity('number', true);
+ return value === '' ? null : (empty ? value : parseFloat(value));
+ } else {
+ ctrl.$setValidity('number', false);
+ return undefined;
+ }
+ });
+
+ ctrl.$formatters.push(function(value) {
+ return isEmpty(value) ? '' : '' + value;
+ });
+
+ if (attr.min) {
+ var min = parseFloat(attr.min);
+ var minValidator = function(value) {
+ if (!isEmpty(value) && value < min) {
+ ctrl.$setValidity('min', false);
+ return undefined;
+ } else {
+ ctrl.$setValidity('min', true);
+ return value;
+ }
+ };
+
+ ctrl.$parsers.push(minValidator);
+ ctrl.$formatters.push(minValidator);
+ }
+
+ if (attr.max) {
+ var max = parseFloat(attr.max);
+ var maxValidator = function(value) {
+ if (!isEmpty(value) && value > max) {
+ ctrl.$setValidity('max', false);
+ return undefined;
+ } else {
+ ctrl.$setValidity('max', true);
+ return value;
+ }
+ };
+
+ ctrl.$parsers.push(maxValidator);
+ ctrl.$formatters.push(maxValidator);
+ }
+
+ ctrl.$formatters.push(function(value) {
+
+ if (isEmpty(value) || isNumber(value)) {
+ ctrl.$setValidity('number', true);
+ return value;
+ } else {
+ ctrl.$setValidity('number', false);
+ return undefined;
+ }
+ });
+}
+
+function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
+ textInputType(scope, element, attr, ctrl, $sniffer, $browser);
+
+ var urlValidator = function(value) {
+ if (isEmpty(value) || URL_REGEXP.test(value)) {
+ ctrl.$setValidity('url', true);
+ return value;
+ } else {
+ ctrl.$setValidity('url', false);
+ return undefined;
+ }
+ };
+
+ ctrl.$formatters.push(urlValidator);
+ ctrl.$parsers.push(urlValidator);
+}
+
+function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
+ textInputType(scope, element, attr, ctrl, $sniffer, $browser);
+
+ var emailValidator = function(value) {
+ if (isEmpty(value) || EMAIL_REGEXP.test(value)) {
+ ctrl.$setValidity('email', true);
+ return value;
+ } else {
+ ctrl.$setValidity('email', false);
+ return undefined;
+ }
+ };
+
+ ctrl.$formatters.push(emailValidator);
+ ctrl.$parsers.push(emailValidator);
+}
+
+function radioInputType(scope, element, attr, ctrl) {
+ // make the name unique, if not defined
+ if (isUndefined(attr.name)) {
+ element.attr('name', nextUid());
+ }
+
+ element.bind('click', function() {
+ if (element[0].checked) {
+ scope.$apply(function() {
+ ctrl.$setViewValue(attr.value);
+ });
+ }
+ });
+
+ ctrl.$render = function() {
+ var value = attr.value;
+ element[0].checked = (value == ctrl.$viewValue);
+ };
+
+ attr.$observe('value', ctrl.$render);
+}
+
+function checkboxInputType(scope, element, attr, ctrl) {
+ var trueValue = attr.ngTrueValue,
+ falseValue = attr.ngFalseValue;
+
+ if (!isString(trueValue)) trueValue = true;
+ if (!isString(falseValue)) falseValue = false;
+
+ element.bind('click', function() {
+ scope.$apply(function() {
+ ctrl.$setViewValue(element[0].checked);
+ });
+ });
+
+ ctrl.$render = function() {
+ element[0].checked = ctrl.$viewValue;
+ };
+
+ ctrl.$formatters.push(function(value) {
+ return value === trueValue;
+ });
+
+ ctrl.$parsers.push(function(value) {
+ return value ? trueValue : falseValue;
+ });
+}
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:textarea
+ * @restrict E
+ *
+ * @description
+ * HTML textarea element control with angular data-binding. The data-binding and validation
+ * properties of this element are exactly the same as those of the
+ * {@link ng.directive:input input element}.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
+ * minlength.
+ * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
+ * maxlength.
+ * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
+ * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
+ * patterns defined as scope expressions.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:input
+ * @restrict E
+ *
+ * @description
+ * HTML input element control with angular data-binding. Input control follows HTML5 input types
+ * and polyfills the HTML5 validation behavior for older browsers.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {boolean=} ngRequired Sets `required` attribute if set to true
+ * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
+ * minlength.
+ * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
+ * maxlength.
+ * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
+ * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
+ * patterns defined as scope expressions.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.user = {name: 'guest', last: 'visitor'};
+ }
+ </script>
+ <div ng-controller="Ctrl">
+ <form name="myForm">
+ User name: <input type="text" name="userName" ng-model="user.name" required>
+ <span class="error" ng-show="myForm.userName.$error.required">
+ Required!</span><br>
+ Last name: <input type="text" name="lastName" ng-model="user.last"
+ ng-minlength="3" ng-maxlength="10">
+ <span class="error" ng-show="myForm.lastName.$error.minlength">
+ Too short!</span>
+ <span class="error" ng-show="myForm.lastName.$error.maxlength">
+ Too long!</span><br>
+ </form>
+ <hr>
+ <tt>user = {{user}}</tt><br/>
+ <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
+ <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
+ <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
+ <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
+ <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
+ <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
+ </div>
+ </doc:source>
+ <doc:scenario>
+ it('should initialize to model', function() {
+ expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}');
+ expect(binding('myForm.userName.$valid')).toEqual('true');
+ expect(binding('myForm.$valid')).toEqual('true');
+ });
+
+ it('should be invalid if empty when required', function() {
+ input('user.name').enter('');
+ expect(binding('user')).toEqual('{"last":"visitor"}');
+ expect(binding('myForm.userName.$valid')).toEqual('false');
+ expect(binding('myForm.$valid')).toEqual('false');
+ });
+
+ it('should be valid if empty when min length is set', function() {
+ input('user.last').enter('');
+ expect(binding('user')).toEqual('{"name":"guest","last":""}');
+ expect(binding('myForm.lastName.$valid')).toEqual('true');
+ expect(binding('myForm.$valid')).toEqual('true');
+ });
+
+ it('should be invalid if less than required min length', function() {
+ input('user.last').enter('xx');
+ expect(binding('user')).toEqual('{"name":"guest"}');
+ expect(binding('myForm.lastName.$valid')).toEqual('false');
+ expect(binding('myForm.lastName.$error')).toMatch(/minlength/);
+ expect(binding('myForm.$valid')).toEqual('false');
+ });
+
+ it('should be invalid if longer than max length', function() {
+ input('user.last').enter('some ridiculously long name');
+ expect(binding('user'))
+ .toEqual('{"name":"guest"}');
+ expect(binding('myForm.lastName.$valid')).toEqual('false');
+ expect(binding('myForm.lastName.$error')).toMatch(/maxlength/);
+ expect(binding('myForm.$valid')).toEqual('false');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
+ return {
+ restrict: 'E',
+ require: '?ngModel',
+ link: function(scope, element, attr, ctrl) {
+ if (ctrl) {
+ (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
+ $browser);
+ }
+ }
+ };
+}];
+
+var VALID_CLASS = 'ng-valid',
+ INVALID_CLASS = 'ng-invalid',
+ PRISTINE_CLASS = 'ng-pristine',
+ DIRTY_CLASS = 'ng-dirty';
+
+/**
+ * @ngdoc object
+ * @name ng.directive:ngModel.NgModelController
+ *
+ * @property {string} $viewValue Actual string value in the view.
+ * @property {*} $modelValue The value in the model, that the control is bound to.
+ * @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes
+ * all of these functions to sanitize / convert the value as well as validate.
+ *
+ * @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of
+ * these functions to convert the value as well as validate.
+ *
+ * @property {Object} $error An object hash with all errors as keys.
+ *
+ * @property {boolean} $pristine True if user has not interacted with the control yet.
+ * @property {boolean} $dirty True if user has already interacted with the control.
+ * @property {boolean} $valid True if there is no error.
+ * @property {boolean} $invalid True if at least one error on the control.
+ *
+ * @description
+ *
+ * `NgModelController` provides API for the `ng-model` directive. The controller contains
+ * services for data-binding, validation, CSS update, value formatting and parsing. It
+ * specifically does not contain any logic which deals with DOM rendering or listening to
+ * DOM events. The `NgModelController` is meant to be extended by other directives where, the
+ * directive provides DOM manipulation and the `NgModelController` provides the data-binding.
+ *
+ * This example shows how to use `NgModelController` with a custom control to achieve
+ * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
+ * collaborate together to achieve the desired result.
+ *
+ * <example module="customControl">
+ <file name="style.css">
+ [contenteditable] {
+ border: 1px solid black;
+ background-color: white;
+ min-height: 20px;
+ }
+
+ .ng-invalid {
+ border: 1px solid red;
+ }
+
+ </file>
+ <file name="script.js">
+ angular.module('customControl', []).
+ directive('contenteditable', function() {
+ return {
+ restrict: 'A', // only activate on element attribute
+ require: '?ngModel', // get a hold of NgModelController
+ link: function(scope, element, attrs, ngModel) {
+ if(!ngModel) return; // do nothing if no ng-model
+
+ // Specify how UI should be updated
+ ngModel.$render = function() {
+ element.html(ngModel.$viewValue || '');
+ };
+
+ // Listen for change events to enable binding
+ element.bind('blur keyup change', function() {
+ scope.$apply(read);
+ });
+ read(); // initialize
+
+ // Write data to the model
+ function read() {
+ ngModel.$setViewValue(element.html());
+ }
+ }
+ };
+ });
+ </file>
+ <file name="index.html">
+ <form name="myForm">
+ <div contenteditable
+ name="myWidget" ng-model="userContent"
+ required>Change me!</div>
+ <span ng-show="myForm.myWidget.$error.required">Required!</span>
+ <hr>
+ <textarea ng-model="userContent"></textarea>
+ </form>
+ </file>
+ <file name="scenario.js">
+ it('should data-bind and become invalid', function() {
+ var contentEditable = element('[contenteditable]');
+
+ expect(contentEditable.text()).toEqual('Change me!');
+ input('userContent').enter('');
+ expect(contentEditable.text()).toEqual('');
+ expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/);
+ });
+ </file>
+ * </example>
+ *
+ */
+var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse',
+ function($scope, $exceptionHandler, $attr, $element, $parse) {
+ this.$viewValue = Number.NaN;
+ this.$modelValue = Number.NaN;
+ this.$parsers = [];
+ this.$formatters = [];
+ this.$viewChangeListeners = [];
+ this.$pristine = true;
+ this.$dirty = false;
+ this.$valid = true;
+ this.$invalid = false;
+ this.$name = $attr.name;
+
+ var ngModelGet = $parse($attr.ngModel),
+ ngModelSet = ngModelGet.assign;
+
+ if (!ngModelSet) {
+ throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel +
+ ' (' + startingTag($element) + ')');
+ }
+
+ /**
+ * @ngdoc function
+ * @name ng.directive:ngModel.NgModelController#$render
+ * @methodOf ng.directive:ngModel.NgModelController
+ *
+ * @description
+ * Called when the view needs to be updated. It is expected that the user of the ng-model
+ * directive will implement this method.
+ */
+ this.$render = noop;
+
+ var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
+ invalidCount = 0, // used to easily determine if we are valid
+ $error = this.$error = {}; // keep invalid keys here
+
+
+ // Setup initial state of the control
+ $element.addClass(PRISTINE_CLASS);
+ toggleValidCss(true);
+
+ // convenience method for easy toggling of classes
+ function toggleValidCss(isValid, validationErrorKey) {
+ validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
+ $element.
+ removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
+ addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
+ }
+
+ /**
+ * @ngdoc function
+ * @name ng.directive:ngModel.NgModelController#$setValidity
+ * @methodOf ng.directive:ngModel.NgModelController
+ *
+ * @description
+ * Change the validity state, and notifies the form when the control changes validity. (i.e. it
+ * does not notify form if given validator is already marked as invalid).
+ *
+ * This method should be called by validators - i.e. the parser or formatter functions.
+ *
+ * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
+ * to `$error[validationErrorKey]=isValid` so that it is available for data-binding.
+ * The `validationErrorKey` should be in camelCase and will get converted into dash-case
+ * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
+ * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
+ * @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
+ */
+ this.$setValidity = function(validationErrorKey, isValid) {
+ if ($error[validationErrorKey] === !isValid) return;
+
+ if (isValid) {
+ if ($error[validationErrorKey]) invalidCount--;
+ if (!invalidCount) {
+ toggleValidCss(true);
+ this.$valid = true;
+ this.$invalid = false;
+ }
+ } else {
+ toggleValidCss(false);
+ this.$invalid = true;
+ this.$valid = false;
+ invalidCount++;
+ }
+
+ $error[validationErrorKey] = !isValid;
+ toggleValidCss(isValid, validationErrorKey);
+
+ parentForm.$setValidity(validationErrorKey, isValid, this);
+ };
+
+ /**
+ * @ngdoc function
+ * @name ng.directive:ngModel.NgModelController#$setPristine
+ * @methodOf ng.directive:ngModel.NgModelController
+ *
+ * @description
+ * Sets the control to its pristine state.
+ *
+ * This method can be called to remove the 'ng-dirty' class and set the control to its pristine
+ * state (ng-pristine class).
+ */
+ this.$setPristine = function () {
+ this.$dirty = false;
+ this.$pristine = true;
+ $element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
+ };
+
+ /**
+ * @ngdoc function
+ * @name ng.directive:ngModel.NgModelController#$setViewValue
+ * @methodOf ng.directive:ngModel.NgModelController
+ *
+ * @description
+ * Read a value from view.
+ *
+ * This method should be called from within a DOM event handler.
+ * For example {@link ng.directive:input input} or
+ * {@link ng.directive:select select} directives call it.
+ *
+ * It internally calls all `parsers` and if resulted value is valid, updates the model and
+ * calls all registered change listeners.
+ *
+ * @param {string} value Value from the view.
+ */
+ this.$setViewValue = function(value) {
+ this.$viewValue = value;
+
+ // change to dirty
+ if (this.$pristine) {
+ this.$dirty = true;
+ this.$pristine = false;
+ $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
+ parentForm.$setDirty();
+ }
+
+ forEach(this.$parsers, function(fn) {
+ value = fn(value);
+ });
+
+ if (this.$modelValue !== value) {
+ this.$modelValue = value;
+ ngModelSet($scope, value);
+ forEach(this.$viewChangeListeners, function(listener) {
+ try {
+ listener();
+ } catch(e) {
+ $exceptionHandler(e);
+ }
+ })
+ }
+ };
+
+ // model -> value
+ var ctrl = this;
+
+ $scope.$watch(function ngModelWatch() {
+ var value = ngModelGet($scope);
+
+ // if scope model value and ngModel value are out of sync
+ if (ctrl.$modelValue !== value) {
+
+ var formatters = ctrl.$formatters,
+ idx = formatters.length;
+
+ ctrl.$modelValue = value;
+ while(idx--) {
+ value = formatters[idx](value);
+ }
+
+ if (ctrl.$viewValue !== value) {
+ ctrl.$viewValue = value;
+ ctrl.$render();
+ }
+ }
+ });
+}];
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngModel
+ *
+ * @element input
+ *
+ * @description
+ * Is directive that tells Angular to do two-way data binding. It works together with `input`,
+ * `select`, `textarea`. You can easily write your own directives to use `ngModel` as well.
+ *
+ * `ngModel` is responsible for:
+ *
+ * - binding the view into the model, which other directives such as `input`, `textarea` or `select`
+ * require,
+ * - providing validation behavior (i.e. required, number, email, url),
+ * - keeping state of the control (valid/invalid, dirty/pristine, validation errors),
+ * - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`),
+ * - register the control with parent {@link ng.directive:form form}.
+ *
+ * For basic examples, how to use `ngModel`, see:
+ *
+ * - {@link ng.directive:input input}
+ * - {@link ng.directive:input.text text}
+ * - {@link ng.directive:input.checkbox checkbox}
+ * - {@link ng.directive:input.radio radio}
+ * - {@link ng.directive:input.number number}
+ * - {@link ng.directive:input.email email}
+ * - {@link ng.directive:input.url url}
+ * - {@link ng.directive:select select}
+ * - {@link ng.directive:textarea textarea}
+ *
+ */
+var ngModelDirective = function() {
+ return {
+ require: ['ngModel', '^?form'],
+ controller: NgModelController,
+ link: function(scope, element, attr, ctrls) {
+ // notify others, especially parent forms
+
+ var modelCtrl = ctrls[0],
+ formCtrl = ctrls[1] || nullFormCtrl;
+
+ formCtrl.$addControl(modelCtrl);
+
+ element.bind('$destroy', function() {
+ formCtrl.$removeControl(modelCtrl);
+ });
+ }
+ };
+};
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngChange
+ * @restrict E
+ *
+ * @description
+ * Evaluate given expression when user changes the input.
+ * The expression is not evaluated when the value change is coming from the model.
+ *
+ * Note, this directive requires `ngModel` to be present.
+ *
+ * @element input
+ *
+ * @example
+ * <doc:example>
+ * <doc:source>
+ * <script>
+ * function Controller($scope) {
+ * $scope.counter = 0;
+ * $scope.change = function() {
+ * $scope.counter++;
+ * };
+ * }
+ * </script>
+ * <div ng-controller="Controller">
+ * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
+ * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
+ * <label for="ng-change-example2">Confirmed</label><br />
+ * debug = {{confirmed}}<br />
+ * counter = {{counter}}
+ * </div>
+ * </doc:source>
+ * <doc:scenario>
+ * it('should evaluate the expression if changing from view', function() {
+ * expect(binding('counter')).toEqual('0');
+ * element('#ng-change-example1').click();
+ * expect(binding('counter')).toEqual('1');
+ * expect(binding('confirmed')).toEqual('true');
+ * });
+ *
+ * it('should not evaluate the expression if changing from model', function() {
+ * element('#ng-change-example2').click();
+ * expect(binding('counter')).toEqual('0');
+ * expect(binding('confirmed')).toEqual('true');
+ * });
+ * </doc:scenario>
+ * </doc:example>
+ */
+var ngChangeDirective = valueFn({
+ require: 'ngModel',
+ link: function(scope, element, attr, ctrl) {
+ ctrl.$viewChangeListeners.push(function() {
+ scope.$eval(attr.ngChange);
+ });
+ }
+});
+
+
+var requiredDirective = function() {
+ return {
+ require: '?ngModel',
+ link: function(scope, elm, attr, ctrl) {
+ if (!ctrl) return;
+ attr.required = true; // force truthy in case we are on non input element
+
+ var validator = function(value) {
+ if (attr.required && (isEmpty(value) || value === false)) {
+ ctrl.$setValidity('required', false);
+ return;
+ } else {
+ ctrl.$setValidity('required', true);
+ return value;
+ }
+ };
+
+ ctrl.$formatters.push(validator);
+ ctrl.$parsers.unshift(validator);
+
+ attr.$observe('required', function() {
+ validator(ctrl.$viewValue);
+ });
+ }
+ };
+};
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngList
+ *
+ * @description
+ * Text input that converts between comma-separated string into an array of strings.
+ *
+ * @element input
+ * @param {string=} ngList optional delimiter that should be used to split the value. If
+ * specified in form `/something/` then the value will be converted into a regular expression.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.names = ['igor', 'misko', 'vojta'];
+ }
+ </script>
+ <form name="myForm" ng-controller="Ctrl">
+ List: <input name="namesInput" ng-model="names" ng-list required>
+ <span class="error" ng-show="myForm.list.$error.required">
+ Required!</span>
+ <tt>names = {{names}}</tt><br/>
+ <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
+ <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ </form>
+ </doc:source>
+ <doc:scenario>
+ it('should initialize to model', function() {
+ expect(binding('names')).toEqual('["igor","misko","vojta"]');
+ expect(binding('myForm.namesInput.$valid')).toEqual('true');
+ });
+
+ it('should be invalid if empty', function() {
+ input('names').enter('');
+ expect(binding('names')).toEqual('[]');
+ expect(binding('myForm.namesInput.$valid')).toEqual('false');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+var ngListDirective = function() {
+ return {
+ require: 'ngModel',
+ link: function(scope, element, attr, ctrl) {
+ var match = /\/(.*)\//.exec(attr.ngList),
+ separator = match && new RegExp(match[1]) || attr.ngList || ',';
+
+ var parse = function(viewValue) {
+ var list = [];
+
+ if (viewValue) {
+ forEach(viewValue.split(separator), function(value) {
+ if (value) list.push(trim(value));
+ });
+ }
+
+ return list;
+ };
+
+ ctrl.$parsers.push(parse);
+ ctrl.$formatters.push(function(value) {
+ if (isArray(value)) {
+ return value.join(', ');
+ }
+
+ return undefined;
+ });
+ }
+ };
+};
+
+
+var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
+
+var ngValueDirective = function() {
+ return {
+ priority: 100,
+ compile: function(tpl, tplAttr) {
+ if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
+ return function(scope, elm, attr) {
+ attr.$set('value', scope.$eval(attr.ngValue));
+ };
+ } else {
+ return function(scope, elm, attr) {
+ scope.$watch(attr.ngValue, function valueWatchAction(value) {
+ attr.$set('value', value, false);
+ });
+ };
+ }
+ }
+ };
+};
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngBind
+ *
+ * @description
+ * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
+ * with the value of a given expression, and to update the text content when the value of that
+ * expression changes.
+ *
+ * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
+ * `{{ expression }}` which is similar but less verbose.
+ *
+ * One scenario in which the use of `ngBind` is preferred over `{{ expression }}` binding is when
+ * it's desirable to put bindings into template that is momentarily displayed by the browser in its
+ * raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the
+ * bindings invisible to the user while the page is loading.
+ *
+ * An alternative solution to this problem would be using the
+ * {@link ng.directive:ngCloak ngCloak} directive.
+ *
+ *
+ * @element ANY
+ * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
+ *
+ * @example
+ * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.name = 'Whirled';
+ }
+ </script>
+ <div ng-controller="Ctrl">
+ Enter name: <input type="text" ng-model="name"><br>
+ Hello <span ng-bind="name"></span>!
+ </div>
+ </doc:source>
+ <doc:scenario>
+ it('should check ng-bind', function() {
+ expect(using('.doc-example-live').binding('name')).toBe('Whirled');
+ using('.doc-example-live').input('name').enter('world');
+ expect(using('.doc-example-live').binding('name')).toBe('world');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+var ngBindDirective = ngDirective(function(scope, element, attr) {
+ element.addClass('ng-binding').data('$binding', attr.ngBind);
+ scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
+ element.text(value == undefined ? '' : value);
+ });
+});
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngBindTemplate
+ *
+ * @description
+ * The `ngBindTemplate` directive specifies that the element
+ * text should be replaced with the template in ngBindTemplate.
+ * Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}`
+ * expressions. (This is required since some HTML elements
+ * can not have SPAN elements such as TITLE, or OPTION to name a few.)
+ *
+ * @element ANY
+ * @param {string} ngBindTemplate template of form
+ * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
+ *
+ * @example
+ * Try it here: enter text in text box and watch the greeting change.
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.salutation = 'Hello';
+ $scope.name = 'World';
+ }
+ </script>
+ <div ng-controller="Ctrl">
+ Salutation: <input type="text" ng-model="salutation"><br>
+ Name: <input type="text" ng-model="name"><br>
+ <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
+ </div>
+ </doc:source>
+ <doc:scenario>
+ it('should check ng-bind', function() {
+ expect(using('.doc-example-live').binding('salutation')).
+ toBe('Hello');
+ expect(using('.doc-example-live').binding('name')).
+ toBe('World');
+ using('.doc-example-live').input('salutation').enter('Greetings');
+ using('.doc-example-live').input('name').enter('user');
+ expect(using('.doc-example-live').binding('salutation')).
+ toBe('Greetings');
+ expect(using('.doc-example-live').binding('name')).
+ toBe('user');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
+ return function(scope, element, attr) {
+ // TODO: move this to scenario runner
+ var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
+ element.addClass('ng-binding').data('$binding', interpolateFn);
+ attr.$observe('ngBindTemplate', function(value) {
+ element.text(value);
+ });
+ }
+}];
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngBindHtmlUnsafe
+ *
+ * @description
+ * Creates a binding that will innerHTML the result of evaluating the `expression` into the current
+ * element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if
+ * {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too
+ * restrictive and when you absolutely trust the source of the content you are binding to.
+ *
+ * See {@link ngSanitize.$sanitize $sanitize} docs for examples.
+ *
+ * @element ANY
+ * @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate.
+ */
+var ngBindHtmlUnsafeDirective = [function() {
+ return function(scope, element, attr) {
+ element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
+ scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) {
+ element.html(value || '');
+ });
+ };
+}];
+
+function classDirective(name, selector) {
+ name = 'ngClass' + name;
+ return ngDirective(function(scope, element, attr) {
+ var oldVal = undefined;
+
+ scope.$watch(attr[name], ngClassWatchAction, true);
+
+ attr.$observe('class', function(value) {
+ var ngClass = scope.$eval(attr[name]);
+ ngClassWatchAction(ngClass, ngClass);
+ });
+
+
+ if (name !== 'ngClass') {
+ scope.$watch('$index', function($index, old$index) {
+ var mod = $index & 1;
+ if (mod !== old$index & 1) {
+ if (mod === selector) {
+ addClass(scope.$eval(attr[name]));
+ } else {
+ removeClass(scope.$eval(attr[name]));
+ }
+ }
+ });
+ }
+
+
+ function ngClassWatchAction(newVal) {
+ if (selector === true || scope.$index % 2 === selector) {
+ if (oldVal && !equals(newVal,oldVal)) {
+ removeClass(oldVal);
+ }
+ addClass(newVal);
+ }
+ oldVal = copy(newVal);
+ }
+
+
+ function removeClass(classVal) {
+ if (isObject(classVal) && !isArray(classVal)) {
+ classVal = map(classVal, function(v, k) { if (v) return k });
+ }
+ element.removeClass(isArray(classVal) ? classVal.join(' ') : classVal);
+ }
+
+
+ function addClass(classVal) {
+ if (isObject(classVal) && !isArray(classVal)) {
+ classVal = map(classVal, function(v, k) { if (v) return k });
+ }
+ if (classVal) {
+ element.addClass(isArray(classVal) ? classVal.join(' ') : classVal);
+ }
+ }
+ });
+}
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngClass
+ *
+ * @description
+ * The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an
+ * expression that represents all classes to be added.
+ *
+ * The directive won't add duplicate classes if a particular class was already set.
+ *
+ * When the expression changes, the previously added classes are removed and only then the
+ * new classes are added.
+ *
+ * @element ANY
+ * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
+ * of the evaluation can be a string representing space delimited class
+ * names, an array, or a map of class names to boolean values.
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <input type="button" value="set" ng-click="myVar='my-class'">
+ <input type="button" value="clear" ng-click="myVar=''">
+ <br>
+ <span ng-class="myVar">Sample Text</span>
+ </file>
+ <file name="style.css">
+ .my-class {
+ color: red;
+ }
+ </file>
+ <file name="scenario.js">
+ it('should check ng-class', function() {
+ expect(element('.doc-example-live span').prop('className')).not().
+ toMatch(/my-class/);
+
+ using('.doc-example-live').element(':button:first').click();
+
+ expect(element('.doc-example-live span').prop('className')).
+ toMatch(/my-class/);
+
+ using('.doc-example-live').element(':button:last').click();
+
+ expect(element('.doc-example-live span').prop('className')).not().
+ toMatch(/my-class/);
+ });
+ </file>
+ </example>
+ */
+var ngClassDirective = classDirective('', true);
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngClassOdd
+ *
+ * @description
+ * The `ngClassOdd` and `ngClassEven` directives work exactly as
+ * {@link ng.directive:ngClass ngClass}, except it works in
+ * conjunction with `ngRepeat` and takes affect only on odd (even) rows.
+ *
+ * This directive can be applied only within a scope of an
+ * {@link ng.directive:ngRepeat ngRepeat}.
+ *
+ * @element ANY
+ * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
+ * of the evaluation can be a string representing space delimited class names or an array.
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
+ <li ng-repeat="name in names">
+ <span ng-class-odd="'odd'" ng-class-even="'even'">
+ {{name}}
+ </span>
+ </li>
+ </ol>
+ </file>
+ <file name="style.css">
+ .odd {
+ color: red;
+ }
+ .even {
+ color: blue;
+ }
+ </file>
+ <file name="scenario.js">
+ it('should check ng-class-odd and ng-class-even', function() {
+ expect(element('.doc-example-live li:first span').prop('className')).
+ toMatch(/odd/);
+ expect(element('.doc-example-live li:last span').prop('className')).
+ toMatch(/even/);
+ });
+ </file>
+ </example>
+ */
+var ngClassOddDirective = classDirective('Odd', 0);
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngClassEven
+ *
+ * @description
+ * The `ngClassOdd` and `ngClassEven` directives work exactly as
+ * {@link ng.directive:ngClass ngClass}, except it works in
+ * conjunction with `ngRepeat` and takes affect only on odd (even) rows.
+ *
+ * This directive can be applied only within a scope of an
+ * {@link ng.directive:ngRepeat ngRepeat}.
+ *
+ * @element ANY
+ * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
+ * result of the evaluation can be a string representing space delimited class names or an array.
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
+ <li ng-repeat="name in names">
+ <span ng-class-odd="'odd'" ng-class-even="'even'">
+ {{name}}
+ </span>
+ </li>
+ </ol>
+ </file>
+ <file name="style.css">
+ .odd {
+ color: red;
+ }
+ .even {
+ color: blue;
+ }
+ </file>
+ <file name="scenario.js">
+ it('should check ng-class-odd and ng-class-even', function() {
+ expect(element('.doc-example-live li:first span').prop('className')).
+ toMatch(/odd/);
+ expect(element('.doc-example-live li:last span').prop('className')).
+ toMatch(/even/);
+ });
+ </file>
+ </example>
+ */
+var ngClassEvenDirective = classDirective('Even', 1);
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngCloak
+ *
+ * @description
+ * The `ngCloak` directive is used to prevent the Angular html template from being briefly
+ * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
+ * directive to avoid the undesirable flicker effect caused by the html template display.
+ *
+ * The directive can be applied to the `<body>` element, but typically a fine-grained application is
+ * preferred in order to benefit from progressive rendering of the browser view.
+ *
+ * `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and
+ * `angular.min.js` files. Following is the css rule:
+ *
+ * <pre>
+ * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
+ * display: none;
+ * }
+ * </pre>
+ *
+ * When this css rule is loaded by the browser, all html elements (including their children) that
+ * are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive
+ * during the compilation of the template it deletes the `ngCloak` element attribute, which
+ * makes the compiled element visible.
+ *
+ * For the best result, `angular.js` script must be loaded in the head section of the html file;
+ * alternatively, the css rule (above) must be included in the external stylesheet of the
+ * application.
+ *
+ * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
+ * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
+ * class `ngCloak` in addition to `ngCloak` directive as shown in the example below.
+ *
+ * @element ANY
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <div id="template1" ng-cloak>{{ 'hello' }}</div>
+ <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
+ </doc:source>
+ <doc:scenario>
+ it('should remove the template directive and css class', function() {
+ expect(element('.doc-example-live #template1').attr('ng-cloak')).
+ not().toBeDefined();
+ expect(element('.doc-example-live #template2').attr('ng-cloak')).
+ not().toBeDefined();
+ });
+ </doc:scenario>
+ </doc:example>
+ *
+ */
+var ngCloakDirective = ngDirective({
+ compile: function(element, attr) {
+ attr.$set('ngCloak', undefined);
+ element.removeClass('ng-cloak');
+ }
+});
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngController
+ *
+ * @description
+ * The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular
+ * supports the principles behind the Model-View-Controller design pattern.
+ *
+ * MVC components in angular:
+ *
+ * * Model — The Model is data in scope properties; scopes are attached to the DOM.
+ * * View — The template (HTML with data bindings) is rendered into the View.
+ * * Controller — The `ngController` directive specifies a Controller class; the class has
+ * methods that typically express the business logic behind the application.
+ *
+ * Note that an alternative way to define controllers is via the {@link ng.$route $route} service.
+ *
+ * @element ANY
+ * @scope
+ * @param {expression} ngController Name of a globally accessible constructor function or an
+ * {@link guide/expression expression} that on the current scope evaluates to a
+ * constructor function. The controller instance can further be published into the scope
+ * by adding `as localName` the controller name attribute.
+ *
+ * @example
+ * Here is a simple form for editing user contact information. Adding, removing, clearing, and
+ * greeting are methods declared on the controller (see source tab). These methods can
+ * easily be called from the angular markup. Notice that the scope becomes the `this` for the
+ * controller's instance. This allows for easy access to the view data from the controller. Also
+ * notice that any changes to the data are automatically reflected in the View without the need
+ * for a manual update. The example is included in two different declaration styles based on
+ * your style preferences.
+ <doc:example>
+ <doc:source>
+ <script>
+ function SettingsController() {
+ this.name = "John Smith";
+ this.contacts = [
+ {type: 'phone', value: '408 555 1212'},
+ {type: 'email', value: 'john.smith@example.org'} ];
+ };
+
+ SettingsController.prototype.greet = function() {
+ alert(this.name);
+ };
+
+ SettingsController.prototype.addContact = function() {
+ this.contacts.push({type: 'email', value: 'yourname@example.org'});
+ };
+
+ SettingsController.prototype.removeContact = function(contactToRemove) {
+ var index = this.contacts.indexOf(contactToRemove);
+ this.contacts.splice(index, 1);
+ };
+
+ SettingsController.prototype.clearContact = function(contact) {
+ contact.type = 'phone';
+ contact.value = '';
+ };
+ </script>
+ <div ng-controller="SettingsController as settings">
+ Name: <input type="text" ng-model="settings.name"/>
+ [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
+ Contact:
+ <ul>
+ <li ng-repeat="contact in settings.contacts">
+ <select ng-model="contact.type">
+ <option>phone</option>
+ <option>email</option>
+ </select>
+ <input type="text" ng-model="contact.value"/>
+ [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
+ | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
+ </li>
+ <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
+ </ul>
+ </div>
+ </doc:source>
+ <doc:scenario>
+ it('should check controller', function() {
+ expect(element('.doc-example-live div>:input').val()).toBe('John Smith');
+ expect(element('.doc-example-live li:nth-child(1) input').val())
+ .toBe('408 555 1212');
+ expect(element('.doc-example-live li:nth-child(2) input').val())
+ .toBe('john.smith@example.org');
+
+ element('.doc-example-live li:first a:contains("clear")').click();
+ expect(element('.doc-example-live li:first input').val()).toBe('');
+
+ element('.doc-example-live li:last a:contains("add")').click();
+ expect(element('.doc-example-live li:nth-child(3) input').val())
+ .toBe('yourname@example.org');
+ });
+ </doc:scenario>
+ </doc:example>
+
+
+
+ <doc:example>
+ <doc:source>
+ <script>
+ function SettingsController($scope) {
+ $scope.name = "John Smith";
+ $scope.contacts = [
+ {type:'phone', value:'408 555 1212'},
+ {type:'email', value:'john.smith@example.org'} ];
+
+ $scope.greet = function() {
+ alert(this.name);
+ };
+
+ $scope.addContact = function() {
+ this.contacts.push({type:'email', value:'yourname@example.org'});
+ };
+
+ $scope.removeContact = function(contactToRemove) {
+ var index = this.contacts.indexOf(contactToRemove);
+ this.contacts.splice(index, 1);
+ };
+
+ $scope.clearContact = function(contact) {
+ contact.type = 'phone';
+ contact.value = '';
+ };
+ }
+ </script>
+ <div ng-controller="SettingsController">
+ Name: <input type="text" ng-model="name"/>
+ [ <a href="" ng-click="greet()">greet</a> ]<br/>
+ Contact:
+ <ul>
+ <li ng-repeat="contact in contacts">
+ <select ng-model="contact.type">
+ <option>phone</option>
+ <option>email</option>
+ </select>
+ <input type="text" ng-model="contact.value"/>
+ [ <a href="" ng-click="clearContact(contact)">clear</a>
+ | <a href="" ng-click="removeContact(contact)">X</a> ]
+ </li>
+ <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
+ </ul>
+ </div>
+ </doc:source>
+ <doc:scenario>
+ it('should check controller', function() {
+ expect(element('.doc-example-live div>:input').val()).toBe('John Smith');
+ expect(element('.doc-example-live li:nth-child(1) input').val())
+ .toBe('408 555 1212');
+ expect(element('.doc-example-live li:nth-child(2) input').val())
+ .toBe('john.smith@example.org');
+
+ element('.doc-example-live li:first a:contains("clear")').click();
+ expect(element('.doc-example-live li:first input').val()).toBe('');
+
+ element('.doc-example-live li:last a:contains("add")').click();
+ expect(element('.doc-example-live li:nth-child(3) input').val())
+ .toBe('yourname@example.org');
+ });
+ </doc:scenario>
+ </doc:example>
+
+ */
+var ngControllerDirective = [function() {
+ return {
+ scope: true,
+ controller: '@'
+ };
+}];
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngCsp
+ * @priority 1000
+ *
+ * @element html
+ * @description
+ * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
+ *
+ * This is necessary when developing things like Google Chrome Extensions.
+ *
+ * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
+ * For us to be compatible, we just need to implement the "getterFn" in $parse without violating
+ * any of these restrictions.
+ *
+ * AngularJS uses `Function(string)` generated functions as a speed optimization. By applying `ngCsp`
+ * it is be possible to opt into the CSP compatible mode. When this mode is on AngularJS will
+ * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
+ * be raised.
+ *
+ * In order to use this feature put `ngCsp` directive on the root element of the application.
+ *
+ * @example
+ * This example shows how to apply the `ngCsp` directive to the `html` tag.
+ <pre>
+ <!doctype html>
+ <html ng-app ng-csp>
+ ...
+ ...
+ </html>
+ </pre>
+ */
+
+var ngCspDirective = ['$sniffer', function($sniffer) {
+ return {
+ priority: 1000,
+ compile: function() {
+ $sniffer.csp = true;
+ }
+ };
+}];
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngClick
+ *
+ * @description
+ * The ngClick allows you to specify custom behavior when
+ * element is clicked.
+ *
+ * @element ANY
+ * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
+ * click. (Event object is available as `$event`)
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <button ng-click="count = count + 1" ng-init="count=0">
+ Increment
+ </button>
+ count: {{count}}
+ </doc:source>
+ <doc:scenario>
+ it('should check ng-click', function() {
+ expect(binding('count')).toBe('0');
+ element('.doc-example-live :button').click();
+ expect(binding('count')).toBe('1');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+/*
+ * A directive that allows creation of custom onclick handlers that are defined as angular
+ * expressions and are compiled and executed within the current scope.
+ *
+ * Events that are handled via these handler are always configured not to propagate further.
+ */
+var ngEventDirectives = {};
+forEach(
+ 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress'.split(' '),
+ function(name) {
+ var directiveName = directiveNormalize('ng-' + name);
+ ngEventDirectives[directiveName] = ['$parse', function($parse) {
+ return function(scope, element, attr) {
+ var fn = $parse(attr[directiveName]);
+ element.bind(lowercase(name), function(event) {
+ scope.$apply(function() {
+ fn(scope, {$event:event});
+ });
+ });
+ };
+ }];
+ }
+);
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngDblclick
+ *
+ * @description
+ * The `ngDblclick` directive allows you to specify custom behavior on dblclick event.
+ *
+ * @element ANY
+ * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
+ * dblclick. (Event object is available as `$event`)
+ *
+ * @example
+ * See {@link ng.directive:ngClick ngClick}
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngMousedown
+ *
+ * @description
+ * The ngMousedown directive allows you to specify custom behavior on mousedown event.
+ *
+ * @element ANY
+ * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
+ * mousedown. (Event object is available as `$event`)
+ *
+ * @example
+ * See {@link ng.directive:ngClick ngClick}
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngMouseup
+ *
+ * @description
+ * Specify custom behavior on mouseup event.
+ *
+ * @element ANY
+ * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
+ * mouseup. (Event object is available as `$event`)
+ *
+ * @example
+ * See {@link ng.directive:ngClick ngClick}
+ */
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngMouseover
+ *
+ * @description
+ * Specify custom behavior on mouseover event.
+ *
+ * @element ANY
+ * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
+ * mouseover. (Event object is available as `$event`)
+ *
+ * @example
+ * See {@link ng.directive:ngClick ngClick}
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngMouseenter
+ *
+ * @description
+ * Specify custom behavior on mouseenter event.
+ *
+ * @element ANY
+ * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
+ * mouseenter. (Event object is available as `$event`)
+ *
+ * @example
+ * See {@link ng.directive:ngClick ngClick}
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngMouseleave
+ *
+ * @description
+ * Specify custom behavior on mouseleave event.
+ *
+ * @element ANY
+ * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
+ * mouseleave. (Event object is available as `$event`)
+ *
+ * @example
+ * See {@link ng.directive:ngClick ngClick}
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngMousemove
+ *
+ * @description
+ * Specify custom behavior on mousemove event.
+ *
+ * @element ANY
+ * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
+ * mousemove. (Event object is available as `$event`)
+ *
+ * @example
+ * See {@link ng.directive:ngClick ngClick}
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngKeydown
+ *
+ * @description
+ * Specify custom behavior on keydown event.
+ *
+ * @element ANY
+ * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
+ * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
+ *
+ * @example
+ * See {@link ng.directive:ngClick ngClick}
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngKeyup
+ *
+ * @description
+ * Specify custom behavior on keyup event.
+ *
+ * @element ANY
+ * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
+ * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
+ *
+ * @example
+ * See {@link ng.directive:ngClick ngClick}
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngKeypress
+ *
+ * @description
+ * Specify custom behavior on keypress event.
+ *
+ * @element ANY
+ * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
+ * keypress. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
+ *
+ * @example
+ * See {@link ng.directive:ngClick ngClick}
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngSubmit
+ *
+ * @description
+ * Enables binding angular expressions to onsubmit events.
+ *
+ * Additionally it prevents the default action (which for form means sending the request to the
+ * server and reloading the current page).
+ *
+ * @element form
+ * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.list = [];
+ $scope.text = 'hello';
+ $scope.submit = function() {
+ if (this.text) {
+ this.list.push(this.text);
+ this.text = '';
+ }
+ };
+ }
+ </script>
+ <form ng-submit="submit()" ng-controller="Ctrl">
+ Enter text and hit enter:
+ <input type="text" ng-model="text" name="text" />
+ <input type="submit" id="submit" value="Submit" />
+ <pre>list={{list}}</pre>
+ </form>
+ </doc:source>
+ <doc:scenario>
+ it('should check ng-submit', function() {
+ expect(binding('list')).toBe('[]');
+ element('.doc-example-live #submit').click();
+ expect(binding('list')).toBe('["hello"]');
+ expect(input('text').val()).toBe('');
+ });
+ it('should ignore empty strings', function() {
+ expect(binding('list')).toBe('[]');
+ element('.doc-example-live #submit').click();
+ element('.doc-example-live #submit').click();
+ expect(binding('list')).toBe('["hello"]');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
+ element.bind('submit', function() {
+ scope.$apply(attrs.ngSubmit);
+ });
+});
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngIf
+ * @restrict A
+ *
+ * @description
+ * The `ngIf` directive removes and recreates a portion of the DOM tree (HTML)
+ * conditionally based on **"falsy"** and **"truthy"** values, respectively, evaluated within
+ * an {expression}. In other words, if the expression assigned to **ngIf evaluates to a false
+ * value** then **the element is removed from the DOM** and **if true** then **a clone of the
+ * element is reinserted into the DOM**.
+ *
+ * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
+ * element in the DOM rather than changing its visibility via the `display` css property. A common
+ * case when this difference is significant is when using css selectors that rely on an element's
+ * position within the DOM (HTML), such as the `:first-child` or `:last-child` pseudo-classes.
+ *
+ * Note that **when an element is removed using ngIf its scope is destroyed** and **a new scope
+ * is created when the element is restored**. The scope created within `ngIf` inherits from
+ * its parent scope using
+ * {@link https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance prototypal inheritance}.
+ * An important implication of this is if `ngModel` is used within `ngIf` to bind to
+ * a javascript primitive defined in the parent scope. In this case any modifications made to the
+ * variable within the child scope will override (hide) the value in the parent scope.
+ *
+ * Also, `ngIf` recreates elements using their compiled state. An example scenario of this behavior
+ * is if an element's class attribute is directly modified after it's compiled, using something like
+ * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
+ * the added class will be lost because the original compiled state is used to regenerate the element.
+ *
+ * Additionally, you can provide animations via the ngAnimate attribute to animate the **enter**
+ * and **leave** effects.
+ *
+ * @animations
+ * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container
+ * leave - happens just before the ngIf contents are removed from the DOM
+ *
+ * @element ANY
+ * @scope
+ * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
+ * the element is removed from the DOM tree (HTML).
+ *
+ * @example
+ <example animations="true">
+ <file name="index.html">
+ Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
+ Show when checked:
+ <span ng-if="checked" ng-animate="'example'">
+ I'm removed when the checkbox is unchecked.
+ </span>
+ </file>
+ <file name="animations.css">
+ .example-leave, .example-enter {
+ -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ -ms-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ }
+
+ .example-enter {
+ opacity:0;
+ }
+ .example-enter.example-enter-active {
+ opacity:1;
+ }
+
+ .example-leave {
+ opacity:1;
+ }
+ .example-leave.example-leave-active {
+ opacity:0;
+ }
+ </file>
+ </example>
+ */
+var ngIfDirective = ['$animator', function($animator) {
+ return {
+ transclude: 'element',
+ priority: 1000,
+ terminal: true,
+ restrict: 'A',
+ compile: function (element, attr, transclude) {
+ return function ($scope, $element, $attr) {
+ var animate = $animator($scope, $attr);
+ var childElement, childScope;
+ $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
+ if (childElement) {
+ animate.leave(childElement);
+ childElement = undefined;
+ }
+ if (childScope) {
+ childScope.$destroy();
+ childScope = undefined;
+ }
+ if (toBoolean(value)) {
+ childScope = $scope.$new();
+ transclude(childScope, function (clone) {
+ childElement = clone;
+ animate.enter(clone, $element.parent(), $element);
+ });
+ }
+ });
+ }
+ }
+ }
+}];
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngInclude
+ * @restrict ECA
+ *
+ * @description
+ * Fetches, compiles and includes an external HTML fragment.
+ *
+ * Keep in mind that Same Origin Policy applies to included resources
+ * (e.g. ngInclude won't work for cross-domain requests on all browsers and for
+ * file:// access on some browsers).
+ *
+ * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter**
+ * and **leave** effects.
+ *
+ * @animations
+ * enter - happens just after the ngInclude contents change and a new DOM element is created and injected into the ngInclude container
+ * leave - happens just after the ngInclude contents change and just before the former contents are removed from the DOM
+ *
+ * @scope
+ *
+ * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
+ * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`.
+ * @param {string=} onload Expression to evaluate when a new partial is loaded.
+ *
+ * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
+ * $anchorScroll} to scroll the viewport after the content is loaded.
+ *
+ * - If the attribute is not set, disable scrolling.
+ * - If the attribute is set without value, enable scrolling.
+ * - Otherwise enable scrolling only if the expression evaluates to truthy value.
+ *
+ * @example
+ <example animations="true">
+ <file name="index.html">
+ <div ng-controller="Ctrl">
+ <select ng-model="template" ng-options="t.name for t in templates">
+ <option value="">(blank)</option>
+ </select>
+ url of the template: <tt>{{template.url}}</tt>
+ <hr/>
+ <div class="example-animate-container"
+ ng-include="template.url"
+ ng-animate="{enter: 'example-enter', leave: 'example-leave'}"></div>
+ </div>
+ </file>
+ <file name="script.js">
+ function Ctrl($scope) {
+ $scope.templates =
+ [ { name: 'template1.html', url: 'template1.html'}
+ , { name: 'template2.html', url: 'template2.html'} ];
+ $scope.template = $scope.templates[0];
+ }
+ </file>
+ <file name="template1.html">
+ <div>Content of template1.html</div>
+ </file>
+ <file name="template2.html">
+ <div>Content of template2.html</div>
+ </file>
+ <file name="animations.css">
+ .example-leave,
+ .example-enter {
+ -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ -ms-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+
+ position:absolute;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+ }
+
+ .example-animate-container > * {
+ display:block;
+ padding:10px;
+ }
+
+ .example-enter {
+ top:-50px;
+ }
+ .example-enter.example-enter-active {
+ top:0;
+ }
+
+ .example-leave {
+ top:0;
+ }
+ .example-leave.example-leave-active {
+ top:50px;
+ }
+ </file>
+ <file name="scenario.js">
+ it('should load template1.html', function() {
+ expect(element('.doc-example-live [ng-include]').text()).
+ toMatch(/Content of template1.html/);
+ });
+ it('should load template2.html', function() {
+ select('template').option('1');
+ expect(element('.doc-example-live [ng-include]').text()).
+ toMatch(/Content of template2.html/);
+ });
+ it('should change to blank', function() {
+ select('template').option('');
+ expect(element('.doc-example-live [ng-include]').text()).toEqual('');
+ });
+ </file>
+ </example>
+ */
+
+
+/**
+ * @ngdoc event
+ * @name ng.directive:ngInclude#$includeContentRequested
+ * @eventOf ng.directive:ngInclude
+ * @eventType emit on the scope ngInclude was declared in
+ * @description
+ * Emitted every time the ngInclude content is requested.
+ */
+
+
+/**
+ * @ngdoc event
+ * @name ng.directive:ngInclude#$includeContentLoaded
+ * @eventOf ng.directive:ngInclude
+ * @eventType emit on the current ngInclude scope
+ * @description
+ * Emitted every time the ngInclude content is reloaded.
+ */
+var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', '$animator',
+ function($http, $templateCache, $anchorScroll, $compile, $animator) {
+ return {
+ restrict: 'ECA',
+ terminal: true,
+ compile: function(element, attr) {
+ var srcExp = attr.ngInclude || attr.src,
+ onloadExp = attr.onload || '',
+ autoScrollExp = attr.autoscroll;
+
+ return function(scope, element, attr) {
+ var animate = $animator(scope, attr);
+ var changeCounter = 0,
+ childScope;
+
+ var clearContent = function() {
+ if (childScope) {
+ childScope.$destroy();
+ childScope = null;
+ }
+ animate.leave(element.contents(), element);
+ };
+
+ scope.$watch(srcExp, function ngIncludeWatchAction(src) {
+ var thisChangeId = ++changeCounter;
+
+ if (src) {
+ $http.get(src, {cache: $templateCache}).success(function(response) {
+ if (thisChangeId !== changeCounter) return;
+
+ if (childScope) childScope.$destroy();
+ childScope = scope.$new();
+ animate.leave(element.contents(), element);
+
+ var contents = jqLite('<div/>').html(response).contents();
+
+ animate.enter(contents, element);
+ $compile(contents)(childScope);
+
+ if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
+ $anchorScroll();
+ }
+
+ childScope.$emit('$includeContentLoaded');
+ scope.$eval(onloadExp);
+ }).error(function() {
+ if (thisChangeId === changeCounter) clearContent();
+ });
+ scope.$emit('$includeContentRequested');
+ } else {
+ clearContent();
+ }
+ });
+ };
+ }
+ };
+}];
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngInit
+ *
+ * @description
+ * The `ngInit` directive specifies initialization tasks to be executed
+ * before the template enters execution mode during bootstrap.
+ *
+ * @element ANY
+ * @param {expression} ngInit {@link guide/expression Expression} to eval.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <div ng-init="greeting='Hello'; person='World'">
+ {{greeting}} {{person}}!
+ </div>
+ </doc:source>
+ <doc:scenario>
+ it('should check greeting', function() {
+ expect(binding('greeting')).toBe('Hello');
+ expect(binding('person')).toBe('World');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+var ngInitDirective = ngDirective({
+ compile: function() {
+ return {
+ pre: function(scope, element, attrs) {
+ scope.$eval(attrs.ngInit);
+ }
+ }
+ }
+});
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngNonBindable
+ * @priority 1000
+ *
+ * @description
+ * Sometimes it is necessary to write code which looks like bindings but which should be left alone
+ * by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML.
+ *
+ * @element ANY
+ *
+ * @example
+ * In this example there are two location where a simple binding (`{{}}`) is present, but the one
+ * wrapped in `ngNonBindable` is left alone.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <div>Normal: {{1 + 2}}</div>
+ <div ng-non-bindable>Ignored: {{1 + 2}}</div>
+ </doc:source>
+ <doc:scenario>
+ it('should check ng-non-bindable', function() {
+ expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
+ expect(using('.doc-example-live').element('div:last').text()).
+ toMatch(/1 \+ 2/);
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngPluralize
+ * @restrict EA
+ *
+ * @description
+ * # Overview
+ * `ngPluralize` is a directive that displays messages according to en-US localization rules.
+ * These rules are bundled with angular.js and the rules can be overridden
+ * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
+ * by specifying the mappings between
+ * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
+ * plural categories} and the strings to be displayed.
+ *
+ * # Plural categories and explicit number rules
+ * There are two
+ * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
+ * plural categories} in Angular's default en-US locale: "one" and "other".
+ *
+ * While a plural category may match many numbers (for example, in en-US locale, "other" can match
+ * any number that is not 1), an explicit number rule can only match one number. For example, the
+ * explicit number rule for "3" matches the number 3. You will see the use of plural categories
+ * and explicit number rules throughout later parts of this documentation.
+ *
+ * # Configuring ngPluralize
+ * You configure ngPluralize by providing 2 attributes: `count` and `when`.
+ * You can also provide an optional attribute, `offset`.
+ *
+ * The value of the `count` attribute can be either a string or an {@link guide/expression
+ * Angular expression}; these are evaluated on the current scope for its bound value.
+ *
+ * The `when` attribute specifies the mappings between plural categories and the actual
+ * string to be displayed. The value of the attribute should be a JSON object so that Angular
+ * can interpret it correctly.
+ *
+ * The following example shows how to configure ngPluralize:
+ *
+ * <pre>
+ * <ng-pluralize count="personCount"
+ when="{'0': 'Nobody is viewing.',
+ * 'one': '1 person is viewing.',
+ * 'other': '{} people are viewing.'}">
+ * </ng-pluralize>
+ *</pre>
+ *
+ * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
+ * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
+ * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
+ * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
+ * show "a dozen people are viewing".
+ *
+ * You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted
+ * into pluralized strings. In the previous example, Angular will replace `{}` with
+ * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
+ * for <span ng-non-bindable>{{numberExpression}}</span>.
+ *
+ * # Configuring ngPluralize with offset
+ * The `offset` attribute allows further customization of pluralized text, which can result in
+ * a better user experience. For example, instead of the message "4 people are viewing this document",
+ * you might display "John, Kate and 2 others are viewing this document".
+ * The offset attribute allows you to offset a number by any desired value.
+ * Let's take a look at an example:
+ *
+ * <pre>
+ * <ng-pluralize count="personCount" offset=2
+ * when="{'0': 'Nobody is viewing.',
+ * '1': '{{person1}} is viewing.',
+ * '2': '{{person1}} and {{person2}} are viewing.',
+ * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
+ * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
+ * </ng-pluralize>
+ * </pre>
+ *
+ * Notice that we are still using two plural categories(one, other), but we added
+ * three explicit number rules 0, 1 and 2.
+ * When one person, perhaps John, views the document, "John is viewing" will be shown.
+ * When three people view the document, no explicit number rule is found, so
+ * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
+ * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
+ * is shown.
+ *
+ * Note that when you specify offsets, you must provide explicit number rules for
+ * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
+ * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
+ * plural categories "one" and "other".
+ *
+ * @param {string|expression} count The variable to be bounded to.
+ * @param {string} when The mapping between plural category to its corresponding strings.
+ * @param {number=} offset Offset to deduct from the total number.
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.person1 = 'Igor';
+ $scope.person2 = 'Misko';
+ $scope.personCount = 1;
+ }
+ </script>
+ <div ng-controller="Ctrl">
+ Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
+ Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
+ Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
+
+ <!--- Example with simple pluralization rules for en locale --->
+ Without Offset:
+ <ng-pluralize count="personCount"
+ when="{'0': 'Nobody is viewing.',
+ 'one': '1 person is viewing.',
+ 'other': '{} people are viewing.'}">
+ </ng-pluralize><br>
+
+ <!--- Example with offset --->
+ With Offset(2):
+ <ng-pluralize count="personCount" offset=2
+ when="{'0': 'Nobody is viewing.',
+ '1': '{{person1}} is viewing.',
+ '2': '{{person1}} and {{person2}} are viewing.',
+ 'one': '{{person1}}, {{person2}} and one other person are viewing.',
+ 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
+ </ng-pluralize>
+ </div>
+ </doc:source>
+ <doc:scenario>
+ it('should show correct pluralized string', function() {
+ expect(element('.doc-example-live ng-pluralize:first').text()).
+ toBe('1 person is viewing.');
+ expect(element('.doc-example-live ng-pluralize:last').text()).
+ toBe('Igor is viewing.');
+
+ using('.doc-example-live').input('personCount').enter('0');
+ expect(element('.doc-example-live ng-pluralize:first').text()).
+ toBe('Nobody is viewing.');
+ expect(element('.doc-example-live ng-pluralize:last').text()).
+ toBe('Nobody is viewing.');
+
+ using('.doc-example-live').input('personCount').enter('2');
+ expect(element('.doc-example-live ng-pluralize:first').text()).
+ toBe('2 people are viewing.');
+ expect(element('.doc-example-live ng-pluralize:last').text()).
+ toBe('Igor and Misko are viewing.');
+
+ using('.doc-example-live').input('personCount').enter('3');
+ expect(element('.doc-example-live ng-pluralize:first').text()).
+ toBe('3 people are viewing.');
+ expect(element('.doc-example-live ng-pluralize:last').text()).
+ toBe('Igor, Misko and one other person are viewing.');
+
+ using('.doc-example-live').input('personCount').enter('4');
+ expect(element('.doc-example-live ng-pluralize:first').text()).
+ toBe('4 people are viewing.');
+ expect(element('.doc-example-live ng-pluralize:last').text()).
+ toBe('Igor, Misko and 2 other people are viewing.');
+ });
+
+ it('should show data-binded names', function() {
+ using('.doc-example-live').input('personCount').enter('4');
+ expect(element('.doc-example-live ng-pluralize:last').text()).
+ toBe('Igor, Misko and 2 other people are viewing.');
+
+ using('.doc-example-live').input('person1').enter('Di');
+ using('.doc-example-live').input('person2').enter('Vojta');
+ expect(element('.doc-example-live ng-pluralize:last').text()).
+ toBe('Di, Vojta and 2 other people are viewing.');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
+ var BRACE = /{}/g;
+ return {
+ restrict: 'EA',
+ link: function(scope, element, attr) {
+ var numberExp = attr.count,
+ whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs
+ offset = attr.offset || 0,
+ whens = scope.$eval(whenExp),
+ whensExpFns = {},
+ startSymbol = $interpolate.startSymbol(),
+ endSymbol = $interpolate.endSymbol();
+
+ forEach(whens, function(expression, key) {
+ whensExpFns[key] =
+ $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
+ offset + endSymbol));
+ });
+
+ scope.$watch(function ngPluralizeWatch() {
+ var value = parseFloat(scope.$eval(numberExp));
+
+ if (!isNaN(value)) {
+ //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
+ //check it against pluralization rules in $locale service
+ if (!(value in whens)) value = $locale.pluralCat(value - offset);
+ return whensExpFns[value](scope, element, true);
+ } else {
+ return '';
+ }
+ }, function ngPluralizeWatchAction(newVal) {
+ element.text(newVal);
+ });
+ }
+ };
+}];
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngRepeat
+ *
+ * @description
+ * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
+ * instance gets its own scope, where the given loop variable is set to the current collection item,
+ * and `$index` is set to the item index or key.
+ *
+ * Special properties are exposed on the local scope of each template instance, including:
+ *
+ * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1)
+ * * `$first` – `{boolean}` – true if the repeated element is first in the iterator.
+ * * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator.
+ * * `$last` – `{boolean}` – true if the repeated element is last in the iterator.
+ *
+ * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter**,
+ * **leave** and **move** effects.
+ *
+ * @animations
+ * enter - when a new item is added to the list or when an item is revealed after a filter
+ * leave - when an item is removed from the list or when an item is filtered out
+ * move - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
+ *
+ * @element ANY
+ * @scope
+ * @priority 1000
+ * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
+ * formats are currently supported:
+ *
+ * * `variable in expression` – where variable is the user defined loop variable and `expression`
+ * is a scope expression giving the collection to enumerate.
+ *
+ * For example: `track in cd.tracks`.
+ *
+ * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
+ * and `expression` is the scope expression giving the collection to enumerate.
+ *
+ * For example: `(name, age) in {'adam':10, 'amalie':12}`.
+ *
+ * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
+ * which can be used to associate the objects in the collection with the DOM elements. If no tractking function
+ * is specified the ng-repeat associates elements by identity in the collection. It is an error to have
+ * more then one tractking function to resolve to the same key. (This would mean that two distinct objects are
+ * mapped to the same DOM element, which is not possible.)
+ *
+ * For example: `item in items` is equivalent to `item in items track by $id(item)'. This implies that the DOM elements
+ * will be associated by item identity in the array.
+ *
+ * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
+ * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
+ * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
+ * element in the same way ian the DOM.
+ *
+ * For example: `item in items track by item.id` Is a typical pattern when the items come from the database. In this
+ * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
+ * property is same.
+ *
+ * @example
+ * This example initializes the scope to a list of names and
+ * then uses `ngRepeat` to display every person:
+ <example animations="true">
+ <file name="index.html">
+ <div ng-init="friends = [
+ {name:'John', age:25, gender:'boy'},
+ {name:'Jessie', age:30, gender:'girl'},
+ {name:'Johanna', age:28, gender:'girl'},
+ {name:'Joy', age:15, gender:'girl'},
+ {name:'Mary', age:28, gender:'girl'},
+ {name:'Peter', age:95, gender:'boy'},
+ {name:'Sebastian', age:50, gender:'boy'},
+ {name:'Erika', age:27, gender:'girl'},
+ {name:'Patrick', age:40, gender:'boy'},
+ {name:'Samantha', age:60, gender:'girl'}
+ ]">
+ I have {{friends.length}} friends. They are:
+ <input type="search" ng-model="q" placeholder="filter friends..." />
+ <ul>
+ <li ng-repeat="friend in friends | filter:q"
+ ng-animate="{enter: 'example-repeat-enter',
+ leave: 'example-repeat-leave',
+ move: 'example-repeat-move'}">
+ [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
+ </li>
+ </ul>
+ </div>
+ </file>
+ <file name="animations.css">
+ .example-repeat-enter,
+ .example-repeat-leave,
+ .example-repeat-move {
+ -webkit-transition:all linear 0.5s;
+ -moz-transition:all linear 0.5s;
+ -ms-transition:all linear 0.5s;
+ -o-transition:all linear 0.5s;
+ transition:all linear 0.5s;
+ }
+
+ .example-repeat-enter {
+ line-height:0;
+ opacity:0;
+ }
+ .example-repeat-enter.example-repeat-enter-active {
+ line-height:20px;
+ opacity:1;
+ }
+
+ .example-repeat-leave {
+ opacity:1;
+ line-height:20px;
+ }
+ .example-repeat-leave.example-repeat-leave-active {
+ opacity:0;
+ line-height:0;
+ }
+
+ .example-repeat-move { }
+ .example-repeat-move.example-repeat-move-active { }
+ </file>
+ <file name="scenario.js">
+ it('should render initial data set', function() {
+ var r = using('.doc-example-live').repeater('ul li');
+ expect(r.count()).toBe(10);
+ expect(r.row(0)).toEqual(["1","John","25"]);
+ expect(r.row(1)).toEqual(["2","Jessie","30"]);
+ expect(r.row(9)).toEqual(["10","Samantha","60"]);
+ expect(binding('friends.length')).toBe("10");
+ });
+
+ it('should update repeater when filter predicate changes', function() {
+ var r = using('.doc-example-live').repeater('ul li');
+ expect(r.count()).toBe(10);
+
+ input('q').enter('ma');
+
+ expect(r.count()).toBe(2);
+ expect(r.row(0)).toEqual(["1","Mary","28"]);
+ expect(r.row(1)).toEqual(["2","Samantha","60"]);
+ });
+ </file>
+ </example>
+ */
+var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
+ var NG_REMOVED = '$$NG_REMOVED';
+ return {
+ transclude: 'element',
+ priority: 1000,
+ terminal: true,
+ compile: function(element, attr, linker) {
+ return function($scope, $element, $attr){
+ var animate = $animator($scope, $attr);
+ var expression = $attr.ngRepeat;
+ var match = expression.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/),
+ trackByExp, trackByExpGetter, trackByIdFn, lhs, rhs, valueIdentifier, keyIdentifier,
+ hashFnLocals = {$id: hashKey};
+
+ if (!match) {
+ throw Error("Expected ngRepeat in form of '_item_ in _collection_[ track by _id_]' but got '" +
+ expression + "'.");
+ }
+
+ lhs = match[1];
+ rhs = match[2];
+ trackByExp = match[4];
+
+ if (trackByExp) {
+ trackByExpGetter = $parse(trackByExp);
+ trackByIdFn = function(key, value, index) {
+ // assign key, value, and $index to the locals so that they can be used in hash functions
+ if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
+ hashFnLocals[valueIdentifier] = value;
+ hashFnLocals.$index = index;
+ return trackByExpGetter($scope, hashFnLocals);
+ };
+ } else {
+ trackByIdFn = function(key, value) {
+ return hashKey(value);
+ }
+ }
+
+ match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
+ if (!match) {
+ throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" +
+ lhs + "'.");
+ }
+ valueIdentifier = match[3] || match[1];
+ keyIdentifier = match[2];
+
+ // Store a list of elements from previous run. This is a hash where key is the item from the
+ // iterator, and the value is objects with following properties.
+ // - scope: bound scope
+ // - element: previous element.
+ // - index: position
+ var lastBlockMap = {};
+
+ //watch props
+ $scope.$watchCollection(rhs, function ngRepeatAction(collection){
+ var index, length,
+ cursor = $element, // current position of the node
+ nextCursor,
+ // Same as lastBlockMap but it has the current state. It will become the
+ // lastBlockMap on the next iteration.
+ nextBlockMap = {},
+ arrayLength,
+ childScope,
+ key, value, // key/value of iteration
+ trackById,
+ collectionKeys,
+ block, // last object information {scope, element, id}
+ nextBlockOrder = [];
+
+
+ if (isArrayLike(collection)) {
+ collectionKeys = collection;
+ } else {
+ // if object, extract keys, sort them and use to determine order of iteration over obj props
+ collectionKeys = [];
+ for (key in collection) {
+ if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
+ collectionKeys.push(key);
+ }
+ }
+ collectionKeys.sort();
+ }
+
+ arrayLength = collectionKeys.length;
+
+ // locate existing items
+ length = nextBlockOrder.length = collectionKeys.length;
+ for(index = 0; index < length; index++) {
+ key = (collection === collectionKeys) ? index : collectionKeys[index];
+ value = collection[key];
+ trackById = trackByIdFn(key, value, index);
+ if(lastBlockMap.hasOwnProperty(trackById)) {
+ block = lastBlockMap[trackById]
+ delete lastBlockMap[trackById];
+ nextBlockMap[trackById] = block;
+ nextBlockOrder[index] = block;
+ } else if (nextBlockMap.hasOwnProperty(trackById)) {
+ // restore lastBlockMap
+ forEach(nextBlockOrder, function(block) {
+ if (block && block.element) lastBlockMap[block.id] = block;
+ });
+ // This is a duplicate and we need to throw an error
+ throw new Error('Duplicates in a repeater are not allowed. Repeater: ' + expression +
+ ' key: ' + trackById);
+ } else {
+ // new never before seen block
+ nextBlockOrder[index] = { id: trackById };
+ nextBlockMap[trackById] = false;
+ }
+ }
+
+ // remove existing items
+ for (key in lastBlockMap) {
+ if (lastBlockMap.hasOwnProperty(key)) {
+ block = lastBlockMap[key];
+ animate.leave(block.element);
+ block.element[0][NG_REMOVED] = true;
+ block.scope.$destroy();
+ }
+ }
+
+ // we are not using forEach for perf reasons (trying to avoid #call)
+ for (index = 0, length = collectionKeys.length; index < length; index++) {
+ key = (collection === collectionKeys) ? index : collectionKeys[index];
+ value = collection[key];
+ block = nextBlockOrder[index];
+
+ if (block.element) {
+ // if we have already seen this object, then we need to reuse the
+ // associated scope/element
+ childScope = block.scope;
+
+ nextCursor = cursor[0];
+ do {
+ nextCursor = nextCursor.nextSibling;
+ } while(nextCursor && nextCursor[NG_REMOVED]);
+
+ if (block.element[0] == nextCursor) {
+ // do nothing
+ cursor = block.element;
+ } else {
+ // existing item which got moved
+ animate.move(block.element, null, cursor);
+ cursor = block.element;
+ }
+ } else {
+ // new item which we don't know about
+ childScope = $scope.$new();
+ }
+
+ childScope[valueIdentifier] = value;
+ if (keyIdentifier) childScope[keyIdentifier] = key;
+ childScope.$index = index;
+ childScope.$first = (index === 0);
+ childScope.$last = (index === (arrayLength - 1));
+ childScope.$middle = !(childScope.$first || childScope.$last);
+
+ if (!block.element) {
+ linker(childScope, function(clone) {
+ animate.enter(clone, null, cursor);
+ cursor = clone;
+ block.scope = childScope;
+ block.element = clone;
+ nextBlockMap[block.id] = block;
+ });
+ }
+ }
+ lastBlockMap = nextBlockMap;
+ });
+ };
+ }
+ };
+}];
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngShow
+ *
+ * @description
+ * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML)
+ * conditionally based on **"truthy"** values evaluated within an {expression}. In other
+ * words, if the expression assigned to **ngShow evaluates to a true value** then **the element is set to visible**
+ * (via `display:block` in css) and **if false** then **the element is set to hidden** (so display:none).
+ * With ngHide this is the reverse whereas true values cause the element itself to become
+ * hidden.
+ *
+ * Additionally, you can also provide animations via the ngAnimate attribute to animate the **show**
+ * and **hide** effects.
+ *
+ * @animations
+ * show - happens after the ngShow expression evaluates to a truthy value and the contents are set to visible
+ * hide - happens before the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden
+ *
+ * @element ANY
+ * @param {expression} ngShow If the {@link guide/expression expression} is truthy
+ * then the element is shown or hidden respectively.
+ *
+ * @example
+ <example animations="true">
+ <file name="index.html">
+ Click me: <input type="checkbox" ng-model="checked"><br/>
+ <div>
+ Show:
+ <span class="check-element"
+ ng-show="checked"
+ ng-animate="{show: 'example-show', hide: 'example-hide'}">
+ <span class="icon-thumbs-up"></span> I show up when your checkbox is checked.
+ </span>
+ </div>
+ <div>
+ Hide:
+ <span class="check-element"
+ ng-hide="checked"
+ ng-animate="{show: 'example-show', hide: 'example-hide'}">
+ <span class="icon-thumbs-down"></span> I hide when your checkbox is checked.
+ </span>
+ </div>
+ </file>
+ <file name="animations.css">
+ .example-show, .example-hide {
+ -webkit-transition:all linear 0.5s;
+ -moz-transition:all linear 0.5s;
+ -ms-transition:all linear 0.5s;
+ -o-transition:all linear 0.5s;
+ transition:all linear 0.5s;
+ }
+
+ .example-show {
+ line-height:0;
+ opacity:0;
+ padding:0 10px;
+ }
+ .example-show-active.example-show-active {
+ line-height:20px;
+ opacity:1;
+ padding:10px;
+ border:1px solid black;
+ background:white;
+ }
+
+ .example-hide {
+ line-height:20px;
+ opacity:1;
+ padding:10px;
+ border:1px solid black;
+ background:white;
+ }
+ .example-hide-active.example-hide-active {
+ line-height:0;
+ opacity:0;
+ padding:0 10px;
+ }
+
+ .check-element {
+ padding:10px;
+ border:1px solid black;
+ background:white;
+ }
+ </file>
+ <file name="scenario.js">
+ it('should check ng-show / ng-hide', function() {
+ expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
+ expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
+
+ input('checked').check();
+
+ expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
+ expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
+ });
+ </file>
+ </example>
+ */
+//TODO(misko): refactor to remove element from the DOM
+var ngShowDirective = ['$animator', function($animator) {
+ return function(scope, element, attr) {
+ var animate = $animator(scope, attr);
+ scope.$watch(attr.ngShow, function ngShowWatchAction(value){
+ animate[toBoolean(value) ? 'show' : 'hide'](element);
+ });
+ };
+}];
+
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngHide
+ *
+ * @description
+ * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML)
+ * conditionally based on **"truthy"** values evaluated within an {expression}. In other
+ * words, if the expression assigned to **ngShow evaluates to a true value** then **the element is set to visible**
+ * (via `display:block` in css) and **if false** then **the element is set to hidden** (so display:none).
+ * With ngHide this is the reverse whereas true values cause the element itself to become
+ * hidden.
+ *
+ * Additionally, you can also provide animations via the ngAnimate attribute to animate the **show**
+ * and **hide** effects.
+ *
+ * @animations
+ * show - happens after the ngHide expression evaluates to a non truthy value and the contents are set to visible
+ * hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden
+ *
+ * @element ANY
+ * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
+ * the element is shown or hidden respectively.
+ *
+ * @example
+ <example animations="true">
+ <file name="index.html">
+ Click me: <input type="checkbox" ng-model="checked"><br/>
+ <div>
+ Show:
+ <span class="check-element"
+ ng-show="checked"
+ ng-animate="{show: 'example-show', hide: 'example-hide'}">
+ <span class="icon-thumbs-up"></span> I show up when your checkbox is checked.
+ </span>
+ </div>
+ <div>
+ Hide:
+ <span class="check-element"
+ ng-hide="checked"
+ ng-animate="{show: 'example-show', hide: 'example-hide'}">
+ <span class="icon-thumbs-down"></span> I hide when your checkbox is checked.
+ </span>
+ </div>
+ </file>
+ <file name="animations.css">
+ .example-show, .example-hide {
+ -webkit-transition:all linear 0.5s;
+ -moz-transition:all linear 0.5s;
+ -ms-transition:all linear 0.5s;
+ -o-transition:all linear 0.5s;
+ transition:all linear 0.5s;
+ }
+
+ .example-show {
+ line-height:0;
+ opacity:0;
+ padding:0 10px;
+ }
+ .example-show.example-show-active {
+ line-height:20px;
+ opacity:1;
+ padding:10px;
+ border:1px solid black;
+ background:white;
+ }
+
+ .example-hide {
+ line-height:20px;
+ opacity:1;
+ padding:10px;
+ border:1px solid black;
+ background:white;
+ }
+ .example-hide.example-hide-active {
+ line-height:0;
+ opacity:0;
+ padding:0 10px;
+ }
+
+ .check-element {
+ padding:10px;
+ border:1px solid black;
+ background:white;
+ }
+ </file>
+ <file name="scenario.js">
+ it('should check ng-show / ng-hide', function() {
+ expect(element('.doc-example-live .check-element:first:hidden').count()).toEqual(1);
+ expect(element('.doc-example-live .check-element:last:visible').count()).toEqual(1);
+
+ input('checked').check();
+
+ expect(element('.doc-example-live .check-element:first:visible').count()).toEqual(1);
+ expect(element('.doc-example-live .check-element:last:hidden').count()).toEqual(1);
+ });
+ </file>
+ </example>
+ */
+//TODO(misko): refactor to remove element from the DOM
+var ngHideDirective = ['$animator', function($animator) {
+ return function(scope, element, attr) {
+ var animate = $animator(scope, attr);
+ scope.$watch(attr.ngHide, function ngHideWatchAction(value){
+ animate[toBoolean(value) ? 'hide' : 'show'](element);
+ });
+ };
+}];
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngStyle
+ *
+ * @description
+ * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
+ *
+ * @element ANY
+ * @param {expression} ngStyle {@link guide/expression Expression} which evals to an
+ * object whose keys are CSS style names and values are corresponding values for those CSS
+ * keys.
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <input type="button" value="set" ng-click="myStyle={color:'red'}">
+ <input type="button" value="clear" ng-click="myStyle={}">
+ <br/>
+ <span ng-style="myStyle">Sample Text</span>
+ <pre>myStyle={{myStyle}}</pre>
+ </file>
+ <file name="style.css">
+ span {
+ color: black;
+ }
+ </file>
+ <file name="scenario.js">
+ it('should check ng-style', function() {
+ expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
+ element('.doc-example-live :button[value=set]').click();
+ expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)');
+ element('.doc-example-live :button[value=clear]').click();
+ expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
+ });
+ </file>
+ </example>
+ */
+var ngStyleDirective = ngDirective(function(scope, element, attr) {
+ scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
+ if (oldStyles && (newStyles !== oldStyles)) {
+ forEach(oldStyles, function(val, style) { element.css(style, '');});
+ }
+ if (newStyles) element.css(newStyles);
+ }, true);
+});
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngSwitch
+ * @restrict EA
+ *
+ * @description
+ * The ngSwitch directive is used to conditionally swap DOM structure on your template based on a scope expression.
+ * Elements within ngSwitch but without ngSwitchWhen or ngSwitchDefault directives will be preserved at the location
+ * as specified in the template.
+ *
+ * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
+ * from the template cache), ngSwitch simply choses one of the nested elements and makes it visible based on which element
+ * matches the value obtained from the evaluated expression. In other words, you define a container element
+ * (where you place the directive), place an expression on the **on="..." attribute**
+ * (or the **ng-switch="..." attribute**), define any inner elements inside of the directive and place
+ * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
+ * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
+ * attribute is displayed.
+ *
+ * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter**
+ * and **leave** effects.
+ *
+ * @animations
+ * enter - happens after the ngSwtich contents change and the matched child element is placed inside the container
+ * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
+ *
+ * @usage
+ * <ANY ng-switch="expression">
+ * <ANY ng-switch-when="matchValue1">...</ANY>
+ * <ANY ng-switch-when="matchValue2">...</ANY>
+ * <ANY ng-switch-default>...</ANY>
+ * </ANY>
+ *
+ * @scope
+ * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
+ * @paramDescription
+ * On child elements add:
+ *
+ * * `ngSwitchWhen`: the case statement to match against. If match then this
+ * case will be displayed. If the same match appears multiple times, all the
+ * elements will be displayed.
+ * * `ngSwitchDefault`: the default case when no other case match. If there
+ * are multiple default cases, all of them will be displayed when no other
+ * case match.
+ *
+ *
+ * @example
+ <example animations="true">
+ <file name="index.html">
+ <div ng-controller="Ctrl">
+ <select ng-model="selection" ng-options="item for item in items">
+ </select>
+ <tt>selection={{selection}}</tt>
+ <hr/>
+ <div
+ class="example-animate-container"
+ ng-switch on="selection"
+ ng-animate="{enter: 'example-enter', leave: 'example-leave'}">
+ <div ng-switch-when="settings">Settings Div</div>
+ <div ng-switch-when="home">Home Span</div>
+ <div ng-switch-default>default</div>
+ </div>
+ </div>
+ </file>
+ <file name="script.js">
+ function Ctrl($scope) {
+ $scope.items = ['settings', 'home', 'other'];
+ $scope.selection = $scope.items[0];
+ }
+ </file>
+ <file name="animations.css">
+ .example-leave, .example-enter {
+ -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ -ms-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+
+ position:absolute;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+ }
+
+ .example-animate-container > * {
+ display:block;
+ padding:10px;
+ }
+
+ .example-enter {
+ top:-50px;
+ }
+ .example-enter.example-enter-active {
+ top:0;
+ }
+
+ .example-leave {
+ top:0;
+ }
+ .example-leave.example-leave-active {
+ top:50px;
+ }
+ </file>
+ <file name="scenario.js">
+ it('should start in settings', function() {
+ expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/);
+ });
+ it('should change to home', function() {
+ select('selection').option('home');
+ expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/);
+ });
+ it('should select default', function() {
+ select('selection').option('other');
+ expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/);
+ });
+ </file>
+ </example>
+ */
+var ngSwitchDirective = ['$animator', function($animator) {
+ return {
+ restrict: 'EA',
+ require: 'ngSwitch',
+
+ // asks for $scope to fool the BC controller module
+ controller: ['$scope', function ngSwitchController() {
+ this.cases = {};
+ }],
+ link: function(scope, element, attr, ngSwitchController) {
+ var animate = $animator(scope, attr);
+ var watchExpr = attr.ngSwitch || attr.on,
+ selectedTranscludes,
+ selectedElements,
+ selectedScopes = [];
+
+ scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
+ for (var i= 0, ii=selectedScopes.length; i<ii; i++) {
+ selectedScopes[i].$destroy();
+ animate.leave(selectedElements[i]);
+ }
+
+ selectedElements = [];
+ selectedScopes = [];
+
+ if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
+ scope.$eval(attr.change);
+ forEach(selectedTranscludes, function(selectedTransclude) {
+ var selectedScope = scope.$new();
+ selectedScopes.push(selectedScope);
+ selectedTransclude.transclude(selectedScope, function(caseElement) {
+ var anchor = selectedTransclude.element;
+
+ selectedElements.push(caseElement);
+ animate.enter(caseElement, anchor.parent(), anchor);
+ });
+ });
+ }
+ });
+ }
+ }
+}];
+
+var ngSwitchWhenDirective = ngDirective({
+ transclude: 'element',
+ priority: 500,
+ require: '^ngSwitch',
+ compile: function(element, attrs, transclude) {
+ return function(scope, element, attr, ctrl) {
+ ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
+ ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: transclude, element: element });
+ };
+ }
+});
+
+var ngSwitchDefaultDirective = ngDirective({
+ transclude: 'element',
+ priority: 500,
+ require: '^ngSwitch',
+ compile: function(element, attrs, transclude) {
+ return function(scope, element, attr, ctrl) {
+ ctrl.cases['?'] = (ctrl.cases['?'] || []);
+ ctrl.cases['?'].push({ transclude: transclude, element: element });
+ };
+ }
+});
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngTransclude
+ *
+ * @description
+ * Insert the transcluded DOM here.
+ *
+ * @element ANY
+ *
+ * @example
+ <doc:example module="transclude">
+ <doc:source>
+ <script>
+ function Ctrl($scope) {
+ $scope.title = 'Lorem Ipsum';
+ $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
+ }
+
+ angular.module('transclude', [])
+ .directive('pane', function(){
+ return {
+ restrict: 'E',
+ transclude: true,
+ scope: 'isolate',
+ locals: { title:'bind' },
+ template: '<div style="border: 1px solid black;">' +
+ '<div style="background-color: gray">{{title}}</div>' +
+ '<div ng-transclude></div>' +
+ '</div>'
+ };
+ });
+ </script>
+ <div ng-controller="Ctrl">
+ <input ng-model="title"><br>
+ <textarea ng-model="text"></textarea> <br/>
+ <pane title="{{title}}">{{text}}</pane>
+ </div>
+ </doc:source>
+ <doc:scenario>
+ it('should have transcluded', function() {
+ input('title').enter('TITLE');
+ input('text').enter('TEXT');
+ expect(binding('title')).toEqual('TITLE');
+ expect(binding('text')).toEqual('TEXT');
+ });
+ </doc:scenario>
+ </doc:example>
+ *
+ */
+var ngTranscludeDirective = ngDirective({
+ controller: ['$transclude', '$element', function($transclude, $element) {
+ $transclude(function(clone) {
+ $element.append(clone);
+ });
+ }]
+});
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngView
+ * @restrict ECA
+ *
+ * @description
+ * # Overview
+ * `ngView` is a directive that complements the {@link ng.$route $route} service by
+ * including the rendered template of the current route into the main layout (`index.html`) file.
+ * Every time the current route changes, the included view changes with it according to the
+ * configuration of the `$route` service.
+ *
+ * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter**
+ * and **leave** effects.
+ *
+ * @animations
+ * enter - happens just after the ngView contents are changed (when the new view DOM element is inserted into the DOM)
+ * leave - happens just after the current ngView contents change and just before the former contents are removed from the DOM
+ *
+ * @scope
+ * @example
+ <example module="ngView" animations="true">
+ <file name="index.html">
+ <div ng-controller="MainCntl as main">
+ Choose:
+ <a href="Book/Moby">Moby</a> |
+ <a href="Book/Moby/ch/1">Moby: Ch1</a> |
+ <a href="Book/Gatsby">Gatsby</a> |
+ <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
+ <a href="Book/Scarlet">Scarlet Letter</a><br/>
+
+ <div
+ ng-view
+ class="example-animate-container"
+ ng-animate="{enter: 'example-enter', leave: 'example-leave'}"></div>
+ <hr />
+
+ <pre>$location.path() = {{main.$location.path()}}</pre>
+ <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
+ <pre>$route.current.params = {{main.$route.current.params}}</pre>
+ <pre>$route.current.scope.name = {{main.$route.current.scope.name}}</pre>
+ <pre>$routeParams = {{main.$routeParams}}</pre>
+ </div>
+ </file>
+
+ <file name="book.html">
+ <div>
+ controller: {{book.name}}<br />
+ Book Id: {{book.params.bookId}}<br />
+ </div>
+ </file>
+
+ <file name="chapter.html">
+ <div>
+ controller: {{chapter.name}}<br />
+ Book Id: {{chapter.params.bookId}}<br />
+ Chapter Id: {{chapter.params.chapterId}}
+ </div>
+ </file>
+
+ <file name="animations.css">
+ .example-leave, .example-enter {
+ -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
+ -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
+ -ms-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
+ -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
+ transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
+ }
+
+ .example-animate-container {
+ position:relative;
+ height:100px;
+ }
+
+ .example-animate-container > * {
+ display:block;
+ width:100%;
+ border-left:1px solid black;
+
+ position:absolute;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+ padding:10px;
+ }
+
+ .example-enter {
+ left:100%;
+ }
+ .example-enter.example-enter-active {
+ left:0;
+ }
+
+ .example-leave { }
+ .example-leave.example-leave-active {
+ left:-100%;
+ }
+ </file>
+
+ <file name="script.js">
+ angular.module('ngView', [], function($routeProvider, $locationProvider) {
+ $routeProvider.when('/Book/:bookId', {
+ templateUrl: 'book.html',
+ controller: BookCntl,
+ controllerAs: 'book'
+ });
+ $routeProvider.when('/Book/:bookId/ch/:chapterId', {
+ templateUrl: 'chapter.html',
+ controller: ChapterCntl,
+ controllerAs: 'chapter'
+ });
+
+ // configure html5 to get links working on jsfiddle
+ $locationProvider.html5Mode(true);
+ });
+
+ function MainCntl($route, $routeParams, $location) {
+ this.$route = $route;
+ this.$location = $location;
+ this.$routeParams = $routeParams;
+ }
+
+ function BookCntl($routeParams) {
+ this.name = "BookCntl";
+ this.params = $routeParams;
+ }
+
+ function ChapterCntl($routeParams) {
+ this.name = "ChapterCntl";
+ this.params = $routeParams;
+ }
+ </file>
+
+ <file name="scenario.js">
+ it('should load and compile correct template', function() {
+ element('a:contains("Moby: Ch1")').click();
+ var content = element('.doc-example-live [ng-view]').text();
+ expect(content).toMatch(/controller\: ChapterCntl/);
+ expect(content).toMatch(/Book Id\: Moby/);
+ expect(content).toMatch(/Chapter Id\: 1/);
+
+ element('a:contains("Scarlet")').click();
+ content = element('.doc-example-live [ng-view]').text();
+ expect(content).toMatch(/controller\: BookCntl/);
+ expect(content).toMatch(/Book Id\: Scarlet/);
+ });
+ </file>
+ </example>
+ */
+
+
+/**
+ * @ngdoc event
+ * @name ng.directive:ngView#$viewContentLoaded
+ * @eventOf ng.directive:ngView
+ * @eventType emit on the current ngView scope
+ * @description
+ * Emitted every time the ngView content is reloaded.
+ */
+var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile',
+ '$controller', '$animator',
+ function($http, $templateCache, $route, $anchorScroll, $compile,
+ $controller, $animator) {
+ return {
+ restrict: 'ECA',
+ terminal: true,
+ link: function(scope, element, attr) {
+ var lastScope,
+ onloadExp = attr.onload || '',
+ animate = $animator(scope, attr);
+
+ scope.$on('$routeChangeSuccess', update);
+ update();
+
+
+ function destroyLastScope() {
+ if (lastScope) {
+ lastScope.$destroy();
+ lastScope = null;
+ }
+ }
+
+ function clearContent() {
+ animate.leave(element.contents(), element);
+ destroyLastScope();
+ }
+
+ function update() {
+ var locals = $route.current && $route.current.locals,
+ template = locals && locals.$template;
+
+ if (template) {
+ clearContent();
+ var enterElements = jqLite('<div></div>').html(template).contents();
+ animate.enter(enterElements, element);
+
+ var link = $compile(enterElements),
+ current = $route.current,
+ controller;
+
+ lastScope = current.scope = scope.$new();
+ if (current.controller) {
+ locals.$scope = lastScope;
+ controller = $controller(current.controller, locals);
+ if (current.controllerAs) {
+ lastScope[current.controllerAs] = controller;
+ }
+ element.children().data('$ngControllerController', controller);
+ }
+
+ link(lastScope);
+ lastScope.$emit('$viewContentLoaded');
+ lastScope.$eval(onloadExp);
+
+ // $anchorScroll might listen on event...
+ $anchorScroll();
+ } else {
+ clearContent();
+ }
+ }
+ }
+ };
+}];
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:script
+ *
+ * @description
+ * Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the
+ * template can be used by `ngInclude`, `ngView` or directive templates.
+ *
+ * @restrict E
+ * @param {'text/ng-template'} type must be set to `'text/ng-template'`
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script type="text/ng-template" id="/tpl.html">
+ Content of the template.
+ </script>
+
+ <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
+ <div id="tpl-content" ng-include src="currentTpl"></div>
+ </doc:source>
+ <doc:scenario>
+ it('should load template defined inside script tag', function() {
+ element('#tpl-link').click();
+ expect(element('#tpl-content').text()).toMatch(/Content of the template/);
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+var scriptDirective = ['$templateCache', function($templateCache) {
+ return {
+ restrict: 'E',
+ terminal: true,
+ compile: function(element, attr) {
+ if (attr.type == 'text/ng-template') {
+ var templateUrl = attr.id,
+ // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
+ text = element[0].text;
+
+ $templateCache.put(templateUrl, text);
+ }
+ }
+ };
+}];
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:select
+ * @restrict E
+ *
+ * @description
+ * HTML `SELECT` element with angular data-binding.
+ *
+ * # `ngOptions`
+ *
+ * Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>`
+ * elements for a `<select>` element using an array or an object obtained by evaluating the
+ * `ngOptions` expression.
+ *˝˝
+ * When an item in the select menu is select, the value of array element or object property
+ * represented by the selected option will be bound to the model identified by the `ngModel`
+ * directive of the parent select element.
+ *
+ * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
+ * be nested into the `<select>` element. This element will then represent `null` or "not selected"
+ * option. See example below for demonstration.
+ *
+ * Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead
+ * of {@link ng.directive:ngRepeat ngRepeat} when you want the
+ * `select` model to be bound to a non-string value. This is because an option element can currently
+ * be bound to string values only.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} required The control is considered valid only if value is entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {comprehension_expression=} ngOptions in one of the following forms:
+ *
+ * * for array data sources:
+ * * `label` **`for`** `value` **`in`** `array`
+ * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
+ * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
+ * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
+ * * for object data sources:
+ * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
+ * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
+ * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
+ * * `select` **`as`** `label` **`group by`** `group`
+ * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
+ *
+ * Where:
+ *
+ * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
+ * * `value`: local variable which will refer to each item in the `array` or each property value
+ * of `object` during iteration.
+ * * `key`: local variable which will refer to a property name in `object` during iteration.
+ * * `label`: The result of this expression will be the label for `<option>` element. The
+ * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
+ * * `select`: The result of this expression will be bound to the model of the parent `<select>`
+ * element. If not specified, `select` expression will default to `value`.
+ * * `group`: The result of this expression will be used to group options using the `<optgroup>`
+ * DOM element.
+ * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
+ * used to identify the objects in the array. The `trackexpr` will most likely refer to the
+ * `value` variable (e.g. `value.propertyName`).
+ *
+ * @example
+ <doc:example>
+ <doc:source>
+ <script>
+ function MyCntrl($scope) {
+ $scope.colors = [
+ {name:'black', shade:'dark'},
+ {name:'white', shade:'light'},
+ {name:'red', shade:'dark'},
+ {name:'blue', shade:'dark'},
+ {name:'yellow', shade:'light'}
+ ];
+ $scope.color = $scope.colors[2]; // red
+ }
+ </script>
+ <div ng-controller="MyCntrl">
+ <ul>
+ <li ng-repeat="color in colors">
+ Name: <input ng-model="color.name">
+ [<a href ng-click="colors.splice($index, 1)">X</a>]
+ </li>
+ <li>
+ [<a href ng-click="colors.push({})">add</a>]
+ </li>
+ </ul>
+ <hr/>
+ Color (null not allowed):
+ <select ng-model="color" ng-options="c.name for c in colors"></select><br>
+
+ Color (null allowed):
+ <span class="nullable">
+ <select ng-model="color" ng-options="c.name for c in colors">
+ <option value="">-- chose color --</option>
+ </select>
+ </span><br/>
+
+ Color grouped by shade:
+ <select ng-model="color" ng-options="c.name group by c.shade for c in colors">
+ </select><br/>
+
+
+ Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>
+ <hr/>
+ Currently selected: {{ {selected_color:color} }}
+ <div style="border:solid 1px black; height:20px"
+ ng-style="{'background-color':color.name}">
+ </div>
+ </div>
+ </doc:source>
+ <doc:scenario>
+ it('should check ng-options', function() {
+ expect(binding('{selected_color:color}')).toMatch('red');
+ select('color').option('0');
+ expect(binding('{selected_color:color}')).toMatch('black');
+ using('.nullable').select('color').option('');
+ expect(binding('{selected_color:color}')).toMatch('null');
+ });
+ </doc:scenario>
+ </doc:example>
+ */
+
+var ngOptionsDirective = valueFn({ terminal: true });
+var selectDirective = ['$compile', '$parse', function($compile, $parse) {
+ //0000111110000000000022220000000000000000000000333300000000000000444444444444444440000000005555555555555555500000006666666666666666600000000000000007777000000000000000000088888
+ var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/,
+ nullModelCtrl = {$setViewValue: noop};
+
+ return {
+ restrict: 'E',
+ require: ['select', '?ngModel'],
+ controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
+ var self = this,
+ optionsMap = {},
+ ngModelCtrl = nullModelCtrl,
+ nullOption,
+ unknownOption;
+
+
+ self.databound = $attrs.ngModel;
+
+
+ self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
+ ngModelCtrl = ngModelCtrl_;
+ nullOption = nullOption_;
+ unknownOption = unknownOption_;
+ }
+
+
+ self.addOption = function(value) {
+ optionsMap[value] = true;
+
+ if (ngModelCtrl.$viewValue == value) {
+ $element.val(value);
+ if (unknownOption.parent()) unknownOption.remove();
+ }
+ };
+
+
+ self.removeOption = function(value) {
+ if (this.hasOption(value)) {
+ delete optionsMap[value];
+ if (ngModelCtrl.$viewValue == value) {
+ this.renderUnknownOption(value);
+ }
+ }
+ };
+
+
+ self.renderUnknownOption = function(val) {
+ var unknownVal = '? ' + hashKey(val) + ' ?';
+ unknownOption.val(unknownVal);
+ $element.prepend(unknownOption);
+ $element.val(unknownVal);
+ unknownOption.prop('selected', true); // needed for IE
+ }
+
+
+ self.hasOption = function(value) {
+ return optionsMap.hasOwnProperty(value);
+ }
+
+ $scope.$on('$destroy', function() {
+ // disable unknown option so that we don't do work when the whole select is being destroyed
+ self.renderUnknownOption = noop;
+ });
+ }],
+
+ link: function(scope, element, attr, ctrls) {
+ // if ngModel is not defined, we don't need to do anything
+ if (!ctrls[1]) return;
+
+ var selectCtrl = ctrls[0],
+ ngModelCtrl = ctrls[1],
+ multiple = attr.multiple,
+ optionsExp = attr.ngOptions,
+ nullOption = false, // if false, user will not be able to select it (used by ngOptions)
+ emptyOption,
+ // we can't just jqLite('<option>') since jqLite is not smart enough
+ // to create it in <select> and IE barfs otherwise.
+ optionTemplate = jqLite(document.createElement('option')),
+ optGroupTemplate =jqLite(document.createElement('optgroup')),
+ unknownOption = optionTemplate.clone();
+
+ // find "null" option
+ for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
+ if (children[i].value == '') {
+ emptyOption = nullOption = children.eq(i);
+ break;
+ }
+ }
+
+ selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
+
+ // required validator
+ if (multiple && (attr.required || attr.ngRequired)) {
+ var requiredValidator = function(value) {
+ ngModelCtrl.$setValidity('required', !attr.required || (value && value.length));
+ return value;
+ };
+
+ ngModelCtrl.$parsers.push(requiredValidator);
+ ngModelCtrl.$formatters.unshift(requiredValidator);
+
+ attr.$observe('required', function() {
+ requiredValidator(ngModelCtrl.$viewValue);
+ });
+ }
+
+ if (optionsExp) Options(scope, element, ngModelCtrl);
+ else if (multiple) Multiple(scope, element, ngModelCtrl);
+ else Single(scope, element, ngModelCtrl, selectCtrl);
+
+
+ ////////////////////////////
+
+
+
+ function Single(scope, selectElement, ngModelCtrl, selectCtrl) {
+ ngModelCtrl.$render = function() {
+ var viewValue = ngModelCtrl.$viewValue;
+
+ if (selectCtrl.hasOption(viewValue)) {
+ if (unknownOption.parent()) unknownOption.remove();
+ selectElement.val(viewValue);
+ if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
+ } else {
+ if (isUndefined(viewValue) && emptyOption) {
+ selectElement.val('');
+ } else {
+ selectCtrl.renderUnknownOption(viewValue);
+ }
+ }
+ };
+
+ selectElement.bind('change', function() {
+ scope.$apply(function() {
+ if (unknownOption.parent()) unknownOption.remove();
+ ngModelCtrl.$setViewValue(selectElement.val());
+ });
+ });
+ }
+
+ function Multiple(scope, selectElement, ctrl) {
+ var lastView;
+ ctrl.$render = function() {
+ var items = new HashMap(ctrl.$viewValue);
+ forEach(selectElement.find('option'), function(option) {
+ option.selected = isDefined(items.get(option.value));
+ });
+ };
+
+ // we have to do it on each watch since ngModel watches reference, but
+ // we need to work of an array, so we need to see if anything was inserted/removed
+ scope.$watch(function selectMultipleWatch() {
+ if (!equals(lastView, ctrl.$viewValue)) {
+ lastView = copy(ctrl.$viewValue);
+ ctrl.$render();
+ }
+ });
+
+ selectElement.bind('change', function() {
+ scope.$apply(function() {
+ var array = [];
+ forEach(selectElement.find('option'), function(option) {
+ if (option.selected) {
+ array.push(option.value);
+ }
+ });
+ ctrl.$setViewValue(array);
+ });
+ });
+ }
+
+ function Options(scope, selectElement, ctrl) {
+ var match;
+
+ if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
+ throw Error(
+ "Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_ (track by _expr_)?'" +
+ " but got '" + optionsExp + "'.");
+ }
+
+ var displayFn = $parse(match[2] || match[1]),
+ valueName = match[4] || match[6],
+ keyName = match[5],
+ groupByFn = $parse(match[3] || ''),
+ valueFn = $parse(match[2] ? match[1] : valueName),
+ valuesFn = $parse(match[7]),
+ track = match[8],
+ trackFn = track ? $parse(match[8]) : null,
+ // This is an array of array of existing option groups in DOM. We try to reuse these if possible
+ // optionGroupsCache[0] is the options with no option group
+ // optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
+ optionGroupsCache = [[{element: selectElement, label:''}]];
+
+ if (nullOption) {
+ // compile the element since there might be bindings in it
+ $compile(nullOption)(scope);
+
+ // remove the class, which is added automatically because we recompile the element and it
+ // becomes the compilation root
+ nullOption.removeClass('ng-scope');
+
+ // we need to remove it before calling selectElement.html('') because otherwise IE will
+ // remove the label from the element. wtf?
+ nullOption.remove();
+ }
+
+ // clear contents, we'll add what's needed based on the model
+ selectElement.html('');
+
+ selectElement.bind('change', function() {
+ scope.$apply(function() {
+ var optionGroup,
+ collection = valuesFn(scope) || [],
+ locals = {},
+ key, value, optionElement, index, groupIndex, length, groupLength;
+
+ if (multiple) {
+ value = [];
+ for (groupIndex = 0, groupLength = optionGroupsCache.length;
+ groupIndex < groupLength;
+ groupIndex++) {
+ // list of options for that group. (first item has the parent)
+ optionGroup = optionGroupsCache[groupIndex];
+
+ for(index = 1, length = optionGroup.length; index < length; index++) {
+ if ((optionElement = optionGroup[index].element)[0].selected) {
+ key = optionElement.val();
+ if (keyName) locals[keyName] = key;
+ if (trackFn) {
+ for (var trackIndex = 0; trackIndex < collection.length; trackIndex++) {
+ locals[valueName] = collection[trackIndex];
+ if (trackFn(scope, locals) == key) break;
+ }
+ } else {
+ locals[valueName] = collection[key];
+ }
+ value.push(valueFn(scope, locals));
+ }
+ }
+ }
+ } else {
+ key = selectElement.val();
+ if (key == '?') {
+ value = undefined;
+ } else if (key == ''){
+ value = null;
+ } else {
+ if (trackFn) {
+ for (var trackIndex = 0; trackIndex < collection.length; trackIndex++) {
+ locals[valueName] = collection[trackIndex];
+ if (trackFn(scope, locals) == key) {
+ value = valueFn(scope, locals);
+ break;
+ }
+ }
+ } else {
+ locals[valueName] = collection[key];
+ if (keyName) locals[keyName] = key;
+ value = valueFn(scope, locals);
+ }
+ }
+ }
+ ctrl.$setViewValue(value);
+ });
+ });
+
+ ctrl.$render = render;
+
+ // TODO(vojta): can't we optimize this ?
+ scope.$watch(render);
+
+ function render() {
+ var optionGroups = {'':[]}, // Temporary location for the option groups before we render them
+ optionGroupNames = [''],
+ optionGroupName,
+ optionGroup,
+ option,
+ existingParent, existingOptions, existingOption,
+ modelValue = ctrl.$modelValue,
+ values = valuesFn(scope) || [],
+ keys = keyName ? sortedKeys(values) : values,
+ groupLength, length,
+ groupIndex, index,
+ locals = {},
+ selected,
+ selectedSet = false, // nothing is selected yet
+ lastElement,
+ element,
+ label;
+
+ if (multiple) {
+ if (trackFn && isArray(modelValue)) {
+ selectedSet = new HashMap([]);
+ for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) {
+ locals[valueName] = modelValue[trackIndex];
+ selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]);
+ }
+ } else {
+ selectedSet = new HashMap(modelValue);
+ }
+ }
+
+ // We now build up the list of options we need (we merge later)
+ for (index = 0; length = keys.length, index < length; index++) {
+ locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index];
+ optionGroupName = groupByFn(scope, locals) || '';
+ if (!(optionGroup = optionGroups[optionGroupName])) {
+ optionGroup = optionGroups[optionGroupName] = [];
+ optionGroupNames.push(optionGroupName);
+ }
+ if (multiple) {
+ selected = selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals)) != undefined;
+ } else {
+ if (trackFn) {
+ var modelCast = {};
+ modelCast[valueName] = modelValue;
+ selected = trackFn(scope, modelCast) === trackFn(scope, locals);
+ } else {
+ selected = modelValue === valueFn(scope, locals);
+ }
+ selectedSet = selectedSet || selected; // see if at least one item is selected
+ }
+ label = displayFn(scope, locals); // what will be seen by the user
+ label = label === undefined ? '' : label; // doing displayFn(scope, locals) || '' overwrites zero values
+ optionGroup.push({
+ id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index), // either the index into array or key from object
+ label: label,
+ selected: selected // determine if we should be selected
+ });
+ }
+ if (!multiple) {
+ if (nullOption || modelValue === null) {
+ // insert null option if we have a placeholder, or the model is null
+ optionGroups[''].unshift({id:'', label:'', selected:!selectedSet});
+ } else if (!selectedSet) {
+ // option could not be found, we have to insert the undefined item
+ optionGroups[''].unshift({id:'?', label:'', selected:true});
+ }
+ }
+
+ // Now we need to update the list of DOM nodes to match the optionGroups we computed above
+ for (groupIndex = 0, groupLength = optionGroupNames.length;
+ groupIndex < groupLength;
+ groupIndex++) {
+ // current option group name or '' if no group
+ optionGroupName = optionGroupNames[groupIndex];
+
+ // list of options for that group. (first item has the parent)
+ optionGroup = optionGroups[optionGroupName];
+
+ if (optionGroupsCache.length <= groupIndex) {
+ // we need to grow the optionGroups
+ existingParent = {
+ element: optGroupTemplate.clone().attr('label', optionGroupName),
+ label: optionGroup.label
+ };
+ existingOptions = [existingParent];
+ optionGroupsCache.push(existingOptions);
+ selectElement.append(existingParent.element);
+ } else {
+ existingOptions = optionGroupsCache[groupIndex];
+ existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
+
+ // update the OPTGROUP label if not the same.
+ if (existingParent.label != optionGroupName) {
+ existingParent.element.attr('label', existingParent.label = optionGroupName);
+ }
+ }
+
+ lastElement = null; // start at the beginning
+ for(index = 0, length = optionGroup.length; index < length; index++) {
+ option = optionGroup[index];
+ if ((existingOption = existingOptions[index+1])) {
+ // reuse elements
+ lastElement = existingOption.element;
+ if (existingOption.label !== option.label) {
+ lastElement.text(existingOption.label = option.label);
+ }
+ if (existingOption.id !== option.id) {
+ lastElement.val(existingOption.id = option.id);
+ }
+ // lastElement.prop('selected') provided by jQuery has side-effects
+ if (lastElement[0].selected !== option.selected) {
+ lastElement.prop('selected', (existingOption.selected = option.selected));
+ }
+ } else {
+ // grow elements
+
+ // if it's a null option
+ if (option.id === '' && nullOption) {
+ // put back the pre-compiled element
+ element = nullOption;
+ } else {
+ // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
+ // in this version of jQuery on some browser the .text() returns a string
+ // rather then the element.
+ (element = optionTemplate.clone())
+ .val(option.id)
+ .attr('selected', option.selected)
+ .text(option.label);
+ }
+
+ existingOptions.push(existingOption = {
+ element: element,
+ label: option.label,
+ id: option.id,
+ selected: option.selected
+ });
+ if (lastElement) {
+ lastElement.after(element);
+ } else {
+ existingParent.element.append(element);
+ }
+ lastElement = element;
+ }
+ }
+ // remove any excessive OPTIONs in a group
+ index++; // increment since the existingOptions[0] is parent element not OPTION
+ while(existingOptions.length > index) {
+ existingOptions.pop().element.remove();
+ }
+ }
+ // remove any excessive OPTGROUPs from select
+ while(optionGroupsCache.length > groupIndex) {
+ optionGroupsCache.pop()[0].element.remove();
+ }
+ }
+ }
+ }
+ }
+}];
+
+var optionDirective = ['$interpolate', function($interpolate) {
+ var nullSelectCtrl = {
+ addOption: noop,
+ removeOption: noop
+ };
+
+ return {
+ restrict: 'E',
+ priority: 100,
+ compile: function(element, attr) {
+ if (isUndefined(attr.value)) {
+ var interpolateFn = $interpolate(element.text(), true);
+ if (!interpolateFn) {
+ attr.$set('value', element.text());
+ }
+ }
+
+ return function (scope, element, attr) {
+ var selectCtrlName = '$selectController',
+ parent = element.parent(),
+ selectCtrl = parent.data(selectCtrlName) ||
+ parent.parent().data(selectCtrlName); // in case we are in optgroup
+
+ if (selectCtrl && selectCtrl.databound) {
+ // For some reason Opera defaults to true and if not overridden this messes up the repeater.
+ // We don't want the view to drive the initialization of the model anyway.
+ element.prop('selected', false);
+ } else {
+ selectCtrl = nullSelectCtrl;
+ }
+
+ if (interpolateFn) {
+ scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
+ attr.$set('value', newVal);
+ if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
+ selectCtrl.addOption(newVal);
+ });
+ } else {
+ selectCtrl.addOption(attr.value);
+ }
+
+ element.bind('$destroy', function() {
+ selectCtrl.removeOption(attr.value);
+ });
+ };
+ }
+ }
+}];
+
+var styleDirective = valueFn({
+ restrict: 'E',
+ terminal: true
+});
+
+ //try to bind to jquery now so that one can write angular.element().read()
+ //but we will rebind on bootstrap again.
+ bindJQuery();
+
+ publishExternalAPI(angular);
+
+ jqLite(document).ready(function() {
+ angularInit(document, bootstrap);
+ });
+
+})(window, document);
+angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak{display:none;}ng\\:form{display:block;}</style>');
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/angular-1.1.5.min.js b/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/angular-1.1.5.min.js
new file mode 100644
index 0000000..ac033dc
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/angular-1.1.5.min.js
@@ -0,0 +1,178 @@
+/*
+ AngularJS v1.1.5
+ (c) 2010-2012 Google, Inc. http://angularjs.org
+ License: MIT
+*/
+(function(M,T,p){'use strict';function lc(){var b=M.angular;M.angular=mc;return b}function Xa(b){return!b||typeof b.length!=="number"?!1:typeof b.hasOwnProperty!="function"&&typeof b.constructor!="function"?!0:b instanceof R||ga&&b instanceof ga||Ea.call(b)!=="[object Object]"||typeof b.callee==="function"}function n(b,a,c){var d;if(b)if(H(b))for(d in b)d!="prototype"&&d!="length"&&d!="name"&&b.hasOwnProperty(d)&&a.call(c,b[d],d);else if(b.forEach&&b.forEach!==n)b.forEach(a,c);else if(Xa(b))for(d=
+0;d<b.length;d++)a.call(c,b[d],d);else for(d in b)b.hasOwnProperty(d)&&a.call(c,b[d],d);return b}function qb(b){var a=[],c;for(c in b)b.hasOwnProperty(c)&&a.push(c);return a.sort()}function nc(b,a,c){for(var d=qb(b),e=0;e<d.length;e++)a.call(c,b[d[e]],d[e]);return d}function rb(b){return function(a,c){b(c,a)}}function Fa(){for(var b=ba.length,a;b;){b--;a=ba[b].charCodeAt(0);if(a==57)return ba[b]="A",ba.join("");if(a==90)ba[b]="0";else return ba[b]=String.fromCharCode(a+1),ba.join("")}ba.unshift("0");
+return ba.join("")}function sb(b,a){a?b.$$hashKey=a:delete b.$$hashKey}function t(b){var a=b.$$hashKey;n(arguments,function(a){a!==b&&n(a,function(a,c){b[c]=a})});sb(b,a);return b}function N(b){return parseInt(b,10)}function tb(b,a){return t(new (t(function(){},{prototype:b})),a)}function q(){}function qa(b){return b}function S(b){return function(){return b}}function C(b){return typeof b=="undefined"}function B(b){return typeof b!="undefined"}function L(b){return b!=null&&typeof b=="object"}function E(b){return typeof b==
+"string"}function Ya(b){return typeof b=="number"}function ra(b){return Ea.apply(b)=="[object Date]"}function F(b){return Ea.apply(b)=="[object Array]"}function H(b){return typeof b=="function"}function sa(b){return b&&b.document&&b.location&&b.alert&&b.setInterval}function U(b){return E(b)?b.replace(/^\s*/,"").replace(/\s*$/,""):b}function oc(b){return b&&(b.nodeName||b.bind&&b.find)}function Za(b,a,c){var d=[];n(b,function(b,g,i){d.push(a.call(c,b,g,i))});return d}function Ga(b,a){if(b.indexOf)return b.indexOf(a);
+for(var c=0;c<b.length;c++)if(a===b[c])return c;return-1}function ta(b,a){var c=Ga(b,a);c>=0&&b.splice(c,1);return a}function V(b,a){if(sa(b)||b&&b.$evalAsync&&b.$watch)throw Error("Can't copy Window or Scope");if(a){if(b===a)throw Error("Can't copy equivalent objects or arrays");if(F(b))for(var c=a.length=0;c<b.length;c++)a.push(V(b[c]));else{c=a.$$hashKey;n(a,function(b,c){delete a[c]});for(var d in b)a[d]=V(b[d]);sb(a,c)}}else(a=b)&&(F(b)?a=V(b,[]):ra(b)?a=new Date(b.getTime()):L(b)&&(a=V(b,{})));
+return a}function pc(b,a){var a=a||{},c;for(c in b)b.hasOwnProperty(c)&&c.substr(0,2)!=="$$"&&(a[c]=b[c]);return a}function ia(b,a){if(b===a)return!0;if(b===null||a===null)return!1;if(b!==b&&a!==a)return!0;var c=typeof b,d;if(c==typeof a&&c=="object")if(F(b)){if((c=b.length)==a.length){for(d=0;d<c;d++)if(!ia(b[d],a[d]))return!1;return!0}}else if(ra(b))return ra(a)&&b.getTime()==a.getTime();else{if(b&&b.$evalAsync&&b.$watch||a&&a.$evalAsync&&a.$watch||sa(b)||sa(a))return!1;c={};for(d in b)if(!(d.charAt(0)===
+"$"||H(b[d]))){if(!ia(b[d],a[d]))return!1;c[d]=!0}for(d in a)if(!c[d]&&d.charAt(0)!=="$"&&a[d]!==p&&!H(a[d]))return!1;return!0}return!1}function $a(b,a){var c=arguments.length>2?ka.call(arguments,2):[];return H(a)&&!(a instanceof RegExp)?c.length?function(){return arguments.length?a.apply(b,c.concat(ka.call(arguments,0))):a.apply(b,c)}:function(){return arguments.length?a.apply(b,arguments):a.call(b)}:a}function qc(b,a){var c=a;/^\$+/.test(b)?c=p:sa(a)?c="$WINDOW":a&&T===a?c="$DOCUMENT":a&&a.$evalAsync&&
+a.$watch&&(c="$SCOPE");return c}function ha(b,a){return JSON.stringify(b,qc,a?" ":null)}function ub(b){return E(b)?JSON.parse(b):b}function ua(b){b&&b.length!==0?(b=I(""+b),b=!(b=="f"||b=="0"||b=="false"||b=="no"||b=="n"||b=="[]")):b=!1;return b}function va(b){b=w(b).clone();try{b.html("")}catch(a){}var c=w("<div>").append(b).html();try{return b[0].nodeType===3?I(c):c.match(/^(<[^>]+>)/)[1].replace(/^<([\w\-]+)/,function(a,b){return"<"+I(b)})}catch(d){return I(c)}}function vb(b){var a={},c,d;n((b||
+"").split("&"),function(b){b&&(c=b.split("="),d=decodeURIComponent(c[0]),a[d]=B(c[1])?decodeURIComponent(c[1]):!0)});return a}function wb(b){var a=[];n(b,function(b,d){a.push(wa(d,!0)+(b===!0?"":"="+wa(b,!0)))});return a.length?a.join("&"):""}function ab(b){return wa(b,!0).replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+")}function wa(b,a){return encodeURIComponent(b).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,a?"%20":"+")}function rc(b,
+a){function c(a){a&&d.push(a)}var d=[b],e,g,i=["ng:app","ng-app","x-ng-app","data-ng-app"],f=/\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;n(i,function(a){i[a]=!0;c(T.getElementById(a));a=a.replace(":","\\:");b.querySelectorAll&&(n(b.querySelectorAll("."+a),c),n(b.querySelectorAll("."+a+"\\:"),c),n(b.querySelectorAll("["+a+"]"),c))});n(d,function(a){if(!e){var b=f.exec(" "+a.className+" ");b?(e=a,g=(b[2]||"").replace(/\s+/g,",")):n(a.attributes,function(b){if(!e&&i[b.name])e=a,g=b.value})}});e&&a(e,g?[g]:[])}
+function xb(b,a){var c=function(){b=w(b);a=a||[];a.unshift(["$provide",function(a){a.value("$rootElement",b)}]);a.unshift("ng");var c=yb(a);c.invoke(["$rootScope","$rootElement","$compile","$injector","$animator",function(a,b,c,d,e){a.$apply(function(){b.data("$injector",d);c(b)(a)});e.enabled(!0)}]);return c},d=/^NG_DEFER_BOOTSTRAP!/;if(M&&!d.test(M.name))return c();M.name=M.name.replace(d,"");Ha.resumeBootstrap=function(b){n(b,function(b){a.push(b)});c()}}function bb(b,a){a=a||"_";return b.replace(sc,
+function(b,d){return(d?a:"")+b.toLowerCase()})}function cb(b,a,c){if(!b)throw Error("Argument '"+(a||"?")+"' is "+(c||"required"));return b}function xa(b,a,c){c&&F(b)&&(b=b[b.length-1]);cb(H(b),a,"not a function, got "+(b&&typeof b=="object"?b.constructor.name||"Object":typeof b));return b}function tc(b){function a(a,b,e){return a[b]||(a[b]=e())}return a(a(b,"angular",Object),"module",function(){var b={};return function(d,e,g){e&&b.hasOwnProperty(d)&&(b[d]=null);return a(b,d,function(){function a(c,
+d,e){return function(){b[e||"push"]([c,d,arguments]);return m}}if(!e)throw Error("No module: "+d);var b=[],c=[],j=a("$injector","invoke"),m={_invokeQueue:b,_runBlocks:c,requires:e,name:d,provider:a("$provide","provider"),factory:a("$provide","factory"),service:a("$provide","service"),value:a("$provide","value"),constant:a("$provide","constant","unshift"),animation:a("$animationProvider","register"),filter:a("$filterProvider","register"),controller:a("$controllerProvider","register"),directive:a("$compileProvider",
+"directive"),config:j,run:function(a){c.push(a);return this}};g&&j(g);return m})}})}function Ia(b){return b.replace(uc,function(a,b,d,e){return e?d.toUpperCase():d}).replace(vc,"Moz$1")}function db(b,a){function c(){var e;for(var b=[this],c=a,i,f,h,j,m,k;b.length;){i=b.shift();f=0;for(h=i.length;f<h;f++){j=w(i[f]);c?j.triggerHandler("$destroy"):c=!c;m=0;for(e=(k=j.children()).length,j=e;m<j;m++)b.push(ga(k[m]))}}return d.apply(this,arguments)}var d=ga.fn[b],d=d.$original||d;c.$original=d;ga.fn[b]=
+c}function R(b){if(b instanceof R)return b;if(!(this instanceof R)){if(E(b)&&b.charAt(0)!="<")throw Error("selectors not implemented");return new R(b)}if(E(b)){var a=T.createElement("div");a.innerHTML="<div> </div>"+b;a.removeChild(a.firstChild);eb(this,a.childNodes);this.remove()}else eb(this,b)}function fb(b){return b.cloneNode(!0)}function ya(b){zb(b);for(var a=0,b=b.childNodes||[];a<b.length;a++)ya(b[a])}function Ab(b,a,c){var d=ca(b,"events");ca(b,"handle")&&(C(a)?n(d,function(a,c){gb(b,
+c,a);delete d[c]}):C(c)?(gb(b,a,d[a]),delete d[a]):ta(d[a],c))}function zb(b){var a=b[Ja],c=Ka[a];c&&(c.handle&&(c.events.$destroy&&c.handle({},"$destroy"),Ab(b)),delete Ka[a],b[Ja]=p)}function ca(b,a,c){var d=b[Ja],d=Ka[d||-1];if(B(c))d||(b[Ja]=d=++wc,d=Ka[d]={}),d[a]=c;else return d&&d[a]}function Bb(b,a,c){var d=ca(b,"data"),e=B(c),g=!e&&B(a),i=g&&!L(a);!d&&!i&&ca(b,"data",d={});if(e)d[a]=c;else if(g)if(i)return d&&d[a];else t(d,a);else return d}function La(b,a){return(" "+b.className+" ").replace(/[\n\t]/g,
+" ").indexOf(" "+a+" ")>-1}function Cb(b,a){a&&n(a.split(" "),function(a){b.className=U((" "+b.className+" ").replace(/[\n\t]/g," ").replace(" "+U(a)+" "," "))})}function Db(b,a){a&&n(a.split(" "),function(a){if(!La(b,a))b.className=U(b.className+" "+U(a))})}function eb(b,a){if(a)for(var a=!a.nodeName&&B(a.length)&&!sa(a)?a:[a],c=0;c<a.length;c++)b.push(a[c])}function Eb(b,a){return Ma(b,"$"+(a||"ngController")+"Controller")}function Ma(b,a,c){b=w(b);for(b[0].nodeType==9&&(b=b.find("html"));b.length;){if(c=
+b.data(a))return c;b=b.parent()}}function Fb(b,a){var c=Na[a.toLowerCase()];return c&&Gb[b.nodeName]&&c}function xc(b,a){var c=function(c,e){if(!c.preventDefault)c.preventDefault=function(){c.returnValue=!1};if(!c.stopPropagation)c.stopPropagation=function(){c.cancelBubble=!0};if(!c.target)c.target=c.srcElement||T;if(C(c.defaultPrevented)){var g=c.preventDefault;c.preventDefault=function(){c.defaultPrevented=!0;g.call(c)};c.defaultPrevented=!1}c.isDefaultPrevented=function(){return c.defaultPrevented||
+c.returnValue==!1};n(a[e||c.type],function(a){a.call(b,c)});Z<=8?(c.preventDefault=null,c.stopPropagation=null,c.isDefaultPrevented=null):(delete c.preventDefault,delete c.stopPropagation,delete c.isDefaultPrevented)};c.elem=b;return c}function la(b){var a=typeof b,c;if(a=="object"&&b!==null)if(typeof(c=b.$$hashKey)=="function")c=b.$$hashKey();else{if(c===p)c=b.$$hashKey=Fa()}else c=b;return a+":"+c}function za(b){n(b,this.put,this)}function Hb(b){var a,c;if(typeof b=="function"){if(!(a=b.$inject))a=
+[],c=b.toString().replace(yc,""),c=c.match(zc),n(c[1].split(Ac),function(b){b.replace(Bc,function(b,c,d){a.push(d)})}),b.$inject=a}else F(b)?(c=b.length-1,xa(b[c],"fn"),a=b.slice(0,c)):xa(b,"fn",!0);return a}function yb(b){function a(a){return function(b,c){if(L(b))n(b,rb(a));else return a(b,c)}}function c(a,b){if(H(b)||F(b))b=k.instantiate(b);if(!b.$get)throw Error("Provider "+a+" must define $get factory method.");return m[a+f]=b}function d(a,b){return c(a,{$get:b})}function e(a){var b=[];n(a,function(a){if(!j.get(a))if(j.put(a,
+!0),E(a)){var c=Aa(a);b=b.concat(e(c.requires)).concat(c._runBlocks);try{for(var d=c._invokeQueue,c=0,f=d.length;c<f;c++){var g=d[c],o=k.get(g[0]);o[g[1]].apply(o,g[2])}}catch(h){throw h.message&&(h.message+=" from "+a),h;}}else if(H(a))try{b.push(k.invoke(a))}catch(l){throw l.message&&(l.message+=" from "+a),l;}else if(F(a))try{b.push(k.invoke(a))}catch(i){throw i.message&&(i.message+=" from "+String(a[a.length-1])),i;}else xa(a,"module")});return b}function g(a,b){function c(d){if(typeof d!=="string")throw Error("Service name expected");
+if(a.hasOwnProperty(d)){if(a[d]===i)throw Error("Circular dependency: "+h.join(" <- "));return a[d]}else try{return h.unshift(d),a[d]=i,a[d]=b(d)}finally{h.shift()}}function d(a,b,e){var f=[],j=Hb(a),g,o,h;o=0;for(g=j.length;o<g;o++)h=j[o],f.push(e&&e.hasOwnProperty(h)?e[h]:c(h));a.$inject||(a=a[g]);switch(b?-1:f.length){case 0:return a();case 1:return a(f[0]);case 2:return a(f[0],f[1]);case 3:return a(f[0],f[1],f[2]);case 4:return a(f[0],f[1],f[2],f[3]);case 5:return a(f[0],f[1],f[2],f[3],f[4]);
+case 6:return a(f[0],f[1],f[2],f[3],f[4],f[5]);case 7:return a(f[0],f[1],f[2],f[3],f[4],f[5],f[6]);case 8:return a(f[0],f[1],f[2],f[3],f[4],f[5],f[6],f[7]);case 9:return a(f[0],f[1],f[2],f[3],f[4],f[5],f[6],f[7],f[8]);case 10:return a(f[0],f[1],f[2],f[3],f[4],f[5],f[6],f[7],f[8],f[9]);default:return a.apply(b,f)}}return{invoke:d,instantiate:function(a,b){var c=function(){},e;c.prototype=(F(a)?a[a.length-1]:a).prototype;c=new c;e=d(a,c,b);return L(e)?e:c},get:c,annotate:Hb,has:function(b){return m.hasOwnProperty(b+
+f)||a.hasOwnProperty(b)}}}var i={},f="Provider",h=[],j=new za,m={$provide:{provider:a(c),factory:a(d),service:a(function(a,b){return d(a,["$injector",function(a){return a.instantiate(b)}])}),value:a(function(a,b){return d(a,S(b))}),constant:a(function(a,b){m[a]=b;l[a]=b}),decorator:function(a,b){var c=k.get(a+f),d=c.$get;c.$get=function(){var a=u.invoke(d,c);return u.invoke(b,null,{$delegate:a})}}}},k=m.$injector=g(m,function(){throw Error("Unknown provider: "+h.join(" <- "));}),l={},u=l.$injector=
+g(l,function(a){a=k.get(a+f);return u.invoke(a.$get,a)});n(e(b),function(a){u.invoke(a||q)});return u}function Cc(){var b=!0;this.disableAutoScrolling=function(){b=!1};this.$get=["$window","$location","$rootScope",function(a,c,d){function e(a){var b=null;n(a,function(a){!b&&I(a.nodeName)==="a"&&(b=a)});return b}function g(){var b=c.hash(),d;b?(d=i.getElementById(b))?d.scrollIntoView():(d=e(i.getElementsByName(b)))?d.scrollIntoView():b==="top"&&a.scrollTo(0,0):a.scrollTo(0,0)}var i=a.document;b&&d.$watch(function(){return c.hash()},
+function(){d.$evalAsync(g)});return g}]}function Ib(b){this.register=function(a,c){b.factory(Ia(a)+"Animation",c)};this.$get=["$injector",function(a){return function(b){if(b&&(b=Ia(b)+"Animation",a.has(b)))return a.get(b)}}]}function Dc(b,a,c,d){function e(a){try{a.apply(null,ka.call(arguments,1))}finally{if(o--,o===0)for(;z.length;)try{z.pop()()}catch(b){c.error(b)}}}function g(a,b){(function s(){n(r,function(a){a()});y=b(s,a)})()}function i(){x!=f.url()&&(x=f.url(),n(v,function(a){a(f.url())}))}
+var f=this,h=a[0],j=b.location,m=b.history,k=b.setTimeout,l=b.clearTimeout,u={};f.isMock=!1;var o=0,z=[];f.$$completeOutstandingRequest=e;f.$$incOutstandingRequestCount=function(){o++};f.notifyWhenNoOutstandingRequests=function(a){n(r,function(a){a()});o===0?a():z.push(a)};var r=[],y;f.addPollFn=function(a){C(y)&&g(100,k);r.push(a);return a};var x=j.href,W=a.find("base");f.url=function(a,b){if(a){if(x!=a)return x=a,d.history?b?m.replaceState(null,"",a):(m.pushState(null,"",a),W.attr("href",W.attr("href"))):
+b?j.replace(a):j.href=a,f}else return j.href.replace(/%27/g,"'")};var v=[],A=!1;f.onUrlChange=function(a){A||(d.history&&w(b).bind("popstate",i),d.hashchange?w(b).bind("hashchange",i):f.addPollFn(i),A=!0);v.push(a);return a};f.baseHref=function(){var a=W.attr("href");return a?a.replace(/^https?\:\/\/[^\/]*/,""):""};var G={},D="",$=f.baseHref();f.cookies=function(a,b){var d,e,f,j;if(a)if(b===p)h.cookie=escape(a)+"=;path="+$+";expires=Thu, 01 Jan 1970 00:00:00 GMT";else{if(E(b))d=(h.cookie=escape(a)+
+"="+escape(b)+";path="+$).length+1,d>4096&&c.warn("Cookie '"+a+"' possibly not set or overflowed because it was too large ("+d+" > 4096 bytes)!")}else{if(h.cookie!==D){D=h.cookie;d=D.split("; ");G={};for(f=0;f<d.length;f++)e=d[f],j=e.indexOf("="),j>0&&(a=unescape(e.substring(0,j)),G[a]===p&&(G[a]=unescape(e.substring(j+1))))}return G}};f.defer=function(a,b){var c;o++;c=k(function(){delete u[c];e(a)},b||0);u[c]=!0;return c};f.defer.cancel=function(a){return u[a]?(delete u[a],l(a),e(q),!0):!1}}function Ec(){this.$get=
+["$window","$log","$sniffer","$document",function(b,a,c,d){return new Dc(b,d,a,c)}]}function Fc(){this.$get=function(){function b(b,d){function e(a){if(a!=k){if(l){if(l==a)l=a.n}else l=a;g(a.n,a.p);g(a,k);k=a;k.n=null}}function g(a,b){if(a!=b){if(a)a.p=b;if(b)b.n=a}}if(b in a)throw Error("cacheId "+b+" taken");var i=0,f=t({},d,{id:b}),h={},j=d&&d.capacity||Number.MAX_VALUE,m={},k=null,l=null;return a[b]={put:function(a,b){var c=m[a]||(m[a]={key:a});e(c);if(!C(b))return a in h||i++,h[a]=b,i>j&&this.remove(l.key),
+b},get:function(a){var b=m[a];if(b)return e(b),h[a]},remove:function(a){var b=m[a];if(b){if(b==k)k=b.p;if(b==l)l=b.n;g(b.n,b.p);delete m[a];delete h[a];i--}},removeAll:function(){h={};i=0;m={};k=l=null},destroy:function(){m=f=h=null;delete a[b]},info:function(){return t({},f,{size:i})}}}var a={};b.info=function(){var b={};n(a,function(a,e){b[e]=a.info()});return b};b.get=function(b){return a[b]};return b}}function Gc(){this.$get=["$cacheFactory",function(b){return b("templates")}]}function Jb(b){var a=
+{},c="Directive",d=/^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,e=/(([\d\w\-_]+)(?:\:([^;]+))?;?)/,g="Template must have exactly one root element. was: ",i=/^\s*(https?|ftp|mailto|file):/;this.directive=function h(d,e){E(d)?(cb(e,"directive"),a.hasOwnProperty(d)||(a[d]=[],b.factory(d+c,["$injector","$exceptionHandler",function(b,c){var e=[];n(a[d],function(a){try{var g=b.invoke(a);if(H(g))g={compile:S(g)};else if(!g.compile&&g.link)g.compile=S(g.link);g.priority=g.priority||0;g.name=g.name||d;g.require=
+g.require||g.controller&&g.name;g.restrict=g.restrict||"A";e.push(g)}catch(h){c(h)}});return e}])),a[d].push(e)):n(d,rb(h));return this};this.urlSanitizationWhitelist=function(a){return B(a)?(i=a,this):i};this.$get=["$injector","$interpolate","$exceptionHandler","$http","$templateCache","$parse","$controller","$rootScope","$document",function(b,j,m,k,l,u,o,z,r){function y(a,b,c){a instanceof w||(a=w(a));n(a,function(b,c){b.nodeType==3&&b.nodeValue.match(/\S+/)&&(a[c]=w(b).wrap("<span></span>").parent()[0])});
+var d=W(a,b,a,c);return function(b,c){cb(b,"scope");for(var e=c?Ba.clone.call(a):a,j=0,g=e.length;j<g;j++){var h=e[j];(h.nodeType==1||h.nodeType==9)&&e.eq(j).data("$scope",b)}x(e,"ng-scope");c&&c(e,b);d&&d(b,e,e);return e}}function x(a,b){try{a.addClass(b)}catch(c){}}function W(a,b,c,d){function e(a,c,d,g){var h,i,k,l,o,m,u,z=[];o=0;for(m=c.length;o<m;o++)z.push(c[o]);u=o=0;for(m=j.length;o<m;u++)i=z[u],c=j[o++],h=j[o++],c?(c.scope?(k=a.$new(L(c.scope)),w(i).data("$scope",k)):k=a,(l=c.transclude)||
+!g&&b?c(h,k,i,d,function(b){return function(c){var d=a.$new();d.$$transcluded=!0;return b(d,c).bind("$destroy",$a(d,d.$destroy))}}(l||b)):c(h,k,i,p,g)):h&&h(a,i.childNodes,p,g)}for(var j=[],g,h,k,i=0;i<a.length;i++)h=new ma,g=v(a[i],[],h,d),h=(g=g.length?A(g,a[i],h,b,c):null)&&g.terminal||!a[i].childNodes||!a[i].childNodes.length?null:W(a[i].childNodes,g?g.transclude:b),j.push(g),j.push(h),k=k||g||h;return k?e:null}function v(a,b,c,j){var g=c.$attr,h;switch(a.nodeType){case 1:G(b,da(hb(a).toLowerCase()),
+"E",j);var i,k,l;h=a.attributes;for(var o=0,m=h&&h.length;o<m;o++)if(i=h[o],i.specified)k=i.name,l=da(k),Y.test(l)&&(k=l.substr(6).toLowerCase()),l=da(k.toLowerCase()),g[l]=k,c[l]=i=U(Z&&k=="href"?decodeURIComponent(a.getAttribute(k,2)):i.value),Fb(a,l)&&(c[l]=!0),s(a,b,i,l),G(b,l,"A",j);a=a.className;if(E(a)&&a!=="")for(;h=e.exec(a);)l=da(h[2]),G(b,l,"C",j)&&(c[l]=U(h[3])),a=a.substr(h.index+h[0].length);break;case 3:P(b,a.nodeValue);break;case 8:try{if(h=d.exec(a.nodeValue))l=da(h[1]),G(b,l,"M",
+j)&&(c[l]=U(h[2]))}catch(u){}}b.sort(K);return b}function A(a,b,c,d,e){function h(a,b){if(a)a.require=s.require,z.push(a);if(b)b.require=s.require,ea.push(b)}function i(a,b){var c,d="data",e=!1;if(E(a)){for(;(c=a.charAt(0))=="^"||c=="?";)a=a.substr(1),c=="^"&&(d="inheritedData"),e=e||c=="?";c=b[d]("$"+a+"Controller");if(!c&&!e)throw Error("No controller: "+a);}else F(a)&&(c=[],n(a,function(a){c.push(i(a,b))}));return c}function k(a,d,e,g,h){var l,v,r,D,x;l=b===e?c:pc(c,new ma(w(e),c.$attr));v=l.$$element;
+if(K){var y=/^\s*([@=&])(\??)\s*(\w*)\s*$/,s=d.$parent||d;n(K.scope,function(a,b){var c=a.match(y)||[],e=c[3]||b,g=c[2]=="?",c=c[1],h,k,i;d.$$isolateBindings[b]=c+e;switch(c){case "@":l.$observe(e,function(a){d[b]=a});l.$$observers[e].$$scope=s;l[e]&&(d[b]=j(l[e])(s));break;case "=":if(g&&!l[e])break;k=u(l[e]);i=k.assign||function(){h=d[b]=k(s);throw Error(Kb+l[e]+" (directive: "+K.name+")");};h=d[b]=k(s);d.$watch(function(){var a=k(s);a!==d[b]&&(a!==h?h=d[b]=a:i(s,a=h=d[b]));return a});break;case "&":k=
+u(l[e]);d[b]=function(a){return k(s,a)};break;default:throw Error("Invalid isolate scope definition for directive "+K.name+": "+a);}})}q&&n(q,function(a){var b={$scope:d,$element:v,$attrs:l,$transclude:h};x=a.controller;x=="@"&&(x=l[a.name]);v.data("$"+a.name+"Controller",o(x,b))});g=0;for(r=z.length;g<r;g++)try{D=z[g],D(d,v,l,D.require&&i(D.require,v))}catch(Hc){m(Hc,va(v))}a&&a(d,e.childNodes,p,h);g=0;for(r=ea.length;g<r;g++)try{D=ea[g],D(d,v,l,D.require&&i(D.require,v))}catch(J){m(J,va(v))}}for(var l=
+-Number.MAX_VALUE,z=[],ea=[],r=null,K=null,W=null,J=c.$$element=w(b),s,A,Y,G,P=d,q,na,t,B=0,C=a.length;B<C;B++){s=a[B];Y=p;if(l>s.priority)break;if(t=s.scope)O("isolated scope",K,s,J),L(t)&&(x(J,"ng-isolate-scope"),K=s),x(J,"ng-scope"),r=r||s;A=s.name;if(t=s.controller)q=q||{},O("'"+A+"' controller",q[A],s,J),q[A]=s;if(t=s.transclude)O("transclusion",G,s,J),G=s,l=s.priority,t=="element"?(Y=w(b),J=c.$$element=w(T.createComment(" "+A+": "+c[A]+" ")),b=J[0],ja(e,w(Y[0]),b),P=y(Y,d,l)):(Y=w(fb(b)).contents(),
+J.html(""),P=y(Y,d));if(s.template)if(O("template",W,s,J),W=s,t=H(s.template)?s.template(J,c):s.template,t=Lb(t),s.replace){Y=w("<div>"+U(t)+"</div>").contents();b=Y[0];if(Y.length!=1||b.nodeType!==1)throw Error(g+t);ja(e,J,b);A={$attr:{}};a=a.concat(v(b,a.splice(B+1,a.length-(B+1)),A));D(c,A);C=a.length}else J.html(t);if(s.templateUrl)O("template",W,s,J),W=s,k=$(a.splice(B,a.length-B),k,J,c,e,s.replace,P),C=a.length;else if(s.compile)try{na=s.compile(J,c,P),H(na)?h(null,na):na&&h(na.pre,na.post)}catch(I){m(I,
+va(J))}if(s.terminal)k.terminal=!0,l=Math.max(l,s.priority)}k.scope=r&&r.scope;k.transclude=G&&P;return k}function G(d,e,j,g){var l=!1;if(a.hasOwnProperty(e))for(var k,e=b.get(e+c),i=0,o=e.length;i<o;i++)try{if(k=e[i],(g===p||g>k.priority)&&k.restrict.indexOf(j)!=-1)d.push(k),l=!0}catch(u){m(u)}return l}function D(a,b){var c=b.$attr,d=a.$attr,e=a.$$element;n(a,function(d,e){e.charAt(0)!="$"&&(b[e]&&(d+=(e==="style"?";":" ")+b[e]),a.$set(e,d,!0,c[e]))});n(b,function(b,j){j=="class"?(x(e,b),a["class"]=
+(a["class"]?a["class"]+" ":"")+b):j=="style"?e.attr("style",e.attr("style")+";"+b):j.charAt(0)!="$"&&!a.hasOwnProperty(j)&&(a[j]=b,d[j]=c[j])})}function $(a,b,c,d,e,j,h){var i=[],o,m,u=c[0],z=a.shift(),r=t({},z,{controller:null,templateUrl:null,transclude:null,scope:null}),z=H(z.templateUrl)?z.templateUrl(c,d):z.templateUrl;c.html("");k.get(z,{cache:l}).success(function(l){var k,z,l=Lb(l);if(j){z=w("<div>"+U(l)+"</div>").contents();k=z[0];if(z.length!=1||k.nodeType!==1)throw Error(g+l);l={$attr:{}};
+ja(e,c,k);v(k,a,l);D(d,l)}else k=u,c.html(l);a.unshift(r);o=A(a,k,d,h);for(m=W(c[0].childNodes,h);i.length;){var ea=i.shift(),l=i.shift();z=i.shift();var x=i.shift(),y=k;l!==u&&(y=fb(k),ja(z,w(l),y));o(function(){b(m,ea,y,e,x)},ea,y,e,x)}i=null}).error(function(a,b,c,d){throw Error("Failed to load template: "+d.url);});return function(a,c,d,e,j){i?(i.push(c),i.push(d),i.push(e),i.push(j)):o(function(){b(m,c,d,e,j)},c,d,e,j)}}function K(a,b){return b.priority-a.priority}function O(a,b,c,d){if(b)throw Error("Multiple directives ["+
+b.name+", "+c.name+"] asking for "+a+" on: "+va(d));}function P(a,b){var c=j(b,!0);c&&a.push({priority:0,compile:S(function(a,b){var d=b.parent(),e=d.data("$binding")||[];e.push(c);x(d.data("$binding",e),"ng-binding");a.$watch(c,function(a){b[0].nodeValue=a})})})}function s(a,b,c,d){var e=j(c,!0);e&&b.push({priority:100,compile:S(function(a,b,c){b=c.$$observers||(c.$$observers={});if(e=j(c[d],!0))c[d]=e(a),(b[d]||(b[d]=[])).$$inter=!0,(c.$$observers&&c.$$observers[d].$$scope||a).$watch(e,function(a){c.$set(d,
+a)})})})}function ja(a,b,c){var d=b[0],e=d.parentNode,j,g;if(a){j=0;for(g=a.length;j<g;j++)if(a[j]==d){a[j]=c;break}}e&&e.replaceChild(c,d);c[w.expando]=d[w.expando];b[0]=c}var ma=function(a,b){this.$$element=a;this.$attr=b||{}};ma.prototype={$normalize:da,$set:function(a,b,c,d){var e=Fb(this.$$element[0],a),j=this.$$observers;e&&(this.$$element.prop(a,b),d=e);this[a]=b;d?this.$attr[a]=d:(d=this.$attr[a])||(this.$attr[a]=d=bb(a,"-"));if(hb(this.$$element[0])==="A"&&a==="href")q.setAttribute("href",
+b),e=q.href,e.match(i)||(this[a]=b="unsafe:"+e);c!==!1&&(b===null||b===p?this.$$element.removeAttr(d):this.$$element.attr(d,b));j&&n(j[a],function(a){try{a(b)}catch(c){m(c)}})},$observe:function(a,b){var c=this,d=c.$$observers||(c.$$observers={}),e=d[a]||(d[a]=[]);e.push(b);z.$evalAsync(function(){e.$$inter||b(c[a])});return b}};var q=r[0].createElement("a"),ea=j.startSymbol(),J=j.endSymbol(),Lb=ea=="{{"||J=="}}"?qa:function(a){return a.replace(/\{\{/g,ea).replace(/}}/g,J)},Y=/^ngAttr[A-Z]/;return y}]}
+function da(b){return Ia(b.replace(Ic,""))}function Jc(){var b={},a=/^(\S+)(\s+as\s+(\w+))?$/;this.register=function(a,d){L(a)?t(b,a):b[a]=d};this.$get=["$injector","$window",function(c,d){return function(e,g){var i,f;E(e)&&(f=e.match(a),i=f[1],f=f[3],e=b.hasOwnProperty(i)?b[i]:ib(g.$scope,i,!0)||ib(d,i,!0),xa(e,i,!0));i=c.instantiate(e,g);if(f){if(typeof g.$scope!=="object")throw Error('Can not export controller as "'+f+'". No scope object provided!');g.$scope[f]=i}return i}}]}function Kc(){this.$get=
+["$window",function(b){return w(b.document)}]}function Lc(){this.$get=["$log",function(b){return function(a,c){b.error.apply(b,arguments)}}]}function Mc(){var b="{{",a="}}";this.startSymbol=function(a){return a?(b=a,this):b};this.endSymbol=function(b){return b?(a=b,this):a};this.$get=["$parse","$exceptionHandler",function(c,d){function e(e,h){for(var j,m,k=0,l=[],u=e.length,o=!1,z=[];k<u;)(j=e.indexOf(b,k))!=-1&&(m=e.indexOf(a,j+g))!=-1?(k!=j&&l.push(e.substring(k,j)),l.push(k=c(o=e.substring(j+g,
+m))),k.exp=o,k=m+i,o=!0):(k!=u&&l.push(e.substring(k)),k=u);if(!(u=l.length))l.push(""),u=1;if(!h||o)return z.length=u,k=function(a){try{for(var b=0,c=u,j;b<c;b++){if(typeof(j=l[b])=="function")j=j(a),j==null||j==p?j="":typeof j!="string"&&(j=ha(j));z[b]=j}return z.join("")}catch(g){d(Error("Error while interpolating: "+e+"\n"+g.toString()))}},k.exp=e,k.parts=l,k}var g=b.length,i=a.length;e.startSymbol=function(){return b};e.endSymbol=function(){return a};return e}]}function Mb(b){for(var b=b.split("/"),
+a=b.length;a--;)b[a]=ab(b[a]);return b.join("/")}function Nb(b,a){var c=jb.exec(b);a.$$protocol=c[1];a.$$host=c[3];a.$$port=N(c[5])||Oa[c[1]]||null}function Ob(b,a){var c=Pb.exec(b);a.$$path=decodeURIComponent(c[1]);a.$$search=vb(c[3]);a.$$hash=decodeURIComponent(c[5]||"");if(a.$$path&&a.$$path.charAt(0)!="/")a.$$path="/"+a.$$path}function fa(b,a,c){return a.indexOf(b)==0?a.substr(b.length):c}function Ca(b){var a=b.indexOf("#");return a==-1?b:b.substr(0,a)}function kb(b){return b.substr(0,Ca(b).lastIndexOf("/")+
+1)}function Qb(b,a){var a=a||"",c=kb(b);this.$$parse=function(a){var b={};Nb(a,b);var g=fa(c,a);if(!E(g))throw Error('Invalid url "'+a+'", missing path prefix "'+c+'".');Ob(g,b);t(this,b);if(!this.$$path)this.$$path="/";this.$$compose()};this.$$compose=function(){var a=wb(this.$$search),b=this.$$hash?"#"+ab(this.$$hash):"";this.$$url=Mb(this.$$path)+(a?"?"+a:"")+b;this.$$absUrl=c+this.$$url.substr(1)};this.$$rewrite=function(d){var e;if((e=fa(b,d))!==p)return d=e,(e=fa(a,e))!==p?c+(fa("/",e)||e):
+b+d;else if((e=fa(c,d))!==p)return c+e;else if(c==d+"/")return c}}function lb(b,a){var c=kb(b);this.$$parse=function(d){Nb(d,this);var e=fa(b,d)||fa(c,d);if(!E(e))throw Error('Invalid url "'+d+'", does not start with "'+b+'".');e=e.charAt(0)=="#"?fa(a,e):e;if(!E(e))throw Error('Invalid url "'+d+'", missing hash prefix "'+a+'".');Ob(e,this);this.$$compose()};this.$$compose=function(){var c=wb(this.$$search),e=this.$$hash?"#"+ab(this.$$hash):"";this.$$url=Mb(this.$$path)+(c?"?"+c:"")+e;this.$$absUrl=
+b+(this.$$url?a+this.$$url:"")};this.$$rewrite=function(a){if(Ca(b)==Ca(a))return a}}function Rb(b,a){lb.apply(this,arguments);var c=kb(b);this.$$rewrite=function(d){var e;if(b==Ca(d))return d;else if(e=fa(c,d))return b+a+e;else if(c===d+"/")return c}}function Pa(b){return function(){return this[b]}}function Sb(b,a){return function(c){if(C(c))return this[b];this[b]=a(c);this.$$compose();return this}}function Nc(){var b="",a=!1;this.hashPrefix=function(a){return B(a)?(b=a,this):b};this.html5Mode=function(b){return B(b)?
+(a=b,this):a};this.$get=["$rootScope","$browser","$sniffer","$rootElement",function(c,d,e,g){function i(a){c.$broadcast("$locationChangeSuccess",f.absUrl(),a)}var f,h=d.baseHref(),j=d.url();a?(h=h?j.substring(0,j.indexOf("/",j.indexOf("//")+2))+h:j,e=e.history?Qb:Rb):(h=Ca(j),e=lb);f=new e(h,"#"+b);f.$$parse(f.$$rewrite(j));g.bind("click",function(a){if(!a.ctrlKey&&!(a.metaKey||a.which==2)){for(var b=w(a.target);I(b[0].nodeName)!=="a";)if(b[0]===g[0]||!(b=b.parent())[0])return;var e=b.prop("href"),
+j=f.$$rewrite(e);e&&!b.attr("target")&&j&&!a.isDefaultPrevented()&&(a.preventDefault(),j!=d.url()&&(f.$$parse(j),c.$apply(),M.angular["ff-684208-preventDefault"]=!0))}});f.absUrl()!=j&&d.url(f.absUrl(),!0);d.onUrlChange(function(a){f.absUrl()!=a&&(c.$broadcast("$locationChangeStart",a,f.absUrl()).defaultPrevented?d.url(f.absUrl()):(c.$evalAsync(function(){var b=f.absUrl();f.$$parse(a);i(b)}),c.$$phase||c.$digest()))});var m=0;c.$watch(function(){var a=d.url(),b=f.$$replace;if(!m||a!=f.absUrl())m++,
+c.$evalAsync(function(){c.$broadcast("$locationChangeStart",f.absUrl(),a).defaultPrevented?f.$$parse(a):(d.url(f.absUrl(),b),i(a))});f.$$replace=!1;return m});return f}]}function Oc(){var b=!0,a=this;this.debugEnabled=function(a){return B(a)?(b=a,this):b};this.$get=["$window",function(c){function d(a){a instanceof Error&&(a.stack?a=a.message&&a.stack.indexOf(a.message)===-1?"Error: "+a.message+"\n"+a.stack:a.stack:a.sourceURL&&(a=a.message+"\n"+a.sourceURL+":"+a.line));return a}function e(a){var b=
+c.console||{},e=b[a]||b.log||q;return e.apply?function(){var a=[];n(arguments,function(b){a.push(d(b))});return e.apply(b,a)}:function(a,b){e(a,b)}}return{log:e("log"),warn:e("warn"),info:e("info"),error:e("error"),debug:function(){var c=e("debug");return function(){b&&c.apply(a,arguments)}}()}}]}function Pc(b,a){function c(a){return a.indexOf(r)!=-1}function d(a){a=a||1;return o+a<b.length?b.charAt(o+a):!1}function e(a){return"0"<=a&&a<="9"}function g(a){return a==" "||a=="\r"||a=="\t"||a=="\n"||
+a=="\u000b"||a=="\u00a0"}function i(a){return"a"<=a&&a<="z"||"A"<=a&&a<="Z"||"_"==a||a=="$"}function f(a){return a=="-"||a=="+"||e(a)}function h(a,c,d){d=d||o;throw Error("Lexer Error: "+a+" at column"+(B(c)?"s "+c+"-"+o+" ["+b.substring(c,d)+"]":" "+d)+" in expression ["+b+"].");}function j(){for(var a="",c=o;o<b.length;){var j=I(b.charAt(o));if(j=="."||e(j))a+=j;else{var g=d();if(j=="e"&&f(g))a+=j;else if(f(j)&&g&&e(g)&&a.charAt(a.length-1)=="e")a+=j;else if(f(j)&&(!g||!e(g))&&a.charAt(a.length-
+1)=="e")h("Invalid exponent");else break}o++}a*=1;l.push({index:c,text:a,json:!0,fn:function(){return a}})}function m(){for(var c="",d=o,f,j,h,k;o<b.length;){k=b.charAt(o);if(k=="."||i(k)||e(k))k=="."&&(f=o),c+=k;else break;o++}if(f)for(j=o;j<b.length;){k=b.charAt(j);if(k=="("){h=c.substr(f-d+1);c=c.substr(0,f-d);o=j;break}if(g(k))j++;else break}d={index:d,text:c};if(Da.hasOwnProperty(c))d.fn=d.json=Da[c];else{var m=Tb(c,a);d.fn=t(function(a,b){return m(a,b)},{assign:function(a,b){return Ub(a,c,b)}})}l.push(d);
+h&&(l.push({index:f,text:".",json:!1}),l.push({index:f+1,text:h,json:!1}))}function k(a){var c=o;o++;for(var d="",e=a,f=!1;o<b.length;){var j=b.charAt(o);e+=j;if(f)j=="u"?(j=b.substring(o+1,o+5),j.match(/[\da-f]{4}/i)||h("Invalid unicode escape [\\u"+j+"]"),o+=4,d+=String.fromCharCode(parseInt(j,16))):(f=Qc[j],d+=f?f:j),f=!1;else if(j=="\\")f=!0;else if(j==a){o++;l.push({index:c,text:e,string:d,json:!0,fn:function(){return d}});return}else d+=j;o++}h("Unterminated quote",c)}for(var l=[],u,o=0,z=[],
+r,y=":";o<b.length;){r=b.charAt(o);if(c("\"'"))k(r);else if(e(r)||c(".")&&e(d()))j();else if(i(r)){if(m(),"{,".indexOf(y)!=-1&&z[0]=="{"&&(u=l[l.length-1]))u.json=u.text.indexOf(".")==-1}else if(c("(){}[].,;:?"))l.push({index:o,text:r,json:":[,".indexOf(y)!=-1&&c("{[")||c("}]:,")}),c("{[")&&z.unshift(r),c("}]")&&z.shift(),o++;else if(g(r)){o++;continue}else{var x=r+d(),n=x+d(2),v=Da[r],A=Da[x],G=Da[n];G?(l.push({index:o,text:n,fn:G}),o+=3):A?(l.push({index:o,text:x,fn:A}),o+=2):v?(l.push({index:o,
+text:r,fn:v,json:"[,:".indexOf(y)!=-1&&c("+-")}),o+=1):h("Unexpected next character ",o,o+1)}y=r}return l}function Rc(b,a,c,d){function e(a,c){throw Error("Syntax Error: Token '"+c.text+"' "+a+" at column "+(c.index+1)+" of the expression ["+b+"] starting at ["+b.substring(c.index)+"].");}function g(){if(O.length===0)throw Error("Unexpected end of expression: "+b);return O[0]}function i(a,b,c,d){if(O.length>0){var e=O[0],f=e.text;if(f==a||f==b||f==c||f==d||!a&&!b&&!c&&!d)return e}return!1}function f(b,
+c,d,f){return(b=i(b,c,d,f))?(a&&!b.json&&e("is not valid json",b),O.shift(),b):!1}function h(a){f(a)||e("is unexpected, expecting ["+a+"]",i())}function j(a,b){return t(function(c,d){return a(c,d,b)},{constant:b.constant})}function m(a,b,c){return t(function(d,e){return a(d,e)?b(d,e):c(d,e)},{constant:a.constant&&b.constant&&c.constant})}function k(a,b,c){return t(function(d,e){return b(d,e,a,c)},{constant:a.constant&&c.constant})}function l(){for(var a=[];;)if(O.length>0&&!i("}",")",";","]")&&a.push(w()),
+!f(";"))return a.length==1?a[0]:function(b,c){for(var d,e=0;e<a.length;e++){var f=a[e];f&&(d=f(b,c))}return d}}function u(){for(var a=f(),b=c(a.text),d=[];;)if(a=f(":"))d.push(P());else{var e=function(a,c,e){for(var e=[e],f=0;f<d.length;f++)e.push(d[f](a,c));return b.apply(a,e)};return function(){return e}}}function o(){var a=z(),b,c;if(f("?"))if(b=o(),c=f(":"))return m(a,b,o());else e("expected :",c);else return a}function z(){for(var a=r(),b;;)if(b=f("||"))a=k(a,b.fn,r());else return a}function r(){var a=
+y(),b;if(b=f("&&"))a=k(a,b.fn,r());return a}function y(){var a=x(),b;if(b=f("==","!=","===","!=="))a=k(a,b.fn,y());return a}function x(){var a;a=n();for(var b;b=f("+","-");)a=k(a,b.fn,n());if(b=f("<",">","<=",">="))a=k(a,b.fn,x());return a}function n(){for(var a=v(),b;b=f("*","/","%");)a=k(a,b.fn,v());return a}function v(){var a;return f("+")?A():(a=f("-"))?k($,a.fn,v()):(a=f("!"))?j(a.fn,v()):A()}function A(){var a;if(f("("))a=w(),h(")");else if(f("["))a=G();else if(f("{"))a=D();else{var b=f();(a=
+b.fn)||e("not a primary expression",b);if(b.json)a.constant=a.literal=!0}for(var c;b=f("(","[",".");)b.text==="("?(a=s(a,c),c=null):b.text==="["?(c=a,a=ma(a)):b.text==="."?(c=a,a=ja(a)):e("IMPOSSIBLE");return a}function G(){var a=[],b=!0;if(g().text!="]"){do{var c=P();a.push(c);c.constant||(b=!1)}while(f(","))}h("]");return t(function(b,c){for(var d=[],e=0;e<a.length;e++)d.push(a[e](b,c));return d},{literal:!0,constant:b})}function D(){var a=[],b=!0;if(g().text!="}"){do{var c=f(),c=c.string||c.text;
+h(":");var d=P();a.push({key:c,value:d});d.constant||(b=!1)}while(f(","))}h("}");return t(function(b,c){for(var d={},e=0;e<a.length;e++){var f=a[e];d[f.key]=f.value(b,c)}return d},{literal:!0,constant:b})}var $=S(0),K,O=Pc(b,d),P=function(){var a=o(),c,d;return(d=f("="))?(a.assign||e("implies assignment but ["+b.substring(0,d.index)+"] can not be assigned to",d),c=o(),function(b,d){return a.assign(b,c(b,d),d)}):a},s=function(a,b){var c=[];if(g().text!=")"){do c.push(P());while(f(","))}h(")");return function(d,
+e){for(var f=[],j=b?b(d,e):d,g=0;g<c.length;g++)f.push(c[g](d,e));g=a(d,e,j)||q;return g.apply?g.apply(j,f):g(f[0],f[1],f[2],f[3],f[4])}},ja=function(a){var b=f().text,c=Tb(b,d);return t(function(b,d,e){return c(e||a(b,d),d)},{assign:function(c,d,e){return Ub(a(c,e),b,d)}})},ma=function(a){var b=P();h("]");return t(function(c,d){var e=a(c,d),f=b(c,d),j;if(!e)return p;if((e=e[f])&&e.then){j=e;if(!("$$v"in e))j.$$v=p,j.then(function(a){j.$$v=a});e=e.$$v}return e},{assign:function(c,d,e){return a(c,
+e)[b(c,e)]=d}})},w=function(){for(var a=P(),b;;)if(b=f("|"))a=k(a,b.fn,u());else return a};a?(P=z,s=ja=ma=w=function(){e("is not valid json",{text:b,index:0})},K=A()):K=l();O.length!==0&&e("is an unexpected token",O[0]);K.literal=!!K.literal;K.constant=!!K.constant;return K}function Ub(b,a,c){for(var a=a.split("."),d=0;a.length>1;d++){var e=a.shift(),g=b[e];g||(g={},b[e]=g);b=g}return b[a.shift()]=c}function ib(b,a,c){if(!a)return b;for(var a=a.split("."),d,e=b,g=a.length,i=0;i<g;i++)d=a[i],b&&(b=
+(e=b)[d]);return!c&&H(b)?$a(e,b):b}function Vb(b,a,c,d,e){return function(g,i){var f=i&&i.hasOwnProperty(b)?i:g,h;if(f===null||f===p)return f;if((f=f[b])&&f.then){if(!("$$v"in f))h=f,h.$$v=p,h.then(function(a){h.$$v=a});f=f.$$v}if(!a||f===null||f===p)return f;if((f=f[a])&&f.then){if(!("$$v"in f))h=f,h.$$v=p,h.then(function(a){h.$$v=a});f=f.$$v}if(!c||f===null||f===p)return f;if((f=f[c])&&f.then){if(!("$$v"in f))h=f,h.$$v=p,h.then(function(a){h.$$v=a});f=f.$$v}if(!d||f===null||f===p)return f;if((f=
+f[d])&&f.then){if(!("$$v"in f))h=f,h.$$v=p,h.then(function(a){h.$$v=a});f=f.$$v}if(!e||f===null||f===p)return f;if((f=f[e])&&f.then){if(!("$$v"in f))h=f,h.$$v=p,h.then(function(a){h.$$v=a});f=f.$$v}return f}}function Tb(b,a){if(mb.hasOwnProperty(b))return mb[b];var c=b.split("."),d=c.length,e;if(a)e=d<6?Vb(c[0],c[1],c[2],c[3],c[4]):function(a,b){var e=0,j;do j=Vb(c[e++],c[e++],c[e++],c[e++],c[e++])(a,b),b=p,a=j;while(e<d);return j};else{var g="var l, fn, p;\n";n(c,function(a,b){g+="if(s === null || s === undefined) return s;\nl=s;\ns="+
+(b?"s":'((k&&k.hasOwnProperty("'+a+'"))?k:s)')+'["'+a+'"];\nif (s && s.then) {\n if (!("$$v" in s)) {\n p=s;\n p.$$v = undefined;\n p.then(function(v) {p.$$v=v;});\n}\n s=s.$$v\n}\n'});g+="return s;";e=Function("s","k",g);e.toString=function(){return g}}return mb[b]=e}function Sc(){var b={};this.$get=["$filter","$sniffer",function(a,c){return function(d){switch(typeof d){case "string":return b.hasOwnProperty(d)?b[d]:b[d]=Rc(d,!1,a,c.csp);case "function":return d;default:return q}}}]}function Tc(){this.$get=
+["$rootScope","$exceptionHandler",function(b,a){return Uc(function(a){b.$evalAsync(a)},a)}]}function Uc(b,a){function c(a){return a}function d(a){return i(a)}var e=function(){var f=[],h,j;return j={resolve:function(a){if(f){var c=f;f=p;h=g(a);c.length&&b(function(){for(var a,b=0,d=c.length;b<d;b++)a=c[b],h.then(a[0],a[1])})}},reject:function(a){j.resolve(i(a))},promise:{then:function(b,j){var g=e(),i=function(d){try{g.resolve((b||c)(d))}catch(e){a(e),g.reject(e)}},o=function(b){try{g.resolve((j||
+d)(b))}catch(c){a(c),g.reject(c)}};f?f.push([i,o]):h.then(i,o);return g.promise},always:function(a){function b(a,c){var d=e();c?d.resolve(a):d.reject(a);return d.promise}function d(e,f){var j=null;try{j=(a||c)()}catch(g){return b(g,!1)}return j&&j.then?j.then(function(){return b(e,f)},function(a){return b(a,!1)}):b(e,f)}return this.then(function(a){return d(a,!0)},function(a){return d(a,!1)})}}}},g=function(a){return a&&a.then?a:{then:function(c){var d=e();b(function(){d.resolve(c(a))});return d.promise}}},
+i=function(a){return{then:function(c,j){var g=e();b(function(){g.resolve((j||d)(a))});return g.promise}}};return{defer:e,reject:i,when:function(f,h,j){var m=e(),k,l=function(b){try{return(h||c)(b)}catch(d){return a(d),i(d)}},u=function(b){try{return(j||d)(b)}catch(c){return a(c),i(c)}};b(function(){g(f).then(function(a){k||(k=!0,m.resolve(g(a).then(l,u)))},function(a){k||(k=!0,m.resolve(u(a)))})});return m.promise},all:function(a){var b=e(),c=0,d=F(a)?[]:{};n(a,function(a,e){c++;g(a).then(function(a){d.hasOwnProperty(e)||
+(d[e]=a,--c||b.resolve(d))},function(a){d.hasOwnProperty(e)||b.reject(a)})});c===0&&b.resolve(d);return b.promise}}}function Vc(){var b={};this.when=function(a,c){b[a]=t({reloadOnSearch:!0,caseInsensitiveMatch:!1},c);if(a){var d=a[a.length-1]=="/"?a.substr(0,a.length-1):a+"/";b[d]={redirectTo:a}}return this};this.otherwise=function(a){this.when(null,a);return this};this.$get=["$rootScope","$location","$routeParams","$q","$injector","$http","$templateCache",function(a,c,d,e,g,i,f){function h(a,b,c){for(var b=
+"^"+b.replace(/[-\/\\^$:*+?.()|[\]{}]/g,"\\$&")+"$",d="",e=[],f={},j=/\\([:*])(\w+)/g,g,i=0;(g=j.exec(b))!==null;){d+=b.slice(i,g.index);switch(g[1]){case ":":d+="([^\\/]*)";break;case "*":d+="(.*)"}e.push(g[2]);i=j.lastIndex}d+=b.substr(i);var h=a.match(RegExp(d,c.caseInsensitiveMatch?"i":""));h&&n(e,function(a,b){f[a]=h[b+1]});return h?f:null}function j(){var b=m(),j=u.current;if(b&&j&&b.$$route===j.$$route&&ia(b.pathParams,j.pathParams)&&!b.reloadOnSearch&&!l)j.params=b.params,V(j.params,d),a.$broadcast("$routeUpdate",
+j);else if(b||j)l=!1,a.$broadcast("$routeChangeStart",b,j),(u.current=b)&&b.redirectTo&&(E(b.redirectTo)?c.path(k(b.redirectTo,b.params)).search(b.params).replace():c.url(b.redirectTo(b.pathParams,c.path(),c.search())).replace()),e.when(b).then(function(){if(b){var a=t({},b.resolve),c;n(a,function(b,c){a[c]=E(b)?g.get(b):g.invoke(b)});if(B(c=b.template))H(c)&&(c=c(b.params));else if(B(c=b.templateUrl))if(H(c)&&(c=c(b.params)),B(c))b.loadedTemplateUrl=c,c=i.get(c,{cache:f}).then(function(a){return a.data});
+B(c)&&(a.$template=c);return e.all(a)}}).then(function(c){if(b==u.current){if(b)b.locals=c,V(b.params,d);a.$broadcast("$routeChangeSuccess",b,j)}},function(c){b==u.current&&a.$broadcast("$routeChangeError",b,j,c)})}function m(){var a,d;n(b,function(b,e){if(!d&&(a=h(c.path(),e,b)))d=tb(b,{params:t({},c.search(),a),pathParams:a}),d.$$route=b});return d||b[null]&&tb(b[null],{params:{},pathParams:{}})}function k(a,b){var c=[];n((a||"").split(":"),function(a,d){if(d==0)c.push(a);else{var e=a.match(/(\w+)(.*)/),
+f=e[1];c.push(b[f]);c.push(e[2]||"");delete b[f]}});return c.join("")}var l=!1,u={routes:b,reload:function(){l=!0;a.$evalAsync(j)}};a.$on("$locationChangeSuccess",j);return u}]}function Wc(){this.$get=S({})}function Xc(){var b=10;this.digestTtl=function(a){arguments.length&&(b=a);return b};this.$get=["$injector","$exceptionHandler","$parse",function(a,c,d){function e(){this.$id=Fa();this.$$phase=this.$parent=this.$$watchers=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=null;
+this["this"]=this.$root=this;this.$$destroyed=!1;this.$$asyncQueue=[];this.$$listeners={};this.$$isolateBindings={}}function g(a){if(h.$$phase)throw Error(h.$$phase+" already in progress");h.$$phase=a}function i(a,b){var c=d(a);xa(c,b);return c}function f(){}e.prototype={$new:function(a){if(H(a))throw Error("API-CHANGE: Use $controller to instantiate controllers.");a?(a=new e,a.$root=this.$root):(a=function(){},a.prototype=this,a=new a,a.$id=Fa());a["this"]=a;a.$$listeners={};a.$parent=this;a.$$watchers=
+a.$$nextSibling=a.$$childHead=a.$$childTail=null;a.$$prevSibling=this.$$childTail;this.$$childHead?this.$$childTail=this.$$childTail.$$nextSibling=a:this.$$childHead=this.$$childTail=a;return a},$watch:function(a,b,c){var d=i(a,"watch"),e=this.$$watchers,g={fn:b,last:f,get:d,exp:a,eq:!!c};if(!H(b)){var h=i(b||q,"listener");g.fn=function(a,b,c){h(c)}}if(typeof a=="string"&&d.constant){var r=g.fn;g.fn=function(a,b,c){r.call(this,a,b,c);ta(e,g)}}if(!e)e=this.$$watchers=[];e.unshift(g);return function(){ta(e,
+g)}},$watchCollection:function(a,b){var c=this,e,f,g=0,i=d(a),h=[],n={},x=0;return this.$watch(function(){f=i(c);var a,b;if(L(f))if(Xa(f)){if(e!==h)e=h,x=e.length=0,g++;a=f.length;if(x!==a)g++,e.length=x=a;for(b=0;b<a;b++)e[b]!==f[b]&&(g++,e[b]=f[b])}else{e!==n&&(e=n={},x=0,g++);a=0;for(b in f)f.hasOwnProperty(b)&&(a++,e.hasOwnProperty(b)?e[b]!==f[b]&&(g++,e[b]=f[b]):(x++,e[b]=f[b],g++));if(x>a)for(b in g++,e)e.hasOwnProperty(b)&&!f.hasOwnProperty(b)&&(x--,delete e[b])}else e!==f&&(e=f,g++);return g},
+function(){b(f,e,c)})},$digest:function(){var a,d,e,i,u=this.$$asyncQueue,o,z,r=b,n,x=[],p,v;g("$digest");do{z=!1;for(n=this;u.length;)try{n.$eval(u.shift())}catch(A){c(A)}do{if(i=n.$$watchers)for(o=i.length;o--;)try{if(a=i[o],(d=a.get(n))!==(e=a.last)&&!(a.eq?ia(d,e):typeof d=="number"&&typeof e=="number"&&isNaN(d)&&isNaN(e)))z=!0,a.last=a.eq?V(d):d,a.fn(d,e===f?d:e,n),r<5&&(p=4-r,x[p]||(x[p]=[]),v=H(a.exp)?"fn: "+(a.exp.name||a.exp.toString()):a.exp,v+="; newVal: "+ha(d)+"; oldVal: "+ha(e),x[p].push(v))}catch(G){c(G)}if(!(i=
+n.$$childHead||n!==this&&n.$$nextSibling))for(;n!==this&&!(i=n.$$nextSibling);)n=n.$parent}while(n=i);if(z&&!r--)throw h.$$phase=null,Error(b+" $digest() iterations reached. Aborting!\nWatchers fired in the last 5 iterations: "+ha(x));}while(z||u.length);h.$$phase=null},$destroy:function(){if(!(h==this||this.$$destroyed)){var a=this.$parent;this.$broadcast("$destroy");this.$$destroyed=!0;if(a.$$childHead==this)a.$$childHead=this.$$nextSibling;if(a.$$childTail==this)a.$$childTail=this.$$prevSibling;
+if(this.$$prevSibling)this.$$prevSibling.$$nextSibling=this.$$nextSibling;if(this.$$nextSibling)this.$$nextSibling.$$prevSibling=this.$$prevSibling;this.$parent=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=null}},$eval:function(a,b){return d(a)(this,b)},$evalAsync:function(a){this.$$asyncQueue.push(a)},$apply:function(a){try{return g("$apply"),this.$eval(a)}catch(b){c(b)}finally{h.$$phase=null;try{h.$digest()}catch(d){throw c(d),d;}}},$on:function(a,b){var c=this.$$listeners[a];
+c||(this.$$listeners[a]=c=[]);c.push(b);return function(){c[Ga(c,b)]=null}},$emit:function(a,b){var d=[],e,f=this,g=!1,i={name:a,targetScope:f,stopPropagation:function(){g=!0},preventDefault:function(){i.defaultPrevented=!0},defaultPrevented:!1},h=[i].concat(ka.call(arguments,1)),n,x;do{e=f.$$listeners[a]||d;i.currentScope=f;n=0;for(x=e.length;n<x;n++)if(e[n])try{if(e[n].apply(null,h),g)return i}catch(p){c(p)}else e.splice(n,1),n--,x--;f=f.$parent}while(f);return i},$broadcast:function(a,b){var d=
+this,e=this,f={name:a,targetScope:this,preventDefault:function(){f.defaultPrevented=!0},defaultPrevented:!1},g=[f].concat(ka.call(arguments,1)),i,h;do{d=e;f.currentScope=d;e=d.$$listeners[a]||[];i=0;for(h=e.length;i<h;i++)if(e[i])try{e[i].apply(null,g)}catch(n){c(n)}else e.splice(i,1),i--,h--;if(!(e=d.$$childHead||d!==this&&d.$$nextSibling))for(;d!==this&&!(e=d.$$nextSibling);)d=d.$parent}while(d=e);return f}};var h=new e;return h}]}function Yc(){this.$get=["$window","$document",function(b,a){var c=
+{},d=N((/android (\d+)/.exec(I((b.navigator||{}).userAgent))||[])[1]),e=a[0]||{},g,i=/^(Moz|webkit|O|ms)(?=[A-Z])/,f=e.body&&e.body.style,h=!1,j=!1;if(f){for(var m in f)if(h=i.exec(m)){g=h[0];g=g.substr(0,1).toUpperCase()+g.substr(1);break}h=!!("transition"in f||g+"Transition"in f);j=!!("animation"in f||g+"Animation"in f)}return{history:!(!b.history||!b.history.pushState||d<4),hashchange:"onhashchange"in b&&(!e.documentMode||e.documentMode>7),hasEvent:function(a){if(a=="input"&&Z==9)return!1;if(C(c[a])){var b=
+e.createElement("div");c[a]="on"+a in b}return c[a]},csp:e.securityPolicy?e.securityPolicy.isActive:!1,vendorPrefix:g,transitions:h,animations:j}}]}function Zc(){this.$get=S(M)}function Wb(b){var a={},c,d,e;if(!b)return a;n(b.split("\n"),function(b){e=b.indexOf(":");c=I(U(b.substr(0,e)));d=U(b.substr(e+1));c&&(a[c]?a[c]+=", "+d:a[c]=d)});return a}function $c(b,a){var c=ad.exec(b);if(c==null)return!0;var d={protocol:c[2],host:c[4],port:N(c[6])||Oa[c[2]]||null,relativeProtocol:c[2]===p||c[2]===""},
+c=jb.exec(a),c={protocol:c[1],host:c[3],port:N(c[5])||Oa[c[1]]||null};return(d.protocol==c.protocol||d.relativeProtocol)&&d.host==c.host&&(d.port==c.port||d.relativeProtocol&&c.port==Oa[c.protocol])}function Xb(b){var a=L(b)?b:p;return function(c){a||(a=Wb(b));return c?a[I(c)]||null:a}}function Yb(b,a,c){if(H(c))return c(b,a);n(c,function(c){b=c(b,a)});return b}function bd(){var b=/^\s*(\[|\{[^\{])/,a=/[\}\]]\s*$/,c=/^\)\]\}',?\n/,d={"Content-Type":"application/json;charset=utf-8"},e=this.defaults=
+{transformResponse:[function(d){E(d)&&(d=d.replace(c,""),b.test(d)&&a.test(d)&&(d=ub(d,!0)));return d}],transformRequest:[function(a){return L(a)&&Ea.apply(a)!=="[object File]"?ha(a):a}],headers:{common:{Accept:"application/json, text/plain, */*"},post:d,put:d,patch:d},xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN"},g=this.interceptors=[],i=this.responseInterceptors=[];this.$get=["$httpBackend","$browser","$cacheFactory","$rootScope","$q","$injector",function(a,b,c,d,k,l){function u(a){function c(a){var b=
+t({},a,{data:Yb(a.data,a.headers,d.transformResponse)});return 200<=a.status&&a.status<300?b:k.reject(b)}var d={transformRequest:e.transformRequest,transformResponse:e.transformResponse},f={};t(d,a);d.headers=f;d.method=oa(d.method);t(f,e.headers.common,e.headers[I(d.method)],a.headers);(a=$c(d.url,b.url())?b.cookies()[d.xsrfCookieName||e.xsrfCookieName]:p)&&(f[d.xsrfHeaderName||e.xsrfHeaderName]=a);var g=[function(a){var b=Yb(a.data,Xb(f),a.transformRequest);C(a.data)&&delete f["Content-Type"];if(C(a.withCredentials)&&
+!C(e.withCredentials))a.withCredentials=e.withCredentials;return o(a,b,f).then(c,c)},p],j=k.when(d);for(n(y,function(a){(a.request||a.requestError)&&g.unshift(a.request,a.requestError);(a.response||a.responseError)&&g.push(a.response,a.responseError)});g.length;)var a=g.shift(),i=g.shift(),j=j.then(a,i);j.success=function(a){j.then(function(b){a(b.data,b.status,b.headers,d)});return j};j.error=function(a){j.then(null,function(b){a(b.data,b.status,b.headers,d)});return j};return j}function o(b,c,g){function j(a,
+b,c){n&&(200<=a&&a<300?n.put(s,[a,b,Wb(c)]):n.remove(s));i(b,a,c);d.$$phase||d.$apply()}function i(a,c,d){c=Math.max(c,0);(200<=c&&c<300?l.resolve:l.reject)({data:a,status:c,headers:Xb(d),config:b})}function h(){var a=Ga(u.pendingRequests,b);a!==-1&&u.pendingRequests.splice(a,1)}var l=k.defer(),o=l.promise,n,p,s=z(b.url,b.params);u.pendingRequests.push(b);o.then(h,h);if((b.cache||e.cache)&&b.cache!==!1&&b.method=="GET")n=L(b.cache)?b.cache:L(e.cache)?e.cache:r;if(n)if(p=n.get(s))if(p.then)return p.then(h,
+h),p;else F(p)?i(p[1],p[0],V(p[2])):i(p,200,{});else n.put(s,o);p||a(b.method,s,c,j,g,b.timeout,b.withCredentials,b.responseType);return o}function z(a,b){if(!b)return a;var c=[];nc(b,function(a,b){a==null||a==p||(F(a)||(a=[a]),n(a,function(a){L(a)&&(a=ha(a));c.push(wa(b)+"="+wa(a))}))});return a+(a.indexOf("?")==-1?"?":"&")+c.join("&")}var r=c("$http"),y=[];n(g,function(a){y.unshift(E(a)?l.get(a):l.invoke(a))});n(i,function(a,b){var c=E(a)?l.get(a):l.invoke(a);y.splice(b,0,{response:function(a){return c(k.when(a))},
+responseError:function(a){return c(k.reject(a))}})});u.pendingRequests=[];(function(a){n(arguments,function(a){u[a]=function(b,c){return u(t(c||{},{method:a,url:b}))}})})("get","delete","head","jsonp");(function(a){n(arguments,function(a){u[a]=function(b,c,d){return u(t(d||{},{method:a,url:b,data:c}))}})})("post","put");u.defaults=e;return u}]}function cd(){this.$get=["$browser","$window","$document",function(b,a,c){return dd(b,ed,b.defer,a.angular.callbacks,c[0],a.location.protocol.replace(":",""))}]}
+function dd(b,a,c,d,e,g){function i(a,b){var c=e.createElement("script"),d=function(){e.body.removeChild(c);b&&b()};c.type="text/javascript";c.src=a;Z?c.onreadystatechange=function(){/loaded|complete/.test(c.readyState)&&d()}:c.onload=c.onerror=d;e.body.appendChild(c);return d}return function(e,h,j,m,k,l,u,o){function z(){p=-1;t&&t();v&&v.abort()}function r(a,d,e,f){var j=(h.match(jb)||["",g])[1];A&&c.cancel(A);t=v=null;d=j=="file"?e?200:404:d;a(d==1223?204:d,e,f);b.$$completeOutstandingRequest(q)}
+var p;b.$$incOutstandingRequestCount();h=h||b.url();if(I(e)=="jsonp"){var x="_"+(d.counter++).toString(36);d[x]=function(a){d[x].data=a};var t=i(h.replace("JSON_CALLBACK","angular.callbacks."+x),function(){d[x].data?r(m,200,d[x].data):r(m,p||-2);delete d[x]})}else{var v=new a;v.open(e,h,!0);n(k,function(a,b){a&&v.setRequestHeader(b,a)});v.onreadystatechange=function(){if(v.readyState==4){var a=v.getAllResponseHeaders(),b=["Cache-Control","Content-Language","Content-Type","Expires","Last-Modified",
+"Pragma"];a||(a="",n(b,function(b){var c=v.getResponseHeader(b);c&&(a+=b+": "+c+"\n")}));r(m,p||v.status,v.responseType?v.response:v.responseText,a)}};if(u)v.withCredentials=!0;if(o)v.responseType=o;v.send(j||"")}if(l>0)var A=c(z,l);else l&&l.then&&l.then(z)}}function fd(){this.$get=function(){return{id:"en-us",NUMBER_FORMATS:{DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{minInt:1,minFrac:0,maxFrac:3,posPre:"",posSuf:"",negPre:"-",negSuf:"",gSize:3,lgSize:3},{minInt:1,minFrac:2,maxFrac:2,posPre:"\u00a4",
+posSuf:"",negPre:"(\u00a4",negSuf:")",gSize:3,lgSize:3}],CURRENCY_SYM:"$"},DATETIME_FORMATS:{MONTH:"January,February,March,April,May,June,July,August,September,October,November,December".split(","),SHORTMONTH:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),DAY:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),SHORTDAY:"Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(","),AMPMS:["AM","PM"],medium:"MMM d, y h:mm:ss a","short":"M/d/yy h:mm a",fullDate:"EEEE, MMMM d, y",longDate:"MMMM d, y",
+mediumDate:"MMM d, y",shortDate:"M/d/yy",mediumTime:"h:mm:ss a",shortTime:"h:mm a"},pluralCat:function(b){return b===1?"one":"other"}}}}function gd(){this.$get=["$rootScope","$browser","$q","$exceptionHandler",function(b,a,c,d){function e(e,f,h){var j=c.defer(),m=j.promise,k=B(h)&&!h,f=a.defer(function(){try{j.resolve(e())}catch(a){j.reject(a),d(a)}k||b.$apply()},f),h=function(){delete g[m.$$timeoutId]};m.$$timeoutId=f;g[f]=j;m.then(h,h);return m}var g={};e.cancel=function(b){return b&&b.$$timeoutId in
+g?(g[b.$$timeoutId].reject("canceled"),a.defer.cancel(b.$$timeoutId)):!1};return e}]}function Zb(b){function a(a,e){return b.factory(a+c,e)}var c="Filter";this.register=a;this.$get=["$injector",function(a){return function(b){return a.get(b+c)}}];a("currency",$b);a("date",ac);a("filter",hd);a("json",id);a("limitTo",jd);a("lowercase",kd);a("number",bc);a("orderBy",cc);a("uppercase",ld)}function hd(){return function(b,a,c){if(!F(b))return b;var d=[];d.check=function(a){for(var b=0;b<d.length;b++)if(!d[b](a))return!1;
+return!0};switch(typeof c){case "function":break;case "boolean":if(c==!0){c=function(a,b){return Ha.equals(a,b)};break}default:c=function(a,b){b=(""+b).toLowerCase();return(""+a).toLowerCase().indexOf(b)>-1}}var e=function(a,b){if(typeof b=="string"&&b.charAt(0)==="!")return!e(a,b.substr(1));switch(typeof a){case "boolean":case "number":case "string":return c(a,b);case "object":switch(typeof b){case "object":return c(a,b);default:for(var d in a)if(d.charAt(0)!=="$"&&e(a[d],b))return!0}return!1;case "array":for(d=
+0;d<a.length;d++)if(e(a[d],b))return!0;return!1;default:return!1}};switch(typeof a){case "boolean":case "number":case "string":a={$:a};case "object":for(var g in a)g=="$"?function(){if(a[g]){var b=g;d.push(function(c){return e(c,a[b])})}}():function(){if(a[g]){var b=g;d.push(function(c){return e(ib(c,b),a[b])})}}();break;case "function":d.push(a);break;default:return b}for(var i=[],f=0;f<b.length;f++){var h=b[f];d.check(h)&&i.push(h)}return i}}function $b(b){var a=b.NUMBER_FORMATS;return function(b,
+d){if(C(d))d=a.CURRENCY_SYM;return dc(b,a.PATTERNS[1],a.GROUP_SEP,a.DECIMAL_SEP,2).replace(/\u00A4/g,d)}}function bc(b){var a=b.NUMBER_FORMATS;return function(b,d){return dc(b,a.PATTERNS[0],a.GROUP_SEP,a.DECIMAL_SEP,d)}}function dc(b,a,c,d,e){if(isNaN(b)||!isFinite(b))return"";var g=b<0,b=Math.abs(b),i=b+"",f="",h=[],j=!1;if(i.indexOf("e")!==-1){var m=i.match(/([\d\.]+)e(-?)(\d+)/);m&&m[2]=="-"&&m[3]>e+1?i="0":(f=i,j=!0)}if(!j){i=(i.split(ec)[1]||"").length;C(e)&&(e=Math.min(Math.max(a.minFrac,i),
+a.maxFrac));var i=Math.pow(10,e),b=Math.round(b*i)/i,b=(""+b).split(ec),i=b[0],b=b[1]||"",j=0,m=a.lgSize,k=a.gSize;if(i.length>=m+k)for(var j=i.length-m,l=0;l<j;l++)(j-l)%k===0&&l!==0&&(f+=c),f+=i.charAt(l);for(l=j;l<i.length;l++)(i.length-l)%m===0&&l!==0&&(f+=c),f+=i.charAt(l);for(;b.length<e;)b+="0";e&&e!=="0"&&(f+=d+b.substr(0,e))}h.push(g?a.negPre:a.posPre);h.push(f);h.push(g?a.negSuf:a.posSuf);return h.join("")}function nb(b,a,c){var d="";b<0&&(d="-",b=-b);for(b=""+b;b.length<a;)b="0"+b;c&&(b=
+b.substr(b.length-a));return d+b}function Q(b,a,c,d){c=c||0;return function(e){e=e["get"+b]();if(c>0||e>-c)e+=c;e===0&&c==-12&&(e=12);return nb(e,a,d)}}function Qa(b,a){return function(c,d){var e=c["get"+b](),g=oa(a?"SHORT"+b:b);return d[g][e]}}function ac(b){function a(a){var b;if(b=a.match(c)){var a=new Date(0),g=0,i=0,f=b[8]?a.setUTCFullYear:a.setFullYear,h=b[8]?a.setUTCHours:a.setHours;b[9]&&(g=N(b[9]+b[10]),i=N(b[9]+b[11]));f.call(a,N(b[1]),N(b[2])-1,N(b[3]));g=N(b[4]||0)-g;i=N(b[5]||0)-i;f=
+N(b[6]||0);b=Math.round(parseFloat("0."+(b[7]||0))*1E3);h.call(a,g,i,f,b)}return a}var c=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;return function(c,e){var g="",i=[],f,h,e=e||"mediumDate",e=b.DATETIME_FORMATS[e]||e;E(c)&&(c=md.test(c)?N(c):a(c));Ya(c)&&(c=new Date(c));if(!ra(c))return c;for(;e;)(h=nd.exec(e))?(i=i.concat(ka.call(h,1)),e=i.pop()):(i.push(e),e=null);n(i,function(a){f=od[a];g+=f?f(c,b.DATETIME_FORMATS):a.replace(/(^'|'$)/g,
+"").replace(/''/g,"'")});return g}}function id(){return function(b){return ha(b,!0)}}function jd(){return function(b,a){if(!F(b)&&!E(b))return b;a=N(a);if(E(b))return a?a>=0?b.slice(0,a):b.slice(a,b.length):"";var c=[],d,e;a>b.length?a=b.length:a<-b.length&&(a=-b.length);a>0?(d=0,e=a):(d=b.length+a,e=b.length);for(;d<e;d++)c.push(b[d]);return c}}function cc(b){return function(a,c,d){function e(a,b){return ua(b)?function(b,c){return a(c,b)}:a}if(!F(a))return a;if(!c)return a;for(var c=F(c)?c:[c],c=
+Za(c,function(a){var c=!1,d=a||qa;if(E(a)){if(a.charAt(0)=="+"||a.charAt(0)=="-")c=a.charAt(0)=="-",a=a.substring(1);d=b(a)}return e(function(a,b){var c;c=d(a);var e=d(b),f=typeof c,g=typeof e;f==g?(f=="string"&&(c=c.toLowerCase()),f=="string"&&(e=e.toLowerCase()),c=c===e?0:c<e?-1:1):c=f<g?-1:1;return c},c)}),g=[],i=0;i<a.length;i++)g.push(a[i]);return g.sort(e(function(a,b){for(var d=0;d<c.length;d++){var e=c[d](a,b);if(e!==0)return e}return 0},d))}}function aa(b){H(b)&&(b={link:b});b.restrict=b.restrict||
+"AC";return S(b)}function fc(b,a){function c(a,c){c=c?"-"+bb(c,"-"):"";b.removeClass((a?Ra:Sa)+c).addClass((a?Sa:Ra)+c)}var d=this,e=b.parent().controller("form")||Ta,g=0,i=d.$error={},f=[];d.$name=a.name;d.$dirty=!1;d.$pristine=!0;d.$valid=!0;d.$invalid=!1;e.$addControl(d);b.addClass(pa);c(!0);d.$addControl=function(a){f.push(a);a.$name&&!d.hasOwnProperty(a.$name)&&(d[a.$name]=a)};d.$removeControl=function(a){a.$name&&d[a.$name]===a&&delete d[a.$name];n(i,function(b,c){d.$setValidity(c,!0,a)});ta(f,
+a)};d.$setValidity=function(a,b,f){var k=i[a];if(b){if(k&&(ta(k,f),!k.length)){g--;if(!g)c(b),d.$valid=!0,d.$invalid=!1;i[a]=!1;c(!0,a);e.$setValidity(a,!0,d)}}else{g||c(b);if(k){if(Ga(k,f)!=-1)return}else i[a]=k=[],g++,c(!1,a),e.$setValidity(a,!1,d);k.push(f);d.$valid=!1;d.$invalid=!0}};d.$setDirty=function(){b.removeClass(pa).addClass(Ua);d.$dirty=!0;d.$pristine=!1;e.$setDirty()};d.$setPristine=function(){b.removeClass(Ua).addClass(pa);d.$dirty=!1;d.$pristine=!0;n(f,function(a){a.$setPristine()})}}
+function X(b){return C(b)||b===""||b===null||b!==b}function Va(b,a,c,d,e,g){var i=function(){var e=a.val();if(ua(c.ngTrim||"T"))e=U(e);d.$viewValue!==e&&b.$apply(function(){d.$setViewValue(e)})};if(e.hasEvent("input"))a.bind("input",i);else{var f,h=function(){f||(f=g.defer(function(){i();f=null}))};a.bind("keydown",function(a){a=a.keyCode;a===91||15<a&&a<19||37<=a&&a<=40||h()});a.bind("change",i);e.hasEvent("paste")&&a.bind("paste cut",h)}d.$render=function(){a.val(X(d.$viewValue)?"":d.$viewValue)};
+var j=c.ngPattern,m=function(a,b){return X(b)||a.test(b)?(d.$setValidity("pattern",!0),b):(d.$setValidity("pattern",!1),p)};j&&((e=j.match(/^\/(.*)\/([gim]*)$/))?(j=RegExp(e[1],e[2]),e=function(a){return m(j,a)}):e=function(a){var c=b.$eval(j);if(!c||!c.test)throw Error("Expected "+j+" to be a RegExp but was "+c);return m(c,a)},d.$formatters.push(e),d.$parsers.push(e));if(c.ngMinlength){var k=N(c.ngMinlength),e=function(a){return!X(a)&&a.length<k?(d.$setValidity("minlength",!1),p):(d.$setValidity("minlength",
+!0),a)};d.$parsers.push(e);d.$formatters.push(e)}if(c.ngMaxlength){var l=N(c.ngMaxlength),e=function(a){return!X(a)&&a.length>l?(d.$setValidity("maxlength",!1),p):(d.$setValidity("maxlength",!0),a)};d.$parsers.push(e);d.$formatters.push(e)}}function ob(b,a){b="ngClass"+b;return aa(function(c,d,e){function g(b){if(a===!0||c.$index%2===a)h&&!ia(b,h)&&i(h),f(b);h=V(b)}function i(a){L(a)&&!F(a)&&(a=Za(a,function(a,b){if(a)return b}));d.removeClass(F(a)?a.join(" "):a)}function f(a){L(a)&&!F(a)&&(a=Za(a,
+function(a,b){if(a)return b}));a&&d.addClass(F(a)?a.join(" "):a)}var h=p;c.$watch(e[b],g,!0);e.$observe("class",function(){var a=c.$eval(e[b]);g(a,a)});b!=="ngClass"&&c.$watch("$index",function(d,g){var h=d&1;h!==g&1&&(h===a?f(c.$eval(e[b])):i(c.$eval(e[b])))})})}var I=function(b){return E(b)?b.toLowerCase():b},oa=function(b){return E(b)?b.toUpperCase():b},Z=N((/msie (\d+)/.exec(I(navigator.userAgent))||[])[1]),w,ga,ka=[].slice,Wa=[].push,Ea=Object.prototype.toString,mc=M.angular,Ha=M.angular||(M.angular=
+{}),Aa,hb,ba=["0","0","0"];q.$inject=[];qa.$inject=[];hb=Z<9?function(b){b=b.nodeName?b:b[0];return b.scopeName&&b.scopeName!="HTML"?oa(b.scopeName+":"+b.nodeName):b.nodeName}:function(b){return b.nodeName?b.nodeName:b[0].nodeName};var sc=/[A-Z]/g,pd={full:"1.1.5",major:1,minor:1,dot:5,codeName:"triangle-squarification"},Ka=R.cache={},Ja=R.expando="ng-"+(new Date).getTime(),wc=1,gc=M.document.addEventListener?function(b,a,c){b.addEventListener(a,c,!1)}:function(b,a,c){b.attachEvent("on"+a,c)},gb=
+M.document.removeEventListener?function(b,a,c){b.removeEventListener(a,c,!1)}:function(b,a,c){b.detachEvent("on"+a,c)},uc=/([\:\-\_]+(.))/g,vc=/^moz([A-Z])/,Ba=R.prototype={ready:function(b){function a(){c||(c=!0,b())}var c=!1;T.readyState==="complete"?setTimeout(a):(this.bind("DOMContentLoaded",a),R(M).bind("load",a))},toString:function(){var b=[];n(this,function(a){b.push(""+a)});return"["+b.join(", ")+"]"},eq:function(b){return b>=0?w(this[b]):w(this[this.length+b])},length:0,push:Wa,sort:[].sort,
+splice:[].splice},Na={};n("multiple,selected,checked,disabled,readOnly,required,open".split(","),function(b){Na[I(b)]=b});var Gb={};n("input,select,option,textarea,button,form,details".split(","),function(b){Gb[oa(b)]=!0});n({data:Bb,inheritedData:Ma,scope:function(b){return Ma(b,"$scope")},controller:Eb,injector:function(b){return Ma(b,"$injector")},removeAttr:function(b,a){b.removeAttribute(a)},hasClass:La,css:function(b,a,c){a=Ia(a);if(B(c))b.style[a]=c;else{var d;Z<=8&&(d=b.currentStyle&&b.currentStyle[a],
+d===""&&(d="auto"));d=d||b.style[a];Z<=8&&(d=d===""?p:d);return d}},attr:function(b,a,c){var d=I(a);if(Na[d])if(B(c))c?(b[a]=!0,b.setAttribute(a,d)):(b[a]=!1,b.removeAttribute(d));else return b[a]||(b.attributes.getNamedItem(a)||q).specified?d:p;else if(B(c))b.setAttribute(a,c);else if(b.getAttribute)return b=b.getAttribute(a,2),b===null?p:b},prop:function(b,a,c){if(B(c))b[a]=c;else return b[a]},text:t(Z<9?function(b,a){if(b.nodeType==1){if(C(a))return b.innerText;b.innerText=a}else{if(C(a))return b.nodeValue;
+b.nodeValue=a}}:function(b,a){if(C(a))return b.textContent;b.textContent=a},{$dv:""}),val:function(b,a){if(C(a))return b.value;b.value=a},html:function(b,a){if(C(a))return b.innerHTML;for(var c=0,d=b.childNodes;c<d.length;c++)ya(d[c]);b.innerHTML=a}},function(b,a){R.prototype[a]=function(a,d){var e,g;if((b.length==2&&b!==La&&b!==Eb?a:d)===p)if(L(a)){for(e=0;e<this.length;e++)if(b===Bb)b(this[e],a);else for(g in a)b(this[e],g,a[g]);return this}else{if(this.length)return b(this[0],a,d)}else{for(e=0;e<
+this.length;e++)b(this[e],a,d);return this}return b.$dv}});n({removeData:zb,dealoc:ya,bind:function a(c,d,e){var g=ca(c,"events"),i=ca(c,"handle");g||ca(c,"events",g={});i||ca(c,"handle",i=xc(c,g));n(d.split(" "),function(d){var h=g[d];if(!h){if(d=="mouseenter"||d=="mouseleave"){var j=T.body.contains||T.body.compareDocumentPosition?function(a,c){var d=a.nodeType===9?a.documentElement:a,e=c&&c.parentNode;return a===e||!(!e||!(e.nodeType===1&&(d.contains?d.contains(e):a.compareDocumentPosition&&a.compareDocumentPosition(e)&
+16)))}:function(a,c){if(c)for(;c=c.parentNode;)if(c===a)return!0;return!1};g[d]=[];a(c,{mouseleave:"mouseout",mouseenter:"mouseover"}[d],function(a){var c=a.relatedTarget;(!c||c!==this&&!j(this,c))&&i(a,d)})}else gc(c,d,i),g[d]=[];h=g[d]}h.push(e)})},unbind:Ab,replaceWith:function(a,c){var d,e=a.parentNode;ya(a);n(new R(c),function(c){d?e.insertBefore(c,d.nextSibling):e.replaceChild(c,a);d=c})},children:function(a){var c=[];n(a.childNodes,function(a){a.nodeType===1&&c.push(a)});return c},contents:function(a){return a.childNodes||
+[]},append:function(a,c){n(new R(c),function(c){(a.nodeType===1||a.nodeType===11)&&a.appendChild(c)})},prepend:function(a,c){if(a.nodeType===1){var d=a.firstChild;n(new R(c),function(c){d?a.insertBefore(c,d):(a.appendChild(c),d=c)})}},wrap:function(a,c){var c=w(c)[0],d=a.parentNode;d&&d.replaceChild(c,a);c.appendChild(a)},remove:function(a){ya(a);var c=a.parentNode;c&&c.removeChild(a)},after:function(a,c){var d=a,e=a.parentNode;n(new R(c),function(a){e.insertBefore(a,d.nextSibling);d=a})},addClass:Db,
+removeClass:Cb,toggleClass:function(a,c,d){C(d)&&(d=!La(a,c));(d?Db:Cb)(a,c)},parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},next:function(a){if(a.nextElementSibling)return a.nextElementSibling;for(a=a.nextSibling;a!=null&&a.nodeType!==1;)a=a.nextSibling;return a},find:function(a,c){return a.getElementsByTagName(c)},clone:fb,triggerHandler:function(a,c){var d=(ca(a,"events")||{})[c];n(d,function(c){c.call(a,{preventDefault:q})})}},function(a,c){R.prototype[c]=function(c,e){for(var g,
+i=0;i<this.length;i++)g==p?(g=a(this[i],c,e),g!==p&&(g=w(g))):eb(g,a(this[i],c,e));return g==p?this:g}});za.prototype={put:function(a,c){this[la(a)]=c},get:function(a){return this[la(a)]},remove:function(a){var c=this[a=la(a)];delete this[a];return c}};var zc=/^function\s*[^\(]*\(\s*([^\)]*)\)/m,Ac=/,/,Bc=/^\s*(_?)(\S+?)\1\s*$/,yc=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;Ib.$inject=["$provide"];var qd=function(){var a="$ngAnimateController",c={running:!0};this.$get=["$animation","$window","$sniffer","$rootElement",
+"$rootScope",function(d,e,g,i){i.data(a,c);i=function(c,i){function j(j,k,o){return function(m,r,p){function x(a){var c=0,a=E(a)?a.split(/\s*,\s*/):[];n(a,function(a){c=Math.max(parseFloat(a)||0,c)});return c}function t(){m.addClass(K);if($)$(m,v,P);else if(H(e.getComputedStyle)){var a=g.vendorPrefix+"Animation",c=g.vendorPrefix+"Transition",d=0;n(m,function(f){if(f.nodeType==1){var g="transition",i=c,j=1,h=e.getComputedStyle(f)||{};if(parseFloat(h.animationDuration)>0||parseFloat(h[a+"Duration"])>
+0)g="animation",i=a,j=Math.max(parseInt(h[g+"IterationCount"])||0,parseInt(h[i+"IterationCount"])||0,j);f=Math.max(x(h[g+"Delay"]),x(h[i+"Delay"]));g=Math.max(x(h[g+"Duration"]),x(h[i+"Duration"]));d=Math.max(f+j*g,d)}});e.setTimeout(v,d*1E3)}else v()}function v(){if(!v.run)v.run=!0,o(m,r,p),m.removeClass(w),m.removeClass(K),m.removeData(a)}var A=c.$eval(i.ngAnimate),w=A?L(A)?A[j]:A+"-"+j:"",D=d(w),A=D&&D.setup,$=D&&D.start,D=D&&D.cancel;if(w){var K=w+"-active";r||(r=p?p.parent():m.parent());if(!g.transitions&&
+!A&&!$||(r.inheritedData(a)||q).running)k(m,r,p),o(m,r,p);else{var O=m.data(a)||{};O.running&&((D||q)(m),O.done());m.data(a,{running:!0,done:v});m.addClass(w);k(m,r,p);if(m.length==0)return v();var P=(A||q)(m);e.setTimeout(t,1)}}else k(m,r,p),o(m,r,p)}}function m(a,c,d){d?d.after(a):c.append(a)}var k={};k.enter=j("enter",m,q);k.leave=j("leave",q,function(a){a.remove()});k.move=j("move",function(a,c,d){m(a,c,d)},q);k.show=j("show",function(a){a.css("display","")},q);k.hide=j("hide",q,function(a){a.css("display",
+"none")});k.animate=function(a,c){j(a,q,q)(c)};return k};i.enabled=function(a){if(arguments.length)c.running=!a;return!c.running};return i}]},Kb="Non-assignable model expression: ";Jb.$inject=["$provide"];var Ic=/^(x[\:\-_]|data[\:\-_])/i,jb=/^([^:]+):\/\/(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,Pb=/^([^\?#]*)(\?([^#]*))?(#(.*))?$/,Oa={http:80,https:443,ftp:21};Rb.prototype=lb.prototype=Qb.prototype={$$replace:!1,absUrl:Pa("$$absUrl"),url:function(a,c){if(C(a))return this.$$url;
+var d=Pb.exec(a);d[1]&&this.path(decodeURIComponent(d[1]));if(d[2]||d[1])this.search(d[3]||"");this.hash(d[5]||"",c);return this},protocol:Pa("$$protocol"),host:Pa("$$host"),port:Pa("$$port"),path:Sb("$$path",function(a){return a.charAt(0)=="/"?a:"/"+a}),search:function(a,c){if(C(a))return this.$$search;B(c)?c===null?delete this.$$search[a]:this.$$search[a]=c:this.$$search=E(a)?vb(a):a;this.$$compose();return this},hash:Sb("$$hash",qa),replace:function(){this.$$replace=!0;return this}};var Da={"null":function(){return null},
+"true":function(){return!0},"false":function(){return!1},undefined:q,"+":function(a,c,d,e){d=d(a,c);e=e(a,c);return B(d)?B(e)?d+e:d:B(e)?e:p},"-":function(a,c,d,e){d=d(a,c);e=e(a,c);return(B(d)?d:0)-(B(e)?e:0)},"*":function(a,c,d,e){return d(a,c)*e(a,c)},"/":function(a,c,d,e){return d(a,c)/e(a,c)},"%":function(a,c,d,e){return d(a,c)%e(a,c)},"^":function(a,c,d,e){return d(a,c)^e(a,c)},"=":q,"===":function(a,c,d,e){return d(a,c)===e(a,c)},"!==":function(a,c,d,e){return d(a,c)!==e(a,c)},"==":function(a,
+c,d,e){return d(a,c)==e(a,c)},"!=":function(a,c,d,e){return d(a,c)!=e(a,c)},"<":function(a,c,d,e){return d(a,c)<e(a,c)},">":function(a,c,d,e){return d(a,c)>e(a,c)},"<=":function(a,c,d,e){return d(a,c)<=e(a,c)},">=":function(a,c,d,e){return d(a,c)>=e(a,c)},"&&":function(a,c,d,e){return d(a,c)&&e(a,c)},"||":function(a,c,d,e){return d(a,c)||e(a,c)},"&":function(a,c,d,e){return d(a,c)&e(a,c)},"|":function(a,c,d,e){return e(a,c)(a,c,d(a,c))},"!":function(a,c,d){return!d(a,c)}},Qc={n:"\n",f:"\u000c",r:"\r",
+t:"\t",v:"\u000b","'":"'",'"':'"'},mb={},ad=/^(([^:]+):)?\/\/(\w+:{0,1}\w*@)?([\w\.-]*)?(:([0-9]+))?(.*)$/,ed=M.XMLHttpRequest||function(){try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(a){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(c){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(d){}throw Error("This browser does not support XMLHttpRequest.");};Zb.$inject=["$provide"];$b.$inject=["$locale"];bc.$inject=["$locale"];var ec=".",od={yyyy:Q("FullYear",4),yy:Q("FullYear",
+2,0,!0),y:Q("FullYear",1),MMMM:Qa("Month"),MMM:Qa("Month",!0),MM:Q("Month",2,1),M:Q("Month",1,1),dd:Q("Date",2),d:Q("Date",1),HH:Q("Hours",2),H:Q("Hours",1),hh:Q("Hours",2,-12),h:Q("Hours",1,-12),mm:Q("Minutes",2),m:Q("Minutes",1),ss:Q("Seconds",2),s:Q("Seconds",1),sss:Q("Milliseconds",3),EEEE:Qa("Day"),EEE:Qa("Day",!0),a:function(a,c){return a.getHours()<12?c.AMPMS[0]:c.AMPMS[1]},Z:function(a){var a=-1*a.getTimezoneOffset(),c=a>=0?"+":"";c+=nb(Math[a>0?"floor":"ceil"](a/60),2)+nb(Math.abs(a%60),
+2);return c}},nd=/((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,md=/^\d+$/;ac.$inject=["$locale"];var kd=S(I),ld=S(oa);cc.$inject=["$parse"];var rd=S({restrict:"E",compile:function(a,c){Z<=8&&(!c.href&&!c.name&&c.$set("href",""),a.append(T.createComment("IE fix")));return function(a,c){c.bind("click",function(a){c.attr("href")||a.preventDefault()})}}}),pb={};n(Na,function(a,c){var d=da("ng-"+c);pb[d]=function(){return{priority:100,compile:function(){return function(a,
+g,i){a.$watch(i[d],function(a){i.$set(c,!!a)})}}}}});n(["src","srcset","href"],function(a){var c=da("ng-"+a);pb[c]=function(){return{priority:99,link:function(d,e,g){g.$observe(c,function(c){c&&(g.$set(a,c),Z&&e.prop(a,g[a]))})}}}});var Ta={$addControl:q,$removeControl:q,$setValidity:q,$setDirty:q,$setPristine:q};fc.$inject=["$element","$attrs","$scope"];var Wa=function(a){return["$timeout",function(c){var d={name:"form",restrict:"E",controller:fc,compile:function(){return{pre:function(a,d,i,f){if(!i.action){var h=
+function(a){a.preventDefault?a.preventDefault():a.returnValue=!1};gc(d[0],"submit",h);d.bind("$destroy",function(){c(function(){gb(d[0],"submit",h)},0,!1)})}var j=d.parent().controller("form"),m=i.name||i.ngForm;m&&(a[m]=f);j&&d.bind("$destroy",function(){j.$removeControl(f);m&&(a[m]=p);t(f,Ta)})}}}};return a?t(V(d),{restrict:"EAC"}):d}]},sd=Wa(),td=Wa(!0),ud=/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,vd=/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/,
+wd=/^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/,hc={text:Va,number:function(a,c,d,e,g,i){Va(a,c,d,e,g,i);e.$parsers.push(function(a){var c=X(a);return c||wd.test(a)?(e.$setValidity("number",!0),a===""?null:c?a:parseFloat(a)):(e.$setValidity("number",!1),p)});e.$formatters.push(function(a){return X(a)?"":""+a});if(d.min){var f=parseFloat(d.min),a=function(a){return!X(a)&&a<f?(e.$setValidity("min",!1),p):(e.$setValidity("min",!0),a)};e.$parsers.push(a);e.$formatters.push(a)}if(d.max){var h=parseFloat(d.max),
+d=function(a){return!X(a)&&a>h?(e.$setValidity("max",!1),p):(e.$setValidity("max",!0),a)};e.$parsers.push(d);e.$formatters.push(d)}e.$formatters.push(function(a){return X(a)||Ya(a)?(e.$setValidity("number",!0),a):(e.$setValidity("number",!1),p)})},url:function(a,c,d,e,g,i){Va(a,c,d,e,g,i);a=function(a){return X(a)||ud.test(a)?(e.$setValidity("url",!0),a):(e.$setValidity("url",!1),p)};e.$formatters.push(a);e.$parsers.push(a)},email:function(a,c,d,e,g,i){Va(a,c,d,e,g,i);a=function(a){return X(a)||vd.test(a)?
+(e.$setValidity("email",!0),a):(e.$setValidity("email",!1),p)};e.$formatters.push(a);e.$parsers.push(a)},radio:function(a,c,d,e){C(d.name)&&c.attr("name",Fa());c.bind("click",function(){c[0].checked&&a.$apply(function(){e.$setViewValue(d.value)})});e.$render=function(){c[0].checked=d.value==e.$viewValue};d.$observe("value",e.$render)},checkbox:function(a,c,d,e){var g=d.ngTrueValue,i=d.ngFalseValue;E(g)||(g=!0);E(i)||(i=!1);c.bind("click",function(){a.$apply(function(){e.$setViewValue(c[0].checked)})});
+e.$render=function(){c[0].checked=e.$viewValue};e.$formatters.push(function(a){return a===g});e.$parsers.push(function(a){return a?g:i})},hidden:q,button:q,submit:q,reset:q},ic=["$browser","$sniffer",function(a,c){return{restrict:"E",require:"?ngModel",link:function(d,e,g,i){i&&(hc[I(g.type)]||hc.text)(d,e,g,i,c,a)}}}],Sa="ng-valid",Ra="ng-invalid",pa="ng-pristine",Ua="ng-dirty",xd=["$scope","$exceptionHandler","$attrs","$element","$parse",function(a,c,d,e,g){function i(a,c){c=c?"-"+bb(c,"-"):"";
+e.removeClass((a?Ra:Sa)+c).addClass((a?Sa:Ra)+c)}this.$modelValue=this.$viewValue=Number.NaN;this.$parsers=[];this.$formatters=[];this.$viewChangeListeners=[];this.$pristine=!0;this.$dirty=!1;this.$valid=!0;this.$invalid=!1;this.$name=d.name;var f=g(d.ngModel),h=f.assign;if(!h)throw Error(Kb+d.ngModel+" ("+va(e)+")");this.$render=q;var j=e.inheritedData("$formController")||Ta,m=0,k=this.$error={};e.addClass(pa);i(!0);this.$setValidity=function(a,c){if(k[a]!==!c){if(c){if(k[a]&&m--,!m)i(!0),this.$valid=
+!0,this.$invalid=!1}else i(!1),this.$invalid=!0,this.$valid=!1,m++;k[a]=!c;i(c,a);j.$setValidity(a,c,this)}};this.$setPristine=function(){this.$dirty=!1;this.$pristine=!0;e.removeClass(Ua).addClass(pa)};this.$setViewValue=function(d){this.$viewValue=d;if(this.$pristine)this.$dirty=!0,this.$pristine=!1,e.removeClass(pa).addClass(Ua),j.$setDirty();n(this.$parsers,function(a){d=a(d)});if(this.$modelValue!==d)this.$modelValue=d,h(a,d),n(this.$viewChangeListeners,function(a){try{a()}catch(d){c(d)}})};
+var l=this;a.$watch(function(){var c=f(a);if(l.$modelValue!==c){var d=l.$formatters,e=d.length;for(l.$modelValue=c;e--;)c=d[e](c);if(l.$viewValue!==c)l.$viewValue=c,l.$render()}})}],yd=function(){return{require:["ngModel","^?form"],controller:xd,link:function(a,c,d,e){var g=e[0],i=e[1]||Ta;i.$addControl(g);c.bind("$destroy",function(){i.$removeControl(g)})}}},zd=S({require:"ngModel",link:function(a,c,d,e){e.$viewChangeListeners.push(function(){a.$eval(d.ngChange)})}}),jc=function(){return{require:"?ngModel",
+link:function(a,c,d,e){if(e){d.required=!0;var g=function(a){if(d.required&&(X(a)||a===!1))e.$setValidity("required",!1);else return e.$setValidity("required",!0),a};e.$formatters.push(g);e.$parsers.unshift(g);d.$observe("required",function(){g(e.$viewValue)})}}}},Ad=function(){return{require:"ngModel",link:function(a,c,d,e){var g=(a=/\/(.*)\//.exec(d.ngList))&&RegExp(a[1])||d.ngList||",";e.$parsers.push(function(a){var c=[];a&&n(a.split(g),function(a){a&&c.push(U(a))});return c});e.$formatters.push(function(a){return F(a)?
+a.join(", "):p})}}},Bd=/^(true|false|\d+)$/,Cd=function(){return{priority:100,compile:function(a,c){return Bd.test(c.ngValue)?function(a,c,g){g.$set("value",a.$eval(g.ngValue))}:function(a,c,g){a.$watch(g.ngValue,function(a){g.$set("value",a,!1)})}}}},Dd=aa(function(a,c,d){c.addClass("ng-binding").data("$binding",d.ngBind);a.$watch(d.ngBind,function(a){c.text(a==p?"":a)})}),Ed=["$interpolate",function(a){return function(c,d,e){c=a(d.attr(e.$attr.ngBindTemplate));d.addClass("ng-binding").data("$binding",
+c);e.$observe("ngBindTemplate",function(a){d.text(a)})}}],Fd=[function(){return function(a,c,d){c.addClass("ng-binding").data("$binding",d.ngBindHtmlUnsafe);a.$watch(d.ngBindHtmlUnsafe,function(a){c.html(a||"")})}}],Gd=ob("",!0),Hd=ob("Odd",0),Id=ob("Even",1),Jd=aa({compile:function(a,c){c.$set("ngCloak",p);a.removeClass("ng-cloak")}}),Kd=[function(){return{scope:!0,controller:"@"}}],Ld=["$sniffer",function(a){return{priority:1E3,compile:function(){a.csp=!0}}}],kc={};n("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress".split(" "),
+function(a){var c=da("ng-"+a);kc[c]=["$parse",function(d){return function(e,g,i){var f=d(i[c]);g.bind(I(a),function(a){e.$apply(function(){f(e,{$event:a})})})}}]});var Md=aa(function(a,c,d){c.bind("submit",function(){a.$apply(d.ngSubmit)})}),Nd=["$animator",function(a){return{transclude:"element",priority:1E3,terminal:!0,restrict:"A",compile:function(c,d,e){return function(c,d,f){var h=a(c,f),j,m;c.$watch(f.ngIf,function(a){j&&(h.leave(j),j=p);m&&(m.$destroy(),m=p);ua(a)&&(m=c.$new(),e(m,function(a){j=
+a;h.enter(a,d.parent(),d)}))})}}}}],Od=["$http","$templateCache","$anchorScroll","$compile","$animator",function(a,c,d,e,g){return{restrict:"ECA",terminal:!0,compile:function(i,f){var h=f.ngInclude||f.src,j=f.onload||"",m=f.autoscroll;return function(f,i,n){var o=g(f,n),p=0,r,t=function(){r&&(r.$destroy(),r=null);o.leave(i.contents(),i)};f.$watch(h,function(g){var h=++p;g?(a.get(g,{cache:c}).success(function(a){h===p&&(r&&r.$destroy(),r=f.$new(),o.leave(i.contents(),i),a=w("<div/>").html(a).contents(),
+o.enter(a,i),e(a)(r),B(m)&&(!m||f.$eval(m))&&d(),r.$emit("$includeContentLoaded"),f.$eval(j))}).error(function(){h===p&&t()}),f.$emit("$includeContentRequested")):t()})}}}}],Pd=aa({compile:function(){return{pre:function(a,c,d){a.$eval(d.ngInit)}}}}),Qd=aa({terminal:!0,priority:1E3}),Rd=["$locale","$interpolate",function(a,c){var d=/{}/g;return{restrict:"EA",link:function(e,g,i){var f=i.count,h=g.attr(i.$attr.when),j=i.offset||0,m=e.$eval(h),k={},l=c.startSymbol(),p=c.endSymbol();n(m,function(a,e){k[e]=
+c(a.replace(d,l+f+"-"+j+p))});e.$watch(function(){var c=parseFloat(e.$eval(f));return isNaN(c)?"":(c in m||(c=a.pluralCat(c-j)),k[c](e,g,!0))},function(a){g.text(a)})}}}],Sd=["$parse","$animator",function(a,c){return{transclude:"element",priority:1E3,terminal:!0,compile:function(d,e,g){return function(d,e,h){var j=c(d,h),m=h.ngRepeat,k=m.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/),l,p,o,z,r,t={$id:la};if(!k)throw Error("Expected ngRepeat in form of '_item_ in _collection_[ track by _id_]' but got '"+
+m+"'.");h=k[1];o=k[2];(k=k[4])?(l=a(k),p=function(a,c,e){r&&(t[r]=a);t[z]=c;t.$index=e;return l(d,t)}):p=function(a,c){return la(c)};k=h.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);if(!k)throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '"+h+"'.");z=k[3]||k[1];r=k[2];var x={};d.$watchCollection(o,function(a){var c,h,k=e,l,o={},t,q,w,s,B,y,C=[];if(Xa(a))B=a;else{B=[];for(w in a)a.hasOwnProperty(w)&&w.charAt(0)!="$"&&B.push(w);B.sort()}t=B.length;h=
+C.length=B.length;for(c=0;c<h;c++)if(w=a===B?c:B[c],s=a[w],l=p(w,s,c),x.hasOwnProperty(l))y=x[l],delete x[l],o[l]=y,C[c]=y;else if(o.hasOwnProperty(l))throw n(C,function(a){a&&a.element&&(x[a.id]=a)}),Error("Duplicates in a repeater are not allowed. Repeater: "+m+" key: "+l);else C[c]={id:l},o[l]=!1;for(w in x)if(x.hasOwnProperty(w))y=x[w],j.leave(y.element),y.element[0].$$NG_REMOVED=!0,y.scope.$destroy();c=0;for(h=B.length;c<h;c++){w=a===B?c:B[c];s=a[w];y=C[c];if(y.element){q=y.scope;l=k[0];do l=
+l.nextSibling;while(l&&l.$$NG_REMOVED);y.element[0]!=l&&j.move(y.element,null,k);k=y.element}else q=d.$new();q[z]=s;r&&(q[r]=w);q.$index=c;q.$first=c===0;q.$last=c===t-1;q.$middle=!(q.$first||q.$last);y.element||g(q,function(a){j.enter(a,null,k);k=a;y.scope=q;y.element=a;o[y.id]=y})}x=o})}}}}],Td=["$animator",function(a){return function(c,d,e){var g=a(c,e);c.$watch(e.ngShow,function(a){g[ua(a)?"show":"hide"](d)})}}],Ud=["$animator",function(a){return function(c,d,e){var g=a(c,e);c.$watch(e.ngHide,
+function(a){g[ua(a)?"hide":"show"](d)})}}],Vd=aa(function(a,c,d){a.$watch(d.ngStyle,function(a,d){d&&a!==d&&n(d,function(a,d){c.css(d,"")});a&&c.css(a)},!0)}),Wd=["$animator",function(a){return{restrict:"EA",require:"ngSwitch",controller:["$scope",function(){this.cases={}}],link:function(c,d,e,g){var i=a(c,e),f,h,j=[];c.$watch(e.ngSwitch||e.on,function(a){for(var d=0,l=j.length;d<l;d++)j[d].$destroy(),i.leave(h[d]);h=[];j=[];if(f=g.cases["!"+a]||g.cases["?"])c.$eval(e.change),n(f,function(a){var d=
+c.$new();j.push(d);a.transclude(d,function(c){var d=a.element;h.push(c);i.enter(c,d.parent(),d)})})})}}}],Xd=aa({transclude:"element",priority:500,require:"^ngSwitch",compile:function(a,c,d){return function(a,g,i,f){f.cases["!"+c.ngSwitchWhen]=f.cases["!"+c.ngSwitchWhen]||[];f.cases["!"+c.ngSwitchWhen].push({transclude:d,element:g})}}}),Yd=aa({transclude:"element",priority:500,require:"^ngSwitch",compile:function(a,c,d){return function(a,c,i,f){f.cases["?"]=f.cases["?"]||[];f.cases["?"].push({transclude:d,
+element:c})}}}),Zd=aa({controller:["$transclude","$element",function(a,c){a(function(a){c.append(a)})}]}),$d=["$http","$templateCache","$route","$anchorScroll","$compile","$controller","$animator",function(a,c,d,e,g,i,f){return{restrict:"ECA",terminal:!0,link:function(a,c,m){function k(){var f=d.current&&d.current.locals,k=f&&f.$template;if(k){o.leave(c.contents(),c);l&&(l.$destroy(),l=null);k=w("<div></div>").html(k).contents();o.enter(k,c);var k=g(k),m=d.current;l=m.scope=a.$new();if(m.controller)f.$scope=
+l,f=i(m.controller,f),m.controllerAs&&(l[m.controllerAs]=f),c.children().data("$ngControllerController",f);k(l);l.$emit("$viewContentLoaded");l.$eval(n);e()}else o.leave(c.contents(),c),l&&(l.$destroy(),l=null)}var l,n=m.onload||"",o=f(a,m);a.$on("$routeChangeSuccess",k);k()}}}],ae=["$templateCache",function(a){return{restrict:"E",terminal:!0,compile:function(c,d){d.type=="text/ng-template"&&a.put(d.id,c[0].text)}}}],be=S({terminal:!0}),ce=["$compile","$parse",function(a,c){var d=/^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/,
+e={$setViewValue:q};return{restrict:"E",require:["select","?ngModel"],controller:["$element","$scope","$attrs",function(a,c,d){var h=this,j={},m=e,k;h.databound=d.ngModel;h.init=function(a,c,d){m=a;k=d};h.addOption=function(c){j[c]=!0;m.$viewValue==c&&(a.val(c),k.parent()&&k.remove())};h.removeOption=function(a){this.hasOption(a)&&(delete j[a],m.$viewValue==a&&this.renderUnknownOption(a))};h.renderUnknownOption=function(c){c="? "+la(c)+" ?";k.val(c);a.prepend(k);a.val(c);k.prop("selected",!0)};h.hasOption=
+function(a){return j.hasOwnProperty(a)};c.$on("$destroy",function(){h.renderUnknownOption=q})}],link:function(e,i,f,h){function j(a,c,d,e){d.$render=function(){var a=d.$viewValue;e.hasOption(a)?(v.parent()&&v.remove(),c.val(a),a===""&&t.prop("selected",!0)):C(a)&&t?c.val(""):e.renderUnknownOption(a)};c.bind("change",function(){a.$apply(function(){v.parent()&&v.remove();d.$setViewValue(c.val())})})}function m(a,c,d){var e;d.$render=function(){var a=new za(d.$viewValue);n(c.find("option"),function(c){c.selected=
+B(a.get(c.value))})};a.$watch(function(){ia(e,d.$viewValue)||(e=V(d.$viewValue),d.$render())});c.bind("change",function(){a.$apply(function(){var a=[];n(c.find("option"),function(c){c.selected&&a.push(c.value)});d.$setViewValue(a)})})}function k(e,f,g){function i(){var a={"":[]},c=[""],d,h,q,v,s;q=g.$modelValue;v=u(e)||[];var z=l?qb(v):v,B,y,A;y={};s=!1;var C,D;if(o)if(t&&F(q)){s=new za([]);for(h=0;h<q.length;h++)y[k]=q[h],s.put(t(e,y),q[h])}else s=new za(q);for(A=0;B=z.length,A<B;A++){y[k]=v[l?y[l]=
+z[A]:A];d=m(e,y)||"";if(!(h=a[d]))h=a[d]=[],c.push(d);o?d=s.remove(t?t(e,y):n(e,y))!=p:(t?(d={},d[k]=q,d=t(e,d)===t(e,y)):d=q===n(e,y),s=s||d);C=j(e,y);C=C===p?"":C;h.push({id:t?t(e,y):l?z[A]:A,label:C,selected:d})}o||(r||q===null?a[""].unshift({id:"",label:"",selected:!s}):s||a[""].unshift({id:"?",label:"",selected:!0}));y=0;for(z=c.length;y<z;y++){d=c[y];h=a[d];if(w.length<=y)q={element:E.clone().attr("label",d),label:h.label},v=[q],w.push(v),f.append(q.element);else if(v=w[y],q=v[0],q.label!=d)q.element.attr("label",
+q.label=d);C=null;A=0;for(B=h.length;A<B;A++)if(d=h[A],s=v[A+1]){C=s.element;if(s.label!==d.label)C.text(s.label=d.label);if(s.id!==d.id)C.val(s.id=d.id);if(C[0].selected!==d.selected)C.prop("selected",s.selected=d.selected)}else d.id===""&&r?D=r:(D=x.clone()).val(d.id).attr("selected",d.selected).text(d.label),v.push({element:D,label:d.label,id:d.id,selected:d.selected}),C?C.after(D):q.element.append(D),C=D;for(A++;v.length>A;)v.pop().element.remove()}for(;w.length>y;)w.pop()[0].element.remove()}
+var h;if(!(h=q.match(d)))throw Error("Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_ (track by _expr_)?' but got '"+q+"'.");var j=c(h[2]||h[1]),k=h[4]||h[6],l=h[5],m=c(h[3]||""),n=c(h[2]?h[1]:k),u=c(h[7]),t=h[8]?c(h[8]):null,w=[[{element:f,label:""}]];r&&(a(r)(e),r.removeClass("ng-scope"),r.remove());f.html("");f.bind("change",function(){e.$apply(function(){var a,c=u(e)||[],d={},h,i,j,m,q,r;if(o){i=[];m=0;for(r=w.length;m<r;m++){a=w[m];j=1;for(q=a.length;j<
+q;j++)if((h=a[j].element)[0].selected){h=h.val();l&&(d[l]=h);if(t)for(var s=0;s<c.length;s++){if(d[k]=c[s],t(e,d)==h)break}else d[k]=c[h];i.push(n(e,d))}}}else if(h=f.val(),h=="?")i=p;else if(h=="")i=null;else if(t)for(s=0;s<c.length;s++){if(d[k]=c[s],t(e,d)==h){i=n(e,d);break}}else d[k]=c[h],l&&(d[l]=h),i=n(e,d);g.$setViewValue(i)})});g.$render=i;e.$watch(i)}if(h[1]){for(var l=h[0],u=h[1],o=f.multiple,q=f.ngOptions,r=!1,t,x=w(T.createElement("option")),E=w(T.createElement("optgroup")),v=x.clone(),
+h=0,A=i.children(),G=A.length;h<G;h++)if(A[h].value==""){t=r=A.eq(h);break}l.init(u,r,v);if(o&&(f.required||f.ngRequired)){var D=function(a){u.$setValidity("required",!f.required||a&&a.length);return a};u.$parsers.push(D);u.$formatters.unshift(D);f.$observe("required",function(){D(u.$viewValue)})}q?k(e,i,u):o?m(e,i,u):j(e,i,u,l)}}}}],de=["$interpolate",function(a){var c={addOption:q,removeOption:q};return{restrict:"E",priority:100,compile:function(d,e){if(C(e.value)){var g=a(d.text(),!0);g||e.$set("value",
+d.text())}return function(a,d,e){var j=d.parent(),m=j.data("$selectController")||j.parent().data("$selectController");m&&m.databound?d.prop("selected",!1):m=c;g?a.$watch(g,function(a,c){e.$set("value",a);a!==c&&m.removeOption(c);m.addOption(a)}):m.addOption(e.value);d.bind("$destroy",function(){m.removeOption(e.value)})}}}}],ee=S({restrict:"E",terminal:!0});(ga=M.jQuery)?(w=ga,t(ga.fn,{scope:Ba.scope,controller:Ba.controller,injector:Ba.injector,inheritedData:Ba.inheritedData}),db("remove",!0),db("empty"),
+db("html")):w=R;Ha.element=w;(function(a){t(a,{bootstrap:xb,copy:V,extend:t,equals:ia,element:w,forEach:n,injector:yb,noop:q,bind:$a,toJson:ha,fromJson:ub,identity:qa,isUndefined:C,isDefined:B,isString:E,isFunction:H,isObject:L,isNumber:Ya,isElement:oc,isArray:F,version:pd,isDate:ra,lowercase:I,uppercase:oa,callbacks:{counter:0},noConflict:lc});Aa=tc(M);try{Aa("ngLocale")}catch(c){Aa("ngLocale",[]).provider("$locale",fd)}Aa("ng",["ngLocale"],["$provide",function(a){a.provider("$compile",Jb).directive({a:rd,
+input:ic,textarea:ic,form:sd,script:ae,select:ce,style:ee,option:de,ngBind:Dd,ngBindHtmlUnsafe:Fd,ngBindTemplate:Ed,ngClass:Gd,ngClassEven:Id,ngClassOdd:Hd,ngCsp:Ld,ngCloak:Jd,ngController:Kd,ngForm:td,ngHide:Ud,ngIf:Nd,ngInclude:Od,ngInit:Pd,ngNonBindable:Qd,ngPluralize:Rd,ngRepeat:Sd,ngShow:Td,ngSubmit:Md,ngStyle:Vd,ngSwitch:Wd,ngSwitchWhen:Xd,ngSwitchDefault:Yd,ngOptions:be,ngView:$d,ngTransclude:Zd,ngModel:yd,ngList:Ad,ngChange:zd,required:jc,ngRequired:jc,ngValue:Cd}).directive(pb).directive(kc);
+a.provider({$anchorScroll:Cc,$animation:Ib,$animator:qd,$browser:Ec,$cacheFactory:Fc,$controller:Jc,$document:Kc,$exceptionHandler:Lc,$filter:Zb,$interpolate:Mc,$http:bd,$httpBackend:cd,$location:Nc,$log:Oc,$parse:Sc,$route:Vc,$routeParams:Wc,$rootScope:Xc,$q:Tc,$sniffer:Yc,$templateCache:Gc,$timeout:gd,$window:Zc})}])})(Ha);w(T).ready(function(){rc(T,xb)})})(window,document);angular.element(document).find("head").append('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak{display:none;}ng\\:form{display:block;}</style>');
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/angular-slider-0.1.6.js b/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/angular-slider-0.1.6.js
new file mode 100755
index 0000000..723cae7
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/angular-slider-0.1.6.js
@@ -0,0 +1,338 @@
+// Generated by CoffeeScript 1.6.2
+(function() {
+ var MODULE_NAME, SLIDER_TAG, angularize, bindHtml, gap, halfWidth, hide, inputEvents, module, offset, offsetLeft, pixelize, qualifiedDirectiveDefinition, roundStep, show, sliderDirective, width;
+
+ MODULE_NAME = 'uiSlider';
+
+ SLIDER_TAG = 'slider';
+
+ angularize = function(element) {
+ return angular.element(element);
+ };
+
+ pixelize = function(position) {
+ return "" + position + "px";
+ };
+
+ hide = function(element) {
+ return element.css({
+ opacity: 0
+ });
+ };
+
+ show = function(element) {
+ return element.css({
+ opacity: 1
+ });
+ };
+
+ offset = function(element, position) {
+ return element.css({
+ left: position
+ });
+ };
+
+ halfWidth = function(element) {
+ return element[0].offsetWidth / 2;
+ };
+
+ offsetLeft = function(element) {
+ return element[0].offsetLeft;
+ };
+
+ width = function(element) {
+ return element[0].offsetWidth;
+ };
+
+ gap = function(element1, element2) {
+ return offsetLeft(element2) - offsetLeft(element1) - width(element1);
+ };
+
+ bindHtml = function(element, html) {
+ return element.attr('ng-bind-html-unsafe', html);
+ };
+
+ roundStep = function(value, precision, step, floor) {
+ var decimals, remainder, roundedValue, steppedValue;
+
+ if (floor == null) {
+ floor = 0;
+ }
+ if (step == null) {
+ step = 1 / Math.pow(10, precision);
+ }
+ remainder = (value - floor) % step;
+ steppedValue = remainder > (step / 2) ? value + step - remainder : value - remainder;
+ decimals = Math.pow(10, precision);
+ roundedValue = steppedValue * decimals / decimals;
+ return roundedValue.toFixed(precision);
+ };
+
+ inputEvents = {
+ mouse: {
+ start: 'mousedown',
+ move: 'mousemove',
+ end: 'mouseup'
+ },
+ touch: {
+ start: 'touchstart',
+ move: 'touchmove',
+ end: 'touchend'
+ }
+ };
+
+ sliderDirective = function($timeout) {
+ return {
+ restrict: 'EA',
+ scope: {
+ floor: '@',
+ ceiling: '@',
+ step: '@',
+ precision: '@',
+ ngModel: '=?',
+ ngModelLow: '=?',
+ ngModelHigh: '=?',
+ translate: '&'
+ },
+ template: '<span class="bar"></span><span class="bar selection"></span><span class="pointer"></span><span class="pointer"></span><span class="bubble selection"></span><span ng-bind-html-unsafe="translate({value: floor})" class="bubble limit"></span><span ng-bind-html-unsafe="translate({value: ceiling})" class="bubble limit"></span><span class="bubble"></span><span class="bubble"></span><span class="bubble"></span>',
+ compile: function(element, attributes) {
+ var ceilBub, cmbBub, e, flrBub, fullBar, highBub, lowBub, maxPtr, minPtr, range, refHigh, refLow, selBar, selBub, watchables, _i, _len, _ref, _ref1;
+
+ if (attributes.translate) {
+ attributes.$set('translate', "" + attributes.translate + "(value)");
+ }
+ range = (attributes.ngModel == null) && ((attributes.ngModelLow != null) && (attributes.ngModelHigh != null));
+ _ref = (function() {
+ var _i, _len, _ref, _results;
+
+ _ref = element.children();
+ _results = [];
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ e = _ref[_i];
+ _results.push(angularize(e));
+ }
+ return _results;
+ })(), fullBar = _ref[0], selBar = _ref[1], minPtr = _ref[2], maxPtr = _ref[3], selBub = _ref[4], flrBub = _ref[5], ceilBub = _ref[6], lowBub = _ref[7], highBub = _ref[8], cmbBub = _ref[9];
+ refLow = range ? 'ngModelLow' : 'ngModel';
+ refHigh = 'ngModelHigh';
+ bindHtml(selBub, "'Range: ' + translate({value: diff})");
+ bindHtml(lowBub, "translate({value: " + refLow + "})");
+ bindHtml(highBub, "translate({value: " + refHigh + "})");
+ bindHtml(cmbBub, "translate({value: " + refLow + "}) + ' - ' + translate({value: " + refHigh + "})");
+ if (!range) {
+ _ref1 = [selBar, maxPtr, selBub, highBub, cmbBub];
+ for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
+ element = _ref1[_i];
+ element.remove();
+ }
+ }
+ watchables = [refLow, 'floor', 'ceiling'];
+ if (range) {
+ watchables.push(refHigh);
+ }
+ return {
+ post: function(scope, element, attributes) {
+ var barWidth, boundToInputs, dimensions, maxOffset, maxValue, minOffset, minValue, ngDocument, offsetRange, pointerHalfWidth, updateDOM, valueRange, w, _j, _len1;
+
+ boundToInputs = false;
+ ngDocument = angularize(document);
+ if (!attributes.translate) {
+ scope.translate = function(value) {
+ return value.value;
+ };
+ }
+ pointerHalfWidth = barWidth = minOffset = maxOffset = minValue = maxValue = valueRange = offsetRange = void 0;
+ dimensions = function() {
+ var value, _j, _len1, _ref2, _ref3;
+
+ if ((_ref2 = scope.precision) == null) {
+ scope.precision = 0;
+ }
+ if ((_ref3 = scope.step) == null) {
+ scope.step = 1;
+ }
+ for (_j = 0, _len1 = watchables.length; _j < _len1; _j++) {
+ value = watchables[_j];
+ scope[value] = roundStep(parseFloat(scope[value]), parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
+ }
+ scope.diff = roundStep(scope[refHigh] - scope[refLow], parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
+ pointerHalfWidth = halfWidth(minPtr);
+ barWidth = width(fullBar);
+ minOffset = 0;
+ maxOffset = barWidth - width(minPtr);
+ minValue = parseFloat(attributes.floor);
+ maxValue = parseFloat(attributes.ceiling);
+ valueRange = maxValue - minValue;
+ return offsetRange = maxOffset - minOffset;
+ };
+ updateDOM = function() {
+ var adjustBubbles, bindToInputEvents, fitToBar, percentOffset, percentToOffset, percentValue, setBindings, setPointers;
+
+ dimensions();
+ percentOffset = function(offset) {
+ return ((offset - minOffset) / offsetRange) * 100;
+ };
+ percentValue = function(value) {
+ return ((value - minValue) / valueRange) * 100;
+ };
+ percentToOffset = function(percent) {
+ return pixelize(percent * offsetRange / 100);
+ };
+ fitToBar = function(element) {
+ return offset(element, pixelize(Math.min(Math.max(0, offsetLeft(element)), barWidth - width(element))));
+ };
+ setPointers = function() {
+ var newHighValue, newLowValue;
+
+ offset(ceilBub, pixelize(barWidth - width(ceilBub)));
+ newLowValue = percentValue(scope[refLow]);
+ offset(minPtr, percentToOffset(newLowValue));
+ offset(lowBub, pixelize(offsetLeft(minPtr) - (halfWidth(lowBub)) + pointerHalfWidth));
+ if (range) {
+ newHighValue = percentValue(scope[refHigh]);
+ offset(maxPtr, percentToOffset(newHighValue));
+ offset(highBub, pixelize(offsetLeft(maxPtr) - (halfWidth(highBub)) + pointerHalfWidth));
+ offset(selBar, pixelize(offsetLeft(minPtr) + pointerHalfWidth));
+ selBar.css({
+ width: percentToOffset(newHighValue - newLowValue)
+ });
+ offset(selBub, pixelize(offsetLeft(selBar) + halfWidth(selBar) - halfWidth(selBub)));
+ return offset(cmbBub, pixelize(offsetLeft(selBar) + halfWidth(selBar) - halfWidth(cmbBub)));
+ }
+ };
+ adjustBubbles = function() {
+ var bubToAdjust;
+
+ fitToBar(lowBub);
+ bubToAdjust = highBub;
+ if (range) {
+ fitToBar(highBub);
+ fitToBar(selBub);
+ if (gap(lowBub, highBub) < 10) {
+ hide(lowBub);
+ hide(highBub);
+ fitToBar(cmbBub);
+ show(cmbBub);
+ bubToAdjust = cmbBub;
+ } else {
+ show(lowBub);
+ show(highBub);
+ hide(cmbBub);
+ bubToAdjust = highBub;
+ }
+ }
+ if (gap(flrBub, lowBub) < 5) {
+ hide(flrBub);
+ } else {
+ if (range) {
+ if (gap(flrBub, bubToAdjust) < 5) {
+ hide(flrBub);
+ } else {
+ show(flrBub);
+ }
+ } else {
+ show(flrBub);
+ }
+ }
+ if (gap(lowBub, ceilBub) < 5) {
+ return hide(ceilBub);
+ } else {
+ if (range) {
+ if (gap(bubToAdjust, ceilBub) < 5) {
+ return hide(ceilBub);
+ } else {
+ return show(ceilBub);
+ }
+ } else {
+ return show(ceilBub);
+ }
+ }
+ };
+ bindToInputEvents = function(pointer, ref, events) {
+ var onEnd, onMove, onStart;
+
+ onEnd = function() {
+ pointer.removeClass('active');
+ ngDocument.unbind(events.move);
+ return ngDocument.unbind(events.end);
+ };
+ onMove = function(event) {
+ var eventX, newOffset, newPercent, newValue;
+
+ eventX = event.clientX || event.touches[0].clientX;
+ newOffset = eventX - element[0].getBoundingClientRect().left - pointerHalfWidth;
+ newOffset = Math.max(Math.min(newOffset, maxOffset), minOffset);
+ newPercent = percentOffset(newOffset);
+ newValue = minValue + (valueRange * newPercent / 100.0);
+ if (range) {
+ if (ref === refLow) {
+ if (newValue > scope[refHigh]) {
+ ref = refHigh;
+ minPtr.removeClass('active');
+ maxPtr.addClass('active');
+ }
+ } else {
+ if (newValue < scope[refLow]) {
+ ref = refLow;
+ maxPtr.removeClass('active');
+ minPtr.addClass('active');
+ }
+ }
+ }
+ newValue = roundStep(newValue, parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
+ scope[ref] = newValue;
+ return scope.$apply();
+ };
+ onStart = function(event) {
+ pointer.addClass('active');
+ dimensions();
+ event.stopPropagation();
+ event.preventDefault();
+ ngDocument.bind(events.move, onMove);
+ return ngDocument.bind(events.end, onEnd);
+ };
+ return pointer.bind(events.start, onStart);
+ };
+ setBindings = function() {
+ var bind, inputMethod, _j, _len1, _ref2, _results;
+
+ boundToInputs = true;
+ bind = function(method) {
+ bindToInputEvents(minPtr, refLow, inputEvents[method]);
+ return bindToInputEvents(maxPtr, refHigh, inputEvents[method]);
+ };
+ _ref2 = ['touch', 'mouse'];
+ _results = [];
+ for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
+ inputMethod = _ref2[_j];
+ _results.push(bind(inputMethod));
+ }
+ return _results;
+ };
+ setPointers();
+ adjustBubbles();
+ if (!boundToInputs) {
+ return setBindings();
+ }
+ };
+ $timeout(updateDOM);
+ for (_j = 0, _len1 = watchables.length; _j < _len1; _j++) {
+ w = watchables[_j];
+ scope.$watch(w, updateDOM);
+ }
+ return window.addEventListener("resize", updateDOM);
+ }
+ };
+ }
+ };
+ };
+
+ qualifiedDirectiveDefinition = ['$timeout', sliderDirective];
+
+ module = function(window, angular) {
+ return angular.module(MODULE_NAME, []).directive(SLIDER_TAG, qualifiedDirectiveDefinition);
+ };
+
+ module(window, window.angular);
+
+}).call(this);
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/angular-slugify-1.0.0.js b/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/angular-slugify-1.0.0.js
new file mode 100644
index 0000000..07f7dfc
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/angular-slugify-1.0.0.js
@@ -0,0 +1,299 @@
+/**
+ * angular-slugify -- provides slugification for AngularJS
+ *
+ * Copyright © 2013 Paul Smith <paulsmith@pobox.com>
+ *
+ * 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.
+ */
+"use strict";
+
+(function() {
+ var mod = angular.module("slugifier", []);
+
+ // Unicode (non-control) characters in the Latin-1 Supplement and Latin
+ // Extended-A blocks, transliterated into ASCII characters.
+ var charmap = {
+ ' ': " ",
+ '¡': "!",
+ '¢': "c",
+ '£': "lb",
+ '¥': "yen",
+ '¦': "|",
+ '§': "SS",
+ '¨': "\"",
+ '©': "(c)",
+ 'ª': "a",
+ '«': "<<",
+ '¬': "not",
+ '': "-",
+ '®': "(R)",
+ '°': "^0",
+ '±': "+/-",
+ '²': "^2",
+ '³': "^3",
+ '´': "'",
+ 'µ': "u",
+ '¶': "P",
+ '·': ".",
+ '¸': ",",
+ '¹': "^1",
+ 'º': "o",
+ '»': ">>",
+ '¼': " 1/4 ",
+ '½': " 1/2 ",
+ '¾': " 3/4 ",
+ '¿': "?",
+ 'À': "`A",
+ 'Á': "'A",
+ 'Â': "^A",
+ 'Ã': "~A",
+ 'Ä': '"A',
+ 'Å': "A",
+ 'Æ': "AE",
+ 'Ç': "C",
+ 'È': "`E",
+ 'É': "'E",
+ 'Ê': "^E",
+ 'Ë': '"E',
+ 'Ì': "`I",
+ 'Í': "'I",
+ 'Î': "^I",
+ 'Ï': '"I',
+ 'Ð': "D",
+ 'Ñ': "~N",
+ 'Ò': "`O",
+ 'Ó': "'O",
+ 'Ô': "^O",
+ 'Õ': "~O",
+ 'Ö': '"O',
+ '×': "x",
+ 'Ø': "O",
+ 'Ù': "`U",
+ 'Ú': "'U",
+ 'Û': "^U",
+ 'Ü': '"U',
+ 'Ý': "'Y",
+ 'Þ': "Th",
+ 'ß': "ss",
+ 'à': "`a",
+ 'á': "'a",
+ 'â': "^a",
+ 'ã': "~a",
+ 'ä': '"a',
+ 'å': "a",
+ 'æ': "ae",
+ 'ç': "c",
+ 'è': "`e",
+ 'é': "'e",
+ 'ê': "^e",
+ 'ë': '"e',
+ 'ì': "`i",
+ 'í': "'i",
+ 'î': "^i",
+ 'ï': '"i',
+ 'ð': "d",
+ 'ñ': "~n",
+ 'ò': "`o",
+ 'ó': "'o",
+ 'ô': "^o",
+ 'õ': "~o",
+ 'ö': '"o',
+ '÷': ":",
+ 'ø': "o",
+ 'ù': "`u",
+ 'ú': "'u",
+ 'û': "^u",
+ 'ü': '"u',
+ 'ý': "'y",
+ 'þ': "th",
+ 'ÿ': '"y',
+ 'Ā': "A",
+ 'ā': "a",
+ 'Ă': "A",
+ 'ă': "a",
+ 'Ą': "A",
+ 'ą': "a",
+ 'Ć': "'C",
+ 'ć': "'c",
+ 'Ĉ': "^C",
+ 'ĉ': "^c",
+ 'Ċ': "C",
+ 'ċ': "c",
+ 'Č': "C",
+ 'č': "c",
+ 'Ď': "D",
+ 'ď': "d",
+ 'Đ': "D",
+ 'đ': "d",
+ 'Ē': "E",
+ 'ē': "e",
+ 'Ĕ': "E",
+ 'ĕ': "e",
+ 'Ė': "E",
+ 'ė': "e",
+ 'Ę': "E",
+ 'ę': "e",
+ 'Ě': "E",
+ 'ě': "e",
+ 'Ĝ': "^G",
+ 'ĝ': "^g",
+ 'Ğ': "G",
+ 'ğ': "g",
+ 'Ġ': "G",
+ 'ġ': "g",
+ 'Ģ': "G",
+ 'ģ': "g",
+ 'Ĥ': "^H",
+ 'ĥ': "^h",
+ 'Ħ': "H",
+ 'ħ': "h",
+ 'Ĩ': "~I",
+ 'ĩ': "~i",
+ 'Ī': "I",
+ 'ī': "i",
+ 'Ĭ': "I",
+ 'ĭ': "i",
+ 'Į': "I",
+ 'į': "i",
+ 'İ': "I",
+ 'ı': "i",
+ 'IJ': "IJ",
+ 'ij': "ij",
+ 'Ĵ': "^J",
+ 'ĵ': "^j",
+ 'Ķ': "K",
+ 'ķ': "k",
+ 'Ĺ': "L",
+ 'ĺ': "l",
+ 'Ļ': "L",
+ 'ļ': "l",
+ 'Ľ': "L",
+ 'ľ': "l",
+ 'Ŀ': "L",
+ 'ŀ': "l",
+ 'Ł': "L",
+ 'ł': "l",
+ 'Ń': "'N",
+ 'ń': "'n",
+ 'Ņ': "N",
+ 'ņ': "n",
+ 'Ň': "N",
+ 'ň': "n",
+ 'ʼn': "'n",
+ 'Ō': "O",
+ 'ō': "o",
+ 'Ŏ': "O",
+ 'ŏ': "o",
+ 'Ő': '"O',
+ 'ő': '"o',
+ 'Œ': "OE",
+ 'œ': "oe",
+ 'Ŕ': "'R",
+ 'ŕ': "'r",
+ 'Ŗ': "R",
+ 'ŗ': "r",
+ 'Ř': "R",
+ 'ř': "r",
+ 'Ś': "'S",
+ 'ś': "'s",
+ 'Ŝ': "^S",
+ 'ŝ': "^s",
+ 'Ş': "S",
+ 'ş': "s",
+ 'Š': "S",
+ 'š': "s",
+ 'Ţ': "T",
+ 'ţ': "t",
+ 'Ť': "T",
+ 'ť': "t",
+ 'Ŧ': "T",
+ 'ŧ': "t",
+ 'Ũ': "~U",
+ 'ũ': "~u",
+ 'Ū': "U",
+ 'ū': "u",
+ 'Ŭ': "U",
+ 'ŭ': "u",
+ 'Ů': "U",
+ 'ů': "u",
+ 'Ű': '"U',
+ 'ű': '"u',
+ 'Ų': "U",
+ 'ų': "u",
+ 'Ŵ': "^W",
+ 'ŵ': "^w",
+ 'Ŷ': "^Y",
+ 'ŷ': "^y",
+ 'Ÿ': '"Y',
+ 'Ź': "'Z",
+ 'ź': "'z",
+ 'Ż': "Z",
+ 'ż': "z",
+ 'Ž': "Z",
+ 'ž': "z",
+ 'ſ': "s"
+ };
+
+ function _slugify(s) {
+ if (!s) return "";
+ var ascii = [];
+ var ch, cp;
+ for (var i = 0; i < s.length; i++) {
+ if ((cp = s.charCodeAt(i)) < 0x180) {
+ ch = String.fromCharCode(cp);
+ ascii.push(charmap[ch] || ch);
+ }
+ }
+ s = ascii.join("");
+ s = s.replace(/[^\w\s-]/g, "").trim().toLowerCase();
+ return s.replace(/[-\s]+/g, "-");
+ }
+
+ mod.factory("Slug", function() {
+ return {
+ slugify: _slugify
+ };
+ });
+
+ mod.directive("slug", ["Slug", function(Slug) {
+ return {
+ restrict: "E",
+ scope: {
+ to: "=",
+ },
+ transclude: true,
+ replace: true,
+ template: "<div ng-transclude></div>",
+ link: function(scope, elem, attrs) {
+ if (!attrs.from) {
+ throw "must set attribute 'from'";
+ }
+ scope.$parent.$watch(attrs.from, function(val) {
+ scope.to = Slug.slugify(val);
+ });
+ }
+ };
+ }]);
+
+ mod.filter("slugify", function(Slug) {
+ return function(input) {
+ return Slug.slugify(input);
+ };
+ });
+})();
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/modernizr.custom.27682.js b/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/modernizr.custom.27682.js
new file mode 100644
index 0000000..d34873a
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/modernizr.custom.27682.js
@@ -0,0 +1,4 @@
+/* Modernizr 2.6.3 (Custom Build) | MIT & BSD
+ * Build: http://modernizr.com/download/#-flexbox-cssclasses-testprop-testallprops-domprefixes
+ */
+;window.Modernizr=function(a,b,c){function x(a){j.cssText=a}function y(a,b){return x(prefixes.join(a+";")+(b||""))}function z(a,b){return typeof a===b}function A(a,b){return!!~(""+a).indexOf(b)}function B(a,b){for(var d in a){var e=a[d];if(!A(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function C(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:z(f,"function")?f.bind(d||b):f}return!1}function D(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+n.join(d+" ")+d).split(" ");return z(b,"string")||z(b,"undefined")?B(e,b):(e=(a+" "+o.join(d+" ")+d).split(" "),C(e,b,c))}var d="2.6.3",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k,l={}.toString,m="Webkit Moz O ms",n=m.split(" "),o=m.toLowerCase().split(" "),p={},q={},r={},s=[],t=s.slice,u,v={}.hasOwnProperty,w;!z(v,"undefined")&&!z(v.call,"undefined")?w=function(a,b){return v.call(a,b)}:w=function(a,b){return b in a&&z(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=t.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(t.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(t.call(arguments)))};return e}),p.flexbox=function(){return D("flexWrap")};for(var E in p)w(p,E)&&(u=E.toLowerCase(),e[u]=p[E](),s.push((e[u]?"":"no-")+u));return e.addTest=function(a,b){if(typeof a=="object")for(var d in a)w(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},x(""),i=k=null,e._version=d,e._domPrefixes=o,e._cssomPrefixes=n,e.testProp=function(a){return B([a])},e.testAllProps=D,g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+s.join(" "):""),e}(this,this.document);
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/ui-bootstrap-custom-tpls-0.4.0.js b/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/ui-bootstrap-custom-tpls-0.4.0.js
new file mode 100644
index 0000000..d4a44fe
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/main/webapp/vendor/ui-bootstrap-custom-tpls-0.4.0.js
@@ -0,0 +1,447 @@
+angular.module("ui.bootstrap", ["ui.bootstrap.tpls", "ui.bootstrap.buttons","ui.bootstrap.transition","ui.bootstrap.dialog"]);
+angular.module("ui.bootstrap.tpls", ["template/dialog/message.html"]);
+angular.module('ui.bootstrap.buttons', [])
+
+ .constant('buttonConfig', {
+ activeClass:'active',
+ toggleEvent:'click'
+ })
+
+ .directive('btnRadio', ['buttonConfig', function (buttonConfig) {
+ var activeClass = buttonConfig.activeClass || 'active';
+ var toggleEvent = buttonConfig.toggleEvent || 'click';
+
+ return {
+
+ require:'ngModel',
+ link:function (scope, element, attrs, ngModelCtrl) {
+
+ //model -> UI
+ ngModelCtrl.$render = function () {
+ element.toggleClass(activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio)));
+ };
+
+ //ui->model
+ element.bind(toggleEvent, function () {
+ if (!element.hasClass(activeClass)) {
+ scope.$apply(function () {
+ ngModelCtrl.$setViewValue(scope.$eval(attrs.btnRadio));
+ ngModelCtrl.$render();
+ });
+ }
+ });
+ }
+ };
+}])
+
+ .directive('btnCheckbox', ['buttonConfig', function (buttonConfig) {
+
+ var activeClass = buttonConfig.activeClass || 'active';
+ var toggleEvent = buttonConfig.toggleEvent || 'click';
+
+ return {
+ require:'ngModel',
+ link:function (scope, element, attrs, ngModelCtrl) {
+
+ var trueValue = scope.$eval(attrs.btnCheckboxTrue);
+ var falseValue = scope.$eval(attrs.btnCheckboxFalse);
+
+ trueValue = angular.isDefined(trueValue) ? trueValue : true;
+ falseValue = angular.isDefined(falseValue) ? falseValue : false;
+
+ //model -> UI
+ ngModelCtrl.$render = function () {
+ element.toggleClass(activeClass, angular.equals(ngModelCtrl.$modelValue, trueValue));
+ };
+
+ //ui->model
+ element.bind(toggleEvent, function () {
+ scope.$apply(function () {
+ ngModelCtrl.$setViewValue(element.hasClass(activeClass) ? falseValue : trueValue);
+ ngModelCtrl.$render();
+ });
+ });
+ }
+ };
+}]);
+angular.module('ui.bootstrap.transition', [])
+
+/**
+ * $transition service provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete.
+ * @param {DOMElement} element The DOMElement that will be animated.
+ * @param {string|object|function} trigger The thing that will cause the transition to start:
+ * - As a string, it represents the css class to be added to the element.
+ * - As an object, it represents a hash of style attributes to be applied to the element.
+ * - As a function, it represents a function to be called that will cause the transition to occur.
+ * @return {Promise} A promise that is resolved when the transition finishes.
+ */
+.factory('$transition', ['$q', '$timeout', '$rootScope', function($q, $timeout, $rootScope) {
+
+ var $transition = function(element, trigger, options) {
+ options = options || {};
+ var deferred = $q.defer();
+ var endEventName = $transition[options.animation ? "animationEndEventName" : "transitionEndEventName"];
+
+ var transitionEndHandler = function(event) {
+ $rootScope.$apply(function() {
+ element.unbind(endEventName, transitionEndHandler);
+ deferred.resolve(element);
+ });
+ };
+
+ if (endEventName) {
+ element.bind(endEventName, transitionEndHandler);
+ }
+
+ // Wrap in a timeout to allow the browser time to update the DOM before the transition is to occur
+ $timeout(function() {
+ if ( angular.isString(trigger) ) {
+ element.addClass(trigger);
+ } else if ( angular.isFunction(trigger) ) {
+ trigger(element);
+ } else if ( angular.isObject(trigger) ) {
+ element.css(trigger);
+ }
+ //If browser does not support transitions, instantly resolve
+ if ( !endEventName ) {
+ deferred.resolve(element);
+ }
+ });
+
+ // Add our custom cancel function to the promise that is returned
+ // We can call this if we are about to run a new transition, which we know will prevent this transition from ending,
+ // i.e. it will therefore never raise a transitionEnd event for that transition
+ deferred.promise.cancel = function() {
+ if ( endEventName ) {
+ element.unbind(endEventName, transitionEndHandler);
+ }
+ deferred.reject('Transition cancelled');
+ };
+
+ return deferred.promise;
+ };
+
+ // Work out the name of the transitionEnd event
+ var transElement = document.createElement('trans');
+ var transitionEndEventNames = {
+ 'WebkitTransition': 'webkitTransitionEnd',
+ 'MozTransition': 'transitionend',
+ 'OTransition': 'oTransitionEnd',
+ 'transition': 'transitionend'
+ };
+ var animationEndEventNames = {
+ 'WebkitTransition': 'webkitAnimationEnd',
+ 'MozTransition': 'animationend',
+ 'OTransition': 'oAnimationEnd',
+ 'transition': 'animationend'
+ };
+ function findEndEventName(endEventNames) {
+ for (var name in endEventNames){
+ if (transElement.style[name] !== undefined) {
+ return endEventNames[name];
+ }
+ }
+ }
+ $transition.transitionEndEventName = findEndEventName(transitionEndEventNames);
+ $transition.animationEndEventName = findEndEventName(animationEndEventNames);
+ return $transition;
+}]);
+
+// The `$dialogProvider` can be used to configure global defaults for your
+// `$dialog` service.
+var dialogModule = angular.module('ui.bootstrap.dialog', ['ui.bootstrap.transition']);
+
+dialogModule.controller('MessageBoxController', ['$scope', 'dialog', 'model', function($scope, dialog, model){
+ $scope.title = model.title;
+ $scope.message = model.message;
+ $scope.buttons = model.buttons;
+ $scope.close = function(res){
+ dialog.close(res);
+ };
+}]);
+
+dialogModule.provider("$dialog", function(){
+
+ // The default options for all dialogs.
+ var defaults = {
+ backdrop: true,
+ dialogClass: 'modal',
+ backdropClass: 'modal-backdrop',
+ transitionClass: 'fade',
+ triggerClass: 'in',
+ resolve:{},
+ backdropFade: false,
+ dialogFade:false,
+ keyboard: true, // close with esc key
+ backdropClick: true // only in conjunction with backdrop=true
+ /* other options: template, templateUrl, controller */
+ };
+
+ var globalOptions = {};
+
+ var activeBackdrops = {value : 0};
+
+ // The `options({})` allows global configuration of all dialogs in the application.
+ //
+ // var app = angular.module('App', ['ui.bootstrap.dialog'], function($dialogProvider){
+ // // don't close dialog when backdrop is clicked by default
+ // $dialogProvider.options({backdropClick: false});
+ // });
+ this.options = function(value){
+ globalOptions = value;
+ };
+
+ // Returns the actual `$dialog` service that is injected in controllers
+ this.$get = ["$http", "$document", "$compile", "$rootScope", "$controller", "$templateCache", "$q", "$transition", "$injector",
+ function ($http, $document, $compile, $rootScope, $controller, $templateCache, $q, $transition, $injector) {
+
+ var body = $document.find('body');
+
+ function createElement(clazz) {
+ var el = angular.element("<div>");
+ el.addClass(clazz);
+ return el;
+ }
+
+ // The `Dialog` class represents a modal dialog. The dialog class can be invoked by providing an options object
+ // containing at lest template or templateUrl and controller:
+ //
+ // var d = new Dialog({templateUrl: 'foo.html', controller: 'BarController'});
+ //
+ // Dialogs can also be created using templateUrl and controller as distinct arguments:
+ //
+ // var d = new Dialog('path/to/dialog.html', MyDialogController);
+ function Dialog(opts) {
+
+ var self = this, options = this.options = angular.extend({}, defaults, globalOptions, opts);
+ this._open = false;
+
+ this.backdropEl = createElement(options.backdropClass);
+ if(options.backdropFade){
+ this.backdropEl.addClass(options.transitionClass);
+ this.backdropEl.removeClass(options.triggerClass);
+ }
+
+ this.modalEl = createElement(options.dialogClass);
+ if(options.dialogFade){
+ this.modalEl.addClass(options.transitionClass);
+ this.modalEl.removeClass(options.triggerClass);
+ }
+
+ this.handledEscapeKey = function(e) {
+ if (e.which === 27) {
+ self.close();
+ e.preventDefault();
+ self.$scope.$apply();
+ }
+ };
+
+ this.handleBackDropClick = function(e) {
+ self.close();
+ e.preventDefault();
+ self.$scope.$apply();
+ };
+
+ this.handleLocationChange = function() {
+ self.close();
+ };
+ }
+
+ // The `isOpen()` method returns wether the dialog is currently visible.
+ Dialog.prototype.isOpen = function(){
+ return this._open;
+ };
+
+ // The `open(templateUrl, controller)` method opens the dialog.
+ // Use the `templateUrl` and `controller` arguments if specifying them at dialog creation time is not desired.
+ Dialog.prototype.open = function(templateUrl, controller){
+ var self = this, options = this.options;
+
+ if(templateUrl){
+ options.templateUrl = templateUrl;
+ }
+ if(controller){
+ options.controller = controller;
+ }
+
+ if(!(options.template || options.templateUrl)) {
+ throw new Error('Dialog.open expected template or templateUrl, neither found. Use options or open method to specify them.');
+ }
+
+ this._loadResolves().then(function(locals) {
+ var $scope = locals.$scope = self.$scope = locals.$scope ? locals.$scope : $rootScope.$new();
+
+ self.modalEl.html(locals.$template);
+
+ if (self.options.controller) {
+ var ctrl = $controller(self.options.controller, locals);
+ self.modalEl.children().data('ngControllerController', ctrl);
+ }
+
+ $compile(self.modalEl)($scope);
+ self._addElementsToDom();
+
+ // trigger tranisitions
+ setTimeout(function(){
+ if(self.options.dialogFade){ self.modalEl.addClass(self.options.triggerClass); }
+ if(self.options.backdropFade){ self.backdropEl.addClass(self.options.triggerClass); }
+ });
+
+ self._bindEvents();
+ });
+
+ this.deferred = $q.defer();
+ return this.deferred.promise;
+ };
+
+ // closes the dialog and resolves the promise returned by the `open` method with the specified result.
+ Dialog.prototype.close = function(result){
+ var self = this;
+ var fadingElements = this._getFadingElements();
+
+ if(fadingElements.length > 0){
+ for (var i = fadingElements.length - 1; i >= 0; i--) {
+ $transition(fadingElements[i], removeTriggerClass).then(onCloseComplete);
+ }
+ return;
+ }
+
+ this._onCloseComplete(result);
+
+ function removeTriggerClass(el){
+ el.removeClass(self.options.triggerClass);
+ }
+
+ function onCloseComplete(){
+ if(self._open){
+ self._onCloseComplete(result);
+ }
+ }
+ };
+
+ Dialog.prototype._getFadingElements = function(){
+ var elements = [];
+ if(this.options.dialogFade){
+ elements.push(this.modalEl);
+ }
+ if(this.options.backdropFade){
+ elements.push(this.backdropEl);
+ }
+
+ return elements;
+ };
+
+ Dialog.prototype._bindEvents = function() {
+ if(this.options.keyboard){ body.bind('keydown', this.handledEscapeKey); }
+ if(this.options.backdrop && this.options.backdropClick){ this.backdropEl.bind('click', this.handleBackDropClick); }
+ };
+
+ Dialog.prototype._unbindEvents = function() {
+ if(this.options.keyboard){ body.unbind('keydown', this.handledEscapeKey); }
+ if(this.options.backdrop && this.options.backdropClick){ this.backdropEl.unbind('click', this.handleBackDropClick); }
+ };
+
+ Dialog.prototype._onCloseComplete = function(result) {
+ this._removeElementsFromDom();
+ this._unbindEvents();
+
+ this.deferred.resolve(result);
+ };
+
+ Dialog.prototype._addElementsToDom = function(){
+ body.append(this.modalEl);
+
+ if(this.options.backdrop) {
+ if (activeBackdrops.value === 0) {
+ body.append(this.backdropEl);
+ }
+ activeBackdrops.value++;
+ }
+
+ this._open = true;
+ };
+
+ Dialog.prototype._removeElementsFromDom = function(){
+ this.modalEl.remove();
+
+ if(this.options.backdrop) {
+ activeBackdrops.value--;
+ if (activeBackdrops.value === 0) {
+ this.backdropEl.remove();
+ }
+ }
+ this._open = false;
+ };
+
+ // Loads all `options.resolve` members to be used as locals for the controller associated with the dialog.
+ Dialog.prototype._loadResolves = function(){
+ var values = [], keys = [], templatePromise, self = this;
+
+ if (this.options.template) {
+ templatePromise = $q.when(this.options.template);
+ } else if (this.options.templateUrl) {
+ templatePromise = $http.get(this.options.templateUrl, {cache:$templateCache})
+ .then(function(response) { return response.data; });
+ }
+
+ angular.forEach(this.options.resolve || [], function(value, key) {
+ keys.push(key);
+ values.push(angular.isString(value) ? $injector.get(value) : $injector.invoke(value));
+ });
+
+ keys.push('$template');
+ values.push(templatePromise);
+
+ return $q.all(values).then(function(values) {
+ var locals = {};
+ angular.forEach(values, function(value, index) {
+ locals[keys[index]] = value;
+ });
+ locals.dialog = self;
+ return locals;
+ });
+ };
+
+ // The actual `$dialog` service that is injected in controllers.
+ return {
+ // Creates a new `Dialog` with the specified options.
+ dialog: function(opts){
+ return new Dialog(opts);
+ },
+ // creates a new `Dialog` tied to the default message box template and controller.
+ //
+ // Arguments `title` and `message` are rendered in the modal header and body sections respectively.
+ // The `buttons` array holds an object with the following members for each button to include in the
+ // modal footer section:
+ //
+ // * `result`: the result to pass to the `close` method of the dialog when the button is clicked
+ // * `label`: the label of the button
+ // * `cssClass`: additional css class(es) to apply to the button for styling
+ messageBox: function(title, message, buttons){
+ return new Dialog({templateUrl: 'template/dialog/message.html', controller: 'MessageBoxController', resolve:
+ {model: function() {
+ return {
+ title: title,
+ message: message,
+ buttons: buttons
+ };
+ }
+ }});
+ }
+ };
+ }];
+});
+
+angular.module("template/dialog/message.html", []).run(["$templateCache", function($templateCache) {
+ $templateCache.put("template/dialog/message.html",
+ "<div class=\"modal-header\">\n" +
+ " <h1>{{ title }}</h1>\n" +
+ "</div>\n" +
+ "<div class=\"modal-body\">\n" +
+ " <p>{{ message }}</p>\n" +
+ "</div>\n" +
+ "<div class=\"modal-footer\">\n" +
+ " <button ng-repeat=\"btn in buttons\" ng-click=\"close(btn.result)\" class=btn ng-class=\"btn.cssClass\">{{ btn.label }}</button>\n" +
+ "</div>\n" +
+ "");
+}]);
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorViewTest.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorViewTest.java
new file mode 100644
index 0000000..fbb8d03
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/BuildMonitorViewTest.java
@@ -0,0 +1,45 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor;
+
+import hudson.util.FormValidation;
+import org.apache.commons.lang.StringEscapeUtils;
+import org.junit.Before;
+import org.junit.Test;
+
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.syntacticsugar.Loops.asFollows;
+import static hudson.util.FormValidation.Kind.*;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+
+public class BuildMonitorViewTest {
+
+ private BuildMonitorView.Descriptor validator;
+
+ @Before
+ public void setUp() throws Exception {
+ validator = new BuildMonitorView.Descriptor();
+ }
+
+ @Test
+ public void form_validator_should_allow_valid_reg_ex_specifying_what_jobs_to_include() {
+ for (String regex : asFollows(null, "", ".*", "myproject-.*")) {
+ assertThat(itShouldAllow(regex), validator.doCheckIncludeRegex(regex).kind, is(OK));
+ }
+ }
+
+ @Test
+ public void form_validator_should_advise_how_a_regex_could_be_improved() {
+ FormValidation result = validator.doCheckIncludeRegex(")");
+
+ assertThat(result.kind, is(ERROR));
+ assertThat(htmlDecoded(result.getMessage()), containsString("Unmatched closing ')'"));
+ }
+
+ private String htmlDecoded(String message) {
+ return StringEscapeUtils.unescapeHtml(message);
+ }
+
+ private String itShouldAllow(String regex) {
+ return "should allow " + regex;
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/BuildViewTest.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/BuildViewTest.java
new file mode 100644
index 0000000..109db63
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/BuildViewTest.java
@@ -0,0 +1,33 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.syntacticsugar.BuildStateRecipe;
+import hudson.model.AbstractBuild;
+import org.junit.Test;
+
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+
+public class BuildViewTest {
+
+ private static final String theName = "1.5+build.3";
+
+ private BuildViewModel view;
+
+
+ @Test
+ public void should_know_the_name_of_the_job_its_based_on() {
+ view = BuildView.of(aBuild(which().nameIs(theName)));
+
+ assertThat(view.name(), is(theName));
+ assertThat(view.toString(), is(theName));
+ }
+
+
+ private AbstractBuild<?, ?> aBuild(BuildStateRecipe recipe) {
+ return recipe.execute();
+ }
+
+ private BuildStateRecipe which() {
+ return new BuildStateRecipe();
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/JobViewTest.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/JobViewTest.java
new file mode 100644
index 0000000..406fb11
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/JobViewTest.java
@@ -0,0 +1,489 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.facade.RelativeLocation;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.Augmentation;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.BuildAugmentor;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.bfa.Analysis;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.claim.Claim;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.syntacticsugar.BuildStateRecipe;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.syntacticsugar.JobStateRecipe;
+import hudson.model.Job;
+import hudson.model.Result;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.syntacticsugar.Loops.asFollows;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.syntacticsugar.TimeMachine.assumeThat;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.syntacticsugar.TimeMachine.assumeThatCurrentTime;
+import static hudson.model.Result.*;
+import static org.hamcrest.CoreMatchers.hasItems;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.*;
+
+/**
+ * @author Jan Molak
+ */
+public class JobViewTest {
+
+ private static final String theName = "some-TLAs-followed-by-a-project-name";
+ private static final String displayName = "Pretty name that has some actual meaning";
+
+ private RelativeLocation relative = mock(RelativeLocation.class);
+ private JobView view;
+
+ /*
+ * By the way, if you were not aware of this: the configuration page of each job has an "Advanced Project Options"
+ * section, where you can set a user-friendly "Display Name"
+ */
+ @Test
+ public void delegates_the_process_of_determining_the_relative_job_name() {
+ when(relative.name()).thenReturn(theName);
+
+ view = JobView.of(a(job().withName(theName)), relative);
+
+ assertThat(view.name(), is(theName));
+ assertThat(view.toString(), is(theName));
+ verify(relative, times(2)).name();
+ }
+
+ @Test
+ public void delegates_the_process_of_determining_the_relative_url() {
+ String expectedUrl = "job/" + theName;
+ when(relative.url()).thenReturn(expectedUrl);
+
+ view = JobView.of(a(job().withName(theName).withDisplayName(displayName)), relative);
+
+ assertThat(view.url(), is(expectedUrl));
+ verify(relative, times(1)).url();
+ }
+
+ @Test
+ public void should_know_current_build_number() {
+ view = JobView.of(a(job().whereTheLast(build().numberIs(5))));
+
+ assertThat(view.lastBuildName(), is("#5"));
+ }
+
+ @Test
+ public void should_use_build_name_if_its_known() {
+ view = JobView.of(a(job().whereTheLast(build().nameIs("1.3.4+build.15"))));
+
+ assertThat(view.lastBuildName(), is("1.3.4+build.15"));
+ }
+
+ @Test
+ public void should_know_the_url_of_the_last_build() {
+ view = JobView.of(
+ a(job().whereTheLast(build().numberIs(22))),
+ locatedAt("job/project-name")
+ );
+
+ assertThat(view.lastBuildUrl(), is("job/project-name/22/"));
+ }
+
+ /*
+ * Should be able to measure the progress
+ */
+
+ @Test
+ public void progress_of_a_not_started_job_should_be_zero() {
+ view = JobView.of(a(job()));
+
+ assertThat(view.progress(), is(0));
+ }
+
+ @Test
+ public void progress_of_a_finished_job_should_be_zero() {
+ view = JobView.of(a(job().whereTheLast(build().finishedWith(SUCCESS))));
+
+ assertThat(view.progress(), is(0));
+ }
+
+ @Test
+ public void progress_of_a_nearly_finished_job_should_be_100() throws Exception {
+ view = JobView.of(
+ a(job().whereTheLast(build().isStillBuilding().startedAt("12:00:00").andUsuallyTakes(0))),
+ assumingThatCurrentTimeIs("12:00:00")
+ );
+
+ assertThat(view.progress(), is(100));
+ }
+
+ @Test
+ public void progress_of_a_job_thats_taking_longer_than_expected_should_be_100() throws Exception {
+ view = JobView.of(
+ a(job().whereTheLast(build().isStillBuilding().startedAt("12:00:00").andUsuallyTakes(5))),
+ assumingThatCurrentTimeIs("12:20:00")
+ );
+
+ assertThat(view.progress(), is(100));
+ }
+
+ @Test
+ public void should_calculate_the_progress_of_a_running_job() throws Exception {
+ view = JobView.of(
+ a(job().whereTheLast(build().isStillBuilding().startedAt("13:10:00").andUsuallyTakes(5))),
+ assumingThatCurrentTimeIs("13:11:00")
+ );
+
+ assertThat(view.progress(), is(20));
+ }
+
+ /*
+ * Elapsed time
+ */
+
+ @Test
+ public void should_know_how_long_a_build_has_been_running_for() throws Exception {
+
+ String startTime = "13:10:00",
+ sixSecondsLater = "13:10:06",
+ twoAndHalfMinutesLater = "13:12:30",
+ anHourAndHalfLater = "14:40:00";
+ Date currentTime = assumeThatCurrentTime().is(startTime);
+
+ view = JobView.of(
+ a(job().whereTheLast(build().startedAt(startTime).isStillBuilding())),
+ currentTime
+ );
+
+ assumeThat(currentTime).is(sixSecondsLater);
+ assertThat(view.lastBuildDuration(), is("6s"));
+
+ assumeThat(currentTime).is(twoAndHalfMinutesLater);
+ assertThat(view.lastBuildDuration(), is("2m 30s"));
+
+ assumeThat(currentTime).is(anHourAndHalfLater);
+ assertThat(view.lastBuildDuration(), is("1h 30m 0s"));
+ }
+
+ @Test
+ public void should_know_how_long_the_last_build_took_once_its_finished() throws Exception {
+ view = JobView.of(a(job().whereTheLast(build().finishedWith(SUCCESS).andTook(3))));
+
+ assertThat(view.lastBuildDuration(), is("3m 0s"));
+ }
+
+ @Test
+ public void should_not_say_anything_about_the_duration_if_the_build_hasnt_run_yet() throws Exception {
+ view = JobView.of(a(job()));
+
+ assertThat(view.lastBuildDuration(), is(""));
+ }
+
+ @Test
+ public void should_know_how_long_the_next_build_is_supposed_to_take() throws Exception {
+ view = JobView.of(a(job().whereTheLast(build().finishedWith(SUCCESS).andUsuallyTakes(5))));
+
+ assertThat(view.estimatedDuration(), is("5m 0s"));
+ }
+
+ @Test
+ public void should_not_say_anything_if_it_doesnt_know_how_long_the_next_build_is_supposed_to_take() throws Exception {
+ view = JobView.of(a(job()));
+
+ assertThat(view.estimatedDuration(), is(""));
+ }
+
+ /*
+ * Should produce a meaningful status description that can be used in the CSS
+ */
+
+ @Test
+ public void should_describe_the_job_as_successful_if_the_last_build_succeeded() {
+ view = JobView.of(a(job().whereTheLast(build().finishedWith(SUCCESS))));
+
+ assertThat(view.status(), containsString("successful"));
+ }
+
+ @Test
+ public void should_describe_the_job_as_failing_if_the_last_build_failed() {
+ for (Result result : asFollows(FAILURE, ABORTED)) {
+ view = JobView.of(a(job().whereTheLast(build().finishedWith(result))));
+
+ assertThat(view.status(), containsString("failing"));
+ }
+ }
+
+ @Test
+ public void should_describe_the_job_as_unstable_if_the_last_build_is_unstable() {
+ view = JobView.of(a(job().whereTheLast(build().finishedWith(UNSTABLE))));
+
+ assertThat(view.status(), containsString("unstable"));
+ }
+
+ @Test
+ public void should_describe_the_state_of_the_job_as_unknown_when_it_is_yet_to_be_determined() {
+ view = JobView.of(a(job()));
+
+ assertThat(view.status(), containsString("unknown"));
+ }
+
+ @Test
+ public void should_describe_the_job_as_running_if_it_is_running() {
+ List<JobView> views = asFollows(
+ JobView.of(a(job().whereTheLast(build().hasntStartedYet()))),
+ JobView.of(a(job().whereTheLast(build().isStillBuilding()))),
+ JobView.of(a(job().whereTheLast(build().isStillUpdatingTheLog())))
+ );
+
+ for (JobView view : views) {
+ assertThat(view.status(), containsString("running"));
+ }
+ }
+
+ @Test
+ public void should_describe_the_job_as_running_and_successful_if_it_is_running_and_the_previous_build_succeeded() {
+ List<JobView> views = asFollows(
+ JobView.of(a(job().
+ whereTheLast(build().hasntStartedYet()).
+ andThePrevious(build().finishedWith(SUCCESS)))),
+
+ JobView.of(a(job().
+ whereTheLast(build().isStillBuilding()).
+ andThePrevious(build().finishedWith(SUCCESS)))),
+
+ JobView.of(a(job().
+ whereTheLast(build().isStillUpdatingTheLog()).
+ andThePrevious(build().finishedWith(SUCCESS))))
+ );
+
+
+ // I could do this instead of having two assertions:
+ // assertThat(view.status(), both(containsString("successful")).and(containsString("running")));
+ // but then it would require Java 7
+
+ for (JobView view : views) {
+ assertThat(view.status(), containsString("successful"));
+ assertThat(view.status(), containsString("running"));
+ }
+ }
+
+ @Test
+ public void should_describe_the_job_as_running_and_failing_if_it_is_running_and_the_previous_build_failed() {
+ List<JobView> views = asFollows(
+ JobView.of(a(job().
+ whereTheLast(build().hasntStartedYet()).
+ andThePrevious(build().finishedWith(FAILURE)))),
+
+ JobView.of(a(job().
+ whereTheLast(build().isStillBuilding()).
+ andThePrevious(build().finishedWith(FAILURE)))),
+
+ JobView.of(a(job().
+ whereTheLast(build().isStillUpdatingTheLog()).
+ andThePrevious(build().finishedWith(FAILURE))))
+ );
+
+ for (JobView view : views) {
+ assertThat(view.status(), containsString("failing"));
+ assertThat(view.status(), containsString("running"));
+ }
+ }
+
+ /*
+ * Parallel build execution handling
+ */
+
+ @Test
+ public void should_describe_the_job_as_successful_when_there_are_several_builds_running_in_parallel_and_the_last_completed_was_successful() {
+ view = JobView.of(a(job().
+ whereTheLast(build().isStillBuilding()).
+ andThePrevious(build().isStillBuilding()).
+ andThePrevious(build().finishedWith(SUCCESS))));
+
+ assertThat(view.status(), containsString("successful"));
+ }
+
+ @Test
+ public void should_describe_the_job_as_failing_when_there_are_several_builds_running_in_parallel_and_the_last_completed_failed() {
+ view = JobView.of(a(job().
+ whereTheLast(build().isStillBuilding()).
+ andThePrevious(build().isStillBuilding()).
+ andThePrevious(build().finishedWith(FAILURE))));
+
+ assertThat(view.status(), containsString("failing"));
+ }
+
+ @Test
+ public void should_describe_the_job_as_claimed_if_someone_claimed_last_build_failures() {
+ view = JobView.of(
+ a(job().whereTheLast(build().finishedWith(FAILURE).andWasClaimedBy("Adam", "sorry, I broke it, fixing now"))),
+ augmentedWith(Claim.class)
+ );
+
+ assertThat(view.status(), containsString("claimed"));
+ }
+
+ /*
+ * Should know who broke the build
+ */
+
+ @Test
+ public void should_know_who_broke_the_build() {
+ view = JobView.of(a(job().whereTheLast(build().wasBrokenBy("Adam", "Ben"))));
+
+ assertThat(view.culprits(), hasSize(2));
+ assertThat(view.culprits(), hasItems("Adam", "Ben"));
+ }
+
+ @Test
+ public void should_know_who_has_been_committing_over_broken_build() {
+ view = JobView.of(a(job().
+ whereTheLast(build().wasBrokenBy("Adam")).
+ andThePrevious(build().wasBrokenBy("Ben", "Connor")).
+ andThePrevious(build().wasBrokenBy("Daniel")).
+ andThePrevious(build().succeededThanksTo("Errol"))));
+
+ assertThat(view.culprits(), hasSize(4));
+ assertThat(view.culprits(), hasItems("Adam", "Ben", "Connor", "Daniel"));
+ assertThat(view.culprits(), not(hasItem("Errol")));
+ }
+
+ @Test
+ public void should_only_mention_each_culprit_once() {
+ view = JobView.of(a(job().
+ whereTheLast(build().wasBrokenBy("Adam")).
+ andThePrevious(build().wasBrokenBy("Adam", "Ben")).
+ andThePrevious(build().wasBrokenBy("Ben", "Connor"))));
+
+ assertThat(view.culprits(), hasSize(3));
+ assertThat(view.culprits(), hasItems("Adam", "Ben", "Connor"));
+ }
+
+ @Test
+ public void should_not_mention_any_culprits_if_the_build_was_successful() {
+ view = JobView.of(a(job().whereTheLast(build().succeededThanksTo("Adam"))));
+
+ assertThat(view.culprits(), hasSize(0));
+ }
+
+ @Test
+ public void should_not_mention_any_culprits_if_the_build_was_successful_and_is_still_running() {
+ view = JobView.of(a(job().
+ whereTheLast(build().isStillBuilding()).
+ andThePrevious(build().succeededThanksTo("Adam"))));
+
+ assertThat(view.culprits(), hasSize(0));
+ }
+
+ @Test
+ public void should_indicate_culprits_if_the_build_is_failing_and_not_claimed() {
+ view = JobView.of(a(job().
+ whereTheLast(build().wasBrokenBy("Adam"))),
+ augmentedWith(Claim.class));
+
+ assertThat(view.shouldIndicateCulprits(), is(true));
+ assertThat(view.culprits(), hasSize(1));
+ }
+
+ @Test
+ public void should_not_indicate_any_culprits_if_the_build_was_failing_but_is_now_claimed() {
+ view = JobView.of(a(job().
+ whereTheLast(build().wasBrokenBy("Adam").andWasClaimedBy("Ben", "Helping out Adam"))),
+ augmentedWith(Claim.class));
+
+ assertThat(view.shouldIndicateCulprits(), is(false));
+ assertThat(view.culprits(), hasSize(1));
+ }
+
+ /*
+ * Should know who claimed a broken build
+ */
+
+ @Test
+ public void should_know_if_a_failing_build_has_been_claimed() throws Exception {
+ String ourPotentialHero = "Adam",
+ theReason = "I broke it, sorry, fixing now";
+
+ view = JobView.of(
+ a(job().whereTheLast(build().finishedWith(FAILURE).andWasClaimedBy(ourPotentialHero, theReason))),
+ augmentedWith(Claim.class)
+ );
+
+ assertThat(view.isClaimed(), is(true));
+ assertThat(view.claimAuthor(), is(ourPotentialHero));
+ assertThat(view.claimReason(), is(theReason));
+ }
+
+ @Test
+ public void should_describe_known_failures() {
+ String rogueAi = "Pod bay doors didn't open";
+
+ view = JobView.of(
+ a(job().whereTheLast(build().finishedWith(FAILURE).andKnownFailures(rogueAi))),
+ augmentedWith(Analysis.class));
+
+ assertThat(view.hasKnownFailures(), is(true));
+ assertThat(view.knownFailures(), contains(rogueAi));
+ }
+
+ @Test
+ public void public_api_should_return_reasonable_defaults_for_jobs_that_never_run() throws Exception {
+ view = JobView.of(a(job().thatHasNeverRun()));
+
+ assertThat(view.lastBuildName(), is(""));
+ assertThat(view.lastBuildUrl(), is(""));
+ assertThat(view.lastBuildDuration(), is(""));
+ assertThat(view.estimatedDuration(), is(""));
+ assertThat(view.progress(), is(0));
+ assertThat(view.shouldIndicateCulprits(), is(false));
+ assertThat(view.culprits(), hasSize(0));
+ assertThat(view.status(), is("unknown"));
+ assertThat(view.isClaimed(), is(false));
+ assertThat(view.hasKnownFailures(), is(false));
+ }
+
+ /*
+ * Syntactic sugar
+ */
+
+ private JobStateRecipe job() {
+ return new JobStateRecipe();
+ }
+
+ private Job<?, ?> a(JobStateRecipe recipe) {
+ return recipe.execute();
+ }
+
+ private BuildStateRecipe build() {
+ return new BuildStateRecipe();
+ }
+
+ private Date assumingThatCurrentTimeIs(String currentTime) throws ParseException {
+ Date currentDate = new SimpleDateFormat("H:m:s").parse(currentTime);
+
+ Date systemTime = mock(Date.class);
+ when(systemTime.getTime()).thenReturn(currentDate.getTime());
+
+ return systemTime;
+ }
+
+ private RelativeLocation locatedAt(String url) {
+
+ RelativeLocation location = mock(RelativeLocation.class);
+ when(location.url()).thenReturn(url);
+
+ return location;
+ }
+
+ private BuildAugmentor augmentedWith(Class<? extends Augmentation>... augmentationsToSupport) {
+ BuildAugmentor augmentor = new BuildAugmentor();
+
+ for (Class<? extends Augmentation> augmentation : augmentationsToSupport) {
+ augmentor.support(augmentation);
+ }
+
+ return augmentor;
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/BuildAugmentorTest.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/BuildAugmentorTest.java
new file mode 100644
index 0000000..3977015
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/BuildAugmentorTest.java
@@ -0,0 +1,86 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.bfa.Analysed;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.bfa.Analysis;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.bfa.NotAnalysed;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.claim.Claim;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.claim.Claimed;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.claim.NotClaimed;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.syntacticsugar.BuildStateRecipe;
+import hudson.model.Result;
+import hudson.model.Run;
+import org.hamcrest.Matchers;
+import org.junit.Test;
+
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+
+public class BuildAugmentorTest {
+
+ private static final String AUTHOR = "Adam";
+ private static final String REASON = "Sorry, I broke it, fixing now";
+ private static final String FLUX_CAPACITOR_FAILED_AGAIN = "Flux capacitor failed again";
+
+ private BuildAugmentor augmentor = new BuildAugmentor();
+
+ private Run<?, ?> plainBuild = a(build());
+ private Run<?, ?> claimedBuild = a(build().finishedWith(Result.FAILURE).andWasClaimedBy(AUTHOR, REASON));
+ private Run<?, ?> failedBuild = a(build().finishedWith(Result.FAILURE).andKnownFailures(FLUX_CAPACITOR_FAILED_AGAIN));
+
+ /*
+ * Claim tests
+ */
+
+ @Test
+ public void should_recognise_any_build_as_not_claimed_by_default() {
+ assertThat(augmentor.detailsOf(plainBuild, Claim.class), instanceOf(NotClaimed.class));
+ assertThat(augmentor.detailsOf(claimedBuild, Claim.class), instanceOf(NotClaimed.class));
+ }
+
+ @Test
+ public void should_recognise_a_claimed_build_once_you_ask_him_to_do_it() throws Exception {
+ augmentor.support(Claim.class);
+
+ Claim claim = augmentor.detailsOf(claimedBuild, Claim.class);
+
+ assertThat(claim, instanceOf(Claimed.class));
+
+ assertThat(claim.wasMade(), is(true));
+ assertThat(claim.author(), is(AUTHOR));
+ assertThat(claim.reason(), is(REASON));
+ }
+
+ /*
+ * Analysis tests
+ */
+ @Test
+ public void should_recognise_any_build_as_not_analysed_by_default() {
+ assertThat(augmentor.detailsOf(plainBuild, Analysis.class), instanceOf(NotAnalysed.class));
+ assertThat(augmentor.detailsOf(failedBuild, Analysis.class), instanceOf(NotAnalysed.class));
+ }
+
+ @Test
+ public void should_recognise_a_failed_build_once_you_ask_him_to_do_it() throws Exception {
+ augmentor.support(Analysis.class);
+
+ Analysis analysis = augmentor.detailsOf(failedBuild, Analysis.class);
+
+ assertThat(analysis, instanceOf(Analysed.class));
+
+ assertThat(analysis.foundKnownFailures(), is(true));
+ assertThat(analysis.failures(), Matchers.contains(FLUX_CAPACITOR_FAILED_AGAIN));
+ }
+
+ /*
+ * Syntactic sugar
+ */
+
+ private Run<?, ?> a(BuildStateRecipe recipe) {
+ return recipe.execute();
+ }
+
+ private BuildStateRecipe build() {
+ return new BuildStateRecipe();
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/bfa/AnalysedTest.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/bfa/AnalysedTest.java
new file mode 100644
index 0000000..3703be9
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/bfa/AnalysedTest.java
@@ -0,0 +1,47 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.bfa;
+
+import com.sonyericsson.jenkins.plugins.bfa.model.FailureCauseBuildAction;
+import com.sonyericsson.jenkins.plugins.bfa.model.FoundFailureCause;
+import org.hamcrest.Matchers;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class AnalysedTest {
+ private final static String FAILURE1_NAME = "JMS Server Down";
+ private final static String FAILURE2_NAME = "Unit test failures";
+
+ @Test
+ public void should_be_a_simple_proxy_to_the_claim_build_action() throws Exception {
+ Analysis analysis = new Analysed(failureCauseBuildAction(FAILURE1_NAME,FAILURE2_NAME));
+
+ assertThat(analysis.foundKnownFailures(), is(true));
+ assertThat(analysis.failures(), contains(FAILURE1_NAME, FAILURE2_NAME));
+ }
+
+ public static FailureCauseBuildAction failureCauseBuildAction(String... FailureNames) {
+ FailureCauseBuildAction action = mock(FailureCauseBuildAction.class);
+ List<FoundFailureCause> items = new ArrayList<FoundFailureCause>();
+ for( String name : FailureNames ) {
+ items.add(failure(name));
+ }
+ when(action.getFoundFailureCauses()).thenReturn(items);
+
+ return action;
+ }
+
+ private static FoundFailureCause failure(String name) {
+ FoundFailureCause failure = mock(FoundFailureCause.class);
+ when(failure.getName()).thenReturn(name);
+ return failure;
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/bfa/NotAnalysedTest.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/bfa/NotAnalysedTest.java
new file mode 100644
index 0000000..ed69454
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/bfa/NotAnalysedTest.java
@@ -0,0 +1,19 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.bfa;
+
+import org.junit.Test;
+
+import static org.hamcrest.Matchers.empty;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+
+public class NotAnalysedTest {
+ @Test
+ public void should_provide_sensible_defaults_if_the_build_has_no_known_failures_or_failure_plugin_is_not_installed() throws Exception {
+ Analysis analysis = new NotAnalysed();
+
+ assertThat(analysis.toString(), is("No known failures"));
+
+ assertThat(analysis.foundKnownFailures(), is(false));
+ assertThat(analysis.failures(), is(empty()));
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/claim/ClaimedTest.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/claim/ClaimedTest.java
new file mode 100644
index 0000000..b53ebb9
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/claim/ClaimedTest.java
@@ -0,0 +1,35 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.claim;
+
+import hudson.plugins.claim.ClaimBuildAction;
+import org.junit.Test;
+
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class ClaimedTest {
+ private final static String AUTHOR = "Adam";
+ private final static String REASON = "I broke it, sorry, fixing now.";
+ private final static String EXPECTED_STRING_REPRESENTATION = String.format("Claimed by \"%s\": \"%s\"", AUTHOR, REASON);
+
+ @Test
+ public void should_be_a_simple_proxy_to_the_claim_build_action() throws Exception {
+ Claim claim = new Claimed(claimBuildAction(AUTHOR, REASON));
+
+ assertThat(claim.wasMade(), is(true));
+ assertThat(claim.author(), is(AUTHOR));
+ assertThat(claim.reason(), is(REASON));
+
+ assertThat(claim.toString(), is(EXPECTED_STRING_REPRESENTATION));
+ }
+
+ public static ClaimBuildAction claimBuildAction(String author, String reason) {
+ ClaimBuildAction action = mock(ClaimBuildAction.class);
+ when(action.isClaimed()).thenReturn(true);
+ when(action.getClaimedByName()).thenReturn(author);
+ when(action.getReason()).thenReturn(reason);
+
+ return action;
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/claim/NotClaimedTest.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/claim/NotClaimedTest.java
new file mode 100644
index 0000000..3f2cde1
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/plugins/claim/NotClaimedTest.java
@@ -0,0 +1,20 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.claim;
+
+import org.junit.Test;
+
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+
+public class NotClaimedTest {
+ @Test
+ public void should_provide_sensible_defaults_if_the_build_is_not_claimed_or_the_claim_plugin_is_not_installed() throws Exception {
+ Claim claim = new NotClaimed();
+
+ assertThat(claim.toString(), is("Not claimed"));
+
+ assertThat(claim.wasMade(), is(false));
+ assertThat(claim.author(), is(nullValue()));
+ assertThat(claim.reason(), is(nullValue()));
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/syntacticsugar/BuildStateRecipe.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/syntacticsugar/BuildStateRecipe.java
new file mode 100644
index 0000000..fa01619
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/syntacticsugar/BuildStateRecipe.java
@@ -0,0 +1,177 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.syntacticsugar;
+
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.bfa.AnalysedTest.failureCauseBuildAction;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.claim.ClaimedTest.claimBuildAction;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.sonyericsson.jenkins.plugins.bfa.model.FailureCauseBuildAction;
+
+import hudson.model.Result;
+import hudson.model.AbstractBuild;
+import hudson.model.AbstractProject;
+import hudson.model.User;
+import hudson.plugins.claim.ClaimBuildAction;
+import hudson.scm.ChangeLogSet;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * @author Jan Molak
+ */
+public class BuildStateRecipe {
+
+ private AbstractBuild build;
+
+ public BuildStateRecipe() {
+ build = mock(AbstractBuild.class);
+
+ AbstractProject<?, ?> parent = mock(AbstractProject.class);
+ when(build.getParent()).thenReturn(parent);
+ }
+
+ public BuildStateRecipe numberIs(int number) {
+ when(build.getNumber()).thenReturn(number);
+
+ // see hudson.model.Run::getDisplayName
+ return nameIs("#" + number);
+ }
+
+ public BuildStateRecipe nameIs(String name) {
+ when(build.getDisplayName()).thenReturn(name);
+
+ return this;
+ }
+
+ public BuildStateRecipe whichNumberIs(int number) {
+ return numberIs(number);
+ }
+
+ public BuildStateRecipe finishedWith(Result result) {
+ when(build.getResult()).thenReturn(result);
+
+ return this;
+ }
+
+ public BuildStateRecipe withChangesFrom(String... authors) {
+ ChangeLogSet changeSet = changeSetBasedOn(entriesBy(authors));
+ when(build.getChangeSet()).thenReturn(changeSet);
+
+ // any methods that use getChangeSet as their source of data should be called normally
+ // (build is a partial mock in this case)
+ when(build.getCulprits()).thenCallRealMethod();
+
+ return this;
+ }
+
+ public BuildStateRecipe succeededThanksTo(String... authors) {
+ finishedWith(Result.SUCCESS);
+ withChangesFrom(authors);
+
+ return this;
+ }
+
+ public BuildStateRecipe wasBrokenBy(String... culprits) {
+ finishedWith(Result.FAILURE);
+ withChangesFrom(culprits);
+
+ return this;
+ }
+
+ public BuildStateRecipe hasntStartedYet() {
+ when(build.hasntStartedYet()).thenReturn(true);
+
+ return this;
+ }
+
+ public BuildStateRecipe isStillBuilding() {
+ when(build.isBuilding()).thenReturn(true);
+
+ return this;
+ }
+
+ public BuildStateRecipe isStillUpdatingTheLog() {
+ when(build.isLogUpdated()).thenReturn(true);
+
+ return this;
+ }
+
+ public BuildStateRecipe startedAt(String time) throws Exception {
+ long startedAt = new SimpleDateFormat("H:m:s").parse(time).getTime();
+
+ Calendar timestamp = mock(Calendar.class);
+ when(build.getTimestamp()).thenReturn(timestamp);
+
+ when(timestamp.getTimeInMillis()).thenReturn(startedAt);
+
+ return this;
+ }
+
+ public BuildStateRecipe andTook(int minutes) throws Exception {
+ long duration = (long) minutes * 60 * 1000;
+
+ when(build.getDuration()).thenReturn(duration);
+
+ return this;
+ }
+
+ public BuildStateRecipe andUsuallyTakes(int minutes) throws Exception {
+ long duration = (long) minutes * 60 * 1000;
+
+ when(build.getEstimatedDuration()).thenReturn(duration);
+
+ return this;
+ }
+
+ public BuildStateRecipe andWasClaimedBy(String aPotentialHero, String reason) {
+ final ClaimBuildAction action = claimBuildAction(aPotentialHero, reason);
+ when(build.getAction(ClaimBuildAction.class)).thenReturn(action);
+
+ return this;
+ }
+
+ public BuildStateRecipe andKnownFailures(String... failures) {
+ final FailureCauseBuildAction action = failureCauseBuildAction(failures);
+ when(build.getAction(FailureCauseBuildAction.class)).thenReturn(action);
+
+ return this;
+ }
+
+ public AbstractBuild execute() {
+ return build;
+ }
+
+
+ private List<ChangeLogSet.Entry> entriesBy(String... authors) {
+ List<ChangeLogSet.Entry> entries = new ArrayList<ChangeLogSet.Entry>();
+
+ for (String name : authors) {
+ User author = mock(User.class);
+ ChangeLogSet.Entry entry = mock(ChangeLogSet.Entry.class);
+
+ when(author.getFullName()).thenReturn(name);
+ when(entry.getAuthor()).thenReturn(author);
+
+ entries.add(entry);
+ }
+ return entries;
+ }
+
+ private ChangeLogSet changeSetBasedOn(final List<ChangeLogSet.Entry> entries) {
+ return new ChangeLogSet<ChangeLogSet.Entry>(null) {
+ @Override
+ public boolean isEmptySet() {
+ return false;
+ }
+
+ @Override
+ public Iterator<Entry> iterator() {
+ return entries.iterator();
+ }
+ };
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/syntacticsugar/JobStateRecipe.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/syntacticsugar/JobStateRecipe.java
new file mode 100644
index 0000000..b4bd1cc
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/syntacticsugar/JobStateRecipe.java
@@ -0,0 +1,98 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.syntacticsugar;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import hudson.model.ItemGroup;
+import hudson.model.AbstractBuild;
+import hudson.model.Job;
+
+import java.util.Stack;
+
+/**
+ * @author Jan Molak
+ */
+public class JobStateRecipe {
+ private Job job;
+ private Stack<AbstractBuild> buildHistory = new Stack<AbstractBuild>();
+
+ public JobStateRecipe() {
+ job = mock(Job.class);
+ }
+
+ public JobStateRecipe withName(String name) {
+ when(job.getName()).thenReturn(name);
+
+ // The name of the job also defines its URL, that's why the stub for getUrl() is defined here as
+ // well.
+ // You could argue, that 'withUrl' could be a separate method on the builder,
+ // but then this would allow for creation of impossible scenarios, such as:
+ // job.withName("a-name").withUrl("something completely different"), which leads nowhere.
+ return withShortUrl(name);
+ }
+
+ private JobStateRecipe withShortUrl(String url) {
+ when(job.getShortUrl()).thenReturn(url);
+
+ // This might not necessarily belong here,
+ // but I don't need to introduce the concept of a parent anywhere else yet.
+ ItemGroup parent = mock(ItemGroup.class);
+ when(parent.getUrl()).thenReturn("job/");
+ when(job.getParent()).thenReturn(parent);
+
+ return this;
+ }
+
+ public JobStateRecipe withDisplayName(String name) {
+ when(job.getDisplayNameOrNull()).thenReturn(name);
+ when(job.getDisplayName()).thenReturn(name);
+
+ return this;
+ }
+
+ public JobStateRecipe thatHasNeverRun() {
+ buildHistory.clear();
+
+ return this;
+ }
+
+ public JobStateRecipe whereTheLast(BuildStateRecipe recipe) {
+ return updatedWithOnlyOneHistoryEntryFor(recipe.execute());
+ }
+
+ public JobStateRecipe andThePrevious(BuildStateRecipe recipe) {
+ return updatedWithEarliestHistoryEntryFor(recipe.execute());
+ }
+
+ @SuppressWarnings("unchecked")
+ public Job<?, ?> execute() {
+ AbstractBuild earlierBuild, earliestBuild;
+
+ // link "previous" builds ...
+ while (buildHistory.size() > 1) {
+ earliestBuild = buildHistory.pop();
+ earlierBuild = buildHistory.peek();
+
+ when(earlierBuild.getPreviousBuild()).thenReturn(earliestBuild);
+ }
+
+ // pick the first build from the build history and make it the "last build"
+ if (buildHistory.size() == 1) {
+ when(job.getLastBuild()).thenReturn(buildHistory.pop());
+ }
+
+ return job;
+ }
+
+ private JobStateRecipe updatedWithEarliestHistoryEntryFor(AbstractBuild build) {
+ buildHistory.push(build);
+
+ return this;
+ }
+
+ private JobStateRecipe updatedWithOnlyOneHistoryEntryFor(AbstractBuild build) {
+ buildHistory.clear();
+
+ return updatedWithEarliestHistoryEntryFor(build);
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/syntacticsugar/Loops.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/syntacticsugar/Loops.java
new file mode 100644
index 0000000..e350c54
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/syntacticsugar/Loops.java
@@ -0,0 +1,14 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.syntacticsugar;
+
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * @author Jan Molak
+ */
+public class Loops {
+
+ public static <T> List<T> asFollows(T... examples) {
+ return Arrays.asList(examples);
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/syntacticsugar/TimeMachine.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/syntacticsugar/TimeMachine.java
new file mode 100644
index 0000000..6ec3843
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor/viewmodel/syntacticsugar/TimeMachine.java
@@ -0,0 +1,36 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.syntacticsugar;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * @author Jan Molak
+ */
+public class TimeMachine {
+ private Date systemTime;
+
+ public static TimeMachine assumeThatCurrentTime() {
+ return new TimeMachine(mock(Date.class));
+ }
+
+ public static TimeMachine assumeThat(Date currentTime) {
+ return new TimeMachine(currentTime);
+ }
+
+ public Date is(String currentTime) throws ParseException {
+ Date currentDate = new SimpleDateFormat("H:m:s").parse(currentTime);
+
+ when(this.systemTime.getTime()).thenReturn(currentDate.getTime());
+
+ return this.systemTime;
+ }
+
+
+ private TimeMachine(Date currentTime) {
+ this.systemTime = currentTime;
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/AcceptanceTest.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/AcceptanceTest.java
new file mode 100644
index 0000000..cb59bac
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/AcceptanceTest.java
@@ -0,0 +1,191 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance;
+
+import com.saucelabs.common.SauceOnDemandAuthentication;
+import com.saucelabs.common.SauceOnDemandSessionIdProvider;
+import com.saucelabs.junit.SauceOnDemandTestWatcher;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.buildmonitor.BuildMonitor;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.buildmonitor.Job;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.Scenario;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.utils.Typograph;
+import hudson.model.FreeStyleProject;
+import hudson.tasks.Builder;
+import hudson.tasks.Shell;
+import org.apache.commons.lang3.StringUtils;
+import org.hamcrest.Description;
+import org.hamcrest.Matcher;
+import org.hamcrest.TypeSafeDiagnosingMatcher;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.jvnet.hudson.test.JenkinsRule;
+import org.openqa.selenium.By;
+import org.openqa.selenium.Platform;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.chrome.ChromeDriver;
+import org.openqa.selenium.remote.BrowserType;
+import org.openqa.selenium.remote.DesiredCapabilities;
+import org.openqa.selenium.remote.RemoteWebDriver;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.concurrent.TimeUnit;
+
+abstract public class AcceptanceTest implements SauceOnDemandSessionIdProvider {
+ public SauceOnDemandAuthentication authentication = new SauceOnDemandAuthentication();
+
+ protected WebDriver browser;
+
+ private String sessionId;
+
+ protected Scenario given;
+
+ @Rule
+ public final JenkinsRule jenkins = new JenkinsRule();
+
+ @Rule
+ public TestName testName = new TestName();
+
+ @Rule
+ public SauceOnDemandTestWatcher resultReportingTestWatcher = new SauceOnDemandTestWatcher(this, authentication);
+
+ @Before
+ public void setUp() throws Exception {
+ if (shouldUseRemoteBrowser()) {
+ browser = sauceLabsBrowser();
+ sessionId = (((RemoteWebDriver) browser).getSessionId()).toString();
+ } else {
+ browser = localChromeBrowser();
+ sessionId = null; // so that SauceOnDemandTestWatcher doesn't try to report back to SauceLabs
+ }
+
+ browser.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
+
+ given = Scenario.using(jenkins, browser);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ browser.quit();
+ }
+
+
+ protected BuildMonitor buildMonitorView(String name) throws IOException {
+ browser.get(urlFor("view/" + name));
+
+ return new BuildMonitor(browser.findElement(By.className("build-monitor")));
+ }
+
+ protected Builder aPassingShellScript() {
+ return new Shell("exit 0");
+ }
+
+ protected Builder aFailingShellScript() {
+ return new Shell("exit 1");
+ }
+
+ protected String urlFor(String path) throws IOException {
+ return jenkins.getURL().toString() + path;
+ }
+
+
+ private boolean shouldUseRemoteBrowser() {
+ return StringUtils.isNotBlank(authentication.getUsername()) && StringUtils.isNotBlank(authentication.getAccessKey());
+ }
+
+ private WebDriver sauceLabsBrowser() throws MalformedURLException {
+ DesiredCapabilities capabilities = DesiredCapabilities.chrome();
+ capabilities.setCapability("platform", Platform.MAC);
+
+ capabilities.setCapability("version", readPropertyOrEnv("SELENIUM_VERSION", "34"));
+ capabilities.setCapability("platform", readPropertyOrEnv("SELENIUM_PLATFORM", "mac"));
+ capabilities.setCapability("browserName", readPropertyOrEnv("SELENIUM_BROWSER", BrowserType.CHROME));
+
+ capabilities.setCapability("name", fullTestName());
+
+ return new RemoteWebDriver(
+ new URL(String.format("http://%s:%s@%s:%s/wd/hub",
+ authentication.getUsername(),
+ authentication.getAccessKey(),
+ readPropertyOrEnv("SELENIUM_HOST", "localhost"),
+ readPropertyOrEnv("SELENIUM_PORT", "4445"))
+ ),
+ capabilities
+ );
+ }
+
+ private WebDriver localChromeBrowser() {
+ WebDriver driver = new ChromeDriver();
+
+ return driver;
+ }
+
+ private String fullTestName() {
+ return String.format("%s: %s",
+ Typograph.deCamelCase(this.getClass().getSimpleName()),
+ Typograph.de_snake_case(testName.getMethodName())
+ );
+ }
+
+ public String readPropertyOrEnv(String key, String defaultValue) {
+ String v = System.getProperty(key);
+ if (v == null) {
+ v = System.getenv(key);
+ }
+ if (v == null) {
+ v = defaultValue;
+ }
+
+ return v;
+ }
+
+ @Override
+ public String getSessionId() {
+ return sessionId;
+ }
+
+ protected Matcher<? super Job> isSuccessful() {
+ return new TypeSafeDiagnosingMatcher<Job>() {
+ @Override
+ public void describeTo(final Description description) {
+ description.appendText("status should be 'successful'");
+ }
+
+ @Override
+ protected boolean matchesSafely(final Job job, final Description mismatchDescription) {
+ mismatchDescription.appendText(" was ").appendValue(job.status());
+ return "successful".equalsIgnoreCase(job.status());
+ }
+ };
+ }
+
+ protected Matcher<? super Job> isFailing() {
+ return new TypeSafeDiagnosingMatcher<Job>() {
+ @Override
+ public void describeTo(final Description description) {
+ description.appendText("status should be 'failing'");
+ }
+
+ @Override
+ protected boolean matchesSafely(final Job job, final Description mismatchDescription) {
+ mismatchDescription.appendText(" was ").appendValue(job.status());
+ return "failing".equalsIgnoreCase(job.status());
+ }
+ };
+ }
+
+ protected Matcher<? super Job> isDisplayed() {
+ return new TypeSafeDiagnosingMatcher<Job>() {
+ @Override
+ public void describeTo(final Description description) {
+ description.appendText("should be displayed");
+ }
+
+ @Override
+ protected boolean matchesSafely(final Job job, final Description mismatchDescription) {
+ return null != job;
+ }
+ };
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/BehaviourWithBuildFailureAnalyserTest.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/BehaviourWithBuildFailureAnalyserTest.java
new file mode 100644
index 0000000..e5f5de0
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/BehaviourWithBuildFailureAnalyserTest.java
@@ -0,0 +1,35 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.recipes.With;
+import org.junit.Test;
+
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.prerequisites.FreestyleProjectExists.aFreestyleProject;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.tasks.CreateBuildMonitorView.createABuildMonitorView;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.tasks.ConfigureJobFilters.includesAllTheJobs;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.tasks.DefineBuildFailureCause.defineABuildFailureCause;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.Is.is;
+
+// @TODO: Work in progress
+public class BehaviourWithBuildFailureAnalyserTest extends AcceptanceTest {
+
+ @Test
+ @With(plugins = { "buildgraph-view-1.0.hpi", "git-1.5.0.hpi", "git-client-1.8.0.jpi" })
+ public void displays_potential_failure_cause_when_it_is_known() throws Exception {
+
+ given.I(
+ defineABuildFailureCause(
+ "Shell script failure",
+ "A shell script failure happened",
+ "Build step 'Execute shell' marked build as failure"
+ ),
+ createABuildMonitorView("Build Monitor").that(includesAllTheJobs())
+ ).
+
+ WhenIHave(aFreestyleProject("example-acceptance").configuredToRun(aFailingShellScript()).executed());
+
+ // then ...
+
+ assertThat(buildMonitorView("Build Monitor").job("example-acceptance").possibleFailureCause(), is("Shell script failure"));
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/BehaviourWithCloudbeesFoldersTest.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/BehaviourWithCloudbeesFoldersTest.java
new file mode 100644
index 0000000..103f7d0
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/BehaviourWithCloudbeesFoldersTest.java
@@ -0,0 +1,49 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.buildmonitor.BuildMonitor;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.recipes.With;
+import org.junit.Test;
+
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.prerequisites.FolderExists.aFolder;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.prerequisites.FreestyleProjectExists.aFreestyleProject;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.tasks.CreateBuildMonitorView.createABuildMonitorView;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.tasks.ConfigureJobFilters.includesAllTheJobs;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.tasks.ConfigureJobFilters.recursesInSubFolders;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+// @TODO: Work in progress
+public class BehaviourWithCloudbeesFoldersTest extends AcceptanceTest {
+
+ private BuildMonitor buildMonitor;
+
+ @Test
+ @With(plugins = {
+ "cloudbees-folder-4.2.3.hpi",
+ "buildgraph-view-1.0.hpi", "git-1.5.0.hpi", "git-client-1.8.0.jpi"
+ })
+ public void displays_jobs_nested_in_folders() throws Exception {
+
+ given.IHave(
+ aFreestyleProject("Deploy to QA"),
+ aFolder("Librarian Project").containing(
+ aFreestyleProject("Librarian Core"),
+ aFolder("Micro-services").containing(
+ aFreestyleProject("Indexer")
+ )
+ )
+ ).
+
+ WhenI(createABuildMonitorView("Search Services").that(
+ includesAllTheJobs(),
+ recursesInSubFolders()
+ ));
+
+ // then ...
+
+ buildMonitor = buildMonitorView("Search Services");
+
+ assertThat(buildMonitor.job("deploy-to-qa"), isDisplayed());
+ assertThat(buildMonitor.job("librarian-project-micro-services-indexer"), isDisplayed());
+ assertThat(buildMonitor.job("librarian-project-librarian-core"), isDisplayed());
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/OutOfTheBoxBehaviourTest.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/OutOfTheBoxBehaviourTest.java
new file mode 100644
index 0000000..c9dd4e6
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/OutOfTheBoxBehaviourTest.java
@@ -0,0 +1,35 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.buildmonitor.BuildMonitor;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.recipes.With;
+import org.junit.Test;
+
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.prerequisites.FreestyleProjectExists.aFreestyleProject;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.tasks.ConfigureJobFilters.includesAllTheJobs;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.tasks.CreateBuildMonitorView.createABuildMonitorView;
+import static org.junit.Assert.assertThat;
+
+// @TODO: Work in progress
+public class OutOfTheBoxBehaviourTest extends AcceptanceTest {
+
+ private BuildMonitor buildMonitor;
+
+ @Test
+ @With(plugins = { "buildgraph-view-1.0.hpi", "git-1.5.0.hpi", "git-client-1.8.0.jpi" })
+ public void correctly_displays_successful_and_failing_jobs() throws Exception {
+
+ given.IHave(
+ aFreestyleProject("example-build").configuredToRun(aPassingShellScript()).executed(),
+ aFreestyleProject("example-acceptance").configuredToRun(aFailingShellScript()).executed()
+ ).
+
+ WhenI(createABuildMonitorView("Build Monitor").that(includesAllTheJobs()));
+
+ // then ...
+
+ buildMonitor = buildMonitorView("Build Monitor");
+
+ assertThat(buildMonitor.job("example-build"), isSuccessful());
+ assertThat(buildMonitor.job("example-acceptance"), isFailing());
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/PageObject.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/PageObject.java
new file mode 100644
index 0000000..d71d4da
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/PageObject.java
@@ -0,0 +1,14 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects;
+
+import org.openqa.selenium.WebElement;
+
+/**
+ * @author Jan Molak
+ */
+public abstract class PageObject {
+ protected final WebElement root;
+
+ public PageObject(WebElement root) {
+ this.root = root;
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/Screen.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/Screen.java
new file mode 100644
index 0000000..af118a7
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/Screen.java
@@ -0,0 +1,8 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects;
+
+/**
+ * @author Jan Molak
+ */
+public interface Screen {
+ public String path();
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/bfa/FailureCauseManagement.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/bfa/FailureCauseManagement.java
new file mode 100644
index 0000000..559e54e
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/bfa/FailureCauseManagement.java
@@ -0,0 +1,23 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.bfa;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.Screen;
+import org.openqa.selenium.By;
+
+/**
+ * @author Jan Molak
+ */
+public class FailureCauseManagement implements Screen {
+
+ public static FailureCauseManagement screen() {
+ return new FailureCauseManagement();
+ }
+
+ @Override
+ public String path() {
+ return "/failure-cause-management/";
+ }
+
+ public By createNew() {
+ return By.linkText("Create new");
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/bfa/NewFailureCause.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/bfa/NewFailureCause.java
new file mode 100644
index 0000000..9ebac50
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/bfa/NewFailureCause.java
@@ -0,0 +1,42 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.bfa;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.Screen;
+import org.openqa.selenium.By;
+
+/**
+ * @author Jan Molak
+ */
+public class NewFailureCause implements Screen {
+ public static NewFailureCause screen() {
+ return new NewFailureCause();
+ }
+
+ public By name() {
+ return By.name("_.name");
+ }
+
+ public By description() {
+ return By.name("_.description");
+ }
+
+ public By save() {
+ return By.xpath("//button[text() = 'Save']");
+ }
+
+ public By addIndication() {
+ return By.xpath("//button[text() = 'Add Indication']");
+ }
+
+ public By buildLogIndication() {
+ return By.linkText("Build Log Indication");
+ }
+
+ public By pattern() {
+ return By.name("pattern");
+ }
+
+ @Override
+ public String path() {
+ return "failure-cause-management/new/";
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/buildmonitor/BuildMonitor.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/buildmonitor/BuildMonitor.java
new file mode 100644
index 0000000..8b29933
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/buildmonitor/BuildMonitor.java
@@ -0,0 +1,18 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.buildmonitor;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.PageObject;
+import org.openqa.selenium.By;
+import org.openqa.selenium.WebElement;
+
+/**
+ * @author Jan Molak
+ */
+public class BuildMonitor extends PageObject {
+ public BuildMonitor(WebElement root) {
+ super(root);
+ }
+
+ public Job job(String name) {
+ return new Job(root.findElement(By.id(name)));
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/buildmonitor/ConfigureBuildMonitor.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/buildmonitor/ConfigureBuildMonitor.java
new file mode 100644
index 0000000..07030e3
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/buildmonitor/ConfigureBuildMonitor.java
@@ -0,0 +1,44 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.buildmonitor;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.Screen;
+import org.openqa.selenium.By;
+
+/**
+ * @author Jan Molak
+ */
+public class ConfigureBuildMonitor implements Screen {
+ public static ConfigureBuildMonitor screen() {
+ return new ConfigureBuildMonitor("Build Monitor");
+ }
+
+ public static ConfigureBuildMonitor screen(String name) {
+ return new ConfigureBuildMonitor(name);
+ }
+
+ public By recurseInSubfolders() { return By.id("recurse"); }
+
+ public By useRegularExpressionToIncludeJobsIntoTheView() {
+ return By.name("useincluderegex");
+ }
+
+ public By regularExpression() {
+ return By.name("includeRegex");
+ }
+
+ public By OK() {
+ return By.xpath("//button[text() = 'OK']");
+ }
+
+ @Override
+ public String path() {
+ return "view/" + name + "/configure";
+ }
+
+
+ private final String name;
+
+ private ConfigureBuildMonitor(String name) {
+ this.name = name;
+ }
+
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/buildmonitor/Job.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/buildmonitor/Job.java
new file mode 100644
index 0000000..af1e4ed
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/buildmonitor/Job.java
@@ -0,0 +1,24 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.buildmonitor;
+
+import org.openqa.selenium.By;
+import org.openqa.selenium.WebElement;
+
+public class Job {
+ private final WebElement root;
+
+ public Job(WebElement root) {
+ this.root = root;
+ }
+
+ public String name() {
+ return root.findElement(By.tagName("h2")).getText();
+ }
+
+ public String status() {
+ return root.getAttribute("class");
+ }
+
+ public String possibleFailureCause() {
+ return root.findElement(By.className("failures")).getText();
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/jenkins/HomePage.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/jenkins/HomePage.java
new file mode 100644
index 0000000..7e2e0fe
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/jenkins/HomePage.java
@@ -0,0 +1,27 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.jenkins;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.Screen;
+import org.openqa.selenium.By;
+
+/**
+ * @author Jan Molak
+ */
+public class HomePage implements Screen {
+
+ @Override
+ public String path() {
+ return "/";
+ }
+
+ public Navigation navigation() {
+ return new Navigation();
+ }
+
+ public By newView() {
+ return By.linkText("+");
+ }
+
+ public static HomePage screen() {
+ return new HomePage();
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/jenkins/Navigation.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/jenkins/Navigation.java
new file mode 100644
index 0000000..761fbdb
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/jenkins/Navigation.java
@@ -0,0 +1,12 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.jenkins;
+
+import org.openqa.selenium.By;
+
+/**
+ * @author Jan Molak
+ */
+public class Navigation {
+ public By failureCauseManagement() {
+ return By.linkText("Failure Cause Management");
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/jenkins/NewView.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/jenkins/NewView.java
new file mode 100644
index 0000000..ebd7102
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/pageobjects/jenkins/NewView.java
@@ -0,0 +1,31 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.jenkins;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.Screen;
+import org.openqa.selenium.By;
+
+/**
+ * @author Jan Molak
+ */
+public class NewView implements Screen {
+
+ public static NewView screen() {
+ return new NewView();
+ }
+
+ public By name() {
+ return By.name("name");
+ }
+
+ public By mode(String name) {
+ return By.xpath(String.format("//label/*[text()='%s']/../../input", name));
+ }
+
+ public By OK() {
+ return By.xpath("//button[text() = 'OK']");
+ }
+
+ @Override
+ public String path() {
+ return "newView";
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/recipes/With.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/recipes/With.java
new file mode 100644
index 0000000..ef74a95
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/recipes/With.java
@@ -0,0 +1,88 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.recipes;
+
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
+ *
+ * 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.
+ */
+
+import org.apache.commons.io.FileUtils;
+import org.jvnet.hudson.test.HudsonTestCase;
+import org.jvnet.hudson.test.JenkinsRecipe;
+import org.jvnet.hudson.test.JenkinsRule;
+import org.jvnet.hudson.test.recipes.Recipe;
+
+import java.io.File;
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import java.net.URL;
+
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * Installs specified plugins before launching Jenkins
+ */
+@Documented
+@Recipe(With.RunnerImpl.class)
+@JenkinsRecipe(With.RuleRunnerImpl.class)
+@Target(METHOD)
+@Retention(RUNTIME)
+public @interface With {
+ String[] plugins();
+
+ class RunnerImpl extends Recipe.Runner<With> {
+ private With a;
+
+ @Override
+ public void setup(HudsonTestCase testCase, With recipe) throws Exception {
+ a = recipe;
+ testCase.useLocalPluginManager = true;
+ }
+
+ @Override
+ public void decorateHome(HudsonTestCase testCase, File home) throws Exception {
+ for(String plugin : a.plugins()) {
+ URL res = getClass().getClassLoader().getResource("plugins/" + plugin);
+ FileUtils.copyURLToFile(res, new File(home,"plugins/" + plugin));
+ }
+ }
+ }
+
+ class RuleRunnerImpl extends JenkinsRecipe.Runner<With> {
+ private With a;
+
+ @Override
+ public void setup(JenkinsRule jenkinsRule, With recipe) throws Exception {
+ a = recipe;
+ jenkinsRule.useLocalPluginManager = true;
+ }
+
+ @Override
+ public void decorateHome(JenkinsRule jenkinsRule, File home) throws Exception {
+ for(String plugin : a.plugins()) {
+ URL res = getClass().getClassLoader().getResource("plugins/" + plugin);
+ FileUtils.copyURLToFile(res, new File(home,"plugins/" + plugin));
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/Context.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/Context.java
new file mode 100644
index 0000000..d0380c2
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/Context.java
@@ -0,0 +1,35 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios;
+
+import com.cloudbees.hudson.plugins.folder.Folder;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.adapters.FolderAdapter;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.adapters.ProjectCreator;
+import hudson.model.FreeStyleProject;
+import hudson.tasks.Builder;
+
+import java.io.IOException;
+import java.util.List;
+
+public class Context {
+ private final ProjectCreator currentRoot;
+
+ public Context(ProjectCreator currentRoot) {
+ this.currentRoot = currentRoot;
+ }
+
+ public Context createFolder(String name) throws IOException {
+ Folder folder = currentRoot.createProject(Folder.class, name);
+ return new Context(new FolderAdapter(folder));
+ }
+
+ public Context createFreestyleProject(String name, List<Builder> builders, boolean shouldExecute) throws IOException {
+ FreeStyleProject project = currentRoot.createProject(FreeStyleProject.class, name);
+
+ project.getBuildersList().addAll(builders);
+
+ if (shouldExecute) {
+ project.scheduleBuild2(0);
+ }
+
+ return this;
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/Scenario.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/Scenario.java
new file mode 100644
index 0000000..ecdf507
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/Scenario.java
@@ -0,0 +1,49 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions.Action;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.adapters.JenkinsAdapter;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.prerequisites.Prerequisite;
+import org.jvnet.hudson.test.JenkinsRule;
+import org.openqa.selenium.WebDriver;
+
+import java.io.IOException;
+
+public class Scenario {
+ public static Scenario using(JenkinsRule jenkins, WebDriver browser) {
+ return new Scenario(jenkins, browser);
+ }
+
+ public Scenario WhenIHave(Prerequisite... prerequisites) throws IOException {
+ return IHave(prerequisites);
+ }
+
+ public Scenario IHave(Prerequisite... prerequisites) throws IOException {
+ Context currentContext = new Context(new JenkinsAdapter(jenkins.getInstance()));
+
+ for(Prerequisite prerequisite : prerequisites) {
+ currentContext = prerequisite.accept(currentContext);
+ }
+
+ return this;
+ }
+
+ public Scenario I(Action... plans) throws Exception {
+ return WhenI(plans);
+ }
+
+ public Scenario WhenI(Action... plans) throws Exception {
+ for(Action plan : plans) {
+ plan.executeUsing(jenkins, browser);
+ }
+
+ return this;
+ }
+
+ private JenkinsRule jenkins;
+ private WebDriver browser;
+
+ private Scenario(JenkinsRule jenkins, WebDriver browser) {
+ this.jenkins = jenkins;
+ this.browser = browser;
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/actions/Action.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/actions/Action.java
new file mode 100644
index 0000000..0888e6e
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/actions/Action.java
@@ -0,0 +1,8 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions;
+
+import org.jvnet.hudson.test.JenkinsRule;
+import org.openqa.selenium.WebDriver;
+
+public interface Action {
+ void executeUsing(JenkinsRule jenkins, WebDriver browser) throws Exception;
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/actions/Click.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/actions/Click.java
new file mode 100644
index 0000000..86b0c55
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/actions/Click.java
@@ -0,0 +1,23 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions;
+
+import org.openqa.selenium.By;
+import org.jvnet.hudson.test.JenkinsRule;
+import org.openqa.selenium.WebDriver;
+
+public class Click implements Action {
+ public static Action click(By what) {
+ return new Click(what);
+ }
+
+ @Override
+ public void executeUsing(JenkinsRule jenkins, WebDriver browser) throws Exception {
+ browser.findElement(what).click();
+ }
+
+
+ private final By what;
+
+ private Click(By what) {
+ this.what = what;
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/actions/Enter.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/actions/Enter.java
new file mode 100644
index 0000000..e1eda16
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/actions/Enter.java
@@ -0,0 +1,29 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions;
+
+import org.jvnet.hudson.test.JenkinsRule;
+import org.openqa.selenium.By;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebElement;
+
+public class Enter implements Action {
+ public static Action enter(String what, By where) {
+ return new Enter(what, where);
+ }
+
+ @Override
+ public void executeUsing(JenkinsRule jenkins, WebDriver browser) throws Exception {
+ WebElement element = browser.findElement(where);
+
+ element.clear();
+ element.sendKeys(what);
+ }
+
+
+ private final String what;
+ private final By where;
+
+ private Enter(String what, By where) {
+ this.what = what;
+ this.where = where;
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/actions/Navigate.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/actions/Navigate.java
new file mode 100644
index 0000000..7566c3f
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/actions/Navigate.java
@@ -0,0 +1,23 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.Screen;
+import org.jvnet.hudson.test.JenkinsRule;
+import org.openqa.selenium.WebDriver;
+
+public class Navigate implements Action {
+ public static Action navigateTo(Screen screen) {
+ return new Navigate(screen);
+ }
+
+ @Override
+ public void executeUsing(JenkinsRule jenkins, WebDriver browser) throws Exception {
+ browser.get(jenkins.getURL().toString() + screen.path());
+ }
+
+
+ private final Screen screen;
+
+ private Navigate(Screen screen) {
+ this.screen = screen;
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/adapters/FolderAdapter.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/adapters/FolderAdapter.java
new file mode 100644
index 0000000..9574df3
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/adapters/FolderAdapter.java
@@ -0,0 +1,19 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.adapters;
+
+import com.cloudbees.hudson.plugins.folder.Folder;
+import hudson.model.TopLevelItem;
+
+import java.io.IOException;
+
+public class FolderAdapter implements ProjectCreator {
+ private final Folder folder;
+
+ public FolderAdapter(Folder folder) {
+ this.folder = folder;
+ }
+
+ @Override
+ public <T extends TopLevelItem> T createProject(Class<T> type, String name) throws IOException {
+ return this.folder.createProject(type, name);
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/adapters/JenkinsAdapter.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/adapters/JenkinsAdapter.java
new file mode 100644
index 0000000..10b0a9c
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/adapters/JenkinsAdapter.java
@@ -0,0 +1,19 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.adapters;
+
+import hudson.model.TopLevelItem;
+import jenkins.model.Jenkins;
+
+import java.io.IOException;
+
+public class JenkinsAdapter implements ProjectCreator {
+ private final Jenkins jenkins;
+
+ public JenkinsAdapter(Jenkins jenkins) {
+ this.jenkins = jenkins;
+ }
+
+ @Override
+ public <T extends TopLevelItem> T createProject(Class<T> type, String name) throws IOException {
+ return jenkins.createProject(type, name);
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/adapters/ProjectCreator.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/adapters/ProjectCreator.java
new file mode 100644
index 0000000..b3168e9
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/adapters/ProjectCreator.java
@@ -0,0 +1,9 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.adapters;
+
+import hudson.model.TopLevelItem;
+
+import java.io.IOException;
+
+public interface ProjectCreator {
+ public <T extends TopLevelItem> T createProject(Class<T> type, String name) throws IOException;
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/prerequisites/FolderExists.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/prerequisites/FolderExists.java
new file mode 100644
index 0000000..2b3f737
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/prerequisites/FolderExists.java
@@ -0,0 +1,38 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.prerequisites;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.Context;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+
+public class FolderExists implements Prerequisite {
+
+ public static FolderExists aFolder(String name) {
+ return new FolderExists(name);
+ }
+
+ public Prerequisite containing(Prerequisite... prerequisites) {
+ this.prerequisites = Arrays.asList(prerequisites);
+
+ return this;
+ }
+
+ @Override
+ public Context accept(Context context) throws IOException {
+ Context currentContext = context.createFolder(name);
+
+ for(Prerequisite p : prerequisites) {
+ currentContext = p.accept(currentContext);
+ }
+
+ return currentContext;
+ }
+
+ private final String name;
+ private List<Prerequisite> prerequisites;
+
+ private FolderExists(String name) {
+ this.name = name;
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/prerequisites/FreestyleProjectExists.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/prerequisites/FreestyleProjectExists.java
new file mode 100644
index 0000000..908457a
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/prerequisites/FreestyleProjectExists.java
@@ -0,0 +1,44 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.prerequisites;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.Context;
+import hudson.tasks.Builder;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class FreestyleProjectExists implements Prerequisite {
+
+ public static FreestyleProjectExists aFreestyleProject(String name) {
+ return new FreestyleProjectExists(name);
+ }
+
+ public FreestyleProjectExists configuredToRun(Builder... builders) {
+ this.builders = Arrays.asList(builders);
+
+ return this;
+ }
+
+ public FreestyleProjectExists executed() {
+ shouldExecute = true;
+
+ return this;
+ }
+
+ @Override
+ public Context accept(Context context) throws IOException {
+ context.createFreestyleProject(name, builders, shouldExecute);
+
+ return context;
+ }
+
+ private final String name;
+
+ private boolean shouldExecute = false;
+ private List<Builder> builders = new ArrayList<Builder>();
+
+ private FreestyleProjectExists(String name) {
+ this.name = name;
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/prerequisites/Prerequisite.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/prerequisites/Prerequisite.java
new file mode 100644
index 0000000..9d785c1
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/prerequisites/Prerequisite.java
@@ -0,0 +1,9 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.prerequisites;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.Context;
+
+import java.io.IOException;
+
+public interface Prerequisite {
+ Context accept(Context context) throws IOException;
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/tasks/ConfigureJobFilters.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/tasks/ConfigureJobFilters.java
new file mode 100644
index 0000000..76428b6
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/tasks/ConfigureJobFilters.java
@@ -0,0 +1,44 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.tasks;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.buildmonitor.ConfigureBuildMonitor;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions.Action;
+import org.jvnet.hudson.test.JenkinsRule;
+import org.openqa.selenium.WebDriver;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions.Click.click;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions.Enter.enter;
+
+public class ConfigureJobFilters implements Action {
+
+ public static Action includesAllTheJobs() {
+ return new ConfigureJobFilters(new ArrayList<Action>() {{
+ ConfigureBuildMonitor configuration = ConfigureBuildMonitor.screen();
+
+ add(click(configuration.useRegularExpressionToIncludeJobsIntoTheView()));
+ add(enter(".*", configuration.regularExpression()));
+ }});
+ }
+
+ public static Action recursesInSubFolders() {
+ return new ConfigureJobFilters(new ArrayList<Action>() {{
+ add(click(ConfigureBuildMonitor.screen().recurseInSubfolders()));
+ }});
+ }
+
+ @Override
+ public void executeUsing(JenkinsRule jenkins, WebDriver browser) throws Exception {
+ for (Action action : actions) {
+ action.executeUsing(jenkins, browser);
+ }
+ }
+
+
+ private List<Action> actions = new ArrayList<Action>();
+
+ private ConfigureJobFilters(List<Action> actions) {
+ this.actions = actions;
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/tasks/CreateBuildMonitorView.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/tasks/CreateBuildMonitorView.java
new file mode 100644
index 0000000..65e2e8d
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/tasks/CreateBuildMonitorView.java
@@ -0,0 +1,51 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.tasks;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.buildmonitor.ConfigureBuildMonitor;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.jenkins.NewView;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions.Action;
+import org.jvnet.hudson.test.JenkinsRule;
+import org.openqa.selenium.WebDriver;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions.Click.click;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions.Enter.enter;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions.Navigate.navigateTo;
+
+public class CreateBuildMonitorView implements Action {
+
+ public static CreateBuildMonitorView createABuildMonitorView(String name) {
+ return new CreateBuildMonitorView(name);
+ }
+
+ public Action that(Action... configurationPlans) {
+ configurationPlan.addAll(Arrays.asList(configurationPlans));
+
+ return this;
+ }
+
+ @Override
+ public void executeUsing(JenkinsRule jenkins, WebDriver browser) throws Exception {
+ configurationPlan.add(click(ConfigureBuildMonitor.screen().OK()));
+
+ for(Action action : configurationPlan) {
+ action.executeUsing(jenkins, browser);
+ }
+ }
+
+
+ private List<Action> configurationPlan;
+
+ private CreateBuildMonitorView(final String name) {
+ this.configurationPlan = new ArrayList<Action>() {{
+ NewView newView = NewView.screen();
+
+ add(navigateTo(newView));
+ add(enter(name, newView.name()));
+ add(click(newView.mode("Build Monitor View")));
+ add(click(newView.OK()));
+ }};
+ }
+}
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/tasks/DefineBuildFailureCause.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/tasks/DefineBuildFailureCause.java
new file mode 100644
index 0000000..c450b8b
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/tasks/DefineBuildFailureCause.java
@@ -0,0 +1,58 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.tasks;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.bfa.FailureCauseManagement;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.bfa.NewFailureCause;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.jenkins.HomePage;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.pageobjects.jenkins.NewView;
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions.Action;
+import org.jvnet.hudson.test.JenkinsRule;
+import org.openqa.selenium.WebDriver;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions.Click.click;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions.Enter.enter;
+import static com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions.Navigate.navigateTo;
+
+public class DefineBuildFailureCause implements Action {
+
+ public static DefineBuildFailureCause defineABuildFailureCause(String name, String description, String pattern) {
+ return new DefineBuildFailureCause(name, description, pattern);
+ }
+
+ @Override
+ public void executeUsing(JenkinsRule jenkins, WebDriver browser) throws Exception {
+ for(Action action : configurationPlan) {
+ action.executeUsing(jenkins, browser);
+ }
+ }
+
+ private List<Action> configurationPlan;
+
+ private DefineBuildFailureCause(final String name, final String description, final String pattern) {
+ this.configurationPlan = new ArrayList<Action>() {{
+ HomePage homePage = HomePage.screen();
+
+ add(navigateTo(homePage));
+
+ add(click(homePage.navigation().failureCauseManagement()));
+
+ // transition
+
+ add(click(FailureCauseManagement.screen().createNew()));
+
+ // transition
+
+ NewFailureCause failureCause = NewFailureCause.screen();
+ add(enter(name, failureCause.name()));
+ add(enter(description, failureCause.description()));
+
+ add(click(failureCause.addIndication()));
+ add(click(failureCause.buildLogIndication()));
+ add(enter(pattern, failureCause.pattern()));
+
+ add(click(failureCause.save()));
+ }};
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/tasks/Task.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/tasks/Task.java
new file mode 100644
index 0000000..3de7b38
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/scenarios/tasks/Task.java
@@ -0,0 +1,24 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.tasks;
+
+import com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.scenarios.actions.Action;
+import org.jvnet.hudson.test.JenkinsRule;
+import org.openqa.selenium.WebDriver;
+
+import java.util.Arrays;
+import java.util.List;
+
+public class Task implements Action {
+
+ private List<Action> actions;
+
+ public Task(Action... actions) {
+ this.actions = Arrays.asList(actions);
+ }
+
+ @Override
+ public void executeUsing(JenkinsRule jenkins, WebDriver browser) throws Exception {
+ for(Action action : actions) {
+ action.executeUsing(jenkins, browser);
+ }
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/utils/Typograph.java b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/utils/Typograph.java
new file mode 100644
index 0000000..9c988d3
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/utils/Typograph.java
@@ -0,0 +1,21 @@
+package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.utils;
+
+/**
+ * @author Jan Molak
+ */
+public class Typograph {
+ public static String deCamelCase(String camelCasedString) {
+ return camelCasedString.replaceAll(
+ String.format("%s|%s|%s",
+ "(?<=[A-Z])(?=[A-Z][a-z])",
+ "(?<=[^A-Z])(?=[A-Z])",
+ "(?<=[A-Za-z])(?=[^A-Za-z])"
+ ),
+ " "
+ );
+ }
+
+ public static String de_snake_case(String snake_cased_string) {
+ return snake_cased_string.replaceAll("_", " ");
+ }
+}
diff --git a/java/jenkins_plugins/build_monitor/src/test/javascript/unit/cron/everySpec.js b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/cron/everySpec.js
new file mode 100644
index 0000000..94867ff
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/cron/everySpec.js
@@ -0,0 +1,200 @@
+describe('buildMonitor', function () {
+ describe('buildMonitor.cron', function () {
+ describe('every', function () {
+
+ var interval = 1000;
+
+ var noop = angular.noop;
+
+ beforeEach(module('buildMonitor.cron', ['everyProvider', '$provide', function (everyProvider, $provide) {
+
+ var timeline = [],
+ nextId = 0,
+ now = 0,
+ $window,
+ $timeout;
+
+ $timeout = function (fn, delay) {
+ timeline.push({
+ nextTime: (now + delay),
+ delay: delay,
+ fn: fn,
+ id: nextId
+ });
+ timeline.sort(function (a, b) {
+ return a.nextTime - b.nextTime;
+ });
+
+ return nextId++;
+ };
+
+ $timeout.flush = function (millis) {
+ now += millis;
+ while (timeline.length && timeline[0].nextTime <= now) {
+ var task = timeline[0];
+ task.fn();
+
+ clearTimeout(task.id)
+
+ timeline.sort(function (a, b) {
+ return a.nextTime - b.nextTime;
+ });
+ }
+
+ return millis;
+
+
+ function clearTimeout(id) {
+ var fnIndex;
+
+ angular.forEach(timeline, function (fn, index) {
+ if (fn.id === id) fnIndex = index;
+ });
+
+ if (fnIndex !== undefined) {
+ timeline.splice(fnIndex, 1);
+ return true;
+ }
+
+ return false;
+ };
+ };
+
+ $provide.provider('every', everyProvider);
+ $provide.value('$timeout', $timeout);
+ }]));
+
+ it('executes the first iteration straight away', inject(function (every) {
+ var counter = 0;
+
+ every(interval, function () {
+ counter++;
+ });
+
+ expect(counter).toBe(1);
+ }));
+
+ it('runs task repeatedly', inject(function (every, $timeout) {
+ var counter = 0;
+
+ every(interval, function () {
+ counter++;
+ });
+
+ $timeout.flush(interval);
+
+ expect(counter).toBe(2);
+ }));
+
+ it('calls $apply after each task is executed', inject(function (every, $rootScope) {
+ var apply = sinon.spy($rootScope, '$apply');
+
+ every(interval, noop);
+
+ expect(apply).toHaveBeenCalledOnce();
+ }));
+
+ describe('asynchronous steps', function () {
+
+ it('shows how angular $q needs to be used with $rootScope.$digest', inject(function ($q, $rootScope) {
+ // https://groups.google.com/forum/#!topic/angular/0dhQzTPexA0
+
+ var deferred = $q.defer(),
+ promise = deferred.promise,
+ counter = 0;
+
+ promise.then(function () {
+ counter++;
+ });
+
+ deferred.resolve();
+
+ expect(counter).toBe(0);
+
+ // that's the important bit !
+ $rootScope.$digest();
+
+ expect(counter).toBe(1);
+ }));
+
+ it('progresses the loop if the current step resolves the promise of the next step', inject(function (every, $rootScope, $timeout, $q) {
+ var task = sinon.spy();
+
+ every(interval, function () {
+ task();
+
+ return $q.when({});
+ });
+
+
+ expect(task.callCount).toBe(1);
+
+ $rootScope.$digest();
+ $timeout.flush(interval);
+
+ expect(task.callCount).toBe(2);
+ }));
+
+ it('stops the loop if the current step brakes the promise of a next step', inject(function (every, $rootScope, $timeout, $q) {
+ var task = sinon.spy();
+
+ every(interval, function () {
+ task();
+
+ return $q.reject({});
+ });
+
+ $timeout.flush(interval)
+
+ expect(task.callCount).toBe(1);
+ }));
+
+
+ it('calls $apply after the step is completed', inject(function (every, $rootScope, $q) {
+ var apply = sinon.spy($rootScope, '$apply');
+
+ every(interval, function () {
+ return $q.when({});
+ });
+
+ expect(apply.callCount).toBe(1);
+ }));
+
+ it("won't run the next step until the previous step has completed", inject(function (every, $q, $timeout, $q) {
+ var syncTask = sinon.spy(),
+
+ asyncTask = sinon.spy(),
+ asyncTaskLength = 2 * interval;
+
+ every(interval, function () {
+ syncTask();
+
+ var deferred = $q.defer();
+
+ $timeout(function () {
+ asyncTask();
+
+ deferred.resolve({});
+ }, asyncTaskLength);
+
+ return deferred.promise;
+ });
+
+ // straight after invoking 'every':
+ expect(syncTask.callCount).toBe(1);
+ expect(asyncTask.callCount).toBe(0);
+
+ // after the interval (half the time it takes to complete the asyncTask):
+ $timeout.flush(interval);
+ expect(syncTask.callCount).toBe(1);
+ expect(asyncTask.callCount).toBe(0);
+
+ // after another interval (it takes two intervals to complete the asyncTask):
+ $timeout.flush(interval);
+ expect(syncTask.callCount).toBe(1);
+ expect(asyncTask.callCount).toBe(1);
+ }));
+ });
+ });
+ });
+});
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/javascript/unit/jenkins/proxyFromSpec.js b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/jenkins/proxyFromSpec.js
new file mode 100644
index 0000000..a498f2a
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/jenkins/proxyFromSpec.js
@@ -0,0 +1,115 @@
+'use strict';
+
+describe('buildMonitor', function () {
+
+ describe('jenkins', function () {
+
+ var httpBackend,
+ stringified;
+
+ beforeEach(module('jenkins'));
+
+ beforeEach(inject(function($injector) {
+ httpBackend = $injector.get('$httpBackend');
+ stringified = $injector.get('stringified');
+ }));
+
+ afterEach(function() {
+ httpBackend.verifyNoOutstandingExpectation();
+ httpBackend.verifyNoOutstandingRequest();
+ });
+
+ describe('proxyFrom', function() {
+
+ var http = {
+ success: 200,
+ internalServerError: 500
+ };
+
+ var url = '/$stapler/bound/97daf472-ab2b-4e96-a02b-968970e68030',
+ crumb = '1d7eae2a-3c33-4fbe-b717-726ac4da8a52';
+
+ var jellyGeneratedServerSideCalculatorBinding = {
+ url: url,
+ crumb: crumb,
+ methods: ['add']
+ };
+
+ describe('factory', function() {
+
+ it('creates proxies configured with jelly-generated server-side bindings', inject(function (proxyFrom) {
+ var serverSideCalculator = proxyFrom(jellyGeneratedServerSideCalculatorBinding);
+
+ expect(serverSideCalculator).toBeAn('object');
+ expect(serverSideCalculator).toHaveFollowingMethods(['add']);
+ }));
+ });
+
+ describe('proxy', function() {
+
+ afterEach(function() {
+ httpBackend.flush();
+ });
+
+ it('allows to call bound server-side objects', inject(function(proxyFrom) {
+ var validResponse = 3;
+
+ givenRemoteMethodCall('add', [1, 2]).
+ willSucceedWith(validResponse);
+
+
+ var serverSideCalculator = proxyFrom(jellyGeneratedServerSideCalculatorBinding);
+
+ serverSideCalculator.add(1, 2).then(function (response) {
+ expect(response.data).toBe(validResponse);
+ });
+ }));
+
+ it('recognises back-end failures', inject(function(proxyFrom) {
+ var someExplanation = "Unknown error has occurred";
+
+ givenRemoteMethodCall('add', [1, 2]).
+ willFailWith(http.internalServerError, someExplanation);
+
+
+ var serverSideCalculator = proxyFrom(jellyGeneratedServerSideCalculatorBinding);
+
+ serverSideCalculator.add(1, 2).error(function (error, status) {
+ expect(status).toBe(http.internalServerError);
+ expect(error).toBe(someExplanation);
+ });
+ }));
+ });
+
+
+ // teeny-tiny DSL to simplify setting up the httpBackend mock
+ function givenRemoteMethodCall(method, parameters) {
+ var expected = {
+ url: url + '/' + method,
+ data: stringified(parameters),
+ headers: {
+ 'Accept': 'application/json, text/plain, */*',
+ 'Content-Type': 'application/x-stapler-method-invocation;charset=UTF-8',
+ 'Crumb': crumb,
+ '.crumb': crumb
+ }
+ };
+
+ function respondsWith(httpStatus, data) {
+ httpBackend.
+ whenPOST(expected.url, expected.data, expected.headers).
+ respond(httpStatus, data);
+ }
+
+ return {
+ willSucceedWith: function(result) {
+ respondsWith(http.success, result);
+ },
+ willFailWith: function(errorCode, explanation) {
+ respondsWith(errorCode, explanation);
+ }
+ }
+ }
+ });
+ });
+});
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/javascript/unit/jenkins/proxyProviderSpec.js b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/jenkins/proxyProviderSpec.js
new file mode 100644
index 0000000..458d4fc
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/jenkins/proxyProviderSpec.js
@@ -0,0 +1,32 @@
+'use strict';
+
+describe('buildMonitor', function () {
+
+ describe('jenkins', function () {
+
+ describe('proxy provider', function() {
+
+ var url = '/$stapler/bound/97daf472-ab2b-4e96-a02b-968970e68030',
+ crumb = '1d7eae2a-3c33-4fbe-b717-726ac4da8a52';
+
+ var jellyGeneratedServerSideBindings = {
+ exampleServerSideCalculator: {
+ url: url,
+ crumb: crumb,
+ methods: ['add']
+ }
+ }
+
+ // before proxies can be used,
+ // they need to be configured using bindings generated by a Jelly BindTag
+ beforeEach(module('jenkins', function (proxyProvider) {
+ proxyProvider.configureProxiesUsing(jellyGeneratedServerSideBindings);
+ }));
+
+ it('allows access to bound server-side objects', inject(function (proxy) {
+ expect(proxy.exampleServerSideCalculator).toBeAn('object');
+ expect(proxy.exampleServerSideCalculator).toHaveFollowingMethods(['add']);
+ }));
+ });
+ });
+});
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/javascript/unit/jenkins/responseCodeStandardsIntroducerSpec.js b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/jenkins/responseCodeStandardsIntroducerSpec.js
new file mode 100644
index 0000000..7242c6d
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/jenkins/responseCodeStandardsIntroducerSpec.js
@@ -0,0 +1,41 @@
+'use strict';
+
+describe('buildMonitor', function () {
+
+ describe('jenkins', function () {
+
+ describe('responseCodeStandardsIntroducer', function () {
+ beforeEach(module('jenkins'));
+
+ it('marks an error response with 500 status without affecting the original response object', inject(function (responseCodeStandardsIntroducer, STAPLER_CONTENT_TYPE, $rootScope) {
+ var OK = 200,
+ INTERNAL_SERVER_ERROR = 500,
+ staplerErrorResponse = {
+ config: {
+ headers: {
+ 'Content-Type': STAPLER_CONTENT_TYPE
+ }
+ },
+ status: OK,
+ data: {
+ "cause": null,
+ "localizedMessage": "",
+ "message": "",
+ "stackTrace": [
+ {"className": "java.util.TreeSet", "fileName": "TreeSet.java", "lineNumber": 154, "methodName": "<init>", "nativeMethod": false},
+ {"className": "hudson.model.ListView", "fileName": "ListView.java", "lineNumber": 144, "methodName": "getItems", "nativeMethod": false}
+ ]}
+ }
+
+
+ responseCodeStandardsIntroducer.response(staplerErrorResponse).then(null, function (response) {
+ expect(response.status).toBe(INTERNAL_SERVER_ERROR);
+ });
+
+ $rootScope.$digest();
+
+ expect(staplerErrorResponse.status).toBe(OK);
+ }));
+ });
+ });
+});
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/javascript/unit/jenkins/stringifiedSpec.js b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/jenkins/stringifiedSpec.js
new file mode 100644
index 0000000..881865e
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/jenkins/stringifiedSpec.js
@@ -0,0 +1,29 @@
+'use strict';
+
+describe('buildMonitor', function () {
+
+ describe('jenkins', function () {
+
+ describe('stringified converts', function() {
+ beforeEach(module('jenkins'));
+
+ it('empty objects to Jenkins-accepted format', inject(function (stringified) {
+ expect(stringified([])).toBe('[]');
+ expect(stringified({})).toBe('{}');
+ expect(stringified(null)).toBe('null');
+ expect(stringified('')).toBe('');
+ }));
+
+ it('an array of parameters to Jenkins-accepted format', inject(function (stringified) {
+ expect(stringified(['a', 2, "c"])).toBe('["a",2,"c"]');
+ }));
+
+ it('a complex object to Jenkins-accepted format', inject(function (stringified) {
+ var input = { array: ['a', { key: 'value'}]},
+ expectedOutput = '{"array":["a",{"key":"value"}]}';
+
+ expect(stringified(input)).toBe(expectedOutput);
+ }));
+ });
+ });
+});
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/javascript/unit/services/cookieJarSpec.js b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/services/cookieJarSpec.js
new file mode 100644
index 0000000..c32f9ce
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/services/cookieJarSpec.js
@@ -0,0 +1,124 @@
+'use strict';
+
+describe('buildMonitor', function () {
+ describe('buildMonitor.services', function () {
+ describe('cookieJar', function () {
+
+ var services,
+ YahooCookie = YAHOO.util.Cookie,
+ mockedCookie, // YAHOO.util.Cookie backend used by the cookieJar
+
+ NAME = 'numberOfColumns',
+ VALUE = 3,
+ DEFAULT_VALUE = 1;
+
+ beforeEach(function () {
+ services = angular.module('buildMonitor.services');
+
+ mockedCookie = sinon.mock(YahooCookie);
+
+ module('buildMonitor.services', function ($provide) {
+ $provide.value('YahooCookie', YahooCookie);
+ });
+ });
+
+ describe('default configuration', function() {
+
+ it('returns "undefined" if requested value couldn\'t be found in a cookie and no defaults are provided', inject(function (cookieJar) {
+ expect(cookieJar.get('aCookieThatDoesNotExist')).toBeUndefined();
+ }));
+
+ it('returns default value if the one requested couldn\'t be found in a cookie', inject(function (cookieJar) {
+ expect(cookieJar.get('aCookieThatDoesNotExist', DEFAULT_VALUE)).toBe(DEFAULT_VALUE);
+ }));
+
+ it('allows for a value to be persisted and then retrieved', inject(function (cookieJar) {
+ mockedCookie.expects("set").withArgs(NAME, VALUE);
+ mockedCookie.expects("get").withArgs(NAME).returns(VALUE);
+
+
+ cookieJar.put(NAME, VALUE);
+
+ expect(cookieJar.get(NAME)).toBe(VALUE);
+
+ mockedCookie.verify()
+ }));
+
+ it('should use cookies that expire at the end of the session', inject(function (cookieJar) {
+ var noExpiryDateSpecified = {};
+
+ mockedCookie.expects("set").withArgs(NAME, VALUE, noExpiryDateSpecified);
+
+
+ cookieJar.put(NAME, VALUE);
+
+ mockedCookie.verify();
+ }));
+ });
+
+ describe('custom label', function () {
+
+ var COOKIE_JAR_LABEL = 'chocolateChipCookies';
+
+ beforeEach(function () {
+ services.config(function(cookieJarProvider) {
+ cookieJarProvider.describe({
+ label: COOKIE_JAR_LABEL
+ });
+ });
+ });
+
+ it('should prefix each cookie with a label', inject(function (cookieJar) {
+ mockedCookie.expects("set").withArgs(prefixed(NAME), VALUE);
+ mockedCookie.expects("get").withArgs(prefixed(NAME));
+
+
+ cookieJar.put(NAME, VALUE);
+ cookieJar.get(NAME);
+
+ mockedCookie.verify();
+ }));
+
+ afterEach(function() {
+ mockedCookie.restore();
+ });
+
+ function prefixed(name) {
+ return COOKIE_JAR_LABEL + '.' + name;
+ };
+ });
+
+ describe('custom shelf life', function() {
+
+ var SHELF_LIFE_IN_DAYS = 7;
+
+ beforeEach(function () {
+
+ services.config(function(cookieJarProvider) {
+ cookieJarProvider.describe({
+ shelfLife: SHELF_LIFE_IN_DAYS
+ });
+ });
+ });
+
+ it('should use cookies that expire when specified', inject(function (cookieJar) {
+ mockedCookie.expects("set").withArgs(NAME, VALUE, {
+ expires: dateIn(SHELF_LIFE_IN_DAYS)}
+ );
+
+ cookieJar.put(NAME, VALUE);
+
+ mockedCookie.verify();
+ }));
+
+ afterEach(function() {
+ mockedCookie.restore();
+ });
+
+ function dateIn(days) {
+ return new Date(+new Date() + (days * 24 * 3600 * 1000));
+ };
+ });
+ });
+ });
+});
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/javascript/unit/services/counterSpec.js b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/services/counterSpec.js
new file mode 100644
index 0000000..fa5cb36
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/services/counterSpec.js
@@ -0,0 +1,39 @@
+'use strict';
+
+describe('buildMonitor', function () {
+ describe('buildMonitor.services', function () {
+ describe('counter', function () {
+
+ var counter;
+
+ beforeEach(module('buildMonitor.services'));
+
+ beforeEach(inject(function(_counter_) {
+ counter = _counter_;
+ }));
+
+ it('starts from zero', inject(function (_counter_) {
+ expect(counter.value()).toBe(0);
+ }));
+
+ it('allows to increment the count', inject(function (_counter_) {
+ counter.increase();
+
+ expect(counter.value()).toBe(1);
+ }));
+
+ it('allows to increment the count', inject(function (_counter_) {
+ counter.increase();
+
+ expect(counter.value()).toBe(1);
+ }));
+
+ it('allows to reset the count', inject(function (_counter_) {
+ counter.increase();
+ counter.reset();
+
+ expect(counter.value()).toBe(0);
+ }));
+ });
+ });
+});
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/javascript/unit/services/hashCodeSpec.js b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/services/hashCodeSpec.js
new file mode 100644
index 0000000..ee14bce
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/javascript/unit/services/hashCodeSpec.js
@@ -0,0 +1,24 @@
+'use strict';
+
+describe('buildMonitor', function () {
+ describe('buildMonitor.services', function () {
+ describe('hashCode', function () {
+
+ beforeEach(module('buildMonitor.services'));
+
+ it('produces a hash code uniquely identifying a string of text', inject(function (hashCode) {
+ expect(hashCode('')).toEqual(0);
+ expect(hashCode('name')).toEqual(3373707)
+ expect(hashCode('Name')).toEqual(2420395);
+ }));
+
+ it('should treat "undefined" the same way as empty string', inject(function (hashCode) {
+ expect(hashCode()).toEqual(hashCode(''));
+ }));
+
+ it('should treat "null" the same way as empty string', inject(function (hashCode) {
+ expect(hashCode(null)).toEqual(hashCode(''));
+ }));
+ });
+ });
+});
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/resources/karma.conf.js b/java/jenkins_plugins/build_monitor/src/test/resources/karma.conf.js
new file mode 100644
index 0000000..dfd3bd5
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/resources/karma.conf.js
@@ -0,0 +1,94 @@
+// Karma configuration
+// Generated on Sat Sep 28 2013 15:27:36 GMT+0100 (BST)
+
+module.exports = function(config) {
+ config.set({
+
+ // base path, that will be used to resolve files and exclude
+ basePath: '../../../',
+
+
+ // frameworks to use
+ frameworks: ['jasmine'],
+
+
+ // list of files / patterns to load in the browser
+ files: [
+ 'src/test/resources/syntacticSugar.js',
+ 'src/main/webapp/vendor/angular-1.1.5.js',
+ 'src/main/webapp/vendor/angular-slider-0.1.6.js',
+ 'src/main/webapp/vendor/ui-*.js',
+ 'src/test/resources/vendor/angular-mocks.js',
+ 'src/test/resources/vendor/sinon-1.7.3.js',
+ 'src/test/resources/vendor/jasmine-sinon-0.3.1.js',
+ 'src/test/resources/vendor/yahoo-2.9.0.min.js',
+ 'src/test/resources/vendor/yahoo-cookie-2.9.0.min.js',
+ 'src/main/webapp/scripts/**/*.js',
+ 'src/test/javascript/**/*Spec.js'
+ ],
+
+
+ // list of files to exclude
+ exclude: [
+
+ ],
+
+ preprocessors: {
+ 'src/main/webapp/scripts/**/*.js': 'coverage'
+ },
+
+
+ // test results reporter to use
+ // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
+ reporters: ['progress', 'junit', 'coverage'],
+
+ junitReporter: {
+ outputFile: 'target/javascript/test-results.xml'
+ },
+
+ coverageReporter: {
+ type: 'cobertura',
+ dir: 'target/javascript/coverage/',
+ file: 'coverage.xml'
+ },
+
+ // web server port
+ port: 9876,
+
+ // cli runner port
+ runnerPort: 9100,
+
+
+ // enable / disable colors in the output (reporters and logs)
+ colors: true,
+
+
+ // level of logging
+ // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
+ logLevel: config.LOG_INFO,
+
+
+ // enable / disable watching file and executing tests whenever any file changes
+ autoWatch: false,
+
+
+ // Start these browsers, currently available:
+ // - Chrome
+ // - ChromeCanary
+ // - Firefox
+ // - Opera
+ // - Safari (only Mac)
+ // - PhantomJS
+ // - IE (only Windows)
+ browsers: ['PhantomJS'],
+
+
+ // If browser does not capture in given timeout [ms], kill it
+ captureTimeout: 60000,
+
+
+ // Continuous Integration mode
+ // if true, it capture browsers, run tests and exit
+ singleRun: false
+ });
+};
diff --git a/java/jenkins_plugins/build_monitor/src/test/resources/plugins/build-failure-analyzer-1.7.0.jpi b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/build-failure-analyzer-1.7.0.jpi
new file mode 100644
index 0000000..180f043
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/build-failure-analyzer-1.7.0.jpi
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/src/test/resources/plugins/buildgraph-view-1.0.hpi b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/buildgraph-view-1.0.hpi
new file mode 100644
index 0000000..8bd664a
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/buildgraph-view-1.0.hpi
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/src/test/resources/plugins/cloudbees-folder-4.2.3.hpi b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/cloudbees-folder-4.2.3.hpi
new file mode 100644
index 0000000..ea89914
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/cloudbees-folder-4.2.3.hpi
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/src/test/resources/plugins/credentials-1.10.jpi b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/credentials-1.10.jpi
new file mode 100644
index 0000000..ea7ebdf
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/credentials-1.10.jpi
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/src/test/resources/plugins/git-1.5.0.hpi b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/git-1.5.0.hpi
new file mode 100644
index 0000000..471cc90
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/git-1.5.0.hpi
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/src/test/resources/plugins/git-client-1.8.0.jpi b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/git-client-1.8.0.jpi
new file mode 100644
index 0000000..f296278
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/git-client-1.8.0.jpi
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/src/test/resources/plugins/scm-api-0.2.jpi b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/scm-api-0.2.jpi
new file mode 100644
index 0000000..5e931d9
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/scm-api-0.2.jpi
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/src/test/resources/plugins/ssh-credentials-1.6.1.jpi b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/ssh-credentials-1.6.1.jpi
new file mode 100644
index 0000000..34cf2c9
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/resources/plugins/ssh-credentials-1.6.1.jpi
Binary files differ
diff --git a/java/jenkins_plugins/build_monitor/src/test/resources/syntacticSugar.js b/java/jenkins_plugins/build_monitor/src/test/resources/syntacticSugar.js
new file mode 100644
index 0000000..64299c4
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/resources/syntacticSugar.js
@@ -0,0 +1,46 @@
+function toBeA(expected) {
+ return typeof this.actual === expected;
+}
+
+function toBeInstanceOf(expected) {
+ return this.actual instanceof expected && this.actual.length > 0;
+}
+
+function toHaveFollowingMethods(expectedMethods) {
+ var missingMethods = [],
+ foundMethods = [],
+ method;
+
+ function isAFunction(candidate) {
+ return typeof candidate == 'function';
+ }
+
+ for (var i = 0; i < expectedMethods.length; i++) {
+ method = expectedMethods[i];
+
+ if (! isAFunction(this.actual[method])) {
+ missingMethods.push(method);
+ }
+ }
+
+ for (method in this.actual) {
+ if (this.actual.hasOwnProperty(method) && isAFunction(this.actual[method])) {
+ foundMethods.push(method);
+ }
+ }
+
+ this.message = function () {
+ return "Expected the object to have following methods: " +
+ jasmine.pp(missingMethods.sort()) +
+ "\ninstead, it only had the following: " +
+ jasmine.pp(foundMethods.sort())
+
+ }
+
+ return missingMethods.length == 0;
+}
+
+jasmine.Matchers.prototype.toBeInstanceOf = toBeInstanceOf;
+jasmine.Matchers.prototype.toHaveFollowingMethods = toHaveFollowingMethods;
+jasmine.Matchers.prototype.toBeA = toBeA;
+jasmine.Matchers.prototype.toBeAn = toBeA;
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/resources/vendor/angular-mocks.js b/java/jenkins_plugins/build_monitor/src/test/resources/vendor/angular-mocks.js
new file mode 100644
index 0000000..f9b0263
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/resources/vendor/angular-mocks.js
@@ -0,0 +1,1886 @@
+/**
+ * @license AngularJS v1.1.5
+ * (c) 2010-2012 Google, Inc. http://angularjs.org
+ * License: MIT
+ *
+ * TODO(vojta): wrap whole file into closure during build
+ */
+
+/**
+ * @ngdoc overview
+ * @name angular.mock
+ * @description
+ *
+ * Namespace from 'angular-mocks.js' which contains testing related code.
+ */
+angular.mock = {};
+
+/**
+ * ! This is a private undocumented service !
+ *
+ * @name ngMock.$browser
+ *
+ * @description
+ * This service is a mock implementation of {@link ng.$browser}. It provides fake
+ * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,
+ * cookies, etc...
+ *
+ * The api of this service is the same as that of the real {@link ng.$browser $browser}, except
+ * that there are several helper methods available which can be used in tests.
+ */
+angular.mock.$BrowserProvider = function() {
+ this.$get = function(){
+ return new angular.mock.$Browser();
+ };
+};
+
+angular.mock.$Browser = function() {
+ var self = this;
+
+ this.isMock = true;
+ self.$$url = "http://server/";
+ self.$$lastUrl = self.$$url; // used by url polling fn
+ self.pollFns = [];
+
+ // TODO(vojta): remove this temporary api
+ self.$$completeOutstandingRequest = angular.noop;
+ self.$$incOutstandingRequestCount = angular.noop;
+
+
+ // register url polling fn
+
+ self.onUrlChange = function(listener) {
+ self.pollFns.push(
+ function() {
+ if (self.$$lastUrl != self.$$url) {
+ self.$$lastUrl = self.$$url;
+ listener(self.$$url);
+ }
+ }
+ );
+
+ return listener;
+ };
+
+ self.cookieHash = {};
+ self.lastCookieHash = {};
+ self.deferredFns = [];
+ self.deferredNextId = 0;
+
+ self.defer = function(fn, delay) {
+ delay = delay || 0;
+ self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId});
+ self.deferredFns.sort(function(a,b){ return a.time - b.time;});
+ return self.deferredNextId++;
+ };
+
+
+ self.defer.now = 0;
+
+
+ self.defer.cancel = function(deferId) {
+ var fnIndex;
+
+ angular.forEach(self.deferredFns, function(fn, index) {
+ if (fn.id === deferId) fnIndex = index;
+ });
+
+ if (fnIndex !== undefined) {
+ self.deferredFns.splice(fnIndex, 1);
+ return true;
+ }
+
+ return false;
+ };
+
+
+ /**
+ * @name ngMock.$browser#defer.flush
+ * @methodOf ngMock.$browser
+ *
+ * @description
+ * Flushes all pending requests and executes the defer callbacks.
+ *
+ * @param {number=} number of milliseconds to flush. See {@link #defer.now}
+ */
+ self.defer.flush = function(delay) {
+ if (angular.isDefined(delay)) {
+ self.defer.now += delay;
+ } else {
+ if (self.deferredFns.length) {
+ self.defer.now = self.deferredFns[self.deferredFns.length-1].time;
+ } else {
+ throw Error('No deferred tasks to be flushed');
+ }
+ }
+
+ while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
+ self.deferredFns.shift().fn();
+ }
+ };
+ /**
+ * @name ngMock.$browser#defer.now
+ * @propertyOf ngMock.$browser
+ *
+ * @description
+ * Current milliseconds mock time.
+ */
+
+ self.$$baseHref = '';
+ self.baseHref = function() {
+ return this.$$baseHref;
+ };
+};
+angular.mock.$Browser.prototype = {
+
+/**
+ * @name ngMock.$browser#poll
+ * @methodOf ngMock.$browser
+ *
+ * @description
+ * run all fns in pollFns
+ */
+ poll: function poll() {
+ angular.forEach(this.pollFns, function(pollFn){
+ pollFn();
+ });
+ },
+
+ addPollFn: function(pollFn) {
+ this.pollFns.push(pollFn);
+ return pollFn;
+ },
+
+ url: function(url, replace) {
+ if (url) {
+ this.$$url = url;
+ return this;
+ }
+
+ return this.$$url;
+ },
+
+ cookies: function(name, value) {
+ if (name) {
+ if (value == undefined) {
+ delete this.cookieHash[name];
+ } else {
+ if (angular.isString(value) && //strings only
+ value.length <= 4096) { //strict cookie storage limits
+ this.cookieHash[name] = value;
+ }
+ }
+ } else {
+ if (!angular.equals(this.cookieHash, this.lastCookieHash)) {
+ this.lastCookieHash = angular.copy(this.cookieHash);
+ this.cookieHash = angular.copy(this.cookieHash);
+ }
+ return this.cookieHash;
+ }
+ },
+
+ notifyWhenNoOutstandingRequests: function(fn) {
+ fn();
+ }
+};
+
+
+/**
+ * @ngdoc object
+ * @name ngMock.$exceptionHandlerProvider
+ *
+ * @description
+ * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors passed
+ * into the `$exceptionHandler`.
+ */
+
+/**
+ * @ngdoc object
+ * @name ngMock.$exceptionHandler
+ *
+ * @description
+ * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed
+ * into it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration
+ * information.
+ *
+ *
+ * <pre>
+ * describe('$exceptionHandlerProvider', function() {
+ *
+ * it('should capture log messages and exceptions', function() {
+ *
+ * module(function($exceptionHandlerProvider) {
+ * $exceptionHandlerProvider.mode('log');
+ * });
+ *
+ * inject(function($log, $exceptionHandler, $timeout) {
+ * $timeout(function() { $log.log(1); });
+ * $timeout(function() { $log.log(2); throw 'banana peel'; });
+ * $timeout(function() { $log.log(3); });
+ * expect($exceptionHandler.errors).toEqual([]);
+ * expect($log.assertEmpty());
+ * $timeout.flush();
+ * expect($exceptionHandler.errors).toEqual(['banana peel']);
+ * expect($log.log.logs).toEqual([[1], [2], [3]]);
+ * });
+ * });
+ * });
+ * </pre>
+ */
+
+angular.mock.$ExceptionHandlerProvider = function() {
+ var handler;
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$exceptionHandlerProvider#mode
+ * @methodOf ngMock.$exceptionHandlerProvider
+ *
+ * @description
+ * Sets the logging mode.
+ *
+ * @param {string} mode Mode of operation, defaults to `rethrow`.
+ *
+ * - `rethrow`: If any errors are passed into the handler in tests, it typically
+ * means that there is a bug in the application or test, so this mock will
+ * make these tests fail.
+ * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log` mode stores an
+ * array of errors in `$exceptionHandler.errors`, to allow later assertion of them.
+ * See {@link ngMock.$log#assertEmpty assertEmpty()} and
+ * {@link ngMock.$log#reset reset()}
+ */
+ this.mode = function(mode) {
+ switch(mode) {
+ case 'rethrow':
+ handler = function(e) {
+ throw e;
+ };
+ break;
+ case 'log':
+ var errors = [];
+
+ handler = function(e) {
+ if (arguments.length == 1) {
+ errors.push(e);
+ } else {
+ errors.push([].slice.call(arguments, 0));
+ }
+ };
+
+ handler.errors = errors;
+ break;
+ default:
+ throw Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
+ }
+ };
+
+ this.$get = function() {
+ return handler;
+ };
+
+ this.mode('rethrow');
+};
+
+
+/**
+ * @ngdoc service
+ * @name ngMock.$log
+ *
+ * @description
+ * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays
+ * (one array per logging level). These arrays are exposed as `logs` property of each of the
+ * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.
+ *
+ */
+angular.mock.$LogProvider = function() {
+
+ function concat(array1, array2, index) {
+ return array1.concat(Array.prototype.slice.call(array2, index));
+ }
+
+
+ this.$get = function () {
+ var $log = {
+ log: function() { $log.log.logs.push(concat([], arguments, 0)); },
+ warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
+ info: function() { $log.info.logs.push(concat([], arguments, 0)); },
+ error: function() { $log.error.logs.push(concat([], arguments, 0)); }
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$log#reset
+ * @methodOf ngMock.$log
+ *
+ * @description
+ * Reset all of the logging arrays to empty.
+ */
+ $log.reset = function () {
+ /**
+ * @ngdoc property
+ * @name ngMock.$log#log.logs
+ * @propertyOf ngMock.$log
+ *
+ * @description
+ * Array of messages logged using {@link ngMock.$log#log}.
+ *
+ * @example
+ * <pre>
+ * $log.log('Some Log');
+ * var first = $log.log.logs.unshift();
+ * </pre>
+ */
+ $log.log.logs = [];
+ /**
+ * @ngdoc property
+ * @name ngMock.$log#warn.logs
+ * @propertyOf ngMock.$log
+ *
+ * @description
+ * Array of messages logged using {@link ngMock.$log#warn}.
+ *
+ * @example
+ * <pre>
+ * $log.warn('Some Warning');
+ * var first = $log.warn.logs.unshift();
+ * </pre>
+ */
+ $log.warn.logs = [];
+ /**
+ * @ngdoc property
+ * @name ngMock.$log#info.logs
+ * @propertyOf ngMock.$log
+ *
+ * @description
+ * Array of messages logged using {@link ngMock.$log#info}.
+ *
+ * @example
+ * <pre>
+ * $log.info('Some Info');
+ * var first = $log.info.logs.unshift();
+ * </pre>
+ */
+ $log.info.logs = [];
+ /**
+ * @ngdoc property
+ * @name ngMock.$log#error.logs
+ * @propertyOf ngMock.$log
+ *
+ * @description
+ * Array of messages logged using {@link ngMock.$log#error}.
+ *
+ * @example
+ * <pre>
+ * $log.log('Some Error');
+ * var first = $log.error.logs.unshift();
+ * </pre>
+ */
+ $log.error.logs = [];
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$log#assertEmpty
+ * @methodOf ngMock.$log
+ *
+ * @description
+ * Assert that the all of the logging methods have no logged messages. If messages present, an exception is thrown.
+ */
+ $log.assertEmpty = function() {
+ var errors = [];
+ angular.forEach(['error', 'warn', 'info', 'log'], function(logLevel) {
+ angular.forEach($log[logLevel].logs, function(log) {
+ angular.forEach(log, function (logItem) {
+ errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || ''));
+ });
+ });
+ });
+ if (errors.length) {
+ errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or an expected " +
+ "log message was not checked and removed:");
+ errors.push('');
+ throw new Error(errors.join('\n---------\n'));
+ }
+ };
+
+ $log.reset();
+ return $log;
+ };
+};
+
+
+(function() {
+ var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
+
+ function jsonStringToDate(string){
+ var match;
+ if (match = string.match(R_ISO8061_STR)) {
+ var date = new Date(0),
+ tzHour = 0,
+ tzMin = 0;
+ if (match[9]) {
+ tzHour = int(match[9] + match[10]);
+ tzMin = int(match[9] + match[11]);
+ }
+ date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
+ date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
+ return date;
+ }
+ return string;
+ }
+
+ function int(str) {
+ return parseInt(str, 10);
+ }
+
+ function padNumber(num, digits, trim) {
+ var neg = '';
+ if (num < 0) {
+ neg = '-';
+ num = -num;
+ }
+ num = '' + num;
+ while(num.length < digits) num = '0' + num;
+ if (trim)
+ num = num.substr(num.length - digits);
+ return neg + num;
+ }
+
+
+ /**
+ * @ngdoc object
+ * @name angular.mock.TzDate
+ * @description
+ *
+ * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
+ *
+ * Mock of the Date type which has its timezone specified via constructor arg.
+ *
+ * The main purpose is to create Date-like instances with timezone fixed to the specified timezone
+ * offset, so that we can test code that depends on local timezone settings without dependency on
+ * the time zone settings of the machine where the code is running.
+ *
+ * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
+ * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
+ *
+ * @example
+ * !!!! WARNING !!!!!
+ * This is not a complete Date object so only methods that were implemented can be called safely.
+ * To make matters worse, TzDate instances inherit stuff from Date via a prototype.
+ *
+ * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
+ * incomplete we might be missing some non-standard methods. This can result in errors like:
+ * "Date.prototype.foo called on incompatible Object".
+ *
+ * <pre>
+ * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
+ * newYearInBratislava.getTimezoneOffset() => -60;
+ * newYearInBratislava.getFullYear() => 2010;
+ * newYearInBratislava.getMonth() => 0;
+ * newYearInBratislava.getDate() => 1;
+ * newYearInBratislava.getHours() => 0;
+ * newYearInBratislava.getMinutes() => 0;
+ * newYearInBratislava.getSeconds() => 0;
+ * </pre>
+ *
+ */
+ angular.mock.TzDate = function (offset, timestamp) {
+ var self = new Date(0);
+ if (angular.isString(timestamp)) {
+ var tsStr = timestamp;
+
+ self.origDate = jsonStringToDate(timestamp);
+
+ timestamp = self.origDate.getTime();
+ if (isNaN(timestamp))
+ throw {
+ name: "Illegal Argument",
+ message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
+ };
+ } else {
+ self.origDate = new Date(timestamp);
+ }
+
+ var localOffset = new Date(timestamp).getTimezoneOffset();
+ self.offsetDiff = localOffset*60*1000 - offset*1000*60*60;
+ self.date = new Date(timestamp + self.offsetDiff);
+
+ self.getTime = function() {
+ return self.date.getTime() - self.offsetDiff;
+ };
+
+ self.toLocaleDateString = function() {
+ return self.date.toLocaleDateString();
+ };
+
+ self.getFullYear = function() {
+ return self.date.getFullYear();
+ };
+
+ self.getMonth = function() {
+ return self.date.getMonth();
+ };
+
+ self.getDate = function() {
+ return self.date.getDate();
+ };
+
+ self.getHours = function() {
+ return self.date.getHours();
+ };
+
+ self.getMinutes = function() {
+ return self.date.getMinutes();
+ };
+
+ self.getSeconds = function() {
+ return self.date.getSeconds();
+ };
+
+ self.getMilliseconds = function() {
+ return self.date.getMilliseconds();
+ };
+
+ self.getTimezoneOffset = function() {
+ return offset * 60;
+ };
+
+ self.getUTCFullYear = function() {
+ return self.origDate.getUTCFullYear();
+ };
+
+ self.getUTCMonth = function() {
+ return self.origDate.getUTCMonth();
+ };
+
+ self.getUTCDate = function() {
+ return self.origDate.getUTCDate();
+ };
+
+ self.getUTCHours = function() {
+ return self.origDate.getUTCHours();
+ };
+
+ self.getUTCMinutes = function() {
+ return self.origDate.getUTCMinutes();
+ };
+
+ self.getUTCSeconds = function() {
+ return self.origDate.getUTCSeconds();
+ };
+
+ self.getUTCMilliseconds = function() {
+ return self.origDate.getUTCMilliseconds();
+ };
+
+ self.getDay = function() {
+ return self.date.getDay();
+ };
+
+ // provide this method only on browsers that already have it
+ if (self.toISOString) {
+ self.toISOString = function() {
+ return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +
+ padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +
+ padNumber(self.origDate.getUTCDate(), 2) + 'T' +
+ padNumber(self.origDate.getUTCHours(), 2) + ':' +
+ padNumber(self.origDate.getUTCMinutes(), 2) + ':' +
+ padNumber(self.origDate.getUTCSeconds(), 2) + '.' +
+ padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z'
+ }
+ }
+
+ //hide all methods not implemented in this mock that the Date prototype exposes
+ var unimplementedMethods = ['getUTCDay',
+ 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
+ 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
+ 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
+ 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
+ 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
+
+ angular.forEach(unimplementedMethods, function(methodName) {
+ self[methodName] = function() {
+ throw Error("Method '" + methodName + "' is not implemented in the TzDate mock");
+ };
+ });
+
+ return self;
+ };
+
+ //make "tzDateInstance instanceof Date" return true
+ angular.mock.TzDate.prototype = Date.prototype;
+})();
+
+/**
+ * @ngdoc function
+ * @name angular.mock.createMockWindow
+ * @description
+ *
+ * This function creates a mock window object useful for controlling access ot setTimeout, but mocking out
+ * sufficient window's properties to allow Angular to execute.
+ *
+ * @example
+ *
+ * <pre>
+ beforeEach(module(function($provide) {
+ $provide.value('$window', window = angular.mock.createMockWindow());
+ }));
+
+ it('should do something', inject(function($window) {
+ var val = null;
+ $window.setTimeout(function() { val = 123; }, 10);
+ expect(val).toEqual(null);
+ window.setTimeout.expect(10).process();
+ expect(val).toEqual(123);
+ });
+ * </pre>
+ *
+ */
+angular.mock.createMockWindow = function() {
+ var mockWindow = {};
+ var setTimeoutQueue = [];
+
+ mockWindow.document = window.document;
+ mockWindow.getComputedStyle = angular.bind(window, window.getComputedStyle);
+ mockWindow.scrollTo = angular.bind(window, window.scrollTo);
+ mockWindow.navigator = window.navigator;
+ mockWindow.setTimeout = function(fn, delay) {
+ setTimeoutQueue.push({fn: fn, delay: delay});
+ };
+ mockWindow.setTimeout.queue = setTimeoutQueue;
+ mockWindow.setTimeout.expect = function(delay) {
+ if (setTimeoutQueue.length > 0) {
+ return {
+ process: function() {
+ var tick = setTimeoutQueue.shift();
+ expect(tick.delay).toEqual(delay);
+ tick.fn();
+ }
+ };
+ } else {
+ expect('SetTimoutQueue empty. Expecting delay of ').toEqual(delay);
+ }
+ };
+
+ return mockWindow;
+};
+
+/**
+ * @ngdoc function
+ * @name angular.mock.dump
+ * @description
+ *
+ * *NOTE*: this is not an injectable instance, just a globally available function.
+ *
+ * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for debugging.
+ *
+ * This method is also available on window, where it can be used to display objects on debug console.
+ *
+ * @param {*} object - any object to turn into string.
+ * @return {string} a serialized string of the argument
+ */
+angular.mock.dump = function(object) {
+ return serialize(object);
+
+ function serialize(object) {
+ var out;
+
+ if (angular.isElement(object)) {
+ object = angular.element(object);
+ out = angular.element('<div></div>');
+ angular.forEach(object, function(element) {
+ out.append(angular.element(element).clone());
+ });
+ out = out.html();
+ } else if (angular.isArray(object)) {
+ out = [];
+ angular.forEach(object, function(o) {
+ out.push(serialize(o));
+ });
+ out = '[ ' + out.join(', ') + ' ]';
+ } else if (angular.isObject(object)) {
+ if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
+ out = serializeScope(object);
+ } else if (object instanceof Error) {
+ out = object.stack || ('' + object.name + ': ' + object.message);
+ } else {
+ out = angular.toJson(object, true);
+ }
+ } else {
+ out = String(object);
+ }
+
+ return out;
+ }
+
+ function serializeScope(scope, offset) {
+ offset = offset || ' ';
+ var log = [offset + 'Scope(' + scope.$id + '): {'];
+ for ( var key in scope ) {
+ if (scope.hasOwnProperty(key) && !key.match(/^(\$|this)/)) {
+ log.push(' ' + key + ': ' + angular.toJson(scope[key]));
+ }
+ }
+ var child = scope.$$childHead;
+ while(child) {
+ log.push(serializeScope(child, offset + ' '));
+ child = child.$$nextSibling;
+ }
+ log.push('}');
+ return log.join('\n' + offset);
+ }
+};
+
+/**
+ * @ngdoc object
+ * @name ngMock.$httpBackend
+ * @description
+ * Fake HTTP backend implementation suitable for unit testing applications that use the
+ * {@link ng.$http $http service}.
+ *
+ * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less
+ * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.
+ *
+ * During unit testing, we want our unit tests to run quickly and have no external dependencies so
+ * we don’t want to send {@link https://developer.mozilla.org/en/xmlhttprequest XHR} or
+ * {@link http://en.wikipedia.org/wiki/JSONP JSONP} requests to a real server. All we really need is
+ * to verify whether a certain request has been sent or not, or alternatively just let the
+ * application make requests, respond with pre-trained responses and assert that the end result is
+ * what we expect it to be.
+ *
+ * This mock implementation can be used to respond with static or dynamic responses via the
+ * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).
+ *
+ * When an Angular application needs some data from a server, it calls the $http service, which
+ * sends the request to a real server using $httpBackend service. With dependency injection, it is
+ * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify
+ * the requests and respond with some testing data without sending a request to real server.
+ *
+ * There are two ways to specify what test data should be returned as http responses by the mock
+ * backend when the code under test makes http requests:
+ *
+ * - `$httpBackend.expect` - specifies a request expectation
+ * - `$httpBackend.when` - specifies a backend definition
+ *
+ *
+ * # Request Expectations vs Backend Definitions
+ *
+ * Request expectations provide a way to make assertions about requests made by the application and
+ * to define responses for those requests. The test will fail if the expected requests are not made
+ * or they are made in the wrong order.
+ *
+ * Backend definitions allow you to define a fake backend for your application which doesn't assert
+ * if a particular request was made or not, it just returns a trained response if a request is made.
+ * The test will pass whether or not the request gets made during testing.
+ *
+ *
+ * <table class="table">
+ * <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr>
+ * <tr>
+ * <th>Syntax</th>
+ * <td>.expect(...).respond(...)</td>
+ * <td>.when(...).respond(...)</td>
+ * </tr>
+ * <tr>
+ * <th>Typical usage</th>
+ * <td>strict unit tests</td>
+ * <td>loose (black-box) unit testing</td>
+ * </tr>
+ * <tr>
+ * <th>Fulfills multiple requests</th>
+ * <td>NO</td>
+ * <td>YES</td>
+ * </tr>
+ * <tr>
+ * <th>Order of requests matters</th>
+ * <td>YES</td>
+ * <td>NO</td>
+ * </tr>
+ * <tr>
+ * <th>Request required</th>
+ * <td>YES</td>
+ * <td>NO</td>
+ * </tr>
+ * <tr>
+ * <th>Response required</th>
+ * <td>optional (see below)</td>
+ * <td>YES</td>
+ * </tr>
+ * </table>
+ *
+ * In cases where both backend definitions and request expectations are specified during unit
+ * testing, the request expectations are evaluated first.
+ *
+ * If a request expectation has no response specified, the algorithm will search your backend
+ * definitions for an appropriate response.
+ *
+ * If a request didn't match any expectation or if the expectation doesn't have the response
+ * defined, the backend definitions are evaluated in sequential order to see if any of them match
+ * the request. The response from the first matched definition is returned.
+ *
+ *
+ * # Flushing HTTP requests
+ *
+ * The $httpBackend used in production, always responds to requests with responses asynchronously.
+ * If we preserved this behavior in unit testing, we'd have to create async unit tests, which are
+ * hard to write, follow and maintain. At the same time the testing mock, can't respond
+ * synchronously because that would change the execution of the code under test. For this reason the
+ * mock $httpBackend has a `flush()` method, which allows the test to explicitly flush pending
+ * requests and thus preserving the async api of the backend, while allowing the test to execute
+ * synchronously.
+ *
+ *
+ * # Unit testing with mock $httpBackend
+ *
+ * <pre>
+ // controller
+ function MyController($scope, $http) {
+ $http.get('/auth.py').success(function(data) {
+ $scope.user = data;
+ });
+
+ this.saveMessage = function(message) {
+ $scope.status = 'Saving...';
+ $http.post('/add-msg.py', message).success(function(response) {
+ $scope.status = '';
+ }).error(function() {
+ $scope.status = 'ERROR!';
+ });
+ };
+ }
+
+ // testing controller
+ var $httpBackend;
+
+ beforeEach(inject(function($injector) {
+ $httpBackend = $injector.get('$httpBackend');
+
+ // backend definition common for all tests
+ $httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});
+ }));
+
+
+ afterEach(function() {
+ $httpBackend.verifyNoOutstandingExpectation();
+ $httpBackend.verifyNoOutstandingRequest();
+ });
+
+
+ it('should fetch authentication token', function() {
+ $httpBackend.expectGET('/auth.py');
+ var controller = scope.$new(MyController);
+ $httpBackend.flush();
+ });
+
+
+ it('should send msg to server', function() {
+ // now you don’t care about the authentication, but
+ // the controller will still send the request and
+ // $httpBackend will respond without you having to
+ // specify the expectation and response for this request
+ $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
+
+ var controller = scope.$new(MyController);
+ $httpBackend.flush();
+ controller.saveMessage('message content');
+ expect(controller.status).toBe('Saving...');
+ $httpBackend.flush();
+ expect(controller.status).toBe('');
+ });
+
+
+ it('should send auth header', function() {
+ $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
+ // check if the header was send, if it wasn't the expectation won't
+ // match the request and the test will fail
+ return headers['Authorization'] == 'xxx';
+ }).respond(201, '');
+
+ var controller = scope.$new(MyController);
+ controller.saveMessage('whatever');
+ $httpBackend.flush();
+ });
+ </pre>
+ */
+angular.mock.$HttpBackendProvider = function() {
+ this.$get = ['$rootScope', createHttpBackendMock];
+};
+
+/**
+ * General factory function for $httpBackend mock.
+ * Returns instance for unit testing (when no arguments specified):
+ * - passing through is disabled
+ * - auto flushing is disabled
+ *
+ * Returns instance for e2e testing (when `$delegate` and `$browser` specified):
+ * - passing through (delegating request to real backend) is enabled
+ * - auto flushing is enabled
+ *
+ * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)
+ * @param {Object=} $browser Auto-flushing enabled if specified
+ * @return {Object} Instance of $httpBackend mock
+ */
+function createHttpBackendMock($rootScope, $delegate, $browser) {
+ var definitions = [],
+ expectations = [],
+ responses = [],
+ responsesPush = angular.bind(responses, responses.push);
+
+ function createResponse(status, data, headers) {
+ if (angular.isFunction(status)) return status;
+
+ return function() {
+ return angular.isNumber(status)
+ ? [status, data, headers]
+ : [200, status, data];
+ };
+ }
+
+ // TODO(vojta): change params to: method, url, data, headers, callback
+ function $httpBackend(method, url, data, callback, headers, timeout) {
+ var xhr = new MockXhr(),
+ expectation = expectations[0],
+ wasExpected = false;
+
+ function prettyPrint(data) {
+ return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
+ ? data
+ : angular.toJson(data);
+ }
+
+ function wrapResponse(wrapped) {
+ if (!$browser && timeout && timeout.then) timeout.then(handleTimeout);
+
+ return handleResponse;
+
+ function handleResponse() {
+ var response = wrapped.response(method, url, data, headers);
+ xhr.$$respHeaders = response[2];
+ callback(response[0], response[1], xhr.getAllResponseHeaders());
+ }
+
+ function handleTimeout() {
+ for (var i = 0, ii = responses.length; i < ii; i++) {
+ if (responses[i] === handleResponse) {
+ responses.splice(i, 1);
+ callback(-1, undefined, '');
+ break;
+ }
+ }
+ }
+ }
+
+ if (expectation && expectation.match(method, url)) {
+ if (!expectation.matchData(data))
+ throw Error('Expected ' + expectation + ' with different data\n' +
+ 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
+
+ if (!expectation.matchHeaders(headers))
+ throw Error('Expected ' + expectation + ' with different headers\n' +
+ 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
+ prettyPrint(headers));
+
+ expectations.shift();
+
+ if (expectation.response) {
+ responses.push(wrapResponse(expectation));
+ return;
+ }
+ wasExpected = true;
+ }
+
+ var i = -1, definition;
+ while ((definition = definitions[++i])) {
+ if (definition.match(method, url, data, headers || {})) {
+ if (definition.response) {
+ // if $browser specified, we do auto flush all requests
+ ($browser ? $browser.defer : responsesPush)(wrapResponse(definition));
+ } else if (definition.passThrough) {
+ $delegate(method, url, data, callback, headers, timeout);
+ } else throw Error('No response defined !');
+ return;
+ }
+ }
+ throw wasExpected ?
+ Error('No response defined !') :
+ Error('Unexpected request: ' + method + ' ' + url + '\n' +
+ (expectation ? 'Expected ' + expectation : 'No more request expected'));
+ }
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#when
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition.
+ *
+ * @param {string} method HTTP method.
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
+ * object and returns true if the headers match the current definition.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ *
+ * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
+ * – The respond method takes a set of static data to be returned or a function that can return
+ * an array containing response status (number), response data (string) and response headers
+ * (Object).
+ */
+ $httpBackend.when = function(method, url, data, headers) {
+ var definition = new MockHttpExpectation(method, url, data, headers),
+ chain = {
+ respond: function(status, data, headers) {
+ definition.response = createResponse(status, data, headers);
+ }
+ };
+
+ if ($browser) {
+ chain.passThrough = function() {
+ definition.passThrough = true;
+ };
+ }
+
+ definitions.push(definition);
+ return chain;
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenGET
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for GET requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenHEAD
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for HEAD requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenDELETE
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for DELETE requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenPOST
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for POST requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenPUT
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for PUT requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#whenJSONP
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new backend definition for JSONP requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+ createShortMethods('when');
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expect
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation.
+ *
+ * @param {string} method HTTP method.
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
+ * object and returns true if the headers match the current expectation.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ *
+ * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
+ * – The respond method takes a set of static data to be returned or a function that can return
+ * an array containing response status (number), response data (string) and response headers
+ * (Object).
+ */
+ $httpBackend.expect = function(method, url, data, headers) {
+ var expectation = new MockHttpExpectation(method, url, data, headers);
+ expectations.push(expectation);
+ return {
+ respond: function(status, data, headers) {
+ expectation.response = createResponse(status, data, headers);
+ }
+ };
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectGET
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for GET requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled. See #expect for more info.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectHEAD
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for HEAD requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectDELETE
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for DELETE requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectPOST
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for POST requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectPUT
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for PUT requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectPATCH
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for PATCH requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#expectJSONP
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Creates a new request expectation for JSONP requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * request is handled.
+ */
+ createShortMethods('expect');
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#flush
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Flushes all pending requests using the trained responses.
+ *
+ * @param {number=} count Number of responses to flush (in the order they arrived). If undefined,
+ * all pending requests will be flushed. If there are no pending requests when the flush method
+ * is called an exception is thrown (as this typically a sign of programming error).
+ */
+ $httpBackend.flush = function(count) {
+ $rootScope.$digest();
+ if (!responses.length) throw Error('No pending request to flush !');
+
+ if (angular.isDefined(count)) {
+ while (count--) {
+ if (!responses.length) throw Error('No more pending request to flush !');
+ responses.shift()();
+ }
+ } else {
+ while (responses.length) {
+ responses.shift()();
+ }
+ }
+ $httpBackend.verifyNoOutstandingExpectation();
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#verifyNoOutstandingExpectation
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Verifies that all of the requests defined via the `expect` api were made. If any of the
+ * requests were not made, verifyNoOutstandingExpectation throws an exception.
+ *
+ * Typically, you would call this method following each test case that asserts requests using an
+ * "afterEach" clause.
+ *
+ * <pre>
+ * afterEach($httpBackend.verifyExpectations);
+ * </pre>
+ */
+ $httpBackend.verifyNoOutstandingExpectation = function() {
+ $rootScope.$digest();
+ if (expectations.length) {
+ throw Error('Unsatisfied requests: ' + expectations.join(', '));
+ }
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#verifyNoOutstandingRequest
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Verifies that there are no outstanding requests that need to be flushed.
+ *
+ * Typically, you would call this method following each test case that asserts requests using an
+ * "afterEach" clause.
+ *
+ * <pre>
+ * afterEach($httpBackend.verifyNoOutstandingRequest);
+ * </pre>
+ */
+ $httpBackend.verifyNoOutstandingRequest = function() {
+ if (responses.length) {
+ throw Error('Unflushed requests: ' + responses.length);
+ }
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$httpBackend#resetExpectations
+ * @methodOf ngMock.$httpBackend
+ * @description
+ * Resets all request expectations, but preserves all backend definitions. Typically, you would
+ * call resetExpectations during a multiple-phase test when you want to reuse the same instance of
+ * $httpBackend mock.
+ */
+ $httpBackend.resetExpectations = function() {
+ expectations.length = 0;
+ responses.length = 0;
+ };
+
+ return $httpBackend;
+
+
+ function createShortMethods(prefix) {
+ angular.forEach(['GET', 'DELETE', 'JSONP'], function(method) {
+ $httpBackend[prefix + method] = function(url, headers) {
+ return $httpBackend[prefix](method, url, undefined, headers)
+ }
+ });
+
+ angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
+ $httpBackend[prefix + method] = function(url, data, headers) {
+ return $httpBackend[prefix](method, url, data, headers)
+ }
+ });
+ }
+}
+
+function MockHttpExpectation(method, url, data, headers) {
+
+ this.data = data;
+ this.headers = headers;
+
+ this.match = function(m, u, d, h) {
+ if (method != m) return false;
+ if (!this.matchUrl(u)) return false;
+ if (angular.isDefined(d) && !this.matchData(d)) return false;
+ if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
+ return true;
+ };
+
+ this.matchUrl = function(u) {
+ if (!url) return true;
+ if (angular.isFunction(url.test)) return url.test(u);
+ return url == u;
+ };
+
+ this.matchHeaders = function(h) {
+ if (angular.isUndefined(headers)) return true;
+ if (angular.isFunction(headers)) return headers(h);
+ return angular.equals(headers, h);
+ };
+
+ this.matchData = function(d) {
+ if (angular.isUndefined(data)) return true;
+ if (data && angular.isFunction(data.test)) return data.test(d);
+ if (data && !angular.isString(data)) return angular.toJson(data) == d;
+ return data == d;
+ };
+
+ this.toString = function() {
+ return method + ' ' + url;
+ };
+}
+
+function MockXhr() {
+
+ // hack for testing $http, $httpBackend
+ MockXhr.$$lastInstance = this;
+
+ this.open = function(method, url, async) {
+ this.$$method = method;
+ this.$$url = url;
+ this.$$async = async;
+ this.$$reqHeaders = {};
+ this.$$respHeaders = {};
+ };
+
+ this.send = function(data) {
+ this.$$data = data;
+ };
+
+ this.setRequestHeader = function(key, value) {
+ this.$$reqHeaders[key] = value;
+ };
+
+ this.getResponseHeader = function(name) {
+ // the lookup must be case insensitive, that's why we try two quick lookups and full scan at last
+ var header = this.$$respHeaders[name];
+ if (header) return header;
+
+ name = angular.lowercase(name);
+ header = this.$$respHeaders[name];
+ if (header) return header;
+
+ header = undefined;
+ angular.forEach(this.$$respHeaders, function(headerVal, headerName) {
+ if (!header && angular.lowercase(headerName) == name) header = headerVal;
+ });
+ return header;
+ };
+
+ this.getAllResponseHeaders = function() {
+ var lines = [];
+
+ angular.forEach(this.$$respHeaders, function(value, key) {
+ lines.push(key + ': ' + value);
+ });
+ return lines.join('\n');
+ };
+
+ this.abort = angular.noop;
+}
+
+
+/**
+ * @ngdoc function
+ * @name ngMock.$timeout
+ * @description
+ *
+ * This service is just a simple decorator for {@link ng.$timeout $timeout} service
+ * that adds a "flush" and "verifyNoPendingTasks" methods.
+ */
+
+angular.mock.$TimeoutDecorator = function($delegate, $browser) {
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$timeout#flush
+ * @methodOf ngMock.$timeout
+ * @description
+ *
+ * Flushes the queue of pending tasks.
+ */
+ $delegate.flush = function() {
+ $browser.defer.flush();
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngMock.$timeout#verifyNoPendingTasks
+ * @methodOf ngMock.$timeout
+ * @description
+ *
+ * Verifies that there are no pending tasks that need to be flushed.
+ */
+ $delegate.verifyNoPendingTasks = function() {
+ if ($browser.deferredFns.length) {
+ throw Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' +
+ formatPendingTasksAsString($browser.deferredFns));
+ }
+ };
+
+ function formatPendingTasksAsString(tasks) {
+ var result = [];
+ angular.forEach(tasks, function(task) {
+ result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}');
+ });
+
+ return result.join(', ');
+ }
+
+ return $delegate;
+};
+
+/**
+ *
+ */
+angular.mock.$RootElementProvider = function() {
+ this.$get = function() {
+ return angular.element('<div ng-app></div>');
+ }
+};
+
+/**
+ * @ngdoc overview
+ * @name ngMock
+ * @description
+ *
+ * The `ngMock` is an angular module which is used with `ng` module and adds unit-test configuration as well as useful
+ * mocks to the {@link AUTO.$injector $injector}.
+ */
+angular.module('ngMock', ['ng']).provider({
+ $browser: angular.mock.$BrowserProvider,
+ $exceptionHandler: angular.mock.$ExceptionHandlerProvider,
+ $log: angular.mock.$LogProvider,
+ $httpBackend: angular.mock.$HttpBackendProvider,
+ $rootElement: angular.mock.$RootElementProvider
+}).config(function($provide) {
+ $provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
+});
+
+/**
+ * @ngdoc overview
+ * @name ngMockE2E
+ * @description
+ *
+ * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
+ * Currently there is only one mock present in this module -
+ * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
+ */
+angular.module('ngMockE2E', ['ng']).config(function($provide) {
+ $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
+});
+
+/**
+ * @ngdoc object
+ * @name ngMockE2E.$httpBackend
+ * @description
+ * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
+ * applications that use the {@link ng.$http $http service}.
+ *
+ * *Note*: For fake http backend implementation suitable for unit testing please see
+ * {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
+ *
+ * This implementation can be used to respond with static or dynamic responses via the `when` api
+ * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
+ * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
+ * templates from a webserver).
+ *
+ * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
+ * is being developed with the real backend api replaced with a mock, it is often desirable for
+ * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
+ * templates or static files from the webserver). To configure the backend with this behavior
+ * use the `passThrough` request handler of `when` instead of `respond`.
+ *
+ * Additionally, we don't want to manually have to flush mocked out requests like we do during unit
+ * testing. For this reason the e2e $httpBackend automatically flushes mocked out requests
+ * automatically, closely simulating the behavior of the XMLHttpRequest object.
+ *
+ * To setup the application to run with this http backend, you have to create a module that depends
+ * on the `ngMockE2E` and your application modules and defines the fake backend:
+ *
+ * <pre>
+ * myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
+ * myAppDev.run(function($httpBackend) {
+ * phones = [{name: 'phone1'}, {name: 'phone2'}];
+ *
+ * // returns the current list of phones
+ * $httpBackend.whenGET('/phones').respond(phones);
+ *
+ * // adds a new phone to the phones array
+ * $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
+ * phones.push(angular.fromJSON(data));
+ * });
+ * $httpBackend.whenGET(/^\/templates\//).passThrough();
+ * //...
+ * });
+ * </pre>
+ *
+ * Afterwards, bootstrap your app with this new module.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#when
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition.
+ *
+ * @param {string} method HTTP method.
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
+ * object and returns true if the headers match the current definition.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ *
+ * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
+ * – The respond method takes a set of static data to be returned or a function that can return
+ * an array containing response status (number), response data (string) and response headers
+ * (Object).
+ * - passThrough – `{function()}` – Any request matching a backend definition with `passThrough`
+ * handler, will be pass through to the real backend (an XHR request will be made to the
+ * server.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#whenGET
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition for GET requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#whenHEAD
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition for HEAD requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#whenDELETE
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition for DELETE requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#whenPOST
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition for POST requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#whenPUT
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition for PUT requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#whenPATCH
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition for PATCH requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name ngMockE2E.$httpBackend#whenJSONP
+ * @methodOf ngMockE2E.$httpBackend
+ * @description
+ * Creates a new backend definition for JSONP requests. For more info see `when()`.
+ *
+ * @param {string|RegExp} url HTTP url.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled.
+ */
+angular.mock.e2e = {};
+angular.mock.e2e.$httpBackendDecorator = ['$rootScope', '$delegate', '$browser', createHttpBackendMock];
+
+
+angular.mock.clearDataCache = function() {
+ var key,
+ cache = angular.element.cache;
+
+ for(key in cache) {
+ if (cache.hasOwnProperty(key)) {
+ var handle = cache[key].handle;
+
+ handle && angular.element(handle.elem).unbind();
+ delete cache[key];
+ }
+ }
+};
+
+
+window.jstestdriver && (function(window) {
+ /**
+ * Global method to output any number of objects into JSTD console. Useful for debugging.
+ */
+ window.dump = function() {
+ var args = [];
+ angular.forEach(arguments, function(arg) {
+ args.push(angular.mock.dump(arg));
+ });
+ jstestdriver.console.log.apply(jstestdriver.console, args);
+ if (window.console) {
+ window.console.log.apply(window.console, args);
+ }
+ };
+})(window);
+
+
+(window.jasmine || window.mocha) && (function(window) {
+
+ var currentSpec = null;
+
+ beforeEach(function() {
+ currentSpec = this;
+ });
+
+ afterEach(function() {
+ var injector = currentSpec.$injector;
+
+ currentSpec.$injector = null;
+ currentSpec.$modules = null;
+ currentSpec = null;
+
+ if (injector) {
+ injector.get('$rootElement').unbind();
+ injector.get('$browser').pollFns.length = 0;
+ }
+
+ angular.mock.clearDataCache();
+
+ // clean up jquery's fragment cache
+ angular.forEach(angular.element.fragments, function(val, key) {
+ delete angular.element.fragments[key];
+ });
+
+ MockXhr.$$lastInstance = null;
+
+ angular.forEach(angular.callbacks, function(val, key) {
+ delete angular.callbacks[key];
+ });
+ angular.callbacks.counter = 0;
+ });
+
+ function isSpecRunning() {
+ return currentSpec && (window.mocha || currentSpec.queue.running);
+ }
+
+ /**
+ * @ngdoc function
+ * @name angular.mock.module
+ * @description
+ *
+ * *NOTE*: This function is also published on window for easy access.<br>
+ *
+ * This function registers a module configuration code. It collects the configuration information
+ * which will be used when the injector is created by {@link angular.mock.inject inject}.
+ *
+ * See {@link angular.mock.inject inject} for usage example
+ *
+ * @param {...(string|Function)} fns any number of modules which are represented as string
+ * aliases or as anonymous module initialization functions. The modules are used to
+ * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded.
+ */
+ window.module = angular.mock.module = function() {
+ var moduleFns = Array.prototype.slice.call(arguments, 0);
+ return isSpecRunning() ? workFn() : workFn;
+ /////////////////////
+ function workFn() {
+ if (currentSpec.$injector) {
+ throw Error('Injector already created, can not register a module!');
+ } else {
+ var modules = currentSpec.$modules || (currentSpec.$modules = []);
+ angular.forEach(moduleFns, function(module) {
+ modules.push(module);
+ });
+ }
+ }
+ };
+
+ /**
+ * @ngdoc function
+ * @name angular.mock.inject
+ * @description
+ *
+ * *NOTE*: This function is also published on window for easy access.<br>
+ *
+ * The inject function wraps a function into an injectable function. The inject() creates new
+ * instance of {@link AUTO.$injector $injector} per test, which is then used for
+ * resolving references.
+ *
+ * See also {@link angular.mock.module module}
+ *
+ * Example of what a typical jasmine tests looks like with the inject method.
+ * <pre>
+ *
+ * angular.module('myApplicationModule', [])
+ * .value('mode', 'app')
+ * .value('version', 'v1.0.1');
+ *
+ *
+ * describe('MyApp', function() {
+ *
+ * // You need to load modules that you want to test,
+ * // it loads only the "ng" module by default.
+ * beforeEach(module('myApplicationModule'));
+ *
+ *
+ * // inject() is used to inject arguments of all given functions
+ * it('should provide a version', inject(function(mode, version) {
+ * expect(version).toEqual('v1.0.1');
+ * expect(mode).toEqual('app');
+ * }));
+ *
+ *
+ * // The inject and module method can also be used inside of the it or beforeEach
+ * it('should override a version and test the new version is injected', function() {
+ * // module() takes functions or strings (module aliases)
+ * module(function($provide) {
+ * $provide.value('version', 'overridden'); // override version here
+ * });
+ *
+ * inject(function(version) {
+ * expect(version).toEqual('overridden');
+ * });
+ * ));
+ * });
+ *
+ * </pre>
+ *
+ * @param {...Function} fns any number of functions which will be injected using the injector.
+ */
+ window.inject = angular.mock.inject = function() {
+ var blockFns = Array.prototype.slice.call(arguments, 0);
+ var errorForStack = new Error('Declaration Location');
+ return isSpecRunning() ? workFn() : workFn;
+ /////////////////////
+ function workFn() {
+ var modules = currentSpec.$modules || [];
+
+ modules.unshift('ngMock');
+ modules.unshift('ng');
+ var injector = currentSpec.$injector;
+ if (!injector) {
+ injector = currentSpec.$injector = angular.injector(modules);
+ }
+ for(var i = 0, ii = blockFns.length; i < ii; i++) {
+ try {
+ injector.invoke(blockFns[i] || angular.noop, this);
+ } catch (e) {
+ if(e.stack && errorForStack) e.stack += '\n' + errorForStack.stack;
+ throw e;
+ } finally {
+ errorForStack = null;
+ }
+ }
+ }
+ };
+})(window);
diff --git a/java/jenkins_plugins/build_monitor/src/test/resources/vendor/jasmine-sinon-0.3.1.js b/java/jenkins_plugins/build_monitor/src/test/resources/vendor/jasmine-sinon-0.3.1.js
new file mode 100644
index 0000000..c49ff92
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/resources/vendor/jasmine-sinon-0.3.1.js
@@ -0,0 +1,58 @@
+/* global jasmine */
+
+'use strict';
+
+(function(jasmine, beforeEach) {
+
+ var sinon = (typeof require === 'function' && typeof module === 'object') ? require('sinon') : window.sinon,
+ spyMatchers = 'called calledOnce calledTwice calledThrice calledBefore calledAfter calledOn alwaysCalledOn calledWith alwaysCalledWith calledWithExactly alwaysCalledWithExactly calledWithMatch alwaysCalledWithMatch'.split(' '),
+ i = spyMatchers.length,
+ spyMatcherHash = {},
+ unusualMatchers = {
+ "returned": "toHaveReturned",
+ "alwaysReturned": "toHaveAlwaysReturned",
+ "threw": "toHaveThrown",
+ "alwaysThrew": "toHaveAlwaysThrown"
+ },
+
+ createCustomMatcher = function(arg) {
+ return sinon.match(function (val) {
+ return jasmine.getEnv().equals_(val, arg);
+ });
+ },
+
+ getMatcherFunction = function(sinonName, matcherName) {
+ var original = jasmine.Matchers.prototype[matcherName];
+ return function () {
+ if (jasmine.isSpy(this.actual) && original) {
+ return original.apply(this, arguments);
+ }
+ var sinonProperty = this.actual[sinonName];
+ var args = Array.prototype.slice.call(arguments);
+
+ for (var i = 0; i < args.length; i++) {
+ if (args[i] && (typeof args[i].jasmineMatches === 'function' || args[i] instanceof jasmine.Matchers.ObjectContaining)) {
+ args[i] = createCustomMatcher(args[i]);
+ }
+ }
+
+ return (typeof sinonProperty === 'function') ? sinonProperty.apply(this.actual, args) : sinonProperty;
+ };
+ };
+
+ while(i--) {
+ var sinonName = spyMatchers[i],
+ matcherName = "toHaveBeen" + sinonName.charAt(0).toUpperCase() + sinonName.slice(1);
+
+ spyMatcherHash[matcherName] = getMatcherFunction(sinonName, matcherName);
+ }
+
+ for (var j in unusualMatchers) {
+ spyMatcherHash[unusualMatchers[j]] = getMatcherFunction(j, unusualMatchers[j]);
+ }
+
+ beforeEach(function() {
+ this.addMatchers(spyMatcherHash);
+ });
+
+})(jasmine, beforeEach);
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/resources/vendor/sinon-1.7.3.js b/java/jenkins_plugins/build_monitor/src/test/resources/vendor/sinon-1.7.3.js
new file mode 100644
index 0000000..26c4bd9
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/resources/vendor/sinon-1.7.3.js
@@ -0,0 +1,4290 @@
+/**
+ * Sinon.JS 1.7.3, 2013/06/20
+ *
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS
+ *
+ * (The BSD License)
+ *
+ * Copyright (c) 2010-2013, Christian Johansen, christian@cjohansen.no
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * * Neither the name of Christian Johansen nor the names of his contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+this.sinon = (function () {
+var buster = (function (setTimeout, B) {
+ var isNode = typeof require == "function" && typeof module == "object";
+ var div = typeof document != "undefined" && document.createElement("div");
+ var F = function () {};
+
+ var buster = {
+ bind: function bind(obj, methOrProp) {
+ var method = typeof methOrProp == "string" ? obj[methOrProp] : methOrProp;
+ var args = Array.prototype.slice.call(arguments, 2);
+ return function () {
+ var allArgs = args.concat(Array.prototype.slice.call(arguments));
+ return method.apply(obj, allArgs);
+ };
+ },
+
+ partial: function partial(fn) {
+ var args = [].slice.call(arguments, 1);
+ return function () {
+ return fn.apply(this, args.concat([].slice.call(arguments)));
+ };
+ },
+
+ create: function create(object) {
+ F.prototype = object;
+ return new F();
+ },
+
+ extend: function extend(target) {
+ if (!target) { return; }
+ for (var i = 1, l = arguments.length, prop; i < l; ++i) {
+ for (prop in arguments[i]) {
+ target[prop] = arguments[i][prop];
+ }
+ }
+ return target;
+ },
+
+ nextTick: function nextTick(callback) {
+ if (typeof process != "undefined" && process.nextTick) {
+ return process.nextTick(callback);
+ }
+ setTimeout(callback, 0);
+ },
+
+ functionName: function functionName(func) {
+ if (!func) return "";
+ if (func.displayName) return func.displayName;
+ if (func.name) return func.name;
+ var matches = func.toString().match(/function\s+([^\(]+)/m);
+ return matches && matches[1] || "";
+ },
+
+ isNode: function isNode(obj) {
+ if (!div) return false;
+ try {
+ obj.appendChild(div);
+ obj.removeChild(div);
+ } catch (e) {
+ return false;
+ }
+ return true;
+ },
+
+ isElement: function isElement(obj) {
+ return obj && obj.nodeType === 1 && buster.isNode(obj);
+ },
+
+ isArray: function isArray(arr) {
+ return Object.prototype.toString.call(arr) == "[object Array]";
+ },
+
+ flatten: function flatten(arr) {
+ var result = [], arr = arr || [];
+ for (var i = 0, l = arr.length; i < l; ++i) {
+ result = result.concat(buster.isArray(arr[i]) ? flatten(arr[i]) : arr[i]);
+ }
+ return result;
+ },
+
+ each: function each(arr, callback) {
+ for (var i = 0, l = arr.length; i < l; ++i) {
+ callback(arr[i]);
+ }
+ },
+
+ map: function map(arr, callback) {
+ var results = [];
+ for (var i = 0, l = arr.length; i < l; ++i) {
+ results.push(callback(arr[i]));
+ }
+ return results;
+ },
+
+ parallel: function parallel(fns, callback) {
+ function cb(err, res) {
+ if (typeof callback == "function") {
+ callback(err, res);
+ callback = null;
+ }
+ }
+ if (fns.length == 0) { return cb(null, []); }
+ var remaining = fns.length, results = [];
+ function makeDone(num) {
+ return function done(err, result) {
+ if (err) { return cb(err); }
+ results[num] = result;
+ if (--remaining == 0) { cb(null, results); }
+ };
+ }
+ for (var i = 0, l = fns.length; i < l; ++i) {
+ fns[i](makeDone(i));
+ }
+ },
+
+ series: function series(fns, callback) {
+ function cb(err, res) {
+ if (typeof callback == "function") {
+ callback(err, res);
+ }
+ }
+ var remaining = fns.slice();
+ var results = [];
+ function callNext() {
+ if (remaining.length == 0) return cb(null, results);
+ var promise = remaining.shift()(next);
+ if (promise && typeof promise.then == "function") {
+ promise.then(buster.partial(next, null), next);
+ }
+ }
+ function next(err, result) {
+ if (err) return cb(err);
+ results.push(result);
+ callNext();
+ }
+ callNext();
+ },
+
+ countdown: function countdown(num, done) {
+ return function () {
+ if (--num == 0) done();
+ };
+ }
+ };
+
+ if (typeof process === "object" &&
+ typeof require === "function" && typeof module === "object") {
+ var crypto = require("crypto");
+ var path = require("path");
+
+ buster.tmpFile = function (fileName) {
+ var hashed = crypto.createHash("sha1");
+ hashed.update(fileName);
+ var tmpfileName = hashed.digest("hex");
+
+ if (process.platform == "win32") {
+ return path.join(process.env["TEMP"], tmpfileName);
+ } else {
+ return path.join("/tmp", tmpfileName);
+ }
+ };
+ }
+
+ if (Array.prototype.some) {
+ buster.some = function (arr, fn, thisp) {
+ return arr.some(fn, thisp);
+ };
+ } else {
+ // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
+ buster.some = function (arr, fun, thisp) {
+ if (arr == null) { throw new TypeError(); }
+ arr = Object(arr);
+ var len = arr.length >>> 0;
+ if (typeof fun !== "function") { throw new TypeError(); }
+
+ for (var i = 0; i < len; i++) {
+ if (arr.hasOwnProperty(i) && fun.call(thisp, arr[i], i, arr)) {
+ return true;
+ }
+ }
+
+ return false;
+ };
+ }
+
+ if (Array.prototype.filter) {
+ buster.filter = function (arr, fn, thisp) {
+ return arr.filter(fn, thisp);
+ };
+ } else {
+ // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
+ buster.filter = function (fn, thisp) {
+ if (this == null) { throw new TypeError(); }
+
+ var t = Object(this);
+ var len = t.length >>> 0;
+ if (typeof fn != "function") { throw new TypeError(); }
+
+ var res = [];
+ for (var i = 0; i < len; i++) {
+ if (i in t) {
+ var val = t[i]; // in case fun mutates this
+ if (fn.call(thisp, val, i, t)) { res.push(val); }
+ }
+ }
+
+ return res;
+ };
+ }
+
+ if (isNode) {
+ module.exports = buster;
+ buster.eventEmitter = require("./buster-event-emitter");
+ Object.defineProperty(buster, "defineVersionGetter", {
+ get: function () {
+ return require("./define-version-getter");
+ }
+ });
+ }
+
+ return buster.extend(B || {}, buster);
+}(setTimeout, buster));
+if (typeof buster === "undefined") {
+ var buster = {};
+}
+
+if (typeof module === "object" && typeof require === "function") {
+ buster = require("buster-core");
+}
+
+buster.format = buster.format || {};
+buster.format.excludeConstructors = ["Object", /^.$/];
+buster.format.quoteStrings = true;
+
+buster.format.ascii = (function () {
+
+ var hasOwn = Object.prototype.hasOwnProperty;
+
+ var specialObjects = [];
+ if (typeof global != "undefined") {
+ specialObjects.push({ obj: global, value: "[object global]" });
+ }
+ if (typeof document != "undefined") {
+ specialObjects.push({ obj: document, value: "[object HTMLDocument]" });
+ }
+ if (typeof window != "undefined") {
+ specialObjects.push({ obj: window, value: "[object Window]" });
+ }
+
+ function keys(object) {
+ var k = Object.keys && Object.keys(object) || [];
+
+ if (k.length == 0) {
+ for (var prop in object) {
+ if (hasOwn.call(object, prop)) {
+ k.push(prop);
+ }
+ }
+ }
+
+ return k.sort();
+ }
+
+ function isCircular(object, objects) {
+ if (typeof object != "object") {
+ return false;
+ }
+
+ for (var i = 0, l = objects.length; i < l; ++i) {
+ if (objects[i] === object) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ function ascii(object, processed, indent) {
+ if (typeof object == "string") {
+ var quote = typeof this.quoteStrings != "boolean" || this.quoteStrings;
+ return processed || quote ? '"' + object + '"' : object;
+ }
+
+ if (typeof object == "function" && !(object instanceof RegExp)) {
+ return ascii.func(object);
+ }
+
+ processed = processed || [];
+
+ if (isCircular(object, processed)) {
+ return "[Circular]";
+ }
+
+ if (Object.prototype.toString.call(object) == "[object Array]") {
+ return ascii.array.call(this, object, processed);
+ }
+
+ if (!object) {
+ return "" + object;
+ }
+
+ if (buster.isElement(object)) {
+ return ascii.element(object);
+ }
+
+ if (typeof object.toString == "function" &&
+ object.toString !== Object.prototype.toString) {
+ return object.toString();
+ }
+
+ for (var i = 0, l = specialObjects.length; i < l; i++) {
+ if (object === specialObjects[i].obj) {
+ return specialObjects[i].value;
+ }
+ }
+
+ return ascii.object.call(this, object, processed, indent);
+ }
+
+ ascii.func = function (func) {
+ return "function " + buster.functionName(func) + "() {}";
+ };
+
+ ascii.array = function (array, processed) {
+ processed = processed || [];
+ processed.push(array);
+ var pieces = [];
+
+ for (var i = 0, l = array.length; i < l; ++i) {
+ pieces.push(ascii.call(this, array[i], processed));
+ }
+
+ return "[" + pieces.join(", ") + "]";
+ };
+
+ ascii.object = function (object, processed, indent) {
+ processed = processed || [];
+ processed.push(object);
+ indent = indent || 0;
+ var pieces = [], properties = keys(object), prop, str, obj;
+ var is = "";
+ var length = 3;
+
+ for (var i = 0, l = indent; i < l; ++i) {
+ is += " ";
+ }
+
+ for (i = 0, l = properties.length; i < l; ++i) {
+ prop = properties[i];
+ obj = object[prop];
+
+ if (isCircular(obj, processed)) {
+ str = "[Circular]";
+ } else {
+ str = ascii.call(this, obj, processed, indent + 2);
+ }
+
+ str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str;
+ length += str.length;
+ pieces.push(str);
+ }
+
+ var cons = ascii.constructorName.call(this, object);
+ var prefix = cons ? "[" + cons + "] " : ""
+
+ return (length + indent) > 80 ?
+ prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" + is + "}" :
+ prefix + "{ " + pieces.join(", ") + " }";
+ };
+
+ ascii.element = function (element) {
+ var tagName = element.tagName.toLowerCase();
+ var attrs = element.attributes, attribute, pairs = [], attrName;
+
+ for (var i = 0, l = attrs.length; i < l; ++i) {
+ attribute = attrs.item(i);
+ attrName = attribute.nodeName.toLowerCase().replace("html:", "");
+
+ if (attrName == "contenteditable" && attribute.nodeValue == "inherit") {
+ continue;
+ }
+
+ if (!!attribute.nodeValue) {
+ pairs.push(attrName + "=\"" + attribute.nodeValue + "\"");
+ }
+ }
+
+ var formatted = "<" + tagName + (pairs.length > 0 ? " " : "");
+ var content = element.innerHTML;
+
+ if (content.length > 20) {
+ content = content.substr(0, 20) + "[...]";
+ }
+
+ var res = formatted + pairs.join(" ") + ">" + content + "</" + tagName + ">";
+
+ return res.replace(/ contentEditable="inherit"/, "");
+ };
+
+ ascii.constructorName = function (object) {
+ var name = buster.functionName(object && object.constructor);
+ var excludes = this.excludeConstructors || buster.format.excludeConstructors || [];
+
+ for (var i = 0, l = excludes.length; i < l; ++i) {
+ if (typeof excludes[i] == "string" && excludes[i] == name) {
+ return "";
+ } else if (excludes[i].test && excludes[i].test(name)) {
+ return "";
+ }
+ }
+
+ return name;
+ };
+
+ return ascii;
+}());
+
+if (typeof module != "undefined") {
+ module.exports = buster.format;
+}
+/*jslint eqeqeq: false, onevar: false, forin: true, nomen: false, regexp: false, plusplus: false*/
+/*global module, require, __dirname, document*/
+/**
+ * Sinon core utilities. For internal use only.
+ *
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @license BSD
+ *
+ * Copyright (c) 2010-2013 Christian Johansen
+ */
+
+var sinon = (function (buster) {
+ var div = typeof document != "undefined" && document.createElement("div");
+ var hasOwn = Object.prototype.hasOwnProperty;
+
+ function isDOMNode(obj) {
+ var success = false;
+
+ try {
+ obj.appendChild(div);
+ success = div.parentNode == obj;
+ } catch (e) {
+ return false;
+ } finally {
+ try {
+ obj.removeChild(div);
+ } catch (e) {
+ // Remove failed, not much we can do about that
+ }
+ }
+
+ return success;
+ }
+
+ function isElement(obj) {
+ return div && obj && obj.nodeType === 1 && isDOMNode(obj);
+ }
+
+ function isFunction(obj) {
+ return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply);
+ }
+
+ function mirrorProperties(target, source) {
+ for (var prop in source) {
+ if (!hasOwn.call(target, prop)) {
+ target[prop] = source[prop];
+ }
+ }
+ }
+
+ function isRestorable (obj) {
+ return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon;
+ }
+
+ var sinon = {
+ wrapMethod: function wrapMethod(object, property, method) {
+ if (!object) {
+ throw new TypeError("Should wrap property of object");
+ }
+
+ if (typeof method != "function") {
+ throw new TypeError("Method wrapper should be function");
+ }
+
+ var wrappedMethod = object[property];
+
+ if (!isFunction(wrappedMethod)) {
+ throw new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " +
+ property + " as function");
+ }
+
+ if (wrappedMethod.restore && wrappedMethod.restore.sinon) {
+ throw new TypeError("Attempted to wrap " + property + " which is already wrapped");
+ }
+
+ if (wrappedMethod.calledBefore) {
+ var verb = !!wrappedMethod.returns ? "stubbed" : "spied on";
+ throw new TypeError("Attempted to wrap " + property + " which is already " + verb);
+ }
+
+ // IE 8 does not support hasOwnProperty on the window object.
+ var owned = hasOwn.call(object, property);
+ object[property] = method;
+ method.displayName = property;
+
+ method.restore = function () {
+ // For prototype properties try to reset by delete first.
+ // If this fails (ex: localStorage on mobile safari) then force a reset
+ // via direct assignment.
+ if (!owned) {
+ delete object[property];
+ }
+ if (object[property] === method) {
+ object[property] = wrappedMethod;
+ }
+ };
+
+ method.restore.sinon = true;
+ mirrorProperties(method, wrappedMethod);
+
+ return method;
+ },
+
+ extend: function extend(target) {
+ for (var i = 1, l = arguments.length; i < l; i += 1) {
+ for (var prop in arguments[i]) {
+ if (arguments[i].hasOwnProperty(prop)) {
+ target[prop] = arguments[i][prop];
+ }
+
+ // DONT ENUM bug, only care about toString
+ if (arguments[i].hasOwnProperty("toString") &&
+ arguments[i].toString != target.toString) {
+ target.toString = arguments[i].toString;
+ }
+ }
+ }
+
+ return target;
+ },
+
+ create: function create(proto) {
+ var F = function () {};
+ F.prototype = proto;
+ return new F();
+ },
+
+ deepEqual: function deepEqual(a, b) {
+ if (sinon.match && sinon.match.isMatcher(a)) {
+ return a.test(b);
+ }
+ if (typeof a != "object" || typeof b != "object") {
+ return a === b;
+ }
+
+ if (isElement(a) || isElement(b)) {
+ return a === b;
+ }
+
+ if (a === b) {
+ return true;
+ }
+
+ if ((a === null && b !== null) || (a !== null && b === null)) {
+ return false;
+ }
+
+ var aString = Object.prototype.toString.call(a);
+ if (aString != Object.prototype.toString.call(b)) {
+ return false;
+ }
+
+ if (aString == "[object Array]") {
+ if (a.length !== b.length) {
+ return false;
+ }
+
+ for (var i = 0, l = a.length; i < l; i += 1) {
+ if (!deepEqual(a[i], b[i])) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ if (aString == "[object Date]") {
+ return a.valueOf() === b.valueOf();
+ }
+
+ var prop, aLength = 0, bLength = 0;
+
+ for (prop in a) {
+ aLength += 1;
+
+ if (!deepEqual(a[prop], b[prop])) {
+ return false;
+ }
+ }
+
+ for (prop in b) {
+ bLength += 1;
+ }
+
+ return aLength == bLength;
+ },
+
+ functionName: function functionName(func) {
+ var name = func.displayName || func.name;
+
+ // Use function decomposition as a last resort to get function
+ // name. Does not rely on function decomposition to work - if it
+ // doesn't debugging will be slightly less informative
+ // (i.e. toString will say 'spy' rather than 'myFunc').
+ if (!name) {
+ var matches = func.toString().match(/function ([^\s\(]+)/);
+ name = matches && matches[1];
+ }
+
+ return name;
+ },
+
+ functionToString: function toString() {
+ if (this.getCall && this.callCount) {
+ var thisValue, prop, i = this.callCount;
+
+ while (i--) {
+ thisValue = this.getCall(i).thisValue;
+
+ for (prop in thisValue) {
+ if (thisValue[prop] === this) {
+ return prop;
+ }
+ }
+ }
+ }
+
+ return this.displayName || "sinon fake";
+ },
+
+ getConfig: function (custom) {
+ var config = {};
+ custom = custom || {};
+ var defaults = sinon.defaultConfig;
+
+ for (var prop in defaults) {
+ if (defaults.hasOwnProperty(prop)) {
+ config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop];
+ }
+ }
+
+ return config;
+ },
+
+ format: function (val) {
+ return "" + val;
+ },
+
+ defaultConfig: {
+ injectIntoThis: true,
+ injectInto: null,
+ properties: ["spy", "stub", "mock", "clock", "server", "requests"],
+ useFakeTimers: true,
+ useFakeServer: true
+ },
+
+ timesInWords: function timesInWords(count) {
+ return count == 1 && "once" ||
+ count == 2 && "twice" ||
+ count == 3 && "thrice" ||
+ (count || 0) + " times";
+ },
+
+ calledInOrder: function (spies) {
+ for (var i = 1, l = spies.length; i < l; i++) {
+ if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) {
+ return false;
+ }
+ }
+
+ return true;
+ },
+
+ orderByFirstCall: function (spies) {
+ return spies.sort(function (a, b) {
+ // uuid, won't ever be equal
+ var aCall = a.getCall(0);
+ var bCall = b.getCall(0);
+ var aId = aCall && aCall.callId || -1;
+ var bId = bCall && bCall.callId || -1;
+
+ return aId < bId ? -1 : 1;
+ });
+ },
+
+ log: function () {},
+
+ logError: function (label, err) {
+ var msg = label + " threw exception: "
+ sinon.log(msg + "[" + err.name + "] " + err.message);
+ if (err.stack) { sinon.log(err.stack); }
+
+ setTimeout(function () {
+ err.message = msg + err.message;
+ throw err;
+ }, 0);
+ },
+
+ typeOf: function (value) {
+ if (value === null) {
+ return "null";
+ }
+ else if (value === undefined) {
+ return "undefined";
+ }
+ var string = Object.prototype.toString.call(value);
+ return string.substring(8, string.length - 1).toLowerCase();
+ },
+
+ createStubInstance: function (constructor) {
+ if (typeof constructor !== "function") {
+ throw new TypeError("The constructor should be a function.");
+ }
+ return sinon.stub(sinon.create(constructor.prototype));
+ },
+
+ restore: function (object) {
+ if (object !== null && typeof object === "object") {
+ for (var prop in object) {
+ if (isRestorable(object[prop])) {
+ object[prop].restore();
+ }
+ }
+ }
+ else if (isRestorable(object)) {
+ object.restore();
+ }
+ }
+ };
+
+ var isNode = typeof module == "object" && typeof require == "function";
+
+ if (isNode) {
+ try {
+ buster = { format: require("buster-format") };
+ } catch (e) {}
+ module.exports = sinon;
+ module.exports.spy = require("./sinon/spy");
+ module.exports.stub = require("./sinon/stub");
+ module.exports.mock = require("./sinon/mock");
+ module.exports.collection = require("./sinon/collection");
+ module.exports.assert = require("./sinon/assert");
+ module.exports.sandbox = require("./sinon/sandbox");
+ module.exports.test = require("./sinon/test");
+ module.exports.testCase = require("./sinon/test_case");
+ module.exports.assert = require("./sinon/assert");
+ module.exports.match = require("./sinon/match");
+ }
+
+ if (buster) {
+ var formatter = sinon.create(buster.format);
+ formatter.quoteStrings = false;
+ sinon.format = function () {
+ return formatter.ascii.apply(formatter, arguments);
+ };
+ } else if (isNode) {
+ try {
+ var util = require("util");
+ sinon.format = function (value) {
+ return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value;
+ };
+ } catch (e) {
+ /* Node, but no util module - would be very old, but better safe than
+ sorry */
+ }
+ }
+
+ return sinon;
+}(typeof buster == "object" && buster));
+
+/* @depend ../sinon.js */
+/*jslint eqeqeq: false, onevar: false, plusplus: false*/
+/*global module, require, sinon*/
+/**
+ * Match functions
+ *
+ * @author Maximilian Antoni (mail@maxantoni.de)
+ * @license BSD
+ *
+ * Copyright (c) 2012 Maximilian Antoni
+ */
+
+(function (sinon) {
+ var commonJSModule = typeof module == "object" && typeof require == "function";
+
+ if (!sinon && commonJSModule) {
+ sinon = require("../sinon");
+ }
+
+ if (!sinon) {
+ return;
+ }
+
+ function assertType(value, type, name) {
+ var actual = sinon.typeOf(value);
+ if (actual !== type) {
+ throw new TypeError("Expected type of " + name + " to be " +
+ type + ", but was " + actual);
+ }
+ }
+
+ var matcher = {
+ toString: function () {
+ return this.message;
+ }
+ };
+
+ function isMatcher(object) {
+ return matcher.isPrototypeOf(object);
+ }
+
+ function matchObject(expectation, actual) {
+ if (actual === null || actual === undefined) {
+ return false;
+ }
+ for (var key in expectation) {
+ if (expectation.hasOwnProperty(key)) {
+ var exp = expectation[key];
+ var act = actual[key];
+ if (match.isMatcher(exp)) {
+ if (!exp.test(act)) {
+ return false;
+ }
+ } else if (sinon.typeOf(exp) === "object") {
+ if (!matchObject(exp, act)) {
+ return false;
+ }
+ } else if (!sinon.deepEqual(exp, act)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ matcher.or = function (m2) {
+ if (!isMatcher(m2)) {
+ throw new TypeError("Matcher expected");
+ }
+ var m1 = this;
+ var or = sinon.create(matcher);
+ or.test = function (actual) {
+ return m1.test(actual) || m2.test(actual);
+ };
+ or.message = m1.message + ".or(" + m2.message + ")";
+ return or;
+ };
+
+ matcher.and = function (m2) {
+ if (!isMatcher(m2)) {
+ throw new TypeError("Matcher expected");
+ }
+ var m1 = this;
+ var and = sinon.create(matcher);
+ and.test = function (actual) {
+ return m1.test(actual) && m2.test(actual);
+ };
+ and.message = m1.message + ".and(" + m2.message + ")";
+ return and;
+ };
+
+ var match = function (expectation, message) {
+ var m = sinon.create(matcher);
+ var type = sinon.typeOf(expectation);
+ switch (type) {
+ case "object":
+ if (typeof expectation.test === "function") {
+ m.test = function (actual) {
+ return expectation.test(actual) === true;
+ };
+ m.message = "match(" + sinon.functionName(expectation.test) + ")";
+ return m;
+ }
+ var str = [];
+ for (var key in expectation) {
+ if (expectation.hasOwnProperty(key)) {
+ str.push(key + ": " + expectation[key]);
+ }
+ }
+ m.test = function (actual) {
+ return matchObject(expectation, actual);
+ };
+ m.message = "match(" + str.join(", ") + ")";
+ break;
+ case "number":
+ m.test = function (actual) {
+ return expectation == actual;
+ };
+ break;
+ case "string":
+ m.test = function (actual) {
+ if (typeof actual !== "string") {
+ return false;
+ }
+ return actual.indexOf(expectation) !== -1;
+ };
+ m.message = "match(\"" + expectation + "\")";
+ break;
+ case "regexp":
+ m.test = function (actual) {
+ if (typeof actual !== "string") {
+ return false;
+ }
+ return expectation.test(actual);
+ };
+ break;
+ case "function":
+ m.test = expectation;
+ if (message) {
+ m.message = message;
+ } else {
+ m.message = "match(" + sinon.functionName(expectation) + ")";
+ }
+ break;
+ default:
+ m.test = function (actual) {
+ return sinon.deepEqual(expectation, actual);
+ };
+ }
+ if (!m.message) {
+ m.message = "match(" + expectation + ")";
+ }
+ return m;
+ };
+
+ match.isMatcher = isMatcher;
+
+ match.any = match(function () {
+ return true;
+ }, "any");
+
+ match.defined = match(function (actual) {
+ return actual !== null && actual !== undefined;
+ }, "defined");
+
+ match.truthy = match(function (actual) {
+ return !!actual;
+ }, "truthy");
+
+ match.falsy = match(function (actual) {
+ return !actual;
+ }, "falsy");
+
+ match.same = function (expectation) {
+ return match(function (actual) {
+ return expectation === actual;
+ }, "same(" + expectation + ")");
+ };
+
+ match.typeOf = function (type) {
+ assertType(type, "string", "type");
+ return match(function (actual) {
+ return sinon.typeOf(actual) === type;
+ }, "typeOf(\"" + type + "\")");
+ };
+
+ match.instanceOf = function (type) {
+ assertType(type, "function", "type");
+ return match(function (actual) {
+ return actual instanceof type;
+ }, "instanceOf(" + sinon.functionName(type) + ")");
+ };
+
+ function createPropertyMatcher(propertyTest, messagePrefix) {
+ return function (property, value) {
+ assertType(property, "string", "property");
+ var onlyProperty = arguments.length === 1;
+ var message = messagePrefix + "(\"" + property + "\"";
+ if (!onlyProperty) {
+ message += ", " + value;
+ }
+ message += ")";
+ return match(function (actual) {
+ if (actual === undefined || actual === null ||
+ !propertyTest(actual, property)) {
+ return false;
+ }
+ return onlyProperty || sinon.deepEqual(value, actual[property]);
+ }, message);
+ };
+ }
+
+ match.has = createPropertyMatcher(function (actual, property) {
+ if (typeof actual === "object") {
+ return property in actual;
+ }
+ return actual[property] !== undefined;
+ }, "has");
+
+ match.hasOwn = createPropertyMatcher(function (actual, property) {
+ return actual.hasOwnProperty(property);
+ }, "hasOwn");
+
+ match.bool = match.typeOf("boolean");
+ match.number = match.typeOf("number");
+ match.string = match.typeOf("string");
+ match.object = match.typeOf("object");
+ match.func = match.typeOf("function");
+ match.array = match.typeOf("array");
+ match.regexp = match.typeOf("regexp");
+ match.date = match.typeOf("date");
+
+ if (commonJSModule) {
+ module.exports = match;
+ } else {
+ sinon.match = match;
+ }
+}(typeof sinon == "object" && sinon || null));
+
+/**
+ * @depend ../sinon.js
+ * @depend match.js
+ */
+/*jslint eqeqeq: false, onevar: false, plusplus: false*/
+/*global module, require, sinon*/
+/**
+ * Spy calls
+ *
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @author Maximilian Antoni (mail@maxantoni.de)
+ * @license BSD
+ *
+ * Copyright (c) 2010-2013 Christian Johansen
+ * Copyright (c) 2013 Maximilian Antoni
+ */
+
+var commonJSModule = typeof module == "object" && typeof require == "function";
+
+if (!this.sinon && commonJSModule) {
+ var sinon = require("../sinon");
+}
+
+(function (sinon) {
+ function throwYieldError(proxy, text, args) {
+ var msg = sinon.functionName(proxy) + text;
+ if (args.length) {
+ msg += " Received [" + slice.call(args).join(", ") + "]";
+ }
+ throw new Error(msg);
+ }
+
+ var slice = Array.prototype.slice;
+
+ var callProto = {
+ calledOn: function calledOn(thisValue) {
+ if (sinon.match && sinon.match.isMatcher(thisValue)) {
+ return thisValue.test(this.thisValue);
+ }
+ return this.thisValue === thisValue;
+ },
+
+ calledWith: function calledWith() {
+ for (var i = 0, l = arguments.length; i < l; i += 1) {
+ if (!sinon.deepEqual(arguments[i], this.args[i])) {
+ return false;
+ }
+ }
+
+ return true;
+ },
+
+ calledWithMatch: function calledWithMatch() {
+ for (var i = 0, l = arguments.length; i < l; i += 1) {
+ var actual = this.args[i];
+ var expectation = arguments[i];
+ if (!sinon.match || !sinon.match(expectation).test(actual)) {
+ return false;
+ }
+ }
+ return true;
+ },
+
+ calledWithExactly: function calledWithExactly() {
+ return arguments.length == this.args.length &&
+ this.calledWith.apply(this, arguments);
+ },
+
+ notCalledWith: function notCalledWith() {
+ return !this.calledWith.apply(this, arguments);
+ },
+
+ notCalledWithMatch: function notCalledWithMatch() {
+ return !this.calledWithMatch.apply(this, arguments);
+ },
+
+ returned: function returned(value) {
+ return sinon.deepEqual(value, this.returnValue);
+ },
+
+ threw: function threw(error) {
+ if (typeof error === "undefined" || !this.exception) {
+ return !!this.exception;
+ }
+
+ return this.exception === error || this.exception.name === error;
+ },
+
+ calledWithNew: function calledWithNew(thisValue) {
+ return this.thisValue instanceof this.proxy;
+ },
+
+ calledBefore: function (other) {
+ return this.callId < other.callId;
+ },
+
+ calledAfter: function (other) {
+ return this.callId > other.callId;
+ },
+
+ callArg: function (pos) {
+ this.args[pos]();
+ },
+
+ callArgOn: function (pos, thisValue) {
+ this.args[pos].apply(thisValue);
+ },
+
+ callArgWith: function (pos) {
+ this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1)));
+ },
+
+ callArgOnWith: function (pos, thisValue) {
+ var args = slice.call(arguments, 2);
+ this.args[pos].apply(thisValue, args);
+ },
+
+ "yield": function () {
+ this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0)));
+ },
+
+ yieldOn: function (thisValue) {
+ var args = this.args;
+ for (var i = 0, l = args.length; i < l; ++i) {
+ if (typeof args[i] === "function") {
+ args[i].apply(thisValue, slice.call(arguments, 1));
+ return;
+ }
+ }
+ throwYieldError(this.proxy, " cannot yield since no callback was passed.", args);
+ },
+
+ yieldTo: function (prop) {
+ this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1)));
+ },
+
+ yieldToOn: function (prop, thisValue) {
+ var args = this.args;
+ for (var i = 0, l = args.length; i < l; ++i) {
+ if (args[i] && typeof args[i][prop] === "function") {
+ args[i][prop].apply(thisValue, slice.call(arguments, 2));
+ return;
+ }
+ }
+ throwYieldError(this.proxy, " cannot yield to '" + prop +
+ "' since no callback was passed.", args);
+ },
+
+ toString: function () {
+ var callStr = this.proxy.toString() + "(";
+ var args = [];
+
+ for (var i = 0, l = this.args.length; i < l; ++i) {
+ args.push(sinon.format(this.args[i]));
+ }
+
+ callStr = callStr + args.join(", ") + ")";
+
+ if (typeof this.returnValue != "undefined") {
+ callStr += " => " + sinon.format(this.returnValue);
+ }
+
+ if (this.exception) {
+ callStr += " !" + this.exception.name;
+
+ if (this.exception.message) {
+ callStr += "(" + this.exception.message + ")";
+ }
+ }
+
+ return callStr;
+ }
+ };
+
+ callProto.invokeCallback = callProto.yield;
+
+ function createSpyCall(spy, thisValue, args, returnValue, exception, id) {
+ if (typeof id !== "number") {
+ throw new TypeError("Call id is not a number");
+ }
+ var proxyCall = sinon.create(callProto);
+ proxyCall.proxy = spy;
+ proxyCall.thisValue = thisValue;
+ proxyCall.args = args;
+ proxyCall.returnValue = returnValue;
+ proxyCall.exception = exception;
+ proxyCall.callId = id;
+
+ return proxyCall;
+ };
+ createSpyCall.toString = callProto.toString; // used by mocks
+
+ sinon.spyCall = createSpyCall;
+}(typeof sinon == "object" && sinon || null));
+
+/**
+ * @depend ../sinon.js
+ */
+/*jslint eqeqeq: false, onevar: false, plusplus: false*/
+/*global module, require, sinon*/
+/**
+ * Spy functions
+ *
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @license BSD
+ *
+ * Copyright (c) 2010-2013 Christian Johansen
+ */
+
+(function (sinon) {
+ var commonJSModule = typeof module == "object" && typeof require == "function";
+ var push = Array.prototype.push;
+ var slice = Array.prototype.slice;
+ var callId = 0;
+
+ function spy(object, property) {
+ if (!property && typeof object == "function") {
+ return spy.create(object);
+ }
+
+ if (!object && !property) {
+ return spy.create(function () { });
+ }
+
+ var method = object[property];
+ return sinon.wrapMethod(object, property, spy.create(method));
+ }
+
+ function matchingFake(fakes, args, strict) {
+ if (!fakes) {
+ return;
+ }
+
+ var alen = args.length;
+
+ for (var i = 0, l = fakes.length; i < l; i++) {
+ if (fakes[i].matches(args, strict)) {
+ return fakes[i];
+ }
+ }
+ }
+
+ function incrementCallCount() {
+ this.called = true;
+ this.callCount += 1;
+ this.notCalled = false;
+ this.calledOnce = this.callCount == 1;
+ this.calledTwice = this.callCount == 2;
+ this.calledThrice = this.callCount == 3;
+ }
+
+ function createCallProperties() {
+ this.firstCall = this.getCall(0);
+ this.secondCall = this.getCall(1);
+ this.thirdCall = this.getCall(2);
+ this.lastCall = this.getCall(this.callCount - 1);
+ }
+
+ var vars = "a,b,c,d,e,f,g,h,i,j,k,l";
+ function createProxy(func) {
+ // Retain the function length:
+ var p;
+ if (func.length) {
+ eval("p = (function proxy(" + vars.substring(0, func.length * 2 - 1) +
+ ") { return p.invoke(func, this, slice.call(arguments)); });");
+ }
+ else {
+ p = function proxy() {
+ return p.invoke(func, this, slice.call(arguments));
+ };
+ }
+ return p;
+ }
+
+ var uuid = 0;
+
+ // Public API
+ var spyApi = {
+ reset: function () {
+ this.called = false;
+ this.notCalled = true;
+ this.calledOnce = false;
+ this.calledTwice = false;
+ this.calledThrice = false;
+ this.callCount = 0;
+ this.firstCall = null;
+ this.secondCall = null;
+ this.thirdCall = null;
+ this.lastCall = null;
+ this.args = [];
+ this.returnValues = [];
+ this.thisValues = [];
+ this.exceptions = [];
+ this.callIds = [];
+ if (this.fakes) {
+ for (var i = 0; i < this.fakes.length; i++) {
+ this.fakes[i].reset();
+ }
+ }
+ },
+
+ create: function create(func) {
+ var name;
+
+ if (typeof func != "function") {
+ func = function () { };
+ } else {
+ name = sinon.functionName(func);
+ }
+
+ var proxy = createProxy(func);
+
+ sinon.extend(proxy, spy);
+ delete proxy.create;
+ sinon.extend(proxy, func);
+
+ proxy.reset();
+ proxy.prototype = func.prototype;
+ proxy.displayName = name || "spy";
+ proxy.toString = sinon.functionToString;
+ proxy._create = sinon.spy.create;
+ proxy.id = "spy#" + uuid++;
+
+ return proxy;
+ },
+
+ invoke: function invoke(func, thisValue, args) {
+ var matching = matchingFake(this.fakes, args);
+ var exception, returnValue;
+
+ incrementCallCount.call(this);
+ push.call(this.thisValues, thisValue);
+ push.call(this.args, args);
+ push.call(this.callIds, callId++);
+
+ try {
+ if (matching) {
+ returnValue = matching.invoke(func, thisValue, args);
+ } else {
+ returnValue = (this.func || func).apply(thisValue, args);
+ }
+ } catch (e) {
+ push.call(this.returnValues, undefined);
+ exception = e;
+ throw e;
+ } finally {
+ push.call(this.exceptions, exception);
+ }
+
+ push.call(this.returnValues, returnValue);
+
+ createCallProperties.call(this);
+
+ return returnValue;
+ },
+
+ getCall: function getCall(i) {
+ if (i < 0 || i >= this.callCount) {
+ return null;
+ }
+
+ return sinon.spyCall(this, this.thisValues[i], this.args[i],
+ this.returnValues[i], this.exceptions[i],
+ this.callIds[i]);
+ },
+
+ calledBefore: function calledBefore(spyFn) {
+ if (!this.called) {
+ return false;
+ }
+
+ if (!spyFn.called) {
+ return true;
+ }
+
+ return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1];
+ },
+
+ calledAfter: function calledAfter(spyFn) {
+ if (!this.called || !spyFn.called) {
+ return false;
+ }
+
+ return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1];
+ },
+
+ withArgs: function () {
+ var args = slice.call(arguments);
+
+ if (this.fakes) {
+ var match = matchingFake(this.fakes, args, true);
+
+ if (match) {
+ return match;
+ }
+ } else {
+ this.fakes = [];
+ }
+
+ var original = this;
+ var fake = this._create();
+ fake.matchingAguments = args;
+ push.call(this.fakes, fake);
+
+ fake.withArgs = function () {
+ return original.withArgs.apply(original, arguments);
+ };
+
+ for (var i = 0; i < this.args.length; i++) {
+ if (fake.matches(this.args[i])) {
+ incrementCallCount.call(fake);
+ push.call(fake.thisValues, this.thisValues[i]);
+ push.call(fake.args, this.args[i]);
+ push.call(fake.returnValues, this.returnValues[i]);
+ push.call(fake.exceptions, this.exceptions[i]);
+ push.call(fake.callIds, this.callIds[i]);
+ }
+ }
+ createCallProperties.call(fake);
+
+ return fake;
+ },
+
+ matches: function (args, strict) {
+ var margs = this.matchingAguments;
+
+ if (margs.length <= args.length &&
+ sinon.deepEqual(margs, args.slice(0, margs.length))) {
+ return !strict || margs.length == args.length;
+ }
+ },
+
+ printf: function (format) {
+ var spy = this;
+ var args = slice.call(arguments, 1);
+ var formatter;
+
+ return (format || "").replace(/%(.)/g, function (match, specifyer) {
+ formatter = spyApi.formatters[specifyer];
+
+ if (typeof formatter == "function") {
+ return formatter.call(null, spy, args);
+ } else if (!isNaN(parseInt(specifyer), 10)) {
+ return sinon.format(args[specifyer - 1]);
+ }
+
+ return "%" + specifyer;
+ });
+ }
+ };
+
+ function delegateToCalls(method, matchAny, actual, notCalled) {
+ spyApi[method] = function () {
+ if (!this.called) {
+ if (notCalled) {
+ return notCalled.apply(this, arguments);
+ }
+ return false;
+ }
+
+ var currentCall;
+ var matches = 0;
+
+ for (var i = 0, l = this.callCount; i < l; i += 1) {
+ currentCall = this.getCall(i);
+
+ if (currentCall[actual || method].apply(currentCall, arguments)) {
+ matches += 1;
+
+ if (matchAny) {
+ return true;
+ }
+ }
+ }
+
+ return matches === this.callCount;
+ };
+ }
+
+ delegateToCalls("calledOn", true);
+ delegateToCalls("alwaysCalledOn", false, "calledOn");
+ delegateToCalls("calledWith", true);
+ delegateToCalls("calledWithMatch", true);
+ delegateToCalls("alwaysCalledWith", false, "calledWith");
+ delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch");
+ delegateToCalls("calledWithExactly", true);
+ delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly");
+ delegateToCalls("neverCalledWith", false, "notCalledWith",
+ function () { return true; });
+ delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch",
+ function () { return true; });
+ delegateToCalls("threw", true);
+ delegateToCalls("alwaysThrew", false, "threw");
+ delegateToCalls("returned", true);
+ delegateToCalls("alwaysReturned", false, "returned");
+ delegateToCalls("calledWithNew", true);
+ delegateToCalls("alwaysCalledWithNew", false, "calledWithNew");
+ delegateToCalls("callArg", false, "callArgWith", function () {
+ throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
+ });
+ spyApi.callArgWith = spyApi.callArg;
+ delegateToCalls("callArgOn", false, "callArgOnWith", function () {
+ throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
+ });
+ spyApi.callArgOnWith = spyApi.callArgOn;
+ delegateToCalls("yield", false, "yield", function () {
+ throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
+ });
+ // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode.
+ spyApi.invokeCallback = spyApi.yield;
+ delegateToCalls("yieldOn", false, "yieldOn", function () {
+ throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
+ });
+ delegateToCalls("yieldTo", false, "yieldTo", function (property) {
+ throw new Error(this.toString() + " cannot yield to '" + property +
+ "' since it was not yet invoked.");
+ });
+ delegateToCalls("yieldToOn", false, "yieldToOn", function (property) {
+ throw new Error(this.toString() + " cannot yield to '" + property +
+ "' since it was not yet invoked.");
+ });
+
+ spyApi.formatters = {
+ "c": function (spy) {
+ return sinon.timesInWords(spy.callCount);
+ },
+
+ "n": function (spy) {
+ return spy.toString();
+ },
+
+ "C": function (spy) {
+ var calls = [];
+
+ for (var i = 0, l = spy.callCount; i < l; ++i) {
+ var stringifiedCall = " " + spy.getCall(i).toString();
+ if (/\n/.test(calls[i - 1])) {
+ stringifiedCall = "\n" + stringifiedCall;
+ }
+ push.call(calls, stringifiedCall);
+ }
+
+ return calls.length > 0 ? "\n" + calls.join("\n") : "";
+ },
+
+ "t": function (spy) {
+ var objects = [];
+
+ for (var i = 0, l = spy.callCount; i < l; ++i) {
+ push.call(objects, sinon.format(spy.thisValues[i]));
+ }
+
+ return objects.join(", ");
+ },
+
+ "*": function (spy, args) {
+ var formatted = [];
+
+ for (var i = 0, l = args.length; i < l; ++i) {
+ push.call(formatted, sinon.format(args[i]));
+ }
+
+ return formatted.join(", ");
+ }
+ };
+
+ sinon.extend(spy, spyApi);
+
+ spy.spyCall = sinon.spyCall;
+
+ if (commonJSModule) {
+ module.exports = spy;
+ } else {
+ sinon.spy = spy;
+ }
+}(typeof sinon == "object" && sinon || null));
+
+/**
+ * @depend ../sinon.js
+ * @depend spy.js
+ */
+/*jslint eqeqeq: false, onevar: false*/
+/*global module, require, sinon*/
+/**
+ * Stub functions
+ *
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @license BSD
+ *
+ * Copyright (c) 2010-2013 Christian Johansen
+ */
+
+(function (sinon) {
+ var commonJSModule = typeof module == "object" && typeof require == "function";
+
+ if (!sinon && commonJSModule) {
+ sinon = require("../sinon");
+ }
+
+ if (!sinon) {
+ return;
+ }
+
+ function stub(object, property, func) {
+ if (!!func && typeof func != "function") {
+ throw new TypeError("Custom stub should be function");
+ }
+
+ var wrapper;
+
+ if (func) {
+ wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func;
+ } else {
+ wrapper = stub.create();
+ }
+
+ if (!object && !property) {
+ return sinon.stub.create();
+ }
+
+ if (!property && !!object && typeof object == "object") {
+ for (var prop in object) {
+ if (typeof object[prop] === "function") {
+ stub(object, prop);
+ }
+ }
+
+ return object;
+ }
+
+ return sinon.wrapMethod(object, property, wrapper);
+ }
+
+ function getChangingValue(stub, property) {
+ var index = stub.callCount - 1;
+ var values = stub[property];
+ var prop = index in values ? values[index] : values[values.length - 1];
+ stub[property + "Last"] = prop;
+
+ return prop;
+ }
+
+ function getCallback(stub, args) {
+ var callArgAt = getChangingValue(stub, "callArgAts");
+
+ if (callArgAt < 0) {
+ var callArgProp = getChangingValue(stub, "callArgProps");
+
+ for (var i = 0, l = args.length; i < l; ++i) {
+ if (!callArgProp && typeof args[i] == "function") {
+ return args[i];
+ }
+
+ if (callArgProp && args[i] &&
+ typeof args[i][callArgProp] == "function") {
+ return args[i][callArgProp];
+ }
+ }
+
+ return null;
+ }
+
+ return args[callArgAt];
+ }
+
+ var join = Array.prototype.join;
+
+ function getCallbackError(stub, func, args) {
+ if (stub.callArgAtsLast < 0) {
+ var msg;
+
+ if (stub.callArgPropsLast) {
+ msg = sinon.functionName(stub) +
+ " expected to yield to '" + stub.callArgPropsLast +
+ "', but no object with such a property was passed."
+ } else {
+ msg = sinon.functionName(stub) +
+ " expected to yield, but no callback was passed."
+ }
+
+ if (args.length > 0) {
+ msg += " Received [" + join.call(args, ", ") + "]";
+ }
+
+ return msg;
+ }
+
+ return "argument at index " + stub.callArgAtsLast + " is not a function: " + func;
+ }
+
+ var nextTick = (function () {
+ if (typeof process === "object" && typeof process.nextTick === "function") {
+ return process.nextTick;
+ } else if (typeof setImmediate === "function") {
+ return setImmediate;
+ } else {
+ return function (callback) {
+ setTimeout(callback, 0);
+ };
+ }
+ })();
+
+ function callCallback(stub, args) {
+ if (stub.callArgAts.length > 0) {
+ var func = getCallback(stub, args);
+
+ if (typeof func != "function") {
+ throw new TypeError(getCallbackError(stub, func, args));
+ }
+
+ var callbackArguments = getChangingValue(stub, "callbackArguments");
+ var callbackContext = getChangingValue(stub, "callbackContexts");
+
+ if (stub.callbackAsync) {
+ nextTick(function() {
+ func.apply(callbackContext, callbackArguments);
+ });
+ } else {
+ func.apply(callbackContext, callbackArguments);
+ }
+ }
+ }
+
+ var uuid = 0;
+
+ sinon.extend(stub, (function () {
+ var slice = Array.prototype.slice, proto;
+
+ function throwsException(error, message) {
+ if (typeof error == "string") {
+ this.exception = new Error(message || "");
+ this.exception.name = error;
+ } else if (!error) {
+ this.exception = new Error("Error");
+ } else {
+ this.exception = error;
+ }
+
+ return this;
+ }
+
+ proto = {
+ create: function create() {
+ var functionStub = function () {
+
+ callCallback(functionStub, arguments);
+
+ if (functionStub.exception) {
+ throw functionStub.exception;
+ } else if (typeof functionStub.returnArgAt == 'number') {
+ return arguments[functionStub.returnArgAt];
+ } else if (functionStub.returnThis) {
+ return this;
+ }
+ return functionStub.returnValue;
+ };
+
+ functionStub.id = "stub#" + uuid++;
+ var orig = functionStub;
+ functionStub = sinon.spy.create(functionStub);
+ functionStub.func = orig;
+
+ functionStub.callArgAts = [];
+ functionStub.callbackArguments = [];
+ functionStub.callbackContexts = [];
+ functionStub.callArgProps = [];
+
+ sinon.extend(functionStub, stub);
+ functionStub._create = sinon.stub.create;
+ functionStub.displayName = "stub";
+ functionStub.toString = sinon.functionToString;
+
+ return functionStub;
+ },
+
+ resetBehavior: function () {
+ var i;
+
+ this.callArgAts = [];
+ this.callbackArguments = [];
+ this.callbackContexts = [];
+ this.callArgProps = [];
+
+ delete this.returnValue;
+ delete this.returnArgAt;
+ this.returnThis = false;
+
+ if (this.fakes) {
+ for (i = 0; i < this.fakes.length; i++) {
+ this.fakes[i].resetBehavior();
+ }
+ }
+ },
+
+ returns: function returns(value) {
+ this.returnValue = value;
+
+ return this;
+ },
+
+ returnsArg: function returnsArg(pos) {
+ if (typeof pos != "number") {
+ throw new TypeError("argument index is not number");
+ }
+
+ this.returnArgAt = pos;
+
+ return this;
+ },
+
+ returnsThis: function returnsThis() {
+ this.returnThis = true;
+
+ return this;
+ },
+
+ "throws": throwsException,
+ throwsException: throwsException,
+
+ callsArg: function callsArg(pos) {
+ if (typeof pos != "number") {
+ throw new TypeError("argument index is not number");
+ }
+
+ this.callArgAts.push(pos);
+ this.callbackArguments.push([]);
+ this.callbackContexts.push(undefined);
+ this.callArgProps.push(undefined);
+
+ return this;
+ },
+
+ callsArgOn: function callsArgOn(pos, context) {
+ if (typeof pos != "number") {
+ throw new TypeError("argument index is not number");
+ }
+ if (typeof context != "object") {
+ throw new TypeError("argument context is not an object");
+ }
+
+ this.callArgAts.push(pos);
+ this.callbackArguments.push([]);
+ this.callbackContexts.push(context);
+ this.callArgProps.push(undefined);
+
+ return this;
+ },
+
+ callsArgWith: function callsArgWith(pos) {
+ if (typeof pos != "number") {
+ throw new TypeError("argument index is not number");
+ }
+
+ this.callArgAts.push(pos);
+ this.callbackArguments.push(slice.call(arguments, 1));
+ this.callbackContexts.push(undefined);
+ this.callArgProps.push(undefined);
+
+ return this;
+ },
+
+ callsArgOnWith: function callsArgWith(pos, context) {
+ if (typeof pos != "number") {
+ throw new TypeError("argument index is not number");
+ }
+ if (typeof context != "object") {
+ throw new TypeError("argument context is not an object");
+ }
+
+ this.callArgAts.push(pos);
+ this.callbackArguments.push(slice.call(arguments, 2));
+ this.callbackContexts.push(context);
+ this.callArgProps.push(undefined);
+
+ return this;
+ },
+
+ yields: function () {
+ this.callArgAts.push(-1);
+ this.callbackArguments.push(slice.call(arguments, 0));
+ this.callbackContexts.push(undefined);
+ this.callArgProps.push(undefined);
+
+ return this;
+ },
+
+ yieldsOn: function (context) {
+ if (typeof context != "object") {
+ throw new TypeError("argument context is not an object");
+ }
+
+ this.callArgAts.push(-1);
+ this.callbackArguments.push(slice.call(arguments, 1));
+ this.callbackContexts.push(context);
+ this.callArgProps.push(undefined);
+
+ return this;
+ },
+
+ yieldsTo: function (prop) {
+ this.callArgAts.push(-1);
+ this.callbackArguments.push(slice.call(arguments, 1));
+ this.callbackContexts.push(undefined);
+ this.callArgProps.push(prop);
+
+ return this;
+ },
+
+ yieldsToOn: function (prop, context) {
+ if (typeof context != "object") {
+ throw new TypeError("argument context is not an object");
+ }
+
+ this.callArgAts.push(-1);
+ this.callbackArguments.push(slice.call(arguments, 2));
+ this.callbackContexts.push(context);
+ this.callArgProps.push(prop);
+
+ return this;
+ }
+ };
+
+ // create asynchronous versions of callsArg* and yields* methods
+ for (var method in proto) {
+ // need to avoid creating anotherasync versions of the newly added async methods
+ if (proto.hasOwnProperty(method) &&
+ method.match(/^(callsArg|yields|thenYields$)/) &&
+ !method.match(/Async/)) {
+ proto[method + 'Async'] = (function (syncFnName) {
+ return function () {
+ this.callbackAsync = true;
+ return this[syncFnName].apply(this, arguments);
+ };
+ })(method);
+ }
+ }
+
+ return proto;
+
+ }()));
+
+ if (commonJSModule) {
+ module.exports = stub;
+ } else {
+ sinon.stub = stub;
+ }
+}(typeof sinon == "object" && sinon || null));
+
+/**
+ * @depend ../sinon.js
+ * @depend stub.js
+ */
+/*jslint eqeqeq: false, onevar: false, nomen: false*/
+/*global module, require, sinon*/
+/**
+ * Mock functions.
+ *
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @license BSD
+ *
+ * Copyright (c) 2010-2013 Christian Johansen
+ */
+
+(function (sinon) {
+ var commonJSModule = typeof module == "object" && typeof require == "function";
+ var push = [].push;
+
+ if (!sinon && commonJSModule) {
+ sinon = require("../sinon");
+ }
+
+ if (!sinon) {
+ return;
+ }
+
+ function mock(object) {
+ if (!object) {
+ return sinon.expectation.create("Anonymous mock");
+ }
+
+ return mock.create(object);
+ }
+
+ sinon.mock = mock;
+
+ sinon.extend(mock, (function () {
+ function each(collection, callback) {
+ if (!collection) {
+ return;
+ }
+
+ for (var i = 0, l = collection.length; i < l; i += 1) {
+ callback(collection[i]);
+ }
+ }
+
+ return {
+ create: function create(object) {
+ if (!object) {
+ throw new TypeError("object is null");
+ }
+
+ var mockObject = sinon.extend({}, mock);
+ mockObject.object = object;
+ delete mockObject.create;
+
+ return mockObject;
+ },
+
+ expects: function expects(method) {
+ if (!method) {
+ throw new TypeError("method is falsy");
+ }
+
+ if (!this.expectations) {
+ this.expectations = {};
+ this.proxies = [];
+ }
+
+ if (!this.expectations[method]) {
+ this.expectations[method] = [];
+ var mockObject = this;
+
+ sinon.wrapMethod(this.object, method, function () {
+ return mockObject.invokeMethod(method, this, arguments);
+ });
+
+ push.call(this.proxies, method);
+ }
+
+ var expectation = sinon.expectation.create(method);
+ push.call(this.expectations[method], expectation);
+
+ return expectation;
+ },
+
+ restore: function restore() {
+ var object = this.object;
+
+ each(this.proxies, function (proxy) {
+ if (typeof object[proxy].restore == "function") {
+ object[proxy].restore();
+ }
+ });
+ },
+
+ verify: function verify() {
+ var expectations = this.expectations || {};
+ var messages = [], met = [];
+
+ each(this.proxies, function (proxy) {
+ each(expectations[proxy], function (expectation) {
+ if (!expectation.met()) {
+ push.call(messages, expectation.toString());
+ } else {
+ push.call(met, expectation.toString());
+ }
+ });
+ });
+
+ this.restore();
+
+ if (messages.length > 0) {
+ sinon.expectation.fail(messages.concat(met).join("\n"));
+ } else {
+ sinon.expectation.pass(messages.concat(met).join("\n"));
+ }
+
+ return true;
+ },
+
+ invokeMethod: function invokeMethod(method, thisValue, args) {
+ var expectations = this.expectations && this.expectations[method];
+ var length = expectations && expectations.length || 0, i;
+
+ for (i = 0; i < length; i += 1) {
+ if (!expectations[i].met() &&
+ expectations[i].allowsCall(thisValue, args)) {
+ return expectations[i].apply(thisValue, args);
+ }
+ }
+
+ var messages = [], available, exhausted = 0;
+
+ for (i = 0; i < length; i += 1) {
+ if (expectations[i].allowsCall(thisValue, args)) {
+ available = available || expectations[i];
+ } else {
+ exhausted += 1;
+ }
+ push.call(messages, " " + expectations[i].toString());
+ }
+
+ if (exhausted === 0) {
+ return available.apply(thisValue, args);
+ }
+
+ messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({
+ proxy: method,
+ args: args
+ }));
+
+ sinon.expectation.fail(messages.join("\n"));
+ }
+ };
+ }()));
+
+ var times = sinon.timesInWords;
+
+ sinon.expectation = (function () {
+ var slice = Array.prototype.slice;
+ var _invoke = sinon.spy.invoke;
+
+ function callCountInWords(callCount) {
+ if (callCount == 0) {
+ return "never called";
+ } else {
+ return "called " + times(callCount);
+ }
+ }
+
+ function expectedCallCountInWords(expectation) {
+ var min = expectation.minCalls;
+ var max = expectation.maxCalls;
+
+ if (typeof min == "number" && typeof max == "number") {
+ var str = times(min);
+
+ if (min != max) {
+ str = "at least " + str + " and at most " + times(max);
+ }
+
+ return str;
+ }
+
+ if (typeof min == "number") {
+ return "at least " + times(min);
+ }
+
+ return "at most " + times(max);
+ }
+
+ function receivedMinCalls(expectation) {
+ var hasMinLimit = typeof expectation.minCalls == "number";
+ return !hasMinLimit || expectation.callCount >= expectation.minCalls;
+ }
+
+ function receivedMaxCalls(expectation) {
+ if (typeof expectation.maxCalls != "number") {
+ return false;
+ }
+
+ return expectation.callCount == expectation.maxCalls;
+ }
+
+ return {
+ minCalls: 1,
+ maxCalls: 1,
+
+ create: function create(methodName) {
+ var expectation = sinon.extend(sinon.stub.create(), sinon.expectation);
+ delete expectation.create;
+ expectation.method = methodName;
+
+ return expectation;
+ },
+
+ invoke: function invoke(func, thisValue, args) {
+ this.verifyCallAllowed(thisValue, args);
+
+ return _invoke.apply(this, arguments);
+ },
+
+ atLeast: function atLeast(num) {
+ if (typeof num != "number") {
+ throw new TypeError("'" + num + "' is not number");
+ }
+
+ if (!this.limitsSet) {
+ this.maxCalls = null;
+ this.limitsSet = true;
+ }
+
+ this.minCalls = num;
+
+ return this;
+ },
+
+ atMost: function atMost(num) {
+ if (typeof num != "number") {
+ throw new TypeError("'" + num + "' is not number");
+ }
+
+ if (!this.limitsSet) {
+ this.minCalls = null;
+ this.limitsSet = true;
+ }
+
+ this.maxCalls = num;
+
+ return this;
+ },
+
+ never: function never() {
+ return this.exactly(0);
+ },
+
+ once: function once() {
+ return this.exactly(1);
+ },
+
+ twice: function twice() {
+ return this.exactly(2);
+ },
+
+ thrice: function thrice() {
+ return this.exactly(3);
+ },
+
+ exactly: function exactly(num) {
+ if (typeof num != "number") {
+ throw new TypeError("'" + num + "' is not a number");
+ }
+
+ this.atLeast(num);
+ return this.atMost(num);
+ },
+
+ met: function met() {
+ return !this.failed && receivedMinCalls(this);
+ },
+
+ verifyCallAllowed: function verifyCallAllowed(thisValue, args) {
+ if (receivedMaxCalls(this)) {
+ this.failed = true;
+ sinon.expectation.fail(this.method + " already called " + times(this.maxCalls));
+ }
+
+ if ("expectedThis" in this && this.expectedThis !== thisValue) {
+ sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " +
+ this.expectedThis);
+ }
+
+ if (!("expectedArguments" in this)) {
+ return;
+ }
+
+ if (!args) {
+ sinon.expectation.fail(this.method + " received no arguments, expected " +
+ sinon.format(this.expectedArguments));
+ }
+
+ if (args.length < this.expectedArguments.length) {
+ sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) +
+ "), expected " + sinon.format(this.expectedArguments));
+ }
+
+ if (this.expectsExactArgCount &&
+ args.length != this.expectedArguments.length) {
+ sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) +
+ "), expected " + sinon.format(this.expectedArguments));
+ }
+
+ for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
+ if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
+ sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) +
+ ", expected " + sinon.format(this.expectedArguments));
+ }
+ }
+ },
+
+ allowsCall: function allowsCall(thisValue, args) {
+ if (this.met() && receivedMaxCalls(this)) {
+ return false;
+ }
+
+ if ("expectedThis" in this && this.expectedThis !== thisValue) {
+ return false;
+ }
+
+ if (!("expectedArguments" in this)) {
+ return true;
+ }
+
+ args = args || [];
+
+ if (args.length < this.expectedArguments.length) {
+ return false;
+ }
+
+ if (this.expectsExactArgCount &&
+ args.length != this.expectedArguments.length) {
+ return false;
+ }
+
+ for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
+ if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
+ return false;
+ }
+ }
+
+ return true;
+ },
+
+ withArgs: function withArgs() {
+ this.expectedArguments = slice.call(arguments);
+ return this;
+ },
+
+ withExactArgs: function withExactArgs() {
+ this.withArgs.apply(this, arguments);
+ this.expectsExactArgCount = true;
+ return this;
+ },
+
+ on: function on(thisValue) {
+ this.expectedThis = thisValue;
+ return this;
+ },
+
+ toString: function () {
+ var args = (this.expectedArguments || []).slice();
+
+ if (!this.expectsExactArgCount) {
+ push.call(args, "[...]");
+ }
+
+ var callStr = sinon.spyCall.toString.call({
+ proxy: this.method || "anonymous mock expectation",
+ args: args
+ });
+
+ var message = callStr.replace(", [...", "[, ...") + " " +
+ expectedCallCountInWords(this);
+
+ if (this.met()) {
+ return "Expectation met: " + message;
+ }
+
+ return "Expected " + message + " (" +
+ callCountInWords(this.callCount) + ")";
+ },
+
+ verify: function verify() {
+ if (!this.met()) {
+ sinon.expectation.fail(this.toString());
+ } else {
+ sinon.expectation.pass(this.toString());
+ }
+
+ return true;
+ },
+
+ pass: function(message) {
+ sinon.assert.pass(message);
+ },
+ fail: function (message) {
+ var exception = new Error(message);
+ exception.name = "ExpectationError";
+
+ throw exception;
+ }
+ };
+ }());
+
+ if (commonJSModule) {
+ module.exports = mock;
+ } else {
+ sinon.mock = mock;
+ }
+}(typeof sinon == "object" && sinon || null));
+
+/**
+ * @depend ../sinon.js
+ * @depend stub.js
+ * @depend mock.js
+ */
+/*jslint eqeqeq: false, onevar: false, forin: true*/
+/*global module, require, sinon*/
+/**
+ * Collections of stubs, spies and mocks.
+ *
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @license BSD
+ *
+ * Copyright (c) 2010-2013 Christian Johansen
+ */
+
+(function (sinon) {
+ var commonJSModule = typeof module == "object" && typeof require == "function";
+ var push = [].push;
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
+
+ if (!sinon && commonJSModule) {
+ sinon = require("../sinon");
+ }
+
+ if (!sinon) {
+ return;
+ }
+
+ function getFakes(fakeCollection) {
+ if (!fakeCollection.fakes) {
+ fakeCollection.fakes = [];
+ }
+
+ return fakeCollection.fakes;
+ }
+
+ function each(fakeCollection, method) {
+ var fakes = getFakes(fakeCollection);
+
+ for (var i = 0, l = fakes.length; i < l; i += 1) {
+ if (typeof fakes[i][method] == "function") {
+ fakes[i][method]();
+ }
+ }
+ }
+
+ function compact(fakeCollection) {
+ var fakes = getFakes(fakeCollection);
+ var i = 0;
+ while (i < fakes.length) {
+ fakes.splice(i, 1);
+ }
+ }
+
+ var collection = {
+ verify: function resolve() {
+ each(this, "verify");
+ },
+
+ restore: function restore() {
+ each(this, "restore");
+ compact(this);
+ },
+
+ verifyAndRestore: function verifyAndRestore() {
+ var exception;
+
+ try {
+ this.verify();
+ } catch (e) {
+ exception = e;
+ }
+
+ this.restore();
+
+ if (exception) {
+ throw exception;
+ }
+ },
+
+ add: function add(fake) {
+ push.call(getFakes(this), fake);
+ return fake;
+ },
+
+ spy: function spy() {
+ return this.add(sinon.spy.apply(sinon, arguments));
+ },
+
+ stub: function stub(object, property, value) {
+ if (property) {
+ var original = object[property];
+
+ if (typeof original != "function") {
+ if (!hasOwnProperty.call(object, property)) {
+ throw new TypeError("Cannot stub non-existent own property " + property);
+ }
+
+ object[property] = value;
+
+ return this.add({
+ restore: function () {
+ object[property] = original;
+ }
+ });
+ }
+ }
+ if (!property && !!object && typeof object == "object") {
+ var stubbedObj = sinon.stub.apply(sinon, arguments);
+
+ for (var prop in stubbedObj) {
+ if (typeof stubbedObj[prop] === "function") {
+ this.add(stubbedObj[prop]);
+ }
+ }
+
+ return stubbedObj;
+ }
+
+ return this.add(sinon.stub.apply(sinon, arguments));
+ },
+
+ mock: function mock() {
+ return this.add(sinon.mock.apply(sinon, arguments));
+ },
+
+ inject: function inject(obj) {
+ var col = this;
+
+ obj.spy = function () {
+ return col.spy.apply(col, arguments);
+ };
+
+ obj.stub = function () {
+ return col.stub.apply(col, arguments);
+ };
+
+ obj.mock = function () {
+ return col.mock.apply(col, arguments);
+ };
+
+ return obj;
+ }
+ };
+
+ if (commonJSModule) {
+ module.exports = collection;
+ } else {
+ sinon.collection = collection;
+ }
+}(typeof sinon == "object" && sinon || null));
+
+/*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/
+/*global module, require, window*/
+/**
+ * Fake timer API
+ * setTimeout
+ * setInterval
+ * clearTimeout
+ * clearInterval
+ * tick
+ * reset
+ * Date
+ *
+ * Inspired by jsUnitMockTimeOut from JsUnit
+ *
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @license BSD
+ *
+ * Copyright (c) 2010-2013 Christian Johansen
+ */
+
+if (typeof sinon == "undefined") {
+ var sinon = {};
+}
+
+(function (global) {
+ var id = 1;
+
+ function addTimer(args, recurring) {
+ if (args.length === 0) {
+ throw new Error("Function requires at least 1 parameter");
+ }
+
+ var toId = id++;
+ var delay = args[1] || 0;
+
+ if (!this.timeouts) {
+ this.timeouts = {};
+ }
+
+ this.timeouts[toId] = {
+ id: toId,
+ func: args[0],
+ callAt: this.now + delay,
+ invokeArgs: Array.prototype.slice.call(args, 2)
+ };
+
+ if (recurring === true) {
+ this.timeouts[toId].interval = delay;
+ }
+
+ return toId;
+ }
+
+ function parseTime(str) {
+ if (!str) {
+ return 0;
+ }
+
+ var strings = str.split(":");
+ var l = strings.length, i = l;
+ var ms = 0, parsed;
+
+ if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
+ throw new Error("tick only understands numbers and 'h:m:s'");
+ }
+
+ while (i--) {
+ parsed = parseInt(strings[i], 10);
+
+ if (parsed >= 60) {
+ throw new Error("Invalid time " + str);
+ }
+
+ ms += parsed * Math.pow(60, (l - i - 1));
+ }
+
+ return ms * 1000;
+ }
+
+ function createObject(object) {
+ var newObject;
+
+ if (Object.create) {
+ newObject = Object.create(object);
+ } else {
+ var F = function () {};
+ F.prototype = object;
+ newObject = new F();
+ }
+
+ newObject.Date.clock = newObject;
+ return newObject;
+ }
+
+ sinon.clock = {
+ now: 0,
+
+ create: function create(now) {
+ var clock = createObject(this);
+
+ if (typeof now == "number") {
+ clock.now = now;
+ }
+
+ if (!!now && typeof now == "object") {
+ throw new TypeError("now should be milliseconds since UNIX epoch");
+ }
+
+ return clock;
+ },
+
+ setTimeout: function setTimeout(callback, timeout) {
+ return addTimer.call(this, arguments, false);
+ },
+
+ clearTimeout: function clearTimeout(timerId) {
+ if (!this.timeouts) {
+ this.timeouts = [];
+ }
+
+ if (timerId in this.timeouts) {
+ delete this.timeouts[timerId];
+ }
+ },
+
+ setInterval: function setInterval(callback, timeout) {
+ return addTimer.call(this, arguments, true);
+ },
+
+ clearInterval: function clearInterval(timerId) {
+ this.clearTimeout(timerId);
+ },
+
+ tick: function tick(ms) {
+ ms = typeof ms == "number" ? ms : parseTime(ms);
+ var tickFrom = this.now, tickTo = this.now + ms, previous = this.now;
+ var timer = this.firstTimerInRange(tickFrom, tickTo);
+
+ var firstException;
+ while (timer && tickFrom <= tickTo) {
+ if (this.timeouts[timer.id]) {
+ tickFrom = this.now = timer.callAt;
+ try {
+ this.callTimer(timer);
+ } catch (e) {
+ firstException = firstException || e;
+ }
+ }
+
+ timer = this.firstTimerInRange(previous, tickTo);
+ previous = tickFrom;
+ }
+
+ this.now = tickTo;
+
+ if (firstException) {
+ throw firstException;
+ }
+
+ return this.now;
+ },
+
+ firstTimerInRange: function (from, to) {
+ var timer, smallest, originalTimer;
+
+ for (var id in this.timeouts) {
+ if (this.timeouts.hasOwnProperty(id)) {
+ if (this.timeouts[id].callAt < from || this.timeouts[id].callAt > to) {
+ continue;
+ }
+
+ if (!smallest || this.timeouts[id].callAt < smallest) {
+ originalTimer = this.timeouts[id];
+ smallest = this.timeouts[id].callAt;
+
+ timer = {
+ func: this.timeouts[id].func,
+ callAt: this.timeouts[id].callAt,
+ interval: this.timeouts[id].interval,
+ id: this.timeouts[id].id,
+ invokeArgs: this.timeouts[id].invokeArgs
+ };
+ }
+ }
+ }
+
+ return timer || null;
+ },
+
+ callTimer: function (timer) {
+ if (typeof timer.interval == "number") {
+ this.timeouts[timer.id].callAt += timer.interval;
+ } else {
+ delete this.timeouts[timer.id];
+ }
+
+ try {
+ if (typeof timer.func == "function") {
+ timer.func.apply(null, timer.invokeArgs);
+ } else {
+ eval(timer.func);
+ }
+ } catch (e) {
+ var exception = e;
+ }
+
+ if (!this.timeouts[timer.id]) {
+ if (exception) {
+ throw exception;
+ }
+ return;
+ }
+
+ if (exception) {
+ throw exception;
+ }
+ },
+
+ reset: function reset() {
+ this.timeouts = {};
+ },
+
+ Date: (function () {
+ var NativeDate = Date;
+
+ function ClockDate(year, month, date, hour, minute, second, ms) {
+ // Defensive and verbose to avoid potential harm in passing
+ // explicit undefined when user does not pass argument
+ switch (arguments.length) {
+ case 0:
+ return new NativeDate(ClockDate.clock.now);
+ case 1:
+ return new NativeDate(year);
+ case 2:
+ return new NativeDate(year, month);
+ case 3:
+ return new NativeDate(year, month, date);
+ case 4:
+ return new NativeDate(year, month, date, hour);
+ case 5:
+ return new NativeDate(year, month, date, hour, minute);
+ case 6:
+ return new NativeDate(year, month, date, hour, minute, second);
+ default:
+ return new NativeDate(year, month, date, hour, minute, second, ms);
+ }
+ }
+
+ return mirrorDateProperties(ClockDate, NativeDate);
+ }())
+ };
+
+ function mirrorDateProperties(target, source) {
+ if (source.now) {
+ target.now = function now() {
+ return target.clock.now;
+ };
+ } else {
+ delete target.now;
+ }
+
+ if (source.toSource) {
+ target.toSource = function toSource() {
+ return source.toSource();
+ };
+ } else {
+ delete target.toSource;
+ }
+
+ target.toString = function toString() {
+ return source.toString();
+ };
+
+ target.prototype = source.prototype;
+ target.parse = source.parse;
+ target.UTC = source.UTC;
+ target.prototype.toUTCString = source.prototype.toUTCString;
+ return target;
+ }
+
+ var methods = ["Date", "setTimeout", "setInterval",
+ "clearTimeout", "clearInterval"];
+
+ function restore() {
+ var method;
+
+ for (var i = 0, l = this.methods.length; i < l; i++) {
+ method = this.methods[i];
+ if (global[method].hadOwnProperty) {
+ global[method] = this["_" + method];
+ } else {
+ delete global[method];
+ }
+ }
+
+ // Prevent multiple executions which will completely remove these props
+ this.methods = [];
+ }
+
+ function stubGlobal(method, clock) {
+ clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(global, method);
+ clock["_" + method] = global[method];
+
+ if (method == "Date") {
+ var date = mirrorDateProperties(clock[method], global[method]);
+ global[method] = date;
+ } else {
+ global[method] = function () {
+ return clock[method].apply(clock, arguments);
+ };
+
+ for (var prop in clock[method]) {
+ if (clock[method].hasOwnProperty(prop)) {
+ global[method][prop] = clock[method][prop];
+ }
+ }
+ }
+
+ global[method].clock = clock;
+ }
+
+ sinon.useFakeTimers = function useFakeTimers(now) {
+ var clock = sinon.clock.create(now);
+ clock.restore = restore;
+ clock.methods = Array.prototype.slice.call(arguments,
+ typeof now == "number" ? 1 : 0);
+
+ if (clock.methods.length === 0) {
+ clock.methods = methods;
+ }
+
+ for (var i = 0, l = clock.methods.length; i < l; i++) {
+ stubGlobal(clock.methods[i], clock);
+ }
+
+ return clock;
+ };
+}(typeof global != "undefined" && typeof global !== "function" ? global : this));
+
+sinon.timers = {
+ setTimeout: setTimeout,
+ clearTimeout: clearTimeout,
+ setInterval: setInterval,
+ clearInterval: clearInterval,
+ Date: Date
+};
+
+if (typeof module == "object" && typeof require == "function") {
+ module.exports = sinon;
+}
+
+/*jslint eqeqeq: false, onevar: false*/
+/*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/
+/**
+ * Minimal Event interface implementation
+ *
+ * Original implementation by Sven Fuchs: https://gist.github.com/995028
+ * Modifications and tests by Christian Johansen.
+ *
+ * @author Sven Fuchs (svenfuchs@artweb-design.de)
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @license BSD
+ *
+ * Copyright (c) 2011 Sven Fuchs, Christian Johansen
+ */
+
+if (typeof sinon == "undefined") {
+ this.sinon = {};
+}
+
+(function () {
+ var push = [].push;
+
+ sinon.Event = function Event(type, bubbles, cancelable, target) {
+ this.initEvent(type, bubbles, cancelable, target);
+ };
+
+ sinon.Event.prototype = {
+ initEvent: function(type, bubbles, cancelable, target) {
+ this.type = type;
+ this.bubbles = bubbles;
+ this.cancelable = cancelable;
+ this.target = target;
+ },
+
+ stopPropagation: function () {},
+
+ preventDefault: function () {
+ this.defaultPrevented = true;
+ }
+ };
+
+ sinon.EventTarget = {
+ addEventListener: function addEventListener(event, listener, useCapture) {
+ this.eventListeners = this.eventListeners || {};
+ this.eventListeners[event] = this.eventListeners[event] || [];
+ push.call(this.eventListeners[event], listener);
+ },
+
+ removeEventListener: function removeEventListener(event, listener, useCapture) {
+ var listeners = this.eventListeners && this.eventListeners[event] || [];
+
+ for (var i = 0, l = listeners.length; i < l; ++i) {
+ if (listeners[i] == listener) {
+ return listeners.splice(i, 1);
+ }
+ }
+ },
+
+ dispatchEvent: function dispatchEvent(event) {
+ var type = event.type;
+ var listeners = this.eventListeners && this.eventListeners[type] || [];
+
+ for (var i = 0; i < listeners.length; i++) {
+ if (typeof listeners[i] == "function") {
+ listeners[i].call(this, event);
+ } else {
+ listeners[i].handleEvent(event);
+ }
+ }
+
+ return !!event.defaultPrevented;
+ }
+ };
+}());
+
+/**
+ * @depend ../../sinon.js
+ * @depend event.js
+ */
+/*jslint eqeqeq: false, onevar: false*/
+/*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/
+/**
+ * Fake XMLHttpRequest object
+ *
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @license BSD
+ *
+ * Copyright (c) 2010-2013 Christian Johansen
+ */
+
+if (typeof sinon == "undefined") {
+ this.sinon = {};
+}
+sinon.xhr = { XMLHttpRequest: this.XMLHttpRequest };
+
+// wrapper for global
+(function(global) {
+ var xhr = sinon.xhr;
+ xhr.GlobalXMLHttpRequest = global.XMLHttpRequest;
+ xhr.GlobalActiveXObject = global.ActiveXObject;
+ xhr.supportsActiveX = typeof xhr.GlobalActiveXObject != "undefined";
+ xhr.supportsXHR = typeof xhr.GlobalXMLHttpRequest != "undefined";
+ xhr.workingXHR = xhr.supportsXHR ? xhr.GlobalXMLHttpRequest : xhr.supportsActiveX
+ ? function() { return new xhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false;
+
+ /*jsl:ignore*/
+ var unsafeHeaders = {
+ "Accept-Charset": true,
+ "Accept-Encoding": true,
+ "Connection": true,
+ "Content-Length": true,
+ "Cookie": true,
+ "Cookie2": true,
+ "Content-Transfer-Encoding": true,
+ "Date": true,
+ "Expect": true,
+ "Host": true,
+ "Keep-Alive": true,
+ "Referer": true,
+ "TE": true,
+ "Trailer": true,
+ "Transfer-Encoding": true,
+ "Upgrade": true,
+ "User-Agent": true,
+ "Via": true
+ };
+ /*jsl:end*/
+
+ function FakeXMLHttpRequest() {
+ this.readyState = FakeXMLHttpRequest.UNSENT;
+ this.requestHeaders = {};
+ this.requestBody = null;
+ this.status = 0;
+ this.statusText = "";
+
+ var xhr = this;
+ var events = ["loadstart", "load", "abort", "loadend"];
+
+ function addEventListener(eventName) {
+ xhr.addEventListener(eventName, function (event) {
+ var listener = xhr["on" + eventName];
+
+ if (listener && typeof listener == "function") {
+ listener(event);
+ }
+ });
+ }
+
+ for (var i = events.length - 1; i >= 0; i--) {
+ addEventListener(events[i]);
+ }
+
+ if (typeof FakeXMLHttpRequest.onCreate == "function") {
+ FakeXMLHttpRequest.onCreate(this);
+ }
+ }
+
+ function verifyState(xhr) {
+ if (xhr.readyState !== FakeXMLHttpRequest.OPENED) {
+ throw new Error("INVALID_STATE_ERR");
+ }
+
+ if (xhr.sendFlag) {
+ throw new Error("INVALID_STATE_ERR");
+ }
+ }
+
+ // filtering to enable a white-list version of Sinon FakeXhr,
+ // where whitelisted requests are passed through to real XHR
+ function each(collection, callback) {
+ if (!collection) return;
+ for (var i = 0, l = collection.length; i < l; i += 1) {
+ callback(collection[i]);
+ }
+ }
+ function some(collection, callback) {
+ for (var index = 0; index < collection.length; index++) {
+ if(callback(collection[index]) === true) return true;
+ };
+ return false;
+ }
+ // largest arity in XHR is 5 - XHR#open
+ var apply = function(obj,method,args) {
+ switch(args.length) {
+ case 0: return obj[method]();
+ case 1: return obj[method](args[0]);
+ case 2: return obj[method](args[0],args[1]);
+ case 3: return obj[method](args[0],args[1],args[2]);
+ case 4: return obj[method](args[0],args[1],args[2],args[3]);
+ case 5: return obj[method](args[0],args[1],args[2],args[3],args[4]);
+ };
+ };
+
+ FakeXMLHttpRequest.filters = [];
+ FakeXMLHttpRequest.addFilter = function(fn) {
+ this.filters.push(fn)
+ };
+ var IE6Re = /MSIE 6/;
+ FakeXMLHttpRequest.defake = function(fakeXhr,xhrArgs) {
+ var xhr = new sinon.xhr.workingXHR();
+ each(["open","setRequestHeader","send","abort","getResponseHeader",
+ "getAllResponseHeaders","addEventListener","overrideMimeType","removeEventListener"],
+ function(method) {
+ fakeXhr[method] = function() {
+ return apply(xhr,method,arguments);
+ };
+ });
+
+ var copyAttrs = function(args) {
+ each(args, function(attr) {
+ try {
+ fakeXhr[attr] = xhr[attr]
+ } catch(e) {
+ if(!IE6Re.test(navigator.userAgent)) throw e;
+ }
+ });
+ };
+
+ var stateChange = function() {
+ fakeXhr.readyState = xhr.readyState;
+ if(xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) {
+ copyAttrs(["status","statusText"]);
+ }
+ if(xhr.readyState >= FakeXMLHttpRequest.LOADING) {
+ copyAttrs(["responseText"]);
+ }
+ if(xhr.readyState === FakeXMLHttpRequest.DONE) {
+ copyAttrs(["responseXML"]);
+ }
+ if(fakeXhr.onreadystatechange) fakeXhr.onreadystatechange.call(fakeXhr);
+ };
+ if(xhr.addEventListener) {
+ for(var event in fakeXhr.eventListeners) {
+ if(fakeXhr.eventListeners.hasOwnProperty(event)) {
+ each(fakeXhr.eventListeners[event],function(handler) {
+ xhr.addEventListener(event, handler);
+ });
+ }
+ }
+ xhr.addEventListener("readystatechange",stateChange);
+ } else {
+ xhr.onreadystatechange = stateChange;
+ }
+ apply(xhr,"open",xhrArgs);
+ };
+ FakeXMLHttpRequest.useFilters = false;
+
+ function verifyRequestSent(xhr) {
+ if (xhr.readyState == FakeXMLHttpRequest.DONE) {
+ throw new Error("Request done");
+ }
+ }
+
+ function verifyHeadersReceived(xhr) {
+ if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) {
+ throw new Error("No headers received");
+ }
+ }
+
+ function verifyResponseBodyType(body) {
+ if (typeof body != "string") {
+ var error = new Error("Attempted to respond to fake XMLHttpRequest with " +
+ body + ", which is not a string.");
+ error.name = "InvalidBodyException";
+ throw error;
+ }
+ }
+
+ sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, {
+ async: true,
+
+ open: function open(method, url, async, username, password) {
+ this.method = method;
+ this.url = url;
+ this.async = typeof async == "boolean" ? async : true;
+ this.username = username;
+ this.password = password;
+ this.responseText = null;
+ this.responseXML = null;
+ this.requestHeaders = {};
+ this.sendFlag = false;
+ if(sinon.FakeXMLHttpRequest.useFilters === true) {
+ var xhrArgs = arguments;
+ var defake = some(FakeXMLHttpRequest.filters,function(filter) {
+ return filter.apply(this,xhrArgs)
+ });
+ if (defake) {
+ return sinon.FakeXMLHttpRequest.defake(this,arguments);
+ }
+ }
+ this.readyStateChange(FakeXMLHttpRequest.OPENED);
+ },
+
+ readyStateChange: function readyStateChange(state) {
+ this.readyState = state;
+
+ if (typeof this.onreadystatechange == "function") {
+ try {
+ this.onreadystatechange();
+ } catch (e) {
+ sinon.logError("Fake XHR onreadystatechange handler", e);
+ }
+ }
+
+ this.dispatchEvent(new sinon.Event("readystatechange"));
+
+ switch (this.readyState) {
+ case FakeXMLHttpRequest.DONE:
+ this.dispatchEvent(new sinon.Event("load", false, false, this));
+ this.dispatchEvent(new sinon.Event("loadend", false, false, this));
+ break;
+ }
+ },
+
+ setRequestHeader: function setRequestHeader(header, value) {
+ verifyState(this);
+
+ if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) {
+ throw new Error("Refused to set unsafe header \"" + header + "\"");
+ }
+
+ if (this.requestHeaders[header]) {
+ this.requestHeaders[header] += "," + value;
+ } else {
+ this.requestHeaders[header] = value;
+ }
+ },
+
+ // Helps testing
+ setResponseHeaders: function setResponseHeaders(headers) {
+ this.responseHeaders = {};
+
+ for (var header in headers) {
+ if (headers.hasOwnProperty(header)) {
+ this.responseHeaders[header] = headers[header];
+ }
+ }
+
+ if (this.async) {
+ this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED);
+ } else {
+ this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED;
+ }
+ },
+
+ // Currently treats ALL data as a DOMString (i.e. no Document)
+ send: function send(data) {
+ verifyState(this);
+
+ if (!/^(get|head)$/i.test(this.method)) {
+ if (this.requestHeaders["Content-Type"]) {
+ var value = this.requestHeaders["Content-Type"].split(";");
+ this.requestHeaders["Content-Type"] = value[0] + ";charset=utf-8";
+ } else {
+ this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8";
+ }
+
+ this.requestBody = data;
+ }
+
+ this.errorFlag = false;
+ this.sendFlag = this.async;
+ this.readyStateChange(FakeXMLHttpRequest.OPENED);
+
+ if (typeof this.onSend == "function") {
+ this.onSend(this);
+ }
+
+ this.dispatchEvent(new sinon.Event("loadstart", false, false, this));
+ },
+
+ abort: function abort() {
+ this.aborted = true;
+ this.responseText = null;
+ this.errorFlag = true;
+ this.requestHeaders = {};
+
+ if (this.readyState > sinon.FakeXMLHttpRequest.UNSENT && this.sendFlag) {
+ this.readyStateChange(sinon.FakeXMLHttpRequest.DONE);
+ this.sendFlag = false;
+ }
+
+ this.readyState = sinon.FakeXMLHttpRequest.UNSENT;
+
+ this.dispatchEvent(new sinon.Event("abort", false, false, this));
+ if (typeof this.onerror === "function") {
+ this.onerror();
+ }
+ },
+
+ getResponseHeader: function getResponseHeader(header) {
+ if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
+ return null;
+ }
+
+ if (/^Set-Cookie2?$/i.test(header)) {
+ return null;
+ }
+
+ header = header.toLowerCase();
+
+ for (var h in this.responseHeaders) {
+ if (h.toLowerCase() == header) {
+ return this.responseHeaders[h];
+ }
+ }
+
+ return null;
+ },
+
+ getAllResponseHeaders: function getAllResponseHeaders() {
+ if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
+ return "";
+ }
+
+ var headers = "";
+
+ for (var header in this.responseHeaders) {
+ if (this.responseHeaders.hasOwnProperty(header) &&
+ !/^Set-Cookie2?$/i.test(header)) {
+ headers += header + ": " + this.responseHeaders[header] + "\r\n";
+ }
+ }
+
+ return headers;
+ },
+
+ setResponseBody: function setResponseBody(body) {
+ verifyRequestSent(this);
+ verifyHeadersReceived(this);
+ verifyResponseBodyType(body);
+
+ var chunkSize = this.chunkSize || 10;
+ var index = 0;
+ this.responseText = "";
+
+ do {
+ if (this.async) {
+ this.readyStateChange(FakeXMLHttpRequest.LOADING);
+ }
+
+ this.responseText += body.substring(index, index + chunkSize);
+ index += chunkSize;
+ } while (index < body.length);
+
+ var type = this.getResponseHeader("Content-Type");
+
+ if (this.responseText &&
+ (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) {
+ try {
+ this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText);
+ } catch (e) {
+ // Unable to parse XML - no biggie
+ }
+ }
+
+ if (this.async) {
+ this.readyStateChange(FakeXMLHttpRequest.DONE);
+ } else {
+ this.readyState = FakeXMLHttpRequest.DONE;
+ }
+ },
+
+ respond: function respond(status, headers, body) {
+ this.setResponseHeaders(headers || {});
+ this.status = typeof status == "number" ? status : 200;
+ this.statusText = FakeXMLHttpRequest.statusCodes[this.status];
+ this.setResponseBody(body || "");
+ if (typeof this.onload === "function"){
+ this.onload();
+ }
+
+ }
+ });
+
+ sinon.extend(FakeXMLHttpRequest, {
+ UNSENT: 0,
+ OPENED: 1,
+ HEADERS_RECEIVED: 2,
+ LOADING: 3,
+ DONE: 4
+ });
+
+ // Borrowed from JSpec
+ FakeXMLHttpRequest.parseXML = function parseXML(text) {
+ var xmlDoc;
+
+ if (typeof DOMParser != "undefined") {
+ var parser = new DOMParser();
+ xmlDoc = parser.parseFromString(text, "text/xml");
+ } else {
+ xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
+ xmlDoc.async = "false";
+ xmlDoc.loadXML(text);
+ }
+
+ return xmlDoc;
+ };
+
+ FakeXMLHttpRequest.statusCodes = {
+ 100: "Continue",
+ 101: "Switching Protocols",
+ 200: "OK",
+ 201: "Created",
+ 202: "Accepted",
+ 203: "Non-Authoritative Information",
+ 204: "No Content",
+ 205: "Reset Content",
+ 206: "Partial Content",
+ 300: "Multiple Choice",
+ 301: "Moved Permanently",
+ 302: "Found",
+ 303: "See Other",
+ 304: "Not Modified",
+ 305: "Use Proxy",
+ 307: "Temporary Redirect",
+ 400: "Bad Request",
+ 401: "Unauthorized",
+ 402: "Payment Required",
+ 403: "Forbidden",
+ 404: "Not Found",
+ 405: "Method Not Allowed",
+ 406: "Not Acceptable",
+ 407: "Proxy Authentication Required",
+ 408: "Request Timeout",
+ 409: "Conflict",
+ 410: "Gone",
+ 411: "Length Required",
+ 412: "Precondition Failed",
+ 413: "Request Entity Too Large",
+ 414: "Request-URI Too Long",
+ 415: "Unsupported Media Type",
+ 416: "Requested Range Not Satisfiable",
+ 417: "Expectation Failed",
+ 422: "Unprocessable Entity",
+ 500: "Internal Server Error",
+ 501: "Not Implemented",
+ 502: "Bad Gateway",
+ 503: "Service Unavailable",
+ 504: "Gateway Timeout",
+ 505: "HTTP Version Not Supported"
+ };
+
+ sinon.useFakeXMLHttpRequest = function () {
+ sinon.FakeXMLHttpRequest.restore = function restore(keepOnCreate) {
+ if (xhr.supportsXHR) {
+ global.XMLHttpRequest = xhr.GlobalXMLHttpRequest;
+ }
+
+ if (xhr.supportsActiveX) {
+ global.ActiveXObject = xhr.GlobalActiveXObject;
+ }
+
+ delete sinon.FakeXMLHttpRequest.restore;
+
+ if (keepOnCreate !== true) {
+ delete sinon.FakeXMLHttpRequest.onCreate;
+ }
+ };
+ if (xhr.supportsXHR) {
+ global.XMLHttpRequest = sinon.FakeXMLHttpRequest;
+ }
+
+ if (xhr.supportsActiveX) {
+ global.ActiveXObject = function ActiveXObject(objId) {
+ if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) {
+
+ return new sinon.FakeXMLHttpRequest();
+ }
+
+ return new xhr.GlobalActiveXObject(objId);
+ };
+ }
+
+ return sinon.FakeXMLHttpRequest;
+ };
+
+ sinon.FakeXMLHttpRequest = FakeXMLHttpRequest;
+})(this);
+
+if (typeof module == "object" && typeof require == "function") {
+ module.exports = sinon;
+}
+
+/**
+ * @depend fake_xml_http_request.js
+ */
+/*jslint eqeqeq: false, onevar: false, regexp: false, plusplus: false*/
+/*global module, require, window*/
+/**
+ * The Sinon "server" mimics a web server that receives requests from
+ * sinon.FakeXMLHttpRequest and provides an API to respond to those requests,
+ * both synchronously and asynchronously. To respond synchronuously, canned
+ * answers have to be provided upfront.
+ *
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @license BSD
+ *
+ * Copyright (c) 2010-2013 Christian Johansen
+ */
+
+if (typeof sinon == "undefined") {
+ var sinon = {};
+}
+
+sinon.fakeServer = (function () {
+ var push = [].push;
+ function F() {}
+
+ function create(proto) {
+ F.prototype = proto;
+ return new F();
+ }
+
+ function responseArray(handler) {
+ var response = handler;
+
+ if (Object.prototype.toString.call(handler) != "[object Array]") {
+ response = [200, {}, handler];
+ }
+
+ if (typeof response[2] != "string") {
+ throw new TypeError("Fake server response body should be string, but was " +
+ typeof response[2]);
+ }
+
+ return response;
+ }
+
+ var wloc = typeof window !== "undefined" ? window.location : {};
+ var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host);
+
+ function matchOne(response, reqMethod, reqUrl) {
+ var rmeth = response.method;
+ var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase();
+ var url = response.url;
+ var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl));
+
+ return matchMethod && matchUrl;
+ }
+
+ function match(response, request) {
+ var requestMethod = this.getHTTPMethod(request);
+ var requestUrl = request.url;
+
+ if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) {
+ requestUrl = requestUrl.replace(rCurrLoc, "");
+ }
+
+ if (matchOne(response, this.getHTTPMethod(request), requestUrl)) {
+ if (typeof response.response == "function") {
+ var ru = response.url;
+ var args = [request].concat(!ru ? [] : requestUrl.match(ru).slice(1));
+ return response.response.apply(response, args);
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ function log(response, request) {
+ var str;
+
+ str = "Request:\n" + sinon.format(request) + "\n\n";
+ str += "Response:\n" + sinon.format(response) + "\n\n";
+
+ sinon.log(str);
+ }
+
+ return {
+ create: function () {
+ var server = create(this);
+ this.xhr = sinon.useFakeXMLHttpRequest();
+ server.requests = [];
+
+ this.xhr.onCreate = function (xhrObj) {
+ server.addRequest(xhrObj);
+ };
+
+ return server;
+ },
+
+ addRequest: function addRequest(xhrObj) {
+ var server = this;
+ push.call(this.requests, xhrObj);
+
+ xhrObj.onSend = function () {
+ server.handleRequest(this);
+ };
+
+ if (this.autoRespond && !this.responding) {
+ setTimeout(function () {
+ server.responding = false;
+ server.respond();
+ }, this.autoRespondAfter || 10);
+
+ this.responding = true;
+ }
+ },
+
+ getHTTPMethod: function getHTTPMethod(request) {
+ if (this.fakeHTTPMethods && /post/i.test(request.method)) {
+ var matches = (request.requestBody || "").match(/_method=([^\b;]+)/);
+ return !!matches ? matches[1] : request.method;
+ }
+
+ return request.method;
+ },
+
+ handleRequest: function handleRequest(xhr) {
+ if (xhr.async) {
+ if (!this.queue) {
+ this.queue = [];
+ }
+
+ push.call(this.queue, xhr);
+ } else {
+ this.processRequest(xhr);
+ }
+ },
+
+ respondWith: function respondWith(method, url, body) {
+ if (arguments.length == 1 && typeof method != "function") {
+ this.response = responseArray(method);
+ return;
+ }
+
+ if (!this.responses) { this.responses = []; }
+
+ if (arguments.length == 1) {
+ body = method;
+ url = method = null;
+ }
+
+ if (arguments.length == 2) {
+ body = url;
+ url = method;
+ method = null;
+ }
+
+ push.call(this.responses, {
+ method: method,
+ url: url,
+ response: typeof body == "function" ? body : responseArray(body)
+ });
+ },
+
+ respond: function respond() {
+ if (arguments.length > 0) this.respondWith.apply(this, arguments);
+ var queue = this.queue || [];
+ var request;
+
+ while(request = queue.shift()) {
+ this.processRequest(request);
+ }
+ },
+
+ processRequest: function processRequest(request) {
+ try {
+ if (request.aborted) {
+ return;
+ }
+
+ var response = this.response || [404, {}, ""];
+
+ if (this.responses) {
+ for (var i = 0, l = this.responses.length; i < l; i++) {
+ if (match.call(this, this.responses[i], request)) {
+ response = this.responses[i].response;
+ break;
+ }
+ }
+ }
+
+ if (request.readyState != 4) {
+ log(response, request);
+
+ request.respond(response[0], response[1], response[2]);
+ }
+ } catch (e) {
+ sinon.logError("Fake server request processing", e);
+ }
+ },
+
+ restore: function restore() {
+ return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments);
+ }
+ };
+}());
+
+if (typeof module == "object" && typeof require == "function") {
+ module.exports = sinon;
+}
+
+/**
+ * @depend fake_server.js
+ * @depend fake_timers.js
+ */
+/*jslint browser: true, eqeqeq: false, onevar: false*/
+/*global sinon*/
+/**
+ * Add-on for sinon.fakeServer that automatically handles a fake timer along with
+ * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery
+ * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead,
+ * it polls the object for completion with setInterval. Dispite the direct
+ * motivation, there is nothing jQuery-specific in this file, so it can be used
+ * in any environment where the ajax implementation depends on setInterval or
+ * setTimeout.
+ *
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @license BSD
+ *
+ * Copyright (c) 2010-2013 Christian Johansen
+ */
+
+(function () {
+ function Server() {}
+ Server.prototype = sinon.fakeServer;
+
+ sinon.fakeServerWithClock = new Server();
+
+ sinon.fakeServerWithClock.addRequest = function addRequest(xhr) {
+ if (xhr.async) {
+ if (typeof setTimeout.clock == "object") {
+ this.clock = setTimeout.clock;
+ } else {
+ this.clock = sinon.useFakeTimers();
+ this.resetClock = true;
+ }
+
+ if (!this.longestTimeout) {
+ var clockSetTimeout = this.clock.setTimeout;
+ var clockSetInterval = this.clock.setInterval;
+ var server = this;
+
+ this.clock.setTimeout = function (fn, timeout) {
+ server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
+
+ return clockSetTimeout.apply(this, arguments);
+ };
+
+ this.clock.setInterval = function (fn, timeout) {
+ server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
+
+ return clockSetInterval.apply(this, arguments);
+ };
+ }
+ }
+
+ return sinon.fakeServer.addRequest.call(this, xhr);
+ };
+
+ sinon.fakeServerWithClock.respond = function respond() {
+ var returnVal = sinon.fakeServer.respond.apply(this, arguments);
+
+ if (this.clock) {
+ this.clock.tick(this.longestTimeout || 0);
+ this.longestTimeout = 0;
+
+ if (this.resetClock) {
+ this.clock.restore();
+ this.resetClock = false;
+ }
+ }
+
+ return returnVal;
+ };
+
+ sinon.fakeServerWithClock.restore = function restore() {
+ if (this.clock) {
+ this.clock.restore();
+ }
+
+ return sinon.fakeServer.restore.apply(this, arguments);
+ };
+}());
+
+/**
+ * @depend ../sinon.js
+ * @depend collection.js
+ * @depend util/fake_timers.js
+ * @depend util/fake_server_with_clock.js
+ */
+/*jslint eqeqeq: false, onevar: false, plusplus: false*/
+/*global require, module*/
+/**
+ * Manages fake collections as well as fake utilities such as Sinon's
+ * timers and fake XHR implementation in one convenient object.
+ *
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @license BSD
+ *
+ * Copyright (c) 2010-2013 Christian Johansen
+ */
+
+if (typeof module == "object" && typeof require == "function") {
+ var sinon = require("../sinon");
+ sinon.extend(sinon, require("./util/fake_timers"));
+}
+
+(function () {
+ var push = [].push;
+
+ function exposeValue(sandbox, config, key, value) {
+ if (!value) {
+ return;
+ }
+
+ if (config.injectInto) {
+ config.injectInto[key] = value;
+ } else {
+ push.call(sandbox.args, value);
+ }
+ }
+
+ function prepareSandboxFromConfig(config) {
+ var sandbox = sinon.create(sinon.sandbox);
+
+ if (config.useFakeServer) {
+ if (typeof config.useFakeServer == "object") {
+ sandbox.serverPrototype = config.useFakeServer;
+ }
+
+ sandbox.useFakeServer();
+ }
+
+ if (config.useFakeTimers) {
+ if (typeof config.useFakeTimers == "object") {
+ sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers);
+ } else {
+ sandbox.useFakeTimers();
+ }
+ }
+
+ return sandbox;
+ }
+
+ sinon.sandbox = sinon.extend(sinon.create(sinon.collection), {
+ useFakeTimers: function useFakeTimers() {
+ this.clock = sinon.useFakeTimers.apply(sinon, arguments);
+
+ return this.add(this.clock);
+ },
+
+ serverPrototype: sinon.fakeServer,
+
+ useFakeServer: function useFakeServer() {
+ var proto = this.serverPrototype || sinon.fakeServer;
+
+ if (!proto || !proto.create) {
+ return null;
+ }
+
+ this.server = proto.create();
+ return this.add(this.server);
+ },
+
+ inject: function (obj) {
+ sinon.collection.inject.call(this, obj);
+
+ if (this.clock) {
+ obj.clock = this.clock;
+ }
+
+ if (this.server) {
+ obj.server = this.server;
+ obj.requests = this.server.requests;
+ }
+
+ return obj;
+ },
+
+ create: function (config) {
+ if (!config) {
+ return sinon.create(sinon.sandbox);
+ }
+
+ var sandbox = prepareSandboxFromConfig(config);
+ sandbox.args = sandbox.args || [];
+ var prop, value, exposed = sandbox.inject({});
+
+ if (config.properties) {
+ for (var i = 0, l = config.properties.length; i < l; i++) {
+ prop = config.properties[i];
+ value = exposed[prop] || prop == "sandbox" && sandbox;
+ exposeValue(sandbox, config, prop, value);
+ }
+ } else {
+ exposeValue(sandbox, config, "sandbox", value);
+ }
+
+ return sandbox;
+ }
+ });
+
+ sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer;
+
+ if (typeof module == "object" && typeof require == "function") {
+ module.exports = sinon.sandbox;
+ }
+}());
+
+/**
+ * @depend ../sinon.js
+ * @depend stub.js
+ * @depend mock.js
+ * @depend sandbox.js
+ */
+/*jslint eqeqeq: false, onevar: false, forin: true, plusplus: false*/
+/*global module, require, sinon*/
+/**
+ * Test function, sandboxes fakes
+ *
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @license BSD
+ *
+ * Copyright (c) 2010-2013 Christian Johansen
+ */
+
+(function (sinon) {
+ var commonJSModule = typeof module == "object" && typeof require == "function";
+
+ if (!sinon && commonJSModule) {
+ sinon = require("../sinon");
+ }
+
+ if (!sinon) {
+ return;
+ }
+
+ function test(callback) {
+ var type = typeof callback;
+
+ if (type != "function") {
+ throw new TypeError("sinon.test needs to wrap a test function, got " + type);
+ }
+
+ return function () {
+ var config = sinon.getConfig(sinon.config);
+ config.injectInto = config.injectIntoThis && this || config.injectInto;
+ var sandbox = sinon.sandbox.create(config);
+ var exception, result;
+ var args = Array.prototype.slice.call(arguments).concat(sandbox.args);
+
+ try {
+ result = callback.apply(this, args);
+ } catch (e) {
+ exception = e;
+ }
+
+ if (typeof exception !== "undefined") {
+ sandbox.restore();
+ throw exception;
+ }
+ else {
+ sandbox.verifyAndRestore();
+ }
+
+ return result;
+ };
+ }
+
+ test.config = {
+ injectIntoThis: true,
+ injectInto: null,
+ properties: ["spy", "stub", "mock", "clock", "server", "requests"],
+ useFakeTimers: true,
+ useFakeServer: true
+ };
+
+ if (commonJSModule) {
+ module.exports = test;
+ } else {
+ sinon.test = test;
+ }
+}(typeof sinon == "object" && sinon || null));
+
+/**
+ * @depend ../sinon.js
+ * @depend test.js
+ */
+/*jslint eqeqeq: false, onevar: false, eqeqeq: false*/
+/*global module, require, sinon*/
+/**
+ * Test case, sandboxes all test functions
+ *
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @license BSD
+ *
+ * Copyright (c) 2010-2013 Christian Johansen
+ */
+
+(function (sinon) {
+ var commonJSModule = typeof module == "object" && typeof require == "function";
+
+ if (!sinon && commonJSModule) {
+ sinon = require("../sinon");
+ }
+
+ if (!sinon || !Object.prototype.hasOwnProperty) {
+ return;
+ }
+
+ function createTest(property, setUp, tearDown) {
+ return function () {
+ if (setUp) {
+ setUp.apply(this, arguments);
+ }
+
+ var exception, result;
+
+ try {
+ result = property.apply(this, arguments);
+ } catch (e) {
+ exception = e;
+ }
+
+ if (tearDown) {
+ tearDown.apply(this, arguments);
+ }
+
+ if (exception) {
+ throw exception;
+ }
+
+ return result;
+ };
+ }
+
+ function testCase(tests, prefix) {
+ /*jsl:ignore*/
+ if (!tests || typeof tests != "object") {
+ throw new TypeError("sinon.testCase needs an object with test functions");
+ }
+ /*jsl:end*/
+
+ prefix = prefix || "test";
+ var rPrefix = new RegExp("^" + prefix);
+ var methods = {}, testName, property, method;
+ var setUp = tests.setUp;
+ var tearDown = tests.tearDown;
+
+ for (testName in tests) {
+ if (tests.hasOwnProperty(testName)) {
+ property = tests[testName];
+
+ if (/^(setUp|tearDown)$/.test(testName)) {
+ continue;
+ }
+
+ if (typeof property == "function" && rPrefix.test(testName)) {
+ method = property;
+
+ if (setUp || tearDown) {
+ method = createTest(property, setUp, tearDown);
+ }
+
+ methods[testName] = sinon.test(method);
+ } else {
+ methods[testName] = tests[testName];
+ }
+ }
+ }
+
+ return methods;
+ }
+
+ if (commonJSModule) {
+ module.exports = testCase;
+ } else {
+ sinon.testCase = testCase;
+ }
+}(typeof sinon == "object" && sinon || null));
+
+/**
+ * @depend ../sinon.js
+ * @depend stub.js
+ */
+/*jslint eqeqeq: false, onevar: false, nomen: false, plusplus: false*/
+/*global module, require, sinon*/
+/**
+ * Assertions matching the test spy retrieval interface.
+ *
+ * @author Christian Johansen (christian@cjohansen.no)
+ * @license BSD
+ *
+ * Copyright (c) 2010-2013 Christian Johansen
+ */
+
+(function (sinon, global) {
+ var commonJSModule = typeof module == "object" && typeof require == "function";
+ var slice = Array.prototype.slice;
+ var assert;
+
+ if (!sinon && commonJSModule) {
+ sinon = require("../sinon");
+ }
+
+ if (!sinon) {
+ return;
+ }
+
+ function verifyIsStub() {
+ var method;
+
+ for (var i = 0, l = arguments.length; i < l; ++i) {
+ method = arguments[i];
+
+ if (!method) {
+ assert.fail("fake is not a spy");
+ }
+
+ if (typeof method != "function") {
+ assert.fail(method + " is not a function");
+ }
+
+ if (typeof method.getCall != "function") {
+ assert.fail(method + " is not stubbed");
+ }
+ }
+ }
+
+ function failAssertion(object, msg) {
+ object = object || global;
+ var failMethod = object.fail || assert.fail;
+ failMethod.call(object, msg);
+ }
+
+ function mirrorPropAsAssertion(name, method, message) {
+ if (arguments.length == 2) {
+ message = method;
+ method = name;
+ }
+
+ assert[name] = function (fake) {
+ verifyIsStub(fake);
+
+ var args = slice.call(arguments, 1);
+ var failed = false;
+
+ if (typeof method == "function") {
+ failed = !method(fake);
+ } else {
+ failed = typeof fake[method] == "function" ?
+ !fake[method].apply(fake, args) : !fake[method];
+ }
+
+ if (failed) {
+ failAssertion(this, fake.printf.apply(fake, [message].concat(args)));
+ } else {
+ assert.pass(name);
+ }
+ };
+ }
+
+ function exposedName(prefix, prop) {
+ return !prefix || /^fail/.test(prop) ? prop :
+ prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1);
+ };
+
+ assert = {
+ failException: "AssertError",
+
+ fail: function fail(message) {
+ var error = new Error(message);
+ error.name = this.failException || assert.failException;
+
+ throw error;
+ },
+
+ pass: function pass(assertion) {},
+
+ callOrder: function assertCallOrder() {
+ verifyIsStub.apply(null, arguments);
+ var expected = "", actual = "";
+
+ if (!sinon.calledInOrder(arguments)) {
+ try {
+ expected = [].join.call(arguments, ", ");
+ var calls = slice.call(arguments);
+ var i = calls.length;
+ while (i) {
+ if (!calls[--i].called) {
+ calls.splice(i, 1);
+ }
+ }
+ actual = sinon.orderByFirstCall(calls).join(", ");
+ } catch (e) {
+ // If this fails, we'll just fall back to the blank string
+ }
+
+ failAssertion(this, "expected " + expected + " to be " +
+ "called in order but were called as " + actual);
+ } else {
+ assert.pass("callOrder");
+ }
+ },
+
+ callCount: function assertCallCount(method, count) {
+ verifyIsStub(method);
+
+ if (method.callCount != count) {
+ var msg = "expected %n to be called " + sinon.timesInWords(count) +
+ " but was called %c%C";
+ failAssertion(this, method.printf(msg));
+ } else {
+ assert.pass("callCount");
+ }
+ },
+
+ expose: function expose(target, options) {
+ if (!target) {
+ throw new TypeError("target is null or undefined");
+ }
+
+ var o = options || {};
+ var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix;
+ var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail;
+
+ for (var method in this) {
+ if (method != "export" && (includeFail || !/^(fail)/.test(method))) {
+ target[exposedName(prefix, method)] = this[method];
+ }
+ }
+
+ return target;
+ }
+ };
+
+ mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called");
+ mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; },
+ "expected %n to not have been called but was called %c%C");
+ mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C");
+ mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C");
+ mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C");
+ mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t");
+ mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t");
+ mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new");
+ mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new");
+ mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C");
+ mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C");
+ mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C");
+ mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C");
+ mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C");
+ mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C");
+ mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C");
+ mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C");
+ mirrorPropAsAssertion("threw", "%n did not throw exception%C");
+ mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C");
+
+ if (commonJSModule) {
+ module.exports = assert;
+ } else {
+ sinon.assert = assert;
+ }
+}(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : (typeof self != "undefined") ? self : global));
+
+return sinon;}.call(typeof window != 'undefined' && window || {}));
diff --git a/java/jenkins_plugins/build_monitor/src/test/resources/vendor/yahoo-2.9.0.min.js b/java/jenkins_plugins/build_monitor/src/test/resources/vendor/yahoo-2.9.0.min.js
new file mode 100644
index 0000000..4f18140
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/resources/vendor/yahoo-2.9.0.min.js
@@ -0,0 +1,8 @@
+/*
+Copyright (c) 2011, Yahoo! Inc. All rights reserved.
+Code licensed under the BSD License:
+http://developer.yahoo.com/yui/license.html
+version: 2.9.0
+*/
+if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={};}YAHOO.namespace=function(){var b=arguments,g=null,e,c,f;for(e=0;e<b.length;e=e+1){f=(""+b[e]).split(".");g=YAHOO;for(c=(f[0]=="YAHOO")?1:0;c<f.length;c=c+1){g[f[c]]=g[f[c]]||{};g=g[f[c]];}}return g;};YAHOO.log=function(d,a,c){var b=YAHOO.widget.Logger;if(b&&b.log){return b.log(d,a,c);}else{return false;}};YAHOO.register=function(a,f,e){var k=YAHOO.env.modules,c,j,h,g,d;if(!k[a]){k[a]={versions:[],builds:[]};}c=k[a];j=e.version;h=e.build;g=YAHOO.env.listeners;c.name=a;c.version=j;c.build=h;c.versions.push(j);c.builds.push(h);c.mainClass=f;for(d=0;d<g.length;d=d+1){g[d](c);}if(f){f.VERSION=j;f.BUILD=h;}else{YAHOO.log("mainClass is undefined for module "+a,"warn");}};YAHOO.env=YAHOO.env||{modules:[],listeners:[]};YAHOO.env.getVersion=function(a){return YAHOO.env.modules[a]||null;};YAHOO.env.parseUA=function(d){var e=function(i){var j=0;return parseFloat(i.replace(/\./g,function(){return(j++==1)?"":".";}));},h=navigator,g={ie:0,opera:0,gecko:0,webkit:0,chrome:0,mobile:null,air:0,ipad:0,iphone:0,ipod:0,ios:null,android:0,webos:0,caja:h&&h.cajaVersion,secure:false,os:null},c=d||(navigator&&navigator.userAgent),f=window&&window.location,b=f&&f.href,a;g.secure=b&&(b.toLowerCase().indexOf("https")===0);if(c){if((/windows|win32/i).test(c)){g.os="windows";}else{if((/macintosh/i).test(c)){g.os="macintosh";}else{if((/rhino/i).test(c)){g.os="rhino";}}}if((/KHTML/).test(c)){g.webkit=1;}a=c.match(/AppleWebKit\/([^\s]*)/);if(a&&a[1]){g.webkit=e(a[1]);if(/ Mobile\//.test(c)){g.mobile="Apple";a=c.match(/OS ([^\s]*)/);if(a&&a[1]){a=e(a[1].replace("_","."));}g.ios=a;g.ipad=g.ipod=g.iphone=0;a=c.match(/iPad|iPod|iPhone/);if(a&&a[0]){g[a[0].toLowerCase()]=g.ios;}}else{a=c.match(/NokiaN[^\/]*|Android \d\.\d|webOS\/\d\.\d/);if(a){g.mobile=a[0];}if(/webOS/.test(c)){g.mobile="WebOS";a=c.match(/webOS\/([^\s]*);/);if(a&&a[1]){g.webos=e(a[1]);}}if(/ Android/.test(c)){g.mobile="Android";a=c.match(/Android ([^\s]*);/);if(a&&a[1]){g.android=e(a[1]);}}}a=c.match(/Chrome\/([^\s]*)/);if(a&&a[1]){g.chrome=e(a[1]);}else{a=c.match(/AdobeAIR\/([^\s]*)/);if(a){g.air=a[0];}}}if(!g.webkit){a=c.match(/Opera[\s\/]([^\s]*)/);if(a&&a[1]){g.opera=e(a[1]);a=c.match(/Version\/([^\s]*)/);if(a&&a[1]){g.opera=e(a[1]);}a=c.match(/Opera Mini[^;]*/);if(a){g.mobile=a[0];}}else{a=c.match(/MSIE\s([^;]*)/);if(a&&a[1]){g.ie=e(a[1]);}else{a=c.match(/Gecko\/([^\s]*)/);if(a){g.gecko=1;a=c.match(/rv:([^\s\)]*)/);if(a&&a[1]){g.gecko=e(a[1]);}}}}}}return g;};YAHOO.env.ua=YAHOO.env.parseUA();(function(){YAHOO.namespace("util","widget","example");if("undefined"!==typeof YAHOO_config){var b=YAHOO_config.listener,a=YAHOO.env.listeners,d=true,c;if(b){for(c=0;c<a.length;c++){if(a[c]==b){d=false;break;}}if(d){a.push(b);}}}})();YAHOO.lang=YAHOO.lang||{};(function(){var f=YAHOO.lang,a=Object.prototype,c="[object Array]",h="[object Function]",i="[object Object]",b=[],g={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`"},d=["toString","valueOf"],e={isArray:function(j){return a.toString.apply(j)===c;},isBoolean:function(j){return typeof j==="boolean";},isFunction:function(j){return(typeof j==="function")||a.toString.apply(j)===h;},isNull:function(j){return j===null;},isNumber:function(j){return typeof j==="number"&&isFinite(j);},isObject:function(j){return(j&&(typeof j==="object"||f.isFunction(j)))||false;},isString:function(j){return typeof j==="string";},isUndefined:function(j){return typeof j==="undefined";},_IEEnumFix:(YAHOO.env.ua.ie)?function(l,k){var j,n,m;for(j=0;j<d.length;j=j+1){n=d[j];m=k[n];if(f.isFunction(m)&&m!=a[n]){l[n]=m;}}}:function(){},escapeHTML:function(j){return j.replace(/[&<>"'\/`]/g,function(k){return g[k];});},extend:function(m,n,l){if(!n||!m){throw new Error("extend failed, please check that "+"all dependencies are included.");}var k=function(){},j;k.prototype=n.prototype;m.prototype=new k();m.prototype.constructor=m;m.superclass=n.prototype;if(n.prototype.constructor==a.constructor){n.prototype.constructor=n;}if(l){for(j in l){if(f.hasOwnProperty(l,j)){m.prototype[j]=l[j];}}f._IEEnumFix(m.prototype,l);}},augmentObject:function(n,m){if(!m||!n){throw new Error("Absorb failed, verify dependencies.");}var j=arguments,l,o,k=j[2];if(k&&k!==true){for(l=2;l<j.length;l=l+1){n[j[l]]=m[j[l]];}}else{for(o in m){if(k||!(o in n)){n[o]=m[o];}}f._IEEnumFix(n,m);}return n;},augmentProto:function(m,l){if(!l||!m){throw new Error("Augment failed, verify dependencies.");}var j=[m.prototype,l.prototype],k;for(k=2;k<arguments.length;k=k+1){j.push(arguments[k]);}f.augmentObject.apply(this,j);return m;},dump:function(j,p){var l,n,r=[],t="{...}",k="f(){...}",q=", ",m=" => ";if(!f.isObject(j)){return j+"";}else{if(j instanceof Date||("nodeType" in j&&"tagName" in j)){return j;}else{if(f.isFunction(j)){return k;}}}p=(f.isNumber(p))?p:3;if(f.isArray(j)){r.push("[");for(l=0,n=j.length;l<n;l=l+1){if(f.isObject(j[l])){r.push((p>0)?f.dump(j[l],p-1):t);}else{r.push(j[l]);}r.push(q);}if(r.length>1){r.pop();}r.push("]");}else{r.push("{");for(l in j){if(f.hasOwnProperty(j,l)){r.push(l+m);if(f.isObject(j[l])){r.push((p>0)?f.dump(j[l],p-1):t);}else{r.push(j[l]);}r.push(q);}}if(r.length>1){r.pop();}r.push("}");}return r.join("");},substitute:function(x,y,E,l){var D,C,B,G,t,u,F=[],p,z=x.length,A="dump",r=" ",q="{",m="}",n,w;for(;;){D=x.lastIndexOf(q,z);if(D<0){break;}C=x.indexOf(m,D);if(D+1>C){break;}p=x.substring(D+1,C);G=p;u=null;B=G.indexOf(r);if(B>-1){u=G.substring(B+1);G=G.substring(0,B);}t=y[G];if(E){t=E(G,t,u);}if(f.isObject(t)){if(f.isArray(t)){t=f.dump(t,parseInt(u,10));}else{u=u||"";n=u.indexOf(A);if(n>-1){u=u.substring(4);}w=t.toString();if(w===i||n>-1){t=f.dump(t,parseInt(u,10));}else{t=w;}}}else{if(!f.isString(t)&&!f.isNumber(t)){t="~-"+F.length+"-~";F[F.length]=p;}}x=x.substring(0,D)+t+x.substring(C+1);if(l===false){z=D-1;}}for(D=F.length-1;D>=0;D=D-1){x=x.replace(new RegExp("~-"+D+"-~"),"{"+F[D]+"}","g");}return x;},trim:function(j){try{return j.replace(/^\s+|\s+$/g,"");}catch(k){return j;
+}},merge:function(){var n={},k=arguments,j=k.length,m;for(m=0;m<j;m=m+1){f.augmentObject(n,k[m],true);}return n;},later:function(t,k,u,n,p){t=t||0;k=k||{};var l=u,s=n,q,j;if(f.isString(u)){l=k[u];}if(!l){throw new TypeError("method undefined");}if(!f.isUndefined(n)&&!f.isArray(s)){s=[n];}q=function(){l.apply(k,s||b);};j=(p)?setInterval(q,t):setTimeout(q,t);return{interval:p,cancel:function(){if(this.interval){clearInterval(j);}else{clearTimeout(j);}}};},isValue:function(j){return(f.isObject(j)||f.isString(j)||f.isNumber(j)||f.isBoolean(j));}};f.hasOwnProperty=(a.hasOwnProperty)?function(j,k){return j&&j.hasOwnProperty&&j.hasOwnProperty(k);}:function(j,k){return !f.isUndefined(j[k])&&j.constructor.prototype[k]!==j[k];};e.augmentObject(f,e,true);YAHOO.util.Lang=f;f.augment=f.augmentProto;YAHOO.augment=f.augmentProto;YAHOO.extend=f.extend;})();YAHOO.register("yahoo",YAHOO,{version:"2.9.0",build:"2800"});
\ No newline at end of file
diff --git a/java/jenkins_plugins/build_monitor/src/test/resources/vendor/yahoo-cookie-2.9.0.min.js b/java/jenkins_plugins/build_monitor/src/test/resources/vendor/yahoo-cookie-2.9.0.min.js
new file mode 100644
index 0000000..290c424
--- /dev/null
+++ b/java/jenkins_plugins/build_monitor/src/test/resources/vendor/yahoo-cookie-2.9.0.min.js
@@ -0,0 +1,7 @@
+/*
+Copyright (c) 2011, Yahoo! Inc. All rights reserved.
+Code licensed under the BSD License:
+http://developer.yahoo.com/yui/license.html
+version: 2.9.0
+*/
+YAHOO.namespace("util");YAHOO.util.Cookie={_createCookieString:function(B,D,C,A){var F=YAHOO.lang,E=encodeURIComponent(B)+"="+(C?encodeURIComponent(D):D);if(F.isObject(A)){if(A.expires instanceof Date){E+="; expires="+A.expires.toUTCString();}if(F.isString(A.path)&&A.path!==""){E+="; path="+A.path;}if(F.isString(A.domain)&&A.domain!==""){E+="; domain="+A.domain;}if(A.secure===true){E+="; secure";}}return E;},_createCookieHashString:function(B){var D=YAHOO.lang;if(!D.isObject(B)){throw new TypeError("Cookie._createCookieHashString(): Argument must be an object.");}var C=[];for(var A in B){if(D.hasOwnProperty(B,A)&&!D.isFunction(B[A])&&!D.isUndefined(B[A])){C.push(encodeURIComponent(A)+"="+encodeURIComponent(String(B[A])));}}return C.join("&");},_parseCookieHash:function(E){var D=E.split("&"),F=null,C={};if(E.length>0){for(var B=0,A=D.length;B<A;B++){F=D[B].split("=");C[decodeURIComponent(F[0])]=decodeURIComponent(F[1]);}}return C;},_parseCookieString:function(J,A){var K={};if(YAHOO.lang.isString(J)&&J.length>0){var B=(A===false?function(L){return L;}:decodeURIComponent);var H=J.split(/;\s/g),I=null,C=null,E=null;for(var D=0,F=H.length;D<F;D++){E=H[D].match(/([^=]+)=/i);if(E instanceof Array){try{I=decodeURIComponent(E[1]);C=B(H[D].substring(E[1].length+1));}catch(G){}}else{I=decodeURIComponent(H[D]);C="";}K[I]=C;}}return K;},exists:function(A){if(!YAHOO.lang.isString(A)||A===""){throw new TypeError("Cookie.exists(): Cookie name must be a non-empty string.");}var B=this._parseCookieString(document.cookie,true);return B.hasOwnProperty(A);},get:function(B,A){var E=YAHOO.lang,C;if(E.isFunction(A)){C=A;A={};}else{if(E.isObject(A)){C=A.converter;}else{A={};}}var D=this._parseCookieString(document.cookie,!A.raw);if(!E.isString(B)||B===""){throw new TypeError("Cookie.get(): Cookie name must be a non-empty string.");}if(E.isUndefined(D[B])){return null;}if(!E.isFunction(C)){return D[B];}else{return C(D[B]);}},getSub:function(A,C,B){var E=YAHOO.lang,D=this.getSubs(A);if(D!==null){if(!E.isString(C)||C===""){throw new TypeError("Cookie.getSub(): Subcookie name must be a non-empty string.");}if(E.isUndefined(D[C])){return null;}if(!E.isFunction(B)){return D[C];}else{return B(D[C]);}}else{return null;}},getSubs:function(B){var A=YAHOO.lang.isString;if(!A(B)||B===""){throw new TypeError("Cookie.getSubs(): Cookie name must be a non-empty string.");}var C=this._parseCookieString(document.cookie,false);if(A(C[B])){return this._parseCookieHash(C[B]);}return null;},remove:function(B,A){if(!YAHOO.lang.isString(B)||B===""){throw new TypeError("Cookie.remove(): Cookie name must be a non-empty string.");}A=YAHOO.lang.merge(A||{},{expires:new Date(0)});return this.set(B,"",A);},removeSub:function(B,E,A){var F=YAHOO.lang;A=A||{};if(!F.isString(B)||B===""){throw new TypeError("Cookie.removeSub(): Cookie name must be a non-empty string.");}if(!F.isString(E)||E===""){throw new TypeError("Cookie.removeSub(): Subcookie name must be a non-empty string.");}var D=this.getSubs(B);if(F.isObject(D)&&F.hasOwnProperty(D,E)){delete D[E];if(!A.removeIfEmpty){return this.setSubs(B,D,A);}else{for(var C in D){if(F.hasOwnProperty(D,C)&&!F.isFunction(D[C])&&!F.isUndefined(D[C])){return this.setSubs(B,D,A);}}return this.remove(B,A);}}else{return"";}},set:function(B,C,A){var E=YAHOO.lang;A=A||{};if(!E.isString(B)){throw new TypeError("Cookie.set(): Cookie name must be a string.");}if(E.isUndefined(C)){throw new TypeError("Cookie.set(): Value cannot be undefined.");}var D=this._createCookieString(B,C,!A.raw,A);document.cookie=D;return D;},setSub:function(B,D,C,A){var F=YAHOO.lang;if(!F.isString(B)||B===""){throw new TypeError("Cookie.setSub(): Cookie name must be a non-empty string.");}if(!F.isString(D)||D===""){throw new TypeError("Cookie.setSub(): Subcookie name must be a non-empty string.");}if(F.isUndefined(C)){throw new TypeError("Cookie.setSub(): Subcookie value cannot be undefined.");}var E=this.getSubs(B);if(!F.isObject(E)){E={};}E[D]=C;return this.setSubs(B,E,A);},setSubs:function(B,C,A){var E=YAHOO.lang;if(!E.isString(B)){throw new TypeError("Cookie.setSubs(): Cookie name must be a string.");}if(!E.isObject(C)){throw new TypeError("Cookie.setSubs(): Cookie value must be an object.");}var D=this._createCookieString(B,this._createCookieHashString(C),false,A);document.cookie=D;return D;}};YAHOO.register("cookie",YAHOO.util.Cookie,{version:"2.9.0",build:"2800"});
\ No newline at end of file