From 464fff4c0375126dc186be7ba620dbb3a006fb2c Mon Sep 17 00:00:00 2001 From: Shawn Hurley Date: Tue, 13 Aug 2024 11:36:13 -0400 Subject: [PATCH] Adding two new static file extension folders for Java Specific Workflows (#97) * Adding two new static file extension folders for Java Specific Workflows When using a spring boot application in Java, many of the static files will be placed in META-INF/resources. Right now these are treated like first class concepts, eventually moving the weight of Java application down far enough to not be selected. Signed-off-by: Shawn Hurley * adding test case for the coolstore application Signed-off-by: Shawn Hurley * Restructure test resource Signed-off-by: thepetk * Increase number of total projects Signed-off-by: thepetk --------- Signed-off-by: Shawn Hurley Signed-off-by: thepetk Co-authored-by: thepetk --- pkg/apis/recognizer/language_recognizer.go | 2 +- .../js-static-files-in-java-app/pom.xml | 160 + .../com/redhat/coolstore/utils/Producers.java | 17 + .../redhat/coolstore/utils/Transformers.java | 100 + .../resources/META-INF/resources/app/app.js | 113 + .../resources/app/controllers/controllers.js | 163 + .../resources/app/directives/header.js | 11 + .../META-INF/resources/app/routes/routes.js | 13 + .../META-INF/resources/app/services/cart.js | 126 + .../resources/app/services/catalog.js | 37 + .../angular-animate/angular-animate.js | 4152 ++ .../angular-animate/angular-animate.min.js | 57 + .../angular-animate.min.js.map | 8 + .../bower_components/angular-animate/index.js | 2 + .../angular-bootstrap/index.js | 2 + .../angular-bootstrap/ui-bootstrap-tpls.js | 8503 ++++ .../ui-bootstrap-tpls.min.js | 12 + .../angular-bootstrap/ui-bootstrap.js | 8126 ++++ .../angular-bootstrap/ui-bootstrap.min.js | 11 + .../dist/angular-patternfly.js | 10378 +++++ .../dist/angular-patternfly.min.js | 4 + .../docs/grunt-scripts/angular-animate.js | 4152 ++ .../angular-bootstrap-prettify.js | 323 + .../docs/grunt-scripts/angular-patternfly.js | 10378 +++++ .../docs/grunt-scripts/angular-sanitize.js | 739 + .../grunt-scripts/angular-ui-router.min.js | 11 + .../dist/docs/grunt-scripts/angular.js | 32621 ++++++++++++++++ .../docs/grunt-scripts/bootstrap-combobox.js | 462 + .../grunt-scripts/bootstrap-datepicker.js | 2096 + .../grunt-scripts/bootstrap-datetimepicker.js | 2637 ++ .../docs/grunt-scripts/bootstrap-select.js | 1709 + .../docs/grunt-scripts/bootstrap-treeview.js | 1931 + .../dist/docs/grunt-scripts/bootstrap.js | 2377 ++ .../dist/docs/grunt-scripts/c3.js | 8202 ++++ .../dist/docs/grunt-scripts/d3.js | 9554 +++++ .../dist/docs/grunt-scripts/jquery.js | 9210 +++++ .../dist/docs/grunt-scripts/lodash.min.js | 98 + .../dist/docs/grunt-scripts/moment.js | 4195 ++ .../dist/docs/grunt-scripts/patternfly.js | 1652 + .../docs/grunt-scripts/ui-bootstrap-tpls.js | 8503 ++++ .../docs/js/angular-bootstrap-prettify.js | 322 + .../dist/docs/js/angular-bootstrap.js | 392 + .../dist/docs/js/angular.min.js | 230 + .../dist/docs/js/docs-setup.js | 412 + .../angular-patternfly/dist/docs/js/docs.js | 541 + .../dist/docs/js/google-code-prettify.js | 1575 + .../angular-patternfly/dist/docs/js/marked.js | 1151 + .../angular-patternfly/index.js | 8 + .../test/autofocus/autofocus.spec.js | 113 + .../aggregate-status-card.directive.spec.js | 228 + .../test/card/basic/card.spec.js | 232 + .../test/charts/c3/c3.spec.js | 25 + .../test/charts/donut/donut-pct.spec.js | 133 + .../charts/heatmap/heatmap-legend.spec.js | 47 + .../test/charts/heatmap/heatmap.spec.js | 116 + .../charts/sparkline/sparkline-chart.spec.js | 181 + .../test/charts/trends/trends-chart.spec.js | 127 + .../utilization-bar/utilization-bar.spec.js | 109 + .../utilization-trend-chart.spec.js | 109 + .../test/filters/filter.spec.js | 210 + .../datepicker/datepicker.directive.spec.js | 42 + .../datetimepicker.directive.spec.js | 38 + .../form-buttons.directive.spec.js | 39 + .../form-group/form-group.directive.spec.js | 62 + .../remaining-chars-count.directive.spec.js | 68 + .../test/modals/about-modal.spec.js | 181 + .../navigation/vertical-navigation.spec.js | 826 + .../notification/notification-drawer.spec.js | 485 + .../test/notification/notification.spec.js | 198 + .../toast-notification-list.spec.js | 210 + .../notification/toast-notification.spec.js | 241 + .../test/select/select.spec.js | 118 + .../angular-patternfly/test/sort/sort.spec.js | 186 + .../test/toolbars/toolbar.spec.js | 582 + .../test/utils/fixed-accordion.spec.js | 71 + .../test/utils/specUtils.js | 11 + .../test/utils/transclude-directive.spec.js | 108 + .../test/utils/utils.spec.js | 92 + .../test/validation/validation.spec.js | 175 + .../test/views/cardview/card-view.spec.js | 222 + .../test/views/listview/list-view.spec.js | 545 + .../angular-patternfly/test/wizard/script.js | 59 + .../test/wizard/wizard.spec.js | 205 + .../angular-route/angular-route.js | 1071 + .../angular-route/angular-route.min.js | 16 + .../angular-route/angular-route.min.js.map | 8 + .../bower_components/angular-route/index.js | 2 + .../angular-sanitize/angular-sanitize.js | 739 + .../angular-sanitize/angular-sanitize.min.js | 16 + .../angular-sanitize.min.js.map | 8 + .../angular-sanitize/index.js | 2 + .../bower_components/angular/angular.js | 32621 ++++++++++++++++ .../bower_components/angular/angular.min.js | 324 + .../angular/angular.min.js.gzip | Bin 0 -> 58216 bytes .../angular/angular.min.js.map | 8 + .../bower_components/angular/index.js | 2 + test/apis/component_recognizer_test.go | 2 +- test/apis/language_recognizer_test.go | 4 + 98 files changed, 178693 insertions(+), 2 deletions(-) create mode 100644 resources/projects/js-static-files-in-java-app/pom.xml create mode 100644 resources/projects/js-static-files-in-java-app/src/main/java/com/redhat/coolstore/utils/Producers.java create mode 100644 resources/projects/js-static-files-in-java-app/src/main/java/com/redhat/coolstore/utils/Transformers.java create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/app.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/controllers/controllers.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/directives/header.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/routes/routes.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/services/cart.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/services/catalog.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-animate/angular-animate.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-animate/angular-animate.min.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-animate/angular-animate.min.js.map create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-animate/index.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-bootstrap/index.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-bootstrap/ui-bootstrap-tpls.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-bootstrap/ui-bootstrap.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-bootstrap/ui-bootstrap.min.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/angular-patternfly.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/angular-patternfly.min.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/angular-animate.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/angular-bootstrap-prettify.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/angular-patternfly.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/angular-sanitize.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/angular-ui-router.min.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/angular.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/bootstrap-combobox.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/bootstrap-datepicker.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/bootstrap-datetimepicker.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/bootstrap-select.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/bootstrap-treeview.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/bootstrap.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/c3.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/d3.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/jquery.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/lodash.min.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/moment.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/patternfly.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/ui-bootstrap-tpls.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/js/angular-bootstrap-prettify.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/js/angular-bootstrap.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/js/angular.min.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/js/docs-setup.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/js/docs.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/js/google-code-prettify.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/js/marked.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/index.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/autofocus/autofocus.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/card/aggregate-status/aggregate-status-card.directive.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/card/basic/card.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/charts/c3/c3.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/charts/donut/donut-pct.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/charts/heatmap/heatmap-legend.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/charts/heatmap/heatmap.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/charts/sparkline/sparkline-chart.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/charts/trends/trends-chart.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/charts/utilization-bar/utilization-bar.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/charts/utilization-trend/utilization-trend-chart.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/filters/filter.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/form/datepicker/datepicker.directive.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/form/datetimepicker/datetimepicker.directive.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/form/form-buttons/form-buttons.directive.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/form/form-group/form-group.directive.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/form/remaining-chars-count/remaining-chars-count.directive.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/modals/about-modal.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/navigation/vertical-navigation.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/notification/notification-drawer.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/notification/notification.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/notification/toast-notification-list.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/notification/toast-notification.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/select/select.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/sort/sort.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/toolbars/toolbar.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/utils/fixed-accordion.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/utils/specUtils.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/utils/transclude-directive.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/utils/utils.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/validation/validation.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/views/cardview/card-view.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/views/listview/list-view.spec.js create mode 100755 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/wizard/script.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/test/wizard/wizard.spec.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-route/angular-route.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-route/angular-route.min.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-route/angular-route.min.js.map create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-route/index.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-sanitize/angular-sanitize.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-sanitize/angular-sanitize.min.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-sanitize/angular-sanitize.min.js.map create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-sanitize/index.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular/angular.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular/angular.min.js create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular/angular.min.js.gzip create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular/angular.min.js.map create mode 100644 resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular/index.js diff --git a/pkg/apis/recognizer/language_recognizer.go b/pkg/apis/recognizer/language_recognizer.go index 6474b906..c1ba468f 100644 --- a/pkg/apis/recognizer/language_recognizer.go +++ b/pkg/apis/recognizer/language_recognizer.go @@ -143,7 +143,7 @@ func AnalyzeFile(configFile string, targetLanguage string) (model.Language, erro } func isStaticFileExtension(path string) bool { - staticDirs := [2]string{"static/", "templates/"} + staticDirs := [4]string{"static/", "templates/", "META-INF/resources/", "public/"} for _, dir := range staticDirs { if strings.Contains(path, dir) { return true diff --git a/resources/projects/js-static-files-in-java-app/pom.xml b/resources/projects/js-static-files-in-java-app/pom.xml new file mode 100644 index 00000000..20997e37 --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/pom.xml @@ -0,0 +1,160 @@ + + + 4.0.0 + com.redhat.coolstore + coolstore + 1.0.0-SNAPSHOT + coolstore-quarkus + + 3.13.0 + 21 + UTF-8 + UTF-8 + quarkus-bom + io.quarkus.platform + 3.12.3 + true + 3.2.5 + + + + + io.quarkus.platform + quarkus-bom + ${quarkus.platform.version} + pom + import + + + + + + io.quarkus + quarkus-arc + + + io.quarkus + quarkus-resteasy + + + io.quarkus + quarkus-resteasy-jackson + + + io.quarkus + quarkus-resteasy-client + + + io.quarkus + quarkus-resteasy-client-jackson + + + io.quarkus + quarkus-hibernate-orm + + + io.quarkus + quarkus-jdbc-postgresql + + + io.quarkus + quarkus-flyway + + + org.flywaydb + flyway-database-postgresql + 10.12.0 + runtime + + + io.quarkus + quarkus-undertow + + + io.quarkus + quarkus-messaging + + + io.quarkus + quarkus-container-image-docker + + + io.quarkus + quarkus-minikube + + + + + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + true + + + + build + generate-code + generate-code-tests + native-image-agent + + + + + + maven-compiler-plugin + ${compiler-plugin.version} + + + -parameters + + + + + maven-surefire-plugin + ${surefire-plugin.version} + + + org.jboss.logmanager.LogManager + ${maven.home} + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + + + ${project.build.directory}/${project.build.finalName}-runner + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + + native + + + native + + + + false + true + + + + diff --git a/resources/projects/js-static-files-in-java-app/src/main/java/com/redhat/coolstore/utils/Producers.java b/resources/projects/js-static-files-in-java-app/src/main/java/com/redhat/coolstore/utils/Producers.java new file mode 100644 index 00000000..7ea8eedb --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/java/com/redhat/coolstore/utils/Producers.java @@ -0,0 +1,17 @@ +package com.redhat.coolstore.utils; + +import jakarta.enterprise.inject.Produces; +import jakarta.enterprise.inject.spi.InjectionPoint; +import java.util.logging.Logger; + + +public class Producers { + + Logger log = Logger.getLogger(Producers.class.getName()); + + @Produces + public Logger produceLog(InjectionPoint injectionPoint) { + return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName()); + } + +} diff --git a/resources/projects/js-static-files-in-java-app/src/main/java/com/redhat/coolstore/utils/Transformers.java b/resources/projects/js-static-files-in-java-app/src/main/java/com/redhat/coolstore/utils/Transformers.java new file mode 100644 index 00000000..5c445c96 --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/java/com/redhat/coolstore/utils/Transformers.java @@ -0,0 +1,100 @@ +package com.redhat.coolstore.utils; + +import com.redhat.coolstore.model.CatalogItemEntity; +import com.redhat.coolstore.model.Order; +import com.redhat.coolstore.model.OrderItem; +import com.redhat.coolstore.model.Product; +import com.redhat.coolstore.model.ShoppingCart; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonArrayBuilder; +import jakarta.json.JsonObject; +import jakarta.json.JsonReader; +import jakarta.json.JsonWriter; + +import java.util.concurrent.ThreadLocalRandom; +import java.util.logging.Logger; + +/** + * Created by tqvarnst on 2017-03-30. + */ +public class Transformers { + + private static final String[] RANDOM_NAMES = {"Sven Karlsson","Johan Andersson","Karl Svensson","Anders Johansson","Stefan Olson","Martin Ericsson"}; + private static final String[] RANDOM_EMAILS = {"sven@gmail.com","johan@gmail.com","karl@gmail.com","anders@gmail.com","stefan@gmail.com","martin@gmail.com"}; + + private static Logger log = Logger.getLogger(Transformers.class.getName()); + + public static Product toProduct(CatalogItemEntity entity) { + Product prod = new Product(); + prod.setItemId(entity.getItemId()); + prod.setName(entity.getName()); + prod.setDesc(entity.getDesc()); + prod.setPrice(entity.getPrice()); + if (entity.getInventory() != null) { + prod.setLocation(entity.getInventory().getLocation()); + prod.setLink(entity.getInventory().getLink()); + prod.setQuantity(entity.getInventory().getQuantity()); + } else { + log.warning("Inventory for " + entity.getName() + "[" + entity.getItemId()+ "] unknown and missing"); + } + return prod; + } + + public static String shoppingCartToJson(ShoppingCart cart) { + JsonArrayBuilder cartItems = Json.createArrayBuilder(); + cart.getShoppingCartItemList().forEach(item -> { + cartItems.add(Json.createObjectBuilder() + .add("productSku",item.getProduct().getItemId()) + .add("quantity",item.getQuantity()) + ); + }); + + int randomNameAndEmailIndex = ThreadLocalRandom.current().nextInt(RANDOM_NAMES.length); + + JsonObject jsonObject = Json.createObjectBuilder() + .add("orderValue", Double.valueOf(cart.getCartTotal())) + .add("customerName",RANDOM_NAMES[randomNameAndEmailIndex]) + .add("customerEmail",RANDOM_EMAILS[randomNameAndEmailIndex]) + .add("retailPrice", cart.getShoppingCartItemList().stream().mapToDouble(i -> i.getQuantity()*i.getPrice()).sum()) + .add("discount", Double.valueOf(cart.getCartItemPromoSavings())) + .add("shippingFee", Double.valueOf(cart.getShippingTotal())) + .add("shippingDiscount", Double.valueOf(cart.getShippingPromoSavings())) + .add("items",cartItems) + .build(); + StringWriter w = new StringWriter(); + try (JsonWriter writer = Json.createWriter(w)) { + writer.write(jsonObject); + } + return w.toString(); + } + + public static Order jsonToOrder(String json) { + JsonReader jsonReader = Json.createReader(new StringReader(json)); + JsonObject rootObject = jsonReader.readObject(); + Order order = new Order(); + order.setCustomerName(rootObject.getString("customerName")); + order.setCustomerEmail(rootObject.getString("customerEmail")); + order.setOrderValue(rootObject.getJsonNumber("orderValue").doubleValue()); + order.setRetailPrice(rootObject.getJsonNumber("retailPrice").doubleValue()); + order.setDiscount(rootObject.getJsonNumber("discount").doubleValue()); + order.setShippingFee(rootObject.getJsonNumber("shippingFee").doubleValue()); + order.setShippingDiscount(rootObject.getJsonNumber("shippingDiscount").doubleValue()); + JsonArray jsonItems = rootObject.getJsonArray("items"); + List items = new ArrayList(jsonItems.size()); + for (JsonObject jsonItem : jsonItems.getValuesAs(JsonObject.class)) { + OrderItem oi = new OrderItem(); + oi.setProductId(jsonItem.getString("productSku")); + oi.setQuantity(jsonItem.getInt("quantity")); + items.add(oi); + } + order.setItemList(items); + return order; + } + + +} diff --git a/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/app.js b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/app.js new file mode 100644 index 00000000..7be452f8 --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/app.js @@ -0,0 +1,113 @@ +'use strict'; + +var module = angular.module('app', ['ngRoute', 'patternfly']), auth = { + loggedIn: false, + ssoEnabled: false, + logout: function () { + } +}; + + +module.factory('Auth', function () { + return auth; +}); + +angular.element(document).ready(function () { + + // get config + var initInjector = angular.injector(["ng"]); + var $http = initInjector.get("$http"); + + $http.get("coolstore.json").then(function (response) { + module.constant("COOLSTORE_CONFIG", response.data); + if (!response.data.SSO_ENABLED) { + angular.bootstrap(document, ["app"], { + strictDi: true + }); + } else { + auth.ssoEnabled = true; + var keycloakAuth = new Keycloak('keycloak.json'); + auth.loggedIn = false; + + auth.login = function () { + keycloakAuth.login({ + loginHint: 'appuser' + }); + }; + + keycloakAuth.init({ + onLoad: 'check-sso' + }).success(function () { + if (keycloakAuth.authenticated) { + keycloakAuth.loadUserInfo().success(function (userInfo) { + auth.userInfo = userInfo; + angular.bootstrap(document, ["app"], { + strictDi: true + }); + auth.loggedIn = true; + auth.authz = keycloakAuth; + auth.logout = function () { + auth.loggedIn = false; + auth.authz = null; + auth.userInfo = {}; + keycloakAuth.logout(); + }; + }).error(function () { + angular.bootstrap(document, ["app"], { + strictDi: true + }); + + }); + } else { + angular.bootstrap(document, ["app"], { + strictDi: true + }); + } + }).error(function (msg) { + angular.bootstrap(document, ["app"], { + strictDi: true + }); + }); + } + }); +}); + + +// setup interceptors +module.config(['$httpProvider', function ($httpProvider) { + + $httpProvider.interceptors.push(['$q', 'Auth', function ($q, Auth) { + return { + 'request': function (config) { + var deferred = $q.defer(); + if (Auth.authz && Auth.authz.token) { + Auth.authz.updateToken(5).success(function () { + config.headers = config.headers || {}; + config.headers.Authorization = 'Bearer ' + Auth.authz.token; + config.withCredentials = true; + deferred.resolve(config); + }).error(function () { + deferred.reject('Failed to refresh token'); + }); + } else { + config.withCredentials = false; + deferred.resolve(config); + } + return deferred.promise; + + }, + 'responseError': function (response) { + if (response.status == 401) { + auth.logout(); + } + return $q.reject(response); + + } + } + }]); +}]); + + + + + diff --git a/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/controllers/controllers.js b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/controllers/controllers.js new file mode 100644 index 00000000..c1ed164b --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/controllers/controllers.js @@ -0,0 +1,163 @@ +'use strict'; + +angular.module('app') + + .controller("HomeController", + ['$scope', '$http', '$filter', 'Notifications', 'cart', 'catalog', 'Auth', + function ($scope, $http, $filter, Notifications, cart, catalog, $auth) { + $scope.products = []; + $scope.addToCart = function (item) { + cart.addToCart(item.product, parseInt(item.quantity)).then(function (data) { + Notifications.success("Added! Your total is " + $filter('currency')(data.cartTotal)); + }, function (err) { + Notifications.error("Error adding to cart: " + err.statusText); + }); + }; + + $scope.isLoggedIn = function () { + return $auth.loggedIn; + }; + $scope.ssoEnabled = function () { + return $auth.ssoEnabled; + }; + + $scope.login = function () { + $auth.login(); + }; + + + // initialize products + catalog.getProducts().then(function (data) { + $scope.products = data.map(function (el) { + return { + quantity: "1", + product: el + } + }) + }, function (err) { + Notifications.error("Error retrieving products: " + err.statusText); + }); + + + }]) + + .controller("CartController", + ['$scope', '$http', 'Notifications', 'cart', 'Auth', + function ($scope, $http, Notifications, cart, $auth) { + + function reset() { + $scope.cart = cart.getCart(); + $scope.items = $scope.cart.shoppingCartItemList; + + $scope.subtotal = 0; + $scope.cart.shoppingCartItemList.forEach(function (item) { + $scope.subtotal += (item.quantity * item.product.price); + }); + } + + $scope.config = { + selectItems: false, + multiSelect: false, + dblClick: false, + showSelectBox: false + }; + + function performAction(action, item) { + cart.removeFromCart(item.product, item.quantity).then(function (newCart) { + reset(); + }, function (err) { + Notifications.error("Error removing from cart: " + err.statusText); + }); + }; + + $scope.actionButtons = [ + { + name: 'Remove', + title: 'Remove', + actionFn: performAction + } + ]; + + + $scope.$watch(function () { + return cart.getCart(); + }, function (newValue) { + reset(); + }); + + $scope.$watch(function () { + return $auth.userInfo; + }, function (newValue) { + cart.reset(); + }); + + $scope.checkout = function () { + cart.checkout().then(function (cartData) { + }, function (err) { + Notifications.error("Error checking out: " + err.statusText); + }); + }; + + $scope.isLoggedIn = function () { + return $auth.loggedIn; + }; + $scope.ssoEnabled = function () { + return $auth.ssoEnabled; + }; + + reset(); + }]) + + .controller("HeaderController", + ['$scope', '$location', '$http', 'Notifications', 'cart', 'Auth', + function ($scope, $location, $http, Notifications, cart, $auth) { + $scope.userInfo = $auth.userInfo; + + $scope.cartTotal = 0.0; + $scope.itemCount = 0; + + $scope.isLoggedIn = function () { + return $auth.loggedIn; + }; + + $scope.login = function () { + $auth.login(); + }; + $scope.logout = function () { + $auth.logout(); + }; + $scope.isLoggedIn = function () { + return $auth.loggedIn; + }; + $scope.ssoEnabled = function () { + return $auth.ssoEnabled; + }; + $scope.profile = function () { + $auth.authz.accountManagement(); + }; + $scope.$watch(function () { + return cart.getCart().cartTotal || 0.0; + }, function (newValue) { + $scope.cartTotal = newValue; + }); + + $scope.$watch(function () { + var totalItems = 0; + cart.getCart().shoppingCartItemList.forEach(function (el) { + totalItems += el.quantity; + }); + return totalItems; + }, function (newValue) { + $scope.itemCount = newValue; + }); + + $scope.$watch(function () { + return $auth.userInfo; + }, function (newValue) { + $scope.userInfo = newValue; + }); + + $scope.isActive = function (loc) { + return loc === $location.path(); + } + }]); diff --git a/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/directives/header.js b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/directives/header.js new file mode 100644 index 00000000..83906af0 --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/directives/header.js @@ -0,0 +1,11 @@ +'use strict'; + + +angular.module('app').directive('header', function() { + return { + restrict: 'A', + replace: true, + templateUrl: 'partials/header.html', + controller: 'HeaderController' + } +}); diff --git a/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/routes/routes.js b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/routes/routes.js new file mode 100644 index 00000000..39cdfbe2 --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/routes/routes.js @@ -0,0 +1,13 @@ +'use strict'; + +angular.module('app').config([ '$routeProvider', function($routeProvider) { + $routeProvider.when('/', { + templateUrl : 'partials/home.html', + controller : 'HomeController' + }).when('/cart', { + templateUrl : 'partials/cart.html', + controller : 'CartController' + }).otherwise({ + redirectTo : '/' + }); +} ]); diff --git a/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/services/cart.js b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/services/cart.js new file mode 100644 index 00000000..f2b1b52f --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/services/cart.js @@ -0,0 +1,126 @@ +'use strict'; + +angular.module("app") + +.factory('cart', ['$http', '$q', 'COOLSTORE_CONFIG', 'Auth', '$location', function($http, $q, COOLSTORE_CONFIG, $auth, $location) { + var factory = {}, cart, products, cartId, baseUrl; + + if(!!COOLSTORE_CONFIG.MONOLITH) { + baseUrl='/services/cart'; + } else { + if ($location.protocol() === 'https') { + baseUrl = (COOLSTORE_CONFIG.SECURE_API_ENDPOINT.startsWith("https://") ? COOLSTORE_CONFIG.SECURE_API_ENDPOINT : "https://" + COOLSTORE_CONFIG.SECURE_API_ENDPOINT + '.' + $location.host().replace(/^.*?\.(.*)/g,"$1")) + '/services/cart'; + } else { + baseUrl = (COOLSTORE_CONFIG.API_ENDPOINT.startsWith("http://") ? COOLSTORE_CONFIG.API_ENDPOINT : "http://" + COOLSTORE_CONFIG.API_ENDPOINT + '.' + $location.host().replace(/^.*?\.(.*)/g,"$1")) + '/services/cart'; + } + } + + factory.checkout = function() { + var deferred = $q.defer(); + $http({ + method: 'POST', + url: baseUrl + '/checkout/' + cartId + }).then(function(resp) { + cart = resp.data; + deferred.resolve(resp.data); + }, function(err) { + deferred.reject(err); + }); + return deferred.promise; + }; + + factory.reset = function() { + cart = { + shoppingCartItemList: [] + }; + var tmpId = localStorage.getItem('cartId'); + var authId = $auth.userInfo ? $auth.userInfo.sub : null; + + if (tmpId && authId) { + // transfer cart + cartId = authId; + this.setCart(tmpId).then(function(result) { + localStorage.removeItem('cartId'); + }, function(err) { + console.log("could not transfer cart " + tmpId + " to cart " + authId + ": " + err); + }); + return; + } + + if (tmpId && !authId) { + cartId = tmpId; + } + + if (!tmpId && authId) { + cartId = authId; + } + + if (!tmpId && !authId) { + tmpId = 'id-' + Math.random(); + localStorage.setItem('cartId', tmpId); + cartId = tmpId; + } + + cart.shoppingCartItemList = []; + $http({ + method: 'GET', + url: baseUrl + '/' + cartId + }).then(function(resp) { + cart = resp.data; + }, function(err) { + }); + + }; + + factory.getCart = function() { + return cart; + }; + + factory.removeFromCart = function(product, quantity) { + var deferred = $q.defer(); + $http({ + method: 'DELETE', + url: baseUrl + '/' + cartId + '/' + product.itemId + '/' + quantity + }).then(function(resp) { + cart = resp.data; + deferred.resolve(resp.data); + }, function(err) { + deferred.reject(err); + }); + return deferred.promise; + + }; + + factory.setCart = function(id) { + var deferred = $q.defer(); + $http({ + method: 'POST', + url: baseUrl + '/' + cartId + '/' + id + }).then(function(resp) { + cart = resp.data; + deferred.resolve(resp.data); + }, function(err) { + deferred.reject(err); + }); + return deferred.promise; + + }; + + factory.addToCart = function(product, quantity) { + var deferred = $q.defer(); + $http({ + method: 'POST', + url: baseUrl + '/' + cartId + '/' + product.itemId + '/' + quantity + }).then(function(resp) { + cart = resp.data; + deferred.resolve(resp.data); + }, function(err) { + deferred.reject(err); + }); + return deferred.promise; + + }; + + factory.reset(); + return factory; +}]); diff --git a/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/services/catalog.js b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/services/catalog.js new file mode 100644 index 00000000..59fabe17 --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/app/services/catalog.js @@ -0,0 +1,37 @@ +'use strict'; + +angular.module("app") + +.factory('catalog', ['$http', '$q', 'COOLSTORE_CONFIG', 'Auth', '$location', function($http, $q, COOLSTORE_CONFIG, $auth, $location) { + var factory = {}, products, baseUrl; + + if(!!COOLSTORE_CONFIG.MONOLITH) { + baseUrl='/services/products'; + } else { + if ($location.protocol() === 'https') { + baseUrl = (COOLSTORE_CONFIG.SECURE_API_ENDPOINT.startsWith("https://") ? COOLSTORE_CONFIG.SECURE_API_ENDPOINT : "https://" + COOLSTORE_CONFIG.SECURE_API_ENDPOINT + '.' + $location.host().replace(/^.*?\.(.*)/g,"$1")) + '/services/products'; + } else { + baseUrl = (COOLSTORE_CONFIG.API_ENDPOINT.startsWith("http://") ? COOLSTORE_CONFIG.API_ENDPOINT : "http://" + COOLSTORE_CONFIG.API_ENDPOINT + '.' + $location.host().replace(/^.*?\.(.*)/g,"$1")) + '/services/products'; + } + } + + factory.getProducts = function() { + var deferred = $q.defer(); + if (products) { + deferred.resolve(products); + } else { + $http({ + method: 'GET', + url: baseUrl + }).then(function(resp) { + products = resp.data; + deferred.resolve(resp.data); + }, function(err) { + deferred.reject(err); + }); + } + return deferred.promise; + }; + + return factory; +}]); diff --git a/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-animate/angular-animate.js b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-animate/angular-animate.js new file mode 100644 index 00000000..bbe4c3f6 --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-animate/angular-animate.js @@ -0,0 +1,4152 @@ +/** + * @license AngularJS v1.5.11 + * (c) 2010-2017 Google, Inc. http://angularjs.org + * License: MIT + */ +(function(window, angular) {'use strict'; + +var ELEMENT_NODE = 1; +var COMMENT_NODE = 8; + +var ADD_CLASS_SUFFIX = '-add'; +var REMOVE_CLASS_SUFFIX = '-remove'; +var EVENT_CLASS_PREFIX = 'ng-'; +var ACTIVE_CLASS_SUFFIX = '-active'; +var PREPARE_CLASS_SUFFIX = '-prepare'; + +var NG_ANIMATE_CLASSNAME = 'ng-animate'; +var NG_ANIMATE_CHILDREN_DATA = '$$ngAnimateChildren'; + +// Detect proper transitionend/animationend event names. +var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT; + +// If unprefixed events are not supported but webkit-prefixed are, use the latter. +// Otherwise, just use W3C names, browsers not supporting them at all will just ignore them. +// Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend` +// but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`. +// Register both events in case `window.onanimationend` is not supported because of that, +// do the same for `transitionend` as Safari is likely to exhibit similar behavior. +// Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit +// therefore there is no reason to test anymore for other vendor prefixes: +// http://caniuse.com/#search=transition +if ((window.ontransitionend === undefined) && (window.onwebkittransitionend !== undefined)) { + CSS_PREFIX = '-webkit-'; + TRANSITION_PROP = 'WebkitTransition'; + TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend'; +} else { + TRANSITION_PROP = 'transition'; + TRANSITIONEND_EVENT = 'transitionend'; +} + +if ((window.onanimationend === undefined) && (window.onwebkitanimationend !== undefined)) { + CSS_PREFIX = '-webkit-'; + ANIMATION_PROP = 'WebkitAnimation'; + ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend'; +} else { + ANIMATION_PROP = 'animation'; + ANIMATIONEND_EVENT = 'animationend'; +} + +var DURATION_KEY = 'Duration'; +var PROPERTY_KEY = 'Property'; +var DELAY_KEY = 'Delay'; +var TIMING_KEY = 'TimingFunction'; +var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount'; +var ANIMATION_PLAYSTATE_KEY = 'PlayState'; +var SAFE_FAST_FORWARD_DURATION_VALUE = 9999; + +var ANIMATION_DELAY_PROP = ANIMATION_PROP + DELAY_KEY; +var ANIMATION_DURATION_PROP = ANIMATION_PROP + DURATION_KEY; +var TRANSITION_DELAY_PROP = TRANSITION_PROP + DELAY_KEY; +var TRANSITION_DURATION_PROP = TRANSITION_PROP + DURATION_KEY; + +var ngMinErr = angular.$$minErr('ng'); +function assertArg(arg, name, reason) { + if (!arg) { + throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required')); + } + return arg; +} + +function mergeClasses(a,b) { + if (!a && !b) return ''; + if (!a) return b; + if (!b) return a; + if (isArray(a)) a = a.join(' '); + if (isArray(b)) b = b.join(' '); + return a + ' ' + b; +} + +function packageStyles(options) { + var styles = {}; + if (options && (options.to || options.from)) { + styles.to = options.to; + styles.from = options.from; + } + return styles; +} + +function pendClasses(classes, fix, isPrefix) { + var className = ''; + classes = isArray(classes) + ? classes + : classes && isString(classes) && classes.length + ? classes.split(/\s+/) + : []; + forEach(classes, function(klass, i) { + if (klass && klass.length > 0) { + className += (i > 0) ? ' ' : ''; + className += isPrefix ? fix + klass + : klass + fix; + } + }); + return className; +} + +function removeFromArray(arr, val) { + var index = arr.indexOf(val); + if (val >= 0) { + arr.splice(index, 1); + } +} + +function stripCommentsFromElement(element) { + if (element instanceof jqLite) { + switch (element.length) { + case 0: + return element; + + case 1: + // there is no point of stripping anything if the element + // is the only element within the jqLite wrapper. + // (it's important that we retain the element instance.) + if (element[0].nodeType === ELEMENT_NODE) { + return element; + } + break; + + default: + return jqLite(extractElementNode(element)); + } + } + + if (element.nodeType === ELEMENT_NODE) { + return jqLite(element); + } +} + +function extractElementNode(element) { + if (!element[0]) return element; + for (var i = 0; i < element.length; i++) { + var elm = element[i]; + if (elm.nodeType === ELEMENT_NODE) { + return elm; + } + } +} + +function $$addClass($$jqLite, element, className) { + forEach(element, function(elm) { + $$jqLite.addClass(elm, className); + }); +} + +function $$removeClass($$jqLite, element, className) { + forEach(element, function(elm) { + $$jqLite.removeClass(elm, className); + }); +} + +function applyAnimationClassesFactory($$jqLite) { + return function(element, options) { + if (options.addClass) { + $$addClass($$jqLite, element, options.addClass); + options.addClass = null; + } + if (options.removeClass) { + $$removeClass($$jqLite, element, options.removeClass); + options.removeClass = null; + } + }; +} + +function prepareAnimationOptions(options) { + options = options || {}; + if (!options.$$prepared) { + var domOperation = options.domOperation || noop; + options.domOperation = function() { + options.$$domOperationFired = true; + domOperation(); + domOperation = noop; + }; + options.$$prepared = true; + } + return options; +} + +function applyAnimationStyles(element, options) { + applyAnimationFromStyles(element, options); + applyAnimationToStyles(element, options); +} + +function applyAnimationFromStyles(element, options) { + if (options.from) { + element.css(options.from); + options.from = null; + } +} + +function applyAnimationToStyles(element, options) { + if (options.to) { + element.css(options.to); + options.to = null; + } +} + +function mergeAnimationDetails(element, oldAnimation, newAnimation) { + var target = oldAnimation.options || {}; + var newOptions = newAnimation.options || {}; + + var toAdd = (target.addClass || '') + ' ' + (newOptions.addClass || ''); + var toRemove = (target.removeClass || '') + ' ' + (newOptions.removeClass || ''); + var classes = resolveElementClasses(element.attr('class'), toAdd, toRemove); + + if (newOptions.preparationClasses) { + target.preparationClasses = concatWithSpace(newOptions.preparationClasses, target.preparationClasses); + delete newOptions.preparationClasses; + } + + // noop is basically when there is no callback; otherwise something has been set + var realDomOperation = target.domOperation !== noop ? target.domOperation : null; + + extend(target, newOptions); + + // TODO(matsko or sreeramu): proper fix is to maintain all animation callback in array and call at last,but now only leave has the callback so no issue with this. + if (realDomOperation) { + target.domOperation = realDomOperation; + } + + if (classes.addClass) { + target.addClass = classes.addClass; + } else { + target.addClass = null; + } + + if (classes.removeClass) { + target.removeClass = classes.removeClass; + } else { + target.removeClass = null; + } + + oldAnimation.addClass = target.addClass; + oldAnimation.removeClass = target.removeClass; + + return target; +} + +function resolveElementClasses(existing, toAdd, toRemove) { + var ADD_CLASS = 1; + var REMOVE_CLASS = -1; + + var flags = {}; + existing = splitClassesToLookup(existing); + + toAdd = splitClassesToLookup(toAdd); + forEach(toAdd, function(value, key) { + flags[key] = ADD_CLASS; + }); + + toRemove = splitClassesToLookup(toRemove); + forEach(toRemove, function(value, key) { + flags[key] = flags[key] === ADD_CLASS ? null : REMOVE_CLASS; + }); + + var classes = { + addClass: '', + removeClass: '' + }; + + forEach(flags, function(val, klass) { + var prop, allow; + if (val === ADD_CLASS) { + prop = 'addClass'; + allow = !existing[klass] || existing[klass + REMOVE_CLASS_SUFFIX]; + } else if (val === REMOVE_CLASS) { + prop = 'removeClass'; + allow = existing[klass] || existing[klass + ADD_CLASS_SUFFIX]; + } + if (allow) { + if (classes[prop].length) { + classes[prop] += ' '; + } + classes[prop] += klass; + } + }); + + function splitClassesToLookup(classes) { + if (isString(classes)) { + classes = classes.split(' '); + } + + var obj = {}; + forEach(classes, function(klass) { + // sometimes the split leaves empty string values + // incase extra spaces were applied to the options + if (klass.length) { + obj[klass] = true; + } + }); + return obj; + } + + return classes; +} + +function getDomNode(element) { + return (element instanceof jqLite) ? element[0] : element; +} + +function applyGeneratedPreparationClasses(element, event, options) { + var classes = ''; + if (event) { + classes = pendClasses(event, EVENT_CLASS_PREFIX, true); + } + if (options.addClass) { + classes = concatWithSpace(classes, pendClasses(options.addClass, ADD_CLASS_SUFFIX)); + } + if (options.removeClass) { + classes = concatWithSpace(classes, pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX)); + } + if (classes.length) { + options.preparationClasses = classes; + element.addClass(classes); + } +} + +function clearGeneratedClasses(element, options) { + if (options.preparationClasses) { + element.removeClass(options.preparationClasses); + options.preparationClasses = null; + } + if (options.activeClasses) { + element.removeClass(options.activeClasses); + options.activeClasses = null; + } +} + +function blockTransitions(node, duration) { + // we use a negative delay value since it performs blocking + // yet it doesn't kill any existing transitions running on the + // same element which makes this safe for class-based animations + var value = duration ? '-' + duration + 's' : ''; + applyInlineStyle(node, [TRANSITION_DELAY_PROP, value]); + return [TRANSITION_DELAY_PROP, value]; +} + +function blockKeyframeAnimations(node, applyBlock) { + var value = applyBlock ? 'paused' : ''; + var key = ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY; + applyInlineStyle(node, [key, value]); + return [key, value]; +} + +function applyInlineStyle(node, styleTuple) { + var prop = styleTuple[0]; + var value = styleTuple[1]; + node.style[prop] = value; +} + +function concatWithSpace(a,b) { + if (!a) return b; + if (!b) return a; + return a + ' ' + b; +} + +var $$rAFSchedulerFactory = ['$$rAF', function($$rAF) { + var queue, cancelFn; + + function scheduler(tasks) { + // we make a copy since RAFScheduler mutates the state + // of the passed in array variable and this would be difficult + // to track down on the outside code + queue = queue.concat(tasks); + nextTick(); + } + + queue = scheduler.queue = []; + + /* waitUntilQuiet does two things: + * 1. It will run the FINAL `fn` value only when an uncanceled RAF has passed through + * 2. It will delay the next wave of tasks from running until the quiet `fn` has run. + * + * The motivation here is that animation code can request more time from the scheduler + * before the next wave runs. This allows for certain DOM properties such as classes to + * be resolved in time for the next animation to run. + */ + scheduler.waitUntilQuiet = function(fn) { + if (cancelFn) cancelFn(); + + cancelFn = $$rAF(function() { + cancelFn = null; + fn(); + nextTick(); + }); + }; + + return scheduler; + + function nextTick() { + if (!queue.length) return; + + var items = queue.shift(); + for (var i = 0; i < items.length; i++) { + items[i](); + } + + if (!cancelFn) { + $$rAF(function() { + if (!cancelFn) nextTick(); + }); + } + } +}]; + +/** + * @ngdoc directive + * @name ngAnimateChildren + * @restrict AE + * @element ANY + * + * @description + * + * ngAnimateChildren allows you to specify that children of this element should animate even if any + * of the children's parents are currently animating. By default, when an element has an active `enter`, `leave`, or `move` + * (structural) animation, child elements that also have an active structural animation are not animated. + * + * Note that even if `ngAnimateChildren` is set, no child animations will run when the parent element is removed from the DOM (`leave` animation). + * + * + * @param {string} ngAnimateChildren If the value is empty, `true` or `on`, + * then child animations are allowed. If the value is `false`, child animations are not allowed. + * + * @example + * + +
+ + +
+
+
+ List of items: +
Item {{item}}
+
+
+
+
+ + + .container.ng-enter, + .container.ng-leave { + transition: all ease 1.5s; + } + + .container.ng-enter, + .container.ng-leave-active { + opacity: 0; + } + + .container.ng-leave, + .container.ng-enter-active { + opacity: 1; + } + + .item { + background: firebrick; + color: #FFF; + margin-bottom: 10px; + } + + .item.ng-enter, + .item.ng-leave { + transition: transform 1.5s ease; + } + + .item.ng-enter { + transform: translateX(50px); + } + + .item.ng-enter-active { + transform: translateX(0); + } + + + angular.module('ngAnimateChildren', ['ngAnimate']) + .controller('MainController', function MainController() { + this.animateChildren = false; + this.enterElement = false; + }); + +
+ */ +var $$AnimateChildrenDirective = ['$interpolate', function($interpolate) { + return { + link: function(scope, element, attrs) { + var val = attrs.ngAnimateChildren; + if (isString(val) && val.length === 0) { //empty attribute + element.data(NG_ANIMATE_CHILDREN_DATA, true); + } else { + // Interpolate and set the value, so that it is available to + // animations that run right after compilation + setData($interpolate(val)(scope)); + attrs.$observe('ngAnimateChildren', setData); + } + + function setData(value) { + value = value === 'on' || value === 'true'; + element.data(NG_ANIMATE_CHILDREN_DATA, value); + } + } + }; +}]; + +/* exported $AnimateCssProvider */ + +var ANIMATE_TIMER_KEY = '$$animateCss'; + +/** + * @ngdoc service + * @name $animateCss + * @kind object + * + * @description + * The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes + * from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT + * to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or + * directives to create more complex animations that can be purely driven using CSS code. + * + * Note that only browsers that support CSS transitions and/or keyframe animations are capable of + * rendering animations triggered via `$animateCss` (bad news for IE9 and lower). + * + * ## Usage + * Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that + * is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however, + * any automatic control over cancelling animations and/or preventing animations from being run on + * child elements will not be handled by Angular. For this to work as expected, please use `$animate` to + * trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger + * the CSS animation. + * + * The example below shows how we can create a folding animation on an element using `ng-if`: + * + * ```html + * + *
+ * This element will go BOOM + *
+ * + * ``` + * + * Now we create the **JavaScript animation** that will trigger the CSS transition: + * + * ```js + * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) { + * return { + * enter: function(element, doneFn) { + * var height = element[0].offsetHeight; + * return $animateCss(element, { + * from: { height:'0px' }, + * to: { height:height + 'px' }, + * duration: 1 // one second + * }); + * } + * } + * }]); + * ``` + * + * ## More Advanced Uses + * + * `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks + * like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code. + * + * This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation, + * applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with + * `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order + * to provide a working animation that will run in CSS. + * + * The example below showcases a more advanced version of the `.fold-animation` from the example above: + * + * ```js + * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) { + * return { + * enter: function(element, doneFn) { + * var height = element[0].offsetHeight; + * return $animateCss(element, { + * addClass: 'red large-text pulse-twice', + * easing: 'ease-out', + * from: { height:'0px' }, + * to: { height:height + 'px' }, + * duration: 1 // one second + * }); + * } + * } + * }]); + * ``` + * + * Since we're adding/removing CSS classes then the CSS transition will also pick those up: + * + * ```css + * /* since a hardcoded duration value of 1 was provided in the JavaScript animation code, + * the CSS classes below will be transitioned despite them being defined as regular CSS classes */ + * .red { background:red; } + * .large-text { font-size:20px; } + * + * /* we can also use a keyframe animation and $animateCss will make it work alongside the transition */ + * .pulse-twice { + * animation: 0.5s pulse linear 2; + * -webkit-animation: 0.5s pulse linear 2; + * } + * + * @keyframes pulse { + * from { transform: scale(0.5); } + * to { transform: scale(1.5); } + * } + * + * @-webkit-keyframes pulse { + * from { -webkit-transform: scale(0.5); } + * to { -webkit-transform: scale(1.5); } + * } + * ``` + * + * Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen. + * + * ## How the Options are handled + * + * `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation + * works with the options provided. Say for example we were adding a class that contained a keyframe value and we wanted to also animate some inline + * styles using the `from` and `to` properties. + * + * ```js + * var animator = $animateCss(element, { + * from: { background:'red' }, + * to: { background:'blue' } + * }); + * animator.start(); + * ``` + * + * ```css + * .rotating-animation { + * animation:0.5s rotate linear; + * -webkit-animation:0.5s rotate linear; + * } + * + * @keyframes rotate { + * from { transform: rotate(0deg); } + * to { transform: rotate(360deg); } + * } + * + * @-webkit-keyframes rotate { + * from { -webkit-transform: rotate(0deg); } + * to { -webkit-transform: rotate(360deg); } + * } + * ``` + * + * The missing pieces here are that we do not have a transition set (within the CSS code nor within the `$animateCss` options) and the duration of the animation is + * going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition + * style matching the duration detected from the keyframe style (which is present in the CSS class that is being added) and then prepare both the transition + * and keyframe animations to run in parallel on the element. Then when the animation is underway the provided `from` and `to` CSS styles will be applied + * and spread across the transition and keyframe animation. + * + * ## What is returned + * + * `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually + * start the animation. All that is going on here is that the element is being prepared for the animation (which means that the generated CSS classes are + * added and removed on the element). Once `$animateCss` is called it will return an object with the following properties: + * + * ```js + * var animator = $animateCss(element, { ... }); + * ``` + * + * Now what do the contents of our `animator` variable look like: + * + * ```js + * { + * // starts the animation + * start: Function, + * + * // ends (aborts) the animation + * end: Function + * } + * ``` + * + * To actually start the animation we need to run `animation.start()` which will then return a promise that we can hook into to detect when the animation ends. + * If we choose not to run the animation then we MUST run `animation.end()` to perform a cleanup on the element (since some CSS classes and styles may have been + * applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties + * and that changing them will not reconfigure the parameters of the animation. + * + * ### runner.done() vs runner.then() + * It is documented that `animation.start()` will return a promise object and this is true, however, there is also an additional method available on the + * runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**. + * Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()` + * unless you really need a digest to kick off afterwards. + * + * Keep in mind that, to make this easier, ngAnimate has tweaked the JS animations API to recognize when a runner instance is returned from $animateCss + * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code). + * Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works. + * + * @param {DOMElement} element the element that will be animated + * @param {object} options the animation-related options that will be applied during the animation + * + * * `event` - The DOM event (e.g. enter, leave, move). When used, a generated CSS class of `ng-EVENT` and `ng-EVENT-active` will be applied + * to the element during the animation. Multiple events can be provided when spaces are used as a separator. (Note that this will not perform any DOM operation.) + * * `structural` - Indicates that the `ng-` prefix will be added to the event class. Setting to `false` or omitting will turn `ng-EVENT` and + * `ng-EVENT-active` in `EVENT` and `EVENT-active`. Unused if `event` is omitted. + * * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both). + * * `transitionStyle` - The raw CSS transition style that will be used (e.g. `1s linear all`). + * * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`). + * * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation. + * * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition. + * * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation. + * * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation. + * * `duration` - A number value representing the total duration of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `0` + * is provided then the animation will be skipped entirely. + * * `delay` - A number value representing the total delay of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `true` is + * used then whatever delay value is detected from the CSS classes will be mirrored on the elements styles (e.g. by setting delay true then the style value + * of the element will be `transition-delay: DETECTED_VALUE`). Using `true` is useful when you want the CSS classes and inline styles to all share the same + * CSS delay value. + * * `stagger` - A numeric time value representing the delay between successively animated elements + * ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.}) + * * `staggerIndex` - The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item in the stagger; therefore when a + * `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`) + * * `applyClassesEarly` - Whether or not the classes being added or removed will be used when detecting the animation. This is set by `$animate` when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time. (Note that this will prevent any transitions from occurring on the classes being added and removed.) + * * `cleanupStyles` - Whether or not the provided `from` and `to` styles will be removed once + * the animation is closed. This is useful for when the styles are used purely for the sake of + * the animation and do not have a lasting visual effect on the element (e.g. a collapse and open animation). + * By default this value is set to `false`. + * + * @return {object} an object with start and end methods and details about the animation. + * + * * `start` - The method to start the animation. This will return a `Promise` when called. + * * `end` - This method will cancel the animation and remove all applied CSS classes and styles. + */ +var ONE_SECOND = 1000; + +var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3; +var CLOSING_TIME_BUFFER = 1.5; + +var DETECT_CSS_PROPERTIES = { + transitionDuration: TRANSITION_DURATION_PROP, + transitionDelay: TRANSITION_DELAY_PROP, + transitionProperty: TRANSITION_PROP + PROPERTY_KEY, + animationDuration: ANIMATION_DURATION_PROP, + animationDelay: ANIMATION_DELAY_PROP, + animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY +}; + +var DETECT_STAGGER_CSS_PROPERTIES = { + transitionDuration: TRANSITION_DURATION_PROP, + transitionDelay: TRANSITION_DELAY_PROP, + animationDuration: ANIMATION_DURATION_PROP, + animationDelay: ANIMATION_DELAY_PROP +}; + +function getCssKeyframeDurationStyle(duration) { + return [ANIMATION_DURATION_PROP, duration + 's']; +} + +function getCssDelayStyle(delay, isKeyframeAnimation) { + var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP; + return [prop, delay + 's']; +} + +function computeCssStyles($window, element, properties) { + var styles = Object.create(null); + var detectedStyles = $window.getComputedStyle(element) || {}; + forEach(properties, function(formalStyleName, actualStyleName) { + var val = detectedStyles[formalStyleName]; + if (val) { + var c = val.charAt(0); + + // only numerical-based values have a negative sign or digit as the first value + if (c === '-' || c === '+' || c >= 0) { + val = parseMaxTime(val); + } + + // by setting this to null in the event that the delay is not set or is set directly as 0 + // then we can still allow for negative values to be used later on and not mistake this + // value for being greater than any other negative value. + if (val === 0) { + val = null; + } + styles[actualStyleName] = val; + } + }); + + return styles; +} + +function parseMaxTime(str) { + var maxValue = 0; + var values = str.split(/\s*,\s*/); + forEach(values, function(value) { + // it's always safe to consider only second values and omit `ms` values since + // getComputedStyle will always handle the conversion for us + if (value.charAt(value.length - 1) === 's') { + value = value.substring(0, value.length - 1); + } + value = parseFloat(value) || 0; + maxValue = maxValue ? Math.max(value, maxValue) : value; + }); + return maxValue; +} + +function truthyTimingValue(val) { + return val === 0 || val != null; +} + +function getCssTransitionDurationStyle(duration, applyOnlyDuration) { + var style = TRANSITION_PROP; + var value = duration + 's'; + if (applyOnlyDuration) { + style += DURATION_KEY; + } else { + value += ' linear all'; + } + return [style, value]; +} + +function createLocalCacheLookup() { + var cache = Object.create(null); + return { + flush: function() { + cache = Object.create(null); + }, + + count: function(key) { + var entry = cache[key]; + return entry ? entry.total : 0; + }, + + get: function(key) { + var entry = cache[key]; + return entry && entry.value; + }, + + put: function(key, value) { + if (!cache[key]) { + cache[key] = { total: 1, value: value }; + } else { + cache[key].total++; + } + } + }; +} + +// we do not reassign an already present style value since +// if we detect the style property value again we may be +// detecting styles that were added via the `from` styles. +// We make use of `isDefined` here since an empty string +// or null value (which is what getPropertyValue will return +// for a non-existing style) will still be marked as a valid +// value for the style (a falsy value implies that the style +// is to be removed at the end of the animation). If we had a simple +// "OR" statement then it would not be enough to catch that. +function registerRestorableStyles(backup, node, properties) { + forEach(properties, function(prop) { + backup[prop] = isDefined(backup[prop]) + ? backup[prop] + : node.style.getPropertyValue(prop); + }); +} + +var $AnimateCssProvider = ['$animateProvider', /** @this */ function($animateProvider) { + var gcsLookup = createLocalCacheLookup(); + var gcsStaggerLookup = createLocalCacheLookup(); + + this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout', + '$$forceReflow', '$sniffer', '$$rAFScheduler', '$$animateQueue', + function($window, $$jqLite, $$AnimateRunner, $timeout, + $$forceReflow, $sniffer, $$rAFScheduler, $$animateQueue) { + + var applyAnimationClasses = applyAnimationClassesFactory($$jqLite); + + var parentCounter = 0; + function gcsHashFn(node, extraClasses) { + var KEY = '$$ngAnimateParentKey'; + var parentNode = node.parentNode; + var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter); + return parentID + '-' + node.getAttribute('class') + '-' + extraClasses; + } + + function computeCachedCssStyles(node, className, cacheKey, properties) { + var timings = gcsLookup.get(cacheKey); + + if (!timings) { + timings = computeCssStyles($window, node, properties); + if (timings.animationIterationCount === 'infinite') { + timings.animationIterationCount = 1; + } + } + + // we keep putting this in multiple times even though the value and the cacheKey are the same + // because we're keeping an internal tally of how many duplicate animations are detected. + gcsLookup.put(cacheKey, timings); + return timings; + } + + function computeCachedCssStaggerStyles(node, className, cacheKey, properties) { + var stagger; + + // if we have one or more existing matches of matching elements + // containing the same parent + CSS styles (which is how cacheKey works) + // then staggering is possible + if (gcsLookup.count(cacheKey) > 0) { + stagger = gcsStaggerLookup.get(cacheKey); + + if (!stagger) { + var staggerClassName = pendClasses(className, '-stagger'); + + $$jqLite.addClass(node, staggerClassName); + + stagger = computeCssStyles($window, node, properties); + + // force the conversion of a null value to zero incase not set + stagger.animationDuration = Math.max(stagger.animationDuration, 0); + stagger.transitionDuration = Math.max(stagger.transitionDuration, 0); + + $$jqLite.removeClass(node, staggerClassName); + + gcsStaggerLookup.put(cacheKey, stagger); + } + } + + return stagger || {}; + } + + var rafWaitQueue = []; + function waitUntilQuiet(callback) { + rafWaitQueue.push(callback); + $$rAFScheduler.waitUntilQuiet(function() { + gcsLookup.flush(); + gcsStaggerLookup.flush(); + + // DO NOT REMOVE THIS LINE OR REFACTOR OUT THE `pageWidth` variable. + // PLEASE EXAMINE THE `$$forceReflow` service to understand why. + var pageWidth = $$forceReflow(); + + // we use a for loop to ensure that if the queue is changed + // during this looping then it will consider new requests + for (var i = 0; i < rafWaitQueue.length; i++) { + rafWaitQueue[i](pageWidth); + } + rafWaitQueue.length = 0; + }); + } + + function computeTimings(node, className, cacheKey) { + var timings = computeCachedCssStyles(node, className, cacheKey, DETECT_CSS_PROPERTIES); + var aD = timings.animationDelay; + var tD = timings.transitionDelay; + timings.maxDelay = aD && tD + ? Math.max(aD, tD) + : (aD || tD); + timings.maxDuration = Math.max( + timings.animationDuration * timings.animationIterationCount, + timings.transitionDuration); + + return timings; + } + + return function init(element, initialOptions) { + // all of the animation functions should create + // a copy of the options data, however, if a + // parent service has already created a copy then + // we should stick to using that + var options = initialOptions || {}; + if (!options.$$prepared) { + options = prepareAnimationOptions(copy(options)); + } + + var restoreStyles = {}; + var node = getDomNode(element); + if (!node + || !node.parentNode + || !$$animateQueue.enabled()) { + return closeAndReturnNoopAnimator(); + } + + var temporaryStyles = []; + var classes = element.attr('class'); + var styles = packageStyles(options); + var animationClosed; + var animationPaused; + var animationCompleted; + var runner; + var runnerHost; + var maxDelay; + var maxDelayTime; + var maxDuration; + var maxDurationTime; + var startTime; + var events = []; + + if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) { + return closeAndReturnNoopAnimator(); + } + + var method = options.event && isArray(options.event) + ? options.event.join(' ') + : options.event; + + var isStructural = method && options.structural; + var structuralClassName = ''; + var addRemoveClassName = ''; + + if (isStructural) { + structuralClassName = pendClasses(method, EVENT_CLASS_PREFIX, true); + } else if (method) { + structuralClassName = method; + } + + if (options.addClass) { + addRemoveClassName += pendClasses(options.addClass, ADD_CLASS_SUFFIX); + } + + if (options.removeClass) { + if (addRemoveClassName.length) { + addRemoveClassName += ' '; + } + addRemoveClassName += pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX); + } + + // there may be a situation where a structural animation is combined together + // with CSS classes that need to resolve before the animation is computed. + // However this means that there is no explicit CSS code to block the animation + // from happening (by setting 0s none in the class name). If this is the case + // we need to apply the classes before the first rAF so we know to continue if + // there actually is a detected transition or keyframe animation + if (options.applyClassesEarly && addRemoveClassName.length) { + applyAnimationClasses(element, options); + } + + var preparationClasses = [structuralClassName, addRemoveClassName].join(' ').trim(); + var fullClassName = classes + ' ' + preparationClasses; + var activeClasses = pendClasses(preparationClasses, ACTIVE_CLASS_SUFFIX); + var hasToStyles = styles.to && Object.keys(styles.to).length > 0; + var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0; + + // there is no way we can trigger an animation if no styles and + // no classes are being applied which would then trigger a transition, + // unless there a is raw keyframe value that is applied to the element. + if (!containsKeyframeAnimation + && !hasToStyles + && !preparationClasses) { + return closeAndReturnNoopAnimator(); + } + + var cacheKey, stagger; + if (options.stagger > 0) { + var staggerVal = parseFloat(options.stagger); + stagger = { + transitionDelay: staggerVal, + animationDelay: staggerVal, + transitionDuration: 0, + animationDuration: 0 + }; + } else { + cacheKey = gcsHashFn(node, fullClassName); + stagger = computeCachedCssStaggerStyles(node, preparationClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES); + } + + if (!options.$$skipPreparationClasses) { + $$jqLite.addClass(element, preparationClasses); + } + + var applyOnlyDuration; + + if (options.transitionStyle) { + var transitionStyle = [TRANSITION_PROP, options.transitionStyle]; + applyInlineStyle(node, transitionStyle); + temporaryStyles.push(transitionStyle); + } + + if (options.duration >= 0) { + applyOnlyDuration = node.style[TRANSITION_PROP].length > 0; + var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration); + + // we set the duration so that it will be picked up by getComputedStyle later + applyInlineStyle(node, durationStyle); + temporaryStyles.push(durationStyle); + } + + if (options.keyframeStyle) { + var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle]; + applyInlineStyle(node, keyframeStyle); + temporaryStyles.push(keyframeStyle); + } + + var itemIndex = stagger + ? options.staggerIndex >= 0 + ? options.staggerIndex + : gcsLookup.count(cacheKey) + : 0; + + var isFirst = itemIndex === 0; + + // this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY + // without causing any combination of transitions to kick in. By adding a negative delay value + // it forces the setup class' transition to end immediately. We later then remove the negative + // transition delay to allow for the transition to naturally do it's thing. The beauty here is + // that if there is no transition defined then nothing will happen and this will also allow + // other transitions to be stacked on top of each other without any chopping them out. + if (isFirst && !options.skipBlocking) { + blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE); + } + + var timings = computeTimings(node, fullClassName, cacheKey); + var relativeDelay = timings.maxDelay; + maxDelay = Math.max(relativeDelay, 0); + maxDuration = timings.maxDuration; + + var flags = {}; + flags.hasTransitions = timings.transitionDuration > 0; + flags.hasAnimations = timings.animationDuration > 0; + flags.hasTransitionAll = flags.hasTransitions && timings.transitionProperty === 'all'; + flags.applyTransitionDuration = hasToStyles && ( + (flags.hasTransitions && !flags.hasTransitionAll) + || (flags.hasAnimations && !flags.hasTransitions)); + flags.applyAnimationDuration = options.duration && flags.hasAnimations; + flags.applyTransitionDelay = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions); + flags.applyAnimationDelay = truthyTimingValue(options.delay) && flags.hasAnimations; + flags.recalculateTimingStyles = addRemoveClassName.length > 0; + + if (flags.applyTransitionDuration || flags.applyAnimationDuration) { + maxDuration = options.duration ? parseFloat(options.duration) : maxDuration; + + if (flags.applyTransitionDuration) { + flags.hasTransitions = true; + timings.transitionDuration = maxDuration; + applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0; + temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration)); + } + + if (flags.applyAnimationDuration) { + flags.hasAnimations = true; + timings.animationDuration = maxDuration; + temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration)); + } + } + + if (maxDuration === 0 && !flags.recalculateTimingStyles) { + return closeAndReturnNoopAnimator(); + } + + if (options.delay != null) { + var delayStyle; + if (typeof options.delay !== 'boolean') { + delayStyle = parseFloat(options.delay); + // number in options.delay means we have to recalculate the delay for the closing timeout + maxDelay = Math.max(delayStyle, 0); + } + + if (flags.applyTransitionDelay) { + temporaryStyles.push(getCssDelayStyle(delayStyle)); + } + + if (flags.applyAnimationDelay) { + temporaryStyles.push(getCssDelayStyle(delayStyle, true)); + } + } + + // we need to recalculate the delay value since we used a pre-emptive negative + // delay value and the delay value is required for the final event checking. This + // property will ensure that this will happen after the RAF phase has passed. + if (options.duration == null && timings.transitionDuration > 0) { + flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst; + } + + maxDelayTime = maxDelay * ONE_SECOND; + maxDurationTime = maxDuration * ONE_SECOND; + if (!options.skipBlocking) { + flags.blockTransition = timings.transitionDuration > 0; + flags.blockKeyframeAnimation = timings.animationDuration > 0 && + stagger.animationDelay > 0 && + stagger.animationDuration === 0; + } + + if (options.from) { + if (options.cleanupStyles) { + registerRestorableStyles(restoreStyles, node, Object.keys(options.from)); + } + applyAnimationFromStyles(element, options); + } + + if (flags.blockTransition || flags.blockKeyframeAnimation) { + applyBlocking(maxDuration); + } else if (!options.skipBlocking) { + blockTransitions(node, false); + } + + // TODO(matsko): for 1.5 change this code to have an animator object for better debugging + return { + $$willAnimate: true, + end: endFn, + start: function() { + if (animationClosed) return; + + runnerHost = { + end: endFn, + cancel: cancelFn, + resume: null, //this will be set during the start() phase + pause: null + }; + + runner = new $$AnimateRunner(runnerHost); + + waitUntilQuiet(start); + + // we don't have access to pause/resume the animation + // since it hasn't run yet. AnimateRunner will therefore + // set noop functions for resume and pause and they will + // later be overridden once the animation is triggered + return runner; + } + }; + + function endFn() { + close(); + } + + function cancelFn() { + close(true); + } + + function close(rejected) { + // if the promise has been called already then we shouldn't close + // the animation again + if (animationClosed || (animationCompleted && animationPaused)) return; + animationClosed = true; + animationPaused = false; + + if (!options.$$skipPreparationClasses) { + $$jqLite.removeClass(element, preparationClasses); + } + $$jqLite.removeClass(element, activeClasses); + + blockKeyframeAnimations(node, false); + blockTransitions(node, false); + + forEach(temporaryStyles, function(entry) { + // There is only one way to remove inline style properties entirely from elements. + // By using `removeProperty` this works, but we need to convert camel-cased CSS + // styles down to hyphenated values. + node.style[entry[0]] = ''; + }); + + applyAnimationClasses(element, options); + applyAnimationStyles(element, options); + + if (Object.keys(restoreStyles).length) { + forEach(restoreStyles, function(value, prop) { + if (value) { + node.style.setProperty(prop, value); + } else { + node.style.removeProperty(prop); + } + }); + } + + // the reason why we have this option is to allow a synchronous closing callback + // that is fired as SOON as the animation ends (when the CSS is removed) or if + // the animation never takes off at all. A good example is a leave animation since + // the element must be removed just after the animation is over or else the element + // will appear on screen for one animation frame causing an overbearing flicker. + if (options.onDone) { + options.onDone(); + } + + if (events && events.length) { + // Remove the transitionend / animationend listener(s) + element.off(events.join(' '), onAnimationProgress); + } + + //Cancel the fallback closing timeout and remove the timer data + var animationTimerData = element.data(ANIMATE_TIMER_KEY); + if (animationTimerData) { + $timeout.cancel(animationTimerData[0].timer); + element.removeData(ANIMATE_TIMER_KEY); + } + + // if the preparation function fails then the promise is not setup + if (runner) { + runner.complete(!rejected); + } + } + + function applyBlocking(duration) { + if (flags.blockTransition) { + blockTransitions(node, duration); + } + + if (flags.blockKeyframeAnimation) { + blockKeyframeAnimations(node, !!duration); + } + } + + function closeAndReturnNoopAnimator() { + runner = new $$AnimateRunner({ + end: endFn, + cancel: cancelFn + }); + + // should flush the cache animation + waitUntilQuiet(noop); + close(); + + return { + $$willAnimate: false, + start: function() { + return runner; + }, + end: endFn + }; + } + + function onAnimationProgress(event) { + event.stopPropagation(); + var ev = event.originalEvent || event; + + // we now always use `Date.now()` due to the recent changes with + // event.timeStamp in Firefox, Webkit and Chrome (see #13494 for more info) + var timeStamp = ev.$manualTimeStamp || Date.now(); + + /* Firefox (or possibly just Gecko) likes to not round values up + * when a ms measurement is used for the animation */ + var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES)); + + /* $manualTimeStamp is a mocked timeStamp value which is set + * within browserTrigger(). This is only here so that tests can + * mock animations properly. Real events fallback to event.timeStamp, + * or, if they don't, then a timeStamp is automatically created for them. + * We're checking to see if the timeStamp surpasses the expected delay, + * but we're using elapsedTime instead of the timeStamp on the 2nd + * pre-condition since animationPauseds sometimes close off early */ + if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) { + // we set this flag to ensure that if the transition is paused then, when resumed, + // the animation will automatically close itself since transitions cannot be paused. + animationCompleted = true; + close(); + } + } + + function start() { + if (animationClosed) return; + if (!node.parentNode) { + close(); + return; + } + + // even though we only pause keyframe animations here the pause flag + // will still happen when transitions are used. Only the transition will + // not be paused since that is not possible. If the animation ends when + // paused then it will not complete until unpaused or cancelled. + var playPause = function(playAnimation) { + if (!animationCompleted) { + animationPaused = !playAnimation; + if (timings.animationDuration) { + var value = blockKeyframeAnimations(node, animationPaused); + if (animationPaused) { + temporaryStyles.push(value); + } else { + removeFromArray(temporaryStyles, value); + } + } + } else if (animationPaused && playAnimation) { + animationPaused = false; + close(); + } + }; + + // checking the stagger duration prevents an accidentally cascade of the CSS delay style + // being inherited from the parent. If the transition duration is zero then we can safely + // rely that the delay value is an intentional stagger delay style. + var maxStagger = itemIndex > 0 + && ((timings.transitionDuration && stagger.transitionDuration === 0) || + (timings.animationDuration && stagger.animationDuration === 0)) + && Math.max(stagger.animationDelay, stagger.transitionDelay); + if (maxStagger) { + $timeout(triggerAnimationStart, + Math.floor(maxStagger * itemIndex * ONE_SECOND), + false); + } else { + triggerAnimationStart(); + } + + // this will decorate the existing promise runner with pause/resume methods + runnerHost.resume = function() { + playPause(true); + }; + + runnerHost.pause = function() { + playPause(false); + }; + + function triggerAnimationStart() { + // just incase a stagger animation kicks in when the animation + // itself was cancelled entirely + if (animationClosed) return; + + applyBlocking(false); + + forEach(temporaryStyles, function(entry) { + var key = entry[0]; + var value = entry[1]; + node.style[key] = value; + }); + + applyAnimationClasses(element, options); + $$jqLite.addClass(element, activeClasses); + + if (flags.recalculateTimingStyles) { + fullClassName = node.className + ' ' + preparationClasses; + cacheKey = gcsHashFn(node, fullClassName); + + timings = computeTimings(node, fullClassName, cacheKey); + relativeDelay = timings.maxDelay; + maxDelay = Math.max(relativeDelay, 0); + maxDuration = timings.maxDuration; + + if (maxDuration === 0) { + close(); + return; + } + + flags.hasTransitions = timings.transitionDuration > 0; + flags.hasAnimations = timings.animationDuration > 0; + } + + if (flags.applyAnimationDelay) { + relativeDelay = typeof options.delay !== 'boolean' && truthyTimingValue(options.delay) + ? parseFloat(options.delay) + : relativeDelay; + + maxDelay = Math.max(relativeDelay, 0); + timings.animationDelay = relativeDelay; + delayStyle = getCssDelayStyle(relativeDelay, true); + temporaryStyles.push(delayStyle); + node.style[delayStyle[0]] = delayStyle[1]; + } + + maxDelayTime = maxDelay * ONE_SECOND; + maxDurationTime = maxDuration * ONE_SECOND; + + if (options.easing) { + var easeProp, easeVal = options.easing; + if (flags.hasTransitions) { + easeProp = TRANSITION_PROP + TIMING_KEY; + temporaryStyles.push([easeProp, easeVal]); + node.style[easeProp] = easeVal; + } + if (flags.hasAnimations) { + easeProp = ANIMATION_PROP + TIMING_KEY; + temporaryStyles.push([easeProp, easeVal]); + node.style[easeProp] = easeVal; + } + } + + if (timings.transitionDuration) { + events.push(TRANSITIONEND_EVENT); + } + + if (timings.animationDuration) { + events.push(ANIMATIONEND_EVENT); + } + + startTime = Date.now(); + var timerTime = maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime; + var endTime = startTime + timerTime; + + var animationsData = element.data(ANIMATE_TIMER_KEY) || []; + var setupFallbackTimer = true; + if (animationsData.length) { + var currentTimerData = animationsData[0]; + setupFallbackTimer = endTime > currentTimerData.expectedEndTime; + if (setupFallbackTimer) { + $timeout.cancel(currentTimerData.timer); + } else { + animationsData.push(close); + } + } + + if (setupFallbackTimer) { + var timer = $timeout(onAnimationExpired, timerTime, false); + animationsData[0] = { + timer: timer, + expectedEndTime: endTime + }; + animationsData.push(close); + element.data(ANIMATE_TIMER_KEY, animationsData); + } + + if (events.length) { + element.on(events.join(' '), onAnimationProgress); + } + + if (options.to) { + if (options.cleanupStyles) { + registerRestorableStyles(restoreStyles, node, Object.keys(options.to)); + } + applyAnimationToStyles(element, options); + } + } + + function onAnimationExpired() { + var animationsData = element.data(ANIMATE_TIMER_KEY); + + // this will be false in the event that the element was + // removed from the DOM (via a leave animation or something + // similar) + if (animationsData) { + for (var i = 1; i < animationsData.length; i++) { + animationsData[i](); + } + element.removeData(ANIMATE_TIMER_KEY); + } + } + } + }; + }]; +}]; + +var $$AnimateCssDriverProvider = ['$$animationProvider', /** @this */ function($$animationProvider) { + $$animationProvider.drivers.push('$$animateCssDriver'); + + var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim'; + var NG_ANIMATE_ANCHOR_CLASS_NAME = 'ng-anchor'; + + var NG_OUT_ANCHOR_CLASS_NAME = 'ng-anchor-out'; + var NG_IN_ANCHOR_CLASS_NAME = 'ng-anchor-in'; + + function isDocumentFragment(node) { + return node.parentNode && node.parentNode.nodeType === 11; + } + + this.$get = ['$animateCss', '$rootScope', '$$AnimateRunner', '$rootElement', '$sniffer', '$$jqLite', '$document', + function($animateCss, $rootScope, $$AnimateRunner, $rootElement, $sniffer, $$jqLite, $document) { + + // only browsers that support these properties can render animations + if (!$sniffer.animations && !$sniffer.transitions) return noop; + + var bodyNode = $document[0].body; + var rootNode = getDomNode($rootElement); + + var rootBodyElement = jqLite( + // this is to avoid using something that exists outside of the body + // we also special case the doc fragment case because our unit test code + // appends the $rootElement to the body after the app has been bootstrapped + isDocumentFragment(rootNode) || bodyNode.contains(rootNode) ? rootNode : bodyNode + ); + + return function initDriverFn(animationDetails) { + return animationDetails.from && animationDetails.to + ? prepareFromToAnchorAnimation(animationDetails.from, + animationDetails.to, + animationDetails.classes, + animationDetails.anchors) + : prepareRegularAnimation(animationDetails); + }; + + function filterCssClasses(classes) { + //remove all the `ng-` stuff + return classes.replace(/\bng-\S+\b/g, ''); + } + + function getUniqueValues(a, b) { + if (isString(a)) a = a.split(' '); + if (isString(b)) b = b.split(' '); + return a.filter(function(val) { + return b.indexOf(val) === -1; + }).join(' '); + } + + function prepareAnchoredAnimation(classes, outAnchor, inAnchor) { + var clone = jqLite(getDomNode(outAnchor).cloneNode(true)); + var startingClasses = filterCssClasses(getClassVal(clone)); + + outAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME); + inAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME); + + clone.addClass(NG_ANIMATE_ANCHOR_CLASS_NAME); + + rootBodyElement.append(clone); + + var animatorIn, animatorOut = prepareOutAnimation(); + + // the user may not end up using the `out` animation and + // only making use of the `in` animation or vice-versa. + // In either case we should allow this and not assume the + // animation is over unless both animations are not used. + if (!animatorOut) { + animatorIn = prepareInAnimation(); + if (!animatorIn) { + return end(); + } + } + + var startingAnimator = animatorOut || animatorIn; + + return { + start: function() { + var runner; + + var currentAnimation = startingAnimator.start(); + currentAnimation.done(function() { + currentAnimation = null; + if (!animatorIn) { + animatorIn = prepareInAnimation(); + if (animatorIn) { + currentAnimation = animatorIn.start(); + currentAnimation.done(function() { + currentAnimation = null; + end(); + runner.complete(); + }); + return currentAnimation; + } + } + // in the event that there is no `in` animation + end(); + runner.complete(); + }); + + runner = new $$AnimateRunner({ + end: endFn, + cancel: endFn + }); + + return runner; + + function endFn() { + if (currentAnimation) { + currentAnimation.end(); + } + } + } + }; + + function calculateAnchorStyles(anchor) { + var styles = {}; + + var coords = getDomNode(anchor).getBoundingClientRect(); + + // we iterate directly since safari messes up and doesn't return + // all the keys for the coords object when iterated + forEach(['width','height','top','left'], function(key) { + var value = coords[key]; + switch (key) { + case 'top': + value += bodyNode.scrollTop; + break; + case 'left': + value += bodyNode.scrollLeft; + break; + } + styles[key] = Math.floor(value) + 'px'; + }); + return styles; + } + + function prepareOutAnimation() { + var animator = $animateCss(clone, { + addClass: NG_OUT_ANCHOR_CLASS_NAME, + delay: true, + from: calculateAnchorStyles(outAnchor) + }); + + // read the comment within `prepareRegularAnimation` to understand + // why this check is necessary + return animator.$$willAnimate ? animator : null; + } + + function getClassVal(element) { + return element.attr('class') || ''; + } + + function prepareInAnimation() { + var endingClasses = filterCssClasses(getClassVal(inAnchor)); + var toAdd = getUniqueValues(endingClasses, startingClasses); + var toRemove = getUniqueValues(startingClasses, endingClasses); + + var animator = $animateCss(clone, { + to: calculateAnchorStyles(inAnchor), + addClass: NG_IN_ANCHOR_CLASS_NAME + ' ' + toAdd, + removeClass: NG_OUT_ANCHOR_CLASS_NAME + ' ' + toRemove, + delay: true + }); + + // read the comment within `prepareRegularAnimation` to understand + // why this check is necessary + return animator.$$willAnimate ? animator : null; + } + + function end() { + clone.remove(); + outAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME); + inAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME); + } + } + + function prepareFromToAnchorAnimation(from, to, classes, anchors) { + var fromAnimation = prepareRegularAnimation(from, noop); + var toAnimation = prepareRegularAnimation(to, noop); + + var anchorAnimations = []; + forEach(anchors, function(anchor) { + var outElement = anchor['out']; + var inElement = anchor['in']; + var animator = prepareAnchoredAnimation(classes, outElement, inElement); + if (animator) { + anchorAnimations.push(animator); + } + }); + + // no point in doing anything when there are no elements to animate + if (!fromAnimation && !toAnimation && anchorAnimations.length === 0) return; + + return { + start: function() { + var animationRunners = []; + + if (fromAnimation) { + animationRunners.push(fromAnimation.start()); + } + + if (toAnimation) { + animationRunners.push(toAnimation.start()); + } + + forEach(anchorAnimations, function(animation) { + animationRunners.push(animation.start()); + }); + + var runner = new $$AnimateRunner({ + end: endFn, + cancel: endFn // CSS-driven animations cannot be cancelled, only ended + }); + + $$AnimateRunner.all(animationRunners, function(status) { + runner.complete(status); + }); + + return runner; + + function endFn() { + forEach(animationRunners, function(runner) { + runner.end(); + }); + } + } + }; + } + + function prepareRegularAnimation(animationDetails) { + var element = animationDetails.element; + var options = animationDetails.options || {}; + + if (animationDetails.structural) { + options.event = animationDetails.event; + options.structural = true; + options.applyClassesEarly = true; + + // we special case the leave animation since we want to ensure that + // the element is removed as soon as the animation is over. Otherwise + // a flicker might appear or the element may not be removed at all + if (animationDetails.event === 'leave') { + options.onDone = options.domOperation; + } + } + + // We assign the preparationClasses as the actual animation event since + // the internals of $animateCss will just suffix the event token values + // with `-active` to trigger the animation. + if (options.preparationClasses) { + options.event = concatWithSpace(options.event, options.preparationClasses); + } + + var animator = $animateCss(element, options); + + // the driver lookup code inside of $$animation attempts to spawn a + // driver one by one until a driver returns a.$$willAnimate animator object. + // $animateCss will always return an object, however, it will pass in + // a flag as a hint as to whether an animation was detected or not + return animator.$$willAnimate ? animator : null; + } + }]; +}]; + +// TODO(matsko): use caching here to speed things up for detection +// TODO(matsko): add documentation +// by the time... + +var $$AnimateJsProvider = ['$animateProvider', /** @this */ function($animateProvider) { + this.$get = ['$injector', '$$AnimateRunner', '$$jqLite', + function($injector, $$AnimateRunner, $$jqLite) { + + var applyAnimationClasses = applyAnimationClassesFactory($$jqLite); + // $animateJs(element, 'enter'); + return function(element, event, classes, options) { + var animationClosed = false; + + // the `classes` argument is optional and if it is not used + // then the classes will be resolved from the element's className + // property as well as options.addClass/options.removeClass. + if (arguments.length === 3 && isObject(classes)) { + options = classes; + classes = null; + } + + options = prepareAnimationOptions(options); + if (!classes) { + classes = element.attr('class') || ''; + if (options.addClass) { + classes += ' ' + options.addClass; + } + if (options.removeClass) { + classes += ' ' + options.removeClass; + } + } + + var classesToAdd = options.addClass; + var classesToRemove = options.removeClass; + + // the lookupAnimations function returns a series of animation objects that are + // matched up with one or more of the CSS classes. These animation objects are + // defined via the module.animation factory function. If nothing is detected then + // we don't return anything which then makes $animation query the next driver. + var animations = lookupAnimations(classes); + var before, after; + if (animations.length) { + var afterFn, beforeFn; + if (event === 'leave') { + beforeFn = 'leave'; + afterFn = 'afterLeave'; // TODO(matsko): get rid of this + } else { + beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1); + afterFn = event; + } + + if (event !== 'enter' && event !== 'move') { + before = packageAnimations(element, event, options, animations, beforeFn); + } + after = packageAnimations(element, event, options, animations, afterFn); + } + + // no matching animations + if (!before && !after) return; + + function applyOptions() { + options.domOperation(); + applyAnimationClasses(element, options); + } + + function close() { + animationClosed = true; + applyOptions(); + applyAnimationStyles(element, options); + } + + var runner; + + return { + $$willAnimate: true, + end: function() { + if (runner) { + runner.end(); + } else { + close(); + runner = new $$AnimateRunner(); + runner.complete(true); + } + return runner; + }, + start: function() { + if (runner) { + return runner; + } + + runner = new $$AnimateRunner(); + var closeActiveAnimations; + var chain = []; + + if (before) { + chain.push(function(fn) { + closeActiveAnimations = before(fn); + }); + } + + if (chain.length) { + chain.push(function(fn) { + applyOptions(); + fn(true); + }); + } else { + applyOptions(); + } + + if (after) { + chain.push(function(fn) { + closeActiveAnimations = after(fn); + }); + } + + runner.setHost({ + end: function() { + endAnimations(); + }, + cancel: function() { + endAnimations(true); + } + }); + + $$AnimateRunner.chain(chain, onComplete); + return runner; + + function onComplete(success) { + close(success); + runner.complete(success); + } + + function endAnimations(cancelled) { + if (!animationClosed) { + (closeActiveAnimations || noop)(cancelled); + onComplete(cancelled); + } + } + } + }; + + function executeAnimationFn(fn, element, event, options, onDone) { + var args; + switch (event) { + case 'animate': + args = [element, options.from, options.to, onDone]; + break; + + case 'setClass': + args = [element, classesToAdd, classesToRemove, onDone]; + break; + + case 'addClass': + args = [element, classesToAdd, onDone]; + break; + + case 'removeClass': + args = [element, classesToRemove, onDone]; + break; + + default: + args = [element, onDone]; + break; + } + + args.push(options); + + var value = fn.apply(fn, args); + if (value) { + if (isFunction(value.start)) { + value = value.start(); + } + + if (value instanceof $$AnimateRunner) { + value.done(onDone); + } else if (isFunction(value)) { + // optional onEnd / onCancel callback + return value; + } + } + + return noop; + } + + function groupEventedAnimations(element, event, options, animations, fnName) { + var operations = []; + forEach(animations, function(ani) { + var animation = ani[fnName]; + if (!animation) return; + + // note that all of these animations will run in parallel + operations.push(function() { + var runner; + var endProgressCb; + + var resolved = false; + var onAnimationComplete = function(rejected) { + if (!resolved) { + resolved = true; + (endProgressCb || noop)(rejected); + runner.complete(!rejected); + } + }; + + runner = new $$AnimateRunner({ + end: function() { + onAnimationComplete(); + }, + cancel: function() { + onAnimationComplete(true); + } + }); + + endProgressCb = executeAnimationFn(animation, element, event, options, function(result) { + var cancelled = result === false; + onAnimationComplete(cancelled); + }); + + return runner; + }); + }); + + return operations; + } + + function packageAnimations(element, event, options, animations, fnName) { + var operations = groupEventedAnimations(element, event, options, animations, fnName); + if (operations.length === 0) { + var a, b; + if (fnName === 'beforeSetClass') { + a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass'); + b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass'); + } else if (fnName === 'setClass') { + a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass'); + b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass'); + } + + if (a) { + operations = operations.concat(a); + } + if (b) { + operations = operations.concat(b); + } + } + + if (operations.length === 0) return; + + // TODO(matsko): add documentation + return function startAnimation(callback) { + var runners = []; + if (operations.length) { + forEach(operations, function(animateFn) { + runners.push(animateFn()); + }); + } + + if (runners.length) { + $$AnimateRunner.all(runners, callback); + } else { + callback(); + } + + return function endFn(reject) { + forEach(runners, function(runner) { + if (reject) { + runner.cancel(); + } else { + runner.end(); + } + }); + }; + }; + } + }; + + function lookupAnimations(classes) { + classes = isArray(classes) ? classes : classes.split(' '); + var matches = [], flagMap = {}; + for (var i = 0; i < classes.length; i++) { + var klass = classes[i], + animationFactory = $animateProvider.$$registeredAnimations[klass]; + if (animationFactory && !flagMap[klass]) { + matches.push($injector.get(animationFactory)); + flagMap[klass] = true; + } + } + return matches; + } + }]; +}]; + +var $$AnimateJsDriverProvider = ['$$animationProvider', /** @this */ function($$animationProvider) { + $$animationProvider.drivers.push('$$animateJsDriver'); + this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) { + return function initDriverFn(animationDetails) { + if (animationDetails.from && animationDetails.to) { + var fromAnimation = prepareAnimation(animationDetails.from); + var toAnimation = prepareAnimation(animationDetails.to); + if (!fromAnimation && !toAnimation) return; + + return { + start: function() { + var animationRunners = []; + + if (fromAnimation) { + animationRunners.push(fromAnimation.start()); + } + + if (toAnimation) { + animationRunners.push(toAnimation.start()); + } + + $$AnimateRunner.all(animationRunners, done); + + var runner = new $$AnimateRunner({ + end: endFnFactory(), + cancel: endFnFactory() + }); + + return runner; + + function endFnFactory() { + return function() { + forEach(animationRunners, function(runner) { + // at this point we cannot cancel animations for groups just yet. 1.5+ + runner.end(); + }); + }; + } + + function done(status) { + runner.complete(status); + } + } + }; + } else { + return prepareAnimation(animationDetails); + } + }; + + function prepareAnimation(animationDetails) { + // TODO(matsko): make sure to check for grouped animations and delegate down to normal animations + var element = animationDetails.element; + var event = animationDetails.event; + var options = animationDetails.options; + var classes = animationDetails.classes; + return $$animateJs(element, event, classes, options); + } + }]; +}]; + +var NG_ANIMATE_ATTR_NAME = 'data-ng-animate'; +var NG_ANIMATE_PIN_DATA = '$ngAnimatePin'; +var $$AnimateQueueProvider = ['$animateProvider', /** @this */ function($animateProvider) { + var PRE_DIGEST_STATE = 1; + var RUNNING_STATE = 2; + var ONE_SPACE = ' '; + + var rules = this.rules = { + skip: [], + cancel: [], + join: [] + }; + + function makeTruthyCssClassMap(classString) { + if (!classString) { + return null; + } + + var keys = classString.split(ONE_SPACE); + var map = Object.create(null); + + forEach(keys, function(key) { + map[key] = true; + }); + return map; + } + + function hasMatchingClasses(newClassString, currentClassString) { + if (newClassString && currentClassString) { + var currentClassMap = makeTruthyCssClassMap(currentClassString); + return newClassString.split(ONE_SPACE).some(function(className) { + return currentClassMap[className]; + }); + } + } + + function isAllowed(ruleType, element, currentAnimation, previousAnimation) { + return rules[ruleType].some(function(fn) { + return fn(element, currentAnimation, previousAnimation); + }); + } + + function hasAnimationClasses(animation, and) { + var a = (animation.addClass || '').length > 0; + var b = (animation.removeClass || '').length > 0; + return and ? a && b : a || b; + } + + rules.join.push(function(element, newAnimation, currentAnimation) { + // if the new animation is class-based then we can just tack that on + return !newAnimation.structural && hasAnimationClasses(newAnimation); + }); + + rules.skip.push(function(element, newAnimation, currentAnimation) { + // there is no need to animate anything if no classes are being added and + // there is no structural animation that will be triggered + return !newAnimation.structural && !hasAnimationClasses(newAnimation); + }); + + rules.skip.push(function(element, newAnimation, currentAnimation) { + // why should we trigger a new structural animation if the element will + // be removed from the DOM anyway? + return currentAnimation.event === 'leave' && newAnimation.structural; + }); + + rules.skip.push(function(element, newAnimation, currentAnimation) { + // if there is an ongoing current animation then don't even bother running the class-based animation + return currentAnimation.structural && currentAnimation.state === RUNNING_STATE && !newAnimation.structural; + }); + + rules.cancel.push(function(element, newAnimation, currentAnimation) { + // there can never be two structural animations running at the same time + return currentAnimation.structural && newAnimation.structural; + }); + + rules.cancel.push(function(element, newAnimation, currentAnimation) { + // if the previous animation is already running, but the new animation will + // be triggered, but the new animation is structural + return currentAnimation.state === RUNNING_STATE && newAnimation.structural; + }); + + rules.cancel.push(function(element, newAnimation, currentAnimation) { + // cancel the animation if classes added / removed in both animation cancel each other out, + // but only if the current animation isn't structural + + if (currentAnimation.structural) return false; + + var nA = newAnimation.addClass; + var nR = newAnimation.removeClass; + var cA = currentAnimation.addClass; + var cR = currentAnimation.removeClass; + + // early detection to save the global CPU shortage :) + if ((isUndefined(nA) && isUndefined(nR)) || (isUndefined(cA) && isUndefined(cR))) { + return false; + } + + return hasMatchingClasses(nA, cR) || hasMatchingClasses(nR, cA); + }); + + this.$get = ['$$rAF', '$rootScope', '$rootElement', '$document', '$$HashMap', + '$$animation', '$$AnimateRunner', '$templateRequest', '$$jqLite', '$$forceReflow', + function($$rAF, $rootScope, $rootElement, $document, $$HashMap, + $$animation, $$AnimateRunner, $templateRequest, $$jqLite, $$forceReflow) { + + var activeAnimationsLookup = new $$HashMap(); + var disabledElementsLookup = new $$HashMap(); + var animationsEnabled = null; + + function postDigestTaskFactory() { + var postDigestCalled = false; + return function(fn) { + // we only issue a call to postDigest before + // it has first passed. This prevents any callbacks + // from not firing once the animation has completed + // since it will be out of the digest cycle. + if (postDigestCalled) { + fn(); + } else { + $rootScope.$$postDigest(function() { + postDigestCalled = true; + fn(); + }); + } + }; + } + + // Wait until all directive and route-related templates are downloaded and + // compiled. The $templateRequest.totalPendingRequests variable keeps track of + // all of the remote templates being currently downloaded. If there are no + // templates currently downloading then the watcher will still fire anyway. + var deregisterWatch = $rootScope.$watch( + function() { return $templateRequest.totalPendingRequests === 0; }, + function(isEmpty) { + if (!isEmpty) return; + deregisterWatch(); + + // Now that all templates have been downloaded, $animate will wait until + // the post digest queue is empty before enabling animations. By having two + // calls to $postDigest calls we can ensure that the flag is enabled at the + // very end of the post digest queue. Since all of the animations in $animate + // use $postDigest, it's important that the code below executes at the end. + // This basically means that the page is fully downloaded and compiled before + // any animations are triggered. + $rootScope.$$postDigest(function() { + $rootScope.$$postDigest(function() { + // we check for null directly in the event that the application already called + // .enabled() with whatever arguments that it provided it with + if (animationsEnabled === null) { + animationsEnabled = true; + } + }); + }); + } + ); + + var callbackRegistry = Object.create(null); + + // remember that the classNameFilter is set during the provider/config + // stage therefore we can optimize here and setup a helper function + var classNameFilter = $animateProvider.classNameFilter(); + var isAnimatableClassName = !classNameFilter + ? function() { return true; } + : function(className) { + return classNameFilter.test(className); + }; + + var applyAnimationClasses = applyAnimationClassesFactory($$jqLite); + + function normalizeAnimationDetails(element, animation) { + return mergeAnimationDetails(element, animation, {}); + } + + // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259. + var contains = window.Node.prototype.contains || /** @this */ function(arg) { + // eslint-disable-next-line no-bitwise + return this === arg || !!(this.compareDocumentPosition(arg) & 16); + }; + + function findCallbacks(parent, element, event) { + var targetNode = getDomNode(element); + var targetParentNode = getDomNode(parent); + + var matches = []; + var entries = callbackRegistry[event]; + if (entries) { + forEach(entries, function(entry) { + if (contains.call(entry.node, targetNode)) { + matches.push(entry.callback); + } else if (event === 'leave' && contains.call(entry.node, targetParentNode)) { + matches.push(entry.callback); + } + }); + } + + return matches; + } + + function filterFromRegistry(list, matchContainer, matchCallback) { + var containerNode = extractElementNode(matchContainer); + return list.filter(function(entry) { + var isMatch = entry.node === containerNode && + (!matchCallback || entry.callback === matchCallback); + return !isMatch; + }); + } + + function cleanupEventListeners(phase, element) { + if (phase === 'close' && !element[0].parentNode) { + // If the element is not attached to a parentNode, it has been removed by + // the domOperation, and we can safely remove the event callbacks + $animate.off(element); + } + } + + var $animate = { + on: function(event, container, callback) { + var node = extractElementNode(container); + callbackRegistry[event] = callbackRegistry[event] || []; + callbackRegistry[event].push({ + node: node, + callback: callback + }); + + // Remove the callback when the element is removed from the DOM + jqLite(container).on('$destroy', function() { + var animationDetails = activeAnimationsLookup.get(node); + + if (!animationDetails) { + // If there's an animation ongoing, the callback calling code will remove + // the event listeners. If we'd remove here, the callbacks would be removed + // before the animation ends + $animate.off(event, container, callback); + } + }); + }, + + off: function(event, container, callback) { + if (arguments.length === 1 && !isString(arguments[0])) { + container = arguments[0]; + for (var eventType in callbackRegistry) { + callbackRegistry[eventType] = filterFromRegistry(callbackRegistry[eventType], container); + } + + return; + } + + var entries = callbackRegistry[event]; + if (!entries) return; + + callbackRegistry[event] = arguments.length === 1 + ? null + : filterFromRegistry(entries, container, callback); + }, + + pin: function(element, parentElement) { + assertArg(isElement(element), 'element', 'not an element'); + assertArg(isElement(parentElement), 'parentElement', 'not an element'); + element.data(NG_ANIMATE_PIN_DATA, parentElement); + }, + + push: function(element, event, options, domOperation) { + options = options || {}; + options.domOperation = domOperation; + return queueAnimation(element, event, options); + }, + + // this method has four signatures: + // () - global getter + // (bool) - global setter + // (element) - element getter + // (element, bool) - element setter + enabled: function(element, bool) { + var argCount = arguments.length; + + if (argCount === 0) { + // () - Global getter + bool = !!animationsEnabled; + } else { + var hasElement = isElement(element); + + if (!hasElement) { + // (bool) - Global setter + bool = animationsEnabled = !!element; + } else { + var node = getDomNode(element); + + if (argCount === 1) { + // (element) - Element getter + bool = !disabledElementsLookup.get(node); + } else { + // (element, bool) - Element setter + disabledElementsLookup.put(node, !bool); + } + } + } + + return bool; + } + }; + + return $animate; + + function queueAnimation(element, event, initialOptions) { + // we always make a copy of the options since + // there should never be any side effects on + // the input data when running `$animateCss`. + var options = copy(initialOptions); + + var node, parent; + element = stripCommentsFromElement(element); + if (element) { + node = getDomNode(element); + parent = element.parent(); + } + + options = prepareAnimationOptions(options); + + // we create a fake runner with a working promise. + // These methods will become available after the digest has passed + var runner = new $$AnimateRunner(); + + // this is used to trigger callbacks in postDigest mode + var runInNextPostDigestOrNow = postDigestTaskFactory(); + + if (isArray(options.addClass)) { + options.addClass = options.addClass.join(' '); + } + + if (options.addClass && !isString(options.addClass)) { + options.addClass = null; + } + + if (isArray(options.removeClass)) { + options.removeClass = options.removeClass.join(' '); + } + + if (options.removeClass && !isString(options.removeClass)) { + options.removeClass = null; + } + + if (options.from && !isObject(options.from)) { + options.from = null; + } + + if (options.to && !isObject(options.to)) { + options.to = null; + } + + // there are situations where a directive issues an animation for + // a jqLite wrapper that contains only comment nodes... If this + // happens then there is no way we can perform an animation + if (!node) { + close(); + return runner; + } + + var className = [node.className, options.addClass, options.removeClass].join(' '); + if (!isAnimatableClassName(className)) { + close(); + return runner; + } + + var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0; + + var documentHidden = $document[0].hidden; + + // this is a hard disable of all animations for the application or on + // the element itself, therefore there is no need to continue further + // past this point if not enabled + // Animations are also disabled if the document is currently hidden (page is not visible + // to the user), because browsers slow down or do not flush calls to requestAnimationFrame + var skipAnimations = !animationsEnabled || documentHidden || disabledElementsLookup.get(node); + var existingAnimation = (!skipAnimations && activeAnimationsLookup.get(node)) || {}; + var hasExistingAnimation = !!existingAnimation.state; + + // there is no point in traversing the same collection of parent ancestors if a followup + // animation will be run on the same element that already did all that checking work + if (!skipAnimations && (!hasExistingAnimation || existingAnimation.state !== PRE_DIGEST_STATE)) { + skipAnimations = !areAnimationsAllowed(element, parent, event); + } + + if (skipAnimations) { + // Callbacks should fire even if the document is hidden (regression fix for issue #14120) + if (documentHidden) notifyProgress(runner, event, 'start'); + close(); + if (documentHidden) notifyProgress(runner, event, 'close'); + return runner; + } + + if (isStructural) { + closeChildAnimations(element); + } + + var newAnimation = { + structural: isStructural, + element: element, + event: event, + addClass: options.addClass, + removeClass: options.removeClass, + close: close, + options: options, + runner: runner + }; + + if (hasExistingAnimation) { + var skipAnimationFlag = isAllowed('skip', element, newAnimation, existingAnimation); + if (skipAnimationFlag) { + if (existingAnimation.state === RUNNING_STATE) { + close(); + return runner; + } else { + mergeAnimationDetails(element, existingAnimation, newAnimation); + return existingAnimation.runner; + } + } + var cancelAnimationFlag = isAllowed('cancel', element, newAnimation, existingAnimation); + if (cancelAnimationFlag) { + if (existingAnimation.state === RUNNING_STATE) { + // this will end the animation right away and it is safe + // to do so since the animation is already running and the + // runner callback code will run in async + existingAnimation.runner.end(); + } else if (existingAnimation.structural) { + // this means that the animation is queued into a digest, but + // hasn't started yet. Therefore it is safe to run the close + // method which will call the runner methods in async. + existingAnimation.close(); + } else { + // this will merge the new animation options into existing animation options + mergeAnimationDetails(element, existingAnimation, newAnimation); + + return existingAnimation.runner; + } + } else { + // a joined animation means that this animation will take over the existing one + // so an example would involve a leave animation taking over an enter. Then when + // the postDigest kicks in the enter will be ignored. + var joinAnimationFlag = isAllowed('join', element, newAnimation, existingAnimation); + if (joinAnimationFlag) { + if (existingAnimation.state === RUNNING_STATE) { + normalizeAnimationDetails(element, newAnimation); + } else { + applyGeneratedPreparationClasses(element, isStructural ? event : null, options); + + event = newAnimation.event = existingAnimation.event; + options = mergeAnimationDetails(element, existingAnimation, newAnimation); + + //we return the same runner since only the option values of this animation will + //be fed into the `existingAnimation`. + return existingAnimation.runner; + } + } + } + } else { + // normalization in this case means that it removes redundant CSS classes that + // already exist (addClass) or do not exist (removeClass) on the element + normalizeAnimationDetails(element, newAnimation); + } + + // when the options are merged and cleaned up we may end up not having to do + // an animation at all, therefore we should check this before issuing a post + // digest callback. Structural animations will always run no matter what. + var isValidAnimation = newAnimation.structural; + if (!isValidAnimation) { + // animate (from/to) can be quickly checked first, otherwise we check if any classes are present + isValidAnimation = (newAnimation.event === 'animate' && Object.keys(newAnimation.options.to || {}).length > 0) + || hasAnimationClasses(newAnimation); + } + + if (!isValidAnimation) { + close(); + clearElementAnimationState(element); + return runner; + } + + // the counter keeps track of cancelled animations + var counter = (existingAnimation.counter || 0) + 1; + newAnimation.counter = counter; + + markElementAnimationState(element, PRE_DIGEST_STATE, newAnimation); + + $rootScope.$$postDigest(function() { + var animationDetails = activeAnimationsLookup.get(node); + var animationCancelled = !animationDetails; + animationDetails = animationDetails || {}; + + // if addClass/removeClass is called before something like enter then the + // registered parent element may not be present. The code below will ensure + // that a final value for parent element is obtained + var parentElement = element.parent() || []; + + // animate/structural/class-based animations all have requirements. Otherwise there + // is no point in performing an animation. The parent node must also be set. + var isValidAnimation = parentElement.length > 0 + && (animationDetails.event === 'animate' + || animationDetails.structural + || hasAnimationClasses(animationDetails)); + + // this means that the previous animation was cancelled + // even if the follow-up animation is the same event + if (animationCancelled || animationDetails.counter !== counter || !isValidAnimation) { + // if another animation did not take over then we need + // to make sure that the domOperation and options are + // handled accordingly + if (animationCancelled) { + applyAnimationClasses(element, options); + applyAnimationStyles(element, options); + } + + // if the event changed from something like enter to leave then we do + // it, otherwise if it's the same then the end result will be the same too + if (animationCancelled || (isStructural && animationDetails.event !== event)) { + options.domOperation(); + runner.end(); + } + + // in the event that the element animation was not cancelled or a follow-up animation + // isn't allowed to animate from here then we need to clear the state of the element + // so that any future animations won't read the expired animation data. + if (!isValidAnimation) { + clearElementAnimationState(element); + } + + return; + } + + // this combined multiple class to addClass / removeClass into a setClass event + // so long as a structural event did not take over the animation + event = !animationDetails.structural && hasAnimationClasses(animationDetails, true) + ? 'setClass' + : animationDetails.event; + + markElementAnimationState(element, RUNNING_STATE); + var realRunner = $$animation(element, event, animationDetails.options); + + // this will update the runner's flow-control events based on + // the `realRunner` object. + runner.setHost(realRunner); + notifyProgress(runner, event, 'start', {}); + + realRunner.done(function(status) { + close(!status); + var animationDetails = activeAnimationsLookup.get(node); + if (animationDetails && animationDetails.counter === counter) { + clearElementAnimationState(getDomNode(element)); + } + notifyProgress(runner, event, 'close', {}); + }); + }); + + return runner; + + function notifyProgress(runner, event, phase, data) { + runInNextPostDigestOrNow(function() { + var callbacks = findCallbacks(parent, element, event); + if (callbacks.length) { + // do not optimize this call here to RAF because + // we don't know how heavy the callback code here will + // be and if this code is buffered then this can + // lead to a performance regression. + $$rAF(function() { + forEach(callbacks, function(callback) { + callback(element, phase, data); + }); + cleanupEventListeners(phase, element); + }); + } else { + cleanupEventListeners(phase, element); + } + }); + runner.progress(event, phase, data); + } + + function close(reject) { + clearGeneratedClasses(element, options); + applyAnimationClasses(element, options); + applyAnimationStyles(element, options); + options.domOperation(); + runner.complete(!reject); + } + } + + function closeChildAnimations(element) { + var node = getDomNode(element); + var children = node.querySelectorAll('[' + NG_ANIMATE_ATTR_NAME + ']'); + forEach(children, function(child) { + var state = parseInt(child.getAttribute(NG_ANIMATE_ATTR_NAME), 10); + var animationDetails = activeAnimationsLookup.get(child); + if (animationDetails) { + switch (state) { + case RUNNING_STATE: + animationDetails.runner.end(); + /* falls through */ + case PRE_DIGEST_STATE: + activeAnimationsLookup.remove(child); + break; + } + } + }); + } + + function clearElementAnimationState(element) { + var node = getDomNode(element); + node.removeAttribute(NG_ANIMATE_ATTR_NAME); + activeAnimationsLookup.remove(node); + } + + function isMatchingElement(nodeOrElmA, nodeOrElmB) { + return getDomNode(nodeOrElmA) === getDomNode(nodeOrElmB); + } + + /** + * This fn returns false if any of the following is true: + * a) animations on any parent element are disabled, and animations on the element aren't explicitly allowed + * b) a parent element has an ongoing structural animation, and animateChildren is false + * c) the element is not a child of the body + * d) the element is not a child of the $rootElement + */ + function areAnimationsAllowed(element, parentElement, event) { + var bodyElement = jqLite($document[0].body); + var bodyElementDetected = isMatchingElement(element, bodyElement) || element[0].nodeName === 'HTML'; + var rootElementDetected = isMatchingElement(element, $rootElement); + var parentAnimationDetected = false; + var animateChildren; + var elementDisabled = disabledElementsLookup.get(getDomNode(element)); + + var parentHost = jqLite.data(element[0], NG_ANIMATE_PIN_DATA); + if (parentHost) { + parentElement = parentHost; + } + + parentElement = getDomNode(parentElement); + + while (parentElement) { + if (!rootElementDetected) { + // angular doesn't want to attempt to animate elements outside of the application + // therefore we need to ensure that the rootElement is an ancestor of the current element + rootElementDetected = isMatchingElement(parentElement, $rootElement); + } + + if (parentElement.nodeType !== ELEMENT_NODE) { + // no point in inspecting the #document element + break; + } + + var details = activeAnimationsLookup.get(parentElement) || {}; + // either an enter, leave or move animation will commence + // therefore we can't allow any animations to take place + // but if a parent animation is class-based then that's ok + if (!parentAnimationDetected) { + var parentElementDisabled = disabledElementsLookup.get(parentElement); + + if (parentElementDisabled === true && elementDisabled !== false) { + // disable animations if the user hasn't explicitly enabled animations on the + // current element + elementDisabled = true; + // element is disabled via parent element, no need to check anything else + break; + } else if (parentElementDisabled === false) { + elementDisabled = false; + } + parentAnimationDetected = details.structural; + } + + if (isUndefined(animateChildren) || animateChildren === true) { + var value = jqLite.data(parentElement, NG_ANIMATE_CHILDREN_DATA); + if (isDefined(value)) { + animateChildren = value; + } + } + + // there is no need to continue traversing at this point + if (parentAnimationDetected && animateChildren === false) break; + + if (!bodyElementDetected) { + // we also need to ensure that the element is or will be a part of the body element + // otherwise it is pointless to even issue an animation to be rendered + bodyElementDetected = isMatchingElement(parentElement, bodyElement); + } + + if (bodyElementDetected && rootElementDetected) { + // If both body and root have been found, any other checks are pointless, + // as no animation data should live outside the application + break; + } + + if (!rootElementDetected) { + // If no rootElement is detected, check if the parentElement is pinned to another element + parentHost = jqLite.data(parentElement, NG_ANIMATE_PIN_DATA); + if (parentHost) { + // The pin target element becomes the next parent element + parentElement = getDomNode(parentHost); + continue; + } + } + + parentElement = parentElement.parentNode; + } + + var allowAnimation = (!parentAnimationDetected || animateChildren) && elementDisabled !== true; + return allowAnimation && rootElementDetected && bodyElementDetected; + } + + function markElementAnimationState(element, state, details) { + details = details || {}; + details.state = state; + + var node = getDomNode(element); + node.setAttribute(NG_ANIMATE_ATTR_NAME, state); + + var oldValue = activeAnimationsLookup.get(node); + var newValue = oldValue + ? extend(oldValue, details) + : details; + activeAnimationsLookup.put(node, newValue); + } + }]; +}]; + +/* exported $$AnimationProvider */ + +var $$AnimationProvider = ['$animateProvider', /** @this */ function($animateProvider) { + var NG_ANIMATE_REF_ATTR = 'ng-animate-ref'; + + var drivers = this.drivers = []; + + var RUNNER_STORAGE_KEY = '$$animationRunner'; + + function setRunner(element, runner) { + element.data(RUNNER_STORAGE_KEY, runner); + } + + function removeRunner(element) { + element.removeData(RUNNER_STORAGE_KEY); + } + + function getRunner(element) { + return element.data(RUNNER_STORAGE_KEY); + } + + this.$get = ['$$jqLite', '$rootScope', '$injector', '$$AnimateRunner', '$$HashMap', '$$rAFScheduler', + function($$jqLite, $rootScope, $injector, $$AnimateRunner, $$HashMap, $$rAFScheduler) { + + var animationQueue = []; + var applyAnimationClasses = applyAnimationClassesFactory($$jqLite); + + function sortAnimations(animations) { + var tree = { children: [] }; + var i, lookup = new $$HashMap(); + + // this is done first beforehand so that the hashmap + // is filled with a list of the elements that will be animated + for (i = 0; i < animations.length; i++) { + var animation = animations[i]; + lookup.put(animation.domNode, animations[i] = { + domNode: animation.domNode, + fn: animation.fn, + children: [] + }); + } + + for (i = 0; i < animations.length; i++) { + processNode(animations[i]); + } + + return flatten(tree); + + function processNode(entry) { + if (entry.processed) return entry; + entry.processed = true; + + var elementNode = entry.domNode; + var parentNode = elementNode.parentNode; + lookup.put(elementNode, entry); + + var parentEntry; + while (parentNode) { + parentEntry = lookup.get(parentNode); + if (parentEntry) { + if (!parentEntry.processed) { + parentEntry = processNode(parentEntry); + } + break; + } + parentNode = parentNode.parentNode; + } + + (parentEntry || tree).children.push(entry); + return entry; + } + + function flatten(tree) { + var result = []; + var queue = []; + var i; + + for (i = 0; i < tree.children.length; i++) { + queue.push(tree.children[i]); + } + + var remainingLevelEntries = queue.length; + var nextLevelEntries = 0; + var row = []; + + for (i = 0; i < queue.length; i++) { + var entry = queue[i]; + if (remainingLevelEntries <= 0) { + remainingLevelEntries = nextLevelEntries; + nextLevelEntries = 0; + result.push(row); + row = []; + } + row.push(entry.fn); + entry.children.forEach(function(childEntry) { + nextLevelEntries++; + queue.push(childEntry); + }); + remainingLevelEntries--; + } + + if (row.length) { + result.push(row); + } + + return result; + } + } + + // TODO(matsko): document the signature in a better way + return function(element, event, options) { + options = prepareAnimationOptions(options); + var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0; + + // there is no animation at the current moment, however + // these runner methods will get later updated with the + // methods leading into the driver's end/cancel methods + // for now they just stop the animation from starting + var runner = new $$AnimateRunner({ + end: function() { close(); }, + cancel: function() { close(true); } + }); + + if (!drivers.length) { + close(); + return runner; + } + + setRunner(element, runner); + + var classes = mergeClasses(element.attr('class'), mergeClasses(options.addClass, options.removeClass)); + var tempClasses = options.tempClasses; + if (tempClasses) { + classes += ' ' + tempClasses; + options.tempClasses = null; + } + + var prepareClassName; + if (isStructural) { + prepareClassName = 'ng-' + event + PREPARE_CLASS_SUFFIX; + $$jqLite.addClass(element, prepareClassName); + } + + animationQueue.push({ + // this data is used by the postDigest code and passed into + // the driver step function + element: element, + classes: classes, + event: event, + structural: isStructural, + options: options, + beforeStart: beforeStart, + close: close + }); + + element.on('$destroy', handleDestroyedElement); + + // we only want there to be one function called within the post digest + // block. This way we can group animations for all the animations that + // were apart of the same postDigest flush call. + if (animationQueue.length > 1) return runner; + + $rootScope.$$postDigest(function() { + var animations = []; + forEach(animationQueue, function(entry) { + // the element was destroyed early on which removed the runner + // form its storage. This means we can't animate this element + // at all and it already has been closed due to destruction. + if (getRunner(entry.element)) { + animations.push(entry); + } else { + entry.close(); + } + }); + + // now any future animations will be in another postDigest + animationQueue.length = 0; + + var groupedAnimations = groupAnimations(animations); + var toBeSortedAnimations = []; + + forEach(groupedAnimations, function(animationEntry) { + toBeSortedAnimations.push({ + domNode: getDomNode(animationEntry.from ? animationEntry.from.element : animationEntry.element), + fn: function triggerAnimationStart() { + // it's important that we apply the `ng-animate` CSS class and the + // temporary classes before we do any driver invoking since these + // CSS classes may be required for proper CSS detection. + animationEntry.beforeStart(); + + var startAnimationFn, closeFn = animationEntry.close; + + // in the event that the element was removed before the digest runs or + // during the RAF sequencing then we should not trigger the animation. + var targetElement = animationEntry.anchors + ? (animationEntry.from.element || animationEntry.to.element) + : animationEntry.element; + + if (getRunner(targetElement)) { + var operation = invokeFirstDriver(animationEntry); + if (operation) { + startAnimationFn = operation.start; + } + } + + if (!startAnimationFn) { + closeFn(); + } else { + var animationRunner = startAnimationFn(); + animationRunner.done(function(status) { + closeFn(!status); + }); + updateAnimationRunners(animationEntry, animationRunner); + } + } + }); + }); + + // we need to sort each of the animations in order of parent to child + // relationships. This ensures that the child classes are applied at the + // right time. + $$rAFScheduler(sortAnimations(toBeSortedAnimations)); + }); + + return runner; + + // TODO(matsko): change to reference nodes + function getAnchorNodes(node) { + var SELECTOR = '[' + NG_ANIMATE_REF_ATTR + ']'; + var items = node.hasAttribute(NG_ANIMATE_REF_ATTR) + ? [node] + : node.querySelectorAll(SELECTOR); + var anchors = []; + forEach(items, function(node) { + var attr = node.getAttribute(NG_ANIMATE_REF_ATTR); + if (attr && attr.length) { + anchors.push(node); + } + }); + return anchors; + } + + function groupAnimations(animations) { + var preparedAnimations = []; + var refLookup = {}; + forEach(animations, function(animation, index) { + var element = animation.element; + var node = getDomNode(element); + var event = animation.event; + var enterOrMove = ['enter', 'move'].indexOf(event) >= 0; + var anchorNodes = animation.structural ? getAnchorNodes(node) : []; + + if (anchorNodes.length) { + var direction = enterOrMove ? 'to' : 'from'; + + forEach(anchorNodes, function(anchor) { + var key = anchor.getAttribute(NG_ANIMATE_REF_ATTR); + refLookup[key] = refLookup[key] || {}; + refLookup[key][direction] = { + animationID: index, + element: jqLite(anchor) + }; + }); + } else { + preparedAnimations.push(animation); + } + }); + + var usedIndicesLookup = {}; + var anchorGroups = {}; + forEach(refLookup, function(operations, key) { + var from = operations.from; + var to = operations.to; + + if (!from || !to) { + // only one of these is set therefore we can't have an + // anchor animation since all three pieces are required + var index = from ? from.animationID : to.animationID; + var indexKey = index.toString(); + if (!usedIndicesLookup[indexKey]) { + usedIndicesLookup[indexKey] = true; + preparedAnimations.push(animations[index]); + } + return; + } + + var fromAnimation = animations[from.animationID]; + var toAnimation = animations[to.animationID]; + var lookupKey = from.animationID.toString(); + if (!anchorGroups[lookupKey]) { + var group = anchorGroups[lookupKey] = { + structural: true, + beforeStart: function() { + fromAnimation.beforeStart(); + toAnimation.beforeStart(); + }, + close: function() { + fromAnimation.close(); + toAnimation.close(); + }, + classes: cssClassesIntersection(fromAnimation.classes, toAnimation.classes), + from: fromAnimation, + to: toAnimation, + anchors: [] // TODO(matsko): change to reference nodes + }; + + // the anchor animations require that the from and to elements both have at least + // one shared CSS class which effectively marries the two elements together to use + // the same animation driver and to properly sequence the anchor animation. + if (group.classes.length) { + preparedAnimations.push(group); + } else { + preparedAnimations.push(fromAnimation); + preparedAnimations.push(toAnimation); + } + } + + anchorGroups[lookupKey].anchors.push({ + 'out': from.element, 'in': to.element + }); + }); + + return preparedAnimations; + } + + function cssClassesIntersection(a,b) { + a = a.split(' '); + b = b.split(' '); + var matches = []; + + for (var i = 0; i < a.length; i++) { + var aa = a[i]; + if (aa.substring(0,3) === 'ng-') continue; + + for (var j = 0; j < b.length; j++) { + if (aa === b[j]) { + matches.push(aa); + break; + } + } + } + + return matches.join(' '); + } + + function invokeFirstDriver(animationDetails) { + // we loop in reverse order since the more general drivers (like CSS and JS) + // may attempt more elements, but custom drivers are more particular + for (var i = drivers.length - 1; i >= 0; i--) { + var driverName = drivers[i]; + var factory = $injector.get(driverName); + var driver = factory(animationDetails); + if (driver) { + return driver; + } + } + } + + function beforeStart() { + element.addClass(NG_ANIMATE_CLASSNAME); + if (tempClasses) { + $$jqLite.addClass(element, tempClasses); + } + if (prepareClassName) { + $$jqLite.removeClass(element, prepareClassName); + prepareClassName = null; + } + } + + function updateAnimationRunners(animation, newRunner) { + if (animation.from && animation.to) { + update(animation.from.element); + update(animation.to.element); + } else { + update(animation.element); + } + + function update(element) { + var runner = getRunner(element); + if (runner) runner.setHost(newRunner); + } + } + + function handleDestroyedElement() { + var runner = getRunner(element); + if (runner && (event !== 'leave' || !options.$$domOperationFired)) { + runner.end(); + } + } + + function close(rejected) { + element.off('$destroy', handleDestroyedElement); + removeRunner(element); + + applyAnimationClasses(element, options); + applyAnimationStyles(element, options); + options.domOperation(); + + if (tempClasses) { + $$jqLite.removeClass(element, tempClasses); + } + + element.removeClass(NG_ANIMATE_CLASSNAME); + runner.complete(!rejected); + } + }; + }]; +}]; + +/** + * @ngdoc directive + * @name ngAnimateSwap + * @restrict A + * @scope + * + * @description + * + * ngAnimateSwap is a animation-oriented directive that allows for the container to + * be removed and entered in whenever the associated expression changes. A + * common usecase for this directive is a rotating banner or slider component which + * contains one image being present at a time. When the active image changes + * then the old image will perform a `leave` animation and the new element + * will be inserted via an `enter` animation. + * + * @animations + * | Animation | Occurs | + * |----------------------------------|--------------------------------------| + * | {@link ng.$animate#enter enter} | when the new element is inserted to the DOM | + * | {@link ng.$animate#leave leave} | when the old element is removed from the DOM | + * + * @example + * + * + *
+ *
+ * {{ number }} + *
+ *
+ *
+ * + * angular.module('ngAnimateSwapExample', ['ngAnimate']) + * .controller('AppCtrl', ['$scope', '$interval', function($scope, $interval) { + * $scope.number = 0; + * $interval(function() { + * $scope.number++; + * }, 1000); + * + * var colors = ['red','blue','green','yellow','orange']; + * $scope.colorClass = function(number) { + * return colors[number % colors.length]; + * }; + * }]); + * + * + * .container { + * height:250px; + * width:250px; + * position:relative; + * overflow:hidden; + * border:2px solid black; + * } + * .container .cell { + * font-size:150px; + * text-align:center; + * line-height:250px; + * position:absolute; + * top:0; + * left:0; + * right:0; + * border-bottom:2px solid black; + * } + * .swap-animation.ng-enter, .swap-animation.ng-leave { + * transition:0.5s linear all; + * } + * .swap-animation.ng-enter { + * top:-250px; + * } + * .swap-animation.ng-enter-active { + * top:0px; + * } + * .swap-animation.ng-leave { + * top:0px; + * } + * .swap-animation.ng-leave-active { + * top:250px; + * } + * .red { background:red; } + * .green { background:green; } + * .blue { background:blue; } + * .yellow { background:yellow; } + * .orange { background:orange; } + * + *
+ */ +var ngAnimateSwapDirective = ['$animate', '$rootScope', function($animate, $rootScope) { + return { + restrict: 'A', + transclude: 'element', + terminal: true, + priority: 600, // we use 600 here to ensure that the directive is caught before others + link: function(scope, $element, attrs, ctrl, $transclude) { + var previousElement, previousScope; + scope.$watchCollection(attrs.ngAnimateSwap || attrs['for'], function(value) { + if (previousElement) { + $animate.leave(previousElement); + } + if (previousScope) { + previousScope.$destroy(); + previousScope = null; + } + if (value || value === 0) { + previousScope = scope.$new(); + $transclude(previousScope, function(element) { + previousElement = element; + $animate.enter(element, null, $element); + }); + } + }); + } + }; +}]; + +/** + * @ngdoc module + * @name ngAnimate + * @description + * + * The `ngAnimate` module provides support for CSS-based animations (keyframes and transitions) as well as JavaScript-based animations via + * callback hooks. Animations are not enabled by default, however, by including `ngAnimate` the animation hooks are enabled for an Angular app. + * + *
+ * + * # Usage + * Simply put, there are two ways to make use of animations when ngAnimate is used: by using **CSS** and **JavaScript**. The former works purely based + * using CSS (by using matching CSS selectors/styles) and the latter triggers animations that are registered via `module.animation()`. For + * both CSS and JS animations the sole requirement is to have a matching `CSS class` that exists both in the registered animation and within + * the HTML element that the animation will be triggered on. + * + * ## Directive Support + * The following directives are "animation aware": + * + * | Directive | Supported Animations | + * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------| + * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move | + * | {@link ngRoute.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:ngClass#animations ngClass} | add and remove (the CSS class(es) present) | + * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide} | add and remove (the ng-hide class value) | + * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) | + * | {@link module:ngMessages#animations ngMessages} | add and remove (ng-active & ng-inactive) | + * | {@link module:ngMessages#animations ngMessage} | enter and leave | + * + * (More information can be found by visiting each the documentation associated with each directive.) + * + * ## CSS-based Animations + * + * CSS-based animations with ngAnimate are unique since they require no JavaScript code at all. By using a CSS class that we reference between our HTML + * and CSS code we can create an animation that will be picked up by Angular when an underlying directive performs an operation. + * + * The example below shows how an `enter` animation can be made possible on an element using `ng-if`: + * + * ```html + *
+ * Fade me in out + *
+ * + * + * ``` + * + * Notice the CSS class **fade**? We can now create the CSS transition code that references this class: + * + * ```css + * /* The starting CSS styles for the enter animation */ + * .fade.ng-enter { + * transition:0.5s linear all; + * opacity:0; + * } + * + * /* The finishing CSS styles for the enter animation */ + * .fade.ng-enter.ng-enter-active { + * opacity:1; + * } + * ``` + * + * The key thing to remember here is that, depending on the animation event (which each of the directives above trigger depending on what's going on) two + * generated CSS classes will be applied to the element; in the example above we have `.ng-enter` and `.ng-enter-active`. For CSS transitions, the transition + * code **must** be defined within the starting CSS class (in this case `.ng-enter`). The destination class is what the transition will animate towards. + * + * If for example we wanted to create animations for `leave` and `move` (ngRepeat triggers move) then we can do so using the same CSS naming conventions: + * + * ```css + * /* now the element will fade out before it is removed from the DOM */ + * .fade.ng-leave { + * transition:0.5s linear all; + * opacity:1; + * } + * .fade.ng-leave.ng-leave-active { + * opacity:0; + * } + * ``` + * + * We can also make use of **CSS Keyframes** by referencing the keyframe animation within the starting CSS class: + * + * ```css + * /* there is no need to define anything inside of the destination + * CSS class since the keyframe will take charge of the animation */ + * .fade.ng-leave { + * animation: my_fade_animation 0.5s linear; + * -webkit-animation: my_fade_animation 0.5s linear; + * } + * + * @keyframes my_fade_animation { + * from { opacity:1; } + * to { opacity:0; } + * } + * + * @-webkit-keyframes my_fade_animation { + * from { opacity:1; } + * to { opacity:0; } + * } + * ``` + * + * Feel free also mix transitions and keyframes together as well as any other CSS classes on the same element. + * + * ### CSS Class-based Animations + * + * Class-based animations (animations that are triggered via `ngClass`, `ngShow`, `ngHide` and some other directives) have a slightly different + * naming convention. Class-based animations are basic enough that a standard transition or keyframe can be referenced on the class being added + * and removed. + * + * For example if we wanted to do a CSS animation for `ngHide` then we place an animation on the `.ng-hide` CSS class: + * + * ```html + *
+ * Show and hide me + *
+ * + * + * + * ``` + * + * All that is going on here with ngShow/ngHide behind the scenes is the `.ng-hide` class is added/removed (when the hidden state is valid). Since + * ngShow and ngHide are animation aware then we can match up a transition and ngAnimate handles the rest. + * + * In addition the addition and removal of the CSS class, ngAnimate also provides two helper methods that we can use to further decorate the animation + * with CSS styles. + * + * ```html + *
+ * Highlight this box + *
+ * + * + * + * ``` + * + * We can also make use of CSS keyframes by placing them within the CSS classes. + * + * + * ### CSS Staggering Animations + * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a + * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be + * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for + * the animation. The style property expected within the stagger class can either be a **transition-delay** or an + * **animation-delay** property (or both if your animation contains both transitions and keyframe animations). + * + * ```css + * .my-animation.ng-enter { + * /* standard transition code */ + * transition: 1s linear all; + * opacity:0; + * } + * .my-animation.ng-enter-stagger { + * /* this will have a 100ms delay between each successive leave animation */ + * transition-delay: 0.1s; + * + * /* As of 1.4.4, this must always be set: it signals ngAnimate + * to not accidentally inherit a delay property from another CSS class */ + * transition-duration: 0s; + * } + * .my-animation.ng-enter.ng-enter-active { + * /* standard transition styles */ + * opacity:1; + * } + * ``` + * + * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations + * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this + * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation + * will also be reset if one or more animation frames have passed since the multiple calls to `$animate` were fired. + * + * The following code will issue the **ng-leave-stagger** event on the element provided: + * + * ```js + * var kids = parent.children(); + * + * $animate.leave(kids[0]); //stagger index=0 + * $animate.leave(kids[1]); //stagger index=1 + * $animate.leave(kids[2]); //stagger index=2 + * $animate.leave(kids[3]); //stagger index=3 + * $animate.leave(kids[4]); //stagger index=4 + * + * window.requestAnimationFrame(function() { + * //stagger has reset itself + * $animate.leave(kids[5]); //stagger index=0 + * $animate.leave(kids[6]); //stagger index=1 + * + * $scope.$digest(); + * }); + * ``` + * + * Stagger animations are currently only supported within CSS-defined animations. + * + * ### The `ng-animate` CSS class + * + * When ngAnimate is animating an element it will apply the `ng-animate` CSS class to the element for the duration of the animation. + * This is a temporary CSS class and it will be removed once the animation is over (for both JavaScript and CSS-based animations). + * + * Therefore, animations can be applied to an element using this temporary class directly via CSS. + * + * ```css + * .zipper.ng-animate { + * transition:0.5s linear all; + * } + * .zipper.ng-enter { + * opacity:0; + * } + * .zipper.ng-enter.ng-enter-active { + * opacity:1; + * } + * .zipper.ng-leave { + * opacity:1; + * } + * .zipper.ng-leave.ng-leave-active { + * opacity:0; + * } + * ``` + * + * (Note that the `ng-animate` CSS class is reserved and it cannot be applied on an element directly since ngAnimate will always remove + * the CSS class once an animation has completed.) + * + * + * ### The `ng-[event]-prepare` class + * + * This is a special class that can be used to prevent unwanted flickering / flash of content before + * the actual animation starts. The class is added as soon as an animation is initialized, but removed + * before the actual animation starts (after waiting for a $digest). + * It is also only added for *structural* animations (`enter`, `move`, and `leave`). + * + * In practice, flickering can appear when nesting elements with structural animations such as `ngIf` + * into elements that have class-based animations such as `ngClass`. + * + * ```html + *
+ *
+ *
+ *
+ *
+ * ``` + * + * It is possible that during the `enter` animation, the `.message` div will be briefly visible before it starts animating. + * In that case, you can add styles to the CSS that make sure the element stays hidden before the animation starts: + * + * ```css + * .message.ng-enter-prepare { + * opacity: 0; + * } + * + * ``` + * + * ## JavaScript-based Animations + * + * ngAnimate also allows for animations to be consumed by JavaScript code. The approach is similar to CSS-based animations (where there is a shared + * CSS class that is referenced in our HTML code) but in addition we need to register the JavaScript animation on the module. By making use of the + * `module.animation()` module function we can register the animation. + * + * Let's see an example of a enter/leave animation using `ngRepeat`: + * + * ```html + *
+ * {{ item }} + *
+ * ``` + * + * See the **slide** CSS class? Let's use that class to define an animation that we'll structure in our module code by using `module.animation`: + * + * ```js + * myModule.animation('.slide', [function() { + * return { + * // make note that other events (like addClass/removeClass) + * // have different function input parameters + * enter: function(element, doneFn) { + * jQuery(element).fadeIn(1000, doneFn); + * + * // remember to call doneFn so that angular + * // knows that the animation has concluded + * }, + * + * move: function(element, doneFn) { + * jQuery(element).fadeIn(1000, doneFn); + * }, + * + * leave: function(element, doneFn) { + * jQuery(element).fadeOut(1000, doneFn); + * } + * } + * }]); + * ``` + * + * The nice thing about JS-based animations is that we can inject other services and make use of advanced animation libraries such as + * greensock.js and velocity.js. + * + * If our animation code class-based (meaning that something like `ngClass`, `ngHide` and `ngShow` triggers it) then we can still define + * our animations inside of the same registered animation, however, the function input arguments are a bit different: + * + * ```html + *
+ * this box is moody + *
+ * + * + * + * ``` + * + * ```js + * myModule.animation('.colorful', [function() { + * return { + * addClass: function(element, className, doneFn) { + * // do some cool animation and call the doneFn + * }, + * removeClass: function(element, className, doneFn) { + * // do some cool animation and call the doneFn + * }, + * setClass: function(element, addedClass, removedClass, doneFn) { + * // do some cool animation and call the doneFn + * } + * } + * }]); + * ``` + * + * ## CSS + JS Animations Together + * + * AngularJS 1.4 and higher has taken steps to make the amalgamation of CSS and JS animations more flexible. However, unlike earlier versions of Angular, + * defining CSS and JS animations to work off of the same CSS class will not work anymore. Therefore the example below will only result in **JS animations taking + * charge of the animation**: + * + * ```html + *
+ * Slide in and out + *
+ * ``` + * + * ```js + * myModule.animation('.slide', [function() { + * return { + * enter: function(element, doneFn) { + * jQuery(element).slideIn(1000, doneFn); + * } + * } + * }]); + * ``` + * + * ```css + * .slide.ng-enter { + * transition:0.5s linear all; + * transform:translateY(-100px); + * } + * .slide.ng-enter.ng-enter-active { + * transform:translateY(0); + * } + * ``` + * + * Does this mean that CSS and JS animations cannot be used together? Do JS-based animations always have higher priority? We can make up for the + * lack of CSS animations by using the `$animateCss` service to trigger our own tweaked-out, CSS-based animations directly from + * our own JS-based animation code: + * + * ```js + * myModule.animation('.slide', ['$animateCss', function($animateCss) { + * return { + * enter: function(element) { +* // this will trigger `.slide.ng-enter` and `.slide.ng-enter-active`. + * return $animateCss(element, { + * event: 'enter', + * structural: true + * }); + * } + * } + * }]); + * ``` + * + * The nice thing here is that we can save bandwidth by sticking to our CSS-based animation code and we don't need to rely on a 3rd-party animation framework. + * + * The `$animateCss` service is very powerful since we can feed in all kinds of extra properties that will be evaluated and fed into a CSS transition or + * keyframe animation. For example if we wanted to animate the height of an element while adding and removing classes then we can do so by providing that + * data into `$animateCss` directly: + * + * ```js + * myModule.animation('.slide', ['$animateCss', function($animateCss) { + * return { + * enter: function(element) { + * return $animateCss(element, { + * event: 'enter', + * structural: true, + * addClass: 'maroon-setting', + * from: { height:0 }, + * to: { height: 200 } + * }); + * } + * } + * }]); + * ``` + * + * Now we can fill in the rest via our transition CSS code: + * + * ```css + * /* the transition tells ngAnimate to make the animation happen */ + * .slide.ng-enter { transition:0.5s linear all; } + * + * /* this extra CSS class will be absorbed into the transition + * since the $animateCss code is adding the class */ + * .maroon-setting { background:red; } + * ``` + * + * And `$animateCss` will figure out the rest. Just make sure to have the `done()` callback fire the `doneFn` function to signal when the animation is over. + * + * To learn more about what's possible be sure to visit the {@link ngAnimate.$animateCss $animateCss service}. + * + * ## Animation Anchoring (via `ng-animate-ref`) + * + * ngAnimate in AngularJS 1.4 comes packed with the ability to cross-animate elements between + * structural areas of an application (like views) by pairing up elements using an attribute + * called `ng-animate-ref`. + * + * Let's say for example we have two views that are managed by `ng-view` and we want to show + * that there is a relationship between two components situated in within these views. By using the + * `ng-animate-ref` attribute we can identify that the two components are paired together and we + * can then attach an animation, which is triggered when the view changes. + * + * Say for example we have the following template code: + * + * ```html + * + *
+ *
+ * + * + * + * + * + * + * + * + * ``` + * + * Now, when the view changes (once the link is clicked), ngAnimate will examine the + * HTML contents to see if there is a match reference between any components in the view + * that is leaving and the view that is entering. It will scan both the view which is being + * removed (leave) and inserted (enter) to see if there are any paired DOM elements that + * contain a matching ref value. + * + * The two images match since they share the same ref value. ngAnimate will now create a + * transport element (which is a clone of the first image element) and it will then attempt + * to animate to the position of the second image element in the next view. For the animation to + * work a special CSS class called `ng-anchor` will be added to the transported element. + * + * We can now attach a transition onto the `.banner.ng-anchor` CSS class and then + * ngAnimate will handle the entire transition for us as well as the addition and removal of + * any changes of CSS classes between the elements: + * + * ```css + * .banner.ng-anchor { + * /* this animation will last for 1 second since there are + * two phases to the animation (an `in` and an `out` phase) */ + * transition:0.5s linear all; + * } + * ``` + * + * We also **must** include animations for the views that are being entered and removed + * (otherwise anchoring wouldn't be possible since the new view would be inserted right away). + * + * ```css + * .view-animation.ng-enter, .view-animation.ng-leave { + * transition:0.5s linear all; + * position:fixed; + * left:0; + * top:0; + * width:100%; + * } + * .view-animation.ng-enter { + * transform:translateX(100%); + * } + * .view-animation.ng-leave, + * .view-animation.ng-enter.ng-enter-active { + * transform:translateX(0%); + * } + * .view-animation.ng-leave.ng-leave-active { + * transform:translateX(-100%); + * } + * ``` + * + * Now we can jump back to the anchor animation. When the animation happens, there are two stages that occur: + * an `out` and an `in` stage. The `out` stage happens first and that is when the element is animated away + * from its origin. Once that animation is over then the `in` stage occurs which animates the + * element to its destination. The reason why there are two animations is to give enough time + * for the enter animation on the new element to be ready. + * + * The example above sets up a transition for both the in and out phases, but we can also target the out or + * in phases directly via `ng-anchor-out` and `ng-anchor-in`. + * + * ```css + * .banner.ng-anchor-out { + * transition: 0.5s linear all; + * + * /* the scale will be applied during the out animation, + * but will be animated away when the in animation runs */ + * transform: scale(1.2); + * } + * + * .banner.ng-anchor-in { + * transition: 1s linear all; + * } + * ``` + * + * + * + * + * ### Anchoring Demo + * + + + Home +
+
+
+
+
+ + angular.module('anchoringExample', ['ngAnimate', 'ngRoute']) + .config(['$routeProvider', function($routeProvider) { + $routeProvider.when('/', { + templateUrl: 'home.html', + controller: 'HomeController as home' + }); + $routeProvider.when('/profile/:id', { + templateUrl: 'profile.html', + controller: 'ProfileController as profile' + }); + }]) + .run(['$rootScope', function($rootScope) { + $rootScope.records = [ + { id: 1, title: 'Miss Beulah Roob' }, + { id: 2, title: 'Trent Morissette' }, + { id: 3, title: 'Miss Ava Pouros' }, + { id: 4, title: 'Rod Pouros' }, + { id: 5, title: 'Abdul Rice' }, + { id: 6, title: 'Laurie Rutherford Sr.' }, + { id: 7, title: 'Nakia McLaughlin' }, + { id: 8, title: 'Jordon Blanda DVM' }, + { id: 9, title: 'Rhoda Hand' }, + { id: 10, title: 'Alexandrea Sauer' } + ]; + }]) + .controller('HomeController', [function() { + //empty + }]) + .controller('ProfileController', ['$rootScope', '$routeParams', + function ProfileController($rootScope, $routeParams) { + var index = parseInt($routeParams.id, 10); + var record = $rootScope.records[index - 1]; + + this.title = record.title; + this.id = record.id; + }]); + + +

Welcome to the home page

+

Please click on an element

+ + {{ record.title }} + +
+ +
+ {{ profile.title }} +
+
+ + .record { + display:block; + font-size:20px; + } + .profile { + background:black; + color:white; + font-size:100px; + } + .view-container { + position:relative; + } + .view-container > .view.ng-animate { + position:absolute; + top:0; + left:0; + width:100%; + min-height:500px; + } + .view.ng-enter, .view.ng-leave, + .record.ng-anchor { + transition:0.5s linear all; + } + .view.ng-enter { + transform:translateX(100%); + } + .view.ng-enter.ng-enter-active, .view.ng-leave { + transform:translateX(0%); + } + .view.ng-leave.ng-leave-active { + transform:translateX(-100%); + } + .record.ng-anchor-out { + background:red; + } + +
+ * + * ### How is the element transported? + * + * When an anchor animation occurs, ngAnimate will clone the starting element and position it exactly where the starting + * element is located on screen via absolute positioning. The cloned element will be placed inside of the root element + * of the application (where ng-app was defined) and all of the CSS classes of the starting element will be applied. The + * element will then animate into the `out` and `in` animations and will eventually reach the coordinates and match + * the dimensions of the destination element. During the entire animation a CSS class of `.ng-animate-shim` will be applied + * to both the starting and destination elements in order to hide them from being visible (the CSS styling for the class + * is: `visibility:hidden`). Once the anchor reaches its destination then it will be removed and the destination element + * will become visible since the shim class will be removed. + * + * ### How is the morphing handled? + * + * CSS Anchoring relies on transitions and keyframes and the internal code is intelligent enough to figure out + * what CSS classes differ between the starting element and the destination element. These different CSS classes + * will be added/removed on the anchor element and a transition will be applied (the transition that is provided + * in the anchor class). Long story short, ngAnimate will figure out what classes to add and remove which will + * make the transition of the element as smooth and automatic as possible. Be sure to use simple CSS classes that + * do not rely on DOM nesting structure so that the anchor element appears the same as the starting element (since + * the cloned element is placed inside of root element which is likely close to the body element). + * + * Note that if the root element is on the `` element then the cloned node will be placed inside of body. + * + * + * ## Using $animate in your directive code + * + * So far we've explored how to feed in animations into an Angular application, but how do we trigger animations within our own directives in our application? + * By injecting the `$animate` service into our directive code, we can trigger structural and class-based hooks which can then be consumed by animations. Let's + * imagine we have a greeting box that shows and hides itself when the data changes + * + * ```html + * Hi there + * ``` + * + * ```js + * ngModule.directive('greetingBox', ['$animate', function($animate) { + * return function(scope, element, attrs) { + * attrs.$observe('active', function(value) { + * value ? $animate.addClass(element, 'on') : $animate.removeClass(element, 'on'); + * }); + * }); + * }]); + * ``` + * + * Now the `on` CSS class is added and removed on the greeting box component. Now if we add a CSS class on top of the greeting box element + * in our HTML code then we can trigger a CSS or JS animation to happen. + * + * ```css + * /* normally we would create a CSS class to reference on the element */ + * greeting-box.on { transition:0.5s linear all; background:green; color:white; } + * ``` + * + * The `$animate` service contains a variety of other methods like `enter`, `leave`, `animate` and `setClass`. To learn more about what's + * possible be sure to visit the {@link ng.$animate $animate service API page}. + * + * + * ## Callbacks and Promises + * + * When `$animate` is called it returns a promise that can be used to capture when the animation has ended. Therefore if we were to trigger + * an animation (within our directive code) then we can continue performing directive and scope related activities after the animation has + * ended by chaining onto the returned promise that animation method returns. + * + * ```js + * // somewhere within the depths of the directive + * $animate.enter(element, parent).then(function() { + * //the animation has completed + * }); + * ``` + * + * (Note that earlier versions of Angular prior to v1.4 required the promise code to be wrapped using `$scope.$apply(...)`. This is not the case + * anymore.) + * + * In addition to the animation promise, we can also make use of animation-related callbacks within our directives and controller code by registering + * an event listener using the `$animate` service. Let's say for example that an animation was triggered on our view + * routing controller to hook into that: + * + * ```js + * ngModule.controller('HomePageController', ['$animate', function($animate) { + * $animate.on('enter', ngViewElement, function(element) { + * // the animation for this route has completed + * }]); + * }]) + * ``` + * + * (Note that you will need to trigger a digest within the callback to get angular to notice any scope-related changes.) + */ + +var copy; +var extend; +var forEach; +var isArray; +var isDefined; +var isElement; +var isFunction; +var isObject; +var isString; +var isUndefined; +var jqLite; +var noop; + +/** + * @ngdoc service + * @name $animate + * @kind object + * + * @description + * The ngAnimate `$animate` service documentation is the same for the core `$animate` service. + * + * Click here {@link ng.$animate to learn more about animations with `$animate`}. + */ +angular.module('ngAnimate', [], function initAngularHelpers() { + // Access helpers from angular core. + // Do it inside a `config` block to ensure `window.angular` is available. + noop = angular.noop; + copy = angular.copy; + extend = angular.extend; + jqLite = angular.element; + forEach = angular.forEach; + isArray = angular.isArray; + isString = angular.isString; + isObject = angular.isObject; + isUndefined = angular.isUndefined; + isDefined = angular.isDefined; + isFunction = angular.isFunction; + isElement = angular.isElement; +}) + .directive('ngAnimateSwap', ngAnimateSwapDirective) + + .directive('ngAnimateChildren', $$AnimateChildrenDirective) + .factory('$$rAFScheduler', $$rAFSchedulerFactory) + + .provider('$$animateQueue', $$AnimateQueueProvider) + .provider('$$animation', $$AnimationProvider) + + .provider('$animateCss', $AnimateCssProvider) + .provider('$$animateCssDriver', $$AnimateCssDriverProvider) + + .provider('$$animateJs', $$AnimateJsProvider) + .provider('$$animateJsDriver', $$AnimateJsDriverProvider); + + +})(window, window.angular); diff --git a/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-animate/angular-animate.min.js b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-animate/angular-animate.min.js new file mode 100644 index 00000000..3733313f --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-animate/angular-animate.min.js @@ -0,0 +1,57 @@ +/* + AngularJS v1.5.11 + (c) 2010-2017 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(R,B){'use strict';function Da(a,b,c){if(!a)throw Ma("areq",b||"?",c||"required");return a}function Ea(a,b){if(!a&&!b)return"";if(!a)return b;if(!b)return a;X(a)&&(a=a.join(" "));X(b)&&(b=b.join(" "));return a+" "+b}function Na(a){var b={};a&&(a.to||a.from)&&(b.to=a.to,b.from=a.from);return b}function Y(a,b,c){var d="";a=X(a)?a:a&&G(a)&&a.length?a.split(/\s+/):[];s(a,function(a,l){a&&0=a&&(a=e,e=0,b.push(k),k=[]);k.push(g.fn);g.children.forEach(function(a){e++;c.push(a)});a--}k.length&&b.push(k);return b}(c)}var u=[],C=Z(a);return function(n,Q,t){function H(a){a= +a.hasAttribute("ng-animate-ref")?[a]:a.querySelectorAll("[ng-animate-ref]");var b=[];s(a,function(a){var c=a.getAttribute("ng-animate-ref");c&&c.length&&b.push(a)});return b}function T(a){var b=[],c={};s(a,function(a,d){var h=y(a.element),e=0<=["enter","move"].indexOf(a.event),h=a.structural?H(h):[];if(h.length){var k=e?"to":"from";s(h,function(a){var b=a.getAttribute("ng-animate-ref");c[b]=c[b]||{};c[b][k]={animationID:d,element:F(a)}})}else b.push(a)});var d={},e={};s(c,function(c,k){var r=c.from, +p=c.to;if(r&&p){var z=a[r.animationID],g=a[p.animationID],A=r.animationID.toString();if(!e[A]){var n=e[A]={structural:!0,beforeStart:function(){z.beforeStart();g.beforeStart()},close:function(){z.close();g.close()},classes:O(z.classes,g.classes),from:z,to:g,anchors:[]};n.classes.length?b.push(n):(b.push(z),b.push(g))}e[A].anchors.push({out:r.element,"in":p.element})}else r=r?r.animationID:p.animationID,p=r.toString(),d[p]||(d[p]=!0,b.push(a[r]))});return b}function O(a,b){a=a.split(" ");b=b.split(" "); +for(var c=[],d=0;d=R&&b>=m&&(F=!0,k())}function N(){function b(){if(!w){M(!1);s(x,function(a){h.style[a[0]]=a[1]});T(a,f);e.addClass(a,ea);if(q.recalculateTimingStyles){na= +h.className+" "+ga;ia=B(h,na);D=H(h,na,ia);ca=D.maxDelay;J=Math.max(ca,0);m=D.maxDuration;if(0===m){k();return}q.hasTransitions=0l.expectedEndTime)?n.cancel(l.timer):g.push(k)}N&&(p=n(c,p,!1),g[0]={timer:p,expectedEndTime:d},g.push(k),a.data("$$animateCss",g));if(fa.length)a.on(fa.join(" "),z);f.to&&(f.cleanupStyles&&Ka(A,h,Object.keys(f.to)),Ga(a,f))}}function c(){var b=a.data("$$animateCss");if(b){for(var d=1;d UI + ngModelCtrl.$render = function() { + element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.uibBtnRadio))); + }; + + //ui->model + element.on(buttonsCtrl.toggleEvent, function() { + if (attrs.disabled) { + return; + } + + var isActive = element.hasClass(buttonsCtrl.activeClass); + + if (!isActive || angular.isDefined(attrs.uncheckable)) { + scope.$apply(function() { + ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.uibBtnRadio)); + ngModelCtrl.$render(); + }); + } + }); + } + }; +}) + +.directive('uibBtnCheckbox', function() { + return { + require: ['uibBtnCheckbox', 'ngModel'], + controller: 'UibButtonsController', + controllerAs: 'button', + link: function(scope, element, attrs, ctrls) { + var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + element.find('input').css({display: 'none'}); + + function getTrueValue() { + return getCheckboxValue(attrs.btnCheckboxTrue, true); + } + + function getFalseValue() { + return getCheckboxValue(attrs.btnCheckboxFalse, false); + } + + function getCheckboxValue(attribute, defaultValue) { + return angular.isDefined(attribute) ? scope.$eval(attribute) : defaultValue; + } + + //model -> UI + ngModelCtrl.$render = function() { + element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue())); + }; + + //ui->model + element.on(buttonsCtrl.toggleEvent, function() { + if (attrs.disabled) { + return; + } + + scope.$apply(function() { + ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue()); + ngModelCtrl.$render(); + }); + }); + } + }; +}); + +/* Deprecated buttons below */ + +angular.module('ui.bootstrap.buttons') + + .value('$buttonsSuppressWarning', false) + + .controller('ButtonsController', ['$controller', '$log', '$buttonsSuppressWarning', function($controller, $log, $buttonsSuppressWarning) { + if (!$buttonsSuppressWarning) { + $log.warn('ButtonsController is now deprecated. Use UibButtonsController instead.'); + } + + angular.extend(this, $controller('UibButtonsController')); + }]) + + .directive('btnRadio', ['$log', '$buttonsSuppressWarning', function($log, $buttonsSuppressWarning) { + return { + require: ['btnRadio', 'ngModel'], + controller: 'ButtonsController', + controllerAs: 'buttons', + link: function(scope, element, attrs, ctrls) { + if (!$buttonsSuppressWarning) { + $log.warn('btn-radio is now deprecated. Use uib-btn-radio instead.'); + } + + var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + element.find('input').css({display: 'none'}); + + //model -> UI + ngModelCtrl.$render = function() { + element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio))); + }; + + //ui->model + element.bind(buttonsCtrl.toggleEvent, function() { + if (attrs.disabled) { + return; + } + + var isActive = element.hasClass(buttonsCtrl.activeClass); + + if (!isActive || angular.isDefined(attrs.uncheckable)) { + scope.$apply(function() { + ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.btnRadio)); + ngModelCtrl.$render(); + }); + } + }); + } + }; + }]) + + .directive('btnCheckbox', ['$document', '$log', '$buttonsSuppressWarning', function($document, $log, $buttonsSuppressWarning) { + return { + require: ['btnCheckbox', 'ngModel'], + controller: 'ButtonsController', + controllerAs: 'button', + link: function(scope, element, attrs, ctrls) { + if (!$buttonsSuppressWarning) { + $log.warn('btn-checkbox is now deprecated. Use uib-btn-checkbox instead.'); + } + + var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + element.find('input').css({display: 'none'}); + + function getTrueValue() { + return getCheckboxValue(attrs.btnCheckboxTrue, true); + } + + function getFalseValue() { + return getCheckboxValue(attrs.btnCheckboxFalse, false); + } + + function getCheckboxValue(attributeValue, defaultValue) { + var val = scope.$eval(attributeValue); + return angular.isDefined(val) ? val : defaultValue; + } + + //model -> UI + ngModelCtrl.$render = function() { + element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue())); + }; + + //ui->model + element.bind(buttonsCtrl.toggleEvent, function() { + if (attrs.disabled) { + return; + } + + scope.$apply(function() { + ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue()); + ngModelCtrl.$render(); + }); + }); + + //accessibility + element.on('keypress', function(e) { + if (attrs.disabled || e.which !== 32 || $document[0].activeElement !== element[0]) { + return; + } + + scope.$apply(function() { + ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue()); + ngModelCtrl.$render(); + }); + }); + } + }; + }]); + + +/** + * @ngdoc overview + * @name ui.bootstrap.carousel + * + * @description + * AngularJS version of an image carousel. + * + */ +angular.module('ui.bootstrap.carousel', []) + +.controller('UibCarouselController', ['$scope', '$element', '$interval', '$animate', function($scope, $element, $interval, $animate) { + var self = this, + slides = self.slides = $scope.slides = [], + NEW_ANIMATE = angular.version.minor >= 4, + NO_TRANSITION = 'uib-noTransition', + SLIDE_DIRECTION = 'uib-slideDirection', + currentIndex = -1, + currentInterval, isPlaying; + self.currentSlide = null; + + var destroyed = false; + /* direction: "prev" or "next" */ + self.select = $scope.select = function(nextSlide, direction) { + var nextIndex = $scope.indexOfSlide(nextSlide); + //Decide direction if it's not given + if (direction === undefined) { + direction = nextIndex > self.getCurrentIndex() ? 'next' : 'prev'; + } + //Prevent this user-triggered transition from occurring if there is already one in progress + if (nextSlide && nextSlide !== self.currentSlide && !$scope.$currentTransition) { + goNext(nextSlide, nextIndex, direction); + } + }; + + function goNext(slide, index, direction) { + // Scope has been destroyed, stop here. + if (destroyed) { return; } + + angular.extend(slide, {direction: direction, active: true}); + angular.extend(self.currentSlide || {}, {direction: direction, active: false}); + if ($animate.enabled() && !$scope.noTransition && !$scope.$currentTransition && + slide.$element && self.slides.length > 1) { + slide.$element.data(SLIDE_DIRECTION, slide.direction); + if (self.currentSlide && self.currentSlide.$element) { + self.currentSlide.$element.data(SLIDE_DIRECTION, slide.direction); + } + + $scope.$currentTransition = true; + if (NEW_ANIMATE) { + $animate.on('addClass', slide.$element, function(element, phase) { + if (phase === 'close') { + $scope.$currentTransition = null; + $animate.off('addClass', element); + } + }); + } else { + slide.$element.one('$animate:close', function closeFn() { + $scope.$currentTransition = null; + }); + } + } + + self.currentSlide = slide; + currentIndex = index; + + //every time you change slides, reset the timer + restartTimer(); + } + + $scope.$on('$destroy', function() { + destroyed = true; + }); + + function getSlideByIndex(index) { + if (angular.isUndefined(slides[index].index)) { + return slides[index]; + } + var i, len = slides.length; + for (i = 0; i < slides.length; ++i) { + if (slides[i].index == index) { + return slides[i]; + } + } + } + + self.getCurrentIndex = function() { + if (self.currentSlide && angular.isDefined(self.currentSlide.index)) { + return +self.currentSlide.index; + } + return currentIndex; + }; + + /* Allow outside people to call indexOf on slides array */ + $scope.indexOfSlide = function(slide) { + return angular.isDefined(slide.index) ? +slide.index : slides.indexOf(slide); + }; + + $scope.next = function() { + var newIndex = (self.getCurrentIndex() + 1) % slides.length; + + if (newIndex === 0 && $scope.noWrap()) { + $scope.pause(); + return; + } + + return self.select(getSlideByIndex(newIndex), 'next'); + }; + + $scope.prev = function() { + var newIndex = self.getCurrentIndex() - 1 < 0 ? slides.length - 1 : self.getCurrentIndex() - 1; + + if ($scope.noWrap() && newIndex === slides.length - 1) { + $scope.pause(); + return; + } + + return self.select(getSlideByIndex(newIndex), 'prev'); + }; + + $scope.isActive = function(slide) { + return self.currentSlide === slide; + }; + + $scope.$watch('interval', restartTimer); + $scope.$watchCollection('slides', resetTransition); + $scope.$on('$destroy', resetTimer); + + function restartTimer() { + resetTimer(); + var interval = +$scope.interval; + if (!isNaN(interval) && interval > 0) { + currentInterval = $interval(timerFn, interval); + } + } + + function resetTimer() { + if (currentInterval) { + $interval.cancel(currentInterval); + currentInterval = null; + } + } + + function timerFn() { + var interval = +$scope.interval; + if (isPlaying && !isNaN(interval) && interval > 0 && slides.length) { + $scope.next(); + } else { + $scope.pause(); + } + } + + function resetTransition(slides) { + if (!slides.length) { + $scope.$currentTransition = null; + } + } + + $scope.play = function() { + if (!isPlaying) { + isPlaying = true; + restartTimer(); + } + }; + $scope.pause = function() { + if (!$scope.noPause) { + isPlaying = false; + resetTimer(); + } + }; + + self.addSlide = function(slide, element) { + slide.$element = element; + slides.push(slide); + //if this is the first slide or the slide is set to active, select it + if (slides.length === 1 || slide.active) { + self.select(slides[slides.length - 1]); + if (slides.length === 1) { + $scope.play(); + } + } else { + slide.active = false; + } + }; + + self.removeSlide = function(slide) { + if (angular.isDefined(slide.index)) { + slides.sort(function(a, b) { + return +a.index > +b.index; + }); + } + //get the index of the slide inside the carousel + var index = slides.indexOf(slide); + slides.splice(index, 1); + if (slides.length > 0 && slide.active) { + if (index >= slides.length) { + self.select(slides[index - 1]); + } else { + self.select(slides[index]); + } + } else if (currentIndex > index) { + currentIndex--; + } + + //clean the currentSlide when no more slide + if (slides.length === 0) { + self.currentSlide = null; + } + }; + + $scope.$watch('noTransition', function(noTransition) { + $element.data(NO_TRANSITION, noTransition); + }); + +}]) + +/** + * @ngdoc directive + * @name ui.bootstrap.carousel.directive:carousel + * @restrict EA + * + * @description + * Carousel is the outer container for a set of image 'slides' to showcase. + * + * @param {number=} interval The time, in milliseconds, that it will take the carousel to go to the next slide. + * @param {boolean=} noTransition Whether to disable transitions on the carousel. + * @param {boolean=} noPause Whether to disable pausing on the carousel (by default, the carousel interval pauses on hover). + * + * @example + + + + + + + + + + + + + + + .carousel-indicators { + top: auto; + bottom: 15px; + } + + + */ +.directive('uibCarousel', [function() { + return { + transclude: true, + replace: true, + controller: 'UibCarouselController', + controllerAs: 'carousel', + require: 'carousel', + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/carousel/carousel.html'; + }, + scope: { + interval: '=', + noTransition: '=', + noPause: '=', + noWrap: '&' + } + }; +}]) + +/** + * @ngdoc directive + * @name ui.bootstrap.carousel.directive:slide + * @restrict EA + * + * @description + * Creates a slide inside a {@link ui.bootstrap.carousel.directive:carousel carousel}. Must be placed as a child of a carousel element. + * + * @param {boolean=} active Model binding, whether or not this slide is currently active. + * @param {number=} index The index of the slide. The slides will be sorted by this parameter. + * + * @example + + +
+ + + + + + + Interval, in milliseconds: +
Enter a negative number to stop the interval. +
+
+ +function CarouselDemoCtrl($scope) { + $scope.myInterval = 5000; +} + + + .carousel-indicators { + top: auto; + bottom: 15px; + } + +
+*/ + +.directive('uibSlide', function() { + return { + require: '^uibCarousel', + restrict: 'EA', + transclude: true, + replace: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/carousel/slide.html'; + }, + scope: { + active: '=?', + actual: '=?', + index: '=?' + }, + link: function (scope, element, attrs, carouselCtrl) { + carouselCtrl.addSlide(scope, element); + //when the scope is destroyed then remove the slide from the current slides array + scope.$on('$destroy', function() { + carouselCtrl.removeSlide(scope); + }); + + scope.$watch('active', function(active) { + if (active) { + carouselCtrl.select(scope); + } + }); + } + }; +}) + +.animation('.item', [ + '$injector', '$animate', +function ($injector, $animate) { + var NO_TRANSITION = 'uib-noTransition', + SLIDE_DIRECTION = 'uib-slideDirection', + $animateCss = null; + + if ($injector.has('$animateCss')) { + $animateCss = $injector.get('$animateCss'); + } + + function removeClass(element, className, callback) { + element.removeClass(className); + if (callback) { + callback(); + } + } + + return { + beforeAddClass: function(element, className, done) { + // Due to transclusion, noTransition property is on parent's scope + if (className == 'active' && element.parent() && element.parent().parent() && + !element.parent().parent().data(NO_TRANSITION)) { + var stopped = false; + var direction = element.data(SLIDE_DIRECTION); + var directionClass = direction == 'next' ? 'left' : 'right'; + var removeClassFn = removeClass.bind(this, element, + directionClass + ' ' + direction, done); + element.addClass(direction); + + if ($animateCss) { + $animateCss(element, {addClass: directionClass}) + .start() + .done(removeClassFn); + } else { + $animate.addClass(element, directionClass).then(function () { + if (!stopped) { + removeClassFn(); + } + done(); + }); + } + + return function () { + stopped = true; + }; + } + done(); + }, + beforeRemoveClass: function (element, className, done) { + // Due to transclusion, noTransition property is on parent's scope + if (className === 'active' && element.parent() && element.parent().parent() && + !element.parent().parent().data(NO_TRANSITION)) { + var stopped = false; + var direction = element.data(SLIDE_DIRECTION); + var directionClass = direction == 'next' ? 'left' : 'right'; + var removeClassFn = removeClass.bind(this, element, directionClass, done); + + if ($animateCss) { + $animateCss(element, {addClass: directionClass}) + .start() + .done(removeClassFn); + } else { + $animate.addClass(element, directionClass).then(function() { + if (!stopped) { + removeClassFn(); + } + done(); + }); + } + return function() { + stopped = true; + }; + } + done(); + } + }; +}]); + +/* deprecated carousel below */ + +angular.module('ui.bootstrap.carousel') + +.value('$carouselSuppressWarning', false) + +.controller('CarouselController', ['$scope', '$element', '$controller', '$log', '$carouselSuppressWarning', function($scope, $element, $controller, $log, $carouselSuppressWarning) { + if (!$carouselSuppressWarning) { + $log.warn('CarouselController is now deprecated. Use UibCarouselController instead.'); + } + + angular.extend(this, $controller('UibCarouselController', { + $scope: $scope, + $element: $element + })); +}]) + +.directive('carousel', ['$log', '$carouselSuppressWarning', function($log, $carouselSuppressWarning) { + return { + transclude: true, + replace: true, + controller: 'CarouselController', + controllerAs: 'carousel', + require: 'carousel', + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/carousel/carousel.html'; + }, + scope: { + interval: '=', + noTransition: '=', + noPause: '=', + noWrap: '&' + }, + link: function() { + if (!$carouselSuppressWarning) { + $log.warn('carousel is now deprecated. Use uib-carousel instead.'); + } + } + }; +}]) + +.directive('slide', ['$log', '$carouselSuppressWarning', function($log, $carouselSuppressWarning) { + return { + require: '^carousel', + transclude: true, + replace: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/carousel/slide.html'; + }, + scope: { + active: '=?', + actual: '=?', + index: '=?' + }, + link: function (scope, element, attrs, carouselCtrl) { + if (!$carouselSuppressWarning) { + $log.warn('slide is now deprecated. Use uib-slide instead.'); + } + + carouselCtrl.addSlide(scope, element); + //when the scope is destroyed then remove the slide from the current slides array + scope.$on('$destroy', function() { + carouselCtrl.removeSlide(scope); + }); + + scope.$watch('active', function(active) { + if (active) { + carouselCtrl.select(scope); + } + }); + } + }; +}]); + +angular.module('ui.bootstrap.dateparser', []) + +.service('uibDateParser', ['$log', '$locale', 'orderByFilter', function($log, $locale, orderByFilter) { + // Pulled from https://github.com/mbostock/d3/blob/master/src/format/requote.js + var SPECIAL_CHARACTERS_REGEXP = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; + + var localeId; + var formatCodeToRegex; + + this.init = function() { + localeId = $locale.id; + + this.parsers = {}; + + formatCodeToRegex = { + 'yyyy': { + regex: '\\d{4}', + apply: function(value) { this.year = +value; } + }, + 'yy': { + regex: '\\d{2}', + apply: function(value) { this.year = +value + 2000; } + }, + 'y': { + regex: '\\d{1,4}', + apply: function(value) { this.year = +value; } + }, + 'MMMM': { + regex: $locale.DATETIME_FORMATS.MONTH.join('|'), + apply: function(value) { this.month = $locale.DATETIME_FORMATS.MONTH.indexOf(value); } + }, + 'MMM': { + regex: $locale.DATETIME_FORMATS.SHORTMONTH.join('|'), + apply: function(value) { this.month = $locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value); } + }, + 'MM': { + regex: '0[1-9]|1[0-2]', + apply: function(value) { this.month = value - 1; } + }, + 'M': { + regex: '[1-9]|1[0-2]', + apply: function(value) { this.month = value - 1; } + }, + 'dd': { + regex: '[0-2][0-9]{1}|3[0-1]{1}', + apply: function(value) { this.date = +value; } + }, + 'd': { + regex: '[1-2]?[0-9]{1}|3[0-1]{1}', + apply: function(value) { this.date = +value; } + }, + 'EEEE': { + regex: $locale.DATETIME_FORMATS.DAY.join('|') + }, + 'EEE': { + regex: $locale.DATETIME_FORMATS.SHORTDAY.join('|') + }, + 'HH': { + regex: '(?:0|1)[0-9]|2[0-3]', + apply: function(value) { this.hours = +value; } + }, + 'hh': { + regex: '0[0-9]|1[0-2]', + apply: function(value) { this.hours = +value; } + }, + 'H': { + regex: '1?[0-9]|2[0-3]', + apply: function(value) { this.hours = +value; } + }, + 'h': { + regex: '[0-9]|1[0-2]', + apply: function(value) { this.hours = +value; } + }, + 'mm': { + regex: '[0-5][0-9]', + apply: function(value) { this.minutes = +value; } + }, + 'm': { + regex: '[0-9]|[1-5][0-9]', + apply: function(value) { this.minutes = +value; } + }, + 'sss': { + regex: '[0-9][0-9][0-9]', + apply: function(value) { this.milliseconds = +value; } + }, + 'ss': { + regex: '[0-5][0-9]', + apply: function(value) { this.seconds = +value; } + }, + 's': { + regex: '[0-9]|[1-5][0-9]', + apply: function(value) { this.seconds = +value; } + }, + 'a': { + regex: $locale.DATETIME_FORMATS.AMPMS.join('|'), + apply: function(value) { + if (this.hours === 12) { + this.hours = 0; + } + + if (value === 'PM') { + this.hours += 12; + } + } + } + }; + }; + + this.init(); + + function createParser(format) { + var map = [], regex = format.split(''); + + angular.forEach(formatCodeToRegex, function(data, code) { + var index = format.indexOf(code); + + if (index > -1) { + format = format.split(''); + + regex[index] = '(' + data.regex + ')'; + format[index] = '$'; // Custom symbol to define consumed part of format + for (var i = index + 1, n = index + code.length; i < n; i++) { + regex[i] = ''; + format[i] = '$'; + } + format = format.join(''); + + map.push({ index: index, apply: data.apply }); + } + }); + + return { + regex: new RegExp('^' + regex.join('') + '$'), + map: orderByFilter(map, 'index') + }; + } + + this.parse = function(input, format, baseDate) { + if (!angular.isString(input) || !format) { + return input; + } + + format = $locale.DATETIME_FORMATS[format] || format; + format = format.replace(SPECIAL_CHARACTERS_REGEXP, '\\$&'); + + if ($locale.id !== localeId) { + this.init(); + } + + if (!this.parsers[format]) { + this.parsers[format] = createParser(format); + } + + var parser = this.parsers[format], + regex = parser.regex, + map = parser.map, + results = input.match(regex); + + if (results && results.length) { + var fields, dt; + if (angular.isDate(baseDate) && !isNaN(baseDate.getTime())) { + fields = { + year: baseDate.getFullYear(), + month: baseDate.getMonth(), + date: baseDate.getDate(), + hours: baseDate.getHours(), + minutes: baseDate.getMinutes(), + seconds: baseDate.getSeconds(), + milliseconds: baseDate.getMilliseconds() + }; + } else { + if (baseDate) { + $log.warn('dateparser:', 'baseDate is not a valid date'); + } + fields = { year: 1900, month: 0, date: 1, hours: 0, minutes: 0, seconds: 0, milliseconds: 0 }; + } + + for (var i = 1, n = results.length; i < n; i++) { + var mapper = map[i-1]; + if (mapper.apply) { + mapper.apply.call(fields, results[i]); + } + } + + if (isValid(fields.year, fields.month, fields.date)) { + if (angular.isDate(baseDate) && !isNaN(baseDate.getTime())) { + dt = new Date(baseDate); + dt.setFullYear(fields.year, fields.month, fields.date, + fields.hours, fields.minutes, fields.seconds, + fields.milliseconds || 0); + } else { + dt = new Date(fields.year, fields.month, fields.date, + fields.hours, fields.minutes, fields.seconds, + fields.milliseconds || 0); + } + } + + return dt; + } + }; + + // Check if date is valid for specific month (and year for February). + // Month: 0 = Jan, 1 = Feb, etc + function isValid(year, month, date) { + if (date < 1) { + return false; + } + + if (month === 1 && date > 28) { + return date === 29 && ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0); + } + + if (month === 3 || month === 5 || month === 8 || month === 10) { + return date < 31; + } + + return true; + } +}]); + +/* Deprecated dateparser below */ + +angular.module('ui.bootstrap.dateparser') + +.value('$dateParserSuppressWarning', false) + +.service('dateParser', ['$log', '$dateParserSuppressWarning', 'uibDateParser', function($log, $dateParserSuppressWarning, uibDateParser) { + if (!$dateParserSuppressWarning) { + $log.warn('dateParser is now deprecated. Use uibDateParser instead.'); + } + + angular.extend(this, uibDateParser); +}]); + +angular.module('ui.bootstrap.position', []) + +/** + * A set of utility methods that can be use to retrieve position of DOM elements. + * It is meant to be used where we need to absolute-position DOM elements in + * relation to other, existing elements (this is the case for tooltips, popovers, + * typeahead suggestions etc.). + */ + .factory('$uibPosition', ['$document', '$window', function($document, $window) { + function getStyle(el, cssprop) { + if (el.currentStyle) { //IE + return el.currentStyle[cssprop]; + } else if ($window.getComputedStyle) { + return $window.getComputedStyle(el)[cssprop]; + } + // finally try and get inline style + return el.style[cssprop]; + } + + /** + * Checks if a given element is statically positioned + * @param element - raw DOM element + */ + function isStaticPositioned(element) { + return (getStyle(element, 'position') || 'static' ) === 'static'; + } + + /** + * returns the closest, non-statically positioned parentOffset of a given element + * @param element + */ + var parentOffsetEl = function(element) { + var docDomEl = $document[0]; + var offsetParent = element.offsetParent || docDomEl; + while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) { + offsetParent = offsetParent.offsetParent; + } + return offsetParent || docDomEl; + }; + + return { + /** + * Provides read-only equivalent of jQuery's position function: + * http://api.jquery.com/position/ + */ + position: function(element) { + var elBCR = this.offset(element); + var offsetParentBCR = { top: 0, left: 0 }; + var offsetParentEl = parentOffsetEl(element[0]); + if (offsetParentEl != $document[0]) { + offsetParentBCR = this.offset(angular.element(offsetParentEl)); + offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop; + offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft; + } + + var boundingClientRect = element[0].getBoundingClientRect(); + return { + width: boundingClientRect.width || element.prop('offsetWidth'), + height: boundingClientRect.height || element.prop('offsetHeight'), + top: elBCR.top - offsetParentBCR.top, + left: elBCR.left - offsetParentBCR.left + }; + }, + + /** + * Provides read-only equivalent of jQuery's offset function: + * http://api.jquery.com/offset/ + */ + offset: function(element) { + var boundingClientRect = element[0].getBoundingClientRect(); + return { + width: boundingClientRect.width || element.prop('offsetWidth'), + height: boundingClientRect.height || element.prop('offsetHeight'), + top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop), + left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft) + }; + }, + + /** + * Provides coordinates for the targetEl in relation to hostEl + */ + positionElements: function(hostEl, targetEl, positionStr, appendToBody) { + var positionStrParts = positionStr.split('-'); + var pos0 = positionStrParts[0], pos1 = positionStrParts[1] || 'center'; + + var hostElPos, + targetElWidth, + targetElHeight, + targetElPos; + + hostElPos = appendToBody ? this.offset(hostEl) : this.position(hostEl); + + targetElWidth = targetEl.prop('offsetWidth'); + targetElHeight = targetEl.prop('offsetHeight'); + + var shiftWidth = { + center: function() { + return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2; + }, + left: function() { + return hostElPos.left; + }, + right: function() { + return hostElPos.left + hostElPos.width; + } + }; + + var shiftHeight = { + center: function() { + return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2; + }, + top: function() { + return hostElPos.top; + }, + bottom: function() { + return hostElPos.top + hostElPos.height; + } + }; + + switch (pos0) { + case 'right': + targetElPos = { + top: shiftHeight[pos1](), + left: shiftWidth[pos0]() + }; + break; + case 'left': + targetElPos = { + top: shiftHeight[pos1](), + left: hostElPos.left - targetElWidth + }; + break; + case 'bottom': + targetElPos = { + top: shiftHeight[pos0](), + left: shiftWidth[pos1]() + }; + break; + default: + targetElPos = { + top: hostElPos.top - targetElHeight, + left: shiftWidth[pos1]() + }; + break; + } + + return targetElPos; + } + }; + }]); + +/* Deprecated position below */ + +angular.module('ui.bootstrap.position') + +.value('$positionSuppressWarning', false) + +.service('$position', ['$log', '$positionSuppressWarning', '$uibPosition', function($log, $positionSuppressWarning, $uibPosition) { + if (!$positionSuppressWarning) { + $log.warn('$position is now deprecated. Use $uibPosition instead.'); + } + + angular.extend(this, $uibPosition); +}]); + +angular.module('ui.bootstrap.datepicker', ['ui.bootstrap.dateparser', 'ui.bootstrap.position']) + +.value('$datepickerSuppressError', false) + +.constant('uibDatepickerConfig', { + formatDay: 'dd', + formatMonth: 'MMMM', + formatYear: 'yyyy', + formatDayHeader: 'EEE', + formatDayTitle: 'MMMM yyyy', + formatMonthTitle: 'yyyy', + datepickerMode: 'day', + minMode: 'day', + maxMode: 'year', + showWeeks: true, + startingDay: 0, + yearRange: 20, + minDate: null, + maxDate: null, + shortcutPropagation: false +}) + +.controller('UibDatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$log', 'dateFilter', 'uibDatepickerConfig', '$datepickerSuppressError', function($scope, $attrs, $parse, $interpolate, $log, dateFilter, datepickerConfig, $datepickerSuppressError) { + var self = this, + ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl; + + // Modes chain + this.modes = ['day', 'month', 'year']; + + // Configuration attributes + angular.forEach(['formatDay', 'formatMonth', 'formatYear', 'formatDayHeader', 'formatDayTitle', 'formatMonthTitle', + 'showWeeks', 'startingDay', 'yearRange', 'shortcutPropagation'], function(key, index) { + self[key] = angular.isDefined($attrs[key]) ? (index < 6 ? $interpolate($attrs[key])($scope.$parent) : $scope.$parent.$eval($attrs[key])) : datepickerConfig[key]; + }); + + // Watchable date attributes + angular.forEach(['minDate', 'maxDate'], function(key) { + if ($attrs[key]) { + $scope.$parent.$watch($parse($attrs[key]), function(value) { + self[key] = value ? new Date(value) : null; + self.refreshView(); + }); + } else { + self[key] = datepickerConfig[key] ? new Date(datepickerConfig[key]) : null; + } + }); + + angular.forEach(['minMode', 'maxMode'], function(key) { + if ($attrs[key]) { + $scope.$parent.$watch($parse($attrs[key]), function(value) { + self[key] = angular.isDefined(value) ? value : $attrs[key]; + $scope[key] = self[key]; + if ((key == 'minMode' && self.modes.indexOf($scope.datepickerMode) < self.modes.indexOf(self[key])) || (key == 'maxMode' && self.modes.indexOf($scope.datepickerMode) > self.modes.indexOf(self[key]))) { + $scope.datepickerMode = self[key]; + } + }); + } else { + self[key] = datepickerConfig[key] || null; + $scope[key] = self[key]; + } + }); + + $scope.datepickerMode = $scope.datepickerMode || datepickerConfig.datepickerMode; + $scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000); + + if (angular.isDefined($attrs.initDate)) { + this.activeDate = $scope.$parent.$eval($attrs.initDate) || new Date(); + $scope.$parent.$watch($attrs.initDate, function(initDate) { + if (initDate && (ngModelCtrl.$isEmpty(ngModelCtrl.$modelValue) || ngModelCtrl.$invalid)) { + self.activeDate = initDate; + self.refreshView(); + } + }); + } else { + this.activeDate = new Date(); + } + + $scope.isActive = function(dateObject) { + if (self.compare(dateObject.date, self.activeDate) === 0) { + $scope.activeDateId = dateObject.uid; + return true; + } + return false; + }; + + this.init = function(ngModelCtrl_) { + ngModelCtrl = ngModelCtrl_; + + ngModelCtrl.$render = function() { + self.render(); + }; + }; + + this.render = function() { + if (ngModelCtrl.$viewValue) { + var date = new Date(ngModelCtrl.$viewValue), + isValid = !isNaN(date); + + if (isValid) { + this.activeDate = date; + } else if (!$datepickerSuppressError) { + $log.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.'); + } + } + this.refreshView(); + }; + + this.refreshView = function() { + if (this.element) { + this._refreshView(); + + var date = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null; + ngModelCtrl.$setValidity('dateDisabled', !date || (this.element && !this.isDisabled(date))); + } + }; + + this.createDateObject = function(date, format) { + var model = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null; + return { + date: date, + label: dateFilter(date, format), + selected: model && this.compare(date, model) === 0, + disabled: this.isDisabled(date), + current: this.compare(date, new Date()) === 0, + customClass: this.customClass(date) + }; + }; + + this.isDisabled = function(date) { + return ((this.minDate && this.compare(date, this.minDate) < 0) || (this.maxDate && this.compare(date, this.maxDate) > 0) || ($attrs.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode}))); + }; + + this.customClass = function(date) { + return $scope.customClass({date: date, mode: $scope.datepickerMode}); + }; + + // Split array into smaller arrays + this.split = function(arr, size) { + var arrays = []; + while (arr.length > 0) { + arrays.push(arr.splice(0, size)); + } + return arrays; + }; + + $scope.select = function(date) { + if ($scope.datepickerMode === self.minMode) { + var dt = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : new Date(0, 0, 0, 0, 0, 0, 0); + dt.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); + ngModelCtrl.$setViewValue(dt); + ngModelCtrl.$render(); + } else { + self.activeDate = date; + $scope.datepickerMode = self.modes[self.modes.indexOf($scope.datepickerMode) - 1]; + } + }; + + $scope.move = function(direction) { + var year = self.activeDate.getFullYear() + direction * (self.step.years || 0), + month = self.activeDate.getMonth() + direction * (self.step.months || 0); + self.activeDate.setFullYear(year, month, 1); + self.refreshView(); + }; + + $scope.toggleMode = function(direction) { + direction = direction || 1; + + if (($scope.datepickerMode === self.maxMode && direction === 1) || ($scope.datepickerMode === self.minMode && direction === -1)) { + return; + } + + $scope.datepickerMode = self.modes[self.modes.indexOf($scope.datepickerMode) + direction]; + }; + + // Key event mapper + $scope.keys = { 13: 'enter', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; + + var focusElement = function() { + self.element[0].focus(); + }; + + // Listen for focus requests from popup directive + $scope.$on('uib:datepicker.focus', focusElement); + + $scope.keydown = function(evt) { + var key = $scope.keys[evt.which]; + + if (!key || evt.shiftKey || evt.altKey) { + return; + } + + evt.preventDefault(); + if (!self.shortcutPropagation) { + evt.stopPropagation(); + } + + if (key === 'enter' || key === 'space') { + if (self.isDisabled(self.activeDate)) { + return; // do nothing + } + $scope.select(self.activeDate); + } else if (evt.ctrlKey && (key === 'up' || key === 'down')) { + $scope.toggleMode(key === 'up' ? 1 : -1); + } else { + self.handleKeyDown(key, evt); + self.refreshView(); + } + }; +}]) + +.controller('UibDaypickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) { + var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + + this.step = { months: 1 }; + this.element = $element; + function getDaysInMonth(year, month) { + return ((month === 1) && (year % 4 === 0) && ((year % 100 !== 0) || (year % 400 === 0))) ? 29 : DAYS_IN_MONTH[month]; + } + + this.init = function(ctrl) { + angular.extend(ctrl, this); + scope.showWeeks = ctrl.showWeeks; + ctrl.refreshView(); + }; + + this.getDates = function(startDate, n) { + var dates = new Array(n), current = new Date(startDate), i = 0, date; + while (i < n) { + date = new Date(current); + dates[i++] = date; + current.setDate(current.getDate() + 1); + } + return dates; + }; + + this._refreshView = function() { + var year = this.activeDate.getFullYear(), + month = this.activeDate.getMonth(), + firstDayOfMonth = new Date(this.activeDate); + + firstDayOfMonth.setFullYear(year, month, 1); + + var difference = this.startingDay - firstDayOfMonth.getDay(), + numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : - difference, + firstDate = new Date(firstDayOfMonth); + + if (numDisplayedFromPreviousMonth > 0) { + firstDate.setDate(-numDisplayedFromPreviousMonth + 1); + } + + // 42 is the number of days on a six-month calendar + var days = this.getDates(firstDate, 42); + for (var i = 0; i < 42; i ++) { + days[i] = angular.extend(this.createDateObject(days[i], this.formatDay), { + secondary: days[i].getMonth() !== month, + uid: scope.uniqueId + '-' + i + }); + } + + scope.labels = new Array(7); + for (var j = 0; j < 7; j++) { + scope.labels[j] = { + abbr: dateFilter(days[j].date, this.formatDayHeader), + full: dateFilter(days[j].date, 'EEEE') + }; + } + + scope.title = dateFilter(this.activeDate, this.formatDayTitle); + scope.rows = this.split(days, 7); + + if (scope.showWeeks) { + scope.weekNumbers = []; + var thursdayIndex = (4 + 7 - this.startingDay) % 7, + numWeeks = scope.rows.length; + for (var curWeek = 0; curWeek < numWeeks; curWeek++) { + scope.weekNumbers.push( + getISO8601WeekNumber(scope.rows[curWeek][thursdayIndex].date)); + } + } + }; + + this.compare = function(date1, date2) { + return (new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate())); + }; + + function getISO8601WeekNumber(date) { + var checkDate = new Date(date); + checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday + var time = checkDate.getTime(); + checkDate.setMonth(0); // Compare with Jan 1 + checkDate.setDate(1); + return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; + } + + this.handleKeyDown = function(key, evt) { + var date = this.activeDate.getDate(); + + if (key === 'left') { + date = date - 1; // up + } else if (key === 'up') { + date = date - 7; // down + } else if (key === 'right') { + date = date + 1; // down + } else if (key === 'down') { + date = date + 7; + } else if (key === 'pageup' || key === 'pagedown') { + var month = this.activeDate.getMonth() + (key === 'pageup' ? - 1 : 1); + this.activeDate.setMonth(month, 1); + date = Math.min(getDaysInMonth(this.activeDate.getFullYear(), this.activeDate.getMonth()), date); + } else if (key === 'home') { + date = 1; + } else if (key === 'end') { + date = getDaysInMonth(this.activeDate.getFullYear(), this.activeDate.getMonth()); + } + this.activeDate.setDate(date); + }; +}]) + +.controller('UibMonthpickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) { + this.step = { years: 1 }; + this.element = $element; + + this.init = function(ctrl) { + angular.extend(ctrl, this); + ctrl.refreshView(); + }; + + this._refreshView = function() { + var months = new Array(12), + year = this.activeDate.getFullYear(), + date; + + for (var i = 0; i < 12; i++) { + date = new Date(this.activeDate); + date.setFullYear(year, i, 1); + months[i] = angular.extend(this.createDateObject(date, this.formatMonth), { + uid: scope.uniqueId + '-' + i + }); + } + + scope.title = dateFilter(this.activeDate, this.formatMonthTitle); + scope.rows = this.split(months, 3); + }; + + this.compare = function(date1, date2) { + return new Date(date1.getFullYear(), date1.getMonth()) - new Date(date2.getFullYear(), date2.getMonth()); + }; + + this.handleKeyDown = function(key, evt) { + var date = this.activeDate.getMonth(); + + if (key === 'left') { + date = date - 1; // up + } else if (key === 'up') { + date = date - 3; // down + } else if (key === 'right') { + date = date + 1; // down + } else if (key === 'down') { + date = date + 3; + } else if (key === 'pageup' || key === 'pagedown') { + var year = this.activeDate.getFullYear() + (key === 'pageup' ? - 1 : 1); + this.activeDate.setFullYear(year); + } else if (key === 'home') { + date = 0; + } else if (key === 'end') { + date = 11; + } + this.activeDate.setMonth(date); + }; +}]) + +.controller('UibYearpickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) { + var range; + this.element = $element; + + function getStartingYear(year) { + return parseInt((year - 1) / range, 10) * range + 1; + } + + this.yearpickerInit = function() { + range = this.yearRange; + this.step = { years: range }; + }; + + this._refreshView = function() { + var years = new Array(range), date; + + for (var i = 0, start = getStartingYear(this.activeDate.getFullYear()); i < range; i++) { + date = new Date(this.activeDate); + date.setFullYear(start + i, 0, 1); + years[i] = angular.extend(this.createDateObject(date, this.formatYear), { + uid: scope.uniqueId + '-' + i + }); + } + + scope.title = [years[0].label, years[range - 1].label].join(' - '); + scope.rows = this.split(years, 5); + }; + + this.compare = function(date1, date2) { + return date1.getFullYear() - date2.getFullYear(); + }; + + this.handleKeyDown = function(key, evt) { + var date = this.activeDate.getFullYear(); + + if (key === 'left') { + date = date - 1; // up + } else if (key === 'up') { + date = date - 5; // down + } else if (key === 'right') { + date = date + 1; // down + } else if (key === 'down') { + date = date + 5; + } else if (key === 'pageup' || key === 'pagedown') { + date += (key === 'pageup' ? - 1 : 1) * this.step.years; + } else if (key === 'home') { + date = getStartingYear(this.activeDate.getFullYear()); + } else if (key === 'end') { + date = getStartingYear(this.activeDate.getFullYear()) + range - 1; + } + this.activeDate.setFullYear(date); + }; +}]) + +.directive('uibDatepicker', function() { + return { + replace: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/datepicker/datepicker.html'; + }, + scope: { + datepickerMode: '=?', + dateDisabled: '&', + customClass: '&', + shortcutPropagation: '&?' + }, + require: ['uibDatepicker', '^ngModel'], + controller: 'UibDatepickerController', + controllerAs: 'datepicker', + link: function(scope, element, attrs, ctrls) { + var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + datepickerCtrl.init(ngModelCtrl); + } + }; +}) + +.directive('uibDaypicker', function() { + return { + replace: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/datepicker/day.html'; + }, + require: ['^?uibDatepicker', 'uibDaypicker', '^?datepicker'], + controller: 'UibDaypickerController', + link: function(scope, element, attrs, ctrls) { + var datepickerCtrl = ctrls[0] || ctrls[2], + daypickerCtrl = ctrls[1]; + + daypickerCtrl.init(datepickerCtrl); + } + }; +}) + +.directive('uibMonthpicker', function() { + return { + replace: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/datepicker/month.html'; + }, + require: ['^?uibDatepicker', 'uibMonthpicker', '^?datepicker'], + controller: 'UibMonthpickerController', + link: function(scope, element, attrs, ctrls) { + var datepickerCtrl = ctrls[0] || ctrls[2], + monthpickerCtrl = ctrls[1]; + + monthpickerCtrl.init(datepickerCtrl); + } + }; +}) + +.directive('uibYearpicker', function() { + return { + replace: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/datepicker/year.html'; + }, + require: ['^?uibDatepicker', 'uibYearpicker', '^?datepicker'], + controller: 'UibYearpickerController', + link: function(scope, element, attrs, ctrls) { + var ctrl = ctrls[0] || ctrls[2]; + angular.extend(ctrl, ctrls[1]); + ctrl.yearpickerInit(); + + ctrl.refreshView(); + } + }; +}) + +.constant('uibDatepickerPopupConfig', { + datepickerPopup: 'yyyy-MM-dd', + datepickerPopupTemplateUrl: 'template/datepicker/popup.html', + datepickerTemplateUrl: 'template/datepicker/datepicker.html', + html5Types: { + date: 'yyyy-MM-dd', + 'datetime-local': 'yyyy-MM-ddTHH:mm:ss.sss', + 'month': 'yyyy-MM' + }, + currentText: 'Today', + clearText: 'Clear', + closeText: 'Done', + closeOnDateSelection: true, + appendToBody: false, + showButtonBar: true, + onOpenFocus: true +}) + +.controller('UibDatepickerPopupController', ['$scope', '$element', '$attrs', '$compile', '$parse', '$document', '$rootScope', '$uibPosition', 'dateFilter', 'uibDateParser', 'uibDatepickerPopupConfig', '$timeout', +function(scope, element, attrs, $compile, $parse, $document, $rootScope, $position, dateFilter, dateParser, datepickerPopupConfig, $timeout) { + var self = this; + var cache = {}, + isHtml5DateInput = false; + var dateFormat, closeOnDateSelection, appendToBody, onOpenFocus, + datepickerPopupTemplateUrl, datepickerTemplateUrl, popupEl, datepickerEl, + ngModel, $popup; + + scope.watchData = {}; + + this.init = function(_ngModel_) { + ngModel = _ngModel_; + closeOnDateSelection = angular.isDefined(attrs.closeOnDateSelection) ? scope.$parent.$eval(attrs.closeOnDateSelection) : datepickerPopupConfig.closeOnDateSelection; + appendToBody = angular.isDefined(attrs.datepickerAppendToBody) ? scope.$parent.$eval(attrs.datepickerAppendToBody) : datepickerPopupConfig.appendToBody; + onOpenFocus = angular.isDefined(attrs.onOpenFocus) ? scope.$parent.$eval(attrs.onOpenFocus) : datepickerPopupConfig.onOpenFocus; + datepickerPopupTemplateUrl = angular.isDefined(attrs.datepickerPopupTemplateUrl) ? attrs.datepickerPopupTemplateUrl : datepickerPopupConfig.datepickerPopupTemplateUrl; + datepickerTemplateUrl = angular.isDefined(attrs.datepickerTemplateUrl) ? attrs.datepickerTemplateUrl : datepickerPopupConfig.datepickerTemplateUrl; + + scope.showButtonBar = angular.isDefined(attrs.showButtonBar) ? scope.$parent.$eval(attrs.showButtonBar) : datepickerPopupConfig.showButtonBar; + + if (datepickerPopupConfig.html5Types[attrs.type]) { + dateFormat = datepickerPopupConfig.html5Types[attrs.type]; + isHtml5DateInput = true; + } else { + dateFormat = attrs.datepickerPopup || attrs.uibDatepickerPopup || datepickerPopupConfig.datepickerPopup; + attrs.$observe('uibDatepickerPopup', function(value, oldValue) { + var newDateFormat = value || datepickerPopupConfig.datepickerPopup; + // Invalidate the $modelValue to ensure that formatters re-run + // FIXME: Refactor when PR is merged: https://github.com/angular/angular.js/pull/10764 + if (newDateFormat !== dateFormat) { + dateFormat = newDateFormat; + ngModel.$modelValue = null; + + if (!dateFormat) { + throw new Error('uibDatepickerPopup must have a date format specified.'); + } + } + }); + } + + if (!dateFormat) { + throw new Error('uibDatepickerPopup must have a date format specified.'); + } + + if (isHtml5DateInput && attrs.datepickerPopup) { + throw new Error('HTML5 date input types do not support custom formats.'); + } + + // popup element used to display calendar + popupEl = angular.element('
'); + popupEl.attr({ + 'ng-model': 'date', + 'ng-change': 'dateSelection(date)', + 'template-url': datepickerPopupTemplateUrl + }); + + // datepicker element + datepickerEl = angular.element(popupEl.children()[0]); + datepickerEl.attr('template-url', datepickerTemplateUrl); + + if (isHtml5DateInput) { + if (attrs.type === 'month') { + datepickerEl.attr('datepicker-mode', '"month"'); + datepickerEl.attr('min-mode', 'month'); + } + } + + if (attrs.datepickerOptions) { + var options = scope.$parent.$eval(attrs.datepickerOptions); + if (options && options.initDate) { + scope.initDate = options.initDate; + datepickerEl.attr('init-date', 'initDate'); + delete options.initDate; + } + angular.forEach(options, function(value, option) { + datepickerEl.attr(cameltoDash(option), value); + }); + } + + angular.forEach(['minMode', 'maxMode', 'minDate', 'maxDate', 'datepickerMode', 'initDate', 'shortcutPropagation'], function(key) { + if (attrs[key]) { + var getAttribute = $parse(attrs[key]); + scope.$parent.$watch(getAttribute, function(value) { + scope.watchData[key] = value; + if (key === 'minDate' || key === 'maxDate') { + cache[key] = new Date(value); + } + }); + datepickerEl.attr(cameltoDash(key), 'watchData.' + key); + + // Propagate changes from datepicker to outside + if (key === 'datepickerMode') { + var setAttribute = getAttribute.assign; + scope.$watch('watchData.' + key, function(value, oldvalue) { + if (angular.isFunction(setAttribute) && value !== oldvalue) { + setAttribute(scope.$parent, value); + } + }); + } + } + }); + if (attrs.dateDisabled) { + datepickerEl.attr('date-disabled', 'dateDisabled({ date: date, mode: mode })'); + } + + if (attrs.showWeeks) { + datepickerEl.attr('show-weeks', attrs.showWeeks); + } + + if (attrs.customClass) { + datepickerEl.attr('custom-class', 'customClass({ date: date, mode: mode })'); + } + + if (!isHtml5DateInput) { + // Internal API to maintain the correct ng-invalid-[key] class + ngModel.$$parserName = 'date'; + ngModel.$validators.date = validator; + ngModel.$parsers.unshift(parseDate); + ngModel.$formatters.push(function(value) { + scope.date = value; + return ngModel.$isEmpty(value) ? value : dateFilter(value, dateFormat); + }); + } else { + ngModel.$formatters.push(function(value) { + scope.date = value; + return value; + }); + } + + // Detect changes in the view from the text box + ngModel.$viewChangeListeners.push(function() { + scope.date = dateParser.parse(ngModel.$viewValue, dateFormat, scope.date); + }); + + element.bind('keydown', inputKeydownBind); + + $popup = $compile(popupEl)(scope); + // Prevent jQuery cache memory leak (template is now redundant after linking) + popupEl.remove(); + + if (appendToBody) { + $document.find('body').append($popup); + } else { + element.after($popup); + } + + scope.$on('$destroy', function() { + if (scope.isOpen === true) { + if (!$rootScope.$$phase) { + scope.$apply(function() { + scope.isOpen = false; + }); + } + } + + $popup.remove(); + element.unbind('keydown', inputKeydownBind); + $document.unbind('click', documentClickBind); + }); + }; + + scope.getText = function(key) { + return scope[key + 'Text'] || datepickerPopupConfig[key + 'Text']; + }; + + scope.isDisabled = function(date) { + if (date === 'today') { + date = new Date(); + } + + return ((scope.watchData.minDate && scope.compare(date, cache.minDate) < 0) || + (scope.watchData.maxDate && scope.compare(date, cache.maxDate) > 0)); + }; + + scope.compare = function(date1, date2) { + return (new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate())); + }; + + // Inner change + scope.dateSelection = function(dt) { + if (angular.isDefined(dt)) { + scope.date = dt; + } + var date = scope.date ? dateFilter(scope.date, dateFormat) : null; // Setting to NULL is necessary for form validators to function + element.val(date); + ngModel.$setViewValue(date); + + if (closeOnDateSelection) { + scope.isOpen = false; + element[0].focus(); + } + }; + + scope.keydown = function(evt) { + if (evt.which === 27) { + scope.isOpen = false; + element[0].focus(); + } + }; + + scope.select = function(date) { + if (date === 'today') { + var today = new Date(); + if (angular.isDate(scope.date)) { + date = new Date(scope.date); + date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate()); + } else { + date = new Date(today.setHours(0, 0, 0, 0)); + } + } + scope.dateSelection(date); + }; + + scope.close = function() { + scope.isOpen = false; + element[0].focus(); + }; + + scope.$watch('isOpen', function(value) { + if (value) { + scope.position = appendToBody ? $position.offset(element) : $position.position(element); + scope.position.top = scope.position.top + element.prop('offsetHeight'); + + $timeout(function() { + if (onOpenFocus) { + scope.$broadcast('uib:datepicker.focus'); + } + $document.bind('click', documentClickBind); + }, 0, false); + } else { + $document.unbind('click', documentClickBind); + } + }); + + function cameltoDash(string) { + return string.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); }); + } + + function parseDate(viewValue) { + if (angular.isNumber(viewValue)) { + // presumably timestamp to date object + viewValue = new Date(viewValue); + } + + if (!viewValue) { + return null; + } else if (angular.isDate(viewValue) && !isNaN(viewValue)) { + return viewValue; + } else if (angular.isString(viewValue)) { + var date = dateParser.parse(viewValue, dateFormat, scope.date); + if (isNaN(date)) { + return undefined; + } else { + return date; + } + } else { + return undefined; + } + } + + function validator(modelValue, viewValue) { + var value = modelValue || viewValue; + + if (!attrs.ngRequired && !value) { + return true; + } + + if (angular.isNumber(value)) { + value = new Date(value); + } + if (!value) { + return true; + } else if (angular.isDate(value) && !isNaN(value)) { + return true; + } else if (angular.isString(value)) { + var date = dateParser.parse(value, dateFormat); + return !isNaN(date); + } else { + return false; + } + } + + function documentClickBind(event) { + var popup = $popup[0]; + var dpContainsTarget = element[0].contains(event.target); + // The popup node may not be an element node + // In some browsers (IE) only element nodes have the 'contains' function + var popupContainsTarget = popup.contains !== undefined && popup.contains(event.target); + if (scope.isOpen && !(dpContainsTarget || popupContainsTarget)) { + scope.$apply(function() { + scope.isOpen = false; + }); + } + } + + function inputKeydownBind(evt) { + if (evt.which === 27 && scope.isOpen) { + evt.preventDefault(); + evt.stopPropagation(); + scope.$apply(function() { + scope.isOpen = false; + }); + element[0].focus(); + } else if (evt.which === 40 && !scope.isOpen) { + evt.preventDefault(); + evt.stopPropagation(); + scope.$apply(function() { + scope.isOpen = true; + }); + } + } +}]) + +.directive('uibDatepickerPopup', function() { + return { + require: ['ngModel', 'uibDatepickerPopup'], + controller: 'UibDatepickerPopupController', + scope: { + isOpen: '=?', + currentText: '@', + clearText: '@', + closeText: '@', + dateDisabled: '&', + customClass: '&' + }, + link: function(scope, element, attrs, ctrls) { + var ngModel = ctrls[0], + ctrl = ctrls[1]; + + ctrl.init(ngModel); + } + }; +}) + +.directive('uibDatepickerPopupWrap', function() { + return { + replace: true, + transclude: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/datepicker/popup.html'; + } + }; +}); + +/* Deprecated datepicker below */ + +angular.module('ui.bootstrap.datepicker') + +.value('$datepickerSuppressWarning', false) + +.controller('DatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$log', 'dateFilter', 'uibDatepickerConfig', '$datepickerSuppressError', '$datepickerSuppressWarning', function($scope, $attrs, $parse, $interpolate, $log, dateFilter, datepickerConfig, $datepickerSuppressError, $datepickerSuppressWarning) { + if (!$datepickerSuppressWarning) { + $log.warn('DatepickerController is now deprecated. Use UibDatepickerController instead.'); + } + + var self = this, + ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl; + + this.modes = ['day', 'month', 'year']; + + angular.forEach(['formatDay', 'formatMonth', 'formatYear', 'formatDayHeader', 'formatDayTitle', 'formatMonthTitle', + 'showWeeks', 'startingDay', 'yearRange', 'shortcutPropagation'], function(key, index) { + self[key] = angular.isDefined($attrs[key]) ? (index < 6 ? $interpolate($attrs[key])($scope.$parent) : $scope.$parent.$eval($attrs[key])) : datepickerConfig[key]; + }); + + angular.forEach(['minDate', 'maxDate'], function(key) { + if ($attrs[key]) { + $scope.$parent.$watch($parse($attrs[key]), function(value) { + self[key] = value ? new Date(value) : null; + self.refreshView(); + }); + } else { + self[key] = datepickerConfig[key] ? new Date(datepickerConfig[key]) : null; + } + }); + + angular.forEach(['minMode', 'maxMode'], function(key) { + if ($attrs[key]) { + $scope.$parent.$watch($parse($attrs[key]), function(value) { + self[key] = angular.isDefined(value) ? value : $attrs[key]; + $scope[key] = self[key]; + if ((key == 'minMode' && self.modes.indexOf($scope.datepickerMode) < self.modes.indexOf(self[key])) || (key == 'maxMode' && self.modes.indexOf($scope.datepickerMode) > self.modes.indexOf(self[key]))) { + $scope.datepickerMode = self[key]; + } + }); + } else { + self[key] = datepickerConfig[key] || null; + $scope[key] = self[key]; + } + }); + + $scope.datepickerMode = $scope.datepickerMode || datepickerConfig.datepickerMode; + $scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000); + + if (angular.isDefined($attrs.initDate)) { + this.activeDate = $scope.$parent.$eval($attrs.initDate) || new Date(); + $scope.$parent.$watch($attrs.initDate, function(initDate) { + if (initDate && (ngModelCtrl.$isEmpty(ngModelCtrl.$modelValue) || ngModelCtrl.$invalid)) { + self.activeDate = initDate; + self.refreshView(); + } + }); + } else { + this.activeDate = new Date(); + } + + $scope.isActive = function(dateObject) { + if (self.compare(dateObject.date, self.activeDate) === 0) { + $scope.activeDateId = dateObject.uid; + return true; + } + return false; + }; + + this.init = function(ngModelCtrl_) { + ngModelCtrl = ngModelCtrl_; + + ngModelCtrl.$render = function() { + self.render(); + }; + }; + + this.render = function() { + if (ngModelCtrl.$viewValue) { + var date = new Date(ngModelCtrl.$viewValue), + isValid = !isNaN(date); + + if (isValid) { + this.activeDate = date; + } else if (!$datepickerSuppressError) { + $log.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.'); + } + } + this.refreshView(); + }; + + this.refreshView = function() { + if (this.element) { + this._refreshView(); + + var date = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null; + ngModelCtrl.$setValidity('dateDisabled', !date || (this.element && !this.isDisabled(date))); + } + }; + + this.createDateObject = function(date, format) { + var model = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null; + return { + date: date, + label: dateFilter(date, format), + selected: model && this.compare(date, model) === 0, + disabled: this.isDisabled(date), + current: this.compare(date, new Date()) === 0, + customClass: this.customClass(date) + }; + }; + + this.isDisabled = function(date) { + return ((this.minDate && this.compare(date, this.minDate) < 0) || (this.maxDate && this.compare(date, this.maxDate) > 0) || ($attrs.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode}))); + }; + + this.customClass = function(date) { + return $scope.customClass({date: date, mode: $scope.datepickerMode}); + }; + + // Split array into smaller arrays + this.split = function(arr, size) { + var arrays = []; + while (arr.length > 0) { + arrays.push(arr.splice(0, size)); + } + return arrays; + }; + + this.fixTimeZone = function(date) { + var hours = date.getHours(); + date.setHours(hours === 23 ? hours + 2 : 0); + }; + + $scope.select = function(date) { + if ($scope.datepickerMode === self.minMode) { + var dt = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : new Date(0, 0, 0, 0, 0, 0, 0); + dt.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); + ngModelCtrl.$setViewValue(dt); + ngModelCtrl.$render(); + } else { + self.activeDate = date; + $scope.datepickerMode = self.modes[self.modes.indexOf($scope.datepickerMode) - 1]; + } + }; + + $scope.move = function(direction) { + var year = self.activeDate.getFullYear() + direction * (self.step.years || 0), + month = self.activeDate.getMonth() + direction * (self.step.months || 0); + self.activeDate.setFullYear(year, month, 1); + self.refreshView(); + }; + + $scope.toggleMode = function(direction) { + direction = direction || 1; + + if (($scope.datepickerMode === self.maxMode && direction === 1) || ($scope.datepickerMode === self.minMode && direction === -1)) { + return; + } + + $scope.datepickerMode = self.modes[self.modes.indexOf($scope.datepickerMode) + direction]; + }; + + // Key event mapper + $scope.keys = { 13: 'enter', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; + + var focusElement = function() { + self.element[0].focus(); + }; + + $scope.$on('uib:datepicker.focus', focusElement); + + $scope.keydown = function(evt) { + var key = $scope.keys[evt.which]; + + if (!key || evt.shiftKey || evt.altKey) { + return; + } + + evt.preventDefault(); + if (!self.shortcutPropagation) { + evt.stopPropagation(); + } + + if (key === 'enter' || key === 'space') { + if (self.isDisabled(self.activeDate)) { + return; // do nothing + } + $scope.select(self.activeDate); + } else if (evt.ctrlKey && (key === 'up' || key === 'down')) { + $scope.toggleMode(key === 'up' ? 1 : -1); + } else { + self.handleKeyDown(key, evt); + self.refreshView(); + } + }; +}]) + +.directive('datepicker', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) { + return { + replace: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/datepicker/datepicker.html'; + }, + scope: { + datepickerMode: '=?', + dateDisabled: '&', + customClass: '&', + shortcutPropagation: '&?' + }, + require: ['datepicker', '^ngModel'], + controller: 'DatepickerController', + controllerAs: 'datepicker', + link: function(scope, element, attrs, ctrls) { + if (!$datepickerSuppressWarning) { + $log.warn('datepicker is now deprecated. Use uib-datepicker instead.'); + } + + var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + datepickerCtrl.init(ngModelCtrl); + } + }; +}]) + +.directive('daypicker', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) { + return { + replace: true, + templateUrl: 'template/datepicker/day.html', + require: ['^datepicker', 'daypicker'], + controller: 'UibDaypickerController', + link: function(scope, element, attrs, ctrls) { + if (!$datepickerSuppressWarning) { + $log.warn('daypicker is now deprecated. Use uib-daypicker instead.'); + } + + var datepickerCtrl = ctrls[0], + daypickerCtrl = ctrls[1]; + + daypickerCtrl.init(datepickerCtrl); + } + }; +}]) + +.directive('monthpicker', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) { + return { + replace: true, + templateUrl: 'template/datepicker/month.html', + require: ['^datepicker', 'monthpicker'], + controller: 'UibMonthpickerController', + link: function(scope, element, attrs, ctrls) { + if (!$datepickerSuppressWarning) { + $log.warn('monthpicker is now deprecated. Use uib-monthpicker instead.'); + } + + var datepickerCtrl = ctrls[0], + monthpickerCtrl = ctrls[1]; + + monthpickerCtrl.init(datepickerCtrl); + } + }; +}]) + +.directive('yearpicker', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) { + return { + replace: true, + templateUrl: 'template/datepicker/year.html', + require: ['^datepicker', 'yearpicker'], + controller: 'UibYearpickerController', + link: function(scope, element, attrs, ctrls) { + if (!$datepickerSuppressWarning) { + $log.warn('yearpicker is now deprecated. Use uib-yearpicker instead.'); + } + + var ctrl = ctrls[0]; + angular.extend(ctrl, ctrls[1]); + ctrl.yearpickerInit(); + + ctrl.refreshView(); + } + }; +}]) + +.directive('datepickerPopup', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) { + return { + require: ['ngModel', 'datepickerPopup'], + controller: 'UibDatepickerPopupController', + scope: { + isOpen: '=?', + currentText: '@', + clearText: '@', + closeText: '@', + dateDisabled: '&', + customClass: '&' + }, + link: function(scope, element, attrs, ctrls) { + if (!$datepickerSuppressWarning) { + $log.warn('datepicker-popup is now deprecated. Use uib-datepicker-popup instead.'); + } + + var ngModel = ctrls[0], + ctrl = ctrls[1]; + + ctrl.init(ngModel); + } + }; +}]) + +.directive('datepickerPopupWrap', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) { + return { + replace: true, + transclude: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/datepicker/popup.html'; + }, + link: function() { + if (!$datepickerSuppressWarning) { + $log.warn('datepicker-popup-wrap is now deprecated. Use uib-datepicker-popup-wrap instead.'); + } + } + }; +}]); + +angular.module('ui.bootstrap.dropdown', ['ui.bootstrap.position']) + +.constant('uibDropdownConfig', { + openClass: 'open' +}) + +.service('uibDropdownService', ['$document', '$rootScope', function($document, $rootScope) { + var openScope = null; + + this.open = function(dropdownScope) { + if (!openScope) { + $document.bind('click', closeDropdown); + $document.bind('keydown', keybindFilter); + } + + if (openScope && openScope !== dropdownScope) { + openScope.isOpen = false; + } + + openScope = dropdownScope; + }; + + this.close = function(dropdownScope) { + if (openScope === dropdownScope) { + openScope = null; + $document.unbind('click', closeDropdown); + $document.unbind('keydown', keybindFilter); + } + }; + + var closeDropdown = function(evt) { + // This method may still be called during the same mouse event that + // unbound this event handler. So check openScope before proceeding. + if (!openScope) { return; } + + if (evt && openScope.getAutoClose() === 'disabled') { return ; } + + var toggleElement = openScope.getToggleElement(); + if (evt && toggleElement && toggleElement[0].contains(evt.target)) { + return; + } + + var dropdownElement = openScope.getDropdownElement(); + if (evt && openScope.getAutoClose() === 'outsideClick' && + dropdownElement && dropdownElement[0].contains(evt.target)) { + return; + } + + openScope.isOpen = false; + + if (!$rootScope.$$phase) { + openScope.$apply(); + } + }; + + var keybindFilter = function(evt) { + if (evt.which === 27) { + openScope.focusToggleElement(); + closeDropdown(); + } else if (openScope.isKeynavEnabled() && /(38|40)/.test(evt.which) && openScope.isOpen) { + evt.preventDefault(); + evt.stopPropagation(); + openScope.focusDropdownEntry(evt.which); + } + }; +}]) + +.controller('UibDropdownController', ['$scope', '$element', '$attrs', '$parse', 'uibDropdownConfig', 'uibDropdownService', '$animate', '$uibPosition', '$document', '$compile', '$templateRequest', function($scope, $element, $attrs, $parse, dropdownConfig, uibDropdownService, $animate, $position, $document, $compile, $templateRequest) { + var self = this, + scope = $scope.$new(), // create a child scope so we are not polluting original one + templateScope, + openClass = dropdownConfig.openClass, + getIsOpen, + setIsOpen = angular.noop, + toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop, + appendToBody = false, + keynavEnabled =false, + selectedOption = null; + + + $element.addClass('dropdown'); + + this.init = function() { + if ($attrs.isOpen) { + getIsOpen = $parse($attrs.isOpen); + setIsOpen = getIsOpen.assign; + + $scope.$watch(getIsOpen, function(value) { + scope.isOpen = !!value; + }); + } + + appendToBody = angular.isDefined($attrs.dropdownAppendToBody); + keynavEnabled = angular.isDefined($attrs.uibKeyboardNav); + + if (appendToBody && self.dropdownMenu) { + $document.find('body').append(self.dropdownMenu); + $element.on('$destroy', function handleDestroyEvent() { + self.dropdownMenu.remove(); + }); + } + }; + + this.toggle = function(open) { + return scope.isOpen = arguments.length ? !!open : !scope.isOpen; + }; + + // Allow other directives to watch status + this.isOpen = function() { + return scope.isOpen; + }; + + scope.getToggleElement = function() { + return self.toggleElement; + }; + + scope.getAutoClose = function() { + return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled' + }; + + scope.getElement = function() { + return $element; + }; + + scope.isKeynavEnabled = function() { + return keynavEnabled; + }; + + scope.focusDropdownEntry = function(keyCode) { + var elems = self.dropdownMenu ? //If append to body is used. + (angular.element(self.dropdownMenu).find('a')) : + (angular.element($element).find('ul').eq(0).find('a')); + + switch (keyCode) { + case (40): { + if (!angular.isNumber(self.selectedOption)) { + self.selectedOption = 0; + } else { + self.selectedOption = (self.selectedOption === elems.length - 1 ? + self.selectedOption : + self.selectedOption + 1); + } + break; + } + case (38): { + if (!angular.isNumber(self.selectedOption)) { + self.selectedOption = elems.length - 1; + } else { + self.selectedOption = self.selectedOption === 0 ? + 0 : self.selectedOption - 1; + } + break; + } + } + elems[self.selectedOption].focus(); + }; + + scope.getDropdownElement = function() { + return self.dropdownMenu; + }; + + scope.focusToggleElement = function() { + if (self.toggleElement) { + self.toggleElement[0].focus(); + } + }; + + scope.$watch('isOpen', function(isOpen, wasOpen) { + if (appendToBody && self.dropdownMenu) { + var pos = $position.positionElements($element, self.dropdownMenu, 'bottom-left', true); + var css = { + top: pos.top + 'px', + display: isOpen ? 'block' : 'none' + }; + + var rightalign = self.dropdownMenu.hasClass('dropdown-menu-right'); + if (!rightalign) { + css.left = pos.left + 'px'; + css.right = 'auto'; + } else { + css.left = 'auto'; + css.right = (window.innerWidth - (pos.left + $element.prop('offsetWidth'))) + 'px'; + } + + self.dropdownMenu.css(css); + } + + $animate[isOpen ? 'addClass' : 'removeClass']($element, openClass).then(function() { + if (angular.isDefined(isOpen) && isOpen !== wasOpen) { + toggleInvoker($scope, { open: !!isOpen }); + } + }); + + if (isOpen) { + if (self.dropdownMenuTemplateUrl) { + $templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) { + templateScope = scope.$new(); + $compile(tplContent.trim())(templateScope, function(dropdownElement) { + var newEl = dropdownElement; + self.dropdownMenu.replaceWith(newEl); + self.dropdownMenu = newEl; + }); + }); + } + + scope.focusToggleElement(); + uibDropdownService.open(scope); + } else { + if (self.dropdownMenuTemplateUrl) { + if (templateScope) { + templateScope.$destroy(); + } + var newEl = angular.element(''); + self.dropdownMenu.replaceWith(newEl); + self.dropdownMenu = newEl; + } + + uibDropdownService.close(scope); + self.selectedOption = null; + } + + if (angular.isFunction(setIsOpen)) { + setIsOpen($scope, isOpen); + } + }); + + $scope.$on('$locationChangeSuccess', function() { + if (scope.getAutoClose() !== 'disabled') { + scope.isOpen = false; + } + }); + + var offDestroy = $scope.$on('$destroy', function() { + scope.$destroy(); + }); + scope.$on('$destroy', offDestroy); +}]) + +.directive('uibDropdown', function() { + return { + controller: 'UibDropdownController', + link: function(scope, element, attrs, dropdownCtrl) { + dropdownCtrl.init(); + } + }; +}) + +.directive('uibDropdownMenu', function() { + return { + restrict: 'AC', + require: '?^uibDropdown', + link: function(scope, element, attrs, dropdownCtrl) { + if (!dropdownCtrl || angular.isDefined(attrs.dropdownNested)) { + return; + } + + element.addClass('dropdown-menu'); + + var tplUrl = attrs.templateUrl; + if (tplUrl) { + dropdownCtrl.dropdownMenuTemplateUrl = tplUrl; + } + + if (!dropdownCtrl.dropdownMenu) { + dropdownCtrl.dropdownMenu = element; + } + } + }; +}) + +.directive('uibKeyboardNav', function() { + return { + restrict: 'A', + require: '?^uibDropdown', + link: function(scope, element, attrs, dropdownCtrl) { + element.bind('keydown', function(e) { + if ([38, 40].indexOf(e.which) !== -1) { + e.preventDefault(); + e.stopPropagation(); + + var elems = dropdownCtrl.dropdownMenu.find('a'); + + switch (e.which) { + case (40): { // Down + if (!angular.isNumber(dropdownCtrl.selectedOption)) { + dropdownCtrl.selectedOption = 0; + } else { + dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === elems.length -1 ? + dropdownCtrl.selectedOption : dropdownCtrl.selectedOption + 1; + } + break; + } + case (38): { // Up + if (!angular.isNumber(dropdownCtrl.selectedOption)) { + dropdownCtrl.selectedOption = elems.length - 1; + } else { + dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === 0 ? + 0 : dropdownCtrl.selectedOption - 1; + } + break; + } + } + elems[dropdownCtrl.selectedOption].focus(); + } + }); + } + }; +}) + +.directive('uibDropdownToggle', function() { + return { + require: '?^uibDropdown', + link: function(scope, element, attrs, dropdownCtrl) { + if (!dropdownCtrl) { + return; + } + + element.addClass('dropdown-toggle'); + + dropdownCtrl.toggleElement = element; + + var toggleDropdown = function(event) { + event.preventDefault(); + + if (!element.hasClass('disabled') && !attrs.disabled) { + scope.$apply(function() { + dropdownCtrl.toggle(); + }); + } + }; + + element.bind('click', toggleDropdown); + + // WAI-ARIA + element.attr({ 'aria-haspopup': true, 'aria-expanded': false }); + scope.$watch(dropdownCtrl.isOpen, function(isOpen) { + element.attr('aria-expanded', !!isOpen); + }); + + scope.$on('$destroy', function() { + element.unbind('click', toggleDropdown); + }); + } + }; +}); + +/* Deprecated dropdown below */ + +angular.module('ui.bootstrap.dropdown') + +.value('$dropdownSuppressWarning', false) + +.service('dropdownService', ['$log', '$dropdownSuppressWarning', 'uibDropdownService', function($log, $dropdownSuppressWarning, uibDropdownService) { + if (!$dropdownSuppressWarning) { + $log.warn('dropdownService is now deprecated. Use uibDropdownService instead.'); + } + + angular.extend(this, uibDropdownService); +}]) + +.controller('DropdownController', ['$scope', '$element', '$attrs', '$parse', 'uibDropdownConfig', 'uibDropdownService', '$animate', '$uibPosition', '$document', '$compile', '$templateRequest', '$log', '$dropdownSuppressWarning', function($scope, $element, $attrs, $parse, dropdownConfig, uibDropdownService, $animate, $position, $document, $compile, $templateRequest, $log, $dropdownSuppressWarning) { + if (!$dropdownSuppressWarning) { + $log.warn('DropdownController is now deprecated. Use UibDropdownController instead.'); + } + + var self = this, + scope = $scope.$new(), // create a child scope so we are not polluting original one + templateScope, + openClass = dropdownConfig.openClass, + getIsOpen, + setIsOpen = angular.noop, + toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop, + appendToBody = false, + keynavEnabled =false, + selectedOption = null; + + + $element.addClass('dropdown'); + + this.init = function() { + if ($attrs.isOpen) { + getIsOpen = $parse($attrs.isOpen); + setIsOpen = getIsOpen.assign; + + $scope.$watch(getIsOpen, function(value) { + scope.isOpen = !!value; + }); + } + + appendToBody = angular.isDefined($attrs.dropdownAppendToBody); + keynavEnabled = angular.isDefined($attrs.uibKeyboardNav); + + if (appendToBody && self.dropdownMenu) { + $document.find('body').append(self.dropdownMenu); + $element.on('$destroy', function handleDestroyEvent() { + self.dropdownMenu.remove(); + }); + } + }; + + this.toggle = function(open) { + return scope.isOpen = arguments.length ? !!open : !scope.isOpen; + }; + + // Allow other directives to watch status + this.isOpen = function() { + return scope.isOpen; + }; + + scope.getToggleElement = function() { + return self.toggleElement; + }; + + scope.getAutoClose = function() { + return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled' + }; + + scope.getElement = function() { + return $element; + }; + + scope.isKeynavEnabled = function() { + return keynavEnabled; + }; + + scope.focusDropdownEntry = function(keyCode) { + var elems = self.dropdownMenu ? //If append to body is used. + (angular.element(self.dropdownMenu).find('a')) : + (angular.element($element).find('ul').eq(0).find('a')); + + switch (keyCode) { + case (40): { + if (!angular.isNumber(self.selectedOption)) { + self.selectedOption = 0; + } else { + self.selectedOption = (self.selectedOption === elems.length -1 ? + self.selectedOption : + self.selectedOption + 1); + } + break; + } + case (38): { + if (!angular.isNumber(self.selectedOption)) { + self.selectedOption = elems.length - 1; + } else { + self.selectedOption = self.selectedOption === 0 ? + 0 : self.selectedOption - 1; + } + break; + } + } + elems[self.selectedOption].focus(); + }; + + scope.getDropdownElement = function() { + return self.dropdownMenu; + }; + + scope.focusToggleElement = function() { + if (self.toggleElement) { + self.toggleElement[0].focus(); + } + }; + + scope.$watch('isOpen', function(isOpen, wasOpen) { + if (appendToBody && self.dropdownMenu) { + var pos = $position.positionElements($element, self.dropdownMenu, 'bottom-left', true); + var css = { + top: pos.top + 'px', + display: isOpen ? 'block' : 'none' + }; + + var rightalign = self.dropdownMenu.hasClass('dropdown-menu-right'); + if (!rightalign) { + css.left = pos.left + 'px'; + css.right = 'auto'; + } else { + css.left = 'auto'; + css.right = (window.innerWidth - (pos.left + $element.prop('offsetWidth'))) + 'px'; + } + + self.dropdownMenu.css(css); + } + + $animate[isOpen ? 'addClass' : 'removeClass']($element, openClass).then(function() { + if (angular.isDefined(isOpen) && isOpen !== wasOpen) { + toggleInvoker($scope, { open: !!isOpen }); + } + }); + + if (isOpen) { + if (self.dropdownMenuTemplateUrl) { + $templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) { + templateScope = scope.$new(); + $compile(tplContent.trim())(templateScope, function(dropdownElement) { + var newEl = dropdownElement; + self.dropdownMenu.replaceWith(newEl); + self.dropdownMenu = newEl; + }); + }); + } + + scope.focusToggleElement(); + uibDropdownService.open(scope); + } else { + if (self.dropdownMenuTemplateUrl) { + if (templateScope) { + templateScope.$destroy(); + } + var newEl = angular.element(''); + self.dropdownMenu.replaceWith(newEl); + self.dropdownMenu = newEl; + } + + uibDropdownService.close(scope); + self.selectedOption = null; + } + + if (angular.isFunction(setIsOpen)) { + setIsOpen($scope, isOpen); + } + }); + + $scope.$on('$locationChangeSuccess', function() { + if (scope.getAutoClose() !== 'disabled') { + scope.isOpen = false; + } + }); + + var offDestroy = $scope.$on('$destroy', function() { + scope.$destroy(); + }); + scope.$on('$destroy', offDestroy); +}]) + +.directive('dropdown', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) { + return { + controller: 'DropdownController', + link: function(scope, element, attrs, dropdownCtrl) { + if (!$dropdownSuppressWarning) { + $log.warn('dropdown is now deprecated. Use uib-dropdown instead.'); + } + + dropdownCtrl.init(); + } + }; +}]) + +.directive('dropdownMenu', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) { + return { + restrict: 'AC', + require: '?^dropdown', + link: function(scope, element, attrs, dropdownCtrl) { + if (!dropdownCtrl || angular.isDefined(attrs.dropdownNested)) { + return; + } + + if (!$dropdownSuppressWarning) { + $log.warn('dropdown-menu is now deprecated. Use uib-dropdown-menu instead.'); + } + + element.addClass('dropdown-menu'); + + var tplUrl = attrs.templateUrl; + if (tplUrl) { + dropdownCtrl.dropdownMenuTemplateUrl = tplUrl; + } + + if (!dropdownCtrl.dropdownMenu) { + dropdownCtrl.dropdownMenu = element; + } + } + }; +}]) + +.directive('keyboardNav', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) { + return { + restrict: 'A', + require: '?^dropdown', + link: function(scope, element, attrs, dropdownCtrl) { + if (!$dropdownSuppressWarning) { + $log.warn('keyboard-nav is now deprecated. Use uib-keyboard-nav instead.'); + } + + element.bind('keydown', function(e) { + if ([38, 40].indexOf(e.which) !== -1) { + e.preventDefault(); + e.stopPropagation(); + + var elems = dropdownCtrl.dropdownMenu.find('a'); + + switch (e.which) { + case (40): { // Down + if (!angular.isNumber(dropdownCtrl.selectedOption)) { + dropdownCtrl.selectedOption = 0; + } else { + dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === elems.length -1 ? + dropdownCtrl.selectedOption : dropdownCtrl.selectedOption + 1; + } + break; + } + case (38): { // Up + if (!angular.isNumber(dropdownCtrl.selectedOption)) { + dropdownCtrl.selectedOption = elems.length - 1; + } else { + dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === 0 ? + 0 : dropdownCtrl.selectedOption - 1; + } + break; + } + } + elems[dropdownCtrl.selectedOption].focus(); + } + }); + } + }; +}]) + +.directive('dropdownToggle', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) { + return { + require: '?^dropdown', + link: function(scope, element, attrs, dropdownCtrl) { + if (!$dropdownSuppressWarning) { + $log.warn('dropdown-toggle is now deprecated. Use uib-dropdown-toggle instead.'); + } + + if (!dropdownCtrl) { + return; + } + + element.addClass('dropdown-toggle'); + + dropdownCtrl.toggleElement = element; + + var toggleDropdown = function(event) { + event.preventDefault(); + + if (!element.hasClass('disabled') && !attrs.disabled) { + scope.$apply(function() { + dropdownCtrl.toggle(); + }); + } + }; + + element.bind('click', toggleDropdown); + + // WAI-ARIA + element.attr({ 'aria-haspopup': true, 'aria-expanded': false }); + scope.$watch(dropdownCtrl.isOpen, function(isOpen) { + element.attr('aria-expanded', !!isOpen); + }); + + scope.$on('$destroy', function() { + element.unbind('click', toggleDropdown); + }); + } + }; +}]); + +angular.module('ui.bootstrap.stackedMap', []) +/** + * A helper, internal data structure that acts as a map but also allows getting / removing + * elements in the LIFO order + */ + .factory('$$stackedMap', function() { + return { + createNew: function() { + var stack = []; + + return { + add: function(key, value) { + stack.push({ + key: key, + value: value + }); + }, + get: function(key) { + for (var i = 0; i < stack.length; i++) { + if (key == stack[i].key) { + return stack[i]; + } + } + }, + keys: function() { + var keys = []; + for (var i = 0; i < stack.length; i++) { + keys.push(stack[i].key); + } + return keys; + }, + top: function() { + return stack[stack.length - 1]; + }, + remove: function(key) { + var idx = -1; + for (var i = 0; i < stack.length; i++) { + if (key == stack[i].key) { + idx = i; + break; + } + } + return stack.splice(idx, 1)[0]; + }, + removeTop: function() { + return stack.splice(stack.length - 1, 1)[0]; + }, + length: function() { + return stack.length; + } + }; + } + }; + }); +angular.module('ui.bootstrap.modal', ['ui.bootstrap.stackedMap']) +/** + * A helper, internal data structure that stores all references attached to key + */ + .factory('$$multiMap', function() { + return { + createNew: function() { + var map = {}; + + return { + entries: function() { + return Object.keys(map).map(function(key) { + return { + key: key, + value: map[key] + }; + }); + }, + get: function(key) { + return map[key]; + }, + hasKey: function(key) { + return !!map[key]; + }, + keys: function() { + return Object.keys(map); + }, + put: function(key, value) { + if (!map[key]) { + map[key] = []; + } + + map[key].push(value); + }, + remove: function(key, value) { + var values = map[key]; + + if (!values) { + return; + } + + var idx = values.indexOf(value); + + if (idx !== -1) { + values.splice(idx, 1); + } + + if (!values.length) { + delete map[key]; + } + } + }; + } + }; + }) + +/** + * A helper directive for the $modal service. It creates a backdrop element. + */ + .directive('uibModalBackdrop', [ + '$animate', '$injector', '$uibModalStack', + function($animate , $injector, $modalStack) { + var $animateCss = null; + + if ($injector.has('$animateCss')) { + $animateCss = $injector.get('$animateCss'); + } + + return { + replace: true, + templateUrl: 'template/modal/backdrop.html', + compile: function(tElement, tAttrs) { + tElement.addClass(tAttrs.backdropClass); + return linkFn; + } + }; + + function linkFn(scope, element, attrs) { + // Temporary fix for prefixing + element.addClass('modal-backdrop'); + + if (attrs.modalInClass) { + if ($animateCss) { + $animateCss(element, { + addClass: attrs.modalInClass + }).start(); + } else { + $animate.addClass(element, attrs.modalInClass); + } + + scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) { + var done = setIsAsync(); + if ($animateCss) { + $animateCss(element, { + removeClass: attrs.modalInClass + }).start().then(done); + } else { + $animate.removeClass(element, attrs.modalInClass).then(done); + } + }); + } + } + }]) + + .directive('uibModalWindow', [ + '$uibModalStack', '$q', '$animate', '$injector', + function($modalStack , $q , $animate, $injector) { + var $animateCss = null; + + if ($injector.has('$animateCss')) { + $animateCss = $injector.get('$animateCss'); + } + + return { + scope: { + index: '@' + }, + replace: true, + transclude: true, + templateUrl: function(tElement, tAttrs) { + return tAttrs.templateUrl || 'template/modal/window.html'; + }, + link: function(scope, element, attrs) { + element.addClass(attrs.windowClass || ''); + element.addClass(attrs.windowTopClass || ''); + scope.size = attrs.size; + + scope.close = function(evt) { + var modal = $modalStack.getTop(); + if (modal && modal.value.backdrop && modal.value.backdrop !== 'static' && (evt.target === evt.currentTarget)) { + evt.preventDefault(); + evt.stopPropagation(); + $modalStack.dismiss(modal.key, 'backdrop click'); + } + }; + + // moved from template to fix issue #2280 + element.on('click', scope.close); + + // This property is only added to the scope for the purpose of detecting when this directive is rendered. + // We can detect that by using this property in the template associated with this directive and then use + // {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}. + scope.$isRendered = true; + + // Deferred object that will be resolved when this modal is render. + var modalRenderDeferObj = $q.defer(); + // Observe function will be called on next digest cycle after compilation, ensuring that the DOM is ready. + // In order to use this way of finding whether DOM is ready, we need to observe a scope property used in modal's template. + attrs.$observe('modalRender', function(value) { + if (value == 'true') { + modalRenderDeferObj.resolve(); + } + }); + + modalRenderDeferObj.promise.then(function() { + var animationPromise = null; + + if (attrs.modalInClass) { + if ($animateCss) { + animationPromise = $animateCss(element, { + addClass: attrs.modalInClass + }).start(); + } else { + animationPromise = $animate.addClass(element, attrs.modalInClass); + } + + scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) { + var done = setIsAsync(); + if ($animateCss) { + $animateCss(element, { + removeClass: attrs.modalInClass + }).start().then(done); + } else { + $animate.removeClass(element, attrs.modalInClass).then(done); + } + }); + } + + + $q.when(animationPromise).then(function() { + var inputWithAutofocus = element[0].querySelector('[autofocus]'); + /** + * Auto-focusing of a freshly-opened modal element causes any child elements + * with the autofocus attribute to lose focus. This is an issue on touch + * based devices which will show and then hide the onscreen keyboard. + * Attempts to refocus the autofocus element via JavaScript will not reopen + * the onscreen keyboard. Fixed by updated the focusing logic to only autofocus + * the modal element if the modal does not contain an autofocus element. + */ + if (inputWithAutofocus) { + inputWithAutofocus.focus(); + } else { + element[0].focus(); + } + }); + + // Notify {@link $modalStack} that modal is rendered. + var modal = $modalStack.getTop(); + if (modal) { + $modalStack.modalRendered(modal.key); + } + }); + } + }; + }]) + + .directive('uibModalAnimationClass', function() { + return { + compile: function(tElement, tAttrs) { + if (tAttrs.modalAnimation) { + tElement.addClass(tAttrs.uibModalAnimationClass); + } + } + }; + }) + + .directive('uibModalTransclude', function() { + return { + link: function($scope, $element, $attrs, controller, $transclude) { + $transclude($scope.$parent, function(clone) { + $element.empty(); + $element.append(clone); + }); + } + }; + }) + + .factory('$uibModalStack', [ + '$animate', '$timeout', '$document', '$compile', '$rootScope', + '$q', + '$injector', + '$$multiMap', + '$$stackedMap', + function($animate , $timeout , $document , $compile , $rootScope , + $q, + $injector, + $$multiMap, + $$stackedMap) { + var $animateCss = null; + + if ($injector.has('$animateCss')) { + $animateCss = $injector.get('$animateCss'); + } + + var OPENED_MODAL_CLASS = 'modal-open'; + + var backdropDomEl, backdropScope; + var openedWindows = $$stackedMap.createNew(); + var openedClasses = $$multiMap.createNew(); + var $modalStack = { + NOW_CLOSING_EVENT: 'modal.stack.now-closing' + }; + + //Modal focus behavior + var focusableElementList; + var focusIndex = 0; + var tababbleSelector = 'a[href], area[href], input:not([disabled]), ' + + 'button:not([disabled]),select:not([disabled]), textarea:not([disabled]), ' + + 'iframe, object, embed, *[tabindex], *[contenteditable=true]'; + + function backdropIndex() { + var topBackdropIndex = -1; + var opened = openedWindows.keys(); + for (var i = 0; i < opened.length; i++) { + if (openedWindows.get(opened[i]).value.backdrop) { + topBackdropIndex = i; + } + } + return topBackdropIndex; + } + + $rootScope.$watch(backdropIndex, function(newBackdropIndex) { + if (backdropScope) { + backdropScope.index = newBackdropIndex; + } + }); + + function removeModalWindow(modalInstance, elementToReceiveFocus) { + var body = $document.find('body').eq(0); + var modalWindow = openedWindows.get(modalInstance).value; + + //clean up the stack + openedWindows.remove(modalInstance); + + removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, function() { + var modalBodyClass = modalWindow.openedClass || OPENED_MODAL_CLASS; + openedClasses.remove(modalBodyClass, modalInstance); + body.toggleClass(modalBodyClass, openedClasses.hasKey(modalBodyClass)); + toggleTopWindowClass(true); + }); + checkRemoveBackdrop(); + + //move focus to specified element if available, or else to body + if (elementToReceiveFocus && elementToReceiveFocus.focus) { + elementToReceiveFocus.focus(); + } else { + body.focus(); + } + } + + // Add or remove "windowTopClass" from the top window in the stack + function toggleTopWindowClass(toggleSwitch) { + var modalWindow; + + if (openedWindows.length() > 0) { + modalWindow = openedWindows.top().value; + modalWindow.modalDomEl.toggleClass(modalWindow.windowTopClass || '', toggleSwitch); + } + } + + function checkRemoveBackdrop() { + //remove backdrop if no longer needed + if (backdropDomEl && backdropIndex() == -1) { + var backdropScopeRef = backdropScope; + removeAfterAnimate(backdropDomEl, backdropScope, function() { + backdropScopeRef = null; + }); + backdropDomEl = undefined; + backdropScope = undefined; + } + } + + function removeAfterAnimate(domEl, scope, done) { + var asyncDeferred; + var asyncPromise = null; + var setIsAsync = function() { + if (!asyncDeferred) { + asyncDeferred = $q.defer(); + asyncPromise = asyncDeferred.promise; + } + + return function asyncDone() { + asyncDeferred.resolve(); + }; + }; + scope.$broadcast($modalStack.NOW_CLOSING_EVENT, setIsAsync); + + // Note that it's intentional that asyncPromise might be null. + // That's when setIsAsync has not been called during the + // NOW_CLOSING_EVENT broadcast. + return $q.when(asyncPromise).then(afterAnimating); + + function afterAnimating() { + if (afterAnimating.done) { + return; + } + afterAnimating.done = true; + + if ($animateCss) { + $animateCss(domEl, { + event: 'leave' + }).start().then(function() { + domEl.remove(); + }); + } else { + $animate.leave(domEl); + } + scope.$destroy(); + if (done) { + done(); + } + } + } + + $document.bind('keydown', function(evt) { + if (evt.isDefaultPrevented()) { + return evt; + } + + var modal = openedWindows.top(); + if (modal && modal.value.keyboard) { + switch (evt.which) { + case 27: { + evt.preventDefault(); + $rootScope.$apply(function() { + $modalStack.dismiss(modal.key, 'escape key press'); + }); + break; + } + case 9: { + $modalStack.loadFocusElementList(modal); + var focusChanged = false; + if (evt.shiftKey) { + if ($modalStack.isFocusInFirstItem(evt)) { + focusChanged = $modalStack.focusLastFocusableElement(); + } + } else { + if ($modalStack.isFocusInLastItem(evt)) { + focusChanged = $modalStack.focusFirstFocusableElement(); + } + } + + if (focusChanged) { + evt.preventDefault(); + evt.stopPropagation(); + } + break; + } + } + } + }); + + $modalStack.open = function(modalInstance, modal) { + var modalOpener = $document[0].activeElement, + modalBodyClass = modal.openedClass || OPENED_MODAL_CLASS; + + toggleTopWindowClass(false); + + openedWindows.add(modalInstance, { + deferred: modal.deferred, + renderDeferred: modal.renderDeferred, + modalScope: modal.scope, + backdrop: modal.backdrop, + keyboard: modal.keyboard, + openedClass: modal.openedClass, + windowTopClass: modal.windowTopClass + }); + + openedClasses.put(modalBodyClass, modalInstance); + + var body = $document.find('body').eq(0), + currBackdropIndex = backdropIndex(); + + if (currBackdropIndex >= 0 && !backdropDomEl) { + backdropScope = $rootScope.$new(true); + backdropScope.index = currBackdropIndex; + var angularBackgroundDomEl = angular.element('
'); + angularBackgroundDomEl.attr('backdrop-class', modal.backdropClass); + if (modal.animation) { + angularBackgroundDomEl.attr('modal-animation', 'true'); + } + backdropDomEl = $compile(angularBackgroundDomEl)(backdropScope); + body.append(backdropDomEl); + } + + var angularDomEl = angular.element('
'); + angularDomEl.attr({ + 'template-url': modal.windowTemplateUrl, + 'window-class': modal.windowClass, + 'window-top-class': modal.windowTopClass, + 'size': modal.size, + 'index': openedWindows.length() - 1, + 'animate': 'animate' + }).html(modal.content); + if (modal.animation) { + angularDomEl.attr('modal-animation', 'true'); + } + + var modalDomEl = $compile(angularDomEl)(modal.scope); + openedWindows.top().value.modalDomEl = modalDomEl; + openedWindows.top().value.modalOpener = modalOpener; + body.append(modalDomEl); + body.addClass(modalBodyClass); + + $modalStack.clearFocusListCache(); + }; + + function broadcastClosing(modalWindow, resultOrReason, closing) { + return !modalWindow.value.modalScope.$broadcast('modal.closing', resultOrReason, closing).defaultPrevented; + } + + $modalStack.close = function(modalInstance, result) { + var modalWindow = openedWindows.get(modalInstance); + if (modalWindow && broadcastClosing(modalWindow, result, true)) { + modalWindow.value.modalScope.$$uibDestructionScheduled = true; + modalWindow.value.deferred.resolve(result); + removeModalWindow(modalInstance, modalWindow.value.modalOpener); + return true; + } + return !modalWindow; + }; + + $modalStack.dismiss = function(modalInstance, reason) { + var modalWindow = openedWindows.get(modalInstance); + if (modalWindow && broadcastClosing(modalWindow, reason, false)) { + modalWindow.value.modalScope.$$uibDestructionScheduled = true; + modalWindow.value.deferred.reject(reason); + removeModalWindow(modalInstance, modalWindow.value.modalOpener); + return true; + } + return !modalWindow; + }; + + $modalStack.dismissAll = function(reason) { + var topModal = this.getTop(); + while (topModal && this.dismiss(topModal.key, reason)) { + topModal = this.getTop(); + } + }; + + $modalStack.getTop = function() { + return openedWindows.top(); + }; + + $modalStack.modalRendered = function(modalInstance) { + var modalWindow = openedWindows.get(modalInstance); + if (modalWindow) { + modalWindow.value.renderDeferred.resolve(); + } + }; + + $modalStack.focusFirstFocusableElement = function() { + if (focusableElementList.length > 0) { + focusableElementList[0].focus(); + return true; + } + return false; + }; + $modalStack.focusLastFocusableElement = function() { + if (focusableElementList.length > 0) { + focusableElementList[focusableElementList.length - 1].focus(); + return true; + } + return false; + }; + + $modalStack.isFocusInFirstItem = function(evt) { + if (focusableElementList.length > 0) { + return (evt.target || evt.srcElement) == focusableElementList[0]; + } + return false; + }; + + $modalStack.isFocusInLastItem = function(evt) { + if (focusableElementList.length > 0) { + return (evt.target || evt.srcElement) == focusableElementList[focusableElementList.length - 1]; + } + return false; + }; + + $modalStack.clearFocusListCache = function() { + focusableElementList = []; + focusIndex = 0; + }; + + $modalStack.loadFocusElementList = function(modalWindow) { + if (focusableElementList === undefined || !focusableElementList.length) { + if (modalWindow) { + var modalDomE1 = modalWindow.value.modalDomEl; + if (modalDomE1 && modalDomE1.length) { + focusableElementList = modalDomE1[0].querySelectorAll(tababbleSelector); + } + } + } + }; + + return $modalStack; + }]) + + .provider('$uibModal', function() { + var $modalProvider = { + options: { + animation: true, + backdrop: true, //can also be false or 'static' + keyboard: true + }, + $get: ['$injector', '$rootScope', '$q', '$templateRequest', '$controller', '$uibModalStack', '$modalSuppressWarning', '$log', + function ($injector, $rootScope, $q, $templateRequest, $controller, $modalStack, $modalSuppressWarning, $log) { + var $modal = {}; + + function getTemplatePromise(options) { + return options.template ? $q.when(options.template) : + $templateRequest(angular.isFunction(options.templateUrl) ? (options.templateUrl)() : options.templateUrl); + } + + function getResolvePromises(resolves) { + var promisesArr = []; + angular.forEach(resolves, function(value) { + if (angular.isFunction(value) || angular.isArray(value)) { + promisesArr.push($q.when($injector.invoke(value))); + } else if (angular.isString(value)) { + promisesArr.push($q.when($injector.get(value))); + } else { + promisesArr.push($q.when(value)); + } + }); + return promisesArr; + } + + var promiseChain = null; + $modal.getPromiseChain = function() { + return promiseChain; + }; + + $modal.open = function(modalOptions) { + var modalResultDeferred = $q.defer(); + var modalOpenedDeferred = $q.defer(); + var modalRenderDeferred = $q.defer(); + + //prepare an instance of a modal to be injected into controllers and returned to a caller + var modalInstance = { + result: modalResultDeferred.promise, + opened: modalOpenedDeferred.promise, + rendered: modalRenderDeferred.promise, + close: function (result) { + return $modalStack.close(modalInstance, result); + }, + dismiss: function (reason) { + return $modalStack.dismiss(modalInstance, reason); + } + }; + + //merge and clean up options + modalOptions = angular.extend({}, $modalProvider.options, modalOptions); + modalOptions.resolve = modalOptions.resolve || {}; + + //verify options + if (!modalOptions.template && !modalOptions.templateUrl) { + throw new Error('One of template or templateUrl options is required.'); + } + + var templateAndResolvePromise = + $q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve))); + + function resolveWithTemplate() { + return templateAndResolvePromise; + } + + // Wait for the resolution of the existing promise chain. + // Then switch to our own combined promise dependency (regardless of how the previous modal fared). + // Then add to $modalStack and resolve opened. + // Finally clean up the chain variable if no subsequent modal has overwritten it. + var samePromise; + samePromise = promiseChain = $q.all([promiseChain]) + .then(resolveWithTemplate, resolveWithTemplate) + .then(function resolveSuccess(tplAndVars) { + + var modalScope = (modalOptions.scope || $rootScope).$new(); + modalScope.$close = modalInstance.close; + modalScope.$dismiss = modalInstance.dismiss; + + modalScope.$on('$destroy', function() { + if (!modalScope.$$uibDestructionScheduled) { + modalScope.$dismiss('$uibUnscheduledDestruction'); + } + }); + + var ctrlInstance, ctrlLocals = {}; + var resolveIter = 1; + + //controllers + if (modalOptions.controller) { + ctrlLocals.$scope = modalScope; + ctrlLocals.$uibModalInstance = modalInstance; + Object.defineProperty(ctrlLocals, '$modalInstance', { + get: function() { + if (!$modalSuppressWarning) { + $log.warn('$modalInstance is now deprecated. Use $uibModalInstance instead.'); + } + + return modalInstance; + } + }); + angular.forEach(modalOptions.resolve, function(value, key) { + ctrlLocals[key] = tplAndVars[resolveIter++]; + }); + + ctrlInstance = $controller(modalOptions.controller, ctrlLocals); + if (modalOptions.controllerAs) { + if (modalOptions.bindToController) { + angular.extend(ctrlInstance, modalScope); + } + + modalScope[modalOptions.controllerAs] = ctrlInstance; + } + } + + $modalStack.open(modalInstance, { + scope: modalScope, + deferred: modalResultDeferred, + renderDeferred: modalRenderDeferred, + content: tplAndVars[0], + animation: modalOptions.animation, + backdrop: modalOptions.backdrop, + keyboard: modalOptions.keyboard, + backdropClass: modalOptions.backdropClass, + windowTopClass: modalOptions.windowTopClass, + windowClass: modalOptions.windowClass, + windowTemplateUrl: modalOptions.windowTemplateUrl, + size: modalOptions.size, + openedClass: modalOptions.openedClass + }); + modalOpenedDeferred.resolve(true); + + }, function resolveError(reason) { + modalOpenedDeferred.reject(reason); + modalResultDeferred.reject(reason); + }) + .finally(function() { + if (promiseChain === samePromise) { + promiseChain = null; + } + }); + + return modalInstance; + }; + + return $modal; + } + ] + }; + + return $modalProvider; + }); + +/* deprecated modal below */ + +angular.module('ui.bootstrap.modal') + + .value('$modalSuppressWarning', false) + + /** + * A helper directive for the $modal service. It creates a backdrop element. + */ + .directive('modalBackdrop', [ + '$animate', '$injector', '$modalStack', '$log', '$modalSuppressWarning', + function($animate , $injector, $modalStack, $log, $modalSuppressWarning) { + var $animateCss = null; + + if ($injector.has('$animateCss')) { + $animateCss = $injector.get('$animateCss'); + } + + return { + replace: true, + templateUrl: 'template/modal/backdrop.html', + compile: function(tElement, tAttrs) { + tElement.addClass(tAttrs.backdropClass); + return linkFn; + } + }; + + function linkFn(scope, element, attrs) { + if (!$modalSuppressWarning) { + $log.warn('modal-backdrop is now deprecated. Use uib-modal-backdrop instead.'); + } + element.addClass('modal-backdrop'); + + if (attrs.modalInClass) { + if ($animateCss) { + $animateCss(element, { + addClass: attrs.modalInClass + }).start(); + } else { + $animate.addClass(element, attrs.modalInClass); + } + + scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) { + var done = setIsAsync(); + if ($animateCss) { + $animateCss(element, { + removeClass: attrs.modalInClass + }).start().then(done); + } else { + $animate.removeClass(element, attrs.modalInClass).then(done); + } + }); + } + } + }]) + + .directive('modalWindow', [ + '$modalStack', '$q', '$animate', '$injector', '$log', '$modalSuppressWarning', + function($modalStack , $q , $animate, $injector, $log, $modalSuppressWarning) { + var $animateCss = null; + + if ($injector.has('$animateCss')) { + $animateCss = $injector.get('$animateCss'); + } + + return { + scope: { + index: '@' + }, + replace: true, + transclude: true, + templateUrl: function(tElement, tAttrs) { + return tAttrs.templateUrl || 'template/modal/window.html'; + }, + link: function(scope, element, attrs) { + if (!$modalSuppressWarning) { + $log.warn('modal-window is now deprecated. Use uib-modal-window instead.'); + } + element.addClass(attrs.windowClass || ''); + element.addClass(attrs.windowTopClass || ''); + scope.size = attrs.size; + + scope.close = function(evt) { + var modal = $modalStack.getTop(); + if (modal && modal.value.backdrop && modal.value.backdrop !== 'static' && (evt.target === evt.currentTarget)) { + evt.preventDefault(); + evt.stopPropagation(); + $modalStack.dismiss(modal.key, 'backdrop click'); + } + }; + + // moved from template to fix issue #2280 + element.on('click', scope.close); + + // This property is only added to the scope for the purpose of detecting when this directive is rendered. + // We can detect that by using this property in the template associated with this directive and then use + // {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}. + scope.$isRendered = true; + + // Deferred object that will be resolved when this modal is render. + var modalRenderDeferObj = $q.defer(); + // Observe function will be called on next digest cycle after compilation, ensuring that the DOM is ready. + // In order to use this way of finding whether DOM is ready, we need to observe a scope property used in modal's template. + attrs.$observe('modalRender', function(value) { + if (value == 'true') { + modalRenderDeferObj.resolve(); + } + }); + + modalRenderDeferObj.promise.then(function() { + var animationPromise = null; + + if (attrs.modalInClass) { + if ($animateCss) { + animationPromise = $animateCss(element, { + addClass: attrs.modalInClass + }).start(); + } else { + animationPromise = $animate.addClass(element, attrs.modalInClass); + } + + scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) { + var done = setIsAsync(); + if ($animateCss) { + $animateCss(element, { + removeClass: attrs.modalInClass + }).start().then(done); + } else { + $animate.removeClass(element, attrs.modalInClass).then(done); + } + }); + } + + + $q.when(animationPromise).then(function() { + var inputWithAutofocus = element[0].querySelector('[autofocus]'); + /** + * Auto-focusing of a freshly-opened modal element causes any child elements + * with the autofocus attribute to lose focus. This is an issue on touch + * based devices which will show and then hide the onscreen keyboard. + * Attempts to refocus the autofocus element via JavaScript will not reopen + * the onscreen keyboard. Fixed by updated the focusing logic to only autofocus + * the modal element if the modal does not contain an autofocus element. + */ + if (inputWithAutofocus) { + inputWithAutofocus.focus(); + } else { + element[0].focus(); + } + }); + + // Notify {@link $modalStack} that modal is rendered. + var modal = $modalStack.getTop(); + if (modal) { + $modalStack.modalRendered(modal.key); + } + }); + } + }; + }]) + + .directive('modalAnimationClass', [ + '$log', '$modalSuppressWarning', + function ($log, $modalSuppressWarning) { + return { + compile: function(tElement, tAttrs) { + if (!$modalSuppressWarning) { + $log.warn('modal-animation-class is now deprecated. Use uib-modal-animation-class instead.'); + } + if (tAttrs.modalAnimation) { + tElement.addClass(tAttrs.modalAnimationClass); + } + } + }; + }]) + + .directive('modalTransclude', [ + '$log', '$modalSuppressWarning', + function ($log, $modalSuppressWarning) { + return { + link: function($scope, $element, $attrs, controller, $transclude) { + if (!$modalSuppressWarning) { + $log.warn('modal-transclude is now deprecated. Use uib-modal-transclude instead.'); + } + $transclude($scope.$parent, function(clone) { + $element.empty(); + $element.append(clone); + }); + } + }; + }]) + + .service('$modalStack', [ + '$animate', '$timeout', '$document', '$compile', '$rootScope', + '$q', + '$injector', + '$$multiMap', + '$$stackedMap', + '$uibModalStack', + '$log', + '$modalSuppressWarning', + function($animate , $timeout , $document , $compile , $rootScope , + $q, + $injector, + $$multiMap, + $$stackedMap, + $uibModalStack, + $log, + $modalSuppressWarning) { + if (!$modalSuppressWarning) { + $log.warn('$modalStack is now deprecated. Use $uibModalStack instead.'); + } + + angular.extend(this, $uibModalStack); + }]) + + .provider('$modal', ['$uibModalProvider', function($uibModalProvider) { + angular.extend(this, $uibModalProvider); + + this.$get = ['$injector', '$log', '$modalSuppressWarning', + function ($injector, $log, $modalSuppressWarning) { + if (!$modalSuppressWarning) { + $log.warn('$modal is now deprecated. Use $uibModal instead.'); + } + + return $injector.invoke($uibModalProvider.$get); + }]; + }]); + +angular.module('ui.bootstrap.pagination', []) +.controller('UibPaginationController', ['$scope', '$attrs', '$parse', function($scope, $attrs, $parse) { + var self = this, + ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl + setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop; + + this.init = function(ngModelCtrl_, config) { + ngModelCtrl = ngModelCtrl_; + this.config = config; + + ngModelCtrl.$render = function() { + self.render(); + }; + + if ($attrs.itemsPerPage) { + $scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) { + self.itemsPerPage = parseInt(value, 10); + $scope.totalPages = self.calculateTotalPages(); + }); + } else { + this.itemsPerPage = config.itemsPerPage; + } + + $scope.$watch('totalItems', function() { + $scope.totalPages = self.calculateTotalPages(); + }); + + $scope.$watch('totalPages', function(value) { + setNumPages($scope.$parent, value); // Readonly variable + + if ( $scope.page > value ) { + $scope.selectPage(value); + } else { + ngModelCtrl.$render(); + } + }); + }; + + this.calculateTotalPages = function() { + var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage); + return Math.max(totalPages || 0, 1); + }; + + this.render = function() { + $scope.page = parseInt(ngModelCtrl.$viewValue, 10) || 1; + }; + + $scope.selectPage = function(page, evt) { + if (evt) { + evt.preventDefault(); + } + + var clickAllowed = !$scope.ngDisabled || !evt; + if (clickAllowed && $scope.page !== page && page > 0 && page <= $scope.totalPages) { + if (evt && evt.target) { + evt.target.blur(); + } + ngModelCtrl.$setViewValue(page); + ngModelCtrl.$render(); + } + }; + + $scope.getText = function(key) { + return $scope[key + 'Text'] || self.config[key + 'Text']; + }; + + $scope.noPrevious = function() { + return $scope.page === 1; + }; + + $scope.noNext = function() { + return $scope.page === $scope.totalPages; + }; +}]) + +.constant('uibPaginationConfig', { + itemsPerPage: 10, + boundaryLinks: false, + directionLinks: true, + firstText: 'First', + previousText: 'Previous', + nextText: 'Next', + lastText: 'Last', + rotate: true +}) + +.directive('uibPagination', ['$parse', 'uibPaginationConfig', function($parse, paginationConfig) { + return { + restrict: 'EA', + scope: { + totalItems: '=', + firstText: '@', + previousText: '@', + nextText: '@', + lastText: '@', + ngDisabled:'=' + }, + require: ['uibPagination', '?ngModel'], + controller: 'UibPaginationController', + controllerAs: 'pagination', + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/pagination/pagination.html'; + }, + replace: true, + link: function(scope, element, attrs, ctrls) { + var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + if (!ngModelCtrl) { + return; // do nothing if no ng-model + } + + // Setup configuration parameters + var maxSize = angular.isDefined(attrs.maxSize) ? scope.$parent.$eval(attrs.maxSize) : paginationConfig.maxSize, + rotate = angular.isDefined(attrs.rotate) ? scope.$parent.$eval(attrs.rotate) : paginationConfig.rotate; + scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : paginationConfig.boundaryLinks; + scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : paginationConfig.directionLinks; + + paginationCtrl.init(ngModelCtrl, paginationConfig); + + if (attrs.maxSize) { + scope.$parent.$watch($parse(attrs.maxSize), function(value) { + maxSize = parseInt(value, 10); + paginationCtrl.render(); + }); + } + + // Create page object used in template + function makePage(number, text, isActive) { + return { + number: number, + text: text, + active: isActive + }; + } + + function getPages(currentPage, totalPages) { + var pages = []; + + // Default page limits + var startPage = 1, endPage = totalPages; + var isMaxSized = angular.isDefined(maxSize) && maxSize < totalPages; + + // recompute if maxSize + if (isMaxSized) { + if (rotate) { + // Current page is displayed in the middle of the visible ones + startPage = Math.max(currentPage - Math.floor(maxSize/2), 1); + endPage = startPage + maxSize - 1; + + // Adjust if limit is exceeded + if (endPage > totalPages) { + endPage = totalPages; + startPage = endPage - maxSize + 1; + } + } else { + // Visible pages are paginated with maxSize + startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1; + + // Adjust last page if limit is exceeded + endPage = Math.min(startPage + maxSize - 1, totalPages); + } + } + + // Add page number links + for (var number = startPage; number <= endPage; number++) { + var page = makePage(number, number, number === currentPage); + pages.push(page); + } + + // Add links to move between page sets + if (isMaxSized && ! rotate) { + if (startPage > 1) { + var previousPageSet = makePage(startPage - 1, '...', false); + pages.unshift(previousPageSet); + } + + if (endPage < totalPages) { + var nextPageSet = makePage(endPage + 1, '...', false); + pages.push(nextPageSet); + } + } + + return pages; + } + + var originalRender = paginationCtrl.render; + paginationCtrl.render = function() { + originalRender(); + if (scope.page > 0 && scope.page <= scope.totalPages) { + scope.pages = getPages(scope.page, scope.totalPages); + } + }; + } + }; +}]) + +.constant('uibPagerConfig', { + itemsPerPage: 10, + previousText: '« Previous', + nextText: 'Next »', + align: true +}) + +.directive('uibPager', ['uibPagerConfig', function(pagerConfig) { + return { + restrict: 'EA', + scope: { + totalItems: '=', + previousText: '@', + nextText: '@', + ngDisabled: '=' + }, + require: ['uibPager', '?ngModel'], + controller: 'UibPaginationController', + controllerAs: 'pagination', + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/pagination/pager.html'; + }, + replace: true, + link: function(scope, element, attrs, ctrls) { + var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + if (!ngModelCtrl) { + return; // do nothing if no ng-model + } + + scope.align = angular.isDefined(attrs.align) ? scope.$parent.$eval(attrs.align) : pagerConfig.align; + paginationCtrl.init(ngModelCtrl, pagerConfig); + } + }; +}]); + +/* Deprecated Pagination Below */ + +angular.module('ui.bootstrap.pagination') +.value('$paginationSuppressWarning', false) +.controller('PaginationController', ['$scope', '$attrs', '$parse', '$log', '$paginationSuppressWarning', function($scope, $attrs, $parse, $log, $paginationSuppressWarning) { + if (!$paginationSuppressWarning) { + $log.warn('PaginationController is now deprecated. Use UibPaginationController instead.'); + } + + var self = this, + ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl + setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop; + + this.init = function(ngModelCtrl_, config) { + ngModelCtrl = ngModelCtrl_; + this.config = config; + + ngModelCtrl.$render = function() { + self.render(); + }; + + if ($attrs.itemsPerPage) { + $scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) { + self.itemsPerPage = parseInt(value, 10); + $scope.totalPages = self.calculateTotalPages(); + }); + } else { + this.itemsPerPage = config.itemsPerPage; + } + + $scope.$watch('totalItems', function() { + $scope.totalPages = self.calculateTotalPages(); + }); + + $scope.$watch('totalPages', function(value) { + setNumPages($scope.$parent, value); // Readonly variable + + if ( $scope.page > value ) { + $scope.selectPage(value); + } else { + ngModelCtrl.$render(); + } + }); + }; + + this.calculateTotalPages = function() { + var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage); + return Math.max(totalPages || 0, 1); + }; + + this.render = function() { + $scope.page = parseInt(ngModelCtrl.$viewValue, 10) || 1; + }; + + $scope.selectPage = function(page, evt) { + if (evt) { + evt.preventDefault(); + } + + var clickAllowed = !$scope.ngDisabled || !evt; + if (clickAllowed && $scope.page !== page && page > 0 && page <= $scope.totalPages) { + if (evt && evt.target) { + evt.target.blur(); + } + ngModelCtrl.$setViewValue(page); + ngModelCtrl.$render(); + } + }; + + $scope.getText = function(key) { + return $scope[key + 'Text'] || self.config[key + 'Text']; + }; + + $scope.noPrevious = function() { + return $scope.page === 1; + }; + + $scope.noNext = function() { + return $scope.page === $scope.totalPages; + }; +}]) +.directive('pagination', ['$parse', 'uibPaginationConfig', '$log', '$paginationSuppressWarning', function($parse, paginationConfig, $log, $paginationSuppressWarning) { + return { + restrict: 'EA', + scope: { + totalItems: '=', + firstText: '@', + previousText: '@', + nextText: '@', + lastText: '@', + ngDisabled:'=' + }, + require: ['pagination', '?ngModel'], + controller: 'PaginationController', + controllerAs: 'pagination', + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/pagination/pagination.html'; + }, + replace: true, + link: function(scope, element, attrs, ctrls) { + if (!$paginationSuppressWarning) { + $log.warn('pagination is now deprecated. Use uib-pagination instead.'); + } + var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + if (!ngModelCtrl) { + return; // do nothing if no ng-model + } + + // Setup configuration parameters + var maxSize = angular.isDefined(attrs.maxSize) ? scope.$parent.$eval(attrs.maxSize) : paginationConfig.maxSize, + rotate = angular.isDefined(attrs.rotate) ? scope.$parent.$eval(attrs.rotate) : paginationConfig.rotate; + scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : paginationConfig.boundaryLinks; + scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : paginationConfig.directionLinks; + + paginationCtrl.init(ngModelCtrl, paginationConfig); + + if (attrs.maxSize) { + scope.$parent.$watch($parse(attrs.maxSize), function(value) { + maxSize = parseInt(value, 10); + paginationCtrl.render(); + }); + } + + // Create page object used in template + function makePage(number, text, isActive) { + return { + number: number, + text: text, + active: isActive + }; + } + + function getPages(currentPage, totalPages) { + var pages = []; + + // Default page limits + var startPage = 1, endPage = totalPages; + var isMaxSized = angular.isDefined(maxSize) && maxSize < totalPages; + + // recompute if maxSize + if (isMaxSized) { + if (rotate) { + // Current page is displayed in the middle of the visible ones + startPage = Math.max(currentPage - Math.floor(maxSize/2), 1); + endPage = startPage + maxSize - 1; + + // Adjust if limit is exceeded + if (endPage > totalPages) { + endPage = totalPages; + startPage = endPage - maxSize + 1; + } + } else { + // Visible pages are paginated with maxSize + startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1; + + // Adjust last page if limit is exceeded + endPage = Math.min(startPage + maxSize - 1, totalPages); + } + } + + // Add page number links + for (var number = startPage; number <= endPage; number++) { + var page = makePage(number, number, number === currentPage); + pages.push(page); + } + + // Add links to move between page sets + if (isMaxSized && ! rotate) { + if (startPage > 1) { + var previousPageSet = makePage(startPage - 1, '...', false); + pages.unshift(previousPageSet); + } + + if (endPage < totalPages) { + var nextPageSet = makePage(endPage + 1, '...', false); + pages.push(nextPageSet); + } + } + + return pages; + } + + var originalRender = paginationCtrl.render; + paginationCtrl.render = function() { + originalRender(); + if (scope.page > 0 && scope.page <= scope.totalPages) { + scope.pages = getPages(scope.page, scope.totalPages); + } + }; + } + }; +}]) + +.directive('pager', ['uibPagerConfig', '$log', '$paginationSuppressWarning', function(pagerConfig, $log, $paginationSuppressWarning) { + return { + restrict: 'EA', + scope: { + totalItems: '=', + previousText: '@', + nextText: '@', + ngDisabled: '=' + }, + require: ['pager', '?ngModel'], + controller: 'PaginationController', + controllerAs: 'pagination', + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/pagination/pager.html'; + }, + replace: true, + link: function(scope, element, attrs, ctrls) { + if (!$paginationSuppressWarning) { + $log.warn('pager is now deprecated. Use uib-pager instead.'); + } + var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + if (!ngModelCtrl) { + return; // do nothing if no ng-model + } + + scope.align = angular.isDefined(attrs.align) ? scope.$parent.$eval(attrs.align) : pagerConfig.align; + paginationCtrl.init(ngModelCtrl, pagerConfig); + } + }; +}]); + +/** + * The following features are still outstanding: animation as a + * function, placement as a function, inside, support for more triggers than + * just mouse enter/leave, html tooltips, and selector delegation. + */ +angular.module('ui.bootstrap.tooltip', ['ui.bootstrap.position', 'ui.bootstrap.stackedMap']) + +/** + * The $tooltip service creates tooltip- and popover-like directives as well as + * houses global options for them. + */ +.provider('$uibTooltip', function() { + // The default options tooltip and popover. + var defaultOptions = { + placement: 'top', + animation: true, + popupDelay: 0, + popupCloseDelay: 0, + useContentExp: false + }; + + // Default hide triggers for each show trigger + var triggerMap = { + 'mouseenter': 'mouseleave', + 'click': 'click', + 'focus': 'blur', + 'none': '' + }; + + // The options specified to the provider globally. + var globalOptions = {}; + + /** + * `options({})` allows global configuration of all tooltips in the + * application. + * + * var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) { + * // place tooltips left instead of top by default + * $tooltipProvider.options( { placement: 'left' } ); + * }); + */ + this.options = function(value) { + angular.extend(globalOptions, value); + }; + + /** + * This allows you to extend the set of trigger mappings available. E.g.: + * + * $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' ); + */ + this.setTriggers = function setTriggers(triggers) { + angular.extend(triggerMap, triggers); + }; + + /** + * This is a helper function for translating camel-case to snake-case. + */ + function snake_case(name) { + var regexp = /[A-Z]/g; + var separator = '-'; + return name.replace(regexp, function(letter, pos) { + return (pos ? separator : '') + letter.toLowerCase(); + }); + } + + /** + * Returns the actual instance of the $tooltip service. + * TODO support multiple triggers + */ + this.$get = ['$window', '$compile', '$timeout', '$document', '$uibPosition', '$interpolate', '$rootScope', '$parse', '$$stackedMap', function($window, $compile, $timeout, $document, $position, $interpolate, $rootScope, $parse, $$stackedMap) { + var openedTooltips = $$stackedMap.createNew(); + $document.on('keypress', function(e) { + if (e.which === 27) { + var last = openedTooltips.top(); + if (last) { + last.value.close(); + openedTooltips.removeTop(); + last = null; + } + } + }); + + return function $tooltip(ttType, prefix, defaultTriggerShow, options) { + options = angular.extend({}, defaultOptions, globalOptions, options); + + /** + * Returns an object of show and hide triggers. + * + * If a trigger is supplied, + * it is used to show the tooltip; otherwise, it will use the `trigger` + * option passed to the `$tooltipProvider.options` method; else it will + * default to the trigger supplied to this directive factory. + * + * The hide trigger is based on the show trigger. If the `trigger` option + * was passed to the `$tooltipProvider.options` method, it will use the + * mapped trigger from `triggerMap` or the passed trigger if the map is + * undefined; otherwise, it uses the `triggerMap` value of the show + * trigger; else it will just use the show trigger. + */ + function getTriggers(trigger) { + var show = (trigger || options.trigger || defaultTriggerShow).split(' '); + var hide = show.map(function(trigger) { + return triggerMap[trigger] || trigger; + }); + return { + show: show, + hide: hide + }; + } + + var directiveName = snake_case(ttType); + + var startSym = $interpolate.startSymbol(); + var endSym = $interpolate.endSymbol(); + var template = + '
' + + '
'; + + return { + compile: function(tElem, tAttrs) { + var tooltipLinker = $compile(template); + + return function link(scope, element, attrs, tooltipCtrl) { + var tooltip; + var tooltipLinkedScope; + var transitionTimeout; + var showTimeout; + var hideTimeout; + var positionTimeout; + var appendToBody = angular.isDefined(options.appendToBody) ? options.appendToBody : false; + var triggers = getTriggers(undefined); + var hasEnableExp = angular.isDefined(attrs[prefix + 'Enable']); + var ttScope = scope.$new(true); + var repositionScheduled = false; + var isOpenParse = angular.isDefined(attrs[prefix + 'IsOpen']) ? $parse(attrs[prefix + 'IsOpen']) : false; + var contentParse = options.useContentExp ? $parse(attrs[ttType]) : false; + var observers = []; + + var positionTooltip = function() { + // check if tooltip exists and is not empty + if (!tooltip || !tooltip.html()) { return; } + + if (!positionTimeout) { + positionTimeout = $timeout(function() { + // Reset the positioning. + tooltip.css({ top: 0, left: 0 }); + + // Now set the calculated positioning. + var ttCss = $position.positionElements(element, tooltip, ttScope.placement, appendToBody); + ttCss.top += 'px'; + ttCss.left += 'px'; + ttCss.visibility = 'visible'; + tooltip.css(ttCss); + + positionTimeout = null; + }, 0, false); + } + }; + + // Set up the correct scope to allow transclusion later + ttScope.origScope = scope; + + // By default, the tooltip is not open. + // TODO add ability to start tooltip opened + ttScope.isOpen = false; + openedTooltips.add(ttScope, { + close: hide + }); + + function toggleTooltipBind() { + if (!ttScope.isOpen) { + showTooltipBind(); + } else { + hideTooltipBind(); + } + } + + // Show the tooltip with delay if specified, otherwise show it immediately + function showTooltipBind() { + if (hasEnableExp && !scope.$eval(attrs[prefix + 'Enable'])) { + return; + } + + cancelHide(); + prepareTooltip(); + + if (ttScope.popupDelay) { + // Do nothing if the tooltip was already scheduled to pop-up. + // This happens if show is triggered multiple times before any hide is triggered. + if (!showTimeout) { + showTimeout = $timeout(show, ttScope.popupDelay, false); + } + } else { + show(); + } + } + + function hideTooltipBind() { + cancelShow(); + + if (ttScope.popupCloseDelay) { + if (!hideTimeout) { + hideTimeout = $timeout(hide, ttScope.popupCloseDelay, false); + } + } else { + hide(); + } + } + + // Show the tooltip popup element. + function show() { + cancelShow(); + cancelHide(); + + // Don't show empty tooltips. + if (!ttScope.content) { + return angular.noop; + } + + createTooltip(); + + // And show the tooltip. + ttScope.$evalAsync(function() { + ttScope.isOpen = true; + assignIsOpen(true); + positionTooltip(); + }); + } + + function cancelShow() { + if (showTimeout) { + $timeout.cancel(showTimeout); + showTimeout = null; + } + + if (positionTimeout) { + $timeout.cancel(positionTimeout); + positionTimeout = null; + } + } + + // Hide the tooltip popup element. + function hide() { + cancelShow(); + cancelHide(); + + if (!ttScope) { + return; + } + + // First things first: we don't show it anymore. + ttScope.$evalAsync(function() { + ttScope.isOpen = false; + assignIsOpen(false); + // And now we remove it from the DOM. However, if we have animation, we + // need to wait for it to expire beforehand. + // FIXME: this is a placeholder for a port of the transitions library. + // The fade transition in TWBS is 150ms. + if (ttScope.animation) { + if (!transitionTimeout) { + transitionTimeout = $timeout(removeTooltip, 150, false); + } + } else { + removeTooltip(); + } + }); + } + + function cancelHide() { + if (hideTimeout) { + $timeout.cancel(hideTimeout); + hideTimeout = null; + } + if (transitionTimeout) { + $timeout.cancel(transitionTimeout); + transitionTimeout = null; + } + } + + function createTooltip() { + // There can only be one tooltip element per directive shown at once. + if (tooltip) { + return; + } + + tooltipLinkedScope = ttScope.$new(); + tooltip = tooltipLinker(tooltipLinkedScope, function(tooltip) { + if (appendToBody) { + $document.find('body').append(tooltip); + } else { + element.after(tooltip); + } + }); + + prepObservers(); + } + + function removeTooltip() { + unregisterObservers(); + + transitionTimeout = null; + if (tooltip) { + tooltip.remove(); + tooltip = null; + } + if (tooltipLinkedScope) { + tooltipLinkedScope.$destroy(); + tooltipLinkedScope = null; + } + } + + /** + * Set the inital scope values. Once + * the tooltip is created, the observers + * will be added to keep things in synch. + */ + function prepareTooltip() { + ttScope.title = attrs[prefix + 'Title']; + if (contentParse) { + ttScope.content = contentParse(scope); + } else { + ttScope.content = attrs[ttType]; + } + + ttScope.popupClass = attrs[prefix + 'Class']; + ttScope.placement = angular.isDefined(attrs[prefix + 'Placement']) ? attrs[prefix + 'Placement'] : options.placement; + + var delay = parseInt(attrs[prefix + 'PopupDelay'], 10); + var closeDelay = parseInt(attrs[prefix + 'PopupCloseDelay'], 10); + ttScope.popupDelay = !isNaN(delay) ? delay : options.popupDelay; + ttScope.popupCloseDelay = !isNaN(closeDelay) ? closeDelay : options.popupCloseDelay; + } + + function assignIsOpen(isOpen) { + if (isOpenParse && angular.isFunction(isOpenParse.assign)) { + isOpenParse.assign(scope, isOpen); + } + } + + ttScope.contentExp = function() { + return ttScope.content; + }; + + /** + * Observe the relevant attributes. + */ + attrs.$observe('disabled', function(val) { + if (val) { + cancelShow(); + } + + if (val && ttScope.isOpen) { + hide(); + } + }); + + if (isOpenParse) { + scope.$watch(isOpenParse, function(val) { + /*jshint -W018 */ + if (ttScope && !val === ttScope.isOpen) { + toggleTooltipBind(); + } + /*jshint +W018 */ + }); + } + + function prepObservers() { + observers.length = 0; + + if (contentParse) { + observers.push( + scope.$watch(contentParse, function(val) { + ttScope.content = val; + if (!val && ttScope.isOpen) { + hide(); + } + }) + ); + + observers.push( + tooltipLinkedScope.$watch(function() { + if (!repositionScheduled) { + repositionScheduled = true; + tooltipLinkedScope.$$postDigest(function() { + repositionScheduled = false; + if (ttScope && ttScope.isOpen) { + positionTooltip(); + } + }); + } + }) + ); + } else { + observers.push( + attrs.$observe(ttType, function(val) { + ttScope.content = val; + if (!val && ttScope.isOpen) { + hide(); + } else { + positionTooltip(); + } + }) + ); + } + + observers.push( + attrs.$observe(prefix + 'Title', function(val) { + ttScope.title = val; + if (ttScope.isOpen) { + positionTooltip(); + } + }) + ); + + observers.push( + attrs.$observe(prefix + 'Placement', function(val) { + ttScope.placement = val ? val : options.placement; + if (ttScope.isOpen) { + positionTooltip(); + } + }) + ); + } + + function unregisterObservers() { + if (observers.length) { + angular.forEach(observers, function(observer) { + observer(); + }); + observers.length = 0; + } + } + + var unregisterTriggers = function() { + triggers.show.forEach(function(trigger) { + element.unbind(trigger, showTooltipBind); + }); + triggers.hide.forEach(function(trigger) { + trigger.split(' ').forEach(function(hideTrigger) { + element[0].removeEventListener(hideTrigger, hideTooltipBind); + }); + }); + }; + + function prepTriggers() { + var val = attrs[prefix + 'Trigger']; + unregisterTriggers(); + + triggers = getTriggers(val); + + if (triggers.show !== 'none') { + triggers.show.forEach(function(trigger, idx) { + // Using raw addEventListener due to jqLite/jQuery bug - #4060 + if (trigger === triggers.hide[idx]) { + element[0].addEventListener(trigger, toggleTooltipBind); + } else if (trigger) { + element[0].addEventListener(trigger, showTooltipBind); + triggers.hide[idx].split(' ').forEach(function(trigger) { + element[0].addEventListener(trigger, hideTooltipBind); + }); + } + + element.on('keypress', function(e) { + if (e.which === 27) { + hideTooltipBind(); + } + }); + }); + } + } + + prepTriggers(); + + var animation = scope.$eval(attrs[prefix + 'Animation']); + ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation; + + var appendToBodyVal = scope.$eval(attrs[prefix + 'AppendToBody']); + appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody; + + // if a tooltip is attached to we need to remove it on + // location change as its parent scope will probably not be destroyed + // by the change. + if (appendToBody) { + scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess() { + if (ttScope.isOpen) { + hide(); + } + }); + } + + // Make sure tooltip is destroyed and removed. + scope.$on('$destroy', function onDestroyTooltip() { + cancelShow(); + cancelHide(); + unregisterTriggers(); + removeTooltip(); + openedTooltips.remove(ttScope); + ttScope = null; + }); + }; + } + }; + }; + }]; +}) + +// This is mostly ngInclude code but with a custom scope +.directive('uibTooltipTemplateTransclude', [ + '$animate', '$sce', '$compile', '$templateRequest', +function ($animate , $sce , $compile , $templateRequest) { + return { + link: function(scope, elem, attrs) { + var origScope = scope.$eval(attrs.tooltipTemplateTranscludeScope); + + var changeCounter = 0, + currentScope, + previousElement, + currentElement; + + var cleanupLastIncludeContent = function() { + if (previousElement) { + previousElement.remove(); + previousElement = null; + } + + if (currentScope) { + currentScope.$destroy(); + currentScope = null; + } + + if (currentElement) { + $animate.leave(currentElement).then(function() { + previousElement = null; + }); + previousElement = currentElement; + currentElement = null; + } + }; + + scope.$watch($sce.parseAsResourceUrl(attrs.uibTooltipTemplateTransclude), function(src) { + var thisChangeId = ++changeCounter; + + if (src) { + //set the 2nd param to true to ignore the template request error so that the inner + //contents and scope can be cleaned up. + $templateRequest(src, true).then(function(response) { + if (thisChangeId !== changeCounter) { return; } + var newScope = origScope.$new(); + var template = response; + + var clone = $compile(template)(newScope, function(clone) { + cleanupLastIncludeContent(); + $animate.enter(clone, elem); + }); + + currentScope = newScope; + currentElement = clone; + + currentScope.$emit('$includeContentLoaded', src); + }, function() { + if (thisChangeId === changeCounter) { + cleanupLastIncludeContent(); + scope.$emit('$includeContentError', src); + } + }); + scope.$emit('$includeContentRequested', src); + } else { + cleanupLastIncludeContent(); + } + }); + + scope.$on('$destroy', cleanupLastIncludeContent); + } + }; +}]) + +/** + * Note that it's intentional that these classes are *not* applied through $animate. + * They must not be animated as they're expected to be present on the tooltip on + * initialization. + */ +.directive('uibTooltipClasses', function() { + return { + restrict: 'A', + link: function(scope, element, attrs) { + if (scope.placement) { + element.addClass(scope.placement); + } + + if (scope.popupClass) { + element.addClass(scope.popupClass); + } + + if (scope.animation()) { + element.addClass(attrs.tooltipAnimationClass); + } + } + }; +}) + +.directive('uibTooltipPopup', function() { + return { + replace: true, + scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/tooltip/tooltip-popup.html', + link: function(scope, element) { + element.addClass('tooltip'); + } + }; +}) + +.directive('uibTooltip', [ '$uibTooltip', function($uibTooltip) { + return $uibTooltip('uibTooltip', 'tooltip', 'mouseenter'); +}]) + +.directive('uibTooltipTemplatePopup', function() { + return { + replace: true, + scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&', + originScope: '&' }, + templateUrl: 'template/tooltip/tooltip-template-popup.html', + link: function(scope, element) { + element.addClass('tooltip'); + } + }; +}) + +.directive('uibTooltipTemplate', ['$uibTooltip', function($uibTooltip) { + return $uibTooltip('uibTooltipTemplate', 'tooltip', 'mouseenter', { + useContentExp: true + }); +}]) + +.directive('uibTooltipHtmlPopup', function() { + return { + replace: true, + scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/tooltip/tooltip-html-popup.html', + link: function(scope, element) { + element.addClass('tooltip'); + } + }; +}) + +.directive('uibTooltipHtml', ['$uibTooltip', function($uibTooltip) { + return $uibTooltip('uibTooltipHtml', 'tooltip', 'mouseenter', { + useContentExp: true + }); +}]); + +/* Deprecated tooltip below */ + +angular.module('ui.bootstrap.tooltip') + +.value('$tooltipSuppressWarning', false) + +.provider('$tooltip', ['$uibTooltipProvider', function($uibTooltipProvider) { + angular.extend(this, $uibTooltipProvider); + + this.$get = ['$log', '$tooltipSuppressWarning', '$injector', function($log, $tooltipSuppressWarning, $injector) { + if (!$tooltipSuppressWarning) { + $log.warn('$tooltip is now deprecated. Use $uibTooltip instead.'); + } + + return $injector.invoke($uibTooltipProvider.$get); + }]; +}]) + +// This is mostly ngInclude code but with a custom scope +.directive('tooltipTemplateTransclude', [ + '$animate', '$sce', '$compile', '$templateRequest', '$log', '$tooltipSuppressWarning', +function ($animate , $sce , $compile , $templateRequest, $log, $tooltipSuppressWarning) { + return { + link: function(scope, elem, attrs) { + if (!$tooltipSuppressWarning) { + $log.warn('tooltip-template-transclude is now deprecated. Use uib-tooltip-template-transclude instead.'); + } + + var origScope = scope.$eval(attrs.tooltipTemplateTranscludeScope); + + var changeCounter = 0, + currentScope, + previousElement, + currentElement; + + var cleanupLastIncludeContent = function() { + if (previousElement) { + previousElement.remove(); + previousElement = null; + } + if (currentScope) { + currentScope.$destroy(); + currentScope = null; + } + if (currentElement) { + $animate.leave(currentElement).then(function() { + previousElement = null; + }); + previousElement = currentElement; + currentElement = null; + } + }; + + scope.$watch($sce.parseAsResourceUrl(attrs.tooltipTemplateTransclude), function(src) { + var thisChangeId = ++changeCounter; + + if (src) { + //set the 2nd param to true to ignore the template request error so that the inner + //contents and scope can be cleaned up. + $templateRequest(src, true).then(function(response) { + if (thisChangeId !== changeCounter) { return; } + var newScope = origScope.$new(); + var template = response; + + var clone = $compile(template)(newScope, function(clone) { + cleanupLastIncludeContent(); + $animate.enter(clone, elem); + }); + + currentScope = newScope; + currentElement = clone; + + currentScope.$emit('$includeContentLoaded', src); + }, function() { + if (thisChangeId === changeCounter) { + cleanupLastIncludeContent(); + scope.$emit('$includeContentError', src); + } + }); + scope.$emit('$includeContentRequested', src); + } else { + cleanupLastIncludeContent(); + } + }); + + scope.$on('$destroy', cleanupLastIncludeContent); + } + }; +}]) + +.directive('tooltipClasses', ['$log', '$tooltipSuppressWarning', function($log, $tooltipSuppressWarning) { + return { + restrict: 'A', + link: function(scope, element, attrs) { + if (!$tooltipSuppressWarning) { + $log.warn('tooltip-classes is now deprecated. Use uib-tooltip-classes instead.'); + } + + if (scope.placement) { + element.addClass(scope.placement); + } + if (scope.popupClass) { + element.addClass(scope.popupClass); + } + if (scope.animation()) { + element.addClass(attrs.tooltipAnimationClass); + } + } + }; +}]) + +.directive('tooltipPopup', ['$log', '$tooltipSuppressWarning', function($log, $tooltipSuppressWarning) { + return { + replace: true, + scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/tooltip/tooltip-popup.html', + link: function(scope, element) { + if (!$tooltipSuppressWarning) { + $log.warn('tooltip-popup is now deprecated. Use uib-tooltip-popup instead.'); + } + + element.addClass('tooltip'); + } + }; +}]) + +.directive('tooltip', ['$tooltip', function($tooltip) { + return $tooltip('tooltip', 'tooltip', 'mouseenter'); +}]) + +.directive('tooltipTemplatePopup', ['$log', '$tooltipSuppressWarning', function($log, $tooltipSuppressWarning) { + return { + replace: true, + scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&', + originScope: '&' }, + templateUrl: 'template/tooltip/tooltip-template-popup.html', + link: function(scope, element) { + if (!$tooltipSuppressWarning) { + $log.warn('tooltip-template-popup is now deprecated. Use uib-tooltip-template-popup instead.'); + } + + element.addClass('tooltip'); + } + }; +}]) + +.directive('tooltipTemplate', ['$tooltip', function($tooltip) { + return $tooltip('tooltipTemplate', 'tooltip', 'mouseenter', { + useContentExp: true + }); +}]) + +.directive('tooltipHtmlPopup', ['$log', '$tooltipSuppressWarning', function($log, $tooltipSuppressWarning) { + return { + replace: true, + scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/tooltip/tooltip-html-popup.html', + link: function(scope, element) { + if (!$tooltipSuppressWarning) { + $log.warn('tooltip-html-popup is now deprecated. Use uib-tooltip-html-popup instead.'); + } + + element.addClass('tooltip'); + } + }; +}]) + +.directive('tooltipHtml', ['$tooltip', function($tooltip) { + return $tooltip('tooltipHtml', 'tooltip', 'mouseenter', { + useContentExp: true + }); +}]); + +/** + * The following features are still outstanding: popup delay, animation as a + * function, placement as a function, inside, support for more triggers than + * just mouse enter/leave, and selector delegatation. + */ +angular.module('ui.bootstrap.popover', ['ui.bootstrap.tooltip']) + +.directive('uibPopoverTemplatePopup', function() { + return { + replace: true, + scope: { title: '@', contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&', + originScope: '&' }, + templateUrl: 'template/popover/popover-template.html', + link: function(scope, element) { + element.addClass('popover'); + } + }; +}) + +.directive('uibPopoverTemplate', ['$uibTooltip', function($uibTooltip) { + return $uibTooltip('uibPopoverTemplate', 'popover', 'click', { + useContentExp: true + }); +}]) + +.directive('uibPopoverHtmlPopup', function() { + return { + replace: true, + scope: { contentExp: '&', title: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/popover/popover-html.html', + link: function(scope, element) { + element.addClass('popover'); + } + }; +}) + +.directive('uibPopoverHtml', ['$uibTooltip', function($uibTooltip) { + return $uibTooltip('uibPopoverHtml', 'popover', 'click', { + useContentExp: true + }); +}]) + +.directive('uibPopoverPopup', function() { + return { + replace: true, + scope: { title: '@', content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/popover/popover.html', + link: function(scope, element) { + element.addClass('popover'); + } + }; +}) + +.directive('uibPopover', ['$uibTooltip', function($uibTooltip) { + return $uibTooltip('uibPopover', 'popover', 'click'); +}]); + +/* Deprecated popover below */ + +angular.module('ui.bootstrap.popover') + +.value('$popoverSuppressWarning', false) + +.directive('popoverTemplatePopup', ['$log', '$popoverSuppressWarning', function($log, $popoverSuppressWarning) { + return { + replace: true, + scope: { title: '@', contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&', + originScope: '&' }, + templateUrl: 'template/popover/popover-template.html', + link: function(scope, element) { + if (!$popoverSuppressWarning) { + $log.warn('popover-template-popup is now deprecated. Use uib-popover-template-popup instead.'); + } + + element.addClass('popover'); + } + }; +}]) + +.directive('popoverTemplate', ['$tooltip', function($tooltip) { + return $tooltip('popoverTemplate', 'popover', 'click', { + useContentExp: true + }); +}]) + +.directive('popoverHtmlPopup', ['$log', '$popoverSuppressWarning', function($log, $popoverSuppressWarning) { + return { + replace: true, + scope: { contentExp: '&', title: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/popover/popover-html.html', + link: function(scope, element) { + if (!$popoverSuppressWarning) { + $log.warn('popover-html-popup is now deprecated. Use uib-popover-html-popup instead.'); + } + + element.addClass('popover'); + } + }; +}]) + +.directive('popoverHtml', ['$tooltip', function($tooltip) { + return $tooltip('popoverHtml', 'popover', 'click', { + useContentExp: true + }); +}]) + +.directive('popoverPopup', ['$log', '$popoverSuppressWarning', function($log, $popoverSuppressWarning) { + return { + replace: true, + scope: { title: '@', content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/popover/popover.html', + link: function(scope, element) { + if (!$popoverSuppressWarning) { + $log.warn('popover-popup is now deprecated. Use uib-popover-popup instead.'); + } + + element.addClass('popover'); + } + }; +}]) + +.directive('popover', ['$tooltip', function($tooltip) { + + return $tooltip('popover', 'popover', 'click'); +}]); + +angular.module('ui.bootstrap.progressbar', []) + +.constant('uibProgressConfig', { + animate: true, + max: 100 +}) + +.controller('UibProgressController', ['$scope', '$attrs', 'uibProgressConfig', function($scope, $attrs, progressConfig) { + var self = this, + animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate; + + this.bars = []; + $scope.max = angular.isDefined($scope.max) ? $scope.max : progressConfig.max; + + this.addBar = function(bar, element, attrs) { + if (!animate) { + element.css({'transition': 'none'}); + } + + this.bars.push(bar); + + bar.max = $scope.max; + bar.title = attrs && angular.isDefined(attrs.title) ? attrs.title : 'progressbar'; + + bar.$watch('value', function(value) { + bar.recalculatePercentage(); + }); + + bar.recalculatePercentage = function() { + var totalPercentage = self.bars.reduce(function(total, bar) { + bar.percent = +(100 * bar.value / bar.max).toFixed(2); + return total + bar.percent; + }, 0); + + if (totalPercentage > 100) { + bar.percent -= totalPercentage - 100; + } + }; + + bar.$on('$destroy', function() { + element = null; + self.removeBar(bar); + }); + }; + + this.removeBar = function(bar) { + this.bars.splice(this.bars.indexOf(bar), 1); + this.bars.forEach(function (bar) { + bar.recalculatePercentage(); + }); + }; + + $scope.$watch('max', function(max) { + self.bars.forEach(function(bar) { + bar.max = $scope.max; + bar.recalculatePercentage(); + }); + }); +}]) + +.directive('uibProgress', function() { + return { + replace: true, + transclude: true, + controller: 'UibProgressController', + require: 'uibProgress', + scope: { + max: '=?' + }, + templateUrl: 'template/progressbar/progress.html' + }; +}) + +.directive('uibBar', function() { + return { + replace: true, + transclude: true, + require: '^uibProgress', + scope: { + value: '=', + type: '@' + }, + templateUrl: 'template/progressbar/bar.html', + link: function(scope, element, attrs, progressCtrl) { + progressCtrl.addBar(scope, element, attrs); + } + }; +}) + +.directive('uibProgressbar', function() { + return { + replace: true, + transclude: true, + controller: 'UibProgressController', + scope: { + value: '=', + max: '=?', + type: '@' + }, + templateUrl: 'template/progressbar/progressbar.html', + link: function(scope, element, attrs, progressCtrl) { + progressCtrl.addBar(scope, angular.element(element.children()[0]), {title: attrs.title}); + } + }; +}); + +/* Deprecated progressbar below */ + +angular.module('ui.bootstrap.progressbar') + +.value('$progressSuppressWarning', false) + +.controller('ProgressController', ['$scope', '$attrs', 'uibProgressConfig', '$log', '$progressSuppressWarning', function($scope, $attrs, progressConfig, $log, $progressSuppressWarning) { + if (!$progressSuppressWarning) { + $log.warn('ProgressController is now deprecated. Use UibProgressController instead.'); + } + + var self = this, + animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate; + + this.bars = []; + $scope.max = angular.isDefined($scope.max) ? $scope.max : progressConfig.max; + + this.addBar = function(bar, element, attrs) { + if (!animate) { + element.css({'transition': 'none'}); + } + + this.bars.push(bar); + + bar.max = $scope.max; + bar.title = attrs && angular.isDefined(attrs.title) ? attrs.title : 'progressbar'; + + bar.$watch('value', function(value) { + bar.recalculatePercentage(); + }); + + bar.recalculatePercentage = function() { + bar.percent = +(100 * bar.value / bar.max).toFixed(2); + + var totalPercentage = self.bars.reduce(function(total, bar) { + return total + bar.percent; + }, 0); + + if (totalPercentage > 100) { + bar.percent -= totalPercentage - 100; + } + }; + + bar.$on('$destroy', function() { + element = null; + self.removeBar(bar); + }); + }; + + this.removeBar = function(bar) { + this.bars.splice(this.bars.indexOf(bar), 1); + }; + + $scope.$watch('max', function(max) { + self.bars.forEach(function(bar) { + bar.max = $scope.max; + bar.recalculatePercentage(); + }); + }); +}]) + +.directive('progress', ['$log', '$progressSuppressWarning', function($log, $progressSuppressWarning) { + return { + replace: true, + transclude: true, + controller: 'ProgressController', + require: 'progress', + scope: { + max: '=?', + title: '@?' + }, + templateUrl: 'template/progressbar/progress.html', + link: function() { + if (!$progressSuppressWarning) { + $log.warn('progress is now deprecated. Use uib-progress instead.'); + } + } + }; +}]) + +.directive('bar', ['$log', '$progressSuppressWarning', function($log, $progressSuppressWarning) { + return { + replace: true, + transclude: true, + require: '^progress', + scope: { + value: '=', + type: '@' + }, + templateUrl: 'template/progressbar/bar.html', + link: function(scope, element, attrs, progressCtrl) { + if (!$progressSuppressWarning) { + $log.warn('bar is now deprecated. Use uib-bar instead.'); + } + progressCtrl.addBar(scope, element); + } + }; +}]) + +.directive('progressbar', ['$log', '$progressSuppressWarning', function($log, $progressSuppressWarning) { + return { + replace: true, + transclude: true, + controller: 'ProgressController', + scope: { + value: '=', + max: '=?', + type: '@' + }, + templateUrl: 'template/progressbar/progressbar.html', + link: function(scope, element, attrs, progressCtrl) { + if (!$progressSuppressWarning) { + $log.warn('progressbar is now deprecated. Use uib-progressbar instead.'); + } + progressCtrl.addBar(scope, angular.element(element.children()[0]), {title: attrs.title}); + } + }; +}]); + +angular.module('ui.bootstrap.rating', []) + +.constant('uibRatingConfig', { + max: 5, + stateOn: null, + stateOff: null, + titles : ['one', 'two', 'three', 'four', 'five'] +}) + +.controller('UibRatingController', ['$scope', '$attrs', 'uibRatingConfig', function($scope, $attrs, ratingConfig) { + var ngModelCtrl = { $setViewValue: angular.noop }; + + this.init = function(ngModelCtrl_) { + ngModelCtrl = ngModelCtrl_; + ngModelCtrl.$render = this.render; + + ngModelCtrl.$formatters.push(function(value) { + if (angular.isNumber(value) && value << 0 !== value) { + value = Math.round(value); + } + return value; + }); + + this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn; + this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff; + var tmpTitles = angular.isDefined($attrs.titles) ? $scope.$parent.$eval($attrs.titles) : ratingConfig.titles ; + this.titles = angular.isArray(tmpTitles) && tmpTitles.length > 0 ? + tmpTitles : ratingConfig.titles; + + var ratingStates = angular.isDefined($attrs.ratingStates) ? + $scope.$parent.$eval($attrs.ratingStates) : + new Array(angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max); + $scope.range = this.buildTemplateObjects(ratingStates); + }; + + this.buildTemplateObjects = function(states) { + for (var i = 0, n = states.length; i < n; i++) { + states[i] = angular.extend({ index: i }, { stateOn: this.stateOn, stateOff: this.stateOff, title: this.getTitle(i) }, states[i]); + } + return states; + }; + + this.getTitle = function(index) { + if (index >= this.titles.length) { + return index + 1; + } else { + return this.titles[index]; + } + }; + + $scope.rate = function(value) { + if (!$scope.readonly && value >= 0 && value <= $scope.range.length) { + ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue === value ? 0 : value); + ngModelCtrl.$render(); + } + }; + + $scope.enter = function(value) { + if (!$scope.readonly) { + $scope.value = value; + } + $scope.onHover({value: value}); + }; + + $scope.reset = function() { + $scope.value = ngModelCtrl.$viewValue; + $scope.onLeave(); + }; + + $scope.onKeydown = function(evt) { + if (/(37|38|39|40)/.test(evt.which)) { + evt.preventDefault(); + evt.stopPropagation(); + $scope.rate($scope.value + (evt.which === 38 || evt.which === 39 ? 1 : -1)); + } + }; + + this.render = function() { + $scope.value = ngModelCtrl.$viewValue; + }; +}]) + +.directive('uibRating', function() { + return { + require: ['uibRating', 'ngModel'], + scope: { + readonly: '=?', + onHover: '&', + onLeave: '&' + }, + controller: 'UibRatingController', + templateUrl: 'template/rating/rating.html', + replace: true, + link: function(scope, element, attrs, ctrls) { + var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + ratingCtrl.init(ngModelCtrl); + } + }; +}); + +/* Deprecated rating below */ + +angular.module('ui.bootstrap.rating') + +.value('$ratingSuppressWarning', false) + +.controller('RatingController', ['$scope', '$attrs', '$controller', '$log', '$ratingSuppressWarning', function($scope, $attrs, $controller, $log, $ratingSuppressWarning) { + if (!$ratingSuppressWarning) { + $log.warn('RatingController is now deprecated. Use UibRatingController instead.'); + } + + angular.extend(this, $controller('UibRatingController', { + $scope: $scope, + $attrs: $attrs + })); +}]) + +.directive('rating', ['$log', '$ratingSuppressWarning', function($log, $ratingSuppressWarning) { + return { + require: ['rating', 'ngModel'], + scope: { + readonly: '=?', + onHover: '&', + onLeave: '&' + }, + controller: 'RatingController', + templateUrl: 'template/rating/rating.html', + replace: true, + link: function(scope, element, attrs, ctrls) { + if (!$ratingSuppressWarning) { + $log.warn('rating is now deprecated. Use uib-rating instead.'); + } + var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + ratingCtrl.init(ngModelCtrl); + } + }; +}]); + + +/** + * @ngdoc overview + * @name ui.bootstrap.tabs + * + * @description + * AngularJS version of the tabs directive. + */ + +angular.module('ui.bootstrap.tabs', []) + +.controller('UibTabsetController', ['$scope', function ($scope) { + var ctrl = this, + tabs = ctrl.tabs = $scope.tabs = []; + + ctrl.select = function(selectedTab) { + angular.forEach(tabs, function(tab) { + if (tab.active && tab !== selectedTab) { + tab.active = false; + tab.onDeselect(); + selectedTab.selectCalled = false; + } + }); + selectedTab.active = true; + // only call select if it has not already been called + if (!selectedTab.selectCalled) { + selectedTab.onSelect(); + selectedTab.selectCalled = true; + } + }; + + ctrl.addTab = function addTab(tab) { + tabs.push(tab); + // we can't run the select function on the first tab + // since that would select it twice + if (tabs.length === 1 && tab.active !== false) { + tab.active = true; + } else if (tab.active) { + ctrl.select(tab); + } else { + tab.active = false; + } + }; + + ctrl.removeTab = function removeTab(tab) { + var index = tabs.indexOf(tab); + //Select a new tab if the tab to be removed is selected and not destroyed + if (tab.active && tabs.length > 1 && !destroyed) { + //If this is the last tab, select the previous tab. else, the next tab. + var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1; + ctrl.select(tabs[newActiveIndex]); + } + tabs.splice(index, 1); + }; + + var destroyed; + $scope.$on('$destroy', function() { + destroyed = true; + }); +}]) + +/** + * @ngdoc directive + * @name ui.bootstrap.tabs.directive:tabset + * @restrict EA + * + * @description + * Tabset is the outer container for the tabs directive + * + * @param {boolean=} vertical Whether or not to use vertical styling for the tabs. + * @param {boolean=} justified Whether or not to use justified styling for the tabs. + * + * @example + + + + First Content! + Second Content! + +
+ + First Vertical Content! + Second Vertical Content! + + + First Justified Content! + Second Justified Content! + +
+
+ */ +.directive('uibTabset', function() { + return { + restrict: 'EA', + transclude: true, + replace: true, + scope: { + type: '@' + }, + controller: 'UibTabsetController', + templateUrl: 'template/tabs/tabset.html', + link: function(scope, element, attrs) { + scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false; + scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false; + } + }; +}) + +/** + * @ngdoc directive + * @name ui.bootstrap.tabs.directive:tab + * @restrict EA + * + * @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link ui.bootstrap.tabs.directive:tabHeading tabHeading}. + * @param {string=} select An expression to evaluate when the tab is selected. + * @param {boolean=} active A binding, telling whether or not this tab is selected. + * @param {boolean=} disabled A binding, telling whether or not this tab is disabled. + * + * @description + * Creates a tab with a heading and content. Must be placed within a {@link ui.bootstrap.tabs.directive:tabset tabset}. + * + * @example + + +
+ + +
+ + First Tab + + Alert me! + Second Tab, with alert callback and html heading! + + + {{item.content}} + + +
+
+ + function TabsDemoCtrl($scope) { + $scope.items = [ + { title:"Dynamic Title 1", content:"Dynamic Item 0" }, + { title:"Dynamic Title 2", content:"Dynamic Item 1", disabled: true } + ]; + + $scope.alertMe = function() { + setTimeout(function() { + alert("You've selected the alert tab!"); + }); + }; + }; + +
+ */ + +/** + * @ngdoc directive + * @name ui.bootstrap.tabs.directive:tabHeading + * @restrict EA + * + * @description + * Creates an HTML heading for a {@link ui.bootstrap.tabs.directive:tab tab}. Must be placed as a child of a tab element. + * + * @example + + + + + HTML in my titles?! + And some content, too! + + + Icon heading?!? + That's right. + + + + + */ +.directive('uibTab', ['$parse', function($parse) { + return { + require: '^uibTabset', + restrict: 'EA', + replace: true, + templateUrl: 'template/tabs/tab.html', + transclude: true, + scope: { + active: '=?', + heading: '@', + onSelect: '&select', //This callback is called in contentHeadingTransclude + //once it inserts the tab's content into the dom + onDeselect: '&deselect' + }, + controller: function() { + //Empty controller so other directives can require being 'under' a tab + }, + link: function(scope, elm, attrs, tabsetCtrl, transclude) { + scope.$watch('active', function(active) { + if (active) { + tabsetCtrl.select(scope); + } + }); + + scope.disabled = false; + if (attrs.disable) { + scope.$parent.$watch($parse(attrs.disable), function(value) { + scope.disabled = !! value; + }); + } + + scope.select = function() { + if (!scope.disabled) { + scope.active = true; + } + }; + + tabsetCtrl.addTab(scope); + scope.$on('$destroy', function() { + tabsetCtrl.removeTab(scope); + }); + + //We need to transclude later, once the content container is ready. + //when this link happens, we're inside a tab heading. + scope.$transcludeFn = transclude; + } + }; +}]) + +.directive('uibTabHeadingTransclude', function() { + return { + restrict: 'A', + require: ['?^uibTab', '?^tab'], // TODO: change to '^uibTab' after deprecation removal + link: function(scope, elm) { + scope.$watch('headingElement', function updateHeadingElement(heading) { + if (heading) { + elm.html(''); + elm.append(heading); + } + }); + } + }; +}) + +.directive('uibTabContentTransclude', function() { + return { + restrict: 'A', + require: ['?^uibTabset', '?^tabset'], // TODO: change to '^uibTabset' after deprecation removal + link: function(scope, elm, attrs) { + var tab = scope.$eval(attrs.uibTabContentTransclude); + + //Now our tab is ready to be transcluded: both the tab heading area + //and the tab content area are loaded. Transclude 'em both. + tab.$transcludeFn(tab.$parent, function(contents) { + angular.forEach(contents, function(node) { + if (isTabHeading(node)) { + //Let tabHeadingTransclude know. + tab.headingElement = node; + } else { + elm.append(node); + } + }); + }); + } + }; + + function isTabHeading(node) { + return node.tagName && ( + node.hasAttribute('tab-heading') || // TODO: remove after deprecation removal + node.hasAttribute('data-tab-heading') || // TODO: remove after deprecation removal + node.hasAttribute('x-tab-heading') || // TODO: remove after deprecation removal + node.hasAttribute('uib-tab-heading') || + node.hasAttribute('data-uib-tab-heading') || + node.hasAttribute('x-uib-tab-heading') || + node.tagName.toLowerCase() === 'tab-heading' || // TODO: remove after deprecation removal + node.tagName.toLowerCase() === 'data-tab-heading' || // TODO: remove after deprecation removal + node.tagName.toLowerCase() === 'x-tab-heading' || // TODO: remove after deprecation removal + node.tagName.toLowerCase() === 'uib-tab-heading' || + node.tagName.toLowerCase() === 'data-uib-tab-heading' || + node.tagName.toLowerCase() === 'x-uib-tab-heading' + ); + } +}); + +/* deprecated tabs below */ + +angular.module('ui.bootstrap.tabs') + + .value('$tabsSuppressWarning', false) + + .controller('TabsetController', ['$scope', '$controller', '$log', '$tabsSuppressWarning', function($scope, $controller, $log, $tabsSuppressWarning) { + if (!$tabsSuppressWarning) { + $log.warn('TabsetController is now deprecated. Use UibTabsetController instead.'); + } + + angular.extend(this, $controller('UibTabsetController', { + $scope: $scope + })); + }]) + + .directive('tabset', ['$log', '$tabsSuppressWarning', function($log, $tabsSuppressWarning) { + return { + restrict: 'EA', + transclude: true, + replace: true, + scope: { + type: '@' + }, + controller: 'TabsetController', + templateUrl: 'template/tabs/tabset.html', + link: function(scope, element, attrs) { + + if (!$tabsSuppressWarning) { + $log.warn('tabset is now deprecated. Use uib-tabset instead.'); + } + scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false; + scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false; + } + }; + }]) + + .directive('tab', ['$parse', '$log', '$tabsSuppressWarning', function($parse, $log, $tabsSuppressWarning) { + return { + require: '^tabset', + restrict: 'EA', + replace: true, + templateUrl: 'template/tabs/tab.html', + transclude: true, + scope: { + active: '=?', + heading: '@', + onSelect: '&select', //This callback is called in contentHeadingTransclude + //once it inserts the tab's content into the dom + onDeselect: '&deselect' + }, + controller: function() { + //Empty controller so other directives can require being 'under' a tab + }, + link: function(scope, elm, attrs, tabsetCtrl, transclude) { + if (!$tabsSuppressWarning) { + $log.warn('tab is now deprecated. Use uib-tab instead.'); + } + + scope.$watch('active', function(active) { + if (active) { + tabsetCtrl.select(scope); + } + }); + + scope.disabled = false; + if (attrs.disable) { + scope.$parent.$watch($parse(attrs.disable), function(value) { + scope.disabled = !!value; + }); + } + + scope.select = function() { + if (!scope.disabled) { + scope.active = true; + } + }; + + tabsetCtrl.addTab(scope); + scope.$on('$destroy', function() { + tabsetCtrl.removeTab(scope); + }); + + //We need to transclude later, once the content container is ready. + //when this link happens, we're inside a tab heading. + scope.$transcludeFn = transclude; + } + }; + }]) + + .directive('tabHeadingTransclude', ['$log', '$tabsSuppressWarning', function($log, $tabsSuppressWarning) { + return { + restrict: 'A', + require: '^tab', + link: function(scope, elm) { + if (!$tabsSuppressWarning) { + $log.warn('tab-heading-transclude is now deprecated. Use uib-tab-heading-transclude instead.'); + } + + scope.$watch('headingElement', function updateHeadingElement(heading) { + if (heading) { + elm.html(''); + elm.append(heading); + } + }); + } + }; + }]) + + .directive('tabContentTransclude', ['$log', '$tabsSuppressWarning', function($log, $tabsSuppressWarning) { + return { + restrict: 'A', + require: '^tabset', + link: function(scope, elm, attrs) { + if (!$tabsSuppressWarning) { + $log.warn('tab-content-transclude is now deprecated. Use uib-tab-content-transclude instead.'); + } + + var tab = scope.$eval(attrs.tabContentTransclude); + + //Now our tab is ready to be transcluded: both the tab heading area + //and the tab content area are loaded. Transclude 'em both. + tab.$transcludeFn(tab.$parent, function(contents) { + angular.forEach(contents, function(node) { + if (isTabHeading(node)) { + //Let tabHeadingTransclude know. + tab.headingElement = node; + } + else { + elm.append(node); + } + }); + }); + } + }; + + function isTabHeading(node) { + return node.tagName && ( + node.hasAttribute('tab-heading') || + node.hasAttribute('data-tab-heading') || + node.hasAttribute('x-tab-heading') || + node.tagName.toLowerCase() === 'tab-heading' || + node.tagName.toLowerCase() === 'data-tab-heading' || + node.tagName.toLowerCase() === 'x-tab-heading' + ); + } + }]); + +angular.module('ui.bootstrap.timepicker', []) + +.constant('uibTimepickerConfig', { + hourStep: 1, + minuteStep: 1, + showMeridian: true, + meridians: null, + readonlyInput: false, + mousewheel: true, + arrowkeys: true, + showSpinners: true +}) + +.controller('UibTimepickerController', ['$scope', '$element', '$attrs', '$parse', '$log', '$locale', 'uibTimepickerConfig', function($scope, $element, $attrs, $parse, $log, $locale, timepickerConfig) { + var selected = new Date(), + ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl + meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS; + + $scope.tabindex = angular.isDefined($attrs.tabindex) ? $attrs.tabindex : 0; + $element.removeAttr('tabindex'); + + this.init = function(ngModelCtrl_, inputs) { + ngModelCtrl = ngModelCtrl_; + ngModelCtrl.$render = this.render; + + ngModelCtrl.$formatters.unshift(function(modelValue) { + return modelValue ? new Date(modelValue) : null; + }); + + var hoursInputEl = inputs.eq(0), + minutesInputEl = inputs.eq(1); + + var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel; + if (mousewheel) { + this.setupMousewheelEvents(hoursInputEl, minutesInputEl); + } + + var arrowkeys = angular.isDefined($attrs.arrowkeys) ? $scope.$parent.$eval($attrs.arrowkeys) : timepickerConfig.arrowkeys; + if (arrowkeys) { + this.setupArrowkeyEvents(hoursInputEl, minutesInputEl); + } + + $scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput; + this.setupInputEvents(hoursInputEl, minutesInputEl); + }; + + var hourStep = timepickerConfig.hourStep; + if ($attrs.hourStep) { + $scope.$parent.$watch($parse($attrs.hourStep), function(value) { + hourStep = parseInt(value, 10); + }); + } + + var minuteStep = timepickerConfig.minuteStep; + if ($attrs.minuteStep) { + $scope.$parent.$watch($parse($attrs.minuteStep), function(value) { + minuteStep = parseInt(value, 10); + }); + } + + var min; + $scope.$parent.$watch($parse($attrs.min), function(value) { + var dt = new Date(value); + min = isNaN(dt) ? undefined : dt; + }); + + var max; + $scope.$parent.$watch($parse($attrs.max), function(value) { + var dt = new Date(value); + max = isNaN(dt) ? undefined : dt; + }); + + $scope.noIncrementHours = function() { + var incrementedSelected = addMinutes(selected, hourStep * 60); + return incrementedSelected > max || + (incrementedSelected < selected && incrementedSelected < min); + }; + + $scope.noDecrementHours = function() { + var decrementedSelected = addMinutes(selected, -hourStep * 60); + return decrementedSelected < min || + (decrementedSelected > selected && decrementedSelected > max); + }; + + $scope.noIncrementMinutes = function() { + var incrementedSelected = addMinutes(selected, minuteStep); + return incrementedSelected > max || + (incrementedSelected < selected && incrementedSelected < min); + }; + + $scope.noDecrementMinutes = function() { + var decrementedSelected = addMinutes(selected, -minuteStep); + return decrementedSelected < min || + (decrementedSelected > selected && decrementedSelected > max); + }; + + $scope.noToggleMeridian = function() { + if (selected.getHours() < 13) { + return addMinutes(selected, 12 * 60) > max; + } else { + return addMinutes(selected, -12 * 60) < min; + } + }; + + // 12H / 24H mode + $scope.showMeridian = timepickerConfig.showMeridian; + if ($attrs.showMeridian) { + $scope.$parent.$watch($parse($attrs.showMeridian), function(value) { + $scope.showMeridian = !!value; + + if (ngModelCtrl.$error.time) { + // Evaluate from template + var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate(); + if (angular.isDefined(hours) && angular.isDefined(minutes)) { + selected.setHours(hours); + refresh(); + } + } else { + updateTemplate(); + } + }); + } + + // Get $scope.hours in 24H mode if valid + function getHoursFromTemplate() { + var hours = parseInt($scope.hours, 10); + var valid = $scope.showMeridian ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24); + if (!valid) { + return undefined; + } + + if ($scope.showMeridian) { + if (hours === 12) { + hours = 0; + } + if ($scope.meridian === meridians[1]) { + hours = hours + 12; + } + } + return hours; + } + + function getMinutesFromTemplate() { + var minutes = parseInt($scope.minutes, 10); + return (minutes >= 0 && minutes < 60) ? minutes : undefined; + } + + function pad(value) { + return (angular.isDefined(value) && value.toString().length < 2) ? '0' + value : value.toString(); + } + + // Respond on mousewheel spin + this.setupMousewheelEvents = function(hoursInputEl, minutesInputEl) { + var isScrollingUp = function(e) { + if (e.originalEvent) { + e = e.originalEvent; + } + //pick correct delta variable depending on event + var delta = (e.wheelDelta) ? e.wheelDelta : -e.deltaY; + return (e.detail || delta > 0); + }; + + hoursInputEl.bind('mousewheel wheel', function(e) { + $scope.$apply(isScrollingUp(e) ? $scope.incrementHours() : $scope.decrementHours()); + e.preventDefault(); + }); + + minutesInputEl.bind('mousewheel wheel', function(e) { + $scope.$apply(isScrollingUp(e) ? $scope.incrementMinutes() : $scope.decrementMinutes()); + e.preventDefault(); + }); + + }; + + // Respond on up/down arrowkeys + this.setupArrowkeyEvents = function(hoursInputEl, minutesInputEl) { + hoursInputEl.bind('keydown', function(e) { + if (e.which === 38) { // up + e.preventDefault(); + $scope.incrementHours(); + $scope.$apply(); + } else if (e.which === 40) { // down + e.preventDefault(); + $scope.decrementHours(); + $scope.$apply(); + } + }); + + minutesInputEl.bind('keydown', function(e) { + if (e.which === 38) { // up + e.preventDefault(); + $scope.incrementMinutes(); + $scope.$apply(); + } else if (e.which === 40) { // down + e.preventDefault(); + $scope.decrementMinutes(); + $scope.$apply(); + } + }); + }; + + this.setupInputEvents = function(hoursInputEl, minutesInputEl) { + if ($scope.readonlyInput) { + $scope.updateHours = angular.noop; + $scope.updateMinutes = angular.noop; + return; + } + + var invalidate = function(invalidHours, invalidMinutes) { + ngModelCtrl.$setViewValue(null); + ngModelCtrl.$setValidity('time', false); + if (angular.isDefined(invalidHours)) { + $scope.invalidHours = invalidHours; + } + if (angular.isDefined(invalidMinutes)) { + $scope.invalidMinutes = invalidMinutes; + } + }; + + $scope.updateHours = function() { + var hours = getHoursFromTemplate(), + minutes = getMinutesFromTemplate(); + + if (angular.isDefined(hours) && angular.isDefined(minutes)) { + selected.setHours(hours); + if (selected < min || selected > max) { + invalidate(true); + } else { + refresh('h'); + } + } else { + invalidate(true); + } + }; + + hoursInputEl.bind('blur', function(e) { + if (!$scope.invalidHours && $scope.hours < 10) { + $scope.$apply(function() { + $scope.hours = pad($scope.hours); + }); + } + }); + + $scope.updateMinutes = function() { + var minutes = getMinutesFromTemplate(), + hours = getHoursFromTemplate(); + + if (angular.isDefined(minutes) && angular.isDefined(hours)) { + selected.setMinutes(minutes); + if (selected < min || selected > max) { + invalidate(undefined, true); + } else { + refresh('m'); + } + } else { + invalidate(undefined, true); + } + }; + + minutesInputEl.bind('blur', function(e) { + if (!$scope.invalidMinutes && $scope.minutes < 10) { + $scope.$apply(function() { + $scope.minutes = pad($scope.minutes); + }); + } + }); + + }; + + this.render = function() { + var date = ngModelCtrl.$viewValue; + + if (isNaN(date)) { + ngModelCtrl.$setValidity('time', false); + $log.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.'); + } else { + if (date) { + selected = date; + } + + if (selected < min || selected > max) { + ngModelCtrl.$setValidity('time', false); + $scope.invalidHours = true; + $scope.invalidMinutes = true; + } else { + makeValid(); + } + updateTemplate(); + } + }; + + // Call internally when we know that model is valid. + function refresh(keyboardChange) { + makeValid(); + ngModelCtrl.$setViewValue(new Date(selected)); + updateTemplate(keyboardChange); + } + + function makeValid() { + ngModelCtrl.$setValidity('time', true); + $scope.invalidHours = false; + $scope.invalidMinutes = false; + } + + function updateTemplate(keyboardChange) { + var hours = selected.getHours(), minutes = selected.getMinutes(); + + if ($scope.showMeridian) { + hours = (hours === 0 || hours === 12) ? 12 : hours % 12; // Convert 24 to 12 hour system + } + + $scope.hours = keyboardChange === 'h' ? hours : pad(hours); + if (keyboardChange !== 'm') { + $scope.minutes = pad(minutes); + } + $scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1]; + } + + function addMinutes(date, minutes) { + var dt = new Date(date.getTime() + minutes * 60000); + var newDate = new Date(date); + newDate.setHours(dt.getHours(), dt.getMinutes()); + return newDate; + } + + function addMinutesToSelected(minutes) { + selected = addMinutes(selected, minutes); + refresh(); + } + + $scope.showSpinners = angular.isDefined($attrs.showSpinners) ? + $scope.$parent.$eval($attrs.showSpinners) : timepickerConfig.showSpinners; + + $scope.incrementHours = function() { + if (!$scope.noIncrementHours()) { + addMinutesToSelected(hourStep * 60); + } + }; + + $scope.decrementHours = function() { + if (!$scope.noDecrementHours()) { + addMinutesToSelected(-hourStep * 60); + } + }; + + $scope.incrementMinutes = function() { + if (!$scope.noIncrementMinutes()) { + addMinutesToSelected(minuteStep); + } + }; + + $scope.decrementMinutes = function() { + if (!$scope.noDecrementMinutes()) { + addMinutesToSelected(-minuteStep); + } + }; + + $scope.toggleMeridian = function() { + if (!$scope.noToggleMeridian()) { + addMinutesToSelected(12 * 60 * (selected.getHours() < 12 ? 1 : -1)); + } + }; +}]) + +.directive('uibTimepicker', function() { + return { + restrict: 'EA', + require: ['uibTimepicker', '?^ngModel'], + controller: 'UibTimepickerController', + controllerAs: 'timepicker', + replace: true, + scope: {}, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/timepicker/timepicker.html'; + }, + link: function(scope, element, attrs, ctrls) { + var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + if (ngModelCtrl) { + timepickerCtrl.init(ngModelCtrl, element.find('input')); + } + } + }; +}); + +/* Deprecated timepicker below */ + +angular.module('ui.bootstrap.timepicker') + +.value('$timepickerSuppressWarning', false) + +.controller('TimepickerController', ['$scope', '$element', '$attrs', '$controller', '$log', '$timepickerSuppressWarning', function($scope, $element, $attrs, $controller, $log, $timepickerSuppressWarning) { + if (!$timepickerSuppressWarning) { + $log.warn('TimepickerController is now deprecated. Use UibTimepickerController instead.'); + } + + angular.extend(this, $controller('UibTimepickerController', { + $scope: $scope, + $element: $element, + $attrs: $attrs + })); +}]) + +.directive('timepicker', ['$log', '$timepickerSuppressWarning', function($log, $timepickerSuppressWarning) { + return { + restrict: 'EA', + require: ['timepicker', '?^ngModel'], + controller: 'TimepickerController', + controllerAs: 'timepicker', + replace: true, + scope: {}, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/timepicker/timepicker.html'; + }, + link: function(scope, element, attrs, ctrls) { + if (!$timepickerSuppressWarning) { + $log.warn('timepicker is now deprecated. Use uib-timepicker instead.'); + } + var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + if (ngModelCtrl) { + timepickerCtrl.init(ngModelCtrl, element.find('input')); + } + } + }; +}]); + +angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position']) + +/** + * A helper service that can parse typeahead's syntax (string provided by users) + * Extracted to a separate service for ease of unit testing + */ + .factory('uibTypeaheadParser', ['$parse', function($parse) { + // 00000111000000000000022200000000000000003333333333333330000000000044000 + var TYPEAHEAD_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/; + return { + parse: function(input) { + var match = input.match(TYPEAHEAD_REGEXP); + if (!match) { + throw new Error( + 'Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_"' + + ' but got "' + input + '".'); + } + + return { + itemName: match[3], + source: $parse(match[4]), + viewMapper: $parse(match[2] || match[1]), + modelMapper: $parse(match[1]) + }; + } + }; + }]) + + .controller('UibTypeaheadController', ['$scope', '$element', '$attrs', '$compile', '$parse', '$q', '$timeout', '$document', '$window', '$rootScope', '$uibPosition', 'uibTypeaheadParser', + function(originalScope, element, attrs, $compile, $parse, $q, $timeout, $document, $window, $rootScope, $position, typeaheadParser) { + var HOT_KEYS = [9, 13, 27, 38, 40]; + var eventDebounceTime = 200; + var modelCtrl, ngModelOptions; + //SUPPORTED ATTRIBUTES (OPTIONS) + + //minimal no of characters that needs to be entered before typeahead kicks-in + var minLength = originalScope.$eval(attrs.typeaheadMinLength); + if (!minLength && minLength !== 0) { + minLength = 1; + } + + //minimal wait time after last character typed before typeahead kicks-in + var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0; + + //should it restrict model values to the ones selected from the popup only? + var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false; + + //binding to a variable that indicates if matches are being retrieved asynchronously + var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop; + + //a callback executed when a match is selected + var onSelectCallback = $parse(attrs.typeaheadOnSelect); + + //should it select highlighted popup value when losing focus? + var isSelectOnBlur = angular.isDefined(attrs.typeaheadSelectOnBlur) ? originalScope.$eval(attrs.typeaheadSelectOnBlur) : false; + + //binding to a variable that indicates if there were no results after the query is completed + var isNoResultsSetter = $parse(attrs.typeaheadNoResults).assign || angular.noop; + + var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined; + + var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false; + + var appendToElementId = attrs.typeaheadAppendToElementId || false; + + var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false; + + //If input matches an item of the list exactly, select it automatically + var selectOnExact = attrs.typeaheadSelectOnExact ? originalScope.$eval(attrs.typeaheadSelectOnExact) : false; + + //INTERNAL VARIABLES + + //model setter executed upon match selection + var parsedModel = $parse(attrs.ngModel); + var invokeModelSetter = $parse(attrs.ngModel + '($$$p)'); + var $setModelValue = function(scope, newValue) { + if (angular.isFunction(parsedModel(originalScope)) && + ngModelOptions && ngModelOptions.$options && ngModelOptions.$options.getterSetter) { + return invokeModelSetter(scope, {$$$p: newValue}); + } else { + return parsedModel.assign(scope, newValue); + } + }; + + //expressions used by typeahead + var parserResult = typeaheadParser.parse(attrs.uibTypeahead); + + var hasFocus; + + //Used to avoid bug in iOS webview where iOS keyboard does not fire + //mousedown & mouseup events + //Issue #3699 + var selected; + + //create a child scope for the typeahead directive so we are not polluting original scope + //with typeahead-specific data (matches, query etc.) + var scope = originalScope.$new(); + var offDestroy = originalScope.$on('$destroy', function() { + scope.$destroy(); + }); + scope.$on('$destroy', offDestroy); + + // WAI-ARIA + var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000); + element.attr({ + 'aria-autocomplete': 'list', + 'aria-expanded': false, + 'aria-owns': popupId + }); + + //pop-up element used to display matches + var popUpEl = angular.element('
'); + popUpEl.attr({ + id: popupId, + matches: 'matches', + active: 'activeIdx', + select: 'select(activeIdx)', + 'move-in-progress': 'moveInProgress', + query: 'query', + position: 'position' + }); + //custom item template + if (angular.isDefined(attrs.typeaheadTemplateUrl)) { + popUpEl.attr('template-url', attrs.typeaheadTemplateUrl); + } + + if (angular.isDefined(attrs.typeaheadPopupTemplateUrl)) { + popUpEl.attr('popup-template-url', attrs.typeaheadPopupTemplateUrl); + } + + var resetMatches = function() { + scope.matches = []; + scope.activeIdx = -1; + element.attr('aria-expanded', false); + }; + + var getMatchId = function(index) { + return popupId + '-option-' + index; + }; + + // Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead. + // This attribute is added or removed automatically when the `activeIdx` changes. + scope.$watch('activeIdx', function(index) { + if (index < 0) { + element.removeAttr('aria-activedescendant'); + } else { + element.attr('aria-activedescendant', getMatchId(index)); + } + }); + + var inputIsExactMatch = function(inputValue, index) { + if (scope.matches.length > index && inputValue) { + return inputValue.toUpperCase() === scope.matches[index].label.toUpperCase(); + } + + return false; + }; + + var getMatchesAsync = function(inputValue) { + var locals = {$viewValue: inputValue}; + isLoadingSetter(originalScope, true); + isNoResultsSetter(originalScope, false); + $q.when(parserResult.source(originalScope, locals)).then(function(matches) { + //it might happen that several async queries were in progress if a user were typing fast + //but we are interested only in responses that correspond to the current view value + var onCurrentRequest = (inputValue === modelCtrl.$viewValue); + if (onCurrentRequest && hasFocus) { + if (matches && matches.length > 0) { + scope.activeIdx = focusFirst ? 0 : -1; + isNoResultsSetter(originalScope, false); + scope.matches.length = 0; + + //transform labels + for (var i = 0; i < matches.length; i++) { + locals[parserResult.itemName] = matches[i]; + scope.matches.push({ + id: getMatchId(i), + label: parserResult.viewMapper(scope, locals), + model: matches[i] + }); + } + + scope.query = inputValue; + //position pop-up with matches - we need to re-calculate its position each time we are opening a window + //with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page + //due to other elements being rendered + recalculatePosition(); + + element.attr('aria-expanded', true); + + //Select the single remaining option if user input matches + if (selectOnExact && scope.matches.length === 1 && inputIsExactMatch(inputValue, 0)) { + scope.select(0); + } + } else { + resetMatches(); + isNoResultsSetter(originalScope, true); + } + } + if (onCurrentRequest) { + isLoadingSetter(originalScope, false); + } + }, function() { + resetMatches(); + isLoadingSetter(originalScope, false); + isNoResultsSetter(originalScope, true); + }); + }; + + // bind events only if appendToBody params exist - performance feature + if (appendToBody) { + angular.element($window).bind('resize', fireRecalculating); + $document.find('body').bind('scroll', fireRecalculating); + } + + // Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later + var timeoutEventPromise; + + // Default progress type + scope.moveInProgress = false; + + function fireRecalculating() { + if (!scope.moveInProgress) { + scope.moveInProgress = true; + scope.$digest(); + } + + // Cancel previous timeout + if (timeoutEventPromise) { + $timeout.cancel(timeoutEventPromise); + } + + // Debounced executing recalculate after events fired + timeoutEventPromise = $timeout(function() { + // if popup is visible + if (scope.matches.length) { + recalculatePosition(); + } + + scope.moveInProgress = false; + }, eventDebounceTime); + } + + // recalculate actual position and set new values to scope + // after digest loop is popup in right position + function recalculatePosition() { + scope.position = appendToBody ? $position.offset(element) : $position.position(element); + scope.position.top += element.prop('offsetHeight'); + } + + //we need to propagate user's query so we can higlight matches + scope.query = undefined; + + //Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later + var timeoutPromise; + + var scheduleSearchWithTimeout = function(inputValue) { + timeoutPromise = $timeout(function() { + getMatchesAsync(inputValue); + }, waitTime); + }; + + var cancelPreviousTimeout = function() { + if (timeoutPromise) { + $timeout.cancel(timeoutPromise); + } + }; + + resetMatches(); + + scope.select = function(activeIdx) { + //called from within the $digest() cycle + var locals = {}; + var model, item; + + selected = true; + locals[parserResult.itemName] = item = scope.matches[activeIdx].model; + model = parserResult.modelMapper(originalScope, locals); + $setModelValue(originalScope, model); + modelCtrl.$setValidity('editable', true); + modelCtrl.$setValidity('parse', true); + + onSelectCallback(originalScope, { + $item: item, + $model: model, + $label: parserResult.viewMapper(originalScope, locals) + }); + + resetMatches(); + + //return focus to the input element if a match was selected via a mouse click event + // use timeout to avoid $rootScope:inprog error + if (scope.$eval(attrs.typeaheadFocusOnSelect) !== false) { + $timeout(function() { element[0].focus(); }, 0, false); + } + }; + + //bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27) + element.bind('keydown', function(evt) { + //typeahead is open and an "interesting" key was pressed + if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) { + return; + } + + // if there's nothing selected (i.e. focusFirst) and enter or tab is hit, clear the results + if (scope.activeIdx === -1 && (evt.which === 9 || evt.which === 13)) { + resetMatches(); + scope.$digest(); + return; + } + + evt.preventDefault(); + + if (evt.which === 40) { + scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length; + scope.$digest(); + } else if (evt.which === 38) { + scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1; + scope.$digest(); + } else if (evt.which === 13 || evt.which === 9) { + scope.$apply(function () { + scope.select(scope.activeIdx); + }); + } else if (evt.which === 27) { + evt.stopPropagation(); + + resetMatches(); + scope.$digest(); + } + }); + + element.bind('blur', function() { + if (isSelectOnBlur && scope.matches.length && scope.activeIdx !== -1 && !selected) { + selected = true; + scope.$apply(function() { + scope.select(scope.activeIdx); + }); + } + hasFocus = false; + selected = false; + }); + + // Keep reference to click handler to unbind it. + var dismissClickHandler = function(evt) { + // Issue #3973 + // Firefox treats right click as a click on document + if (element[0] !== evt.target && evt.which !== 3 && scope.matches.length !== 0) { + resetMatches(); + if (!$rootScope.$$phase) { + scope.$digest(); + } + } + }; + + $document.bind('click', dismissClickHandler); + + originalScope.$on('$destroy', function() { + $document.unbind('click', dismissClickHandler); + if (appendToBody || appendToElementId) { + $popup.remove(); + } + + if (appendToBody) { + angular.element($window).unbind('resize', fireRecalculating); + $document.find('body').unbind('scroll', fireRecalculating); + } + // Prevent jQuery cache memory leak + popUpEl.remove(); + }); + + var $popup = $compile(popUpEl)(scope); + + if (appendToBody) { + $document.find('body').append($popup); + } else if (appendToElementId !== false) { + angular.element($document[0].getElementById(appendToElementId)).append($popup); + } else { + element.after($popup); + } + + this.init = function(_modelCtrl, _ngModelOptions) { + modelCtrl = _modelCtrl; + ngModelOptions = _ngModelOptions; + + //plug into $parsers pipeline to open a typeahead on view changes initiated from DOM + //$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue + modelCtrl.$parsers.unshift(function(inputValue) { + hasFocus = true; + + if (minLength === 0 || inputValue && inputValue.length >= minLength) { + if (waitTime > 0) { + cancelPreviousTimeout(); + scheduleSearchWithTimeout(inputValue); + } else { + getMatchesAsync(inputValue); + } + } else { + isLoadingSetter(originalScope, false); + cancelPreviousTimeout(); + resetMatches(); + } + + if (isEditable) { + return inputValue; + } else { + if (!inputValue) { + // Reset in case user had typed something previously. + modelCtrl.$setValidity('editable', true); + return null; + } else { + modelCtrl.$setValidity('editable', false); + return undefined; + } + } + }); + + modelCtrl.$formatters.push(function(modelValue) { + var candidateViewValue, emptyViewValue; + var locals = {}; + + // The validity may be set to false via $parsers (see above) if + // the model is restricted to selected values. If the model + // is set manually it is considered to be valid. + if (!isEditable) { + modelCtrl.$setValidity('editable', true); + } + + if (inputFormatter) { + locals.$model = modelValue; + return inputFormatter(originalScope, locals); + } else { + //it might happen that we don't have enough info to properly render input value + //we need to check for this situation and simply return model value if we can't apply custom formatting + locals[parserResult.itemName] = modelValue; + candidateViewValue = parserResult.viewMapper(originalScope, locals); + locals[parserResult.itemName] = undefined; + emptyViewValue = parserResult.viewMapper(originalScope, locals); + + return candidateViewValue !== emptyViewValue ? candidateViewValue : modelValue; + } + }); + }; + }]) + + .directive('uibTypeahead', function() { + return { + controller: 'UibTypeaheadController', + require: ['ngModel', '^?ngModelOptions', 'uibTypeahead'], + link: function(originalScope, element, attrs, ctrls) { + ctrls[2].init(ctrls[0], ctrls[1]); + } + }; + }) + + .directive('uibTypeaheadPopup', function() { + return { + scope: { + matches: '=', + query: '=', + active: '=', + position: '&', + moveInProgress: '=', + select: '&' + }, + replace: true, + templateUrl: function(element, attrs) { + return attrs.popupTemplateUrl || 'template/typeahead/typeahead-popup.html'; + }, + link: function(scope, element, attrs) { + scope.templateUrl = attrs.templateUrl; + + scope.isOpen = function() { + return scope.matches.length > 0; + }; + + scope.isActive = function(matchIdx) { + return scope.active == matchIdx; + }; + + scope.selectActive = function(matchIdx) { + scope.active = matchIdx; + }; + + scope.selectMatch = function(activeIdx) { + scope.select({activeIdx:activeIdx}); + }; + } + }; + }) + + .directive('uibTypeaheadMatch', ['$templateRequest', '$compile', '$parse', function($templateRequest, $compile, $parse) { + return { + scope: { + index: '=', + match: '=', + query: '=' + }, + link:function(scope, element, attrs) { + var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html'; + $templateRequest(tplUrl).then(function(tplContent) { + $compile(tplContent.trim())(scope, function(clonedElement) { + element.replaceWith(clonedElement); + }); + }); + } + }; + }]) + + .filter('uibTypeaheadHighlight', ['$sce', '$injector', '$log', function($sce, $injector, $log) { + var isSanitizePresent; + isSanitizePresent = $injector.has('$sanitize'); + + function escapeRegexp(queryToEscape) { + // Regex: capture the whole query string and replace it with the string that will be used to match + // the results, for example if the capture is "a" the result will be \a + return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); + } + + function containsHtml(matchItem) { + return /<.*>/g.test(matchItem); + } + + return function(matchItem, query) { + if (!isSanitizePresent && containsHtml(matchItem)) { + $log.warn('Unsafe use of typeahead please use ngSanitize'); // Warn the user about the danger + } + matchItem = query? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '$&') : matchItem; // Replaces the capture string with a the same string inside of a "strong" tag + if (!isSanitizePresent) { + matchItem = $sce.trustAsHtml(matchItem); // If $sanitize is not present we pack the string in a $sce object for the ng-bind-html directive + } + return matchItem; + }; + }]); + +/* Deprecated typeahead below */ + +angular.module('ui.bootstrap.typeahead') + .value('$typeaheadSuppressWarning', false) + .service('typeaheadParser', ['$parse', 'uibTypeaheadParser', '$log', '$typeaheadSuppressWarning', function($parse, uibTypeaheadParser, $log, $typeaheadSuppressWarning) { + if (!$typeaheadSuppressWarning) { + $log.warn('typeaheadParser is now deprecated. Use uibTypeaheadParser instead.'); + } + + return uibTypeaheadParser; + }]) + + .directive('typeahead', ['$compile', '$parse', '$q', '$timeout', '$document', '$window', '$rootScope', '$uibPosition', 'typeaheadParser', '$log', '$typeaheadSuppressWarning', + function($compile, $parse, $q, $timeout, $document, $window, $rootScope, $position, typeaheadParser, $log, $typeaheadSuppressWarning) { + var HOT_KEYS = [9, 13, 27, 38, 40]; + var eventDebounceTime = 200; + return { + require: ['ngModel', '^?ngModelOptions'], + link: function(originalScope, element, attrs, ctrls) { + if (!$typeaheadSuppressWarning) { + $log.warn('typeahead is now deprecated. Use uib-typeahead instead.'); + } + var modelCtrl = ctrls[0]; + var ngModelOptions = ctrls[1]; + //SUPPORTED ATTRIBUTES (OPTIONS) + + //minimal no of characters that needs to be entered before typeahead kicks-in + var minLength = originalScope.$eval(attrs.typeaheadMinLength); + if (!minLength && minLength !== 0) { + minLength = 1; + } + + //minimal wait time after last character typed before typeahead kicks-in + var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0; + + //should it restrict model values to the ones selected from the popup only? + var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false; + + //binding to a variable that indicates if matches are being retrieved asynchronously + var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop; + + //a callback executed when a match is selected + var onSelectCallback = $parse(attrs.typeaheadOnSelect); + + //should it select highlighted popup value when losing focus? + var isSelectOnBlur = angular.isDefined(attrs.typeaheadSelectOnBlur) ? originalScope.$eval(attrs.typeaheadSelectOnBlur) : false; + + //binding to a variable that indicates if there were no results after the query is completed + var isNoResultsSetter = $parse(attrs.typeaheadNoResults).assign || angular.noop; + + var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined; + + var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false; + + var appendToElementId = attrs.typeaheadAppendToElementId || false; + + var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false; + + //If input matches an item of the list exactly, select it automatically + var selectOnExact = attrs.typeaheadSelectOnExact ? originalScope.$eval(attrs.typeaheadSelectOnExact) : false; + + //INTERNAL VARIABLES + + //model setter executed upon match selection + var parsedModel = $parse(attrs.ngModel); + var invokeModelSetter = $parse(attrs.ngModel + '($$$p)'); + var $setModelValue = function(scope, newValue) { + if (angular.isFunction(parsedModel(originalScope)) && + ngModelOptions && ngModelOptions.$options && ngModelOptions.$options.getterSetter) { + return invokeModelSetter(scope, {$$$p: newValue}); + } else { + return parsedModel.assign(scope, newValue); + } + }; + + //expressions used by typeahead + var parserResult = typeaheadParser.parse(attrs.typeahead); + + var hasFocus; + + //Used to avoid bug in iOS webview where iOS keyboard does not fire + //mousedown & mouseup events + //Issue #3699 + var selected; + + //create a child scope for the typeahead directive so we are not polluting original scope + //with typeahead-specific data (matches, query etc.) + var scope = originalScope.$new(); + var offDestroy = originalScope.$on('$destroy', function() { + scope.$destroy(); + }); + scope.$on('$destroy', offDestroy); + + // WAI-ARIA + var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000); + element.attr({ + 'aria-autocomplete': 'list', + 'aria-expanded': false, + 'aria-owns': popupId + }); + + //pop-up element used to display matches + var popUpEl = angular.element('
'); + popUpEl.attr({ + id: popupId, + matches: 'matches', + active: 'activeIdx', + select: 'select(activeIdx)', + 'move-in-progress': 'moveInProgress', + query: 'query', + position: 'position' + }); + //custom item template + if (angular.isDefined(attrs.typeaheadTemplateUrl)) { + popUpEl.attr('template-url', attrs.typeaheadTemplateUrl); + } + + if (angular.isDefined(attrs.typeaheadPopupTemplateUrl)) { + popUpEl.attr('popup-template-url', attrs.typeaheadPopupTemplateUrl); + } + + var resetMatches = function() { + scope.matches = []; + scope.activeIdx = -1; + element.attr('aria-expanded', false); + }; + + var getMatchId = function(index) { + return popupId + '-option-' + index; + }; + + // Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead. + // This attribute is added or removed automatically when the `activeIdx` changes. + scope.$watch('activeIdx', function(index) { + if (index < 0) { + element.removeAttr('aria-activedescendant'); + } else { + element.attr('aria-activedescendant', getMatchId(index)); + } + }); + + var inputIsExactMatch = function(inputValue, index) { + if (scope.matches.length > index && inputValue) { + return inputValue.toUpperCase() === scope.matches[index].label.toUpperCase(); + } + + return false; + }; + + var getMatchesAsync = function(inputValue) { + var locals = {$viewValue: inputValue}; + isLoadingSetter(originalScope, true); + isNoResultsSetter(originalScope, false); + $q.when(parserResult.source(originalScope, locals)).then(function(matches) { + //it might happen that several async queries were in progress if a user were typing fast + //but we are interested only in responses that correspond to the current view value + var onCurrentRequest = (inputValue === modelCtrl.$viewValue); + if (onCurrentRequest && hasFocus) { + if (matches && matches.length > 0) { + scope.activeIdx = focusFirst ? 0 : -1; + isNoResultsSetter(originalScope, false); + scope.matches.length = 0; + + //transform labels + for (var i = 0; i < matches.length; i++) { + locals[parserResult.itemName] = matches[i]; + scope.matches.push({ + id: getMatchId(i), + label: parserResult.viewMapper(scope, locals), + model: matches[i] + }); + } + + scope.query = inputValue; + //position pop-up with matches - we need to re-calculate its position each time we are opening a window + //with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page + //due to other elements being rendered + recalculatePosition(); + + element.attr('aria-expanded', true); + + //Select the single remaining option if user input matches + if (selectOnExact && scope.matches.length === 1 && inputIsExactMatch(inputValue, 0)) { + scope.select(0); + } + } else { + resetMatches(); + isNoResultsSetter(originalScope, true); + } + } + if (onCurrentRequest) { + isLoadingSetter(originalScope, false); + } + }, function() { + resetMatches(); + isLoadingSetter(originalScope, false); + isNoResultsSetter(originalScope, true); + }); + }; + + // bind events only if appendToBody params exist - performance feature + if (appendToBody) { + angular.element($window).bind('resize', fireRecalculating); + $document.find('body').bind('scroll', fireRecalculating); + } + + // Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later + var timeoutEventPromise; + + // Default progress type + scope.moveInProgress = false; + + function fireRecalculating() { + if (!scope.moveInProgress) { + scope.moveInProgress = true; + scope.$digest(); + } + + // Cancel previous timeout + if (timeoutEventPromise) { + $timeout.cancel(timeoutEventPromise); + } + + // Debounced executing recalculate after events fired + timeoutEventPromise = $timeout(function() { + // if popup is visible + if (scope.matches.length) { + recalculatePosition(); + } + + scope.moveInProgress = false; + }, eventDebounceTime); + } + + // recalculate actual position and set new values to scope + // after digest loop is popup in right position + function recalculatePosition() { + scope.position = appendToBody ? $position.offset(element) : $position.position(element); + scope.position.top += element.prop('offsetHeight'); + } + + resetMatches(); + + //we need to propagate user's query so we can higlight matches + scope.query = undefined; + + //Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later + var timeoutPromise; + + var scheduleSearchWithTimeout = function(inputValue) { + timeoutPromise = $timeout(function() { + getMatchesAsync(inputValue); + }, waitTime); + }; + + var cancelPreviousTimeout = function() { + if (timeoutPromise) { + $timeout.cancel(timeoutPromise); + } + }; + + //plug into $parsers pipeline to open a typeahead on view changes initiated from DOM + //$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue + modelCtrl.$parsers.unshift(function(inputValue) { + hasFocus = true; + + if (minLength === 0 || inputValue && inputValue.length >= minLength) { + if (waitTime > 0) { + cancelPreviousTimeout(); + scheduleSearchWithTimeout(inputValue); + } else { + getMatchesAsync(inputValue); + } + } else { + isLoadingSetter(originalScope, false); + cancelPreviousTimeout(); + resetMatches(); + } + + if (isEditable) { + return inputValue; + } else { + if (!inputValue) { + // Reset in case user had typed something previously. + modelCtrl.$setValidity('editable', true); + return null; + } else { + modelCtrl.$setValidity('editable', false); + return undefined; + } + } + }); + + modelCtrl.$formatters.push(function(modelValue) { + var candidateViewValue, emptyViewValue; + var locals = {}; + + // The validity may be set to false via $parsers (see above) if + // the model is restricted to selected values. If the model + // is set manually it is considered to be valid. + if (!isEditable) { + modelCtrl.$setValidity('editable', true); + } + + if (inputFormatter) { + locals.$model = modelValue; + return inputFormatter(originalScope, locals); + } else { + //it might happen that we don't have enough info to properly render input value + //we need to check for this situation and simply return model value if we can't apply custom formatting + locals[parserResult.itemName] = modelValue; + candidateViewValue = parserResult.viewMapper(originalScope, locals); + locals[parserResult.itemName] = undefined; + emptyViewValue = parserResult.viewMapper(originalScope, locals); + + return candidateViewValue !== emptyViewValue ? candidateViewValue : modelValue; + } + }); + + scope.select = function(activeIdx) { + //called from within the $digest() cycle + var locals = {}; + var model, item; + + selected = true; + locals[parserResult.itemName] = item = scope.matches[activeIdx].model; + model = parserResult.modelMapper(originalScope, locals); + $setModelValue(originalScope, model); + modelCtrl.$setValidity('editable', true); + modelCtrl.$setValidity('parse', true); + + onSelectCallback(originalScope, { + $item: item, + $model: model, + $label: parserResult.viewMapper(originalScope, locals) + }); + + resetMatches(); + + //return focus to the input element if a match was selected via a mouse click event + // use timeout to avoid $rootScope:inprog error + if (scope.$eval(attrs.typeaheadFocusOnSelect) !== false) { + $timeout(function() { element[0].focus(); }, 0, false); + } + }; + + //bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27) + element.bind('keydown', function(evt) { + //typeahead is open and an "interesting" key was pressed + if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) { + return; + } + + // if there's nothing selected (i.e. focusFirst) and enter or tab is hit, clear the results + if (scope.activeIdx === -1 && (evt.which === 9 || evt.which === 13)) { + resetMatches(); + scope.$digest(); + return; + } + + evt.preventDefault(); + + if (evt.which === 40) { + scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length; + scope.$digest(); + } else if (evt.which === 38) { + scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1; + scope.$digest(); + } else if (evt.which === 13 || evt.which === 9) { + scope.$apply(function () { + scope.select(scope.activeIdx); + }); + } else if (evt.which === 27) { + evt.stopPropagation(); + + resetMatches(); + scope.$digest(); + } + }); + + element.bind('blur', function() { + if (isSelectOnBlur && scope.matches.length && scope.activeIdx !== -1 && !selected) { + selected = true; + scope.$apply(function() { + scope.select(scope.activeIdx); + }); + } + hasFocus = false; + selected = false; + }); + + // Keep reference to click handler to unbind it. + var dismissClickHandler = function(evt) { + // Issue #3973 + // Firefox treats right click as a click on document + if (element[0] !== evt.target && evt.which !== 3 && scope.matches.length !== 0) { + resetMatches(); + if (!$rootScope.$$phase) { + scope.$digest(); + } + } + }; + + $document.bind('click', dismissClickHandler); + + originalScope.$on('$destroy', function() { + $document.unbind('click', dismissClickHandler); + if (appendToBody || appendToElementId) { + $popup.remove(); + } + + if (appendToBody) { + angular.element($window).unbind('resize', fireRecalculating); + $document.find('body').unbind('scroll', fireRecalculating); + } + // Prevent jQuery cache memory leak + popUpEl.remove(); + }); + + var $popup = $compile(popUpEl)(scope); + + if (appendToBody) { + $document.find('body').append($popup); + } else if (appendToElementId !== false) { + angular.element($document[0].getElementById(appendToElementId)).append($popup); + } else { + element.after($popup); + } + } + }; + }]) + + .directive('typeaheadPopup', ['$typeaheadSuppressWarning', '$log', function($typeaheadSuppressWarning, $log) { + return { + scope: { + matches: '=', + query: '=', + active: '=', + position: '&', + moveInProgress: '=', + select: '&' + }, + replace: true, + templateUrl: function(element, attrs) { + return attrs.popupTemplateUrl || 'template/typeahead/typeahead-popup.html'; + }, + link: function(scope, element, attrs) { + + if (!$typeaheadSuppressWarning) { + $log.warn('typeahead-popup is now deprecated. Use uib-typeahead-popup instead.'); + } + scope.templateUrl = attrs.templateUrl; + + scope.isOpen = function() { + return scope.matches.length > 0; + }; + + scope.isActive = function(matchIdx) { + return scope.active == matchIdx; + }; + + scope.selectActive = function(matchIdx) { + scope.active = matchIdx; + }; + + scope.selectMatch = function(activeIdx) { + scope.select({activeIdx:activeIdx}); + }; + } + }; + }]) + + .directive('typeaheadMatch', ['$templateRequest', '$compile', '$parse', '$typeaheadSuppressWarning', '$log', function($templateRequest, $compile, $parse, $typeaheadSuppressWarning, $log) { + return { + restrict: 'EA', + scope: { + index: '=', + match: '=', + query: '=' + }, + link:function(scope, element, attrs) { + if (!$typeaheadSuppressWarning) { + $log.warn('typeahead-match is now deprecated. Use uib-typeahead-match instead.'); + } + + var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html'; + $templateRequest(tplUrl).then(function(tplContent) { + $compile(tplContent.trim())(scope, function(clonedElement) { + element.replaceWith(clonedElement); + }); + }); + } + }; + }]) + + .filter('typeaheadHighlight', ['$sce', '$injector', '$log', '$typeaheadSuppressWarning', function($sce, $injector, $log, $typeaheadSuppressWarning) { + var isSanitizePresent; + isSanitizePresent = $injector.has('$sanitize'); + + function escapeRegexp(queryToEscape) { + // Regex: capture the whole query string and replace it with the string that will be used to match + // the results, for example if the capture is "a" the result will be \a + return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); + } + + function containsHtml(matchItem) { + return /<.*>/g.test(matchItem); + } + + return function(matchItem, query) { + if (!$typeaheadSuppressWarning) { + $log.warn('typeaheadHighlight is now deprecated. Use uibTypeaheadHighlight instead.'); + } + + if (!isSanitizePresent && containsHtml(matchItem)) { + $log.warn('Unsafe use of typeahead please use ngSanitize'); // Warn the user about the danger + } + + matchItem = query? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '$&') : matchItem; // Replaces the capture string with a the same string inside of a "strong" tag + if (!isSanitizePresent) { + matchItem = $sce.trustAsHtml(matchItem); // If $sanitize is not present we pack the string in a $sce object for the ng-bind-html directive + } + + return matchItem; + }; + }]); + +angular.module("template/accordion/accordion-group.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/accordion/accordion-group.html", + "
\n" + + "
\n" + + "

\n" + + " {{heading}}\n" + + "

\n" + + "
\n" + + "
\n" + + "
\n" + + "
\n" + + "
\n" + + ""); +}]); + +angular.module("template/accordion/accordion.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/accordion/accordion.html", + "
"); +}]); + +angular.module("template/alert/alert.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/alert/alert.html", + "
\n" + + " \n" + + "
\n" + + "
\n" + + ""); +}]); + +angular.module("template/carousel/carousel.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/carousel/carousel.html", + "
\n" + + "
\n" + + " 1\">\n" + + " \n" + + " previous\n" + + " \n" + + " 1\">\n" + + " \n" + + " next\n" + + " \n" + + "
    1\">\n" + + "
  1. \n" + + " slide {{ $index + 1 }} of {{ slides.length }}, currently active\n" + + "
  2. \n" + + "
\n" + + "
"); +}]); + +angular.module("template/carousel/slide.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/carousel/slide.html", + "
\n" + + ""); +}]); + +angular.module("template/datepicker/datepicker.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/datepicker/datepicker.html", + "
\n" + + " \n" + + " \n" + + " \n" + + "
"); +}]); + +angular.module("template/datepicker/day.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/datepicker/day.html", + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "
{{::label.abbr}}
{{ weekNumbers[$index] }}\n" + + " \n" + + "
\n" + + ""); +}]); + +angular.module("template/datepicker/month.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/datepicker/month.html", + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "
\n" + + " \n" + + "
\n" + + ""); +}]); + +angular.module("template/datepicker/popup.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/datepicker/popup.html", + "
    \n" + + "
  • \n" + + "
  • \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "
  • \n" + + "
\n" + + ""); +}]); + +angular.module("template/datepicker/year.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/datepicker/year.html", + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "
\n" + + " \n" + + "
\n" + + ""); +}]); + +angular.module("template/modal/backdrop.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/modal/backdrop.html", + "
\n" + + ""); +}]); + +angular.module("template/modal/window.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/modal/window.html", + "
\n" + + "
\n" + + "
\n" + + ""); +}]); + +angular.module("template/pagination/pager.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/pagination/pager.html", + "\n" + + ""); +}]); + +angular.module("template/pagination/pagination.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/pagination/pagination.html", + "\n" + + ""); +}]); + +angular.module("template/tooltip/tooltip-html-popup.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/tooltip/tooltip-html-popup.html", + "\n" + + "
\n" + + "
\n" + + "\n" + + ""); +}]); + +angular.module("template/tooltip/tooltip-popup.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/tooltip/tooltip-popup.html", + "\n" + + "
\n" + + "
\n" + + "\n" + + ""); +}]); + +angular.module("template/tooltip/tooltip-template-popup.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/tooltip/tooltip-template-popup.html", + "\n" + + "
\n" + + "
\n" + + "\n" + + ""); +}]); + +angular.module("template/popover/popover-html.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/popover/popover-html.html", + "
\n" + + "
\n" + + "\n" + + "
\n" + + "

\n" + + "
\n" + + "
\n" + + "
\n" + + ""); +}]); + +angular.module("template/popover/popover-template.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/popover/popover-template.html", + "
\n" + + "
\n" + + "\n" + + "
\n" + + "

\n" + + "
\n" + + "
\n" + + "
\n" + + ""); +}]); + +angular.module("template/popover/popover.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/popover/popover.html", + "
\n" + + "
\n" + + "\n" + + "
\n" + + "

\n" + + "
\n" + + "
\n" + + "
\n" + + ""); +}]); + +angular.module("template/progressbar/bar.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/progressbar/bar.html", + "
\n" + + ""); +}]); + +angular.module("template/progressbar/progress.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/progressbar/progress.html", + "
"); +}]); + +angular.module("template/progressbar/progressbar.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/progressbar/progressbar.html", + "
\n" + + "
\n" + + "
\n" + + ""); +}]); + +angular.module("template/rating/rating.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/rating/rating.html", + "\n" + + " ({{ $index < value ? '*' : ' ' }})\n" + + " \n" + + "\n" + + ""); +}]); + +angular.module("template/tabs/tab.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/tabs/tab.html", + "
  • \n" + + " {{heading}}\n" + + "
  • \n" + + ""); +}]); + +angular.module("template/tabs/tabset.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/tabs/tabset.html", + "
    \n" + + "
      \n" + + "
      \n" + + "
      \n" + + "
      \n" + + "
      \n" + + "
      \n" + + ""); +}]); + +angular.module("template/timepicker/timepicker.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/timepicker/timepicker.html", + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "
       
      \n" + + " \n" + + " :\n" + + " \n" + + "
       
      \n" + + ""); +}]); + +angular.module("template/typeahead/typeahead-match.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/typeahead/typeahead-match.html", + "\n" + + ""); +}]); + +angular.module("template/typeahead/typeahead-popup.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("template/typeahead/typeahead-popup.html", + "
        \n" + + "
      • \n" + + "
        \n" + + "
      • \n" + + "
      \n" + + ""); +}]); +!angular.$$csp() && angular.element(document).find('head').prepend(''); \ No newline at end of file diff --git a/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js new file mode 100644 index 00000000..f729eda6 --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js @@ -0,0 +1,12 @@ +/* + * angular-ui-bootstrap + * http://angular-ui.github.io/bootstrap/ + + * Version: 0.14.3 - 2015-10-23 + * License: MIT + */ +angular.module("ui.bootstrap",["ui.bootstrap.tpls","ui.bootstrap.collapse","ui.bootstrap.accordion","ui.bootstrap.alert","ui.bootstrap.buttons","ui.bootstrap.carousel","ui.bootstrap.dateparser","ui.bootstrap.position","ui.bootstrap.datepicker","ui.bootstrap.dropdown","ui.bootstrap.stackedMap","ui.bootstrap.modal","ui.bootstrap.pagination","ui.bootstrap.tooltip","ui.bootstrap.popover","ui.bootstrap.progressbar","ui.bootstrap.rating","ui.bootstrap.tabs","ui.bootstrap.timepicker","ui.bootstrap.typeahead"]),angular.module("ui.bootstrap.tpls",["template/accordion/accordion-group.html","template/accordion/accordion.html","template/alert/alert.html","template/carousel/carousel.html","template/carousel/slide.html","template/datepicker/datepicker.html","template/datepicker/day.html","template/datepicker/month.html","template/datepicker/popup.html","template/datepicker/year.html","template/modal/backdrop.html","template/modal/window.html","template/pagination/pager.html","template/pagination/pagination.html","template/tooltip/tooltip-html-popup.html","template/tooltip/tooltip-popup.html","template/tooltip/tooltip-template-popup.html","template/popover/popover-html.html","template/popover/popover-template.html","template/popover/popover.html","template/progressbar/bar.html","template/progressbar/progress.html","template/progressbar/progressbar.html","template/rating/rating.html","template/tabs/tab.html","template/tabs/tabset.html","template/timepicker/timepicker.html","template/typeahead/typeahead-match.html","template/typeahead/typeahead-popup.html"]),angular.module("ui.bootstrap.collapse",[]).directive("uibCollapse",["$animate","$injector",function(a,b){var c=b.has("$animateCss")?b.get("$animateCss"):null;return{link:function(b,d,e){function f(){d.removeClass("collapse").addClass("collapsing").attr("aria-expanded",!0).attr("aria-hidden",!1),c?c(d,{addClass:"in",easing:"ease",to:{height:d[0].scrollHeight+"px"}}).start()["finally"](g):a.addClass(d,"in",{to:{height:d[0].scrollHeight+"px"}}).then(g)}function g(){d.removeClass("collapsing").addClass("collapse").css({height:"auto"})}function h(){return d.hasClass("collapse")||d.hasClass("in")?(d.css({height:d[0].scrollHeight+"px"}).removeClass("collapse").addClass("collapsing").attr("aria-expanded",!1).attr("aria-hidden",!0),void(c?c(d,{removeClass:"in",to:{height:"0"}}).start()["finally"](i):a.removeClass(d,"in",{to:{height:"0"}}).then(i))):i()}function i(){d.css({height:"0"}),d.removeClass("collapsing").addClass("collapse")}b.$watch(e.uibCollapse,function(a){a?h():f()})}}}]),angular.module("ui.bootstrap.collapse").value("$collapseSuppressWarning",!1).directive("collapse",["$animate","$injector","$log","$collapseSuppressWarning",function(a,b,c,d){var e=b.has("$animateCss")?b.get("$animateCss"):null;return{link:function(b,f,g){function h(){f.removeClass("collapse").addClass("collapsing").attr("aria-expanded",!0).attr("aria-hidden",!1),e?e(f,{easing:"ease",to:{height:f[0].scrollHeight+"px"}}).start().done(i):a.animate(f,{},{height:f[0].scrollHeight+"px"}).then(i)}function i(){f.removeClass("collapsing").addClass("collapse in").css({height:"auto"})}function j(){return f.hasClass("collapse")||f.hasClass("in")?(f.css({height:f[0].scrollHeight+"px"}).removeClass("collapse in").addClass("collapsing").attr("aria-expanded",!1).attr("aria-hidden",!0),void(e?e(f,{to:{height:"0"}}).start().done(k):a.animate(f,{},{height:"0"}).then(k))):k()}function k(){f.css({height:"0"}),f.removeClass("collapsing").addClass("collapse")}d||c.warn("collapse is now deprecated. Use uib-collapse instead."),b.$watch(g.collapse,function(a){a?j():h()})}}}]),angular.module("ui.bootstrap.accordion",["ui.bootstrap.collapse"]).constant("uibAccordionConfig",{closeOthers:!0}).controller("UibAccordionController",["$scope","$attrs","uibAccordionConfig",function(a,b,c){this.groups=[],this.closeOthers=function(d){var e=angular.isDefined(b.closeOthers)?a.$eval(b.closeOthers):c.closeOthers;e&&angular.forEach(this.groups,function(a){a!==d&&(a.isOpen=!1)})},this.addGroup=function(a){var b=this;this.groups.push(a),a.$on("$destroy",function(c){b.removeGroup(a)})},this.removeGroup=function(a){var b=this.groups.indexOf(a);-1!==b&&this.groups.splice(b,1)}}]).directive("uibAccordion",function(){return{controller:"UibAccordionController",controllerAs:"accordion",transclude:!0,templateUrl:function(a,b){return b.templateUrl||"template/accordion/accordion.html"}}}).directive("uibAccordionGroup",function(){return{require:"^uibAccordion",transclude:!0,replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/accordion/accordion-group.html"},scope:{heading:"@",isOpen:"=?",isDisabled:"=?"},controller:function(){this.setHeading=function(a){this.heading=a}},link:function(a,b,c,d){d.addGroup(a),a.openClass=c.openClass||"panel-open",a.panelClass=c.panelClass,a.$watch("isOpen",function(c){b.toggleClass(a.openClass,!!c),c&&d.closeOthers(a)}),a.toggleOpen=function(b){a.isDisabled||b&&32!==b.which||(a.isOpen=!a.isOpen)}}}}).directive("uibAccordionHeading",function(){return{transclude:!0,template:"",replace:!0,require:"^uibAccordionGroup",link:function(a,b,c,d,e){d.setHeading(e(a,angular.noop))}}}).directive("uibAccordionTransclude",function(){return{require:["?^uibAccordionGroup","?^accordionGroup"],link:function(a,b,c,d){d=d[0]?d[0]:d[1],a.$watch(function(){return d[c.uibAccordionTransclude]},function(a){a&&(b.find("span").html(""),b.find("span").append(a))})}}}),angular.module("ui.bootstrap.accordion").value("$accordionSuppressWarning",!1).controller("AccordionController",["$scope","$attrs","$controller","$log","$accordionSuppressWarning",function(a,b,c,d,e){e||d.warn("AccordionController is now deprecated. Use UibAccordionController instead."),angular.extend(this,c("UibAccordionController",{$scope:a,$attrs:b}))}]).directive("accordion",["$log","$accordionSuppressWarning",function(a,b){return{restrict:"EA",controller:"AccordionController",controllerAs:"accordion",transclude:!0,replace:!1,templateUrl:function(a,b){return b.templateUrl||"template/accordion/accordion.html"},link:function(){b||a.warn("accordion is now deprecated. Use uib-accordion instead.")}}}]).directive("accordionGroup",["$log","$accordionSuppressWarning",function(a,b){return{require:"^accordion",restrict:"EA",transclude:!0,replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/accordion/accordion-group.html"},scope:{heading:"@",isOpen:"=?",isDisabled:"=?"},controller:function(){this.setHeading=function(a){this.heading=a}},link:function(c,d,e,f){b||a.warn("accordion-group is now deprecated. Use uib-accordion-group instead."),f.addGroup(c),c.openClass=e.openClass||"panel-open",c.panelClass=e.panelClass,c.$watch("isOpen",function(a){d.toggleClass(c.openClass,!!a),a&&f.closeOthers(c)}),c.toggleOpen=function(a){c.isDisabled||a&&32!==a.which||(c.isOpen=!c.isOpen)}}}}]).directive("accordionHeading",["$log","$accordionSuppressWarning",function(a,b){return{restrict:"EA",transclude:!0,template:"",replace:!0,require:"^accordionGroup",link:function(c,d,e,f,g){b||a.warn("accordion-heading is now deprecated. Use uib-accordion-heading instead."),f.setHeading(g(c,angular.noop))}}}]).directive("accordionTransclude",["$log","$accordionSuppressWarning",function(a,b){return{require:"^accordionGroup",link:function(c,d,e,f){b||a.warn("accordion-transclude is now deprecated. Use uib-accordion-transclude instead."),c.$watch(function(){return f[e.accordionTransclude]},function(a){a&&(d.find("span").html(""),d.find("span").append(a))})}}}]),angular.module("ui.bootstrap.alert",[]).controller("UibAlertController",["$scope","$attrs","$interpolate","$timeout",function(a,b,c,d){a.closeable=!!b.close;var e=angular.isDefined(b.dismissOnTimeout)?c(b.dismissOnTimeout)(a.$parent):null;e&&d(function(){a.close()},parseInt(e,10))}]).directive("uibAlert",function(){return{controller:"UibAlertController",controllerAs:"alert",templateUrl:function(a,b){return b.templateUrl||"template/alert/alert.html"},transclude:!0,replace:!0,scope:{type:"@",close:"&"}}}),angular.module("ui.bootstrap.alert").value("$alertSuppressWarning",!1).controller("AlertController",["$scope","$attrs","$controller","$log","$alertSuppressWarning",function(a,b,c,d,e){e||d.warn("AlertController is now deprecated. Use UibAlertController instead."),angular.extend(this,c("UibAlertController",{$scope:a,$attrs:b}))}]).directive("alert",["$log","$alertSuppressWarning",function(a,b){return{controller:"AlertController",controllerAs:"alert",templateUrl:function(a,b){return b.templateUrl||"template/alert/alert.html"},transclude:!0,replace:!0,scope:{type:"@",close:"&"},link:function(){b||a.warn("alert is now deprecated. Use uib-alert instead.")}}}]),angular.module("ui.bootstrap.buttons",[]).constant("uibButtonConfig",{activeClass:"active",toggleEvent:"click"}).controller("UibButtonsController",["uibButtonConfig",function(a){this.activeClass=a.activeClass||"active",this.toggleEvent=a.toggleEvent||"click"}]).directive("uibBtnRadio",function(){return{require:["uibBtnRadio","ngModel"],controller:"UibButtonsController",controllerAs:"buttons",link:function(a,b,c,d){var e=d[0],f=d[1];b.find("input").css({display:"none"}),f.$render=function(){b.toggleClass(e.activeClass,angular.equals(f.$modelValue,a.$eval(c.uibBtnRadio)))},b.on(e.toggleEvent,function(){if(!c.disabled){var d=b.hasClass(e.activeClass);(!d||angular.isDefined(c.uncheckable))&&a.$apply(function(){f.$setViewValue(d?null:a.$eval(c.uibBtnRadio)),f.$render()})}})}}}).directive("uibBtnCheckbox",function(){return{require:["uibBtnCheckbox","ngModel"],controller:"UibButtonsController",controllerAs:"button",link:function(a,b,c,d){function e(){return g(c.btnCheckboxTrue,!0)}function f(){return g(c.btnCheckboxFalse,!1)}function g(b,c){return angular.isDefined(b)?a.$eval(b):c}var h=d[0],i=d[1];b.find("input").css({display:"none"}),i.$render=function(){b.toggleClass(h.activeClass,angular.equals(i.$modelValue,e()))},b.on(h.toggleEvent,function(){c.disabled||a.$apply(function(){i.$setViewValue(b.hasClass(h.activeClass)?f():e()),i.$render()})})}}}),angular.module("ui.bootstrap.buttons").value("$buttonsSuppressWarning",!1).controller("ButtonsController",["$controller","$log","$buttonsSuppressWarning",function(a,b,c){c||b.warn("ButtonsController is now deprecated. Use UibButtonsController instead."),angular.extend(this,a("UibButtonsController"))}]).directive("btnRadio",["$log","$buttonsSuppressWarning",function(a,b){return{require:["btnRadio","ngModel"],controller:"ButtonsController",controllerAs:"buttons",link:function(c,d,e,f){b||a.warn("btn-radio is now deprecated. Use uib-btn-radio instead.");var g=f[0],h=f[1];d.find("input").css({display:"none"}),h.$render=function(){d.toggleClass(g.activeClass,angular.equals(h.$modelValue,c.$eval(e.btnRadio)))},d.bind(g.toggleEvent,function(){if(!e.disabled){var a=d.hasClass(g.activeClass);(!a||angular.isDefined(e.uncheckable))&&c.$apply(function(){h.$setViewValue(a?null:c.$eval(e.btnRadio)),h.$render()})}})}}}]).directive("btnCheckbox",["$document","$log","$buttonsSuppressWarning",function(a,b,c){return{require:["btnCheckbox","ngModel"],controller:"ButtonsController",controllerAs:"button",link:function(d,e,f,g){function h(){return j(f.btnCheckboxTrue,!0)}function i(){return j(f.btnCheckboxFalse,!1)}function j(a,b){var c=d.$eval(a);return angular.isDefined(c)?c:b}c||b.warn("btn-checkbox is now deprecated. Use uib-btn-checkbox instead.");var k=g[0],l=g[1];e.find("input").css({display:"none"}),l.$render=function(){e.toggleClass(k.activeClass,angular.equals(l.$modelValue,h()))},e.bind(k.toggleEvent,function(){f.disabled||d.$apply(function(){l.$setViewValue(e.hasClass(k.activeClass)?i():h()),l.$render()})}),e.on("keypress",function(b){f.disabled||32!==b.which||a[0].activeElement!==e[0]||d.$apply(function(){l.$setViewValue(e.hasClass(k.activeClass)?i():h()),l.$render()})})}}}]),angular.module("ui.bootstrap.carousel",[]).controller("UibCarouselController",["$scope","$element","$interval","$animate",function(a,b,c,d){function e(b,c,e){s||(angular.extend(b,{direction:e,active:!0}),angular.extend(m.currentSlide||{},{direction:e,active:!1}),d.enabled()&&!a.noTransition&&!a.$currentTransition&&b.$element&&m.slides.length>1&&(b.$element.data(q,b.direction),m.currentSlide&&m.currentSlide.$element&&m.currentSlide.$element.data(q,b.direction),a.$currentTransition=!0,o?d.on("addClass",b.$element,function(b,c){"close"===c&&(a.$currentTransition=null,d.off("addClass",b))}):b.$element.one("$animate:close",function(){a.$currentTransition=null})),m.currentSlide=b,r=c,g())}function f(a){if(angular.isUndefined(n[a].index))return n[a];var b;n.length;for(b=0;b0&&(k=c(i,b))}function h(){k&&(c.cancel(k),k=null)}function i(){var b=+a.interval;l&&!isNaN(b)&&b>0&&n.length?a.next():a.pause()}function j(b){b.length||(a.$currentTransition=null)}var k,l,m=this,n=m.slides=a.slides=[],o=angular.version.minor>=4,p="uib-noTransition",q="uib-slideDirection",r=-1;m.currentSlide=null;var s=!1;m.select=a.select=function(b,c){var d=a.indexOfSlide(b);void 0===c&&(c=d>m.getCurrentIndex()?"next":"prev"),b&&b!==m.currentSlide&&!a.$currentTransition&&e(b,d,c)},a.$on("$destroy",function(){s=!0}),m.getCurrentIndex=function(){return m.currentSlide&&angular.isDefined(m.currentSlide.index)?+m.currentSlide.index:r},a.indexOfSlide=function(a){return angular.isDefined(a.index)?+a.index:n.indexOf(a)},a.next=function(){var b=(m.getCurrentIndex()+1)%n.length;return 0===b&&a.noWrap()?void a.pause():m.select(f(b),"next")},a.prev=function(){var b=m.getCurrentIndex()-1<0?n.length-1:m.getCurrentIndex()-1;return a.noWrap()&&b===n.length-1?void a.pause():m.select(f(b),"prev")},a.isActive=function(a){return m.currentSlide===a},a.$watch("interval",g),a.$watchCollection("slides",j),a.$on("$destroy",h),a.play=function(){l||(l=!0,g())},a.pause=function(){a.noPause||(l=!1,h())},m.addSlide=function(b,c){b.$element=c,n.push(b),1===n.length||b.active?(m.select(n[n.length-1]),1===n.length&&a.play()):b.active=!1},m.removeSlide=function(a){angular.isDefined(a.index)&&n.sort(function(a,b){return+a.index>+b.index});var b=n.indexOf(a);n.splice(b,1),n.length>0&&a.active?b>=n.length?m.select(n[b-1]):m.select(n[b]):r>b&&r--,0===n.length&&(m.currentSlide=null)},a.$watch("noTransition",function(a){b.data(p,a)})}]).directive("uibCarousel",[function(){return{transclude:!0,replace:!0,controller:"UibCarouselController",controllerAs:"carousel",require:"carousel",templateUrl:function(a,b){return b.templateUrl||"template/carousel/carousel.html"},scope:{interval:"=",noTransition:"=",noPause:"=",noWrap:"&"}}}]).directive("uibSlide",function(){return{require:"^uibCarousel",restrict:"EA",transclude:!0,replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/carousel/slide.html"},scope:{active:"=?",actual:"=?",index:"=?"},link:function(a,b,c,d){d.addSlide(a,b),a.$on("$destroy",function(){d.removeSlide(a)}),a.$watch("active",function(b){b&&d.select(a)})}}}).animation(".item",["$injector","$animate",function(a,b){function c(a,b,c){a.removeClass(b),c&&c()}var d="uib-noTransition",e="uib-slideDirection",f=null;return a.has("$animateCss")&&(f=a.get("$animateCss")),{beforeAddClass:function(a,g,h){if("active"==g&&a.parent()&&a.parent().parent()&&!a.parent().parent().data(d)){var i=!1,j=a.data(e),k="next"==j?"left":"right",l=c.bind(this,a,k+" "+j,h);return a.addClass(j),f?f(a,{addClass:k}).start().done(l):b.addClass(a,k).then(function(){i||l(),h()}),function(){i=!0}}h()},beforeRemoveClass:function(a,g,h){if("active"===g&&a.parent()&&a.parent().parent()&&!a.parent().parent().data(d)){var i=!1,j=a.data(e),k="next"==j?"left":"right",l=c.bind(this,a,k,h);return f?f(a,{addClass:k}).start().done(l):b.addClass(a,k).then(function(){i||l(),h()}),function(){i=!0}}h()}}}]),angular.module("ui.bootstrap.carousel").value("$carouselSuppressWarning",!1).controller("CarouselController",["$scope","$element","$controller","$log","$carouselSuppressWarning",function(a,b,c,d,e){e||d.warn("CarouselController is now deprecated. Use UibCarouselController instead."),angular.extend(this,c("UibCarouselController",{$scope:a,$element:b}))}]).directive("carousel",["$log","$carouselSuppressWarning",function(a,b){return{transclude:!0,replace:!0,controller:"CarouselController",controllerAs:"carousel",require:"carousel",templateUrl:function(a,b){return b.templateUrl||"template/carousel/carousel.html"},scope:{interval:"=",noTransition:"=",noPause:"=",noWrap:"&"},link:function(){b||a.warn("carousel is now deprecated. Use uib-carousel instead.")}}}]).directive("slide",["$log","$carouselSuppressWarning",function(a,b){return{require:"^carousel",transclude:!0,replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/carousel/slide.html"},scope:{active:"=?",actual:"=?",index:"=?"},link:function(c,d,e,f){b||a.warn("slide is now deprecated. Use uib-slide instead."),f.addSlide(c,d),c.$on("$destroy",function(){f.removeSlide(c)}),c.$watch("active",function(a){a&&f.select(c)})}}}]),angular.module("ui.bootstrap.dateparser",[]).service("uibDateParser",["$log","$locale","orderByFilter",function(a,b,c){function d(a){var b=[],d=a.split("");return angular.forEach(g,function(c,e){var f=a.indexOf(e);if(f>-1){a=a.split(""),d[f]="("+c.regex+")",a[f]="$";for(var g=f+1,h=f+e.length;h>g;g++)d[g]="",a[g]="$";a=a.join(""),b.push({index:f,apply:c.apply})}}),{regex:new RegExp("^"+d.join("")+"$"),map:c(b,"index")}}function e(a,b,c){return 1>c?!1:1===b&&c>28?29===c&&(a%4===0&&a%100!==0||a%400===0):3===b||5===b||8===b||10===b?31>c:!0}var f,g,h=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;this.init=function(){f=b.id,this.parsers={},g={yyyy:{regex:"\\d{4}",apply:function(a){this.year=+a}},yy:{regex:"\\d{2}",apply:function(a){this.year=+a+2e3}},y:{regex:"\\d{1,4}",apply:function(a){this.year=+a}},MMMM:{regex:b.DATETIME_FORMATS.MONTH.join("|"),apply:function(a){this.month=b.DATETIME_FORMATS.MONTH.indexOf(a)}},MMM:{regex:b.DATETIME_FORMATS.SHORTMONTH.join("|"),apply:function(a){this.month=b.DATETIME_FORMATS.SHORTMONTH.indexOf(a)}},MM:{regex:"0[1-9]|1[0-2]",apply:function(a){this.month=a-1}},M:{regex:"[1-9]|1[0-2]",apply:function(a){this.month=a-1}},dd:{regex:"[0-2][0-9]{1}|3[0-1]{1}",apply:function(a){this.date=+a}},d:{regex:"[1-2]?[0-9]{1}|3[0-1]{1}",apply:function(a){this.date=+a}},EEEE:{regex:b.DATETIME_FORMATS.DAY.join("|")},EEE:{regex:b.DATETIME_FORMATS.SHORTDAY.join("|")},HH:{regex:"(?:0|1)[0-9]|2[0-3]",apply:function(a){this.hours=+a}},hh:{regex:"0[0-9]|1[0-2]",apply:function(a){this.hours=+a}},H:{regex:"1?[0-9]|2[0-3]",apply:function(a){this.hours=+a}},h:{regex:"[0-9]|1[0-2]",apply:function(a){this.hours=+a}},mm:{regex:"[0-5][0-9]",apply:function(a){this.minutes=+a}},m:{regex:"[0-9]|[1-5][0-9]",apply:function(a){this.minutes=+a}},sss:{regex:"[0-9][0-9][0-9]",apply:function(a){this.milliseconds=+a}},ss:{regex:"[0-5][0-9]",apply:function(a){this.seconds=+a}},s:{regex:"[0-9]|[1-5][0-9]",apply:function(a){this.seconds=+a}},a:{regex:b.DATETIME_FORMATS.AMPMS.join("|"),apply:function(a){12===this.hours&&(this.hours=0),"PM"===a&&(this.hours+=12)}}}},this.init(),this.parse=function(c,g,i){if(!angular.isString(c)||!g)return c;g=b.DATETIME_FORMATS[g]||g,g=g.replace(h,"\\$&"),b.id!==f&&this.init(),this.parsers[g]||(this.parsers[g]=d(g));var j=this.parsers[g],k=j.regex,l=j.map,m=c.match(k);if(m&&m.length){var n,o;angular.isDate(i)&&!isNaN(i.getTime())?n={year:i.getFullYear(),month:i.getMonth(),date:i.getDate(),hours:i.getHours(),minutes:i.getMinutes(),seconds:i.getSeconds(),milliseconds:i.getMilliseconds()}:(i&&a.warn("dateparser:","baseDate is not a valid date"),n={year:1900,month:0,date:1,hours:0,minutes:0,seconds:0,milliseconds:0});for(var p=1,q=m.length;q>p;p++){var r=l[p-1];r.apply&&r.apply.call(n,m[p])}return e(n.year,n.month,n.date)&&(angular.isDate(i)&&!isNaN(i.getTime())?(o=new Date(i),o.setFullYear(n.year,n.month,n.date,n.hours,n.minutes,n.seconds,n.milliseconds||0)):o=new Date(n.year,n.month,n.date,n.hours,n.minutes,n.seconds,n.milliseconds||0)),o}}}]),angular.module("ui.bootstrap.dateparser").value("$dateParserSuppressWarning",!1).service("dateParser",["$log","$dateParserSuppressWarning","uibDateParser",function(a,b,c){b||a.warn("dateParser is now deprecated. Use uibDateParser instead."),angular.extend(this,c)}]),angular.module("ui.bootstrap.position",[]).factory("$uibPosition",["$document","$window",function(a,b){function c(a,c){return a.currentStyle?a.currentStyle[c]:b.getComputedStyle?b.getComputedStyle(a)[c]:a.style[c]}function d(a){return"static"===(c(a,"position")||"static")}var e=function(b){for(var c=a[0],e=b.offsetParent||c;e&&e!==c&&d(e);)e=e.offsetParent;return e||c};return{position:function(b){var c=this.offset(b),d={top:0,left:0},f=e(b[0]);f!=a[0]&&(d=this.offset(angular.element(f)),d.top+=f.clientTop-f.scrollTop,d.left+=f.clientLeft-f.scrollLeft);var g=b[0].getBoundingClientRect();return{width:g.width||b.prop("offsetWidth"),height:g.height||b.prop("offsetHeight"),top:c.top-d.top,left:c.left-d.left}},offset:function(c){var d=c[0].getBoundingClientRect();return{width:d.width||c.prop("offsetWidth"),height:d.height||c.prop("offsetHeight"),top:d.top+(b.pageYOffset||a[0].documentElement.scrollTop),left:d.left+(b.pageXOffset||a[0].documentElement.scrollLeft)}},positionElements:function(a,b,c,d){var e,f,g,h,i=c.split("-"),j=i[0],k=i[1]||"center";e=d?this.offset(a):this.position(a),f=b.prop("offsetWidth"),g=b.prop("offsetHeight");var l={center:function(){return e.left+e.width/2-f/2},left:function(){return e.left},right:function(){return e.left+e.width}},m={center:function(){return e.top+e.height/2-g/2},top:function(){return e.top},bottom:function(){return e.top+e.height}};switch(j){case"right":h={top:m[k](),left:l[j]()};break;case"left":h={top:m[k](),left:e.left-f};break;case"bottom":h={top:m[j](),left:l[k]()};break;default:h={top:e.top-g,left:l[k]()}}return h}}}]),angular.module("ui.bootstrap.position").value("$positionSuppressWarning",!1).service("$position",["$log","$positionSuppressWarning","$uibPosition",function(a,b,c){b||a.warn("$position is now deprecated. Use $uibPosition instead."),angular.extend(this,c)}]),angular.module("ui.bootstrap.datepicker",["ui.bootstrap.dateparser","ui.bootstrap.position"]).value("$datepickerSuppressError",!1).constant("uibDatepickerConfig",{formatDay:"dd",formatMonth:"MMMM",formatYear:"yyyy",formatDayHeader:"EEE",formatDayTitle:"MMMM yyyy",formatMonthTitle:"yyyy",datepickerMode:"day",minMode:"day",maxMode:"year",showWeeks:!0,startingDay:0,yearRange:20,minDate:null,maxDate:null,shortcutPropagation:!1}).controller("UibDatepickerController",["$scope","$attrs","$parse","$interpolate","$log","dateFilter","uibDatepickerConfig","$datepickerSuppressError",function(a,b,c,d,e,f,g,h){var i=this,j={$setViewValue:angular.noop};this.modes=["day","month","year"],angular.forEach(["formatDay","formatMonth","formatYear","formatDayHeader","formatDayTitle","formatMonthTitle","showWeeks","startingDay","yearRange","shortcutPropagation"],function(c,e){i[c]=angular.isDefined(b[c])?6>e?d(b[c])(a.$parent):a.$parent.$eval(b[c]):g[c]}),angular.forEach(["minDate","maxDate"],function(d){b[d]?a.$parent.$watch(c(b[d]),function(a){i[d]=a?new Date(a):null,i.refreshView()}):i[d]=g[d]?new Date(g[d]):null}),angular.forEach(["minMode","maxMode"],function(d){b[d]?a.$parent.$watch(c(b[d]),function(c){i[d]=angular.isDefined(c)?c:b[d],a[d]=i[d],("minMode"==d&&i.modes.indexOf(a.datepickerMode)i.modes.indexOf(i[d]))&&(a.datepickerMode=i[d])}):(i[d]=g[d]||null,a[d]=i[d])}),a.datepickerMode=a.datepickerMode||g.datepickerMode,a.uniqueId="datepicker-"+a.$id+"-"+Math.floor(1e4*Math.random()),angular.isDefined(b.initDate)?(this.activeDate=a.$parent.$eval(b.initDate)||new Date,a.$parent.$watch(b.initDate,function(a){a&&(j.$isEmpty(j.$modelValue)||j.$invalid)&&(i.activeDate=a,i.refreshView())})):this.activeDate=new Date,a.isActive=function(b){return 0===i.compare(b.date,i.activeDate)?(a.activeDateId=b.uid,!0):!1},this.init=function(a){j=a,j.$render=function(){i.render()}},this.render=function(){if(j.$viewValue){var a=new Date(j.$viewValue),b=!isNaN(a);b?this.activeDate=a:h||e.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.')}this.refreshView()},this.refreshView=function(){if(this.element){this._refreshView();var a=j.$viewValue?new Date(j.$viewValue):null;j.$setValidity("dateDisabled",!a||this.element&&!this.isDisabled(a))}},this.createDateObject=function(a,b){var c=j.$viewValue?new Date(j.$viewValue):null;return{date:a,label:f(a,b),selected:c&&0===this.compare(a,c),disabled:this.isDisabled(a),current:0===this.compare(a,new Date),customClass:this.customClass(a)}},this.isDisabled=function(c){return this.minDate&&this.compare(c,this.minDate)<0||this.maxDate&&this.compare(c,this.maxDate)>0||b.dateDisabled&&a.dateDisabled({date:c,mode:a.datepickerMode})},this.customClass=function(b){return a.customClass({date:b,mode:a.datepickerMode})},this.split=function(a,b){for(var c=[];a.length>0;)c.push(a.splice(0,b));return c},a.select=function(b){if(a.datepickerMode===i.minMode){var c=j.$viewValue?new Date(j.$viewValue):new Date(0,0,0,0,0,0,0);c.setFullYear(b.getFullYear(),b.getMonth(),b.getDate()),j.$setViewValue(c),j.$render()}else i.activeDate=b,a.datepickerMode=i.modes[i.modes.indexOf(a.datepickerMode)-1]},a.move=function(a){var b=i.activeDate.getFullYear()+a*(i.step.years||0),c=i.activeDate.getMonth()+a*(i.step.months||0);i.activeDate.setFullYear(b,c,1),i.refreshView()},a.toggleMode=function(b){b=b||1,a.datepickerMode===i.maxMode&&1===b||a.datepickerMode===i.minMode&&-1===b||(a.datepickerMode=i.modes[i.modes.indexOf(a.datepickerMode)+b])},a.keys={13:"enter",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down"};var k=function(){i.element[0].focus()};a.$on("uib:datepicker.focus",k),a.keydown=function(b){var c=a.keys[b.which];if(c&&!b.shiftKey&&!b.altKey)if(b.preventDefault(),i.shortcutPropagation||b.stopPropagation(),"enter"===c||"space"===c){if(i.isDisabled(i.activeDate))return;a.select(i.activeDate)}else!b.ctrlKey||"up"!==c&&"down"!==c?(i.handleKeyDown(c,b),i.refreshView()):a.toggleMode("up"===c?1:-1)}}]).controller("UibDaypickerController",["$scope","$element","dateFilter",function(a,b,c){function d(a,b){return 1!==b||a%4!==0||a%100===0&&a%400!==0?f[b]:29}function e(a){var b=new Date(a);b.setDate(b.getDate()+4-(b.getDay()||7));var c=b.getTime();return b.setMonth(0),b.setDate(1),Math.floor(Math.round((c-b)/864e5)/7)+1}var f=[31,28,31,30,31,30,31,31,30,31,30,31];this.step={months:1},this.element=b,this.init=function(b){angular.extend(b,this),a.showWeeks=b.showWeeks,b.refreshView()},this.getDates=function(a,b){for(var c,d=new Array(b),e=new Date(a),f=0;b>f;)c=new Date(e),d[f++]=c,e.setDate(e.getDate()+1);return d},this._refreshView=function(){var b=this.activeDate.getFullYear(),d=this.activeDate.getMonth(),f=new Date(this.activeDate);f.setFullYear(b,d,1);var g=this.startingDay-f.getDay(),h=g>0?7-g:-g,i=new Date(f);h>0&&i.setDate(-h+1);for(var j=this.getDates(i,42),k=0;42>k;k++)j[k]=angular.extend(this.createDateObject(j[k],this.formatDay),{secondary:j[k].getMonth()!==d,uid:a.uniqueId+"-"+k});a.labels=new Array(7);for(var l=0;7>l;l++)a.labels[l]={abbr:c(j[l].date,this.formatDayHeader),full:c(j[l].date,"EEEE")};if(a.title=c(this.activeDate,this.formatDayTitle),a.rows=this.split(j,7),a.showWeeks){a.weekNumbers=[];for(var m=(11-this.startingDay)%7,n=a.rows.length,o=0;n>o;o++)a.weekNumbers.push(e(a.rows[o][m].date))}},this.compare=function(a,b){return new Date(a.getFullYear(),a.getMonth(),a.getDate())-new Date(b.getFullYear(),b.getMonth(),b.getDate())},this.handleKeyDown=function(a,b){var c=this.activeDate.getDate();if("left"===a)c-=1;else if("up"===a)c-=7;else if("right"===a)c+=1;else if("down"===a)c+=7;else if("pageup"===a||"pagedown"===a){var e=this.activeDate.getMonth()+("pageup"===a?-1:1);this.activeDate.setMonth(e,1),c=Math.min(d(this.activeDate.getFullYear(),this.activeDate.getMonth()),c)}else"home"===a?c=1:"end"===a&&(c=d(this.activeDate.getFullYear(),this.activeDate.getMonth()));this.activeDate.setDate(c)}}]).controller("UibMonthpickerController",["$scope","$element","dateFilter",function(a,b,c){this.step={years:1},this.element=b,this.init=function(a){angular.extend(a,this),a.refreshView()},this._refreshView=function(){for(var b,d=new Array(12),e=this.activeDate.getFullYear(),f=0;12>f;f++)b=new Date(this.activeDate),b.setFullYear(e,f,1),d[f]=angular.extend(this.createDateObject(b,this.formatMonth),{uid:a.uniqueId+"-"+f});a.title=c(this.activeDate,this.formatMonthTitle),a.rows=this.split(d,3)},this.compare=function(a,b){return new Date(a.getFullYear(),a.getMonth())-new Date(b.getFullYear(),b.getMonth())},this.handleKeyDown=function(a,b){var c=this.activeDate.getMonth();if("left"===a)c-=1;else if("up"===a)c-=3;else if("right"===a)c+=1;else if("down"===a)c+=3;else if("pageup"===a||"pagedown"===a){var d=this.activeDate.getFullYear()+("pageup"===a?-1:1);this.activeDate.setFullYear(d)}else"home"===a?c=0:"end"===a&&(c=11);this.activeDate.setMonth(c)}}]).controller("UibYearpickerController",["$scope","$element","dateFilter",function(a,b,c){function d(a){return parseInt((a-1)/e,10)*e+1}var e;this.element=b,this.yearpickerInit=function(){e=this.yearRange,this.step={years:e}},this._refreshView=function(){for(var b,c=new Array(e),f=0,g=d(this.activeDate.getFullYear());e>f;f++)b=new Date(this.activeDate),b.setFullYear(g+f,0,1),c[f]=angular.extend(this.createDateObject(b,this.formatYear),{uid:a.uniqueId+"-"+f});a.title=[c[0].label,c[e-1].label].join(" - "),a.rows=this.split(c,5)},this.compare=function(a,b){return a.getFullYear()-b.getFullYear()},this.handleKeyDown=function(a,b){var c=this.activeDate.getFullYear();"left"===a?c-=1:"up"===a?c-=5:"right"===a?c+=1:"down"===a?c+=5:"pageup"===a||"pagedown"===a?c+=("pageup"===a?-1:1)*this.step.years:"home"===a?c=d(this.activeDate.getFullYear()):"end"===a&&(c=d(this.activeDate.getFullYear())+e-1),this.activeDate.setFullYear(c)}}]).directive("uibDatepicker",function(){return{replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/datepicker/datepicker.html"},scope:{datepickerMode:"=?",dateDisabled:"&",customClass:"&",shortcutPropagation:"&?"},require:["uibDatepicker","^ngModel"],controller:"UibDatepickerController",controllerAs:"datepicker",link:function(a,b,c,d){var e=d[0],f=d[1];e.init(f)}}}).directive("uibDaypicker",function(){return{replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/datepicker/day.html"},require:["^?uibDatepicker","uibDaypicker","^?datepicker"],controller:"UibDaypickerController",link:function(a,b,c,d){var e=d[0]||d[2],f=d[1];f.init(e)}}}).directive("uibMonthpicker",function(){return{replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/datepicker/month.html"},require:["^?uibDatepicker","uibMonthpicker","^?datepicker"],controller:"UibMonthpickerController",link:function(a,b,c,d){var e=d[0]||d[2],f=d[1];f.init(e)}}}).directive("uibYearpicker",function(){return{replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/datepicker/year.html"},require:["^?uibDatepicker","uibYearpicker","^?datepicker"],controller:"UibYearpickerController",link:function(a,b,c,d){var e=d[0]||d[2];angular.extend(e,d[1]),e.yearpickerInit(),e.refreshView()}}}).constant("uibDatepickerPopupConfig",{datepickerPopup:"yyyy-MM-dd",datepickerPopupTemplateUrl:"template/datepicker/popup.html",datepickerTemplateUrl:"template/datepicker/datepicker.html",html5Types:{date:"yyyy-MM-dd","datetime-local":"yyyy-MM-ddTHH:mm:ss.sss",month:"yyyy-MM"},currentText:"Today",clearText:"Clear",closeText:"Done",closeOnDateSelection:!0,appendToBody:!1,showButtonBar:!0,onOpenFocus:!0}).controller("UibDatepickerPopupController",["$scope","$element","$attrs","$compile","$parse","$document","$rootScope","$uibPosition","dateFilter","uibDateParser","uibDatepickerPopupConfig","$timeout",function(a,b,c,d,e,f,g,h,i,j,k,l){ +function m(a){return a.replace(/([A-Z])/g,function(a){return"-"+a.toLowerCase()})}function n(b){if(angular.isNumber(b)&&(b=new Date(b)),b){if(angular.isDate(b)&&!isNaN(b))return b;if(angular.isString(b)){var c=j.parse(b,r,a.date);return isNaN(c)?void 0:c}return void 0}return null}function o(a,b){var d=a||b;if(!c.ngRequired&&!d)return!0;if(angular.isNumber(d)&&(d=new Date(d)),d){if(angular.isDate(d)&&!isNaN(d))return!0;if(angular.isString(d)){var e=j.parse(d,r);return!isNaN(e)}return!1}return!0}function p(c){var d=A[0],e=b[0].contains(c.target),f=void 0!==d.contains&&d.contains(c.target);!a.isOpen||e||f||a.$apply(function(){a.isOpen=!1})}function q(c){27===c.which&&a.isOpen?(c.preventDefault(),c.stopPropagation(),a.$apply(function(){a.isOpen=!1}),b[0].focus()):40!==c.which||a.isOpen||(c.preventDefault(),c.stopPropagation(),a.$apply(function(){a.isOpen=!0}))}var r,s,t,u,v,w,x,y,z,A,B={},C=!1;a.watchData={},this.init=function(h){if(z=h,s=angular.isDefined(c.closeOnDateSelection)?a.$parent.$eval(c.closeOnDateSelection):k.closeOnDateSelection,t=angular.isDefined(c.datepickerAppendToBody)?a.$parent.$eval(c.datepickerAppendToBody):k.appendToBody,u=angular.isDefined(c.onOpenFocus)?a.$parent.$eval(c.onOpenFocus):k.onOpenFocus,v=angular.isDefined(c.datepickerPopupTemplateUrl)?c.datepickerPopupTemplateUrl:k.datepickerPopupTemplateUrl,w=angular.isDefined(c.datepickerTemplateUrl)?c.datepickerTemplateUrl:k.datepickerTemplateUrl,a.showButtonBar=angular.isDefined(c.showButtonBar)?a.$parent.$eval(c.showButtonBar):k.showButtonBar,k.html5Types[c.type]?(r=k.html5Types[c.type],C=!0):(r=c.datepickerPopup||c.uibDatepickerPopup||k.datepickerPopup,c.$observe("uibDatepickerPopup",function(a,b){var c=a||k.datepickerPopup;if(c!==r&&(r=c,z.$modelValue=null,!r))throw new Error("uibDatepickerPopup must have a date format specified.")})),!r)throw new Error("uibDatepickerPopup must have a date format specified.");if(C&&c.datepickerPopup)throw new Error("HTML5 date input types do not support custom formats.");if(x=angular.element("
      "),x.attr({"ng-model":"date","ng-change":"dateSelection(date)","template-url":v}),y=angular.element(x.children()[0]),y.attr("template-url",w),C&&"month"===c.type&&(y.attr("datepicker-mode",'"month"'),y.attr("min-mode","month")),c.datepickerOptions){var l=a.$parent.$eval(c.datepickerOptions);l&&l.initDate&&(a.initDate=l.initDate,y.attr("init-date","initDate"),delete l.initDate),angular.forEach(l,function(a,b){y.attr(m(b),a)})}angular.forEach(["minMode","maxMode","minDate","maxDate","datepickerMode","initDate","shortcutPropagation"],function(b){if(c[b]){var d=e(c[b]);if(a.$parent.$watch(d,function(c){a.watchData[b]=c,("minDate"===b||"maxDate"===b)&&(B[b]=new Date(c))}),y.attr(m(b),"watchData."+b),"datepickerMode"===b){var f=d.assign;a.$watch("watchData."+b,function(b,c){angular.isFunction(f)&&b!==c&&f(a.$parent,b)})}}}),c.dateDisabled&&y.attr("date-disabled","dateDisabled({ date: date, mode: mode })"),c.showWeeks&&y.attr("show-weeks",c.showWeeks),c.customClass&&y.attr("custom-class","customClass({ date: date, mode: mode })"),C?z.$formatters.push(function(b){return a.date=b,b}):(z.$$parserName="date",z.$validators.date=o,z.$parsers.unshift(n),z.$formatters.push(function(b){return a.date=b,z.$isEmpty(b)?b:i(b,r)})),z.$viewChangeListeners.push(function(){a.date=j.parse(z.$viewValue,r,a.date)}),b.bind("keydown",q),A=d(x)(a),x.remove(),t?f.find("body").append(A):b.after(A),a.$on("$destroy",function(){a.isOpen===!0&&(g.$$phase||a.$apply(function(){a.isOpen=!1})),A.remove(),b.unbind("keydown",q),f.unbind("click",p)})},a.getText=function(b){return a[b+"Text"]||k[b+"Text"]},a.isDisabled=function(b){return"today"===b&&(b=new Date),a.watchData.minDate&&a.compare(b,B.minDate)<0||a.watchData.maxDate&&a.compare(b,B.maxDate)>0},a.compare=function(a,b){return new Date(a.getFullYear(),a.getMonth(),a.getDate())-new Date(b.getFullYear(),b.getMonth(),b.getDate())},a.dateSelection=function(c){angular.isDefined(c)&&(a.date=c);var d=a.date?i(a.date,r):null;b.val(d),z.$setViewValue(d),s&&(a.isOpen=!1,b[0].focus())},a.keydown=function(c){27===c.which&&(a.isOpen=!1,b[0].focus())},a.select=function(b){if("today"===b){var c=new Date;angular.isDate(a.date)?(b=new Date(a.date),b.setFullYear(c.getFullYear(),c.getMonth(),c.getDate())):b=new Date(c.setHours(0,0,0,0))}a.dateSelection(b)},a.close=function(){a.isOpen=!1,b[0].focus()},a.$watch("isOpen",function(c){c?(a.position=t?h.offset(b):h.position(b),a.position.top=a.position.top+b.prop("offsetHeight"),l(function(){u&&a.$broadcast("uib:datepicker.focus"),f.bind("click",p)},0,!1)):f.unbind("click",p)})}]).directive("uibDatepickerPopup",function(){return{require:["ngModel","uibDatepickerPopup"],controller:"UibDatepickerPopupController",scope:{isOpen:"=?",currentText:"@",clearText:"@",closeText:"@",dateDisabled:"&",customClass:"&"},link:function(a,b,c,d){var e=d[0],f=d[1];f.init(e)}}}).directive("uibDatepickerPopupWrap",function(){return{replace:!0,transclude:!0,templateUrl:function(a,b){return b.templateUrl||"template/datepicker/popup.html"}}}),angular.module("ui.bootstrap.datepicker").value("$datepickerSuppressWarning",!1).controller("DatepickerController",["$scope","$attrs","$parse","$interpolate","$log","dateFilter","uibDatepickerConfig","$datepickerSuppressError","$datepickerSuppressWarning",function(a,b,c,d,e,f,g,h,i){i||e.warn("DatepickerController is now deprecated. Use UibDatepickerController instead.");var j=this,k={$setViewValue:angular.noop};this.modes=["day","month","year"],angular.forEach(["formatDay","formatMonth","formatYear","formatDayHeader","formatDayTitle","formatMonthTitle","showWeeks","startingDay","yearRange","shortcutPropagation"],function(c,e){j[c]=angular.isDefined(b[c])?6>e?d(b[c])(a.$parent):a.$parent.$eval(b[c]):g[c]}),angular.forEach(["minDate","maxDate"],function(d){b[d]?a.$parent.$watch(c(b[d]),function(a){j[d]=a?new Date(a):null,j.refreshView()}):j[d]=g[d]?new Date(g[d]):null}),angular.forEach(["minMode","maxMode"],function(d){b[d]?a.$parent.$watch(c(b[d]),function(c){j[d]=angular.isDefined(c)?c:b[d],a[d]=j[d],("minMode"==d&&j.modes.indexOf(a.datepickerMode)j.modes.indexOf(j[d]))&&(a.datepickerMode=j[d])}):(j[d]=g[d]||null,a[d]=j[d])}),a.datepickerMode=a.datepickerMode||g.datepickerMode,a.uniqueId="datepicker-"+a.$id+"-"+Math.floor(1e4*Math.random()),angular.isDefined(b.initDate)?(this.activeDate=a.$parent.$eval(b.initDate)||new Date,a.$parent.$watch(b.initDate,function(a){a&&(k.$isEmpty(k.$modelValue)||k.$invalid)&&(j.activeDate=a,j.refreshView())})):this.activeDate=new Date,a.isActive=function(b){return 0===j.compare(b.date,j.activeDate)?(a.activeDateId=b.uid,!0):!1},this.init=function(a){k=a,k.$render=function(){j.render()}},this.render=function(){if(k.$viewValue){var a=new Date(k.$viewValue),b=!isNaN(a);b?this.activeDate=a:h||e.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.')}this.refreshView()},this.refreshView=function(){if(this.element){this._refreshView();var a=k.$viewValue?new Date(k.$viewValue):null;k.$setValidity("dateDisabled",!a||this.element&&!this.isDisabled(a))}},this.createDateObject=function(a,b){var c=k.$viewValue?new Date(k.$viewValue):null;return{date:a,label:f(a,b),selected:c&&0===this.compare(a,c),disabled:this.isDisabled(a),current:0===this.compare(a,new Date),customClass:this.customClass(a)}},this.isDisabled=function(c){return this.minDate&&this.compare(c,this.minDate)<0||this.maxDate&&this.compare(c,this.maxDate)>0||b.dateDisabled&&a.dateDisabled({date:c,mode:a.datepickerMode})},this.customClass=function(b){return a.customClass({date:b,mode:a.datepickerMode})},this.split=function(a,b){for(var c=[];a.length>0;)c.push(a.splice(0,b));return c},this.fixTimeZone=function(a){var b=a.getHours();a.setHours(23===b?b+2:0)},a.select=function(b){if(a.datepickerMode===j.minMode){var c=k.$viewValue?new Date(k.$viewValue):new Date(0,0,0,0,0,0,0);c.setFullYear(b.getFullYear(),b.getMonth(),b.getDate()),k.$setViewValue(c),k.$render()}else j.activeDate=b,a.datepickerMode=j.modes[j.modes.indexOf(a.datepickerMode)-1]},a.move=function(a){var b=j.activeDate.getFullYear()+a*(j.step.years||0),c=j.activeDate.getMonth()+a*(j.step.months||0);j.activeDate.setFullYear(b,c,1),j.refreshView()},a.toggleMode=function(b){b=b||1,a.datepickerMode===j.maxMode&&1===b||a.datepickerMode===j.minMode&&-1===b||(a.datepickerMode=j.modes[j.modes.indexOf(a.datepickerMode)+b])},a.keys={13:"enter",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down"};var l=function(){j.element[0].focus()};a.$on("uib:datepicker.focus",l),a.keydown=function(b){var c=a.keys[b.which];if(c&&!b.shiftKey&&!b.altKey)if(b.preventDefault(),j.shortcutPropagation||b.stopPropagation(),"enter"===c||"space"===c){if(j.isDisabled(j.activeDate))return;a.select(j.activeDate)}else!b.ctrlKey||"up"!==c&&"down"!==c?(j.handleKeyDown(c,b),j.refreshView()):a.toggleMode("up"===c?1:-1)}}]).directive("datepicker",["$log","$datepickerSuppressWarning",function(a,b){return{replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/datepicker/datepicker.html"},scope:{datepickerMode:"=?",dateDisabled:"&",customClass:"&",shortcutPropagation:"&?"},require:["datepicker","^ngModel"],controller:"DatepickerController",controllerAs:"datepicker",link:function(c,d,e,f){b||a.warn("datepicker is now deprecated. Use uib-datepicker instead.");var g=f[0],h=f[1];g.init(h)}}}]).directive("daypicker",["$log","$datepickerSuppressWarning",function(a,b){return{replace:!0,templateUrl:"template/datepicker/day.html",require:["^datepicker","daypicker"],controller:"UibDaypickerController",link:function(c,d,e,f){b||a.warn("daypicker is now deprecated. Use uib-daypicker instead.");var g=f[0],h=f[1];h.init(g)}}}]).directive("monthpicker",["$log","$datepickerSuppressWarning",function(a,b){return{replace:!0,templateUrl:"template/datepicker/month.html",require:["^datepicker","monthpicker"],controller:"UibMonthpickerController",link:function(c,d,e,f){b||a.warn("monthpicker is now deprecated. Use uib-monthpicker instead.");var g=f[0],h=f[1];h.init(g)}}}]).directive("yearpicker",["$log","$datepickerSuppressWarning",function(a,b){return{replace:!0,templateUrl:"template/datepicker/year.html",require:["^datepicker","yearpicker"],controller:"UibYearpickerController",link:function(c,d,e,f){b||a.warn("yearpicker is now deprecated. Use uib-yearpicker instead.");var g=f[0];angular.extend(g,f[1]),g.yearpickerInit(),g.refreshView()}}}]).directive("datepickerPopup",["$log","$datepickerSuppressWarning",function(a,b){return{require:["ngModel","datepickerPopup"],controller:"UibDatepickerPopupController",scope:{isOpen:"=?",currentText:"@",clearText:"@",closeText:"@",dateDisabled:"&",customClass:"&"},link:function(c,d,e,f){b||a.warn("datepicker-popup is now deprecated. Use uib-datepicker-popup instead.");var g=f[0],h=f[1];h.init(g)}}}]).directive("datepickerPopupWrap",["$log","$datepickerSuppressWarning",function(a,b){return{replace:!0,transclude:!0,templateUrl:function(a,b){return b.templateUrl||"template/datepicker/popup.html"},link:function(){b||a.warn("datepicker-popup-wrap is now deprecated. Use uib-datepicker-popup-wrap instead.")}}}]),angular.module("ui.bootstrap.dropdown",["ui.bootstrap.position"]).constant("uibDropdownConfig",{openClass:"open"}).service("uibDropdownService",["$document","$rootScope",function(a,b){var c=null;this.open=function(b){c||(a.bind("click",d),a.bind("keydown",e)),c&&c!==b&&(c.isOpen=!1),c=b},this.close=function(b){c===b&&(c=null,a.unbind("click",d),a.unbind("keydown",e))};var d=function(a){if(c&&(!a||"disabled"!==c.getAutoClose())){var d=c.getToggleElement();if(!(a&&d&&d[0].contains(a.target))){var e=c.getDropdownElement();a&&"outsideClick"===c.getAutoClose()&&e&&e[0].contains(a.target)||(c.isOpen=!1,b.$$phase||c.$apply())}}},e=function(a){27===a.which?(c.focusToggleElement(),d()):c.isKeynavEnabled()&&/(38|40)/.test(a.which)&&c.isOpen&&(a.preventDefault(),a.stopPropagation(),c.focusDropdownEntry(a.which))}}]).controller("UibDropdownController",["$scope","$element","$attrs","$parse","uibDropdownConfig","uibDropdownService","$animate","$uibPosition","$document","$compile","$templateRequest",function(a,b,c,d,e,f,g,h,i,j,k){var l,m,n=this,o=a.$new(),p=e.openClass,q=angular.noop,r=c.onToggle?d(c.onToggle):angular.noop,s=!1,t=!1;b.addClass("dropdown"),this.init=function(){c.isOpen&&(m=d(c.isOpen),q=m.assign,a.$watch(m,function(a){o.isOpen=!!a})),s=angular.isDefined(c.dropdownAppendToBody),t=angular.isDefined(c.uibKeyboardNav),s&&n.dropdownMenu&&(i.find("body").append(n.dropdownMenu),b.on("$destroy",function(){n.dropdownMenu.remove()}))},this.toggle=function(a){return o.isOpen=arguments.length?!!a:!o.isOpen},this.isOpen=function(){return o.isOpen},o.getToggleElement=function(){return n.toggleElement},o.getAutoClose=function(){return c.autoClose||"always"},o.getElement=function(){return b},o.isKeynavEnabled=function(){return t},o.focusDropdownEntry=function(a){var c=n.dropdownMenu?angular.element(n.dropdownMenu).find("a"):angular.element(b).find("ul").eq(0).find("a");switch(a){case 40:angular.isNumber(n.selectedOption)?n.selectedOption=n.selectedOption===c.length-1?n.selectedOption:n.selectedOption+1:n.selectedOption=0;break;case 38:angular.isNumber(n.selectedOption)?n.selectedOption=0===n.selectedOption?0:n.selectedOption-1:n.selectedOption=c.length-1}c[n.selectedOption].focus()},o.getDropdownElement=function(){return n.dropdownMenu},o.focusToggleElement=function(){n.toggleElement&&n.toggleElement[0].focus()},o.$watch("isOpen",function(c,d){if(s&&n.dropdownMenu){var e=h.positionElements(b,n.dropdownMenu,"bottom-left",!0),i={top:e.top+"px",display:c?"block":"none"},m=n.dropdownMenu.hasClass("dropdown-menu-right");m?(i.left="auto",i.right=window.innerWidth-(e.left+b.prop("offsetWidth"))+"px"):(i.left=e.left+"px",i.right="auto"),n.dropdownMenu.css(i)}if(g[c?"addClass":"removeClass"](b,p).then(function(){angular.isDefined(c)&&c!==d&&r(a,{open:!!c})}),c)n.dropdownMenuTemplateUrl&&k(n.dropdownMenuTemplateUrl).then(function(a){l=o.$new(),j(a.trim())(l,function(a){var b=a;n.dropdownMenu.replaceWith(b),n.dropdownMenu=b})}),o.focusToggleElement(),f.open(o);else{if(n.dropdownMenuTemplateUrl){l&&l.$destroy();var t=angular.element('');n.dropdownMenu.replaceWith(t),n.dropdownMenu=t}f.close(o),n.selectedOption=null}angular.isFunction(q)&&q(a,c)}),a.$on("$locationChangeSuccess",function(){"disabled"!==o.getAutoClose()&&(o.isOpen=!1)});var u=a.$on("$destroy",function(){o.$destroy()});o.$on("$destroy",u)}]).directive("uibDropdown",function(){return{controller:"UibDropdownController",link:function(a,b,c,d){d.init()}}}).directive("uibDropdownMenu",function(){return{restrict:"AC",require:"?^uibDropdown",link:function(a,b,c,d){if(d&&!angular.isDefined(c.dropdownNested)){b.addClass("dropdown-menu");var e=c.templateUrl;e&&(d.dropdownMenuTemplateUrl=e),d.dropdownMenu||(d.dropdownMenu=b)}}}}).directive("uibKeyboardNav",function(){return{restrict:"A",require:"?^uibDropdown",link:function(a,b,c,d){b.bind("keydown",function(a){if(-1!==[38,40].indexOf(a.which)){a.preventDefault(),a.stopPropagation();var b=d.dropdownMenu.find("a");switch(a.which){case 40:angular.isNumber(d.selectedOption)?d.selectedOption=d.selectedOption===b.length-1?d.selectedOption:d.selectedOption+1:d.selectedOption=0;break;case 38:angular.isNumber(d.selectedOption)?d.selectedOption=0===d.selectedOption?0:d.selectedOption-1:d.selectedOption=b.length-1}b[d.selectedOption].focus()}})}}}).directive("uibDropdownToggle",function(){return{require:"?^uibDropdown",link:function(a,b,c,d){if(d){b.addClass("dropdown-toggle"),d.toggleElement=b;var e=function(e){e.preventDefault(),b.hasClass("disabled")||c.disabled||a.$apply(function(){d.toggle()})};b.bind("click",e),b.attr({"aria-haspopup":!0,"aria-expanded":!1}),a.$watch(d.isOpen,function(a){b.attr("aria-expanded",!!a)}),a.$on("$destroy",function(){b.unbind("click",e)})}}}}),angular.module("ui.bootstrap.dropdown").value("$dropdownSuppressWarning",!1).service("dropdownService",["$log","$dropdownSuppressWarning","uibDropdownService",function(a,b,c){b||a.warn("dropdownService is now deprecated. Use uibDropdownService instead."),angular.extend(this,c)}]).controller("DropdownController",["$scope","$element","$attrs","$parse","uibDropdownConfig","uibDropdownService","$animate","$uibPosition","$document","$compile","$templateRequest","$log","$dropdownSuppressWarning",function(a,b,c,d,e,f,g,h,i,j,k,l,m){m||l.warn("DropdownController is now deprecated. Use UibDropdownController instead.");var n,o,p=this,q=a.$new(),r=e.openClass,s=angular.noop,t=c.onToggle?d(c.onToggle):angular.noop,u=!1,v=!1;b.addClass("dropdown"),this.init=function(){c.isOpen&&(o=d(c.isOpen),s=o.assign,a.$watch(o,function(a){q.isOpen=!!a})),u=angular.isDefined(c.dropdownAppendToBody),v=angular.isDefined(c.uibKeyboardNav),u&&p.dropdownMenu&&(i.find("body").append(p.dropdownMenu),b.on("$destroy",function(){p.dropdownMenu.remove()}))},this.toggle=function(a){return q.isOpen=arguments.length?!!a:!q.isOpen},this.isOpen=function(){return q.isOpen},q.getToggleElement=function(){return p.toggleElement},q.getAutoClose=function(){return c.autoClose||"always"},q.getElement=function(){return b},q.isKeynavEnabled=function(){return v},q.focusDropdownEntry=function(a){var c=p.dropdownMenu?angular.element(p.dropdownMenu).find("a"):angular.element(b).find("ul").eq(0).find("a");switch(a){case 40:angular.isNumber(p.selectedOption)?p.selectedOption=p.selectedOption===c.length-1?p.selectedOption:p.selectedOption+1:p.selectedOption=0;break;case 38:angular.isNumber(p.selectedOption)?p.selectedOption=0===p.selectedOption?0:p.selectedOption-1:p.selectedOption=c.length-1}c[p.selectedOption].focus()},q.getDropdownElement=function(){return p.dropdownMenu},q.focusToggleElement=function(){p.toggleElement&&p.toggleElement[0].focus()},q.$watch("isOpen",function(c,d){if(u&&p.dropdownMenu){var e=h.positionElements(b,p.dropdownMenu,"bottom-left",!0),i={top:e.top+"px",display:c?"block":"none"},l=p.dropdownMenu.hasClass("dropdown-menu-right");l?(i.left="auto",i.right=window.innerWidth-(e.left+b.prop("offsetWidth"))+"px"):(i.left=e.left+"px",i.right="auto"),p.dropdownMenu.css(i)}if(g[c?"addClass":"removeClass"](b,r).then(function(){angular.isDefined(c)&&c!==d&&t(a,{open:!!c})}),c)p.dropdownMenuTemplateUrl&&k(p.dropdownMenuTemplateUrl).then(function(a){n=q.$new(),j(a.trim())(n,function(a){var b=a;p.dropdownMenu.replaceWith(b),p.dropdownMenu=b})}),q.focusToggleElement(),f.open(q);else{if(p.dropdownMenuTemplateUrl){n&&n.$destroy();var m=angular.element('');p.dropdownMenu.replaceWith(m),p.dropdownMenu=m}f.close(q),p.selectedOption=null}angular.isFunction(s)&&s(a,c)}),a.$on("$locationChangeSuccess",function(){"disabled"!==q.getAutoClose()&&(q.isOpen=!1)});var w=a.$on("$destroy",function(){q.$destroy()});q.$on("$destroy",w)}]).directive("dropdown",["$log","$dropdownSuppressWarning",function(a,b){return{controller:"DropdownController",link:function(c,d,e,f){b||a.warn("dropdown is now deprecated. Use uib-dropdown instead."),f.init()}}}]).directive("dropdownMenu",["$log","$dropdownSuppressWarning",function(a,b){return{restrict:"AC",require:"?^dropdown",link:function(c,d,e,f){if(f&&!angular.isDefined(e.dropdownNested)){b||a.warn("dropdown-menu is now deprecated. Use uib-dropdown-menu instead."),d.addClass("dropdown-menu");var g=e.templateUrl;g&&(f.dropdownMenuTemplateUrl=g),f.dropdownMenu||(f.dropdownMenu=d)}}}}]).directive("keyboardNav",["$log","$dropdownSuppressWarning",function(a,b){return{restrict:"A",require:"?^dropdown",link:function(c,d,e,f){b||a.warn("keyboard-nav is now deprecated. Use uib-keyboard-nav instead."),d.bind("keydown",function(a){if(-1!==[38,40].indexOf(a.which)){a.preventDefault(),a.stopPropagation();var b=f.dropdownMenu.find("a");switch(a.which){case 40:angular.isNumber(f.selectedOption)?f.selectedOption=f.selectedOption===b.length-1?f.selectedOption:f.selectedOption+1:f.selectedOption=0;break;case 38:angular.isNumber(f.selectedOption)?f.selectedOption=0===f.selectedOption?0:f.selectedOption-1:f.selectedOption=b.length-1}b[f.selectedOption].focus()}})}}}]).directive("dropdownToggle",["$log","$dropdownSuppressWarning",function(a,b){return{require:"?^dropdown",link:function(c,d,e,f){if(b||a.warn("dropdown-toggle is now deprecated. Use uib-dropdown-toggle instead."),f){d.addClass("dropdown-toggle"),f.toggleElement=d;var g=function(a){a.preventDefault(),d.hasClass("disabled")||e.disabled||c.$apply(function(){f.toggle()})};d.bind("click",g),d.attr({"aria-haspopup":!0,"aria-expanded":!1}),c.$watch(f.isOpen,function(a){d.attr("aria-expanded",!!a)}),c.$on("$destroy",function(){d.unbind("click",g)})}}}}]),angular.module("ui.bootstrap.stackedMap",[]).factory("$$stackedMap",function(){return{createNew:function(){var a=[];return{add:function(b,c){a.push({key:b,value:c})},get:function(b){for(var c=0;c0&&(b=u.top().value,b.modalDomEl.toggleClass(b.windowTopClass||"",a))}function m(){if(q&&-1==j()){var a=r;n(q,r,function(){a=null}),q=void 0,r=void 0}}function n(b,c,d){function e(){e.done||(e.done=!0,p?p(b,{event:"leave"}).start().then(function(){b.remove()}):a.leave(b),c.$destroy(),d&&d())}var g,h=null,i=function(){return g||(g=f.defer(),h=g.promise),function(){g.resolve()}};return c.$broadcast(w.NOW_CLOSING_EVENT,i),f.when(h).then(e)}function o(a,b,c){return!a.value.modalScope.$broadcast("modal.closing",b,c).defaultPrevented}var p=null;g.has("$animateCss")&&(p=g.get("$animateCss"));var q,r,s,t="modal-open",u=i.createNew(),v=h.createNew(),w={NOW_CLOSING_EVENT:"modal.stack.now-closing"},x=0,y="a[href], area[href], input:not([disabled]), button:not([disabled]),select:not([disabled]), textarea:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable=true]";return e.$watch(j,function(a){r&&(r.index=a)}),c.bind("keydown",function(a){if(a.isDefaultPrevented())return a;var b=u.top();if(b&&b.value.keyboard)switch(a.which){case 27:a.preventDefault(),e.$apply(function(){w.dismiss(b.key,"escape key press")});break;case 9:w.loadFocusElementList(b);var c=!1;a.shiftKey?w.isFocusInFirstItem(a)&&(c=w.focusLastFocusableElement()):w.isFocusInLastItem(a)&&(c=w.focusFirstFocusableElement()),c&&(a.preventDefault(),a.stopPropagation())}}),w.open=function(a,b){var f=c[0].activeElement,g=b.openedClass||t;l(!1),u.add(a,{deferred:b.deferred,renderDeferred:b.renderDeferred,modalScope:b.scope,backdrop:b.backdrop,keyboard:b.keyboard,openedClass:b.openedClass,windowTopClass:b.windowTopClass}),v.put(g,a);var h=c.find("body").eq(0),i=j();if(i>=0&&!q){r=e.$new(!0),r.index=i;var k=angular.element('
      ');k.attr("backdrop-class",b.backdropClass),b.animation&&k.attr("modal-animation","true"),q=d(k)(r),h.append(q)}var m=angular.element('
      ');m.attr({"template-url":b.windowTemplateUrl,"window-class":b.windowClass,"window-top-class":b.windowTopClass,size:b.size,index:u.length()-1,animate:"animate"}).html(b.content),b.animation&&m.attr("modal-animation","true");var n=d(m)(b.scope);u.top().value.modalDomEl=n,u.top().value.modalOpener=f,h.append(n),h.addClass(g),w.clearFocusListCache()},w.close=function(a,b){var c=u.get(a);return c&&o(c,b,!0)?(c.value.modalScope.$$uibDestructionScheduled=!0,c.value.deferred.resolve(b),k(a,c.value.modalOpener),!0):!c},w.dismiss=function(a,b){var c=u.get(a);return c&&o(c,b,!1)?(c.value.modalScope.$$uibDestructionScheduled=!0,c.value.deferred.reject(b),k(a,c.value.modalOpener),!0):!c},w.dismissAll=function(a){for(var b=this.getTop();b&&this.dismiss(b.key,a);)b=this.getTop()},w.getTop=function(){return u.top()},w.modalRendered=function(a){var b=u.get(a);b&&b.value.renderDeferred.resolve()},w.focusFirstFocusableElement=function(){return s.length>0?(s[0].focus(),!0):!1},w.focusLastFocusableElement=function(){return s.length>0?(s[s.length-1].focus(),!0):!1},w.isFocusInFirstItem=function(a){return s.length>0?(a.target||a.srcElement)==s[0]:!1},w.isFocusInLastItem=function(a){return s.length>0?(a.target||a.srcElement)==s[s.length-1]:!1},w.clearFocusListCache=function(){s=[],x=0},w.loadFocusElementList=function(a){if((void 0===s||!s.length)&&a){var b=a.value.modalDomEl;b&&b.length&&(s=b[0].querySelectorAll(y))}},w}]).provider("$uibModal",function(){var a={options:{animation:!0,backdrop:!0,keyboard:!0},$get:["$injector","$rootScope","$q","$templateRequest","$controller","$uibModalStack","$modalSuppressWarning","$log",function(b,c,d,e,f,g,h,i){function j(a){return a.template?d.when(a.template):e(angular.isFunction(a.templateUrl)?a.templateUrl():a.templateUrl)}function k(a){var c=[];return angular.forEach(a,function(a){angular.isFunction(a)||angular.isArray(a)?c.push(d.when(b.invoke(a))):angular.isString(a)?c.push(d.when(b.get(a))):c.push(d.when(a))}),c}var l={},m=null;return l.getPromiseChain=function(){return m},l.open=function(b){function e(){return r}var l=d.defer(),n=d.defer(),o=d.defer(),p={result:l.promise,opened:n.promise,rendered:o.promise,close:function(a){return g.close(p,a)},dismiss:function(a){return g.dismiss(p,a)}};if(b=angular.extend({},a.options,b),b.resolve=b.resolve||{},!b.template&&!b.templateUrl)throw new Error("One of template or templateUrl options is required.");var q,r=d.all([j(b)].concat(k(b.resolve)));return q=m=d.all([m]).then(e,e).then(function(a){var d=(b.scope||c).$new();d.$close=p.close,d.$dismiss=p.dismiss,d.$on("$destroy",function(){d.$$uibDestructionScheduled||d.$dismiss("$uibUnscheduledDestruction")});var e,j={},k=1;b.controller&&(j.$scope=d,j.$uibModalInstance=p,Object.defineProperty(j,"$modalInstance",{get:function(){return h||i.warn("$modalInstance is now deprecated. Use $uibModalInstance instead."),p}}),angular.forEach(b.resolve,function(b,c){j[c]=a[k++]}),e=f(b.controller,j),b.controllerAs&&(b.bindToController&&angular.extend(e,d),d[b.controllerAs]=e)),g.open(p,{scope:d,deferred:l,renderDeferred:o,content:a[0],animation:b.animation,backdrop:b.backdrop,keyboard:b.keyboard,backdropClass:b.backdropClass,windowTopClass:b.windowTopClass,windowClass:b.windowClass,windowTemplateUrl:b.windowTemplateUrl,size:b.size,openedClass:b.openedClass}),n.resolve(!0)},function(a){n.reject(a),l.reject(a)})["finally"](function(){m===q&&(m=null)}),p},l}]};return a}),angular.module("ui.bootstrap.modal").value("$modalSuppressWarning",!1).directive("modalBackdrop",["$animate","$injector","$modalStack","$log","$modalSuppressWarning",function(a,b,c,d,e){function f(b,f,h){e||d.warn("modal-backdrop is now deprecated. Use uib-modal-backdrop instead."),f.addClass("modal-backdrop"),h.modalInClass&&(g?g(f,{addClass:h.modalInClass}).start():a.addClass(f,h.modalInClass),b.$on(c.NOW_CLOSING_EVENT,function(b,c){var d=c();g?g(f,{removeClass:h.modalInClass}).start().then(d):a.removeClass(f,h.modalInClass).then(d)}))}var g=null;return b.has("$animateCss")&&(g=b.get("$animateCss")),{replace:!0,templateUrl:"template/modal/backdrop.html",compile:function(a,b){return a.addClass(b.backdropClass),f}}}]).directive("modalWindow",["$modalStack","$q","$animate","$injector","$log","$modalSuppressWarning",function(a,b,c,d,e,f){var g=null;return d.has("$animateCss")&&(g=d.get("$animateCss")),{scope:{index:"@"},replace:!0,transclude:!0,templateUrl:function(a,b){return b.templateUrl||"template/modal/window.html"},link:function(d,h,i){f||e.warn("modal-window is now deprecated. Use uib-modal-window instead."),h.addClass(i.windowClass||""),h.addClass(i.windowTopClass||""),d.size=i.size,d.close=function(b){var c=a.getTop();c&&c.value.backdrop&&"static"!==c.value.backdrop&&b.target===b.currentTarget&&(b.preventDefault(),b.stopPropagation(),a.dismiss(c.key,"backdrop click"))},h.on("click",d.close),d.$isRendered=!0;var j=b.defer();i.$observe("modalRender",function(a){"true"==a&&j.resolve()}),j.promise.then(function(){var e=null;i.modalInClass&&(e=g?g(h,{addClass:i.modalInClass}).start():c.addClass(h,i.modalInClass),d.$on(a.NOW_CLOSING_EVENT,function(a,b){var d=b();g?g(h,{removeClass:i.modalInClass}).start().then(d):c.removeClass(h,i.modalInClass).then(d)})),b.when(e).then(function(){var a=h[0].querySelector("[autofocus]");a?a.focus():h[0].focus()});var f=a.getTop();f&&a.modalRendered(f.key)})}}}]).directive("modalAnimationClass",["$log","$modalSuppressWarning",function(a,b){return{compile:function(c,d){b||a.warn("modal-animation-class is now deprecated. Use uib-modal-animation-class instead."),d.modalAnimation&&c.addClass(d.modalAnimationClass)}}}]).directive("modalTransclude",["$log","$modalSuppressWarning",function(a,b){return{link:function(c,d,e,f,g){ +b||a.warn("modal-transclude is now deprecated. Use uib-modal-transclude instead."),g(c.$parent,function(a){d.empty(),d.append(a)})}}}]).service("$modalStack",["$animate","$timeout","$document","$compile","$rootScope","$q","$injector","$$multiMap","$$stackedMap","$uibModalStack","$log","$modalSuppressWarning",function(a,b,c,d,e,f,g,h,i,j,k,l){l||k.warn("$modalStack is now deprecated. Use $uibModalStack instead."),angular.extend(this,j)}]).provider("$modal",["$uibModalProvider",function(a){angular.extend(this,a),this.$get=["$injector","$log","$modalSuppressWarning",function(b,c,d){return d||c.warn("$modal is now deprecated. Use $uibModal instead."),b.invoke(a.$get)}]}]),angular.module("ui.bootstrap.pagination",[]).controller("UibPaginationController",["$scope","$attrs","$parse",function(a,b,c){var d=this,e={$setViewValue:angular.noop},f=b.numPages?c(b.numPages).assign:angular.noop;this.init=function(g,h){e=g,this.config=h,e.$render=function(){d.render()},b.itemsPerPage?a.$parent.$watch(c(b.itemsPerPage),function(b){d.itemsPerPage=parseInt(b,10),a.totalPages=d.calculateTotalPages()}):this.itemsPerPage=h.itemsPerPage,a.$watch("totalItems",function(){a.totalPages=d.calculateTotalPages()}),a.$watch("totalPages",function(b){f(a.$parent,b),a.page>b?a.selectPage(b):e.$render()})},this.calculateTotalPages=function(){var b=this.itemsPerPage<1?1:Math.ceil(a.totalItems/this.itemsPerPage);return Math.max(b||0,1)},this.render=function(){a.page=parseInt(e.$viewValue,10)||1},a.selectPage=function(b,c){c&&c.preventDefault();var d=!a.ngDisabled||!c;d&&a.page!==b&&b>0&&b<=a.totalPages&&(c&&c.target&&c.target.blur(),e.$setViewValue(b),e.$render())},a.getText=function(b){return a[b+"Text"]||d.config[b+"Text"]},a.noPrevious=function(){return 1===a.page},a.noNext=function(){return a.page===a.totalPages}}]).constant("uibPaginationConfig",{itemsPerPage:10,boundaryLinks:!1,directionLinks:!0,firstText:"First",previousText:"Previous",nextText:"Next",lastText:"Last",rotate:!0}).directive("uibPagination",["$parse","uibPaginationConfig",function(a,b){return{restrict:"EA",scope:{totalItems:"=",firstText:"@",previousText:"@",nextText:"@",lastText:"@",ngDisabled:"="},require:["uibPagination","?ngModel"],controller:"UibPaginationController",controllerAs:"pagination",templateUrl:function(a,b){return b.templateUrl||"template/pagination/pagination.html"},replace:!0,link:function(c,d,e,f){function g(a,b,c){return{number:a,text:b,active:c}}function h(a,b){var c=[],d=1,e=b,f=angular.isDefined(k)&&b>k;f&&(l?(d=Math.max(a-Math.floor(k/2),1),e=d+k-1,e>b&&(e=b,d=e-k+1)):(d=(Math.ceil(a/k)-1)*k+1,e=Math.min(d+k-1,b)));for(var h=d;e>=h;h++){var i=g(h,h,h===a);c.push(i)}if(f&&!l){if(d>1){var j=g(d-1,"...",!1);c.unshift(j)}if(b>e){var m=g(e+1,"...",!1);c.push(m)}}return c}var i=f[0],j=f[1];if(j){var k=angular.isDefined(e.maxSize)?c.$parent.$eval(e.maxSize):b.maxSize,l=angular.isDefined(e.rotate)?c.$parent.$eval(e.rotate):b.rotate;c.boundaryLinks=angular.isDefined(e.boundaryLinks)?c.$parent.$eval(e.boundaryLinks):b.boundaryLinks,c.directionLinks=angular.isDefined(e.directionLinks)?c.$parent.$eval(e.directionLinks):b.directionLinks,i.init(j,b),e.maxSize&&c.$parent.$watch(a(e.maxSize),function(a){k=parseInt(a,10),i.render()});var m=i.render;i.render=function(){m(),c.page>0&&c.page<=c.totalPages&&(c.pages=h(c.page,c.totalPages))}}}}}]).constant("uibPagerConfig",{itemsPerPage:10,previousText:"« Previous",nextText:"Next »",align:!0}).directive("uibPager",["uibPagerConfig",function(a){return{restrict:"EA",scope:{totalItems:"=",previousText:"@",nextText:"@",ngDisabled:"="},require:["uibPager","?ngModel"],controller:"UibPaginationController",controllerAs:"pagination",templateUrl:function(a,b){return b.templateUrl||"template/pagination/pager.html"},replace:!0,link:function(b,c,d,e){var f=e[0],g=e[1];g&&(b.align=angular.isDefined(d.align)?b.$parent.$eval(d.align):a.align,f.init(g,a))}}}]),angular.module("ui.bootstrap.pagination").value("$paginationSuppressWarning",!1).controller("PaginationController",["$scope","$attrs","$parse","$log","$paginationSuppressWarning",function(a,b,c,d,e){e||d.warn("PaginationController is now deprecated. Use UibPaginationController instead.");var f=this,g={$setViewValue:angular.noop},h=b.numPages?c(b.numPages).assign:angular.noop;this.init=function(d,e){g=d,this.config=e,g.$render=function(){f.render()},b.itemsPerPage?a.$parent.$watch(c(b.itemsPerPage),function(b){f.itemsPerPage=parseInt(b,10),a.totalPages=f.calculateTotalPages()}):this.itemsPerPage=e.itemsPerPage,a.$watch("totalItems",function(){a.totalPages=f.calculateTotalPages()}),a.$watch("totalPages",function(b){h(a.$parent,b),a.page>b?a.selectPage(b):g.$render()})},this.calculateTotalPages=function(){var b=this.itemsPerPage<1?1:Math.ceil(a.totalItems/this.itemsPerPage);return Math.max(b||0,1)},this.render=function(){a.page=parseInt(g.$viewValue,10)||1},a.selectPage=function(b,c){c&&c.preventDefault();var d=!a.ngDisabled||!c;d&&a.page!==b&&b>0&&b<=a.totalPages&&(c&&c.target&&c.target.blur(),g.$setViewValue(b),g.$render())},a.getText=function(b){return a[b+"Text"]||f.config[b+"Text"]},a.noPrevious=function(){return 1===a.page},a.noNext=function(){return a.page===a.totalPages}}]).directive("pagination",["$parse","uibPaginationConfig","$log","$paginationSuppressWarning",function(a,b,c,d){return{restrict:"EA",scope:{totalItems:"=",firstText:"@",previousText:"@",nextText:"@",lastText:"@",ngDisabled:"="},require:["pagination","?ngModel"],controller:"PaginationController",controllerAs:"pagination",templateUrl:function(a,b){return b.templateUrl||"template/pagination/pagination.html"},replace:!0,link:function(e,f,g,h){function i(a,b,c){return{number:a,text:b,active:c}}function j(a,b){var c=[],d=1,e=b,f=angular.isDefined(m)&&b>m;f&&(n?(d=Math.max(a-Math.floor(m/2),1),e=d+m-1,e>b&&(e=b,d=e-m+1)):(d=(Math.ceil(a/m)-1)*m+1,e=Math.min(d+m-1,b)));for(var g=d;e>=g;g++){var h=i(g,g,g===a);c.push(h)}if(f&&!n){if(d>1){var j=i(d-1,"...",!1);c.unshift(j)}if(b>e){var k=i(e+1,"...",!1);c.push(k)}}return c}d||c.warn("pagination is now deprecated. Use uib-pagination instead.");var k=h[0],l=h[1];if(l){var m=angular.isDefined(g.maxSize)?e.$parent.$eval(g.maxSize):b.maxSize,n=angular.isDefined(g.rotate)?e.$parent.$eval(g.rotate):b.rotate;e.boundaryLinks=angular.isDefined(g.boundaryLinks)?e.$parent.$eval(g.boundaryLinks):b.boundaryLinks,e.directionLinks=angular.isDefined(g.directionLinks)?e.$parent.$eval(g.directionLinks):b.directionLinks,k.init(l,b),g.maxSize&&e.$parent.$watch(a(g.maxSize),function(a){m=parseInt(a,10),k.render()});var o=k.render;k.render=function(){o(),e.page>0&&e.page<=e.totalPages&&(e.pages=j(e.page,e.totalPages))}}}}}]).directive("pager",["uibPagerConfig","$log","$paginationSuppressWarning",function(a,b,c){return{restrict:"EA",scope:{totalItems:"=",previousText:"@",nextText:"@",ngDisabled:"="},require:["pager","?ngModel"],controller:"PaginationController",controllerAs:"pagination",templateUrl:function(a,b){return b.templateUrl||"template/pagination/pager.html"},replace:!0,link:function(d,e,f,g){c||b.warn("pager is now deprecated. Use uib-pager instead.");var h=g[0],i=g[1];i&&(d.align=angular.isDefined(f.align)?d.$parent.$eval(f.align):a.align,h.init(i,a))}}}]),angular.module("ui.bootstrap.tooltip",["ui.bootstrap.position","ui.bootstrap.stackedMap"]).provider("$uibTooltip",function(){function a(a){var b=/[A-Z]/g,c="-";return a.replace(b,function(a,b){return(b?c:"")+a.toLowerCase()})}var b={placement:"top",animation:!0,popupDelay:0,popupCloseDelay:0,useContentExp:!1},c={mouseenter:"mouseleave",click:"click",focus:"blur",none:""},d={};this.options=function(a){angular.extend(d,a)},this.setTriggers=function(a){angular.extend(c,a)},this.$get=["$window","$compile","$timeout","$document","$uibPosition","$interpolate","$rootScope","$parse","$$stackedMap",function(e,f,g,h,i,j,k,l,m){var n=m.createNew();return h.on("keypress",function(a){if(27===a.which){var b=n.top();b&&(b.value.close(),n.removeTop(),b=null)}}),function(e,k,m,o){function p(a){var b=(a||o.trigger||m).split(" "),d=b.map(function(a){return c[a]||a});return{show:b,hide:d}}o=angular.extend({},b,d,o);var q=a(e),r=j.startSymbol(),s=j.endSymbol(),t="
      ';return{compile:function(a,b){var c=f(t);return function(a,b,d,f){function j(){L.isOpen?q():m()}function m(){(!K||a.$eval(d[k+"Enable"]))&&(u(),x(),L.popupDelay?F||(F=g(r,L.popupDelay,!1)):r())}function q(){s(),L.popupCloseDelay?G||(G=g(t,L.popupCloseDelay,!1)):t()}function r(){return s(),u(),L.content?(v(),void L.$evalAsync(function(){L.isOpen=!0,y(!0),Q()})):angular.noop}function s(){F&&(g.cancel(F),F=null),H&&(g.cancel(H),H=null)}function t(){s(),u(),L&&L.$evalAsync(function(){L.isOpen=!1,y(!1),L.animation?E||(E=g(w,150,!1)):w()})}function u(){G&&(g.cancel(G),G=null),E&&(g.cancel(E),E=null)}function v(){C||(D=L.$new(),C=c(D,function(a){I?h.find("body").append(a):b.after(a)}),z())}function w(){A(),E=null,C&&(C.remove(),C=null),D&&(D.$destroy(),D=null)}function x(){L.title=d[k+"Title"],O?L.content=O(a):L.content=d[e],L.popupClass=d[k+"Class"],L.placement=angular.isDefined(d[k+"Placement"])?d[k+"Placement"]:o.placement;var b=parseInt(d[k+"PopupDelay"],10),c=parseInt(d[k+"PopupCloseDelay"],10);L.popupDelay=isNaN(b)?o.popupDelay:b,L.popupCloseDelay=isNaN(c)?o.popupCloseDelay:c}function y(b){N&&angular.isFunction(N.assign)&&N.assign(a,b)}function z(){P.length=0,O?(P.push(a.$watch(O,function(a){L.content=a,!a&&L.isOpen&&t()})),P.push(D.$watch(function(){M||(M=!0,D.$$postDigest(function(){M=!1,L&&L.isOpen&&Q()}))}))):P.push(d.$observe(e,function(a){L.content=a,!a&&L.isOpen?t():Q()})),P.push(d.$observe(k+"Title",function(a){L.title=a,L.isOpen&&Q()})),P.push(d.$observe(k+"Placement",function(a){L.placement=a?a:o.placement,L.isOpen&&Q()}))}function A(){P.length&&(angular.forEach(P,function(a){a()}),P.length=0)}function B(){var a=d[k+"Trigger"];R(),J=p(a),"none"!==J.show&&J.show.forEach(function(a,c){a===J.hide[c]?b[0].addEventListener(a,j):a&&(b[0].addEventListener(a,m),J.hide[c].split(" ").forEach(function(a){b[0].addEventListener(a,q)})),b.on("keypress",function(a){27===a.which&&q()})})}var C,D,E,F,G,H,I=angular.isDefined(o.appendToBody)?o.appendToBody:!1,J=p(void 0),K=angular.isDefined(d[k+"Enable"]),L=a.$new(!0),M=!1,N=angular.isDefined(d[k+"IsOpen"])?l(d[k+"IsOpen"]):!1,O=o.useContentExp?l(d[e]):!1,P=[],Q=function(){C&&C.html()&&(H||(H=g(function(){C.css({top:0,left:0});var a=i.positionElements(b,C,L.placement,I);a.top+="px",a.left+="px",a.visibility="visible",C.css(a),H=null},0,!1)))};L.origScope=a,L.isOpen=!1,n.add(L,{close:t}),L.contentExp=function(){return L.content},d.$observe("disabled",function(a){a&&s(),a&&L.isOpen&&t()}),N&&a.$watch(N,function(a){L&&!a===L.isOpen&&j()});var R=function(){J.show.forEach(function(a){b.unbind(a,m)}),J.hide.forEach(function(a){a.split(" ").forEach(function(a){b[0].removeEventListener(a,q)})})};B();var S=a.$eval(d[k+"Animation"]);L.animation=angular.isDefined(S)?!!S:o.animation;var T=a.$eval(d[k+"AppendToBody"]);I=angular.isDefined(T)?T:I,I&&a.$on("$locationChangeSuccess",function(){L.isOpen&&t()}),a.$on("$destroy",function(){s(),u(),R(),w(),n.remove(L),L=null})}}}}}]}).directive("uibTooltipTemplateTransclude",["$animate","$sce","$compile","$templateRequest",function(a,b,c,d){return{link:function(e,f,g){var h,i,j,k=e.$eval(g.tooltipTemplateTranscludeScope),l=0,m=function(){i&&(i.remove(),i=null),h&&(h.$destroy(),h=null),j&&(a.leave(j).then(function(){i=null}),i=j,j=null)};e.$watch(b.parseAsResourceUrl(g.uibTooltipTemplateTransclude),function(b){var g=++l;b?(d(b,!0).then(function(d){if(g===l){var e=k.$new(),i=d,n=c(i)(e,function(b){m(),a.enter(b,f)});h=e,j=n,h.$emit("$includeContentLoaded",b)}},function(){g===l&&(m(),e.$emit("$includeContentError",b))}),e.$emit("$includeContentRequested",b)):m()}),e.$on("$destroy",m)}}}]).directive("uibTooltipClasses",function(){return{restrict:"A",link:function(a,b,c){a.placement&&b.addClass(a.placement),a.popupClass&&b.addClass(a.popupClass),a.animation()&&b.addClass(c.tooltipAnimationClass)}}}).directive("uibTooltipPopup",function(){return{replace:!0,scope:{content:"@",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/tooltip/tooltip-popup.html",link:function(a,b){b.addClass("tooltip")}}}).directive("uibTooltip",["$uibTooltip",function(a){return a("uibTooltip","tooltip","mouseenter")}]).directive("uibTooltipTemplatePopup",function(){return{replace:!0,scope:{contentExp:"&",placement:"@",popupClass:"@",animation:"&",isOpen:"&",originScope:"&"},templateUrl:"template/tooltip/tooltip-template-popup.html",link:function(a,b){b.addClass("tooltip")}}}).directive("uibTooltipTemplate",["$uibTooltip",function(a){return a("uibTooltipTemplate","tooltip","mouseenter",{useContentExp:!0})}]).directive("uibTooltipHtmlPopup",function(){return{replace:!0,scope:{contentExp:"&",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/tooltip/tooltip-html-popup.html",link:function(a,b){b.addClass("tooltip")}}}).directive("uibTooltipHtml",["$uibTooltip",function(a){return a("uibTooltipHtml","tooltip","mouseenter",{useContentExp:!0})}]),angular.module("ui.bootstrap.tooltip").value("$tooltipSuppressWarning",!1).provider("$tooltip",["$uibTooltipProvider",function(a){angular.extend(this,a),this.$get=["$log","$tooltipSuppressWarning","$injector",function(b,c,d){return c||b.warn("$tooltip is now deprecated. Use $uibTooltip instead."),d.invoke(a.$get)}]}]).directive("tooltipTemplateTransclude",["$animate","$sce","$compile","$templateRequest","$log","$tooltipSuppressWarning",function(a,b,c,d,e,f){return{link:function(g,h,i){f||e.warn("tooltip-template-transclude is now deprecated. Use uib-tooltip-template-transclude instead.");var j,k,l,m=g.$eval(i.tooltipTemplateTranscludeScope),n=0,o=function(){k&&(k.remove(),k=null),j&&(j.$destroy(),j=null),l&&(a.leave(l).then(function(){k=null}),k=l,l=null)};g.$watch(b.parseAsResourceUrl(i.tooltipTemplateTransclude),function(b){var e=++n;b?(d(b,!0).then(function(d){if(e===n){var f=m.$new(),g=d,i=c(g)(f,function(b){o(),a.enter(b,h)});j=f,l=i,j.$emit("$includeContentLoaded",b)}},function(){e===n&&(o(),g.$emit("$includeContentError",b))}),g.$emit("$includeContentRequested",b)):o()}),g.$on("$destroy",o)}}}]).directive("tooltipClasses",["$log","$tooltipSuppressWarning",function(a,b){return{restrict:"A",link:function(c,d,e){b||a.warn("tooltip-classes is now deprecated. Use uib-tooltip-classes instead."),c.placement&&d.addClass(c.placement),c.popupClass&&d.addClass(c.popupClass),c.animation()&&d.addClass(e.tooltipAnimationClass)}}}]).directive("tooltipPopup",["$log","$tooltipSuppressWarning",function(a,b){return{replace:!0,scope:{content:"@",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/tooltip/tooltip-popup.html",link:function(c,d){b||a.warn("tooltip-popup is now deprecated. Use uib-tooltip-popup instead."),d.addClass("tooltip")}}}]).directive("tooltip",["$tooltip",function(a){return a("tooltip","tooltip","mouseenter")}]).directive("tooltipTemplatePopup",["$log","$tooltipSuppressWarning",function(a,b){return{replace:!0,scope:{contentExp:"&",placement:"@",popupClass:"@",animation:"&",isOpen:"&",originScope:"&"},templateUrl:"template/tooltip/tooltip-template-popup.html",link:function(c,d){b||a.warn("tooltip-template-popup is now deprecated. Use uib-tooltip-template-popup instead."),d.addClass("tooltip")}}}]).directive("tooltipTemplate",["$tooltip",function(a){return a("tooltipTemplate","tooltip","mouseenter",{useContentExp:!0})}]).directive("tooltipHtmlPopup",["$log","$tooltipSuppressWarning",function(a,b){return{replace:!0,scope:{contentExp:"&",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/tooltip/tooltip-html-popup.html",link:function(c,d){b||a.warn("tooltip-html-popup is now deprecated. Use uib-tooltip-html-popup instead."),d.addClass("tooltip")}}}]).directive("tooltipHtml",["$tooltip",function(a){return a("tooltipHtml","tooltip","mouseenter",{useContentExp:!0})}]),angular.module("ui.bootstrap.popover",["ui.bootstrap.tooltip"]).directive("uibPopoverTemplatePopup",function(){return{replace:!0,scope:{title:"@",contentExp:"&",placement:"@",popupClass:"@",animation:"&",isOpen:"&",originScope:"&"},templateUrl:"template/popover/popover-template.html",link:function(a,b){b.addClass("popover")}}}).directive("uibPopoverTemplate",["$uibTooltip",function(a){return a("uibPopoverTemplate","popover","click",{useContentExp:!0})}]).directive("uibPopoverHtmlPopup",function(){return{replace:!0,scope:{contentExp:"&",title:"@",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/popover/popover-html.html",link:function(a,b){b.addClass("popover")}}}).directive("uibPopoverHtml",["$uibTooltip",function(a){return a("uibPopoverHtml","popover","click",{useContentExp:!0})}]).directive("uibPopoverPopup",function(){return{replace:!0,scope:{title:"@",content:"@",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/popover/popover.html",link:function(a,b){b.addClass("popover")}}}).directive("uibPopover",["$uibTooltip",function(a){return a("uibPopover","popover","click")}]),angular.module("ui.bootstrap.popover").value("$popoverSuppressWarning",!1).directive("popoverTemplatePopup",["$log","$popoverSuppressWarning",function(a,b){return{replace:!0,scope:{title:"@",contentExp:"&",placement:"@",popupClass:"@",animation:"&",isOpen:"&",originScope:"&"},templateUrl:"template/popover/popover-template.html",link:function(c,d){b||a.warn("popover-template-popup is now deprecated. Use uib-popover-template-popup instead."),d.addClass("popover")}}}]).directive("popoverTemplate",["$tooltip",function(a){return a("popoverTemplate","popover","click",{useContentExp:!0})}]).directive("popoverHtmlPopup",["$log","$popoverSuppressWarning",function(a,b){return{replace:!0,scope:{contentExp:"&",title:"@",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/popover/popover-html.html",link:function(c,d){b||a.warn("popover-html-popup is now deprecated. Use uib-popover-html-popup instead."),d.addClass("popover")}}}]).directive("popoverHtml",["$tooltip",function(a){return a("popoverHtml","popover","click",{useContentExp:!0})}]).directive("popoverPopup",["$log","$popoverSuppressWarning",function(a,b){return{replace:!0,scope:{title:"@",content:"@",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/popover/popover.html",link:function(c,d){b||a.warn("popover-popup is now deprecated. Use uib-popover-popup instead."),d.addClass("popover")}}}]).directive("popover",["$tooltip",function(a){return a("popover","popover","click")}]),angular.module("ui.bootstrap.progressbar",[]).constant("uibProgressConfig",{animate:!0,max:100}).controller("UibProgressController",["$scope","$attrs","uibProgressConfig",function(a,b,c){var d=this,e=angular.isDefined(b.animate)?a.$parent.$eval(b.animate):c.animate;this.bars=[],a.max=angular.isDefined(a.max)?a.max:c.max,this.addBar=function(b,c,f){e||c.css({transition:"none"}),this.bars.push(b),b.max=a.max,b.title=f&&angular.isDefined(f.title)?f.title:"progressbar",b.$watch("value",function(a){b.recalculatePercentage()}),b.recalculatePercentage=function(){var a=d.bars.reduce(function(a,b){return b.percent=+(100*b.value/b.max).toFixed(2),a+b.percent},0);a>100&&(b.percent-=a-100)},b.$on("$destroy",function(){c=null,d.removeBar(b)})},this.removeBar=function(a){this.bars.splice(this.bars.indexOf(a),1),this.bars.forEach(function(a){a.recalculatePercentage()})},a.$watch("max",function(b){d.bars.forEach(function(b){b.max=a.max,b.recalculatePercentage()})})}]).directive("uibProgress",function(){return{replace:!0,transclude:!0,controller:"UibProgressController",require:"uibProgress",scope:{max:"=?"},templateUrl:"template/progressbar/progress.html"}}).directive("uibBar",function(){return{replace:!0,transclude:!0,require:"^uibProgress",scope:{value:"=",type:"@"},templateUrl:"template/progressbar/bar.html",link:function(a,b,c,d){d.addBar(a,b,c)}}}).directive("uibProgressbar",function(){return{replace:!0,transclude:!0,controller:"UibProgressController",scope:{value:"=",max:"=?",type:"@"},templateUrl:"template/progressbar/progressbar.html",link:function(a,b,c,d){d.addBar(a,angular.element(b.children()[0]),{title:c.title})}}}),angular.module("ui.bootstrap.progressbar").value("$progressSuppressWarning",!1).controller("ProgressController",["$scope","$attrs","uibProgressConfig","$log","$progressSuppressWarning",function(a,b,c,d,e){e||d.warn("ProgressController is now deprecated. Use UibProgressController instead.");var f=this,g=angular.isDefined(b.animate)?a.$parent.$eval(b.animate):c.animate;this.bars=[],a.max=angular.isDefined(a.max)?a.max:c.max,this.addBar=function(b,c,d){g||c.css({transition:"none"}),this.bars.push(b),b.max=a.max,b.title=d&&angular.isDefined(d.title)?d.title:"progressbar",b.$watch("value",function(a){b.recalculatePercentage()}),b.recalculatePercentage=function(){b.percent=+(100*b.value/b.max).toFixed(2);var a=f.bars.reduce(function(a,b){return a+b.percent},0);a>100&&(b.percent-=a-100)},b.$on("$destroy",function(){c=null,f.removeBar(b)})},this.removeBar=function(a){this.bars.splice(this.bars.indexOf(a),1)},a.$watch("max",function(b){f.bars.forEach(function(b){b.max=a.max,b.recalculatePercentage()})})}]).directive("progress",["$log","$progressSuppressWarning",function(a,b){return{replace:!0,transclude:!0,controller:"ProgressController",require:"progress",scope:{max:"=?",title:"@?"},templateUrl:"template/progressbar/progress.html",link:function(){b||a.warn("progress is now deprecated. Use uib-progress instead.")}}}]).directive("bar",["$log","$progressSuppressWarning",function(a,b){return{replace:!0,transclude:!0,require:"^progress",scope:{value:"=",type:"@"},templateUrl:"template/progressbar/bar.html",link:function(c,d,e,f){b||a.warn("bar is now deprecated. Use uib-bar instead."),f.addBar(c,d)}}}]).directive("progressbar",["$log","$progressSuppressWarning",function(a,b){return{replace:!0,transclude:!0,controller:"ProgressController",scope:{value:"=",max:"=?",type:"@"},templateUrl:"template/progressbar/progressbar.html",link:function(c,d,e,f){b||a.warn("progressbar is now deprecated. Use uib-progressbar instead."),f.addBar(c,angular.element(d.children()[0]),{title:e.title})}}}]),angular.module("ui.bootstrap.rating",[]).constant("uibRatingConfig",{max:5,stateOn:null,stateOff:null,titles:["one","two","three","four","five"]}).controller("UibRatingController",["$scope","$attrs","uibRatingConfig",function(a,b,c){var d={$setViewValue:angular.noop};this.init=function(e){d=e,d.$render=this.render,d.$formatters.push(function(a){return angular.isNumber(a)&&a<<0!==a&&(a=Math.round(a)),a}),this.stateOn=angular.isDefined(b.stateOn)?a.$parent.$eval(b.stateOn):c.stateOn,this.stateOff=angular.isDefined(b.stateOff)?a.$parent.$eval(b.stateOff):c.stateOff;var f=angular.isDefined(b.titles)?a.$parent.$eval(b.titles):c.titles;this.titles=angular.isArray(f)&&f.length>0?f:c.titles;var g=angular.isDefined(b.ratingStates)?a.$parent.$eval(b.ratingStates):new Array(angular.isDefined(b.max)?a.$parent.$eval(b.max):c.max);a.range=this.buildTemplateObjects(g)},this.buildTemplateObjects=function(a){for(var b=0,c=a.length;c>b;b++)a[b]=angular.extend({index:b},{stateOn:this.stateOn,stateOff:this.stateOff,title:this.getTitle(b)},a[b]);return a},this.getTitle=function(a){return a>=this.titles.length?a+1:this.titles[a]},a.rate=function(b){!a.readonly&&b>=0&&b<=a.range.length&&(d.$setViewValue(d.$viewValue===b?0:b),d.$render())},a.enter=function(b){a.readonly||(a.value=b),a.onHover({value:b})},a.reset=function(){a.value=d.$viewValue,a.onLeave()},a.onKeydown=function(b){/(37|38|39|40)/.test(b.which)&&(b.preventDefault(),b.stopPropagation(),a.rate(a.value+(38===b.which||39===b.which?1:-1)))},this.render=function(){a.value=d.$viewValue}}]).directive("uibRating",function(){return{require:["uibRating","ngModel"],scope:{readonly:"=?",onHover:"&",onLeave:"&"},controller:"UibRatingController",templateUrl:"template/rating/rating.html",replace:!0,link:function(a,b,c,d){var e=d[0],f=d[1];e.init(f)}}}),angular.module("ui.bootstrap.rating").value("$ratingSuppressWarning",!1).controller("RatingController",["$scope","$attrs","$controller","$log","$ratingSuppressWarning",function(a,b,c,d,e){e||d.warn("RatingController is now deprecated. Use UibRatingController instead."),angular.extend(this,c("UibRatingController",{$scope:a,$attrs:b}))}]).directive("rating",["$log","$ratingSuppressWarning",function(a,b){return{require:["rating","ngModel"],scope:{readonly:"=?",onHover:"&",onLeave:"&"},controller:"RatingController",templateUrl:"template/rating/rating.html",replace:!0,link:function(c,d,e,f){b||a.warn("rating is now deprecated. Use uib-rating instead.");var g=f[0],h=f[1];g.init(h)}}}]),angular.module("ui.bootstrap.tabs",[]).controller("UibTabsetController",["$scope",function(a){var b=this,c=b.tabs=a.tabs=[];b.select=function(a){angular.forEach(c,function(b){b.active&&b!==a&&(b.active=!1,b.onDeselect(),a.selectCalled=!1)}),a.active=!0,a.selectCalled||(a.onSelect(),a.selectCalled=!0)},b.addTab=function(a){c.push(a),1===c.length&&a.active!==!1?a.active=!0:a.active?b.select(a):a.active=!1},b.removeTab=function(a){var e=c.indexOf(a);if(a.active&&c.length>1&&!d){var f=e==c.length-1?e-1:e+1;b.select(c[f])}c.splice(e,1)};var d;a.$on("$destroy",function(){d=!0})}]).directive("uibTabset",function(){return{restrict:"EA",transclude:!0,replace:!0,scope:{type:"@"},controller:"UibTabsetController",templateUrl:"template/tabs/tabset.html",link:function(a,b,c){a.vertical=angular.isDefined(c.vertical)?a.$parent.$eval(c.vertical):!1,a.justified=angular.isDefined(c.justified)?a.$parent.$eval(c.justified):!1}}}).directive("uibTab",["$parse",function(a){return{require:"^uibTabset",restrict:"EA",replace:!0,templateUrl:"template/tabs/tab.html",transclude:!0,scope:{active:"=?",heading:"@",onSelect:"&select",onDeselect:"&deselect"},controller:function(){},link:function(b,c,d,e,f){b.$watch("active",function(a){a&&e.select(b)}),b.disabled=!1,d.disable&&b.$parent.$watch(a(d.disable),function(a){b.disabled=!!a}),b.select=function(){b.disabled||(b.active=!0)},e.addTab(b),b.$on("$destroy",function(){e.removeTab(b)}),b.$transcludeFn=f}}}]).directive("uibTabHeadingTransclude",function(){return{restrict:"A",require:["?^uibTab","?^tab"],link:function(a,b){a.$watch("headingElement",function(a){a&&(b.html(""),b.append(a))})}}}).directive("uibTabContentTransclude",function(){function a(a){return a.tagName&&(a.hasAttribute("tab-heading")||a.hasAttribute("data-tab-heading")||a.hasAttribute("x-tab-heading")||a.hasAttribute("uib-tab-heading")||a.hasAttribute("data-uib-tab-heading")||a.hasAttribute("x-uib-tab-heading")||"tab-heading"===a.tagName.toLowerCase()||"data-tab-heading"===a.tagName.toLowerCase()||"x-tab-heading"===a.tagName.toLowerCase()||"uib-tab-heading"===a.tagName.toLowerCase()||"data-uib-tab-heading"===a.tagName.toLowerCase()||"x-uib-tab-heading"===a.tagName.toLowerCase())}return{restrict:"A",require:["?^uibTabset","?^tabset"],link:function(b,c,d){var e=b.$eval(d.uibTabContentTransclude);e.$transcludeFn(e.$parent,function(b){angular.forEach(b,function(b){a(b)?e.headingElement=b:c.append(b)})})}}}),angular.module("ui.bootstrap.tabs").value("$tabsSuppressWarning",!1).controller("TabsetController",["$scope","$controller","$log","$tabsSuppressWarning",function(a,b,c,d){d||c.warn("TabsetController is now deprecated. Use UibTabsetController instead."),angular.extend(this,b("UibTabsetController",{$scope:a}))}]).directive("tabset",["$log","$tabsSuppressWarning",function(a,b){return{restrict:"EA",transclude:!0,replace:!0,scope:{type:"@"},controller:"TabsetController",templateUrl:"template/tabs/tabset.html",link:function(c,d,e){b||a.warn("tabset is now deprecated. Use uib-tabset instead."),c.vertical=angular.isDefined(e.vertical)?c.$parent.$eval(e.vertical):!1,c.justified=angular.isDefined(e.justified)?c.$parent.$eval(e.justified):!1}}}]).directive("tab",["$parse","$log","$tabsSuppressWarning",function(a,b,c){return{require:"^tabset",restrict:"EA",replace:!0,templateUrl:"template/tabs/tab.html",transclude:!0,scope:{active:"=?",heading:"@",onSelect:"&select",onDeselect:"&deselect"},controller:function(){},link:function(d,e,f,g,h){c||b.warn("tab is now deprecated. Use uib-tab instead."),d.$watch("active",function(a){a&&g.select(d)}),d.disabled=!1,f.disable&&d.$parent.$watch(a(f.disable),function(a){d.disabled=!!a}),d.select=function(){d.disabled||(d.active=!0)},g.addTab(d),d.$on("$destroy",function(){g.removeTab(d)}),d.$transcludeFn=h}}}]).directive("tabHeadingTransclude",["$log","$tabsSuppressWarning",function(a,b){return{restrict:"A",require:"^tab",link:function(c,d){b||a.warn("tab-heading-transclude is now deprecated. Use uib-tab-heading-transclude instead."),c.$watch("headingElement",function(a){a&&(d.html(""),d.append(a))})}}}]).directive("tabContentTransclude",["$log","$tabsSuppressWarning",function(a,b){function c(a){return a.tagName&&(a.hasAttribute("tab-heading")||a.hasAttribute("data-tab-heading")||a.hasAttribute("x-tab-heading")||"tab-heading"===a.tagName.toLowerCase()||"data-tab-heading"===a.tagName.toLowerCase()||"x-tab-heading"===a.tagName.toLowerCase())}return{restrict:"A",require:"^tabset",link:function(d,e,f){b||a.warn("tab-content-transclude is now deprecated. Use uib-tab-content-transclude instead.");var g=d.$eval(f.tabContentTransclude);g.$transcludeFn(g.$parent,function(a){angular.forEach(a,function(a){c(a)?g.headingElement=a:e.append(a)})})}}}]),angular.module("ui.bootstrap.timepicker",[]).constant("uibTimepickerConfig",{hourStep:1,minuteStep:1,showMeridian:!0,meridians:null,readonlyInput:!1,mousewheel:!0,arrowkeys:!0,showSpinners:!0}).controller("UibTimepickerController",["$scope","$element","$attrs","$parse","$log","$locale","uibTimepickerConfig",function(a,b,c,d,e,f,g){function h(){var b=parseInt(a.hours,10),c=a.showMeridian?b>0&&13>b:b>=0&&24>b;return c?(a.showMeridian&&(12===b&&(b=0),a.meridian===r[1]&&(b+=12)),b):void 0}function i(){var b=parseInt(a.minutes,10);return b>=0&&60>b?b:void 0}function j(a){return angular.isDefined(a)&&a.toString().length<2?"0"+a:a.toString()}function k(a){l(),q.$setViewValue(new Date(p)),m(a)}function l(){q.$setValidity("time",!0),a.invalidHours=!1,a.invalidMinutes=!1}function m(b){var c=p.getHours(),d=p.getMinutes();a.showMeridian&&(c=0===c||12===c?12:c%12),a.hours="h"===b?c:j(c),"m"!==b&&(a.minutes=j(d)),a.meridian=p.getHours()<12?r[0]:r[1]}function n(a,b){var c=new Date(a.getTime()+6e4*b),d=new Date(a);return d.setHours(c.getHours(),c.getMinutes()),d}function o(a){p=n(p,a),k()}var p=new Date,q={$setViewValue:angular.noop},r=angular.isDefined(c.meridians)?a.$parent.$eval(c.meridians):g.meridians||f.DATETIME_FORMATS.AMPMS;a.tabindex=angular.isDefined(c.tabindex)?c.tabindex:0,b.removeAttr("tabindex"),this.init=function(b,d){q=b,q.$render=this.render,q.$formatters.unshift(function(a){return a?new Date(a):null});var e=d.eq(0),f=d.eq(1),h=angular.isDefined(c.mousewheel)?a.$parent.$eval(c.mousewheel):g.mousewheel;h&&this.setupMousewheelEvents(e,f);var i=angular.isDefined(c.arrowkeys)?a.$parent.$eval(c.arrowkeys):g.arrowkeys;i&&this.setupArrowkeyEvents(e,f),a.readonlyInput=angular.isDefined(c.readonlyInput)?a.$parent.$eval(c.readonlyInput):g.readonlyInput,this.setupInputEvents(e,f)};var s=g.hourStep;c.hourStep&&a.$parent.$watch(d(c.hourStep),function(a){s=parseInt(a,10)});var t=g.minuteStep;c.minuteStep&&a.$parent.$watch(d(c.minuteStep),function(a){t=parseInt(a,10)});var u;a.$parent.$watch(d(c.min),function(a){var b=new Date(a);u=isNaN(b)?void 0:b});var v;a.$parent.$watch(d(c.max),function(a){var b=new Date(a);v=isNaN(b)?void 0:b}),a.noIncrementHours=function(){var a=n(p,60*s); +return a>v||p>a&&u>a},a.noDecrementHours=function(){var a=n(p,60*-s);return u>a||a>p&&a>v},a.noIncrementMinutes=function(){var a=n(p,t);return a>v||p>a&&u>a},a.noDecrementMinutes=function(){var a=n(p,-t);return u>a||a>p&&a>v},a.noToggleMeridian=function(){return p.getHours()<13?n(p,720)>v:n(p,-720)0};b.bind("mousewheel wheel",function(b){a.$apply(d(b)?a.incrementHours():a.decrementHours()),b.preventDefault()}),c.bind("mousewheel wheel",function(b){a.$apply(d(b)?a.incrementMinutes():a.decrementMinutes()),b.preventDefault()})},this.setupArrowkeyEvents=function(b,c){b.bind("keydown",function(b){38===b.which?(b.preventDefault(),a.incrementHours(),a.$apply()):40===b.which&&(b.preventDefault(),a.decrementHours(),a.$apply())}),c.bind("keydown",function(b){38===b.which?(b.preventDefault(),a.incrementMinutes(),a.$apply()):40===b.which&&(b.preventDefault(),a.decrementMinutes(),a.$apply())})},this.setupInputEvents=function(b,c){if(a.readonlyInput)return a.updateHours=angular.noop,void(a.updateMinutes=angular.noop);var d=function(b,c){q.$setViewValue(null),q.$setValidity("time",!1),angular.isDefined(b)&&(a.invalidHours=b),angular.isDefined(c)&&(a.invalidMinutes=c)};a.updateHours=function(){var a=h(),b=i();angular.isDefined(a)&&angular.isDefined(b)?(p.setHours(a),u>p||p>v?d(!0):k("h")):d(!0)},b.bind("blur",function(b){!a.invalidHours&&a.hours<10&&a.$apply(function(){a.hours=j(a.hours)})}),a.updateMinutes=function(){var a=i(),b=h();angular.isDefined(a)&&angular.isDefined(b)?(p.setMinutes(a),u>p||p>v?d(void 0,!0):k("m")):d(void 0,!0)},c.bind("blur",function(b){!a.invalidMinutes&&a.minutes<10&&a.$apply(function(){a.minutes=j(a.minutes)})})},this.render=function(){var b=q.$viewValue;isNaN(b)?(q.$setValidity("time",!1),e.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.')):(b&&(p=b),u>p||p>v?(q.$setValidity("time",!1),a.invalidHours=!0,a.invalidMinutes=!0):l(),m())},a.showSpinners=angular.isDefined(c.showSpinners)?a.$parent.$eval(c.showSpinners):g.showSpinners,a.incrementHours=function(){a.noIncrementHours()||o(60*s)},a.decrementHours=function(){a.noDecrementHours()||o(60*-s)},a.incrementMinutes=function(){a.noIncrementMinutes()||o(t)},a.decrementMinutes=function(){a.noDecrementMinutes()||o(-t)},a.toggleMeridian=function(){a.noToggleMeridian()||o(720*(p.getHours()<12?1:-1))}}]).directive("uibTimepicker",function(){return{restrict:"EA",require:["uibTimepicker","?^ngModel"],controller:"UibTimepickerController",controllerAs:"timepicker",replace:!0,scope:{},templateUrl:function(a,b){return b.templateUrl||"template/timepicker/timepicker.html"},link:function(a,b,c,d){var e=d[0],f=d[1];f&&e.init(f,b.find("input"))}}}),angular.module("ui.bootstrap.timepicker").value("$timepickerSuppressWarning",!1).controller("TimepickerController",["$scope","$element","$attrs","$controller","$log","$timepickerSuppressWarning",function(a,b,c,d,e,f){f||e.warn("TimepickerController is now deprecated. Use UibTimepickerController instead."),angular.extend(this,d("UibTimepickerController",{$scope:a,$element:b,$attrs:c}))}]).directive("timepicker",["$log","$timepickerSuppressWarning",function(a,b){return{restrict:"EA",require:["timepicker","?^ngModel"],controller:"TimepickerController",controllerAs:"timepicker",replace:!0,scope:{},templateUrl:function(a,b){return b.templateUrl||"template/timepicker/timepicker.html"},link:function(c,d,e,f){b||a.warn("timepicker is now deprecated. Use uib-timepicker instead.");var g=f[0],h=f[1];h&&g.init(h,d.find("input"))}}}]),angular.module("ui.bootstrap.typeahead",["ui.bootstrap.position"]).factory("uibTypeaheadParser",["$parse",function(a){var b=/^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/;return{parse:function(c){var d=c.match(b);if(!d)throw new Error('Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_" but got "'+c+'".');return{itemName:d[3],source:a(d[4]),viewMapper:a(d[2]||d[1]),modelMapper:a(d[1])}}}}]).controller("UibTypeaheadController",["$scope","$element","$attrs","$compile","$parse","$q","$timeout","$document","$window","$rootScope","$uibPosition","uibTypeaheadParser",function(a,b,c,d,e,f,g,h,i,j,k,l){function m(){K.moveInProgress||(K.moveInProgress=!0,K.$digest()),S&&g.cancel(S),S=g(function(){K.matches.length&&n(),K.moveInProgress=!1},r)}function n(){K.position=C?k.offset(b):k.position(b),K.position.top+=b.prop("offsetHeight")}var o,p,q=[9,13,27,38,40],r=200,s=a.$eval(c.typeaheadMinLength);s||0===s||(s=1);var t,u,v=a.$eval(c.typeaheadWaitMs)||0,w=a.$eval(c.typeaheadEditable)!==!1,x=e(c.typeaheadLoading).assign||angular.noop,y=e(c.typeaheadOnSelect),z=angular.isDefined(c.typeaheadSelectOnBlur)?a.$eval(c.typeaheadSelectOnBlur):!1,A=e(c.typeaheadNoResults).assign||angular.noop,B=c.typeaheadInputFormatter?e(c.typeaheadInputFormatter):void 0,C=c.typeaheadAppendToBody?a.$eval(c.typeaheadAppendToBody):!1,D=c.typeaheadAppendToElementId||!1,E=a.$eval(c.typeaheadFocusFirst)!==!1,F=c.typeaheadSelectOnExact?a.$eval(c.typeaheadSelectOnExact):!1,G=e(c.ngModel),H=e(c.ngModel+"($$$p)"),I=function(b,c){return angular.isFunction(G(a))&&p&&p.$options&&p.$options.getterSetter?H(b,{$$$p:c}):G.assign(b,c)},J=l.parse(c.uibTypeahead),K=a.$new(),L=a.$on("$destroy",function(){K.$destroy()});K.$on("$destroy",L);var M="typeahead-"+K.$id+"-"+Math.floor(1e4*Math.random());b.attr({"aria-autocomplete":"list","aria-expanded":!1,"aria-owns":M});var N=angular.element("
      ");N.attr({id:M,matches:"matches",active:"activeIdx",select:"select(activeIdx)","move-in-progress":"moveInProgress",query:"query",position:"position"}),angular.isDefined(c.typeaheadTemplateUrl)&&N.attr("template-url",c.typeaheadTemplateUrl),angular.isDefined(c.typeaheadPopupTemplateUrl)&&N.attr("popup-template-url",c.typeaheadPopupTemplateUrl);var O=function(){K.matches=[],K.activeIdx=-1,b.attr("aria-expanded",!1)},P=function(a){return M+"-option-"+a};K.$watch("activeIdx",function(a){0>a?b.removeAttr("aria-activedescendant"):b.attr("aria-activedescendant",P(a))});var Q=function(a,b){return K.matches.length>b&&a?a.toUpperCase()===K.matches[b].label.toUpperCase():!1},R=function(c){var d={$viewValue:c};x(a,!0),A(a,!1),f.when(J.source(a,d)).then(function(e){var f=c===o.$viewValue;if(f&&t)if(e&&e.length>0){K.activeIdx=E?0:-1,A(a,!1),K.matches.length=0;for(var g=0;g0?K.activeIdx:K.matches.length)-1,K.$digest()):13===a.which||9===a.which?K.$apply(function(){K.select(K.activeIdx)}):27===a.which&&(a.stopPropagation(),O(),K.$digest())}}),b.bind("blur",function(){z&&K.matches.length&&-1!==K.activeIdx&&!u&&(u=!0,K.$apply(function(){K.select(K.activeIdx)})),t=!1,u=!1});var W=function(a){b[0]!==a.target&&3!==a.which&&0!==K.matches.length&&(O(),j.$$phase||K.$digest())};h.bind("click",W),a.$on("$destroy",function(){h.unbind("click",W),(C||D)&&X.remove(),C&&(angular.element(i).unbind("resize",m),h.find("body").unbind("scroll",m)),N.remove()});var X=d(N)(K);C?h.find("body").append(X):D!==!1?angular.element(h[0].getElementById(D)).append(X):b.after(X),this.init=function(b,c){o=b,p=c,o.$parsers.unshift(function(b){return t=!0,0===s||b&&b.length>=s?v>0?(V(),U(b)):R(b):(x(a,!1),V(),O()),w?b:b?void o.$setValidity("editable",!1):(o.$setValidity("editable",!0),null)}),o.$formatters.push(function(b){var c,d,e={};return w||o.$setValidity("editable",!0),B?(e.$model=b,B(a,e)):(e[J.itemName]=b,c=J.viewMapper(a,e),e[J.itemName]=void 0,d=J.viewMapper(a,e),c!==d?c:b)})}}]).directive("uibTypeahead",function(){return{controller:"UibTypeaheadController",require:["ngModel","^?ngModelOptions","uibTypeahead"],link:function(a,b,c,d){d[2].init(d[0],d[1])}}}).directive("uibTypeaheadPopup",function(){return{scope:{matches:"=",query:"=",active:"=",position:"&",moveInProgress:"=",select:"&"},replace:!0,templateUrl:function(a,b){return b.popupTemplateUrl||"template/typeahead/typeahead-popup.html"},link:function(a,b,c){a.templateUrl=c.templateUrl,a.isOpen=function(){return a.matches.length>0},a.isActive=function(b){return a.active==b},a.selectActive=function(b){a.active=b},a.selectMatch=function(b){a.select({activeIdx:b})}}}}).directive("uibTypeaheadMatch",["$templateRequest","$compile","$parse",function(a,b,c){return{scope:{index:"=",match:"=",query:"="},link:function(d,e,f){var g=c(f.templateUrl)(d.$parent)||"template/typeahead/typeahead-match.html";a(g).then(function(a){b(a.trim())(d,function(a){e.replaceWith(a)})})}}}]).filter("uibTypeaheadHighlight",["$sce","$injector","$log",function(a,b,c){function d(a){return a.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")}function e(a){return/<.*>/g.test(a)}var f;return f=b.has("$sanitize"),function(b,g){return!f&&e(b)&&c.warn("Unsafe use of typeahead please use ngSanitize"),b=g?(""+b).replace(new RegExp(d(g),"gi"),"$&"):b,f||(b=a.trustAsHtml(b)),b}}]),angular.module("ui.bootstrap.typeahead").value("$typeaheadSuppressWarning",!1).service("typeaheadParser",["$parse","uibTypeaheadParser","$log","$typeaheadSuppressWarning",function(a,b,c,d){return d||c.warn("typeaheadParser is now deprecated. Use uibTypeaheadParser instead."),b}]).directive("typeahead",["$compile","$parse","$q","$timeout","$document","$window","$rootScope","$uibPosition","typeaheadParser","$log","$typeaheadSuppressWarning",function(a,b,c,d,e,f,g,h,i,j,k){var l=[9,13,27,38,40],m=200;return{require:["ngModel","^?ngModelOptions"],link:function(n,o,p,q){function r(){N.moveInProgress||(N.moveInProgress=!0,N.$digest()),V&&d.cancel(V),V=d(function(){N.matches.length&&s(),N.moveInProgress=!1},m)}function s(){N.position=F?h.offset(o):h.position(o),N.position.top+=o.prop("offsetHeight")}k||j.warn("typeahead is now deprecated. Use uib-typeahead instead.");var t=q[0],u=q[1],v=n.$eval(p.typeaheadMinLength);v||0===v||(v=1);var w,x,y=n.$eval(p.typeaheadWaitMs)||0,z=n.$eval(p.typeaheadEditable)!==!1,A=b(p.typeaheadLoading).assign||angular.noop,B=b(p.typeaheadOnSelect),C=angular.isDefined(p.typeaheadSelectOnBlur)?n.$eval(p.typeaheadSelectOnBlur):!1,D=b(p.typeaheadNoResults).assign||angular.noop,E=p.typeaheadInputFormatter?b(p.typeaheadInputFormatter):void 0,F=p.typeaheadAppendToBody?n.$eval(p.typeaheadAppendToBody):!1,G=p.typeaheadAppendToElementId||!1,H=n.$eval(p.typeaheadFocusFirst)!==!1,I=p.typeaheadSelectOnExact?n.$eval(p.typeaheadSelectOnExact):!1,J=b(p.ngModel),K=b(p.ngModel+"($$$p)"),L=function(a,b){return angular.isFunction(J(n))&&u&&u.$options&&u.$options.getterSetter?K(a,{$$$p:b}):J.assign(a,b)},M=i.parse(p.typeahead),N=n.$new(),O=n.$on("$destroy",function(){N.$destroy()});N.$on("$destroy",O);var P="typeahead-"+N.$id+"-"+Math.floor(1e4*Math.random());o.attr({"aria-autocomplete":"list","aria-expanded":!1,"aria-owns":P});var Q=angular.element("
      ");Q.attr({id:P,matches:"matches",active:"activeIdx",select:"select(activeIdx)","move-in-progress":"moveInProgress",query:"query",position:"position"}),angular.isDefined(p.typeaheadTemplateUrl)&&Q.attr("template-url",p.typeaheadTemplateUrl),angular.isDefined(p.typeaheadPopupTemplateUrl)&&Q.attr("popup-template-url",p.typeaheadPopupTemplateUrl);var R=function(){N.matches=[],N.activeIdx=-1,o.attr("aria-expanded",!1)},S=function(a){return P+"-option-"+a};N.$watch("activeIdx",function(a){0>a?o.removeAttr("aria-activedescendant"):o.attr("aria-activedescendant",S(a))});var T=function(a,b){return N.matches.length>b&&a?a.toUpperCase()===N.matches[b].label.toUpperCase():!1},U=function(a){var b={$viewValue:a};A(n,!0),D(n,!1),c.when(M.source(n,b)).then(function(c){var d=a===t.$viewValue;if(d&&w)if(c&&c.length>0){N.activeIdx=H?0:-1,D(n,!1),N.matches.length=0;for(var e=0;e=v?y>0?(Y(),X(a)):U(a):(A(n,!1),Y(),R()),z?a:a?void t.$setValidity("editable",!1):(t.$setValidity("editable",!0),null)}),t.$formatters.push(function(a){var b,c,d={};return z||t.$setValidity("editable",!0),E?(d.$model=a,E(n,d)):(d[M.itemName]=a,b=M.viewMapper(n,d),d[M.itemName]=void 0,c=M.viewMapper(n,d),b!==c?b:a)}),N.select=function(a){var b,c,e={};x=!0,e[M.itemName]=c=N.matches[a].model,b=M.modelMapper(n,e),L(n,b),t.$setValidity("editable",!0),t.$setValidity("parse",!0),B(n,{$item:c,$model:b,$label:M.viewMapper(n,e)}),R(),N.$eval(p.typeaheadFocusOnSelect)!==!1&&d(function(){o[0].focus()},0,!1)},o.bind("keydown",function(a){if(0!==N.matches.length&&-1!==l.indexOf(a.which)){if(-1===N.activeIdx&&(9===a.which||13===a.which))return R(),void N.$digest();a.preventDefault(),40===a.which?(N.activeIdx=(N.activeIdx+1)%N.matches.length,N.$digest()):38===a.which?(N.activeIdx=(N.activeIdx>0?N.activeIdx:N.matches.length)-1,N.$digest()):13===a.which||9===a.which?N.$apply(function(){N.select(N.activeIdx)}):27===a.which&&(a.stopPropagation(),R(),N.$digest())}}),o.bind("blur",function(){C&&N.matches.length&&-1!==N.activeIdx&&!x&&(x=!0,N.$apply(function(){N.select(N.activeIdx)})),w=!1,x=!1});var Z=function(a){o[0]!==a.target&&3!==a.which&&0!==N.matches.length&&(R(),g.$$phase||N.$digest())};e.bind("click",Z),n.$on("$destroy",function(){e.unbind("click",Z),(F||G)&&$.remove(),F&&(angular.element(f).unbind("resize",r),e.find("body").unbind("scroll",r)),Q.remove()});var $=a(Q)(N);F?e.find("body").append($):G!==!1?angular.element(e[0].getElementById(G)).append($):o.after($)}}}]).directive("typeaheadPopup",["$typeaheadSuppressWarning","$log",function(a,b){return{scope:{matches:"=",query:"=",active:"=",position:"&",moveInProgress:"=",select:"&"},replace:!0,templateUrl:function(a,b){return b.popupTemplateUrl||"template/typeahead/typeahead-popup.html"},link:function(c,d,e){a||b.warn("typeahead-popup is now deprecated. Use uib-typeahead-popup instead."),c.templateUrl=e.templateUrl,c.isOpen=function(){return c.matches.length>0},c.isActive=function(a){return c.active==a},c.selectActive=function(a){c.active=a},c.selectMatch=function(a){c.select({activeIdx:a})}}}}]).directive("typeaheadMatch",["$templateRequest","$compile","$parse","$typeaheadSuppressWarning","$log",function(a,b,c,d,e){return{restrict:"EA",scope:{index:"=",match:"=",query:"="},link:function(f,g,h){d||e.warn("typeahead-match is now deprecated. Use uib-typeahead-match instead.");var i=c(h.templateUrl)(f.$parent)||"template/typeahead/typeahead-match.html";a(i).then(function(a){b(a.trim())(f,function(a){g.replaceWith(a)})})}}}]).filter("typeaheadHighlight",["$sce","$injector","$log","$typeaheadSuppressWarning",function(a,b,c,d){function e(a){return a.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")}function f(a){return/<.*>/g.test(a)}var g;return g=b.has("$sanitize"),function(b,h){return d||c.warn("typeaheadHighlight is now deprecated. Use uibTypeaheadHighlight instead."),!g&&f(b)&&c.warn("Unsafe use of typeahead please use ngSanitize"),b=h?(""+b).replace(new RegExp(e(h),"gi"),"$&"):b,g||(b=a.trustAsHtml(b)),b}}]),angular.module("template/accordion/accordion-group.html",[]).run(["$templateCache",function(a){a.put("template/accordion/accordion-group.html",'
      \n
      \n

      \n {{heading}}\n

      \n
      \n
      \n
      \n
      \n
      \n')}]),angular.module("template/accordion/accordion.html",[]).run(["$templateCache",function(a){a.put("template/accordion/accordion.html",'
      ')}]),angular.module("template/alert/alert.html",[]).run(["$templateCache",function(a){a.put("template/alert/alert.html",'\n')}]),angular.module("template/carousel/carousel.html",[]).run(["$templateCache",function(a){a.put("template/carousel/carousel.html",'')}]),angular.module("template/carousel/slide.html",[]).run(["$templateCache",function(a){a.put("template/carousel/slide.html",'
      \n')}]),angular.module("template/datepicker/datepicker.html",[]).run(["$templateCache",function(a){a.put("template/datepicker/datepicker.html",'
      \n \n \n \n
      ')}]),angular.module("template/datepicker/day.html",[]).run(["$templateCache",function(a){a.put("template/datepicker/day.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      {{::label.abbr}}
      {{ weekNumbers[$index] }}\n \n
      \n')}]),angular.module("template/datepicker/month.html",[]).run(["$templateCache",function(a){a.put("template/datepicker/month.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n
      \n \n
      \n')}]),angular.module("template/datepicker/popup.html",[]).run(["$templateCache",function(a){a.put("template/datepicker/popup.html",'\n')}]),angular.module("template/datepicker/year.html",[]).run(["$templateCache",function(a){a.put("template/datepicker/year.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n
      \n \n
      \n')}]),angular.module("template/modal/backdrop.html",[]).run(["$templateCache",function(a){a.put("template/modal/backdrop.html",'
      \n')}]),angular.module("template/modal/window.html",[]).run(["$templateCache",function(a){a.put("template/modal/window.html",'\n')}]),angular.module("template/pagination/pager.html",[]).run(["$templateCache",function(a){a.put("template/pagination/pager.html",'\n')}]),angular.module("template/pagination/pagination.html",[]).run(["$templateCache",function(a){a.put("template/pagination/pagination.html",'\n')}]),angular.module("template/tooltip/tooltip-html-popup.html",[]).run(["$templateCache",function(a){a.put("template/tooltip/tooltip-html-popup.html",'\n
      \n
      \n\n')}]),angular.module("template/tooltip/tooltip-popup.html",[]).run(["$templateCache",function(a){a.put("template/tooltip/tooltip-popup.html",'\n
      \n
      \n\n')}]),angular.module("template/tooltip/tooltip-template-popup.html",[]).run(["$templateCache",function(a){a.put("template/tooltip/tooltip-template-popup.html",'\n
      \n
      \n\n')}]),angular.module("template/popover/popover-html.html",[]).run(["$templateCache",function(a){a.put("template/popover/popover-html.html",'
      \n
      \n\n
      \n

      \n
      \n
      \n
      \n')}]),angular.module("template/popover/popover-template.html",[]).run(["$templateCache",function(a){a.put("template/popover/popover-template.html",'
      \n
      \n\n
      \n

      \n
      \n
      \n
      \n')}]),angular.module("template/popover/popover.html",[]).run(["$templateCache",function(a){a.put("template/popover/popover.html",'
      \n
      \n\n
      \n

      \n
      \n
      \n
      \n')}]),angular.module("template/progressbar/bar.html",[]).run(["$templateCache",function(a){a.put("template/progressbar/bar.html",'
      \n')}]),angular.module("template/progressbar/progress.html",[]).run(["$templateCache",function(a){a.put("template/progressbar/progress.html",'
      ')}]),angular.module("template/progressbar/progressbar.html",[]).run(["$templateCache",function(a){a.put("template/progressbar/progressbar.html",'
      \n
      \n
      \n')}]),angular.module("template/rating/rating.html",[]).run(["$templateCache",function(a){a.put("template/rating/rating.html",'\n ({{ $index < value ? \'*\' : \' \' }})\n \n\n'); +}]),angular.module("template/tabs/tab.html",[]).run(["$templateCache",function(a){a.put("template/tabs/tab.html",'
    • \n {{heading}}\n
    • \n')}]),angular.module("template/tabs/tabset.html",[]).run(["$templateCache",function(a){a.put("template/tabs/tabset.html",'
      \n \n
      \n
      \n
      \n
      \n
      \n')}]),angular.module("template/timepicker/timepicker.html",[]).run(["$templateCache",function(a){a.put("template/timepicker/timepicker.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
       
      \n \n :\n \n
       
      \n')}]),angular.module("template/typeahead/typeahead-match.html",[]).run(["$templateCache",function(a){a.put("template/typeahead/typeahead-match.html",'\n')}]),angular.module("template/typeahead/typeahead-popup.html",[]).run(["$templateCache",function(a){a.put("template/typeahead/typeahead-popup.html",'\n')}]),!angular.$$csp()&&angular.element(document).find("head").prepend(''); \ No newline at end of file diff --git a/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-bootstrap/ui-bootstrap.js b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-bootstrap/ui-bootstrap.js new file mode 100644 index 00000000..9287bb54 --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-bootstrap/ui-bootstrap.js @@ -0,0 +1,8126 @@ +/* + * angular-ui-bootstrap + * http://angular-ui.github.io/bootstrap/ + + * Version: 0.14.3 - 2015-10-23 + * License: MIT + */ +angular.module("ui.bootstrap", ["ui.bootstrap.collapse","ui.bootstrap.accordion","ui.bootstrap.alert","ui.bootstrap.buttons","ui.bootstrap.carousel","ui.bootstrap.dateparser","ui.bootstrap.position","ui.bootstrap.datepicker","ui.bootstrap.dropdown","ui.bootstrap.stackedMap","ui.bootstrap.modal","ui.bootstrap.pagination","ui.bootstrap.tooltip","ui.bootstrap.popover","ui.bootstrap.progressbar","ui.bootstrap.rating","ui.bootstrap.tabs","ui.bootstrap.timepicker","ui.bootstrap.typeahead"]); +angular.module('ui.bootstrap.collapse', []) + + .directive('uibCollapse', ['$animate', '$injector', function($animate, $injector) { + var $animateCss = $injector.has('$animateCss') ? $injector.get('$animateCss') : null; + return { + link: function(scope, element, attrs) { + function expand() { + element.removeClass('collapse') + .addClass('collapsing') + .attr('aria-expanded', true) + .attr('aria-hidden', false); + + if ($animateCss) { + $animateCss(element, { + addClass: 'in', + easing: 'ease', + to: { height: element[0].scrollHeight + 'px' } + }).start().finally(expandDone); + } else { + $animate.addClass(element, 'in', { + to: { height: element[0].scrollHeight + 'px' } + }).then(expandDone); + } + } + + function expandDone() { + element.removeClass('collapsing') + .addClass('collapse') + .css({height: 'auto'}); + } + + function collapse() { + if (!element.hasClass('collapse') && !element.hasClass('in')) { + return collapseDone(); + } + + element + // IMPORTANT: The height must be set before adding "collapsing" class. + // Otherwise, the browser attempts to animate from height 0 (in + // collapsing class) to the given height here. + .css({height: element[0].scrollHeight + 'px'}) + // initially all panel collapse have the collapse class, this removal + // prevents the animation from jumping to collapsed state + .removeClass('collapse') + .addClass('collapsing') + .attr('aria-expanded', false) + .attr('aria-hidden', true); + + if ($animateCss) { + $animateCss(element, { + removeClass: 'in', + to: {height: '0'} + }).start().finally(collapseDone); + } else { + $animate.removeClass(element, 'in', { + to: {height: '0'} + }).then(collapseDone); + } + } + + function collapseDone() { + element.css({height: '0'}); // Required so that collapse works when animation is disabled + element.removeClass('collapsing') + .addClass('collapse'); + } + + scope.$watch(attrs.uibCollapse, function(shouldCollapse) { + if (shouldCollapse) { + collapse(); + } else { + expand(); + } + }); + } + }; + }]); + +/* Deprecated collapse below */ + +angular.module('ui.bootstrap.collapse') + + .value('$collapseSuppressWarning', false) + + .directive('collapse', ['$animate', '$injector', '$log', '$collapseSuppressWarning', function($animate, $injector, $log, $collapseSuppressWarning) { + var $animateCss = $injector.has('$animateCss') ? $injector.get('$animateCss') : null; + return { + link: function(scope, element, attrs) { + if (!$collapseSuppressWarning) { + $log.warn('collapse is now deprecated. Use uib-collapse instead.'); + } + + function expand() { + element.removeClass('collapse') + .addClass('collapsing') + .attr('aria-expanded', true) + .attr('aria-hidden', false); + + if ($animateCss) { + $animateCss(element, { + easing: 'ease', + to: { height: element[0].scrollHeight + 'px' } + }).start().done(expandDone); + } else { + $animate.animate(element, {}, { + height: element[0].scrollHeight + 'px' + }).then(expandDone); + } + } + + function expandDone() { + element.removeClass('collapsing') + .addClass('collapse in') + .css({height: 'auto'}); + } + + function collapse() { + if (!element.hasClass('collapse') && !element.hasClass('in')) { + return collapseDone(); + } + + element + // IMPORTANT: The height must be set before adding "collapsing" class. + // Otherwise, the browser attempts to animate from height 0 (in + // collapsing class) to the given height here. + .css({height: element[0].scrollHeight + 'px'}) + // initially all panel collapse have the collapse class, this removal + // prevents the animation from jumping to collapsed state + .removeClass('collapse in') + .addClass('collapsing') + .attr('aria-expanded', false) + .attr('aria-hidden', true); + + if ($animateCss) { + $animateCss(element, { + to: {height: '0'} + }).start().done(collapseDone); + } else { + $animate.animate(element, {}, { + height: '0' + }).then(collapseDone); + } + } + + function collapseDone() { + element.css({height: '0'}); // Required so that collapse works when animation is disabled + element.removeClass('collapsing') + .addClass('collapse'); + } + + scope.$watch(attrs.collapse, function(shouldCollapse) { + if (shouldCollapse) { + collapse(); + } else { + expand(); + } + }); + } + }; + }]); + +angular.module('ui.bootstrap.accordion', ['ui.bootstrap.collapse']) + +.constant('uibAccordionConfig', { + closeOthers: true +}) + +.controller('UibAccordionController', ['$scope', '$attrs', 'uibAccordionConfig', function($scope, $attrs, accordionConfig) { + // This array keeps track of the accordion groups + this.groups = []; + + // Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to + this.closeOthers = function(openGroup) { + var closeOthers = angular.isDefined($attrs.closeOthers) ? + $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers; + if (closeOthers) { + angular.forEach(this.groups, function(group) { + if (group !== openGroup) { + group.isOpen = false; + } + }); + } + }; + + // This is called from the accordion-group directive to add itself to the accordion + this.addGroup = function(groupScope) { + var that = this; + this.groups.push(groupScope); + + groupScope.$on('$destroy', function(event) { + that.removeGroup(groupScope); + }); + }; + + // This is called from the accordion-group directive when to remove itself + this.removeGroup = function(group) { + var index = this.groups.indexOf(group); + if (index !== -1) { + this.groups.splice(index, 1); + } + }; + +}]) + +// The accordion directive simply sets up the directive controller +// and adds an accordion CSS class to itself element. +.directive('uibAccordion', function() { + return { + controller: 'UibAccordionController', + controllerAs: 'accordion', + transclude: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/accordion/accordion.html'; + } + }; +}) + +// The accordion-group directive indicates a block of html that will expand and collapse in an accordion +.directive('uibAccordionGroup', function() { + return { + require: '^uibAccordion', // We need this directive to be inside an accordion + transclude: true, // It transcludes the contents of the directive into the template + replace: true, // The element containing the directive will be replaced with the template + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/accordion/accordion-group.html'; + }, + scope: { + heading: '@', // Interpolate the heading attribute onto this scope + isOpen: '=?', + isDisabled: '=?' + }, + controller: function() { + this.setHeading = function(element) { + this.heading = element; + }; + }, + link: function(scope, element, attrs, accordionCtrl) { + accordionCtrl.addGroup(scope); + + scope.openClass = attrs.openClass || 'panel-open'; + scope.panelClass = attrs.panelClass; + scope.$watch('isOpen', function(value) { + element.toggleClass(scope.openClass, !!value); + if (value) { + accordionCtrl.closeOthers(scope); + } + }); + + scope.toggleOpen = function($event) { + if (!scope.isDisabled) { + if (!$event || $event.which === 32) { + scope.isOpen = !scope.isOpen; + } + } + }; + } + }; +}) + +// Use accordion-heading below an accordion-group to provide a heading containing HTML +.directive('uibAccordionHeading', function() { + return { + transclude: true, // Grab the contents to be used as the heading + template: '', // In effect remove this element! + replace: true, + require: '^uibAccordionGroup', + link: function(scope, element, attrs, accordionGroupCtrl, transclude) { + // Pass the heading to the accordion-group controller + // so that it can be transcluded into the right place in the template + // [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat] + accordionGroupCtrl.setHeading(transclude(scope, angular.noop)); + } + }; +}) + +// Use in the accordion-group template to indicate where you want the heading to be transcluded +// You must provide the property on the accordion-group controller that will hold the transcluded element +.directive('uibAccordionTransclude', function() { + return { + require: ['?^uibAccordionGroup', '?^accordionGroup'], + link: function(scope, element, attrs, controller) { + controller = controller[0] ? controller[0] : controller[1]; // Delete after we remove deprecation + scope.$watch(function() { return controller[attrs.uibAccordionTransclude]; }, function(heading) { + if (heading) { + element.find('span').html(''); + element.find('span').append(heading); + } + }); + } + }; +}); + +/* Deprecated accordion below */ + +angular.module('ui.bootstrap.accordion') + + .value('$accordionSuppressWarning', false) + + .controller('AccordionController', ['$scope', '$attrs', '$controller', '$log', '$accordionSuppressWarning', function($scope, $attrs, $controller, $log, $accordionSuppressWarning) { + if (!$accordionSuppressWarning) { + $log.warn('AccordionController is now deprecated. Use UibAccordionController instead.'); + } + + angular.extend(this, $controller('UibAccordionController', { + $scope: $scope, + $attrs: $attrs + })); + }]) + + .directive('accordion', ['$log', '$accordionSuppressWarning', function($log, $accordionSuppressWarning) { + return { + restrict: 'EA', + controller: 'AccordionController', + controllerAs: 'accordion', + transclude: true, + replace: false, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/accordion/accordion.html'; + }, + link: function() { + if (!$accordionSuppressWarning) { + $log.warn('accordion is now deprecated. Use uib-accordion instead.'); + } + } + }; + }]) + + .directive('accordionGroup', ['$log', '$accordionSuppressWarning', function($log, $accordionSuppressWarning) { + return { + require: '^accordion', // We need this directive to be inside an accordion + restrict: 'EA', + transclude: true, // It transcludes the contents of the directive into the template + replace: true, // The element containing the directive will be replaced with the template + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/accordion/accordion-group.html'; + }, + scope: { + heading: '@', // Interpolate the heading attribute onto this scope + isOpen: '=?', + isDisabled: '=?' + }, + controller: function() { + this.setHeading = function(element) { + this.heading = element; + }; + }, + link: function(scope, element, attrs, accordionCtrl) { + if (!$accordionSuppressWarning) { + $log.warn('accordion-group is now deprecated. Use uib-accordion-group instead.'); + } + + accordionCtrl.addGroup(scope); + + scope.openClass = attrs.openClass || 'panel-open'; + scope.panelClass = attrs.panelClass; + scope.$watch('isOpen', function(value) { + element.toggleClass(scope.openClass, !!value); + if (value) { + accordionCtrl.closeOthers(scope); + } + }); + + scope.toggleOpen = function($event) { + if (!scope.isDisabled) { + if (!$event || $event.which === 32) { + scope.isOpen = !scope.isOpen; + } + } + }; + } + }; + }]) + + .directive('accordionHeading', ['$log', '$accordionSuppressWarning', function($log, $accordionSuppressWarning) { + return { + restrict: 'EA', + transclude: true, // Grab the contents to be used as the heading + template: '', // In effect remove this element! + replace: true, + require: '^accordionGroup', + link: function(scope, element, attr, accordionGroupCtrl, transclude) { + if (!$accordionSuppressWarning) { + $log.warn('accordion-heading is now deprecated. Use uib-accordion-heading instead.'); + } + // Pass the heading to the accordion-group controller + // so that it can be transcluded into the right place in the template + // [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat] + accordionGroupCtrl.setHeading(transclude(scope, angular.noop)); + } + }; + }]) + + .directive('accordionTransclude', ['$log', '$accordionSuppressWarning', function($log, $accordionSuppressWarning) { + return { + require: '^accordionGroup', + link: function(scope, element, attr, controller) { + if (!$accordionSuppressWarning) { + $log.warn('accordion-transclude is now deprecated. Use uib-accordion-transclude instead.'); + } + + scope.$watch(function() { return controller[attr.accordionTransclude]; }, function(heading) { + if (heading) { + element.find('span').html(''); + element.find('span').append(heading); + } + }); + } + }; + }]); + + +angular.module('ui.bootstrap.alert', []) + +.controller('UibAlertController', ['$scope', '$attrs', '$interpolate', '$timeout', function($scope, $attrs, $interpolate, $timeout) { + $scope.closeable = !!$attrs.close; + + var dismissOnTimeout = angular.isDefined($attrs.dismissOnTimeout) ? + $interpolate($attrs.dismissOnTimeout)($scope.$parent) : null; + + if (dismissOnTimeout) { + $timeout(function() { + $scope.close(); + }, parseInt(dismissOnTimeout, 10)); + } +}]) + +.directive('uibAlert', function() { + return { + controller: 'UibAlertController', + controllerAs: 'alert', + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/alert/alert.html'; + }, + transclude: true, + replace: true, + scope: { + type: '@', + close: '&' + } + }; +}); + +/* Deprecated alert below */ + +angular.module('ui.bootstrap.alert') + + .value('$alertSuppressWarning', false) + + .controller('AlertController', ['$scope', '$attrs', '$controller', '$log', '$alertSuppressWarning', function($scope, $attrs, $controller, $log, $alertSuppressWarning) { + if (!$alertSuppressWarning) { + $log.warn('AlertController is now deprecated. Use UibAlertController instead.'); + } + + angular.extend(this, $controller('UibAlertController', { + $scope: $scope, + $attrs: $attrs + })); + }]) + + .directive('alert', ['$log', '$alertSuppressWarning', function($log, $alertSuppressWarning) { + return { + controller: 'AlertController', + controllerAs: 'alert', + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/alert/alert.html'; + }, + transclude: true, + replace: true, + scope: { + type: '@', + close: '&' + }, + link: function() { + if (!$alertSuppressWarning) { + $log.warn('alert is now deprecated. Use uib-alert instead.'); + } + } + }; + }]); + +angular.module('ui.bootstrap.buttons', []) + +.constant('uibButtonConfig', { + activeClass: 'active', + toggleEvent: 'click' +}) + +.controller('UibButtonsController', ['uibButtonConfig', function(buttonConfig) { + this.activeClass = buttonConfig.activeClass || 'active'; + this.toggleEvent = buttonConfig.toggleEvent || 'click'; +}]) + +.directive('uibBtnRadio', function() { + return { + require: ['uibBtnRadio', 'ngModel'], + controller: 'UibButtonsController', + controllerAs: 'buttons', + link: function(scope, element, attrs, ctrls) { + var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + element.find('input').css({display: 'none'}); + + //model -> UI + ngModelCtrl.$render = function() { + element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.uibBtnRadio))); + }; + + //ui->model + element.on(buttonsCtrl.toggleEvent, function() { + if (attrs.disabled) { + return; + } + + var isActive = element.hasClass(buttonsCtrl.activeClass); + + if (!isActive || angular.isDefined(attrs.uncheckable)) { + scope.$apply(function() { + ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.uibBtnRadio)); + ngModelCtrl.$render(); + }); + } + }); + } + }; +}) + +.directive('uibBtnCheckbox', function() { + return { + require: ['uibBtnCheckbox', 'ngModel'], + controller: 'UibButtonsController', + controllerAs: 'button', + link: function(scope, element, attrs, ctrls) { + var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + element.find('input').css({display: 'none'}); + + function getTrueValue() { + return getCheckboxValue(attrs.btnCheckboxTrue, true); + } + + function getFalseValue() { + return getCheckboxValue(attrs.btnCheckboxFalse, false); + } + + function getCheckboxValue(attribute, defaultValue) { + return angular.isDefined(attribute) ? scope.$eval(attribute) : defaultValue; + } + + //model -> UI + ngModelCtrl.$render = function() { + element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue())); + }; + + //ui->model + element.on(buttonsCtrl.toggleEvent, function() { + if (attrs.disabled) { + return; + } + + scope.$apply(function() { + ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue()); + ngModelCtrl.$render(); + }); + }); + } + }; +}); + +/* Deprecated buttons below */ + +angular.module('ui.bootstrap.buttons') + + .value('$buttonsSuppressWarning', false) + + .controller('ButtonsController', ['$controller', '$log', '$buttonsSuppressWarning', function($controller, $log, $buttonsSuppressWarning) { + if (!$buttonsSuppressWarning) { + $log.warn('ButtonsController is now deprecated. Use UibButtonsController instead.'); + } + + angular.extend(this, $controller('UibButtonsController')); + }]) + + .directive('btnRadio', ['$log', '$buttonsSuppressWarning', function($log, $buttonsSuppressWarning) { + return { + require: ['btnRadio', 'ngModel'], + controller: 'ButtonsController', + controllerAs: 'buttons', + link: function(scope, element, attrs, ctrls) { + if (!$buttonsSuppressWarning) { + $log.warn('btn-radio is now deprecated. Use uib-btn-radio instead.'); + } + + var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + element.find('input').css({display: 'none'}); + + //model -> UI + ngModelCtrl.$render = function() { + element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio))); + }; + + //ui->model + element.bind(buttonsCtrl.toggleEvent, function() { + if (attrs.disabled) { + return; + } + + var isActive = element.hasClass(buttonsCtrl.activeClass); + + if (!isActive || angular.isDefined(attrs.uncheckable)) { + scope.$apply(function() { + ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.btnRadio)); + ngModelCtrl.$render(); + }); + } + }); + } + }; + }]) + + .directive('btnCheckbox', ['$document', '$log', '$buttonsSuppressWarning', function($document, $log, $buttonsSuppressWarning) { + return { + require: ['btnCheckbox', 'ngModel'], + controller: 'ButtonsController', + controllerAs: 'button', + link: function(scope, element, attrs, ctrls) { + if (!$buttonsSuppressWarning) { + $log.warn('btn-checkbox is now deprecated. Use uib-btn-checkbox instead.'); + } + + var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + element.find('input').css({display: 'none'}); + + function getTrueValue() { + return getCheckboxValue(attrs.btnCheckboxTrue, true); + } + + function getFalseValue() { + return getCheckboxValue(attrs.btnCheckboxFalse, false); + } + + function getCheckboxValue(attributeValue, defaultValue) { + var val = scope.$eval(attributeValue); + return angular.isDefined(val) ? val : defaultValue; + } + + //model -> UI + ngModelCtrl.$render = function() { + element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue())); + }; + + //ui->model + element.bind(buttonsCtrl.toggleEvent, function() { + if (attrs.disabled) { + return; + } + + scope.$apply(function() { + ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue()); + ngModelCtrl.$render(); + }); + }); + + //accessibility + element.on('keypress', function(e) { + if (attrs.disabled || e.which !== 32 || $document[0].activeElement !== element[0]) { + return; + } + + scope.$apply(function() { + ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue()); + ngModelCtrl.$render(); + }); + }); + } + }; + }]); + + +/** + * @ngdoc overview + * @name ui.bootstrap.carousel + * + * @description + * AngularJS version of an image carousel. + * + */ +angular.module('ui.bootstrap.carousel', []) + +.controller('UibCarouselController', ['$scope', '$element', '$interval', '$animate', function($scope, $element, $interval, $animate) { + var self = this, + slides = self.slides = $scope.slides = [], + NEW_ANIMATE = angular.version.minor >= 4, + NO_TRANSITION = 'uib-noTransition', + SLIDE_DIRECTION = 'uib-slideDirection', + currentIndex = -1, + currentInterval, isPlaying; + self.currentSlide = null; + + var destroyed = false; + /* direction: "prev" or "next" */ + self.select = $scope.select = function(nextSlide, direction) { + var nextIndex = $scope.indexOfSlide(nextSlide); + //Decide direction if it's not given + if (direction === undefined) { + direction = nextIndex > self.getCurrentIndex() ? 'next' : 'prev'; + } + //Prevent this user-triggered transition from occurring if there is already one in progress + if (nextSlide && nextSlide !== self.currentSlide && !$scope.$currentTransition) { + goNext(nextSlide, nextIndex, direction); + } + }; + + function goNext(slide, index, direction) { + // Scope has been destroyed, stop here. + if (destroyed) { return; } + + angular.extend(slide, {direction: direction, active: true}); + angular.extend(self.currentSlide || {}, {direction: direction, active: false}); + if ($animate.enabled() && !$scope.noTransition && !$scope.$currentTransition && + slide.$element && self.slides.length > 1) { + slide.$element.data(SLIDE_DIRECTION, slide.direction); + if (self.currentSlide && self.currentSlide.$element) { + self.currentSlide.$element.data(SLIDE_DIRECTION, slide.direction); + } + + $scope.$currentTransition = true; + if (NEW_ANIMATE) { + $animate.on('addClass', slide.$element, function(element, phase) { + if (phase === 'close') { + $scope.$currentTransition = null; + $animate.off('addClass', element); + } + }); + } else { + slide.$element.one('$animate:close', function closeFn() { + $scope.$currentTransition = null; + }); + } + } + + self.currentSlide = slide; + currentIndex = index; + + //every time you change slides, reset the timer + restartTimer(); + } + + $scope.$on('$destroy', function() { + destroyed = true; + }); + + function getSlideByIndex(index) { + if (angular.isUndefined(slides[index].index)) { + return slides[index]; + } + var i, len = slides.length; + for (i = 0; i < slides.length; ++i) { + if (slides[i].index == index) { + return slides[i]; + } + } + } + + self.getCurrentIndex = function() { + if (self.currentSlide && angular.isDefined(self.currentSlide.index)) { + return +self.currentSlide.index; + } + return currentIndex; + }; + + /* Allow outside people to call indexOf on slides array */ + $scope.indexOfSlide = function(slide) { + return angular.isDefined(slide.index) ? +slide.index : slides.indexOf(slide); + }; + + $scope.next = function() { + var newIndex = (self.getCurrentIndex() + 1) % slides.length; + + if (newIndex === 0 && $scope.noWrap()) { + $scope.pause(); + return; + } + + return self.select(getSlideByIndex(newIndex), 'next'); + }; + + $scope.prev = function() { + var newIndex = self.getCurrentIndex() - 1 < 0 ? slides.length - 1 : self.getCurrentIndex() - 1; + + if ($scope.noWrap() && newIndex === slides.length - 1) { + $scope.pause(); + return; + } + + return self.select(getSlideByIndex(newIndex), 'prev'); + }; + + $scope.isActive = function(slide) { + return self.currentSlide === slide; + }; + + $scope.$watch('interval', restartTimer); + $scope.$watchCollection('slides', resetTransition); + $scope.$on('$destroy', resetTimer); + + function restartTimer() { + resetTimer(); + var interval = +$scope.interval; + if (!isNaN(interval) && interval > 0) { + currentInterval = $interval(timerFn, interval); + } + } + + function resetTimer() { + if (currentInterval) { + $interval.cancel(currentInterval); + currentInterval = null; + } + } + + function timerFn() { + var interval = +$scope.interval; + if (isPlaying && !isNaN(interval) && interval > 0 && slides.length) { + $scope.next(); + } else { + $scope.pause(); + } + } + + function resetTransition(slides) { + if (!slides.length) { + $scope.$currentTransition = null; + } + } + + $scope.play = function() { + if (!isPlaying) { + isPlaying = true; + restartTimer(); + } + }; + $scope.pause = function() { + if (!$scope.noPause) { + isPlaying = false; + resetTimer(); + } + }; + + self.addSlide = function(slide, element) { + slide.$element = element; + slides.push(slide); + //if this is the first slide or the slide is set to active, select it + if (slides.length === 1 || slide.active) { + self.select(slides[slides.length - 1]); + if (slides.length === 1) { + $scope.play(); + } + } else { + slide.active = false; + } + }; + + self.removeSlide = function(slide) { + if (angular.isDefined(slide.index)) { + slides.sort(function(a, b) { + return +a.index > +b.index; + }); + } + //get the index of the slide inside the carousel + var index = slides.indexOf(slide); + slides.splice(index, 1); + if (slides.length > 0 && slide.active) { + if (index >= slides.length) { + self.select(slides[index - 1]); + } else { + self.select(slides[index]); + } + } else if (currentIndex > index) { + currentIndex--; + } + + //clean the currentSlide when no more slide + if (slides.length === 0) { + self.currentSlide = null; + } + }; + + $scope.$watch('noTransition', function(noTransition) { + $element.data(NO_TRANSITION, noTransition); + }); + +}]) + +/** + * @ngdoc directive + * @name ui.bootstrap.carousel.directive:carousel + * @restrict EA + * + * @description + * Carousel is the outer container for a set of image 'slides' to showcase. + * + * @param {number=} interval The time, in milliseconds, that it will take the carousel to go to the next slide. + * @param {boolean=} noTransition Whether to disable transitions on the carousel. + * @param {boolean=} noPause Whether to disable pausing on the carousel (by default, the carousel interval pauses on hover). + * + * @example + + + + + + + + + + + + + + + .carousel-indicators { + top: auto; + bottom: 15px; + } + + + */ +.directive('uibCarousel', [function() { + return { + transclude: true, + replace: true, + controller: 'UibCarouselController', + controllerAs: 'carousel', + require: 'carousel', + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/carousel/carousel.html'; + }, + scope: { + interval: '=', + noTransition: '=', + noPause: '=', + noWrap: '&' + } + }; +}]) + +/** + * @ngdoc directive + * @name ui.bootstrap.carousel.directive:slide + * @restrict EA + * + * @description + * Creates a slide inside a {@link ui.bootstrap.carousel.directive:carousel carousel}. Must be placed as a child of a carousel element. + * + * @param {boolean=} active Model binding, whether or not this slide is currently active. + * @param {number=} index The index of the slide. The slides will be sorted by this parameter. + * + * @example + + +
      + + + + + + + Interval, in milliseconds: +
      Enter a negative number to stop the interval. +
      +
      + +function CarouselDemoCtrl($scope) { + $scope.myInterval = 5000; +} + + + .carousel-indicators { + top: auto; + bottom: 15px; + } + +
      +*/ + +.directive('uibSlide', function() { + return { + require: '^uibCarousel', + restrict: 'EA', + transclude: true, + replace: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/carousel/slide.html'; + }, + scope: { + active: '=?', + actual: '=?', + index: '=?' + }, + link: function (scope, element, attrs, carouselCtrl) { + carouselCtrl.addSlide(scope, element); + //when the scope is destroyed then remove the slide from the current slides array + scope.$on('$destroy', function() { + carouselCtrl.removeSlide(scope); + }); + + scope.$watch('active', function(active) { + if (active) { + carouselCtrl.select(scope); + } + }); + } + }; +}) + +.animation('.item', [ + '$injector', '$animate', +function ($injector, $animate) { + var NO_TRANSITION = 'uib-noTransition', + SLIDE_DIRECTION = 'uib-slideDirection', + $animateCss = null; + + if ($injector.has('$animateCss')) { + $animateCss = $injector.get('$animateCss'); + } + + function removeClass(element, className, callback) { + element.removeClass(className); + if (callback) { + callback(); + } + } + + return { + beforeAddClass: function(element, className, done) { + // Due to transclusion, noTransition property is on parent's scope + if (className == 'active' && element.parent() && element.parent().parent() && + !element.parent().parent().data(NO_TRANSITION)) { + var stopped = false; + var direction = element.data(SLIDE_DIRECTION); + var directionClass = direction == 'next' ? 'left' : 'right'; + var removeClassFn = removeClass.bind(this, element, + directionClass + ' ' + direction, done); + element.addClass(direction); + + if ($animateCss) { + $animateCss(element, {addClass: directionClass}) + .start() + .done(removeClassFn); + } else { + $animate.addClass(element, directionClass).then(function () { + if (!stopped) { + removeClassFn(); + } + done(); + }); + } + + return function () { + stopped = true; + }; + } + done(); + }, + beforeRemoveClass: function (element, className, done) { + // Due to transclusion, noTransition property is on parent's scope + if (className === 'active' && element.parent() && element.parent().parent() && + !element.parent().parent().data(NO_TRANSITION)) { + var stopped = false; + var direction = element.data(SLIDE_DIRECTION); + var directionClass = direction == 'next' ? 'left' : 'right'; + var removeClassFn = removeClass.bind(this, element, directionClass, done); + + if ($animateCss) { + $animateCss(element, {addClass: directionClass}) + .start() + .done(removeClassFn); + } else { + $animate.addClass(element, directionClass).then(function() { + if (!stopped) { + removeClassFn(); + } + done(); + }); + } + return function() { + stopped = true; + }; + } + done(); + } + }; +}]); + +/* deprecated carousel below */ + +angular.module('ui.bootstrap.carousel') + +.value('$carouselSuppressWarning', false) + +.controller('CarouselController', ['$scope', '$element', '$controller', '$log', '$carouselSuppressWarning', function($scope, $element, $controller, $log, $carouselSuppressWarning) { + if (!$carouselSuppressWarning) { + $log.warn('CarouselController is now deprecated. Use UibCarouselController instead.'); + } + + angular.extend(this, $controller('UibCarouselController', { + $scope: $scope, + $element: $element + })); +}]) + +.directive('carousel', ['$log', '$carouselSuppressWarning', function($log, $carouselSuppressWarning) { + return { + transclude: true, + replace: true, + controller: 'CarouselController', + controllerAs: 'carousel', + require: 'carousel', + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/carousel/carousel.html'; + }, + scope: { + interval: '=', + noTransition: '=', + noPause: '=', + noWrap: '&' + }, + link: function() { + if (!$carouselSuppressWarning) { + $log.warn('carousel is now deprecated. Use uib-carousel instead.'); + } + } + }; +}]) + +.directive('slide', ['$log', '$carouselSuppressWarning', function($log, $carouselSuppressWarning) { + return { + require: '^carousel', + transclude: true, + replace: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/carousel/slide.html'; + }, + scope: { + active: '=?', + actual: '=?', + index: '=?' + }, + link: function (scope, element, attrs, carouselCtrl) { + if (!$carouselSuppressWarning) { + $log.warn('slide is now deprecated. Use uib-slide instead.'); + } + + carouselCtrl.addSlide(scope, element); + //when the scope is destroyed then remove the slide from the current slides array + scope.$on('$destroy', function() { + carouselCtrl.removeSlide(scope); + }); + + scope.$watch('active', function(active) { + if (active) { + carouselCtrl.select(scope); + } + }); + } + }; +}]); + +angular.module('ui.bootstrap.dateparser', []) + +.service('uibDateParser', ['$log', '$locale', 'orderByFilter', function($log, $locale, orderByFilter) { + // Pulled from https://github.com/mbostock/d3/blob/master/src/format/requote.js + var SPECIAL_CHARACTERS_REGEXP = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; + + var localeId; + var formatCodeToRegex; + + this.init = function() { + localeId = $locale.id; + + this.parsers = {}; + + formatCodeToRegex = { + 'yyyy': { + regex: '\\d{4}', + apply: function(value) { this.year = +value; } + }, + 'yy': { + regex: '\\d{2}', + apply: function(value) { this.year = +value + 2000; } + }, + 'y': { + regex: '\\d{1,4}', + apply: function(value) { this.year = +value; } + }, + 'MMMM': { + regex: $locale.DATETIME_FORMATS.MONTH.join('|'), + apply: function(value) { this.month = $locale.DATETIME_FORMATS.MONTH.indexOf(value); } + }, + 'MMM': { + regex: $locale.DATETIME_FORMATS.SHORTMONTH.join('|'), + apply: function(value) { this.month = $locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value); } + }, + 'MM': { + regex: '0[1-9]|1[0-2]', + apply: function(value) { this.month = value - 1; } + }, + 'M': { + regex: '[1-9]|1[0-2]', + apply: function(value) { this.month = value - 1; } + }, + 'dd': { + regex: '[0-2][0-9]{1}|3[0-1]{1}', + apply: function(value) { this.date = +value; } + }, + 'd': { + regex: '[1-2]?[0-9]{1}|3[0-1]{1}', + apply: function(value) { this.date = +value; } + }, + 'EEEE': { + regex: $locale.DATETIME_FORMATS.DAY.join('|') + }, + 'EEE': { + regex: $locale.DATETIME_FORMATS.SHORTDAY.join('|') + }, + 'HH': { + regex: '(?:0|1)[0-9]|2[0-3]', + apply: function(value) { this.hours = +value; } + }, + 'hh': { + regex: '0[0-9]|1[0-2]', + apply: function(value) { this.hours = +value; } + }, + 'H': { + regex: '1?[0-9]|2[0-3]', + apply: function(value) { this.hours = +value; } + }, + 'h': { + regex: '[0-9]|1[0-2]', + apply: function(value) { this.hours = +value; } + }, + 'mm': { + regex: '[0-5][0-9]', + apply: function(value) { this.minutes = +value; } + }, + 'm': { + regex: '[0-9]|[1-5][0-9]', + apply: function(value) { this.minutes = +value; } + }, + 'sss': { + regex: '[0-9][0-9][0-9]', + apply: function(value) { this.milliseconds = +value; } + }, + 'ss': { + regex: '[0-5][0-9]', + apply: function(value) { this.seconds = +value; } + }, + 's': { + regex: '[0-9]|[1-5][0-9]', + apply: function(value) { this.seconds = +value; } + }, + 'a': { + regex: $locale.DATETIME_FORMATS.AMPMS.join('|'), + apply: function(value) { + if (this.hours === 12) { + this.hours = 0; + } + + if (value === 'PM') { + this.hours += 12; + } + } + } + }; + }; + + this.init(); + + function createParser(format) { + var map = [], regex = format.split(''); + + angular.forEach(formatCodeToRegex, function(data, code) { + var index = format.indexOf(code); + + if (index > -1) { + format = format.split(''); + + regex[index] = '(' + data.regex + ')'; + format[index] = '$'; // Custom symbol to define consumed part of format + for (var i = index + 1, n = index + code.length; i < n; i++) { + regex[i] = ''; + format[i] = '$'; + } + format = format.join(''); + + map.push({ index: index, apply: data.apply }); + } + }); + + return { + regex: new RegExp('^' + regex.join('') + '$'), + map: orderByFilter(map, 'index') + }; + } + + this.parse = function(input, format, baseDate) { + if (!angular.isString(input) || !format) { + return input; + } + + format = $locale.DATETIME_FORMATS[format] || format; + format = format.replace(SPECIAL_CHARACTERS_REGEXP, '\\$&'); + + if ($locale.id !== localeId) { + this.init(); + } + + if (!this.parsers[format]) { + this.parsers[format] = createParser(format); + } + + var parser = this.parsers[format], + regex = parser.regex, + map = parser.map, + results = input.match(regex); + + if (results && results.length) { + var fields, dt; + if (angular.isDate(baseDate) && !isNaN(baseDate.getTime())) { + fields = { + year: baseDate.getFullYear(), + month: baseDate.getMonth(), + date: baseDate.getDate(), + hours: baseDate.getHours(), + minutes: baseDate.getMinutes(), + seconds: baseDate.getSeconds(), + milliseconds: baseDate.getMilliseconds() + }; + } else { + if (baseDate) { + $log.warn('dateparser:', 'baseDate is not a valid date'); + } + fields = { year: 1900, month: 0, date: 1, hours: 0, minutes: 0, seconds: 0, milliseconds: 0 }; + } + + for (var i = 1, n = results.length; i < n; i++) { + var mapper = map[i-1]; + if (mapper.apply) { + mapper.apply.call(fields, results[i]); + } + } + + if (isValid(fields.year, fields.month, fields.date)) { + if (angular.isDate(baseDate) && !isNaN(baseDate.getTime())) { + dt = new Date(baseDate); + dt.setFullYear(fields.year, fields.month, fields.date, + fields.hours, fields.minutes, fields.seconds, + fields.milliseconds || 0); + } else { + dt = new Date(fields.year, fields.month, fields.date, + fields.hours, fields.minutes, fields.seconds, + fields.milliseconds || 0); + } + } + + return dt; + } + }; + + // Check if date is valid for specific month (and year for February). + // Month: 0 = Jan, 1 = Feb, etc + function isValid(year, month, date) { + if (date < 1) { + return false; + } + + if (month === 1 && date > 28) { + return date === 29 && ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0); + } + + if (month === 3 || month === 5 || month === 8 || month === 10) { + return date < 31; + } + + return true; + } +}]); + +/* Deprecated dateparser below */ + +angular.module('ui.bootstrap.dateparser') + +.value('$dateParserSuppressWarning', false) + +.service('dateParser', ['$log', '$dateParserSuppressWarning', 'uibDateParser', function($log, $dateParserSuppressWarning, uibDateParser) { + if (!$dateParserSuppressWarning) { + $log.warn('dateParser is now deprecated. Use uibDateParser instead.'); + } + + angular.extend(this, uibDateParser); +}]); + +angular.module('ui.bootstrap.position', []) + +/** + * A set of utility methods that can be use to retrieve position of DOM elements. + * It is meant to be used where we need to absolute-position DOM elements in + * relation to other, existing elements (this is the case for tooltips, popovers, + * typeahead suggestions etc.). + */ + .factory('$uibPosition', ['$document', '$window', function($document, $window) { + function getStyle(el, cssprop) { + if (el.currentStyle) { //IE + return el.currentStyle[cssprop]; + } else if ($window.getComputedStyle) { + return $window.getComputedStyle(el)[cssprop]; + } + // finally try and get inline style + return el.style[cssprop]; + } + + /** + * Checks if a given element is statically positioned + * @param element - raw DOM element + */ + function isStaticPositioned(element) { + return (getStyle(element, 'position') || 'static' ) === 'static'; + } + + /** + * returns the closest, non-statically positioned parentOffset of a given element + * @param element + */ + var parentOffsetEl = function(element) { + var docDomEl = $document[0]; + var offsetParent = element.offsetParent || docDomEl; + while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) { + offsetParent = offsetParent.offsetParent; + } + return offsetParent || docDomEl; + }; + + return { + /** + * Provides read-only equivalent of jQuery's position function: + * http://api.jquery.com/position/ + */ + position: function(element) { + var elBCR = this.offset(element); + var offsetParentBCR = { top: 0, left: 0 }; + var offsetParentEl = parentOffsetEl(element[0]); + if (offsetParentEl != $document[0]) { + offsetParentBCR = this.offset(angular.element(offsetParentEl)); + offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop; + offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft; + } + + var boundingClientRect = element[0].getBoundingClientRect(); + return { + width: boundingClientRect.width || element.prop('offsetWidth'), + height: boundingClientRect.height || element.prop('offsetHeight'), + top: elBCR.top - offsetParentBCR.top, + left: elBCR.left - offsetParentBCR.left + }; + }, + + /** + * Provides read-only equivalent of jQuery's offset function: + * http://api.jquery.com/offset/ + */ + offset: function(element) { + var boundingClientRect = element[0].getBoundingClientRect(); + return { + width: boundingClientRect.width || element.prop('offsetWidth'), + height: boundingClientRect.height || element.prop('offsetHeight'), + top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop), + left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft) + }; + }, + + /** + * Provides coordinates for the targetEl in relation to hostEl + */ + positionElements: function(hostEl, targetEl, positionStr, appendToBody) { + var positionStrParts = positionStr.split('-'); + var pos0 = positionStrParts[0], pos1 = positionStrParts[1] || 'center'; + + var hostElPos, + targetElWidth, + targetElHeight, + targetElPos; + + hostElPos = appendToBody ? this.offset(hostEl) : this.position(hostEl); + + targetElWidth = targetEl.prop('offsetWidth'); + targetElHeight = targetEl.prop('offsetHeight'); + + var shiftWidth = { + center: function() { + return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2; + }, + left: function() { + return hostElPos.left; + }, + right: function() { + return hostElPos.left + hostElPos.width; + } + }; + + var shiftHeight = { + center: function() { + return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2; + }, + top: function() { + return hostElPos.top; + }, + bottom: function() { + return hostElPos.top + hostElPos.height; + } + }; + + switch (pos0) { + case 'right': + targetElPos = { + top: shiftHeight[pos1](), + left: shiftWidth[pos0]() + }; + break; + case 'left': + targetElPos = { + top: shiftHeight[pos1](), + left: hostElPos.left - targetElWidth + }; + break; + case 'bottom': + targetElPos = { + top: shiftHeight[pos0](), + left: shiftWidth[pos1]() + }; + break; + default: + targetElPos = { + top: hostElPos.top - targetElHeight, + left: shiftWidth[pos1]() + }; + break; + } + + return targetElPos; + } + }; + }]); + +/* Deprecated position below */ + +angular.module('ui.bootstrap.position') + +.value('$positionSuppressWarning', false) + +.service('$position', ['$log', '$positionSuppressWarning', '$uibPosition', function($log, $positionSuppressWarning, $uibPosition) { + if (!$positionSuppressWarning) { + $log.warn('$position is now deprecated. Use $uibPosition instead.'); + } + + angular.extend(this, $uibPosition); +}]); + +angular.module('ui.bootstrap.datepicker', ['ui.bootstrap.dateparser', 'ui.bootstrap.position']) + +.value('$datepickerSuppressError', false) + +.constant('uibDatepickerConfig', { + formatDay: 'dd', + formatMonth: 'MMMM', + formatYear: 'yyyy', + formatDayHeader: 'EEE', + formatDayTitle: 'MMMM yyyy', + formatMonthTitle: 'yyyy', + datepickerMode: 'day', + minMode: 'day', + maxMode: 'year', + showWeeks: true, + startingDay: 0, + yearRange: 20, + minDate: null, + maxDate: null, + shortcutPropagation: false +}) + +.controller('UibDatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$log', 'dateFilter', 'uibDatepickerConfig', '$datepickerSuppressError', function($scope, $attrs, $parse, $interpolate, $log, dateFilter, datepickerConfig, $datepickerSuppressError) { + var self = this, + ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl; + + // Modes chain + this.modes = ['day', 'month', 'year']; + + // Configuration attributes + angular.forEach(['formatDay', 'formatMonth', 'formatYear', 'formatDayHeader', 'formatDayTitle', 'formatMonthTitle', + 'showWeeks', 'startingDay', 'yearRange', 'shortcutPropagation'], function(key, index) { + self[key] = angular.isDefined($attrs[key]) ? (index < 6 ? $interpolate($attrs[key])($scope.$parent) : $scope.$parent.$eval($attrs[key])) : datepickerConfig[key]; + }); + + // Watchable date attributes + angular.forEach(['minDate', 'maxDate'], function(key) { + if ($attrs[key]) { + $scope.$parent.$watch($parse($attrs[key]), function(value) { + self[key] = value ? new Date(value) : null; + self.refreshView(); + }); + } else { + self[key] = datepickerConfig[key] ? new Date(datepickerConfig[key]) : null; + } + }); + + angular.forEach(['minMode', 'maxMode'], function(key) { + if ($attrs[key]) { + $scope.$parent.$watch($parse($attrs[key]), function(value) { + self[key] = angular.isDefined(value) ? value : $attrs[key]; + $scope[key] = self[key]; + if ((key == 'minMode' && self.modes.indexOf($scope.datepickerMode) < self.modes.indexOf(self[key])) || (key == 'maxMode' && self.modes.indexOf($scope.datepickerMode) > self.modes.indexOf(self[key]))) { + $scope.datepickerMode = self[key]; + } + }); + } else { + self[key] = datepickerConfig[key] || null; + $scope[key] = self[key]; + } + }); + + $scope.datepickerMode = $scope.datepickerMode || datepickerConfig.datepickerMode; + $scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000); + + if (angular.isDefined($attrs.initDate)) { + this.activeDate = $scope.$parent.$eval($attrs.initDate) || new Date(); + $scope.$parent.$watch($attrs.initDate, function(initDate) { + if (initDate && (ngModelCtrl.$isEmpty(ngModelCtrl.$modelValue) || ngModelCtrl.$invalid)) { + self.activeDate = initDate; + self.refreshView(); + } + }); + } else { + this.activeDate = new Date(); + } + + $scope.isActive = function(dateObject) { + if (self.compare(dateObject.date, self.activeDate) === 0) { + $scope.activeDateId = dateObject.uid; + return true; + } + return false; + }; + + this.init = function(ngModelCtrl_) { + ngModelCtrl = ngModelCtrl_; + + ngModelCtrl.$render = function() { + self.render(); + }; + }; + + this.render = function() { + if (ngModelCtrl.$viewValue) { + var date = new Date(ngModelCtrl.$viewValue), + isValid = !isNaN(date); + + if (isValid) { + this.activeDate = date; + } else if (!$datepickerSuppressError) { + $log.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.'); + } + } + this.refreshView(); + }; + + this.refreshView = function() { + if (this.element) { + this._refreshView(); + + var date = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null; + ngModelCtrl.$setValidity('dateDisabled', !date || (this.element && !this.isDisabled(date))); + } + }; + + this.createDateObject = function(date, format) { + var model = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null; + return { + date: date, + label: dateFilter(date, format), + selected: model && this.compare(date, model) === 0, + disabled: this.isDisabled(date), + current: this.compare(date, new Date()) === 0, + customClass: this.customClass(date) + }; + }; + + this.isDisabled = function(date) { + return ((this.minDate && this.compare(date, this.minDate) < 0) || (this.maxDate && this.compare(date, this.maxDate) > 0) || ($attrs.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode}))); + }; + + this.customClass = function(date) { + return $scope.customClass({date: date, mode: $scope.datepickerMode}); + }; + + // Split array into smaller arrays + this.split = function(arr, size) { + var arrays = []; + while (arr.length > 0) { + arrays.push(arr.splice(0, size)); + } + return arrays; + }; + + $scope.select = function(date) { + if ($scope.datepickerMode === self.minMode) { + var dt = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : new Date(0, 0, 0, 0, 0, 0, 0); + dt.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); + ngModelCtrl.$setViewValue(dt); + ngModelCtrl.$render(); + } else { + self.activeDate = date; + $scope.datepickerMode = self.modes[self.modes.indexOf($scope.datepickerMode) - 1]; + } + }; + + $scope.move = function(direction) { + var year = self.activeDate.getFullYear() + direction * (self.step.years || 0), + month = self.activeDate.getMonth() + direction * (self.step.months || 0); + self.activeDate.setFullYear(year, month, 1); + self.refreshView(); + }; + + $scope.toggleMode = function(direction) { + direction = direction || 1; + + if (($scope.datepickerMode === self.maxMode && direction === 1) || ($scope.datepickerMode === self.minMode && direction === -1)) { + return; + } + + $scope.datepickerMode = self.modes[self.modes.indexOf($scope.datepickerMode) + direction]; + }; + + // Key event mapper + $scope.keys = { 13: 'enter', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; + + var focusElement = function() { + self.element[0].focus(); + }; + + // Listen for focus requests from popup directive + $scope.$on('uib:datepicker.focus', focusElement); + + $scope.keydown = function(evt) { + var key = $scope.keys[evt.which]; + + if (!key || evt.shiftKey || evt.altKey) { + return; + } + + evt.preventDefault(); + if (!self.shortcutPropagation) { + evt.stopPropagation(); + } + + if (key === 'enter' || key === 'space') { + if (self.isDisabled(self.activeDate)) { + return; // do nothing + } + $scope.select(self.activeDate); + } else if (evt.ctrlKey && (key === 'up' || key === 'down')) { + $scope.toggleMode(key === 'up' ? 1 : -1); + } else { + self.handleKeyDown(key, evt); + self.refreshView(); + } + }; +}]) + +.controller('UibDaypickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) { + var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + + this.step = { months: 1 }; + this.element = $element; + function getDaysInMonth(year, month) { + return ((month === 1) && (year % 4 === 0) && ((year % 100 !== 0) || (year % 400 === 0))) ? 29 : DAYS_IN_MONTH[month]; + } + + this.init = function(ctrl) { + angular.extend(ctrl, this); + scope.showWeeks = ctrl.showWeeks; + ctrl.refreshView(); + }; + + this.getDates = function(startDate, n) { + var dates = new Array(n), current = new Date(startDate), i = 0, date; + while (i < n) { + date = new Date(current); + dates[i++] = date; + current.setDate(current.getDate() + 1); + } + return dates; + }; + + this._refreshView = function() { + var year = this.activeDate.getFullYear(), + month = this.activeDate.getMonth(), + firstDayOfMonth = new Date(this.activeDate); + + firstDayOfMonth.setFullYear(year, month, 1); + + var difference = this.startingDay - firstDayOfMonth.getDay(), + numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : - difference, + firstDate = new Date(firstDayOfMonth); + + if (numDisplayedFromPreviousMonth > 0) { + firstDate.setDate(-numDisplayedFromPreviousMonth + 1); + } + + // 42 is the number of days on a six-month calendar + var days = this.getDates(firstDate, 42); + for (var i = 0; i < 42; i ++) { + days[i] = angular.extend(this.createDateObject(days[i], this.formatDay), { + secondary: days[i].getMonth() !== month, + uid: scope.uniqueId + '-' + i + }); + } + + scope.labels = new Array(7); + for (var j = 0; j < 7; j++) { + scope.labels[j] = { + abbr: dateFilter(days[j].date, this.formatDayHeader), + full: dateFilter(days[j].date, 'EEEE') + }; + } + + scope.title = dateFilter(this.activeDate, this.formatDayTitle); + scope.rows = this.split(days, 7); + + if (scope.showWeeks) { + scope.weekNumbers = []; + var thursdayIndex = (4 + 7 - this.startingDay) % 7, + numWeeks = scope.rows.length; + for (var curWeek = 0; curWeek < numWeeks; curWeek++) { + scope.weekNumbers.push( + getISO8601WeekNumber(scope.rows[curWeek][thursdayIndex].date)); + } + } + }; + + this.compare = function(date1, date2) { + return (new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate())); + }; + + function getISO8601WeekNumber(date) { + var checkDate = new Date(date); + checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday + var time = checkDate.getTime(); + checkDate.setMonth(0); // Compare with Jan 1 + checkDate.setDate(1); + return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; + } + + this.handleKeyDown = function(key, evt) { + var date = this.activeDate.getDate(); + + if (key === 'left') { + date = date - 1; // up + } else if (key === 'up') { + date = date - 7; // down + } else if (key === 'right') { + date = date + 1; // down + } else if (key === 'down') { + date = date + 7; + } else if (key === 'pageup' || key === 'pagedown') { + var month = this.activeDate.getMonth() + (key === 'pageup' ? - 1 : 1); + this.activeDate.setMonth(month, 1); + date = Math.min(getDaysInMonth(this.activeDate.getFullYear(), this.activeDate.getMonth()), date); + } else if (key === 'home') { + date = 1; + } else if (key === 'end') { + date = getDaysInMonth(this.activeDate.getFullYear(), this.activeDate.getMonth()); + } + this.activeDate.setDate(date); + }; +}]) + +.controller('UibMonthpickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) { + this.step = { years: 1 }; + this.element = $element; + + this.init = function(ctrl) { + angular.extend(ctrl, this); + ctrl.refreshView(); + }; + + this._refreshView = function() { + var months = new Array(12), + year = this.activeDate.getFullYear(), + date; + + for (var i = 0; i < 12; i++) { + date = new Date(this.activeDate); + date.setFullYear(year, i, 1); + months[i] = angular.extend(this.createDateObject(date, this.formatMonth), { + uid: scope.uniqueId + '-' + i + }); + } + + scope.title = dateFilter(this.activeDate, this.formatMonthTitle); + scope.rows = this.split(months, 3); + }; + + this.compare = function(date1, date2) { + return new Date(date1.getFullYear(), date1.getMonth()) - new Date(date2.getFullYear(), date2.getMonth()); + }; + + this.handleKeyDown = function(key, evt) { + var date = this.activeDate.getMonth(); + + if (key === 'left') { + date = date - 1; // up + } else if (key === 'up') { + date = date - 3; // down + } else if (key === 'right') { + date = date + 1; // down + } else if (key === 'down') { + date = date + 3; + } else if (key === 'pageup' || key === 'pagedown') { + var year = this.activeDate.getFullYear() + (key === 'pageup' ? - 1 : 1); + this.activeDate.setFullYear(year); + } else if (key === 'home') { + date = 0; + } else if (key === 'end') { + date = 11; + } + this.activeDate.setMonth(date); + }; +}]) + +.controller('UibYearpickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) { + var range; + this.element = $element; + + function getStartingYear(year) { + return parseInt((year - 1) / range, 10) * range + 1; + } + + this.yearpickerInit = function() { + range = this.yearRange; + this.step = { years: range }; + }; + + this._refreshView = function() { + var years = new Array(range), date; + + for (var i = 0, start = getStartingYear(this.activeDate.getFullYear()); i < range; i++) { + date = new Date(this.activeDate); + date.setFullYear(start + i, 0, 1); + years[i] = angular.extend(this.createDateObject(date, this.formatYear), { + uid: scope.uniqueId + '-' + i + }); + } + + scope.title = [years[0].label, years[range - 1].label].join(' - '); + scope.rows = this.split(years, 5); + }; + + this.compare = function(date1, date2) { + return date1.getFullYear() - date2.getFullYear(); + }; + + this.handleKeyDown = function(key, evt) { + var date = this.activeDate.getFullYear(); + + if (key === 'left') { + date = date - 1; // up + } else if (key === 'up') { + date = date - 5; // down + } else if (key === 'right') { + date = date + 1; // down + } else if (key === 'down') { + date = date + 5; + } else if (key === 'pageup' || key === 'pagedown') { + date += (key === 'pageup' ? - 1 : 1) * this.step.years; + } else if (key === 'home') { + date = getStartingYear(this.activeDate.getFullYear()); + } else if (key === 'end') { + date = getStartingYear(this.activeDate.getFullYear()) + range - 1; + } + this.activeDate.setFullYear(date); + }; +}]) + +.directive('uibDatepicker', function() { + return { + replace: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/datepicker/datepicker.html'; + }, + scope: { + datepickerMode: '=?', + dateDisabled: '&', + customClass: '&', + shortcutPropagation: '&?' + }, + require: ['uibDatepicker', '^ngModel'], + controller: 'UibDatepickerController', + controllerAs: 'datepicker', + link: function(scope, element, attrs, ctrls) { + var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + datepickerCtrl.init(ngModelCtrl); + } + }; +}) + +.directive('uibDaypicker', function() { + return { + replace: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/datepicker/day.html'; + }, + require: ['^?uibDatepicker', 'uibDaypicker', '^?datepicker'], + controller: 'UibDaypickerController', + link: function(scope, element, attrs, ctrls) { + var datepickerCtrl = ctrls[0] || ctrls[2], + daypickerCtrl = ctrls[1]; + + daypickerCtrl.init(datepickerCtrl); + } + }; +}) + +.directive('uibMonthpicker', function() { + return { + replace: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/datepicker/month.html'; + }, + require: ['^?uibDatepicker', 'uibMonthpicker', '^?datepicker'], + controller: 'UibMonthpickerController', + link: function(scope, element, attrs, ctrls) { + var datepickerCtrl = ctrls[0] || ctrls[2], + monthpickerCtrl = ctrls[1]; + + monthpickerCtrl.init(datepickerCtrl); + } + }; +}) + +.directive('uibYearpicker', function() { + return { + replace: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/datepicker/year.html'; + }, + require: ['^?uibDatepicker', 'uibYearpicker', '^?datepicker'], + controller: 'UibYearpickerController', + link: function(scope, element, attrs, ctrls) { + var ctrl = ctrls[0] || ctrls[2]; + angular.extend(ctrl, ctrls[1]); + ctrl.yearpickerInit(); + + ctrl.refreshView(); + } + }; +}) + +.constant('uibDatepickerPopupConfig', { + datepickerPopup: 'yyyy-MM-dd', + datepickerPopupTemplateUrl: 'template/datepicker/popup.html', + datepickerTemplateUrl: 'template/datepicker/datepicker.html', + html5Types: { + date: 'yyyy-MM-dd', + 'datetime-local': 'yyyy-MM-ddTHH:mm:ss.sss', + 'month': 'yyyy-MM' + }, + currentText: 'Today', + clearText: 'Clear', + closeText: 'Done', + closeOnDateSelection: true, + appendToBody: false, + showButtonBar: true, + onOpenFocus: true +}) + +.controller('UibDatepickerPopupController', ['$scope', '$element', '$attrs', '$compile', '$parse', '$document', '$rootScope', '$uibPosition', 'dateFilter', 'uibDateParser', 'uibDatepickerPopupConfig', '$timeout', +function(scope, element, attrs, $compile, $parse, $document, $rootScope, $position, dateFilter, dateParser, datepickerPopupConfig, $timeout) { + var self = this; + var cache = {}, + isHtml5DateInput = false; + var dateFormat, closeOnDateSelection, appendToBody, onOpenFocus, + datepickerPopupTemplateUrl, datepickerTemplateUrl, popupEl, datepickerEl, + ngModel, $popup; + + scope.watchData = {}; + + this.init = function(_ngModel_) { + ngModel = _ngModel_; + closeOnDateSelection = angular.isDefined(attrs.closeOnDateSelection) ? scope.$parent.$eval(attrs.closeOnDateSelection) : datepickerPopupConfig.closeOnDateSelection; + appendToBody = angular.isDefined(attrs.datepickerAppendToBody) ? scope.$parent.$eval(attrs.datepickerAppendToBody) : datepickerPopupConfig.appendToBody; + onOpenFocus = angular.isDefined(attrs.onOpenFocus) ? scope.$parent.$eval(attrs.onOpenFocus) : datepickerPopupConfig.onOpenFocus; + datepickerPopupTemplateUrl = angular.isDefined(attrs.datepickerPopupTemplateUrl) ? attrs.datepickerPopupTemplateUrl : datepickerPopupConfig.datepickerPopupTemplateUrl; + datepickerTemplateUrl = angular.isDefined(attrs.datepickerTemplateUrl) ? attrs.datepickerTemplateUrl : datepickerPopupConfig.datepickerTemplateUrl; + + scope.showButtonBar = angular.isDefined(attrs.showButtonBar) ? scope.$parent.$eval(attrs.showButtonBar) : datepickerPopupConfig.showButtonBar; + + if (datepickerPopupConfig.html5Types[attrs.type]) { + dateFormat = datepickerPopupConfig.html5Types[attrs.type]; + isHtml5DateInput = true; + } else { + dateFormat = attrs.datepickerPopup || attrs.uibDatepickerPopup || datepickerPopupConfig.datepickerPopup; + attrs.$observe('uibDatepickerPopup', function(value, oldValue) { + var newDateFormat = value || datepickerPopupConfig.datepickerPopup; + // Invalidate the $modelValue to ensure that formatters re-run + // FIXME: Refactor when PR is merged: https://github.com/angular/angular.js/pull/10764 + if (newDateFormat !== dateFormat) { + dateFormat = newDateFormat; + ngModel.$modelValue = null; + + if (!dateFormat) { + throw new Error('uibDatepickerPopup must have a date format specified.'); + } + } + }); + } + + if (!dateFormat) { + throw new Error('uibDatepickerPopup must have a date format specified.'); + } + + if (isHtml5DateInput && attrs.datepickerPopup) { + throw new Error('HTML5 date input types do not support custom formats.'); + } + + // popup element used to display calendar + popupEl = angular.element('
      '); + popupEl.attr({ + 'ng-model': 'date', + 'ng-change': 'dateSelection(date)', + 'template-url': datepickerPopupTemplateUrl + }); + + // datepicker element + datepickerEl = angular.element(popupEl.children()[0]); + datepickerEl.attr('template-url', datepickerTemplateUrl); + + if (isHtml5DateInput) { + if (attrs.type === 'month') { + datepickerEl.attr('datepicker-mode', '"month"'); + datepickerEl.attr('min-mode', 'month'); + } + } + + if (attrs.datepickerOptions) { + var options = scope.$parent.$eval(attrs.datepickerOptions); + if (options && options.initDate) { + scope.initDate = options.initDate; + datepickerEl.attr('init-date', 'initDate'); + delete options.initDate; + } + angular.forEach(options, function(value, option) { + datepickerEl.attr(cameltoDash(option), value); + }); + } + + angular.forEach(['minMode', 'maxMode', 'minDate', 'maxDate', 'datepickerMode', 'initDate', 'shortcutPropagation'], function(key) { + if (attrs[key]) { + var getAttribute = $parse(attrs[key]); + scope.$parent.$watch(getAttribute, function(value) { + scope.watchData[key] = value; + if (key === 'minDate' || key === 'maxDate') { + cache[key] = new Date(value); + } + }); + datepickerEl.attr(cameltoDash(key), 'watchData.' + key); + + // Propagate changes from datepicker to outside + if (key === 'datepickerMode') { + var setAttribute = getAttribute.assign; + scope.$watch('watchData.' + key, function(value, oldvalue) { + if (angular.isFunction(setAttribute) && value !== oldvalue) { + setAttribute(scope.$parent, value); + } + }); + } + } + }); + if (attrs.dateDisabled) { + datepickerEl.attr('date-disabled', 'dateDisabled({ date: date, mode: mode })'); + } + + if (attrs.showWeeks) { + datepickerEl.attr('show-weeks', attrs.showWeeks); + } + + if (attrs.customClass) { + datepickerEl.attr('custom-class', 'customClass({ date: date, mode: mode })'); + } + + if (!isHtml5DateInput) { + // Internal API to maintain the correct ng-invalid-[key] class + ngModel.$$parserName = 'date'; + ngModel.$validators.date = validator; + ngModel.$parsers.unshift(parseDate); + ngModel.$formatters.push(function(value) { + scope.date = value; + return ngModel.$isEmpty(value) ? value : dateFilter(value, dateFormat); + }); + } else { + ngModel.$formatters.push(function(value) { + scope.date = value; + return value; + }); + } + + // Detect changes in the view from the text box + ngModel.$viewChangeListeners.push(function() { + scope.date = dateParser.parse(ngModel.$viewValue, dateFormat, scope.date); + }); + + element.bind('keydown', inputKeydownBind); + + $popup = $compile(popupEl)(scope); + // Prevent jQuery cache memory leak (template is now redundant after linking) + popupEl.remove(); + + if (appendToBody) { + $document.find('body').append($popup); + } else { + element.after($popup); + } + + scope.$on('$destroy', function() { + if (scope.isOpen === true) { + if (!$rootScope.$$phase) { + scope.$apply(function() { + scope.isOpen = false; + }); + } + } + + $popup.remove(); + element.unbind('keydown', inputKeydownBind); + $document.unbind('click', documentClickBind); + }); + }; + + scope.getText = function(key) { + return scope[key + 'Text'] || datepickerPopupConfig[key + 'Text']; + }; + + scope.isDisabled = function(date) { + if (date === 'today') { + date = new Date(); + } + + return ((scope.watchData.minDate && scope.compare(date, cache.minDate) < 0) || + (scope.watchData.maxDate && scope.compare(date, cache.maxDate) > 0)); + }; + + scope.compare = function(date1, date2) { + return (new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate())); + }; + + // Inner change + scope.dateSelection = function(dt) { + if (angular.isDefined(dt)) { + scope.date = dt; + } + var date = scope.date ? dateFilter(scope.date, dateFormat) : null; // Setting to NULL is necessary for form validators to function + element.val(date); + ngModel.$setViewValue(date); + + if (closeOnDateSelection) { + scope.isOpen = false; + element[0].focus(); + } + }; + + scope.keydown = function(evt) { + if (evt.which === 27) { + scope.isOpen = false; + element[0].focus(); + } + }; + + scope.select = function(date) { + if (date === 'today') { + var today = new Date(); + if (angular.isDate(scope.date)) { + date = new Date(scope.date); + date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate()); + } else { + date = new Date(today.setHours(0, 0, 0, 0)); + } + } + scope.dateSelection(date); + }; + + scope.close = function() { + scope.isOpen = false; + element[0].focus(); + }; + + scope.$watch('isOpen', function(value) { + if (value) { + scope.position = appendToBody ? $position.offset(element) : $position.position(element); + scope.position.top = scope.position.top + element.prop('offsetHeight'); + + $timeout(function() { + if (onOpenFocus) { + scope.$broadcast('uib:datepicker.focus'); + } + $document.bind('click', documentClickBind); + }, 0, false); + } else { + $document.unbind('click', documentClickBind); + } + }); + + function cameltoDash(string) { + return string.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); }); + } + + function parseDate(viewValue) { + if (angular.isNumber(viewValue)) { + // presumably timestamp to date object + viewValue = new Date(viewValue); + } + + if (!viewValue) { + return null; + } else if (angular.isDate(viewValue) && !isNaN(viewValue)) { + return viewValue; + } else if (angular.isString(viewValue)) { + var date = dateParser.parse(viewValue, dateFormat, scope.date); + if (isNaN(date)) { + return undefined; + } else { + return date; + } + } else { + return undefined; + } + } + + function validator(modelValue, viewValue) { + var value = modelValue || viewValue; + + if (!attrs.ngRequired && !value) { + return true; + } + + if (angular.isNumber(value)) { + value = new Date(value); + } + if (!value) { + return true; + } else if (angular.isDate(value) && !isNaN(value)) { + return true; + } else if (angular.isString(value)) { + var date = dateParser.parse(value, dateFormat); + return !isNaN(date); + } else { + return false; + } + } + + function documentClickBind(event) { + var popup = $popup[0]; + var dpContainsTarget = element[0].contains(event.target); + // The popup node may not be an element node + // In some browsers (IE) only element nodes have the 'contains' function + var popupContainsTarget = popup.contains !== undefined && popup.contains(event.target); + if (scope.isOpen && !(dpContainsTarget || popupContainsTarget)) { + scope.$apply(function() { + scope.isOpen = false; + }); + } + } + + function inputKeydownBind(evt) { + if (evt.which === 27 && scope.isOpen) { + evt.preventDefault(); + evt.stopPropagation(); + scope.$apply(function() { + scope.isOpen = false; + }); + element[0].focus(); + } else if (evt.which === 40 && !scope.isOpen) { + evt.preventDefault(); + evt.stopPropagation(); + scope.$apply(function() { + scope.isOpen = true; + }); + } + } +}]) + +.directive('uibDatepickerPopup', function() { + return { + require: ['ngModel', 'uibDatepickerPopup'], + controller: 'UibDatepickerPopupController', + scope: { + isOpen: '=?', + currentText: '@', + clearText: '@', + closeText: '@', + dateDisabled: '&', + customClass: '&' + }, + link: function(scope, element, attrs, ctrls) { + var ngModel = ctrls[0], + ctrl = ctrls[1]; + + ctrl.init(ngModel); + } + }; +}) + +.directive('uibDatepickerPopupWrap', function() { + return { + replace: true, + transclude: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/datepicker/popup.html'; + } + }; +}); + +/* Deprecated datepicker below */ + +angular.module('ui.bootstrap.datepicker') + +.value('$datepickerSuppressWarning', false) + +.controller('DatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$log', 'dateFilter', 'uibDatepickerConfig', '$datepickerSuppressError', '$datepickerSuppressWarning', function($scope, $attrs, $parse, $interpolate, $log, dateFilter, datepickerConfig, $datepickerSuppressError, $datepickerSuppressWarning) { + if (!$datepickerSuppressWarning) { + $log.warn('DatepickerController is now deprecated. Use UibDatepickerController instead.'); + } + + var self = this, + ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl; + + this.modes = ['day', 'month', 'year']; + + angular.forEach(['formatDay', 'formatMonth', 'formatYear', 'formatDayHeader', 'formatDayTitle', 'formatMonthTitle', + 'showWeeks', 'startingDay', 'yearRange', 'shortcutPropagation'], function(key, index) { + self[key] = angular.isDefined($attrs[key]) ? (index < 6 ? $interpolate($attrs[key])($scope.$parent) : $scope.$parent.$eval($attrs[key])) : datepickerConfig[key]; + }); + + angular.forEach(['minDate', 'maxDate'], function(key) { + if ($attrs[key]) { + $scope.$parent.$watch($parse($attrs[key]), function(value) { + self[key] = value ? new Date(value) : null; + self.refreshView(); + }); + } else { + self[key] = datepickerConfig[key] ? new Date(datepickerConfig[key]) : null; + } + }); + + angular.forEach(['minMode', 'maxMode'], function(key) { + if ($attrs[key]) { + $scope.$parent.$watch($parse($attrs[key]), function(value) { + self[key] = angular.isDefined(value) ? value : $attrs[key]; + $scope[key] = self[key]; + if ((key == 'minMode' && self.modes.indexOf($scope.datepickerMode) < self.modes.indexOf(self[key])) || (key == 'maxMode' && self.modes.indexOf($scope.datepickerMode) > self.modes.indexOf(self[key]))) { + $scope.datepickerMode = self[key]; + } + }); + } else { + self[key] = datepickerConfig[key] || null; + $scope[key] = self[key]; + } + }); + + $scope.datepickerMode = $scope.datepickerMode || datepickerConfig.datepickerMode; + $scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000); + + if (angular.isDefined($attrs.initDate)) { + this.activeDate = $scope.$parent.$eval($attrs.initDate) || new Date(); + $scope.$parent.$watch($attrs.initDate, function(initDate) { + if (initDate && (ngModelCtrl.$isEmpty(ngModelCtrl.$modelValue) || ngModelCtrl.$invalid)) { + self.activeDate = initDate; + self.refreshView(); + } + }); + } else { + this.activeDate = new Date(); + } + + $scope.isActive = function(dateObject) { + if (self.compare(dateObject.date, self.activeDate) === 0) { + $scope.activeDateId = dateObject.uid; + return true; + } + return false; + }; + + this.init = function(ngModelCtrl_) { + ngModelCtrl = ngModelCtrl_; + + ngModelCtrl.$render = function() { + self.render(); + }; + }; + + this.render = function() { + if (ngModelCtrl.$viewValue) { + var date = new Date(ngModelCtrl.$viewValue), + isValid = !isNaN(date); + + if (isValid) { + this.activeDate = date; + } else if (!$datepickerSuppressError) { + $log.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.'); + } + } + this.refreshView(); + }; + + this.refreshView = function() { + if (this.element) { + this._refreshView(); + + var date = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null; + ngModelCtrl.$setValidity('dateDisabled', !date || (this.element && !this.isDisabled(date))); + } + }; + + this.createDateObject = function(date, format) { + var model = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null; + return { + date: date, + label: dateFilter(date, format), + selected: model && this.compare(date, model) === 0, + disabled: this.isDisabled(date), + current: this.compare(date, new Date()) === 0, + customClass: this.customClass(date) + }; + }; + + this.isDisabled = function(date) { + return ((this.minDate && this.compare(date, this.minDate) < 0) || (this.maxDate && this.compare(date, this.maxDate) > 0) || ($attrs.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode}))); + }; + + this.customClass = function(date) { + return $scope.customClass({date: date, mode: $scope.datepickerMode}); + }; + + // Split array into smaller arrays + this.split = function(arr, size) { + var arrays = []; + while (arr.length > 0) { + arrays.push(arr.splice(0, size)); + } + return arrays; + }; + + this.fixTimeZone = function(date) { + var hours = date.getHours(); + date.setHours(hours === 23 ? hours + 2 : 0); + }; + + $scope.select = function(date) { + if ($scope.datepickerMode === self.minMode) { + var dt = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : new Date(0, 0, 0, 0, 0, 0, 0); + dt.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); + ngModelCtrl.$setViewValue(dt); + ngModelCtrl.$render(); + } else { + self.activeDate = date; + $scope.datepickerMode = self.modes[self.modes.indexOf($scope.datepickerMode) - 1]; + } + }; + + $scope.move = function(direction) { + var year = self.activeDate.getFullYear() + direction * (self.step.years || 0), + month = self.activeDate.getMonth() + direction * (self.step.months || 0); + self.activeDate.setFullYear(year, month, 1); + self.refreshView(); + }; + + $scope.toggleMode = function(direction) { + direction = direction || 1; + + if (($scope.datepickerMode === self.maxMode && direction === 1) || ($scope.datepickerMode === self.minMode && direction === -1)) { + return; + } + + $scope.datepickerMode = self.modes[self.modes.indexOf($scope.datepickerMode) + direction]; + }; + + // Key event mapper + $scope.keys = { 13: 'enter', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; + + var focusElement = function() { + self.element[0].focus(); + }; + + $scope.$on('uib:datepicker.focus', focusElement); + + $scope.keydown = function(evt) { + var key = $scope.keys[evt.which]; + + if (!key || evt.shiftKey || evt.altKey) { + return; + } + + evt.preventDefault(); + if (!self.shortcutPropagation) { + evt.stopPropagation(); + } + + if (key === 'enter' || key === 'space') { + if (self.isDisabled(self.activeDate)) { + return; // do nothing + } + $scope.select(self.activeDate); + } else if (evt.ctrlKey && (key === 'up' || key === 'down')) { + $scope.toggleMode(key === 'up' ? 1 : -1); + } else { + self.handleKeyDown(key, evt); + self.refreshView(); + } + }; +}]) + +.directive('datepicker', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) { + return { + replace: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/datepicker/datepicker.html'; + }, + scope: { + datepickerMode: '=?', + dateDisabled: '&', + customClass: '&', + shortcutPropagation: '&?' + }, + require: ['datepicker', '^ngModel'], + controller: 'DatepickerController', + controllerAs: 'datepicker', + link: function(scope, element, attrs, ctrls) { + if (!$datepickerSuppressWarning) { + $log.warn('datepicker is now deprecated. Use uib-datepicker instead.'); + } + + var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + datepickerCtrl.init(ngModelCtrl); + } + }; +}]) + +.directive('daypicker', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) { + return { + replace: true, + templateUrl: 'template/datepicker/day.html', + require: ['^datepicker', 'daypicker'], + controller: 'UibDaypickerController', + link: function(scope, element, attrs, ctrls) { + if (!$datepickerSuppressWarning) { + $log.warn('daypicker is now deprecated. Use uib-daypicker instead.'); + } + + var datepickerCtrl = ctrls[0], + daypickerCtrl = ctrls[1]; + + daypickerCtrl.init(datepickerCtrl); + } + }; +}]) + +.directive('monthpicker', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) { + return { + replace: true, + templateUrl: 'template/datepicker/month.html', + require: ['^datepicker', 'monthpicker'], + controller: 'UibMonthpickerController', + link: function(scope, element, attrs, ctrls) { + if (!$datepickerSuppressWarning) { + $log.warn('monthpicker is now deprecated. Use uib-monthpicker instead.'); + } + + var datepickerCtrl = ctrls[0], + monthpickerCtrl = ctrls[1]; + + monthpickerCtrl.init(datepickerCtrl); + } + }; +}]) + +.directive('yearpicker', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) { + return { + replace: true, + templateUrl: 'template/datepicker/year.html', + require: ['^datepicker', 'yearpicker'], + controller: 'UibYearpickerController', + link: function(scope, element, attrs, ctrls) { + if (!$datepickerSuppressWarning) { + $log.warn('yearpicker is now deprecated. Use uib-yearpicker instead.'); + } + + var ctrl = ctrls[0]; + angular.extend(ctrl, ctrls[1]); + ctrl.yearpickerInit(); + + ctrl.refreshView(); + } + }; +}]) + +.directive('datepickerPopup', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) { + return { + require: ['ngModel', 'datepickerPopup'], + controller: 'UibDatepickerPopupController', + scope: { + isOpen: '=?', + currentText: '@', + clearText: '@', + closeText: '@', + dateDisabled: '&', + customClass: '&' + }, + link: function(scope, element, attrs, ctrls) { + if (!$datepickerSuppressWarning) { + $log.warn('datepicker-popup is now deprecated. Use uib-datepicker-popup instead.'); + } + + var ngModel = ctrls[0], + ctrl = ctrls[1]; + + ctrl.init(ngModel); + } + }; +}]) + +.directive('datepickerPopupWrap', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) { + return { + replace: true, + transclude: true, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/datepicker/popup.html'; + }, + link: function() { + if (!$datepickerSuppressWarning) { + $log.warn('datepicker-popup-wrap is now deprecated. Use uib-datepicker-popup-wrap instead.'); + } + } + }; +}]); + +angular.module('ui.bootstrap.dropdown', ['ui.bootstrap.position']) + +.constant('uibDropdownConfig', { + openClass: 'open' +}) + +.service('uibDropdownService', ['$document', '$rootScope', function($document, $rootScope) { + var openScope = null; + + this.open = function(dropdownScope) { + if (!openScope) { + $document.bind('click', closeDropdown); + $document.bind('keydown', keybindFilter); + } + + if (openScope && openScope !== dropdownScope) { + openScope.isOpen = false; + } + + openScope = dropdownScope; + }; + + this.close = function(dropdownScope) { + if (openScope === dropdownScope) { + openScope = null; + $document.unbind('click', closeDropdown); + $document.unbind('keydown', keybindFilter); + } + }; + + var closeDropdown = function(evt) { + // This method may still be called during the same mouse event that + // unbound this event handler. So check openScope before proceeding. + if (!openScope) { return; } + + if (evt && openScope.getAutoClose() === 'disabled') { return ; } + + var toggleElement = openScope.getToggleElement(); + if (evt && toggleElement && toggleElement[0].contains(evt.target)) { + return; + } + + var dropdownElement = openScope.getDropdownElement(); + if (evt && openScope.getAutoClose() === 'outsideClick' && + dropdownElement && dropdownElement[0].contains(evt.target)) { + return; + } + + openScope.isOpen = false; + + if (!$rootScope.$$phase) { + openScope.$apply(); + } + }; + + var keybindFilter = function(evt) { + if (evt.which === 27) { + openScope.focusToggleElement(); + closeDropdown(); + } else if (openScope.isKeynavEnabled() && /(38|40)/.test(evt.which) && openScope.isOpen) { + evt.preventDefault(); + evt.stopPropagation(); + openScope.focusDropdownEntry(evt.which); + } + }; +}]) + +.controller('UibDropdownController', ['$scope', '$element', '$attrs', '$parse', 'uibDropdownConfig', 'uibDropdownService', '$animate', '$uibPosition', '$document', '$compile', '$templateRequest', function($scope, $element, $attrs, $parse, dropdownConfig, uibDropdownService, $animate, $position, $document, $compile, $templateRequest) { + var self = this, + scope = $scope.$new(), // create a child scope so we are not polluting original one + templateScope, + openClass = dropdownConfig.openClass, + getIsOpen, + setIsOpen = angular.noop, + toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop, + appendToBody = false, + keynavEnabled =false, + selectedOption = null; + + + $element.addClass('dropdown'); + + this.init = function() { + if ($attrs.isOpen) { + getIsOpen = $parse($attrs.isOpen); + setIsOpen = getIsOpen.assign; + + $scope.$watch(getIsOpen, function(value) { + scope.isOpen = !!value; + }); + } + + appendToBody = angular.isDefined($attrs.dropdownAppendToBody); + keynavEnabled = angular.isDefined($attrs.uibKeyboardNav); + + if (appendToBody && self.dropdownMenu) { + $document.find('body').append(self.dropdownMenu); + $element.on('$destroy', function handleDestroyEvent() { + self.dropdownMenu.remove(); + }); + } + }; + + this.toggle = function(open) { + return scope.isOpen = arguments.length ? !!open : !scope.isOpen; + }; + + // Allow other directives to watch status + this.isOpen = function() { + return scope.isOpen; + }; + + scope.getToggleElement = function() { + return self.toggleElement; + }; + + scope.getAutoClose = function() { + return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled' + }; + + scope.getElement = function() { + return $element; + }; + + scope.isKeynavEnabled = function() { + return keynavEnabled; + }; + + scope.focusDropdownEntry = function(keyCode) { + var elems = self.dropdownMenu ? //If append to body is used. + (angular.element(self.dropdownMenu).find('a')) : + (angular.element($element).find('ul').eq(0).find('a')); + + switch (keyCode) { + case (40): { + if (!angular.isNumber(self.selectedOption)) { + self.selectedOption = 0; + } else { + self.selectedOption = (self.selectedOption === elems.length - 1 ? + self.selectedOption : + self.selectedOption + 1); + } + break; + } + case (38): { + if (!angular.isNumber(self.selectedOption)) { + self.selectedOption = elems.length - 1; + } else { + self.selectedOption = self.selectedOption === 0 ? + 0 : self.selectedOption - 1; + } + break; + } + } + elems[self.selectedOption].focus(); + }; + + scope.getDropdownElement = function() { + return self.dropdownMenu; + }; + + scope.focusToggleElement = function() { + if (self.toggleElement) { + self.toggleElement[0].focus(); + } + }; + + scope.$watch('isOpen', function(isOpen, wasOpen) { + if (appendToBody && self.dropdownMenu) { + var pos = $position.positionElements($element, self.dropdownMenu, 'bottom-left', true); + var css = { + top: pos.top + 'px', + display: isOpen ? 'block' : 'none' + }; + + var rightalign = self.dropdownMenu.hasClass('dropdown-menu-right'); + if (!rightalign) { + css.left = pos.left + 'px'; + css.right = 'auto'; + } else { + css.left = 'auto'; + css.right = (window.innerWidth - (pos.left + $element.prop('offsetWidth'))) + 'px'; + } + + self.dropdownMenu.css(css); + } + + $animate[isOpen ? 'addClass' : 'removeClass']($element, openClass).then(function() { + if (angular.isDefined(isOpen) && isOpen !== wasOpen) { + toggleInvoker($scope, { open: !!isOpen }); + } + }); + + if (isOpen) { + if (self.dropdownMenuTemplateUrl) { + $templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) { + templateScope = scope.$new(); + $compile(tplContent.trim())(templateScope, function(dropdownElement) { + var newEl = dropdownElement; + self.dropdownMenu.replaceWith(newEl); + self.dropdownMenu = newEl; + }); + }); + } + + scope.focusToggleElement(); + uibDropdownService.open(scope); + } else { + if (self.dropdownMenuTemplateUrl) { + if (templateScope) { + templateScope.$destroy(); + } + var newEl = angular.element(''); + self.dropdownMenu.replaceWith(newEl); + self.dropdownMenu = newEl; + } + + uibDropdownService.close(scope); + self.selectedOption = null; + } + + if (angular.isFunction(setIsOpen)) { + setIsOpen($scope, isOpen); + } + }); + + $scope.$on('$locationChangeSuccess', function() { + if (scope.getAutoClose() !== 'disabled') { + scope.isOpen = false; + } + }); + + var offDestroy = $scope.$on('$destroy', function() { + scope.$destroy(); + }); + scope.$on('$destroy', offDestroy); +}]) + +.directive('uibDropdown', function() { + return { + controller: 'UibDropdownController', + link: function(scope, element, attrs, dropdownCtrl) { + dropdownCtrl.init(); + } + }; +}) + +.directive('uibDropdownMenu', function() { + return { + restrict: 'AC', + require: '?^uibDropdown', + link: function(scope, element, attrs, dropdownCtrl) { + if (!dropdownCtrl || angular.isDefined(attrs.dropdownNested)) { + return; + } + + element.addClass('dropdown-menu'); + + var tplUrl = attrs.templateUrl; + if (tplUrl) { + dropdownCtrl.dropdownMenuTemplateUrl = tplUrl; + } + + if (!dropdownCtrl.dropdownMenu) { + dropdownCtrl.dropdownMenu = element; + } + } + }; +}) + +.directive('uibKeyboardNav', function() { + return { + restrict: 'A', + require: '?^uibDropdown', + link: function(scope, element, attrs, dropdownCtrl) { + element.bind('keydown', function(e) { + if ([38, 40].indexOf(e.which) !== -1) { + e.preventDefault(); + e.stopPropagation(); + + var elems = dropdownCtrl.dropdownMenu.find('a'); + + switch (e.which) { + case (40): { // Down + if (!angular.isNumber(dropdownCtrl.selectedOption)) { + dropdownCtrl.selectedOption = 0; + } else { + dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === elems.length -1 ? + dropdownCtrl.selectedOption : dropdownCtrl.selectedOption + 1; + } + break; + } + case (38): { // Up + if (!angular.isNumber(dropdownCtrl.selectedOption)) { + dropdownCtrl.selectedOption = elems.length - 1; + } else { + dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === 0 ? + 0 : dropdownCtrl.selectedOption - 1; + } + break; + } + } + elems[dropdownCtrl.selectedOption].focus(); + } + }); + } + }; +}) + +.directive('uibDropdownToggle', function() { + return { + require: '?^uibDropdown', + link: function(scope, element, attrs, dropdownCtrl) { + if (!dropdownCtrl) { + return; + } + + element.addClass('dropdown-toggle'); + + dropdownCtrl.toggleElement = element; + + var toggleDropdown = function(event) { + event.preventDefault(); + + if (!element.hasClass('disabled') && !attrs.disabled) { + scope.$apply(function() { + dropdownCtrl.toggle(); + }); + } + }; + + element.bind('click', toggleDropdown); + + // WAI-ARIA + element.attr({ 'aria-haspopup': true, 'aria-expanded': false }); + scope.$watch(dropdownCtrl.isOpen, function(isOpen) { + element.attr('aria-expanded', !!isOpen); + }); + + scope.$on('$destroy', function() { + element.unbind('click', toggleDropdown); + }); + } + }; +}); + +/* Deprecated dropdown below */ + +angular.module('ui.bootstrap.dropdown') + +.value('$dropdownSuppressWarning', false) + +.service('dropdownService', ['$log', '$dropdownSuppressWarning', 'uibDropdownService', function($log, $dropdownSuppressWarning, uibDropdownService) { + if (!$dropdownSuppressWarning) { + $log.warn('dropdownService is now deprecated. Use uibDropdownService instead.'); + } + + angular.extend(this, uibDropdownService); +}]) + +.controller('DropdownController', ['$scope', '$element', '$attrs', '$parse', 'uibDropdownConfig', 'uibDropdownService', '$animate', '$uibPosition', '$document', '$compile', '$templateRequest', '$log', '$dropdownSuppressWarning', function($scope, $element, $attrs, $parse, dropdownConfig, uibDropdownService, $animate, $position, $document, $compile, $templateRequest, $log, $dropdownSuppressWarning) { + if (!$dropdownSuppressWarning) { + $log.warn('DropdownController is now deprecated. Use UibDropdownController instead.'); + } + + var self = this, + scope = $scope.$new(), // create a child scope so we are not polluting original one + templateScope, + openClass = dropdownConfig.openClass, + getIsOpen, + setIsOpen = angular.noop, + toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop, + appendToBody = false, + keynavEnabled =false, + selectedOption = null; + + + $element.addClass('dropdown'); + + this.init = function() { + if ($attrs.isOpen) { + getIsOpen = $parse($attrs.isOpen); + setIsOpen = getIsOpen.assign; + + $scope.$watch(getIsOpen, function(value) { + scope.isOpen = !!value; + }); + } + + appendToBody = angular.isDefined($attrs.dropdownAppendToBody); + keynavEnabled = angular.isDefined($attrs.uibKeyboardNav); + + if (appendToBody && self.dropdownMenu) { + $document.find('body').append(self.dropdownMenu); + $element.on('$destroy', function handleDestroyEvent() { + self.dropdownMenu.remove(); + }); + } + }; + + this.toggle = function(open) { + return scope.isOpen = arguments.length ? !!open : !scope.isOpen; + }; + + // Allow other directives to watch status + this.isOpen = function() { + return scope.isOpen; + }; + + scope.getToggleElement = function() { + return self.toggleElement; + }; + + scope.getAutoClose = function() { + return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled' + }; + + scope.getElement = function() { + return $element; + }; + + scope.isKeynavEnabled = function() { + return keynavEnabled; + }; + + scope.focusDropdownEntry = function(keyCode) { + var elems = self.dropdownMenu ? //If append to body is used. + (angular.element(self.dropdownMenu).find('a')) : + (angular.element($element).find('ul').eq(0).find('a')); + + switch (keyCode) { + case (40): { + if (!angular.isNumber(self.selectedOption)) { + self.selectedOption = 0; + } else { + self.selectedOption = (self.selectedOption === elems.length -1 ? + self.selectedOption : + self.selectedOption + 1); + } + break; + } + case (38): { + if (!angular.isNumber(self.selectedOption)) { + self.selectedOption = elems.length - 1; + } else { + self.selectedOption = self.selectedOption === 0 ? + 0 : self.selectedOption - 1; + } + break; + } + } + elems[self.selectedOption].focus(); + }; + + scope.getDropdownElement = function() { + return self.dropdownMenu; + }; + + scope.focusToggleElement = function() { + if (self.toggleElement) { + self.toggleElement[0].focus(); + } + }; + + scope.$watch('isOpen', function(isOpen, wasOpen) { + if (appendToBody && self.dropdownMenu) { + var pos = $position.positionElements($element, self.dropdownMenu, 'bottom-left', true); + var css = { + top: pos.top + 'px', + display: isOpen ? 'block' : 'none' + }; + + var rightalign = self.dropdownMenu.hasClass('dropdown-menu-right'); + if (!rightalign) { + css.left = pos.left + 'px'; + css.right = 'auto'; + } else { + css.left = 'auto'; + css.right = (window.innerWidth - (pos.left + $element.prop('offsetWidth'))) + 'px'; + } + + self.dropdownMenu.css(css); + } + + $animate[isOpen ? 'addClass' : 'removeClass']($element, openClass).then(function() { + if (angular.isDefined(isOpen) && isOpen !== wasOpen) { + toggleInvoker($scope, { open: !!isOpen }); + } + }); + + if (isOpen) { + if (self.dropdownMenuTemplateUrl) { + $templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) { + templateScope = scope.$new(); + $compile(tplContent.trim())(templateScope, function(dropdownElement) { + var newEl = dropdownElement; + self.dropdownMenu.replaceWith(newEl); + self.dropdownMenu = newEl; + }); + }); + } + + scope.focusToggleElement(); + uibDropdownService.open(scope); + } else { + if (self.dropdownMenuTemplateUrl) { + if (templateScope) { + templateScope.$destroy(); + } + var newEl = angular.element(''); + self.dropdownMenu.replaceWith(newEl); + self.dropdownMenu = newEl; + } + + uibDropdownService.close(scope); + self.selectedOption = null; + } + + if (angular.isFunction(setIsOpen)) { + setIsOpen($scope, isOpen); + } + }); + + $scope.$on('$locationChangeSuccess', function() { + if (scope.getAutoClose() !== 'disabled') { + scope.isOpen = false; + } + }); + + var offDestroy = $scope.$on('$destroy', function() { + scope.$destroy(); + }); + scope.$on('$destroy', offDestroy); +}]) + +.directive('dropdown', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) { + return { + controller: 'DropdownController', + link: function(scope, element, attrs, dropdownCtrl) { + if (!$dropdownSuppressWarning) { + $log.warn('dropdown is now deprecated. Use uib-dropdown instead.'); + } + + dropdownCtrl.init(); + } + }; +}]) + +.directive('dropdownMenu', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) { + return { + restrict: 'AC', + require: '?^dropdown', + link: function(scope, element, attrs, dropdownCtrl) { + if (!dropdownCtrl || angular.isDefined(attrs.dropdownNested)) { + return; + } + + if (!$dropdownSuppressWarning) { + $log.warn('dropdown-menu is now deprecated. Use uib-dropdown-menu instead.'); + } + + element.addClass('dropdown-menu'); + + var tplUrl = attrs.templateUrl; + if (tplUrl) { + dropdownCtrl.dropdownMenuTemplateUrl = tplUrl; + } + + if (!dropdownCtrl.dropdownMenu) { + dropdownCtrl.dropdownMenu = element; + } + } + }; +}]) + +.directive('keyboardNav', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) { + return { + restrict: 'A', + require: '?^dropdown', + link: function(scope, element, attrs, dropdownCtrl) { + if (!$dropdownSuppressWarning) { + $log.warn('keyboard-nav is now deprecated. Use uib-keyboard-nav instead.'); + } + + element.bind('keydown', function(e) { + if ([38, 40].indexOf(e.which) !== -1) { + e.preventDefault(); + e.stopPropagation(); + + var elems = dropdownCtrl.dropdownMenu.find('a'); + + switch (e.which) { + case (40): { // Down + if (!angular.isNumber(dropdownCtrl.selectedOption)) { + dropdownCtrl.selectedOption = 0; + } else { + dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === elems.length -1 ? + dropdownCtrl.selectedOption : dropdownCtrl.selectedOption + 1; + } + break; + } + case (38): { // Up + if (!angular.isNumber(dropdownCtrl.selectedOption)) { + dropdownCtrl.selectedOption = elems.length - 1; + } else { + dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === 0 ? + 0 : dropdownCtrl.selectedOption - 1; + } + break; + } + } + elems[dropdownCtrl.selectedOption].focus(); + } + }); + } + }; +}]) + +.directive('dropdownToggle', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) { + return { + require: '?^dropdown', + link: function(scope, element, attrs, dropdownCtrl) { + if (!$dropdownSuppressWarning) { + $log.warn('dropdown-toggle is now deprecated. Use uib-dropdown-toggle instead.'); + } + + if (!dropdownCtrl) { + return; + } + + element.addClass('dropdown-toggle'); + + dropdownCtrl.toggleElement = element; + + var toggleDropdown = function(event) { + event.preventDefault(); + + if (!element.hasClass('disabled') && !attrs.disabled) { + scope.$apply(function() { + dropdownCtrl.toggle(); + }); + } + }; + + element.bind('click', toggleDropdown); + + // WAI-ARIA + element.attr({ 'aria-haspopup': true, 'aria-expanded': false }); + scope.$watch(dropdownCtrl.isOpen, function(isOpen) { + element.attr('aria-expanded', !!isOpen); + }); + + scope.$on('$destroy', function() { + element.unbind('click', toggleDropdown); + }); + } + }; +}]); + +angular.module('ui.bootstrap.stackedMap', []) +/** + * A helper, internal data structure that acts as a map but also allows getting / removing + * elements in the LIFO order + */ + .factory('$$stackedMap', function() { + return { + createNew: function() { + var stack = []; + + return { + add: function(key, value) { + stack.push({ + key: key, + value: value + }); + }, + get: function(key) { + for (var i = 0; i < stack.length; i++) { + if (key == stack[i].key) { + return stack[i]; + } + } + }, + keys: function() { + var keys = []; + for (var i = 0; i < stack.length; i++) { + keys.push(stack[i].key); + } + return keys; + }, + top: function() { + return stack[stack.length - 1]; + }, + remove: function(key) { + var idx = -1; + for (var i = 0; i < stack.length; i++) { + if (key == stack[i].key) { + idx = i; + break; + } + } + return stack.splice(idx, 1)[0]; + }, + removeTop: function() { + return stack.splice(stack.length - 1, 1)[0]; + }, + length: function() { + return stack.length; + } + }; + } + }; + }); +angular.module('ui.bootstrap.modal', ['ui.bootstrap.stackedMap']) +/** + * A helper, internal data structure that stores all references attached to key + */ + .factory('$$multiMap', function() { + return { + createNew: function() { + var map = {}; + + return { + entries: function() { + return Object.keys(map).map(function(key) { + return { + key: key, + value: map[key] + }; + }); + }, + get: function(key) { + return map[key]; + }, + hasKey: function(key) { + return !!map[key]; + }, + keys: function() { + return Object.keys(map); + }, + put: function(key, value) { + if (!map[key]) { + map[key] = []; + } + + map[key].push(value); + }, + remove: function(key, value) { + var values = map[key]; + + if (!values) { + return; + } + + var idx = values.indexOf(value); + + if (idx !== -1) { + values.splice(idx, 1); + } + + if (!values.length) { + delete map[key]; + } + } + }; + } + }; + }) + +/** + * A helper directive for the $modal service. It creates a backdrop element. + */ + .directive('uibModalBackdrop', [ + '$animate', '$injector', '$uibModalStack', + function($animate , $injector, $modalStack) { + var $animateCss = null; + + if ($injector.has('$animateCss')) { + $animateCss = $injector.get('$animateCss'); + } + + return { + replace: true, + templateUrl: 'template/modal/backdrop.html', + compile: function(tElement, tAttrs) { + tElement.addClass(tAttrs.backdropClass); + return linkFn; + } + }; + + function linkFn(scope, element, attrs) { + // Temporary fix for prefixing + element.addClass('modal-backdrop'); + + if (attrs.modalInClass) { + if ($animateCss) { + $animateCss(element, { + addClass: attrs.modalInClass + }).start(); + } else { + $animate.addClass(element, attrs.modalInClass); + } + + scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) { + var done = setIsAsync(); + if ($animateCss) { + $animateCss(element, { + removeClass: attrs.modalInClass + }).start().then(done); + } else { + $animate.removeClass(element, attrs.modalInClass).then(done); + } + }); + } + } + }]) + + .directive('uibModalWindow', [ + '$uibModalStack', '$q', '$animate', '$injector', + function($modalStack , $q , $animate, $injector) { + var $animateCss = null; + + if ($injector.has('$animateCss')) { + $animateCss = $injector.get('$animateCss'); + } + + return { + scope: { + index: '@' + }, + replace: true, + transclude: true, + templateUrl: function(tElement, tAttrs) { + return tAttrs.templateUrl || 'template/modal/window.html'; + }, + link: function(scope, element, attrs) { + element.addClass(attrs.windowClass || ''); + element.addClass(attrs.windowTopClass || ''); + scope.size = attrs.size; + + scope.close = function(evt) { + var modal = $modalStack.getTop(); + if (modal && modal.value.backdrop && modal.value.backdrop !== 'static' && (evt.target === evt.currentTarget)) { + evt.preventDefault(); + evt.stopPropagation(); + $modalStack.dismiss(modal.key, 'backdrop click'); + } + }; + + // moved from template to fix issue #2280 + element.on('click', scope.close); + + // This property is only added to the scope for the purpose of detecting when this directive is rendered. + // We can detect that by using this property in the template associated with this directive and then use + // {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}. + scope.$isRendered = true; + + // Deferred object that will be resolved when this modal is render. + var modalRenderDeferObj = $q.defer(); + // Observe function will be called on next digest cycle after compilation, ensuring that the DOM is ready. + // In order to use this way of finding whether DOM is ready, we need to observe a scope property used in modal's template. + attrs.$observe('modalRender', function(value) { + if (value == 'true') { + modalRenderDeferObj.resolve(); + } + }); + + modalRenderDeferObj.promise.then(function() { + var animationPromise = null; + + if (attrs.modalInClass) { + if ($animateCss) { + animationPromise = $animateCss(element, { + addClass: attrs.modalInClass + }).start(); + } else { + animationPromise = $animate.addClass(element, attrs.modalInClass); + } + + scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) { + var done = setIsAsync(); + if ($animateCss) { + $animateCss(element, { + removeClass: attrs.modalInClass + }).start().then(done); + } else { + $animate.removeClass(element, attrs.modalInClass).then(done); + } + }); + } + + + $q.when(animationPromise).then(function() { + var inputWithAutofocus = element[0].querySelector('[autofocus]'); + /** + * Auto-focusing of a freshly-opened modal element causes any child elements + * with the autofocus attribute to lose focus. This is an issue on touch + * based devices which will show and then hide the onscreen keyboard. + * Attempts to refocus the autofocus element via JavaScript will not reopen + * the onscreen keyboard. Fixed by updated the focusing logic to only autofocus + * the modal element if the modal does not contain an autofocus element. + */ + if (inputWithAutofocus) { + inputWithAutofocus.focus(); + } else { + element[0].focus(); + } + }); + + // Notify {@link $modalStack} that modal is rendered. + var modal = $modalStack.getTop(); + if (modal) { + $modalStack.modalRendered(modal.key); + } + }); + } + }; + }]) + + .directive('uibModalAnimationClass', function() { + return { + compile: function(tElement, tAttrs) { + if (tAttrs.modalAnimation) { + tElement.addClass(tAttrs.uibModalAnimationClass); + } + } + }; + }) + + .directive('uibModalTransclude', function() { + return { + link: function($scope, $element, $attrs, controller, $transclude) { + $transclude($scope.$parent, function(clone) { + $element.empty(); + $element.append(clone); + }); + } + }; + }) + + .factory('$uibModalStack', [ + '$animate', '$timeout', '$document', '$compile', '$rootScope', + '$q', + '$injector', + '$$multiMap', + '$$stackedMap', + function($animate , $timeout , $document , $compile , $rootScope , + $q, + $injector, + $$multiMap, + $$stackedMap) { + var $animateCss = null; + + if ($injector.has('$animateCss')) { + $animateCss = $injector.get('$animateCss'); + } + + var OPENED_MODAL_CLASS = 'modal-open'; + + var backdropDomEl, backdropScope; + var openedWindows = $$stackedMap.createNew(); + var openedClasses = $$multiMap.createNew(); + var $modalStack = { + NOW_CLOSING_EVENT: 'modal.stack.now-closing' + }; + + //Modal focus behavior + var focusableElementList; + var focusIndex = 0; + var tababbleSelector = 'a[href], area[href], input:not([disabled]), ' + + 'button:not([disabled]),select:not([disabled]), textarea:not([disabled]), ' + + 'iframe, object, embed, *[tabindex], *[contenteditable=true]'; + + function backdropIndex() { + var topBackdropIndex = -1; + var opened = openedWindows.keys(); + for (var i = 0; i < opened.length; i++) { + if (openedWindows.get(opened[i]).value.backdrop) { + topBackdropIndex = i; + } + } + return topBackdropIndex; + } + + $rootScope.$watch(backdropIndex, function(newBackdropIndex) { + if (backdropScope) { + backdropScope.index = newBackdropIndex; + } + }); + + function removeModalWindow(modalInstance, elementToReceiveFocus) { + var body = $document.find('body').eq(0); + var modalWindow = openedWindows.get(modalInstance).value; + + //clean up the stack + openedWindows.remove(modalInstance); + + removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, function() { + var modalBodyClass = modalWindow.openedClass || OPENED_MODAL_CLASS; + openedClasses.remove(modalBodyClass, modalInstance); + body.toggleClass(modalBodyClass, openedClasses.hasKey(modalBodyClass)); + toggleTopWindowClass(true); + }); + checkRemoveBackdrop(); + + //move focus to specified element if available, or else to body + if (elementToReceiveFocus && elementToReceiveFocus.focus) { + elementToReceiveFocus.focus(); + } else { + body.focus(); + } + } + + // Add or remove "windowTopClass" from the top window in the stack + function toggleTopWindowClass(toggleSwitch) { + var modalWindow; + + if (openedWindows.length() > 0) { + modalWindow = openedWindows.top().value; + modalWindow.modalDomEl.toggleClass(modalWindow.windowTopClass || '', toggleSwitch); + } + } + + function checkRemoveBackdrop() { + //remove backdrop if no longer needed + if (backdropDomEl && backdropIndex() == -1) { + var backdropScopeRef = backdropScope; + removeAfterAnimate(backdropDomEl, backdropScope, function() { + backdropScopeRef = null; + }); + backdropDomEl = undefined; + backdropScope = undefined; + } + } + + function removeAfterAnimate(domEl, scope, done) { + var asyncDeferred; + var asyncPromise = null; + var setIsAsync = function() { + if (!asyncDeferred) { + asyncDeferred = $q.defer(); + asyncPromise = asyncDeferred.promise; + } + + return function asyncDone() { + asyncDeferred.resolve(); + }; + }; + scope.$broadcast($modalStack.NOW_CLOSING_EVENT, setIsAsync); + + // Note that it's intentional that asyncPromise might be null. + // That's when setIsAsync has not been called during the + // NOW_CLOSING_EVENT broadcast. + return $q.when(asyncPromise).then(afterAnimating); + + function afterAnimating() { + if (afterAnimating.done) { + return; + } + afterAnimating.done = true; + + if ($animateCss) { + $animateCss(domEl, { + event: 'leave' + }).start().then(function() { + domEl.remove(); + }); + } else { + $animate.leave(domEl); + } + scope.$destroy(); + if (done) { + done(); + } + } + } + + $document.bind('keydown', function(evt) { + if (evt.isDefaultPrevented()) { + return evt; + } + + var modal = openedWindows.top(); + if (modal && modal.value.keyboard) { + switch (evt.which) { + case 27: { + evt.preventDefault(); + $rootScope.$apply(function() { + $modalStack.dismiss(modal.key, 'escape key press'); + }); + break; + } + case 9: { + $modalStack.loadFocusElementList(modal); + var focusChanged = false; + if (evt.shiftKey) { + if ($modalStack.isFocusInFirstItem(evt)) { + focusChanged = $modalStack.focusLastFocusableElement(); + } + } else { + if ($modalStack.isFocusInLastItem(evt)) { + focusChanged = $modalStack.focusFirstFocusableElement(); + } + } + + if (focusChanged) { + evt.preventDefault(); + evt.stopPropagation(); + } + break; + } + } + } + }); + + $modalStack.open = function(modalInstance, modal) { + var modalOpener = $document[0].activeElement, + modalBodyClass = modal.openedClass || OPENED_MODAL_CLASS; + + toggleTopWindowClass(false); + + openedWindows.add(modalInstance, { + deferred: modal.deferred, + renderDeferred: modal.renderDeferred, + modalScope: modal.scope, + backdrop: modal.backdrop, + keyboard: modal.keyboard, + openedClass: modal.openedClass, + windowTopClass: modal.windowTopClass + }); + + openedClasses.put(modalBodyClass, modalInstance); + + var body = $document.find('body').eq(0), + currBackdropIndex = backdropIndex(); + + if (currBackdropIndex >= 0 && !backdropDomEl) { + backdropScope = $rootScope.$new(true); + backdropScope.index = currBackdropIndex; + var angularBackgroundDomEl = angular.element('
      '); + angularBackgroundDomEl.attr('backdrop-class', modal.backdropClass); + if (modal.animation) { + angularBackgroundDomEl.attr('modal-animation', 'true'); + } + backdropDomEl = $compile(angularBackgroundDomEl)(backdropScope); + body.append(backdropDomEl); + } + + var angularDomEl = angular.element('
      '); + angularDomEl.attr({ + 'template-url': modal.windowTemplateUrl, + 'window-class': modal.windowClass, + 'window-top-class': modal.windowTopClass, + 'size': modal.size, + 'index': openedWindows.length() - 1, + 'animate': 'animate' + }).html(modal.content); + if (modal.animation) { + angularDomEl.attr('modal-animation', 'true'); + } + + var modalDomEl = $compile(angularDomEl)(modal.scope); + openedWindows.top().value.modalDomEl = modalDomEl; + openedWindows.top().value.modalOpener = modalOpener; + body.append(modalDomEl); + body.addClass(modalBodyClass); + + $modalStack.clearFocusListCache(); + }; + + function broadcastClosing(modalWindow, resultOrReason, closing) { + return !modalWindow.value.modalScope.$broadcast('modal.closing', resultOrReason, closing).defaultPrevented; + } + + $modalStack.close = function(modalInstance, result) { + var modalWindow = openedWindows.get(modalInstance); + if (modalWindow && broadcastClosing(modalWindow, result, true)) { + modalWindow.value.modalScope.$$uibDestructionScheduled = true; + modalWindow.value.deferred.resolve(result); + removeModalWindow(modalInstance, modalWindow.value.modalOpener); + return true; + } + return !modalWindow; + }; + + $modalStack.dismiss = function(modalInstance, reason) { + var modalWindow = openedWindows.get(modalInstance); + if (modalWindow && broadcastClosing(modalWindow, reason, false)) { + modalWindow.value.modalScope.$$uibDestructionScheduled = true; + modalWindow.value.deferred.reject(reason); + removeModalWindow(modalInstance, modalWindow.value.modalOpener); + return true; + } + return !modalWindow; + }; + + $modalStack.dismissAll = function(reason) { + var topModal = this.getTop(); + while (topModal && this.dismiss(topModal.key, reason)) { + topModal = this.getTop(); + } + }; + + $modalStack.getTop = function() { + return openedWindows.top(); + }; + + $modalStack.modalRendered = function(modalInstance) { + var modalWindow = openedWindows.get(modalInstance); + if (modalWindow) { + modalWindow.value.renderDeferred.resolve(); + } + }; + + $modalStack.focusFirstFocusableElement = function() { + if (focusableElementList.length > 0) { + focusableElementList[0].focus(); + return true; + } + return false; + }; + $modalStack.focusLastFocusableElement = function() { + if (focusableElementList.length > 0) { + focusableElementList[focusableElementList.length - 1].focus(); + return true; + } + return false; + }; + + $modalStack.isFocusInFirstItem = function(evt) { + if (focusableElementList.length > 0) { + return (evt.target || evt.srcElement) == focusableElementList[0]; + } + return false; + }; + + $modalStack.isFocusInLastItem = function(evt) { + if (focusableElementList.length > 0) { + return (evt.target || evt.srcElement) == focusableElementList[focusableElementList.length - 1]; + } + return false; + }; + + $modalStack.clearFocusListCache = function() { + focusableElementList = []; + focusIndex = 0; + }; + + $modalStack.loadFocusElementList = function(modalWindow) { + if (focusableElementList === undefined || !focusableElementList.length) { + if (modalWindow) { + var modalDomE1 = modalWindow.value.modalDomEl; + if (modalDomE1 && modalDomE1.length) { + focusableElementList = modalDomE1[0].querySelectorAll(tababbleSelector); + } + } + } + }; + + return $modalStack; + }]) + + .provider('$uibModal', function() { + var $modalProvider = { + options: { + animation: true, + backdrop: true, //can also be false or 'static' + keyboard: true + }, + $get: ['$injector', '$rootScope', '$q', '$templateRequest', '$controller', '$uibModalStack', '$modalSuppressWarning', '$log', + function ($injector, $rootScope, $q, $templateRequest, $controller, $modalStack, $modalSuppressWarning, $log) { + var $modal = {}; + + function getTemplatePromise(options) { + return options.template ? $q.when(options.template) : + $templateRequest(angular.isFunction(options.templateUrl) ? (options.templateUrl)() : options.templateUrl); + } + + function getResolvePromises(resolves) { + var promisesArr = []; + angular.forEach(resolves, function(value) { + if (angular.isFunction(value) || angular.isArray(value)) { + promisesArr.push($q.when($injector.invoke(value))); + } else if (angular.isString(value)) { + promisesArr.push($q.when($injector.get(value))); + } else { + promisesArr.push($q.when(value)); + } + }); + return promisesArr; + } + + var promiseChain = null; + $modal.getPromiseChain = function() { + return promiseChain; + }; + + $modal.open = function(modalOptions) { + var modalResultDeferred = $q.defer(); + var modalOpenedDeferred = $q.defer(); + var modalRenderDeferred = $q.defer(); + + //prepare an instance of a modal to be injected into controllers and returned to a caller + var modalInstance = { + result: modalResultDeferred.promise, + opened: modalOpenedDeferred.promise, + rendered: modalRenderDeferred.promise, + close: function (result) { + return $modalStack.close(modalInstance, result); + }, + dismiss: function (reason) { + return $modalStack.dismiss(modalInstance, reason); + } + }; + + //merge and clean up options + modalOptions = angular.extend({}, $modalProvider.options, modalOptions); + modalOptions.resolve = modalOptions.resolve || {}; + + //verify options + if (!modalOptions.template && !modalOptions.templateUrl) { + throw new Error('One of template or templateUrl options is required.'); + } + + var templateAndResolvePromise = + $q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve))); + + function resolveWithTemplate() { + return templateAndResolvePromise; + } + + // Wait for the resolution of the existing promise chain. + // Then switch to our own combined promise dependency (regardless of how the previous modal fared). + // Then add to $modalStack and resolve opened. + // Finally clean up the chain variable if no subsequent modal has overwritten it. + var samePromise; + samePromise = promiseChain = $q.all([promiseChain]) + .then(resolveWithTemplate, resolveWithTemplate) + .then(function resolveSuccess(tplAndVars) { + + var modalScope = (modalOptions.scope || $rootScope).$new(); + modalScope.$close = modalInstance.close; + modalScope.$dismiss = modalInstance.dismiss; + + modalScope.$on('$destroy', function() { + if (!modalScope.$$uibDestructionScheduled) { + modalScope.$dismiss('$uibUnscheduledDestruction'); + } + }); + + var ctrlInstance, ctrlLocals = {}; + var resolveIter = 1; + + //controllers + if (modalOptions.controller) { + ctrlLocals.$scope = modalScope; + ctrlLocals.$uibModalInstance = modalInstance; + Object.defineProperty(ctrlLocals, '$modalInstance', { + get: function() { + if (!$modalSuppressWarning) { + $log.warn('$modalInstance is now deprecated. Use $uibModalInstance instead.'); + } + + return modalInstance; + } + }); + angular.forEach(modalOptions.resolve, function(value, key) { + ctrlLocals[key] = tplAndVars[resolveIter++]; + }); + + ctrlInstance = $controller(modalOptions.controller, ctrlLocals); + if (modalOptions.controllerAs) { + if (modalOptions.bindToController) { + angular.extend(ctrlInstance, modalScope); + } + + modalScope[modalOptions.controllerAs] = ctrlInstance; + } + } + + $modalStack.open(modalInstance, { + scope: modalScope, + deferred: modalResultDeferred, + renderDeferred: modalRenderDeferred, + content: tplAndVars[0], + animation: modalOptions.animation, + backdrop: modalOptions.backdrop, + keyboard: modalOptions.keyboard, + backdropClass: modalOptions.backdropClass, + windowTopClass: modalOptions.windowTopClass, + windowClass: modalOptions.windowClass, + windowTemplateUrl: modalOptions.windowTemplateUrl, + size: modalOptions.size, + openedClass: modalOptions.openedClass + }); + modalOpenedDeferred.resolve(true); + + }, function resolveError(reason) { + modalOpenedDeferred.reject(reason); + modalResultDeferred.reject(reason); + }) + .finally(function() { + if (promiseChain === samePromise) { + promiseChain = null; + } + }); + + return modalInstance; + }; + + return $modal; + } + ] + }; + + return $modalProvider; + }); + +/* deprecated modal below */ + +angular.module('ui.bootstrap.modal') + + .value('$modalSuppressWarning', false) + + /** + * A helper directive for the $modal service. It creates a backdrop element. + */ + .directive('modalBackdrop', [ + '$animate', '$injector', '$modalStack', '$log', '$modalSuppressWarning', + function($animate , $injector, $modalStack, $log, $modalSuppressWarning) { + var $animateCss = null; + + if ($injector.has('$animateCss')) { + $animateCss = $injector.get('$animateCss'); + } + + return { + replace: true, + templateUrl: 'template/modal/backdrop.html', + compile: function(tElement, tAttrs) { + tElement.addClass(tAttrs.backdropClass); + return linkFn; + } + }; + + function linkFn(scope, element, attrs) { + if (!$modalSuppressWarning) { + $log.warn('modal-backdrop is now deprecated. Use uib-modal-backdrop instead.'); + } + element.addClass('modal-backdrop'); + + if (attrs.modalInClass) { + if ($animateCss) { + $animateCss(element, { + addClass: attrs.modalInClass + }).start(); + } else { + $animate.addClass(element, attrs.modalInClass); + } + + scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) { + var done = setIsAsync(); + if ($animateCss) { + $animateCss(element, { + removeClass: attrs.modalInClass + }).start().then(done); + } else { + $animate.removeClass(element, attrs.modalInClass).then(done); + } + }); + } + } + }]) + + .directive('modalWindow', [ + '$modalStack', '$q', '$animate', '$injector', '$log', '$modalSuppressWarning', + function($modalStack , $q , $animate, $injector, $log, $modalSuppressWarning) { + var $animateCss = null; + + if ($injector.has('$animateCss')) { + $animateCss = $injector.get('$animateCss'); + } + + return { + scope: { + index: '@' + }, + replace: true, + transclude: true, + templateUrl: function(tElement, tAttrs) { + return tAttrs.templateUrl || 'template/modal/window.html'; + }, + link: function(scope, element, attrs) { + if (!$modalSuppressWarning) { + $log.warn('modal-window is now deprecated. Use uib-modal-window instead.'); + } + element.addClass(attrs.windowClass || ''); + element.addClass(attrs.windowTopClass || ''); + scope.size = attrs.size; + + scope.close = function(evt) { + var modal = $modalStack.getTop(); + if (modal && modal.value.backdrop && modal.value.backdrop !== 'static' && (evt.target === evt.currentTarget)) { + evt.preventDefault(); + evt.stopPropagation(); + $modalStack.dismiss(modal.key, 'backdrop click'); + } + }; + + // moved from template to fix issue #2280 + element.on('click', scope.close); + + // This property is only added to the scope for the purpose of detecting when this directive is rendered. + // We can detect that by using this property in the template associated with this directive and then use + // {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}. + scope.$isRendered = true; + + // Deferred object that will be resolved when this modal is render. + var modalRenderDeferObj = $q.defer(); + // Observe function will be called on next digest cycle after compilation, ensuring that the DOM is ready. + // In order to use this way of finding whether DOM is ready, we need to observe a scope property used in modal's template. + attrs.$observe('modalRender', function(value) { + if (value == 'true') { + modalRenderDeferObj.resolve(); + } + }); + + modalRenderDeferObj.promise.then(function() { + var animationPromise = null; + + if (attrs.modalInClass) { + if ($animateCss) { + animationPromise = $animateCss(element, { + addClass: attrs.modalInClass + }).start(); + } else { + animationPromise = $animate.addClass(element, attrs.modalInClass); + } + + scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) { + var done = setIsAsync(); + if ($animateCss) { + $animateCss(element, { + removeClass: attrs.modalInClass + }).start().then(done); + } else { + $animate.removeClass(element, attrs.modalInClass).then(done); + } + }); + } + + + $q.when(animationPromise).then(function() { + var inputWithAutofocus = element[0].querySelector('[autofocus]'); + /** + * Auto-focusing of a freshly-opened modal element causes any child elements + * with the autofocus attribute to lose focus. This is an issue on touch + * based devices which will show and then hide the onscreen keyboard. + * Attempts to refocus the autofocus element via JavaScript will not reopen + * the onscreen keyboard. Fixed by updated the focusing logic to only autofocus + * the modal element if the modal does not contain an autofocus element. + */ + if (inputWithAutofocus) { + inputWithAutofocus.focus(); + } else { + element[0].focus(); + } + }); + + // Notify {@link $modalStack} that modal is rendered. + var modal = $modalStack.getTop(); + if (modal) { + $modalStack.modalRendered(modal.key); + } + }); + } + }; + }]) + + .directive('modalAnimationClass', [ + '$log', '$modalSuppressWarning', + function ($log, $modalSuppressWarning) { + return { + compile: function(tElement, tAttrs) { + if (!$modalSuppressWarning) { + $log.warn('modal-animation-class is now deprecated. Use uib-modal-animation-class instead.'); + } + if (tAttrs.modalAnimation) { + tElement.addClass(tAttrs.modalAnimationClass); + } + } + }; + }]) + + .directive('modalTransclude', [ + '$log', '$modalSuppressWarning', + function ($log, $modalSuppressWarning) { + return { + link: function($scope, $element, $attrs, controller, $transclude) { + if (!$modalSuppressWarning) { + $log.warn('modal-transclude is now deprecated. Use uib-modal-transclude instead.'); + } + $transclude($scope.$parent, function(clone) { + $element.empty(); + $element.append(clone); + }); + } + }; + }]) + + .service('$modalStack', [ + '$animate', '$timeout', '$document', '$compile', '$rootScope', + '$q', + '$injector', + '$$multiMap', + '$$stackedMap', + '$uibModalStack', + '$log', + '$modalSuppressWarning', + function($animate , $timeout , $document , $compile , $rootScope , + $q, + $injector, + $$multiMap, + $$stackedMap, + $uibModalStack, + $log, + $modalSuppressWarning) { + if (!$modalSuppressWarning) { + $log.warn('$modalStack is now deprecated. Use $uibModalStack instead.'); + } + + angular.extend(this, $uibModalStack); + }]) + + .provider('$modal', ['$uibModalProvider', function($uibModalProvider) { + angular.extend(this, $uibModalProvider); + + this.$get = ['$injector', '$log', '$modalSuppressWarning', + function ($injector, $log, $modalSuppressWarning) { + if (!$modalSuppressWarning) { + $log.warn('$modal is now deprecated. Use $uibModal instead.'); + } + + return $injector.invoke($uibModalProvider.$get); + }]; + }]); + +angular.module('ui.bootstrap.pagination', []) +.controller('UibPaginationController', ['$scope', '$attrs', '$parse', function($scope, $attrs, $parse) { + var self = this, + ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl + setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop; + + this.init = function(ngModelCtrl_, config) { + ngModelCtrl = ngModelCtrl_; + this.config = config; + + ngModelCtrl.$render = function() { + self.render(); + }; + + if ($attrs.itemsPerPage) { + $scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) { + self.itemsPerPage = parseInt(value, 10); + $scope.totalPages = self.calculateTotalPages(); + }); + } else { + this.itemsPerPage = config.itemsPerPage; + } + + $scope.$watch('totalItems', function() { + $scope.totalPages = self.calculateTotalPages(); + }); + + $scope.$watch('totalPages', function(value) { + setNumPages($scope.$parent, value); // Readonly variable + + if ( $scope.page > value ) { + $scope.selectPage(value); + } else { + ngModelCtrl.$render(); + } + }); + }; + + this.calculateTotalPages = function() { + var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage); + return Math.max(totalPages || 0, 1); + }; + + this.render = function() { + $scope.page = parseInt(ngModelCtrl.$viewValue, 10) || 1; + }; + + $scope.selectPage = function(page, evt) { + if (evt) { + evt.preventDefault(); + } + + var clickAllowed = !$scope.ngDisabled || !evt; + if (clickAllowed && $scope.page !== page && page > 0 && page <= $scope.totalPages) { + if (evt && evt.target) { + evt.target.blur(); + } + ngModelCtrl.$setViewValue(page); + ngModelCtrl.$render(); + } + }; + + $scope.getText = function(key) { + return $scope[key + 'Text'] || self.config[key + 'Text']; + }; + + $scope.noPrevious = function() { + return $scope.page === 1; + }; + + $scope.noNext = function() { + return $scope.page === $scope.totalPages; + }; +}]) + +.constant('uibPaginationConfig', { + itemsPerPage: 10, + boundaryLinks: false, + directionLinks: true, + firstText: 'First', + previousText: 'Previous', + nextText: 'Next', + lastText: 'Last', + rotate: true +}) + +.directive('uibPagination', ['$parse', 'uibPaginationConfig', function($parse, paginationConfig) { + return { + restrict: 'EA', + scope: { + totalItems: '=', + firstText: '@', + previousText: '@', + nextText: '@', + lastText: '@', + ngDisabled:'=' + }, + require: ['uibPagination', '?ngModel'], + controller: 'UibPaginationController', + controllerAs: 'pagination', + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/pagination/pagination.html'; + }, + replace: true, + link: function(scope, element, attrs, ctrls) { + var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + if (!ngModelCtrl) { + return; // do nothing if no ng-model + } + + // Setup configuration parameters + var maxSize = angular.isDefined(attrs.maxSize) ? scope.$parent.$eval(attrs.maxSize) : paginationConfig.maxSize, + rotate = angular.isDefined(attrs.rotate) ? scope.$parent.$eval(attrs.rotate) : paginationConfig.rotate; + scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : paginationConfig.boundaryLinks; + scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : paginationConfig.directionLinks; + + paginationCtrl.init(ngModelCtrl, paginationConfig); + + if (attrs.maxSize) { + scope.$parent.$watch($parse(attrs.maxSize), function(value) { + maxSize = parseInt(value, 10); + paginationCtrl.render(); + }); + } + + // Create page object used in template + function makePage(number, text, isActive) { + return { + number: number, + text: text, + active: isActive + }; + } + + function getPages(currentPage, totalPages) { + var pages = []; + + // Default page limits + var startPage = 1, endPage = totalPages; + var isMaxSized = angular.isDefined(maxSize) && maxSize < totalPages; + + // recompute if maxSize + if (isMaxSized) { + if (rotate) { + // Current page is displayed in the middle of the visible ones + startPage = Math.max(currentPage - Math.floor(maxSize/2), 1); + endPage = startPage + maxSize - 1; + + // Adjust if limit is exceeded + if (endPage > totalPages) { + endPage = totalPages; + startPage = endPage - maxSize + 1; + } + } else { + // Visible pages are paginated with maxSize + startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1; + + // Adjust last page if limit is exceeded + endPage = Math.min(startPage + maxSize - 1, totalPages); + } + } + + // Add page number links + for (var number = startPage; number <= endPage; number++) { + var page = makePage(number, number, number === currentPage); + pages.push(page); + } + + // Add links to move between page sets + if (isMaxSized && ! rotate) { + if (startPage > 1) { + var previousPageSet = makePage(startPage - 1, '...', false); + pages.unshift(previousPageSet); + } + + if (endPage < totalPages) { + var nextPageSet = makePage(endPage + 1, '...', false); + pages.push(nextPageSet); + } + } + + return pages; + } + + var originalRender = paginationCtrl.render; + paginationCtrl.render = function() { + originalRender(); + if (scope.page > 0 && scope.page <= scope.totalPages) { + scope.pages = getPages(scope.page, scope.totalPages); + } + }; + } + }; +}]) + +.constant('uibPagerConfig', { + itemsPerPage: 10, + previousText: '« Previous', + nextText: 'Next »', + align: true +}) + +.directive('uibPager', ['uibPagerConfig', function(pagerConfig) { + return { + restrict: 'EA', + scope: { + totalItems: '=', + previousText: '@', + nextText: '@', + ngDisabled: '=' + }, + require: ['uibPager', '?ngModel'], + controller: 'UibPaginationController', + controllerAs: 'pagination', + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/pagination/pager.html'; + }, + replace: true, + link: function(scope, element, attrs, ctrls) { + var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + if (!ngModelCtrl) { + return; // do nothing if no ng-model + } + + scope.align = angular.isDefined(attrs.align) ? scope.$parent.$eval(attrs.align) : pagerConfig.align; + paginationCtrl.init(ngModelCtrl, pagerConfig); + } + }; +}]); + +/* Deprecated Pagination Below */ + +angular.module('ui.bootstrap.pagination') +.value('$paginationSuppressWarning', false) +.controller('PaginationController', ['$scope', '$attrs', '$parse', '$log', '$paginationSuppressWarning', function($scope, $attrs, $parse, $log, $paginationSuppressWarning) { + if (!$paginationSuppressWarning) { + $log.warn('PaginationController is now deprecated. Use UibPaginationController instead.'); + } + + var self = this, + ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl + setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop; + + this.init = function(ngModelCtrl_, config) { + ngModelCtrl = ngModelCtrl_; + this.config = config; + + ngModelCtrl.$render = function() { + self.render(); + }; + + if ($attrs.itemsPerPage) { + $scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) { + self.itemsPerPage = parseInt(value, 10); + $scope.totalPages = self.calculateTotalPages(); + }); + } else { + this.itemsPerPage = config.itemsPerPage; + } + + $scope.$watch('totalItems', function() { + $scope.totalPages = self.calculateTotalPages(); + }); + + $scope.$watch('totalPages', function(value) { + setNumPages($scope.$parent, value); // Readonly variable + + if ( $scope.page > value ) { + $scope.selectPage(value); + } else { + ngModelCtrl.$render(); + } + }); + }; + + this.calculateTotalPages = function() { + var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage); + return Math.max(totalPages || 0, 1); + }; + + this.render = function() { + $scope.page = parseInt(ngModelCtrl.$viewValue, 10) || 1; + }; + + $scope.selectPage = function(page, evt) { + if (evt) { + evt.preventDefault(); + } + + var clickAllowed = !$scope.ngDisabled || !evt; + if (clickAllowed && $scope.page !== page && page > 0 && page <= $scope.totalPages) { + if (evt && evt.target) { + evt.target.blur(); + } + ngModelCtrl.$setViewValue(page); + ngModelCtrl.$render(); + } + }; + + $scope.getText = function(key) { + return $scope[key + 'Text'] || self.config[key + 'Text']; + }; + + $scope.noPrevious = function() { + return $scope.page === 1; + }; + + $scope.noNext = function() { + return $scope.page === $scope.totalPages; + }; +}]) +.directive('pagination', ['$parse', 'uibPaginationConfig', '$log', '$paginationSuppressWarning', function($parse, paginationConfig, $log, $paginationSuppressWarning) { + return { + restrict: 'EA', + scope: { + totalItems: '=', + firstText: '@', + previousText: '@', + nextText: '@', + lastText: '@', + ngDisabled:'=' + }, + require: ['pagination', '?ngModel'], + controller: 'PaginationController', + controllerAs: 'pagination', + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/pagination/pagination.html'; + }, + replace: true, + link: function(scope, element, attrs, ctrls) { + if (!$paginationSuppressWarning) { + $log.warn('pagination is now deprecated. Use uib-pagination instead.'); + } + var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + if (!ngModelCtrl) { + return; // do nothing if no ng-model + } + + // Setup configuration parameters + var maxSize = angular.isDefined(attrs.maxSize) ? scope.$parent.$eval(attrs.maxSize) : paginationConfig.maxSize, + rotate = angular.isDefined(attrs.rotate) ? scope.$parent.$eval(attrs.rotate) : paginationConfig.rotate; + scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : paginationConfig.boundaryLinks; + scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : paginationConfig.directionLinks; + + paginationCtrl.init(ngModelCtrl, paginationConfig); + + if (attrs.maxSize) { + scope.$parent.$watch($parse(attrs.maxSize), function(value) { + maxSize = parseInt(value, 10); + paginationCtrl.render(); + }); + } + + // Create page object used in template + function makePage(number, text, isActive) { + return { + number: number, + text: text, + active: isActive + }; + } + + function getPages(currentPage, totalPages) { + var pages = []; + + // Default page limits + var startPage = 1, endPage = totalPages; + var isMaxSized = angular.isDefined(maxSize) && maxSize < totalPages; + + // recompute if maxSize + if (isMaxSized) { + if (rotate) { + // Current page is displayed in the middle of the visible ones + startPage = Math.max(currentPage - Math.floor(maxSize/2), 1); + endPage = startPage + maxSize - 1; + + // Adjust if limit is exceeded + if (endPage > totalPages) { + endPage = totalPages; + startPage = endPage - maxSize + 1; + } + } else { + // Visible pages are paginated with maxSize + startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1; + + // Adjust last page if limit is exceeded + endPage = Math.min(startPage + maxSize - 1, totalPages); + } + } + + // Add page number links + for (var number = startPage; number <= endPage; number++) { + var page = makePage(number, number, number === currentPage); + pages.push(page); + } + + // Add links to move between page sets + if (isMaxSized && ! rotate) { + if (startPage > 1) { + var previousPageSet = makePage(startPage - 1, '...', false); + pages.unshift(previousPageSet); + } + + if (endPage < totalPages) { + var nextPageSet = makePage(endPage + 1, '...', false); + pages.push(nextPageSet); + } + } + + return pages; + } + + var originalRender = paginationCtrl.render; + paginationCtrl.render = function() { + originalRender(); + if (scope.page > 0 && scope.page <= scope.totalPages) { + scope.pages = getPages(scope.page, scope.totalPages); + } + }; + } + }; +}]) + +.directive('pager', ['uibPagerConfig', '$log', '$paginationSuppressWarning', function(pagerConfig, $log, $paginationSuppressWarning) { + return { + restrict: 'EA', + scope: { + totalItems: '=', + previousText: '@', + nextText: '@', + ngDisabled: '=' + }, + require: ['pager', '?ngModel'], + controller: 'PaginationController', + controllerAs: 'pagination', + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/pagination/pager.html'; + }, + replace: true, + link: function(scope, element, attrs, ctrls) { + if (!$paginationSuppressWarning) { + $log.warn('pager is now deprecated. Use uib-pager instead.'); + } + var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + if (!ngModelCtrl) { + return; // do nothing if no ng-model + } + + scope.align = angular.isDefined(attrs.align) ? scope.$parent.$eval(attrs.align) : pagerConfig.align; + paginationCtrl.init(ngModelCtrl, pagerConfig); + } + }; +}]); + +/** + * The following features are still outstanding: animation as a + * function, placement as a function, inside, support for more triggers than + * just mouse enter/leave, html tooltips, and selector delegation. + */ +angular.module('ui.bootstrap.tooltip', ['ui.bootstrap.position', 'ui.bootstrap.stackedMap']) + +/** + * The $tooltip service creates tooltip- and popover-like directives as well as + * houses global options for them. + */ +.provider('$uibTooltip', function() { + // The default options tooltip and popover. + var defaultOptions = { + placement: 'top', + animation: true, + popupDelay: 0, + popupCloseDelay: 0, + useContentExp: false + }; + + // Default hide triggers for each show trigger + var triggerMap = { + 'mouseenter': 'mouseleave', + 'click': 'click', + 'focus': 'blur', + 'none': '' + }; + + // The options specified to the provider globally. + var globalOptions = {}; + + /** + * `options({})` allows global configuration of all tooltips in the + * application. + * + * var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) { + * // place tooltips left instead of top by default + * $tooltipProvider.options( { placement: 'left' } ); + * }); + */ + this.options = function(value) { + angular.extend(globalOptions, value); + }; + + /** + * This allows you to extend the set of trigger mappings available. E.g.: + * + * $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' ); + */ + this.setTriggers = function setTriggers(triggers) { + angular.extend(triggerMap, triggers); + }; + + /** + * This is a helper function for translating camel-case to snake-case. + */ + function snake_case(name) { + var regexp = /[A-Z]/g; + var separator = '-'; + return name.replace(regexp, function(letter, pos) { + return (pos ? separator : '') + letter.toLowerCase(); + }); + } + + /** + * Returns the actual instance of the $tooltip service. + * TODO support multiple triggers + */ + this.$get = ['$window', '$compile', '$timeout', '$document', '$uibPosition', '$interpolate', '$rootScope', '$parse', '$$stackedMap', function($window, $compile, $timeout, $document, $position, $interpolate, $rootScope, $parse, $$stackedMap) { + var openedTooltips = $$stackedMap.createNew(); + $document.on('keypress', function(e) { + if (e.which === 27) { + var last = openedTooltips.top(); + if (last) { + last.value.close(); + openedTooltips.removeTop(); + last = null; + } + } + }); + + return function $tooltip(ttType, prefix, defaultTriggerShow, options) { + options = angular.extend({}, defaultOptions, globalOptions, options); + + /** + * Returns an object of show and hide triggers. + * + * If a trigger is supplied, + * it is used to show the tooltip; otherwise, it will use the `trigger` + * option passed to the `$tooltipProvider.options` method; else it will + * default to the trigger supplied to this directive factory. + * + * The hide trigger is based on the show trigger. If the `trigger` option + * was passed to the `$tooltipProvider.options` method, it will use the + * mapped trigger from `triggerMap` or the passed trigger if the map is + * undefined; otherwise, it uses the `triggerMap` value of the show + * trigger; else it will just use the show trigger. + */ + function getTriggers(trigger) { + var show = (trigger || options.trigger || defaultTriggerShow).split(' '); + var hide = show.map(function(trigger) { + return triggerMap[trigger] || trigger; + }); + return { + show: show, + hide: hide + }; + } + + var directiveName = snake_case(ttType); + + var startSym = $interpolate.startSymbol(); + var endSym = $interpolate.endSymbol(); + var template = + '
      ' + + '
      '; + + return { + compile: function(tElem, tAttrs) { + var tooltipLinker = $compile(template); + + return function link(scope, element, attrs, tooltipCtrl) { + var tooltip; + var tooltipLinkedScope; + var transitionTimeout; + var showTimeout; + var hideTimeout; + var positionTimeout; + var appendToBody = angular.isDefined(options.appendToBody) ? options.appendToBody : false; + var triggers = getTriggers(undefined); + var hasEnableExp = angular.isDefined(attrs[prefix + 'Enable']); + var ttScope = scope.$new(true); + var repositionScheduled = false; + var isOpenParse = angular.isDefined(attrs[prefix + 'IsOpen']) ? $parse(attrs[prefix + 'IsOpen']) : false; + var contentParse = options.useContentExp ? $parse(attrs[ttType]) : false; + var observers = []; + + var positionTooltip = function() { + // check if tooltip exists and is not empty + if (!tooltip || !tooltip.html()) { return; } + + if (!positionTimeout) { + positionTimeout = $timeout(function() { + // Reset the positioning. + tooltip.css({ top: 0, left: 0 }); + + // Now set the calculated positioning. + var ttCss = $position.positionElements(element, tooltip, ttScope.placement, appendToBody); + ttCss.top += 'px'; + ttCss.left += 'px'; + ttCss.visibility = 'visible'; + tooltip.css(ttCss); + + positionTimeout = null; + }, 0, false); + } + }; + + // Set up the correct scope to allow transclusion later + ttScope.origScope = scope; + + // By default, the tooltip is not open. + // TODO add ability to start tooltip opened + ttScope.isOpen = false; + openedTooltips.add(ttScope, { + close: hide + }); + + function toggleTooltipBind() { + if (!ttScope.isOpen) { + showTooltipBind(); + } else { + hideTooltipBind(); + } + } + + // Show the tooltip with delay if specified, otherwise show it immediately + function showTooltipBind() { + if (hasEnableExp && !scope.$eval(attrs[prefix + 'Enable'])) { + return; + } + + cancelHide(); + prepareTooltip(); + + if (ttScope.popupDelay) { + // Do nothing if the tooltip was already scheduled to pop-up. + // This happens if show is triggered multiple times before any hide is triggered. + if (!showTimeout) { + showTimeout = $timeout(show, ttScope.popupDelay, false); + } + } else { + show(); + } + } + + function hideTooltipBind() { + cancelShow(); + + if (ttScope.popupCloseDelay) { + if (!hideTimeout) { + hideTimeout = $timeout(hide, ttScope.popupCloseDelay, false); + } + } else { + hide(); + } + } + + // Show the tooltip popup element. + function show() { + cancelShow(); + cancelHide(); + + // Don't show empty tooltips. + if (!ttScope.content) { + return angular.noop; + } + + createTooltip(); + + // And show the tooltip. + ttScope.$evalAsync(function() { + ttScope.isOpen = true; + assignIsOpen(true); + positionTooltip(); + }); + } + + function cancelShow() { + if (showTimeout) { + $timeout.cancel(showTimeout); + showTimeout = null; + } + + if (positionTimeout) { + $timeout.cancel(positionTimeout); + positionTimeout = null; + } + } + + // Hide the tooltip popup element. + function hide() { + cancelShow(); + cancelHide(); + + if (!ttScope) { + return; + } + + // First things first: we don't show it anymore. + ttScope.$evalAsync(function() { + ttScope.isOpen = false; + assignIsOpen(false); + // And now we remove it from the DOM. However, if we have animation, we + // need to wait for it to expire beforehand. + // FIXME: this is a placeholder for a port of the transitions library. + // The fade transition in TWBS is 150ms. + if (ttScope.animation) { + if (!transitionTimeout) { + transitionTimeout = $timeout(removeTooltip, 150, false); + } + } else { + removeTooltip(); + } + }); + } + + function cancelHide() { + if (hideTimeout) { + $timeout.cancel(hideTimeout); + hideTimeout = null; + } + if (transitionTimeout) { + $timeout.cancel(transitionTimeout); + transitionTimeout = null; + } + } + + function createTooltip() { + // There can only be one tooltip element per directive shown at once. + if (tooltip) { + return; + } + + tooltipLinkedScope = ttScope.$new(); + tooltip = tooltipLinker(tooltipLinkedScope, function(tooltip) { + if (appendToBody) { + $document.find('body').append(tooltip); + } else { + element.after(tooltip); + } + }); + + prepObservers(); + } + + function removeTooltip() { + unregisterObservers(); + + transitionTimeout = null; + if (tooltip) { + tooltip.remove(); + tooltip = null; + } + if (tooltipLinkedScope) { + tooltipLinkedScope.$destroy(); + tooltipLinkedScope = null; + } + } + + /** + * Set the inital scope values. Once + * the tooltip is created, the observers + * will be added to keep things in synch. + */ + function prepareTooltip() { + ttScope.title = attrs[prefix + 'Title']; + if (contentParse) { + ttScope.content = contentParse(scope); + } else { + ttScope.content = attrs[ttType]; + } + + ttScope.popupClass = attrs[prefix + 'Class']; + ttScope.placement = angular.isDefined(attrs[prefix + 'Placement']) ? attrs[prefix + 'Placement'] : options.placement; + + var delay = parseInt(attrs[prefix + 'PopupDelay'], 10); + var closeDelay = parseInt(attrs[prefix + 'PopupCloseDelay'], 10); + ttScope.popupDelay = !isNaN(delay) ? delay : options.popupDelay; + ttScope.popupCloseDelay = !isNaN(closeDelay) ? closeDelay : options.popupCloseDelay; + } + + function assignIsOpen(isOpen) { + if (isOpenParse && angular.isFunction(isOpenParse.assign)) { + isOpenParse.assign(scope, isOpen); + } + } + + ttScope.contentExp = function() { + return ttScope.content; + }; + + /** + * Observe the relevant attributes. + */ + attrs.$observe('disabled', function(val) { + if (val) { + cancelShow(); + } + + if (val && ttScope.isOpen) { + hide(); + } + }); + + if (isOpenParse) { + scope.$watch(isOpenParse, function(val) { + /*jshint -W018 */ + if (ttScope && !val === ttScope.isOpen) { + toggleTooltipBind(); + } + /*jshint +W018 */ + }); + } + + function prepObservers() { + observers.length = 0; + + if (contentParse) { + observers.push( + scope.$watch(contentParse, function(val) { + ttScope.content = val; + if (!val && ttScope.isOpen) { + hide(); + } + }) + ); + + observers.push( + tooltipLinkedScope.$watch(function() { + if (!repositionScheduled) { + repositionScheduled = true; + tooltipLinkedScope.$$postDigest(function() { + repositionScheduled = false; + if (ttScope && ttScope.isOpen) { + positionTooltip(); + } + }); + } + }) + ); + } else { + observers.push( + attrs.$observe(ttType, function(val) { + ttScope.content = val; + if (!val && ttScope.isOpen) { + hide(); + } else { + positionTooltip(); + } + }) + ); + } + + observers.push( + attrs.$observe(prefix + 'Title', function(val) { + ttScope.title = val; + if (ttScope.isOpen) { + positionTooltip(); + } + }) + ); + + observers.push( + attrs.$observe(prefix + 'Placement', function(val) { + ttScope.placement = val ? val : options.placement; + if (ttScope.isOpen) { + positionTooltip(); + } + }) + ); + } + + function unregisterObservers() { + if (observers.length) { + angular.forEach(observers, function(observer) { + observer(); + }); + observers.length = 0; + } + } + + var unregisterTriggers = function() { + triggers.show.forEach(function(trigger) { + element.unbind(trigger, showTooltipBind); + }); + triggers.hide.forEach(function(trigger) { + trigger.split(' ').forEach(function(hideTrigger) { + element[0].removeEventListener(hideTrigger, hideTooltipBind); + }); + }); + }; + + function prepTriggers() { + var val = attrs[prefix + 'Trigger']; + unregisterTriggers(); + + triggers = getTriggers(val); + + if (triggers.show !== 'none') { + triggers.show.forEach(function(trigger, idx) { + // Using raw addEventListener due to jqLite/jQuery bug - #4060 + if (trigger === triggers.hide[idx]) { + element[0].addEventListener(trigger, toggleTooltipBind); + } else if (trigger) { + element[0].addEventListener(trigger, showTooltipBind); + triggers.hide[idx].split(' ').forEach(function(trigger) { + element[0].addEventListener(trigger, hideTooltipBind); + }); + } + + element.on('keypress', function(e) { + if (e.which === 27) { + hideTooltipBind(); + } + }); + }); + } + } + + prepTriggers(); + + var animation = scope.$eval(attrs[prefix + 'Animation']); + ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation; + + var appendToBodyVal = scope.$eval(attrs[prefix + 'AppendToBody']); + appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody; + + // if a tooltip is attached to we need to remove it on + // location change as its parent scope will probably not be destroyed + // by the change. + if (appendToBody) { + scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess() { + if (ttScope.isOpen) { + hide(); + } + }); + } + + // Make sure tooltip is destroyed and removed. + scope.$on('$destroy', function onDestroyTooltip() { + cancelShow(); + cancelHide(); + unregisterTriggers(); + removeTooltip(); + openedTooltips.remove(ttScope); + ttScope = null; + }); + }; + } + }; + }; + }]; +}) + +// This is mostly ngInclude code but with a custom scope +.directive('uibTooltipTemplateTransclude', [ + '$animate', '$sce', '$compile', '$templateRequest', +function ($animate , $sce , $compile , $templateRequest) { + return { + link: function(scope, elem, attrs) { + var origScope = scope.$eval(attrs.tooltipTemplateTranscludeScope); + + var changeCounter = 0, + currentScope, + previousElement, + currentElement; + + var cleanupLastIncludeContent = function() { + if (previousElement) { + previousElement.remove(); + previousElement = null; + } + + if (currentScope) { + currentScope.$destroy(); + currentScope = null; + } + + if (currentElement) { + $animate.leave(currentElement).then(function() { + previousElement = null; + }); + previousElement = currentElement; + currentElement = null; + } + }; + + scope.$watch($sce.parseAsResourceUrl(attrs.uibTooltipTemplateTransclude), function(src) { + var thisChangeId = ++changeCounter; + + if (src) { + //set the 2nd param to true to ignore the template request error so that the inner + //contents and scope can be cleaned up. + $templateRequest(src, true).then(function(response) { + if (thisChangeId !== changeCounter) { return; } + var newScope = origScope.$new(); + var template = response; + + var clone = $compile(template)(newScope, function(clone) { + cleanupLastIncludeContent(); + $animate.enter(clone, elem); + }); + + currentScope = newScope; + currentElement = clone; + + currentScope.$emit('$includeContentLoaded', src); + }, function() { + if (thisChangeId === changeCounter) { + cleanupLastIncludeContent(); + scope.$emit('$includeContentError', src); + } + }); + scope.$emit('$includeContentRequested', src); + } else { + cleanupLastIncludeContent(); + } + }); + + scope.$on('$destroy', cleanupLastIncludeContent); + } + }; +}]) + +/** + * Note that it's intentional that these classes are *not* applied through $animate. + * They must not be animated as they're expected to be present on the tooltip on + * initialization. + */ +.directive('uibTooltipClasses', function() { + return { + restrict: 'A', + link: function(scope, element, attrs) { + if (scope.placement) { + element.addClass(scope.placement); + } + + if (scope.popupClass) { + element.addClass(scope.popupClass); + } + + if (scope.animation()) { + element.addClass(attrs.tooltipAnimationClass); + } + } + }; +}) + +.directive('uibTooltipPopup', function() { + return { + replace: true, + scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/tooltip/tooltip-popup.html', + link: function(scope, element) { + element.addClass('tooltip'); + } + }; +}) + +.directive('uibTooltip', [ '$uibTooltip', function($uibTooltip) { + return $uibTooltip('uibTooltip', 'tooltip', 'mouseenter'); +}]) + +.directive('uibTooltipTemplatePopup', function() { + return { + replace: true, + scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&', + originScope: '&' }, + templateUrl: 'template/tooltip/tooltip-template-popup.html', + link: function(scope, element) { + element.addClass('tooltip'); + } + }; +}) + +.directive('uibTooltipTemplate', ['$uibTooltip', function($uibTooltip) { + return $uibTooltip('uibTooltipTemplate', 'tooltip', 'mouseenter', { + useContentExp: true + }); +}]) + +.directive('uibTooltipHtmlPopup', function() { + return { + replace: true, + scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/tooltip/tooltip-html-popup.html', + link: function(scope, element) { + element.addClass('tooltip'); + } + }; +}) + +.directive('uibTooltipHtml', ['$uibTooltip', function($uibTooltip) { + return $uibTooltip('uibTooltipHtml', 'tooltip', 'mouseenter', { + useContentExp: true + }); +}]); + +/* Deprecated tooltip below */ + +angular.module('ui.bootstrap.tooltip') + +.value('$tooltipSuppressWarning', false) + +.provider('$tooltip', ['$uibTooltipProvider', function($uibTooltipProvider) { + angular.extend(this, $uibTooltipProvider); + + this.$get = ['$log', '$tooltipSuppressWarning', '$injector', function($log, $tooltipSuppressWarning, $injector) { + if (!$tooltipSuppressWarning) { + $log.warn('$tooltip is now deprecated. Use $uibTooltip instead.'); + } + + return $injector.invoke($uibTooltipProvider.$get); + }]; +}]) + +// This is mostly ngInclude code but with a custom scope +.directive('tooltipTemplateTransclude', [ + '$animate', '$sce', '$compile', '$templateRequest', '$log', '$tooltipSuppressWarning', +function ($animate , $sce , $compile , $templateRequest, $log, $tooltipSuppressWarning) { + return { + link: function(scope, elem, attrs) { + if (!$tooltipSuppressWarning) { + $log.warn('tooltip-template-transclude is now deprecated. Use uib-tooltip-template-transclude instead.'); + } + + var origScope = scope.$eval(attrs.tooltipTemplateTranscludeScope); + + var changeCounter = 0, + currentScope, + previousElement, + currentElement; + + var cleanupLastIncludeContent = function() { + if (previousElement) { + previousElement.remove(); + previousElement = null; + } + if (currentScope) { + currentScope.$destroy(); + currentScope = null; + } + if (currentElement) { + $animate.leave(currentElement).then(function() { + previousElement = null; + }); + previousElement = currentElement; + currentElement = null; + } + }; + + scope.$watch($sce.parseAsResourceUrl(attrs.tooltipTemplateTransclude), function(src) { + var thisChangeId = ++changeCounter; + + if (src) { + //set the 2nd param to true to ignore the template request error so that the inner + //contents and scope can be cleaned up. + $templateRequest(src, true).then(function(response) { + if (thisChangeId !== changeCounter) { return; } + var newScope = origScope.$new(); + var template = response; + + var clone = $compile(template)(newScope, function(clone) { + cleanupLastIncludeContent(); + $animate.enter(clone, elem); + }); + + currentScope = newScope; + currentElement = clone; + + currentScope.$emit('$includeContentLoaded', src); + }, function() { + if (thisChangeId === changeCounter) { + cleanupLastIncludeContent(); + scope.$emit('$includeContentError', src); + } + }); + scope.$emit('$includeContentRequested', src); + } else { + cleanupLastIncludeContent(); + } + }); + + scope.$on('$destroy', cleanupLastIncludeContent); + } + }; +}]) + +.directive('tooltipClasses', ['$log', '$tooltipSuppressWarning', function($log, $tooltipSuppressWarning) { + return { + restrict: 'A', + link: function(scope, element, attrs) { + if (!$tooltipSuppressWarning) { + $log.warn('tooltip-classes is now deprecated. Use uib-tooltip-classes instead.'); + } + + if (scope.placement) { + element.addClass(scope.placement); + } + if (scope.popupClass) { + element.addClass(scope.popupClass); + } + if (scope.animation()) { + element.addClass(attrs.tooltipAnimationClass); + } + } + }; +}]) + +.directive('tooltipPopup', ['$log', '$tooltipSuppressWarning', function($log, $tooltipSuppressWarning) { + return { + replace: true, + scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/tooltip/tooltip-popup.html', + link: function(scope, element) { + if (!$tooltipSuppressWarning) { + $log.warn('tooltip-popup is now deprecated. Use uib-tooltip-popup instead.'); + } + + element.addClass('tooltip'); + } + }; +}]) + +.directive('tooltip', ['$tooltip', function($tooltip) { + return $tooltip('tooltip', 'tooltip', 'mouseenter'); +}]) + +.directive('tooltipTemplatePopup', ['$log', '$tooltipSuppressWarning', function($log, $tooltipSuppressWarning) { + return { + replace: true, + scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&', + originScope: '&' }, + templateUrl: 'template/tooltip/tooltip-template-popup.html', + link: function(scope, element) { + if (!$tooltipSuppressWarning) { + $log.warn('tooltip-template-popup is now deprecated. Use uib-tooltip-template-popup instead.'); + } + + element.addClass('tooltip'); + } + }; +}]) + +.directive('tooltipTemplate', ['$tooltip', function($tooltip) { + return $tooltip('tooltipTemplate', 'tooltip', 'mouseenter', { + useContentExp: true + }); +}]) + +.directive('tooltipHtmlPopup', ['$log', '$tooltipSuppressWarning', function($log, $tooltipSuppressWarning) { + return { + replace: true, + scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/tooltip/tooltip-html-popup.html', + link: function(scope, element) { + if (!$tooltipSuppressWarning) { + $log.warn('tooltip-html-popup is now deprecated. Use uib-tooltip-html-popup instead.'); + } + + element.addClass('tooltip'); + } + }; +}]) + +.directive('tooltipHtml', ['$tooltip', function($tooltip) { + return $tooltip('tooltipHtml', 'tooltip', 'mouseenter', { + useContentExp: true + }); +}]); + +/** + * The following features are still outstanding: popup delay, animation as a + * function, placement as a function, inside, support for more triggers than + * just mouse enter/leave, and selector delegatation. + */ +angular.module('ui.bootstrap.popover', ['ui.bootstrap.tooltip']) + +.directive('uibPopoverTemplatePopup', function() { + return { + replace: true, + scope: { title: '@', contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&', + originScope: '&' }, + templateUrl: 'template/popover/popover-template.html', + link: function(scope, element) { + element.addClass('popover'); + } + }; +}) + +.directive('uibPopoverTemplate', ['$uibTooltip', function($uibTooltip) { + return $uibTooltip('uibPopoverTemplate', 'popover', 'click', { + useContentExp: true + }); +}]) + +.directive('uibPopoverHtmlPopup', function() { + return { + replace: true, + scope: { contentExp: '&', title: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/popover/popover-html.html', + link: function(scope, element) { + element.addClass('popover'); + } + }; +}) + +.directive('uibPopoverHtml', ['$uibTooltip', function($uibTooltip) { + return $uibTooltip('uibPopoverHtml', 'popover', 'click', { + useContentExp: true + }); +}]) + +.directive('uibPopoverPopup', function() { + return { + replace: true, + scope: { title: '@', content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/popover/popover.html', + link: function(scope, element) { + element.addClass('popover'); + } + }; +}) + +.directive('uibPopover', ['$uibTooltip', function($uibTooltip) { + return $uibTooltip('uibPopover', 'popover', 'click'); +}]); + +/* Deprecated popover below */ + +angular.module('ui.bootstrap.popover') + +.value('$popoverSuppressWarning', false) + +.directive('popoverTemplatePopup', ['$log', '$popoverSuppressWarning', function($log, $popoverSuppressWarning) { + return { + replace: true, + scope: { title: '@', contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&', + originScope: '&' }, + templateUrl: 'template/popover/popover-template.html', + link: function(scope, element) { + if (!$popoverSuppressWarning) { + $log.warn('popover-template-popup is now deprecated. Use uib-popover-template-popup instead.'); + } + + element.addClass('popover'); + } + }; +}]) + +.directive('popoverTemplate', ['$tooltip', function($tooltip) { + return $tooltip('popoverTemplate', 'popover', 'click', { + useContentExp: true + }); +}]) + +.directive('popoverHtmlPopup', ['$log', '$popoverSuppressWarning', function($log, $popoverSuppressWarning) { + return { + replace: true, + scope: { contentExp: '&', title: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/popover/popover-html.html', + link: function(scope, element) { + if (!$popoverSuppressWarning) { + $log.warn('popover-html-popup is now deprecated. Use uib-popover-html-popup instead.'); + } + + element.addClass('popover'); + } + }; +}]) + +.directive('popoverHtml', ['$tooltip', function($tooltip) { + return $tooltip('popoverHtml', 'popover', 'click', { + useContentExp: true + }); +}]) + +.directive('popoverPopup', ['$log', '$popoverSuppressWarning', function($log, $popoverSuppressWarning) { + return { + replace: true, + scope: { title: '@', content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, + templateUrl: 'template/popover/popover.html', + link: function(scope, element) { + if (!$popoverSuppressWarning) { + $log.warn('popover-popup is now deprecated. Use uib-popover-popup instead.'); + } + + element.addClass('popover'); + } + }; +}]) + +.directive('popover', ['$tooltip', function($tooltip) { + + return $tooltip('popover', 'popover', 'click'); +}]); + +angular.module('ui.bootstrap.progressbar', []) + +.constant('uibProgressConfig', { + animate: true, + max: 100 +}) + +.controller('UibProgressController', ['$scope', '$attrs', 'uibProgressConfig', function($scope, $attrs, progressConfig) { + var self = this, + animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate; + + this.bars = []; + $scope.max = angular.isDefined($scope.max) ? $scope.max : progressConfig.max; + + this.addBar = function(bar, element, attrs) { + if (!animate) { + element.css({'transition': 'none'}); + } + + this.bars.push(bar); + + bar.max = $scope.max; + bar.title = attrs && angular.isDefined(attrs.title) ? attrs.title : 'progressbar'; + + bar.$watch('value', function(value) { + bar.recalculatePercentage(); + }); + + bar.recalculatePercentage = function() { + var totalPercentage = self.bars.reduce(function(total, bar) { + bar.percent = +(100 * bar.value / bar.max).toFixed(2); + return total + bar.percent; + }, 0); + + if (totalPercentage > 100) { + bar.percent -= totalPercentage - 100; + } + }; + + bar.$on('$destroy', function() { + element = null; + self.removeBar(bar); + }); + }; + + this.removeBar = function(bar) { + this.bars.splice(this.bars.indexOf(bar), 1); + this.bars.forEach(function (bar) { + bar.recalculatePercentage(); + }); + }; + + $scope.$watch('max', function(max) { + self.bars.forEach(function(bar) { + bar.max = $scope.max; + bar.recalculatePercentage(); + }); + }); +}]) + +.directive('uibProgress', function() { + return { + replace: true, + transclude: true, + controller: 'UibProgressController', + require: 'uibProgress', + scope: { + max: '=?' + }, + templateUrl: 'template/progressbar/progress.html' + }; +}) + +.directive('uibBar', function() { + return { + replace: true, + transclude: true, + require: '^uibProgress', + scope: { + value: '=', + type: '@' + }, + templateUrl: 'template/progressbar/bar.html', + link: function(scope, element, attrs, progressCtrl) { + progressCtrl.addBar(scope, element, attrs); + } + }; +}) + +.directive('uibProgressbar', function() { + return { + replace: true, + transclude: true, + controller: 'UibProgressController', + scope: { + value: '=', + max: '=?', + type: '@' + }, + templateUrl: 'template/progressbar/progressbar.html', + link: function(scope, element, attrs, progressCtrl) { + progressCtrl.addBar(scope, angular.element(element.children()[0]), {title: attrs.title}); + } + }; +}); + +/* Deprecated progressbar below */ + +angular.module('ui.bootstrap.progressbar') + +.value('$progressSuppressWarning', false) + +.controller('ProgressController', ['$scope', '$attrs', 'uibProgressConfig', '$log', '$progressSuppressWarning', function($scope, $attrs, progressConfig, $log, $progressSuppressWarning) { + if (!$progressSuppressWarning) { + $log.warn('ProgressController is now deprecated. Use UibProgressController instead.'); + } + + var self = this, + animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate; + + this.bars = []; + $scope.max = angular.isDefined($scope.max) ? $scope.max : progressConfig.max; + + this.addBar = function(bar, element, attrs) { + if (!animate) { + element.css({'transition': 'none'}); + } + + this.bars.push(bar); + + bar.max = $scope.max; + bar.title = attrs && angular.isDefined(attrs.title) ? attrs.title : 'progressbar'; + + bar.$watch('value', function(value) { + bar.recalculatePercentage(); + }); + + bar.recalculatePercentage = function() { + bar.percent = +(100 * bar.value / bar.max).toFixed(2); + + var totalPercentage = self.bars.reduce(function(total, bar) { + return total + bar.percent; + }, 0); + + if (totalPercentage > 100) { + bar.percent -= totalPercentage - 100; + } + }; + + bar.$on('$destroy', function() { + element = null; + self.removeBar(bar); + }); + }; + + this.removeBar = function(bar) { + this.bars.splice(this.bars.indexOf(bar), 1); + }; + + $scope.$watch('max', function(max) { + self.bars.forEach(function(bar) { + bar.max = $scope.max; + bar.recalculatePercentage(); + }); + }); +}]) + +.directive('progress', ['$log', '$progressSuppressWarning', function($log, $progressSuppressWarning) { + return { + replace: true, + transclude: true, + controller: 'ProgressController', + require: 'progress', + scope: { + max: '=?', + title: '@?' + }, + templateUrl: 'template/progressbar/progress.html', + link: function() { + if (!$progressSuppressWarning) { + $log.warn('progress is now deprecated. Use uib-progress instead.'); + } + } + }; +}]) + +.directive('bar', ['$log', '$progressSuppressWarning', function($log, $progressSuppressWarning) { + return { + replace: true, + transclude: true, + require: '^progress', + scope: { + value: '=', + type: '@' + }, + templateUrl: 'template/progressbar/bar.html', + link: function(scope, element, attrs, progressCtrl) { + if (!$progressSuppressWarning) { + $log.warn('bar is now deprecated. Use uib-bar instead.'); + } + progressCtrl.addBar(scope, element); + } + }; +}]) + +.directive('progressbar', ['$log', '$progressSuppressWarning', function($log, $progressSuppressWarning) { + return { + replace: true, + transclude: true, + controller: 'ProgressController', + scope: { + value: '=', + max: '=?', + type: '@' + }, + templateUrl: 'template/progressbar/progressbar.html', + link: function(scope, element, attrs, progressCtrl) { + if (!$progressSuppressWarning) { + $log.warn('progressbar is now deprecated. Use uib-progressbar instead.'); + } + progressCtrl.addBar(scope, angular.element(element.children()[0]), {title: attrs.title}); + } + }; +}]); + +angular.module('ui.bootstrap.rating', []) + +.constant('uibRatingConfig', { + max: 5, + stateOn: null, + stateOff: null, + titles : ['one', 'two', 'three', 'four', 'five'] +}) + +.controller('UibRatingController', ['$scope', '$attrs', 'uibRatingConfig', function($scope, $attrs, ratingConfig) { + var ngModelCtrl = { $setViewValue: angular.noop }; + + this.init = function(ngModelCtrl_) { + ngModelCtrl = ngModelCtrl_; + ngModelCtrl.$render = this.render; + + ngModelCtrl.$formatters.push(function(value) { + if (angular.isNumber(value) && value << 0 !== value) { + value = Math.round(value); + } + return value; + }); + + this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn; + this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff; + var tmpTitles = angular.isDefined($attrs.titles) ? $scope.$parent.$eval($attrs.titles) : ratingConfig.titles ; + this.titles = angular.isArray(tmpTitles) && tmpTitles.length > 0 ? + tmpTitles : ratingConfig.titles; + + var ratingStates = angular.isDefined($attrs.ratingStates) ? + $scope.$parent.$eval($attrs.ratingStates) : + new Array(angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max); + $scope.range = this.buildTemplateObjects(ratingStates); + }; + + this.buildTemplateObjects = function(states) { + for (var i = 0, n = states.length; i < n; i++) { + states[i] = angular.extend({ index: i }, { stateOn: this.stateOn, stateOff: this.stateOff, title: this.getTitle(i) }, states[i]); + } + return states; + }; + + this.getTitle = function(index) { + if (index >= this.titles.length) { + return index + 1; + } else { + return this.titles[index]; + } + }; + + $scope.rate = function(value) { + if (!$scope.readonly && value >= 0 && value <= $scope.range.length) { + ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue === value ? 0 : value); + ngModelCtrl.$render(); + } + }; + + $scope.enter = function(value) { + if (!$scope.readonly) { + $scope.value = value; + } + $scope.onHover({value: value}); + }; + + $scope.reset = function() { + $scope.value = ngModelCtrl.$viewValue; + $scope.onLeave(); + }; + + $scope.onKeydown = function(evt) { + if (/(37|38|39|40)/.test(evt.which)) { + evt.preventDefault(); + evt.stopPropagation(); + $scope.rate($scope.value + (evt.which === 38 || evt.which === 39 ? 1 : -1)); + } + }; + + this.render = function() { + $scope.value = ngModelCtrl.$viewValue; + }; +}]) + +.directive('uibRating', function() { + return { + require: ['uibRating', 'ngModel'], + scope: { + readonly: '=?', + onHover: '&', + onLeave: '&' + }, + controller: 'UibRatingController', + templateUrl: 'template/rating/rating.html', + replace: true, + link: function(scope, element, attrs, ctrls) { + var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + ratingCtrl.init(ngModelCtrl); + } + }; +}); + +/* Deprecated rating below */ + +angular.module('ui.bootstrap.rating') + +.value('$ratingSuppressWarning', false) + +.controller('RatingController', ['$scope', '$attrs', '$controller', '$log', '$ratingSuppressWarning', function($scope, $attrs, $controller, $log, $ratingSuppressWarning) { + if (!$ratingSuppressWarning) { + $log.warn('RatingController is now deprecated. Use UibRatingController instead.'); + } + + angular.extend(this, $controller('UibRatingController', { + $scope: $scope, + $attrs: $attrs + })); +}]) + +.directive('rating', ['$log', '$ratingSuppressWarning', function($log, $ratingSuppressWarning) { + return { + require: ['rating', 'ngModel'], + scope: { + readonly: '=?', + onHover: '&', + onLeave: '&' + }, + controller: 'RatingController', + templateUrl: 'template/rating/rating.html', + replace: true, + link: function(scope, element, attrs, ctrls) { + if (!$ratingSuppressWarning) { + $log.warn('rating is now deprecated. Use uib-rating instead.'); + } + var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + ratingCtrl.init(ngModelCtrl); + } + }; +}]); + + +/** + * @ngdoc overview + * @name ui.bootstrap.tabs + * + * @description + * AngularJS version of the tabs directive. + */ + +angular.module('ui.bootstrap.tabs', []) + +.controller('UibTabsetController', ['$scope', function ($scope) { + var ctrl = this, + tabs = ctrl.tabs = $scope.tabs = []; + + ctrl.select = function(selectedTab) { + angular.forEach(tabs, function(tab) { + if (tab.active && tab !== selectedTab) { + tab.active = false; + tab.onDeselect(); + selectedTab.selectCalled = false; + } + }); + selectedTab.active = true; + // only call select if it has not already been called + if (!selectedTab.selectCalled) { + selectedTab.onSelect(); + selectedTab.selectCalled = true; + } + }; + + ctrl.addTab = function addTab(tab) { + tabs.push(tab); + // we can't run the select function on the first tab + // since that would select it twice + if (tabs.length === 1 && tab.active !== false) { + tab.active = true; + } else if (tab.active) { + ctrl.select(tab); + } else { + tab.active = false; + } + }; + + ctrl.removeTab = function removeTab(tab) { + var index = tabs.indexOf(tab); + //Select a new tab if the tab to be removed is selected and not destroyed + if (tab.active && tabs.length > 1 && !destroyed) { + //If this is the last tab, select the previous tab. else, the next tab. + var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1; + ctrl.select(tabs[newActiveIndex]); + } + tabs.splice(index, 1); + }; + + var destroyed; + $scope.$on('$destroy', function() { + destroyed = true; + }); +}]) + +/** + * @ngdoc directive + * @name ui.bootstrap.tabs.directive:tabset + * @restrict EA + * + * @description + * Tabset is the outer container for the tabs directive + * + * @param {boolean=} vertical Whether or not to use vertical styling for the tabs. + * @param {boolean=} justified Whether or not to use justified styling for the tabs. + * + * @example + + + + First Content! + Second Content! + +
      + + First Vertical Content! + Second Vertical Content! + + + First Justified Content! + Second Justified Content! + +
      +
      + */ +.directive('uibTabset', function() { + return { + restrict: 'EA', + transclude: true, + replace: true, + scope: { + type: '@' + }, + controller: 'UibTabsetController', + templateUrl: 'template/tabs/tabset.html', + link: function(scope, element, attrs) { + scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false; + scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false; + } + }; +}) + +/** + * @ngdoc directive + * @name ui.bootstrap.tabs.directive:tab + * @restrict EA + * + * @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link ui.bootstrap.tabs.directive:tabHeading tabHeading}. + * @param {string=} select An expression to evaluate when the tab is selected. + * @param {boolean=} active A binding, telling whether or not this tab is selected. + * @param {boolean=} disabled A binding, telling whether or not this tab is disabled. + * + * @description + * Creates a tab with a heading and content. Must be placed within a {@link ui.bootstrap.tabs.directive:tabset tabset}. + * + * @example + + +
      + + +
      + + First Tab + + Alert me! + Second Tab, with alert callback and html heading! + + + {{item.content}} + + +
      +
      + + function TabsDemoCtrl($scope) { + $scope.items = [ + { title:"Dynamic Title 1", content:"Dynamic Item 0" }, + { title:"Dynamic Title 2", content:"Dynamic Item 1", disabled: true } + ]; + + $scope.alertMe = function() { + setTimeout(function() { + alert("You've selected the alert tab!"); + }); + }; + }; + +
      + */ + +/** + * @ngdoc directive + * @name ui.bootstrap.tabs.directive:tabHeading + * @restrict EA + * + * @description + * Creates an HTML heading for a {@link ui.bootstrap.tabs.directive:tab tab}. Must be placed as a child of a tab element. + * + * @example + + + + + HTML in my titles?! + And some content, too! + + + Icon heading?!? + That's right. + + + + + */ +.directive('uibTab', ['$parse', function($parse) { + return { + require: '^uibTabset', + restrict: 'EA', + replace: true, + templateUrl: 'template/tabs/tab.html', + transclude: true, + scope: { + active: '=?', + heading: '@', + onSelect: '&select', //This callback is called in contentHeadingTransclude + //once it inserts the tab's content into the dom + onDeselect: '&deselect' + }, + controller: function() { + //Empty controller so other directives can require being 'under' a tab + }, + link: function(scope, elm, attrs, tabsetCtrl, transclude) { + scope.$watch('active', function(active) { + if (active) { + tabsetCtrl.select(scope); + } + }); + + scope.disabled = false; + if (attrs.disable) { + scope.$parent.$watch($parse(attrs.disable), function(value) { + scope.disabled = !! value; + }); + } + + scope.select = function() { + if (!scope.disabled) { + scope.active = true; + } + }; + + tabsetCtrl.addTab(scope); + scope.$on('$destroy', function() { + tabsetCtrl.removeTab(scope); + }); + + //We need to transclude later, once the content container is ready. + //when this link happens, we're inside a tab heading. + scope.$transcludeFn = transclude; + } + }; +}]) + +.directive('uibTabHeadingTransclude', function() { + return { + restrict: 'A', + require: ['?^uibTab', '?^tab'], // TODO: change to '^uibTab' after deprecation removal + link: function(scope, elm) { + scope.$watch('headingElement', function updateHeadingElement(heading) { + if (heading) { + elm.html(''); + elm.append(heading); + } + }); + } + }; +}) + +.directive('uibTabContentTransclude', function() { + return { + restrict: 'A', + require: ['?^uibTabset', '?^tabset'], // TODO: change to '^uibTabset' after deprecation removal + link: function(scope, elm, attrs) { + var tab = scope.$eval(attrs.uibTabContentTransclude); + + //Now our tab is ready to be transcluded: both the tab heading area + //and the tab content area are loaded. Transclude 'em both. + tab.$transcludeFn(tab.$parent, function(contents) { + angular.forEach(contents, function(node) { + if (isTabHeading(node)) { + //Let tabHeadingTransclude know. + tab.headingElement = node; + } else { + elm.append(node); + } + }); + }); + } + }; + + function isTabHeading(node) { + return node.tagName && ( + node.hasAttribute('tab-heading') || // TODO: remove after deprecation removal + node.hasAttribute('data-tab-heading') || // TODO: remove after deprecation removal + node.hasAttribute('x-tab-heading') || // TODO: remove after deprecation removal + node.hasAttribute('uib-tab-heading') || + node.hasAttribute('data-uib-tab-heading') || + node.hasAttribute('x-uib-tab-heading') || + node.tagName.toLowerCase() === 'tab-heading' || // TODO: remove after deprecation removal + node.tagName.toLowerCase() === 'data-tab-heading' || // TODO: remove after deprecation removal + node.tagName.toLowerCase() === 'x-tab-heading' || // TODO: remove after deprecation removal + node.tagName.toLowerCase() === 'uib-tab-heading' || + node.tagName.toLowerCase() === 'data-uib-tab-heading' || + node.tagName.toLowerCase() === 'x-uib-tab-heading' + ); + } +}); + +/* deprecated tabs below */ + +angular.module('ui.bootstrap.tabs') + + .value('$tabsSuppressWarning', false) + + .controller('TabsetController', ['$scope', '$controller', '$log', '$tabsSuppressWarning', function($scope, $controller, $log, $tabsSuppressWarning) { + if (!$tabsSuppressWarning) { + $log.warn('TabsetController is now deprecated. Use UibTabsetController instead.'); + } + + angular.extend(this, $controller('UibTabsetController', { + $scope: $scope + })); + }]) + + .directive('tabset', ['$log', '$tabsSuppressWarning', function($log, $tabsSuppressWarning) { + return { + restrict: 'EA', + transclude: true, + replace: true, + scope: { + type: '@' + }, + controller: 'TabsetController', + templateUrl: 'template/tabs/tabset.html', + link: function(scope, element, attrs) { + + if (!$tabsSuppressWarning) { + $log.warn('tabset is now deprecated. Use uib-tabset instead.'); + } + scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false; + scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false; + } + }; + }]) + + .directive('tab', ['$parse', '$log', '$tabsSuppressWarning', function($parse, $log, $tabsSuppressWarning) { + return { + require: '^tabset', + restrict: 'EA', + replace: true, + templateUrl: 'template/tabs/tab.html', + transclude: true, + scope: { + active: '=?', + heading: '@', + onSelect: '&select', //This callback is called in contentHeadingTransclude + //once it inserts the tab's content into the dom + onDeselect: '&deselect' + }, + controller: function() { + //Empty controller so other directives can require being 'under' a tab + }, + link: function(scope, elm, attrs, tabsetCtrl, transclude) { + if (!$tabsSuppressWarning) { + $log.warn('tab is now deprecated. Use uib-tab instead.'); + } + + scope.$watch('active', function(active) { + if (active) { + tabsetCtrl.select(scope); + } + }); + + scope.disabled = false; + if (attrs.disable) { + scope.$parent.$watch($parse(attrs.disable), function(value) { + scope.disabled = !!value; + }); + } + + scope.select = function() { + if (!scope.disabled) { + scope.active = true; + } + }; + + tabsetCtrl.addTab(scope); + scope.$on('$destroy', function() { + tabsetCtrl.removeTab(scope); + }); + + //We need to transclude later, once the content container is ready. + //when this link happens, we're inside a tab heading. + scope.$transcludeFn = transclude; + } + }; + }]) + + .directive('tabHeadingTransclude', ['$log', '$tabsSuppressWarning', function($log, $tabsSuppressWarning) { + return { + restrict: 'A', + require: '^tab', + link: function(scope, elm) { + if (!$tabsSuppressWarning) { + $log.warn('tab-heading-transclude is now deprecated. Use uib-tab-heading-transclude instead.'); + } + + scope.$watch('headingElement', function updateHeadingElement(heading) { + if (heading) { + elm.html(''); + elm.append(heading); + } + }); + } + }; + }]) + + .directive('tabContentTransclude', ['$log', '$tabsSuppressWarning', function($log, $tabsSuppressWarning) { + return { + restrict: 'A', + require: '^tabset', + link: function(scope, elm, attrs) { + if (!$tabsSuppressWarning) { + $log.warn('tab-content-transclude is now deprecated. Use uib-tab-content-transclude instead.'); + } + + var tab = scope.$eval(attrs.tabContentTransclude); + + //Now our tab is ready to be transcluded: both the tab heading area + //and the tab content area are loaded. Transclude 'em both. + tab.$transcludeFn(tab.$parent, function(contents) { + angular.forEach(contents, function(node) { + if (isTabHeading(node)) { + //Let tabHeadingTransclude know. + tab.headingElement = node; + } + else { + elm.append(node); + } + }); + }); + } + }; + + function isTabHeading(node) { + return node.tagName && ( + node.hasAttribute('tab-heading') || + node.hasAttribute('data-tab-heading') || + node.hasAttribute('x-tab-heading') || + node.tagName.toLowerCase() === 'tab-heading' || + node.tagName.toLowerCase() === 'data-tab-heading' || + node.tagName.toLowerCase() === 'x-tab-heading' + ); + } + }]); + +angular.module('ui.bootstrap.timepicker', []) + +.constant('uibTimepickerConfig', { + hourStep: 1, + minuteStep: 1, + showMeridian: true, + meridians: null, + readonlyInput: false, + mousewheel: true, + arrowkeys: true, + showSpinners: true +}) + +.controller('UibTimepickerController', ['$scope', '$element', '$attrs', '$parse', '$log', '$locale', 'uibTimepickerConfig', function($scope, $element, $attrs, $parse, $log, $locale, timepickerConfig) { + var selected = new Date(), + ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl + meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS; + + $scope.tabindex = angular.isDefined($attrs.tabindex) ? $attrs.tabindex : 0; + $element.removeAttr('tabindex'); + + this.init = function(ngModelCtrl_, inputs) { + ngModelCtrl = ngModelCtrl_; + ngModelCtrl.$render = this.render; + + ngModelCtrl.$formatters.unshift(function(modelValue) { + return modelValue ? new Date(modelValue) : null; + }); + + var hoursInputEl = inputs.eq(0), + minutesInputEl = inputs.eq(1); + + var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel; + if (mousewheel) { + this.setupMousewheelEvents(hoursInputEl, minutesInputEl); + } + + var arrowkeys = angular.isDefined($attrs.arrowkeys) ? $scope.$parent.$eval($attrs.arrowkeys) : timepickerConfig.arrowkeys; + if (arrowkeys) { + this.setupArrowkeyEvents(hoursInputEl, minutesInputEl); + } + + $scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput; + this.setupInputEvents(hoursInputEl, minutesInputEl); + }; + + var hourStep = timepickerConfig.hourStep; + if ($attrs.hourStep) { + $scope.$parent.$watch($parse($attrs.hourStep), function(value) { + hourStep = parseInt(value, 10); + }); + } + + var minuteStep = timepickerConfig.minuteStep; + if ($attrs.minuteStep) { + $scope.$parent.$watch($parse($attrs.minuteStep), function(value) { + minuteStep = parseInt(value, 10); + }); + } + + var min; + $scope.$parent.$watch($parse($attrs.min), function(value) { + var dt = new Date(value); + min = isNaN(dt) ? undefined : dt; + }); + + var max; + $scope.$parent.$watch($parse($attrs.max), function(value) { + var dt = new Date(value); + max = isNaN(dt) ? undefined : dt; + }); + + $scope.noIncrementHours = function() { + var incrementedSelected = addMinutes(selected, hourStep * 60); + return incrementedSelected > max || + (incrementedSelected < selected && incrementedSelected < min); + }; + + $scope.noDecrementHours = function() { + var decrementedSelected = addMinutes(selected, -hourStep * 60); + return decrementedSelected < min || + (decrementedSelected > selected && decrementedSelected > max); + }; + + $scope.noIncrementMinutes = function() { + var incrementedSelected = addMinutes(selected, minuteStep); + return incrementedSelected > max || + (incrementedSelected < selected && incrementedSelected < min); + }; + + $scope.noDecrementMinutes = function() { + var decrementedSelected = addMinutes(selected, -minuteStep); + return decrementedSelected < min || + (decrementedSelected > selected && decrementedSelected > max); + }; + + $scope.noToggleMeridian = function() { + if (selected.getHours() < 13) { + return addMinutes(selected, 12 * 60) > max; + } else { + return addMinutes(selected, -12 * 60) < min; + } + }; + + // 12H / 24H mode + $scope.showMeridian = timepickerConfig.showMeridian; + if ($attrs.showMeridian) { + $scope.$parent.$watch($parse($attrs.showMeridian), function(value) { + $scope.showMeridian = !!value; + + if (ngModelCtrl.$error.time) { + // Evaluate from template + var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate(); + if (angular.isDefined(hours) && angular.isDefined(minutes)) { + selected.setHours(hours); + refresh(); + } + } else { + updateTemplate(); + } + }); + } + + // Get $scope.hours in 24H mode if valid + function getHoursFromTemplate() { + var hours = parseInt($scope.hours, 10); + var valid = $scope.showMeridian ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24); + if (!valid) { + return undefined; + } + + if ($scope.showMeridian) { + if (hours === 12) { + hours = 0; + } + if ($scope.meridian === meridians[1]) { + hours = hours + 12; + } + } + return hours; + } + + function getMinutesFromTemplate() { + var minutes = parseInt($scope.minutes, 10); + return (minutes >= 0 && minutes < 60) ? minutes : undefined; + } + + function pad(value) { + return (angular.isDefined(value) && value.toString().length < 2) ? '0' + value : value.toString(); + } + + // Respond on mousewheel spin + this.setupMousewheelEvents = function(hoursInputEl, minutesInputEl) { + var isScrollingUp = function(e) { + if (e.originalEvent) { + e = e.originalEvent; + } + //pick correct delta variable depending on event + var delta = (e.wheelDelta) ? e.wheelDelta : -e.deltaY; + return (e.detail || delta > 0); + }; + + hoursInputEl.bind('mousewheel wheel', function(e) { + $scope.$apply(isScrollingUp(e) ? $scope.incrementHours() : $scope.decrementHours()); + e.preventDefault(); + }); + + minutesInputEl.bind('mousewheel wheel', function(e) { + $scope.$apply(isScrollingUp(e) ? $scope.incrementMinutes() : $scope.decrementMinutes()); + e.preventDefault(); + }); + + }; + + // Respond on up/down arrowkeys + this.setupArrowkeyEvents = function(hoursInputEl, minutesInputEl) { + hoursInputEl.bind('keydown', function(e) { + if (e.which === 38) { // up + e.preventDefault(); + $scope.incrementHours(); + $scope.$apply(); + } else if (e.which === 40) { // down + e.preventDefault(); + $scope.decrementHours(); + $scope.$apply(); + } + }); + + minutesInputEl.bind('keydown', function(e) { + if (e.which === 38) { // up + e.preventDefault(); + $scope.incrementMinutes(); + $scope.$apply(); + } else if (e.which === 40) { // down + e.preventDefault(); + $scope.decrementMinutes(); + $scope.$apply(); + } + }); + }; + + this.setupInputEvents = function(hoursInputEl, minutesInputEl) { + if ($scope.readonlyInput) { + $scope.updateHours = angular.noop; + $scope.updateMinutes = angular.noop; + return; + } + + var invalidate = function(invalidHours, invalidMinutes) { + ngModelCtrl.$setViewValue(null); + ngModelCtrl.$setValidity('time', false); + if (angular.isDefined(invalidHours)) { + $scope.invalidHours = invalidHours; + } + if (angular.isDefined(invalidMinutes)) { + $scope.invalidMinutes = invalidMinutes; + } + }; + + $scope.updateHours = function() { + var hours = getHoursFromTemplate(), + minutes = getMinutesFromTemplate(); + + if (angular.isDefined(hours) && angular.isDefined(minutes)) { + selected.setHours(hours); + if (selected < min || selected > max) { + invalidate(true); + } else { + refresh('h'); + } + } else { + invalidate(true); + } + }; + + hoursInputEl.bind('blur', function(e) { + if (!$scope.invalidHours && $scope.hours < 10) { + $scope.$apply(function() { + $scope.hours = pad($scope.hours); + }); + } + }); + + $scope.updateMinutes = function() { + var minutes = getMinutesFromTemplate(), + hours = getHoursFromTemplate(); + + if (angular.isDefined(minutes) && angular.isDefined(hours)) { + selected.setMinutes(minutes); + if (selected < min || selected > max) { + invalidate(undefined, true); + } else { + refresh('m'); + } + } else { + invalidate(undefined, true); + } + }; + + minutesInputEl.bind('blur', function(e) { + if (!$scope.invalidMinutes && $scope.minutes < 10) { + $scope.$apply(function() { + $scope.minutes = pad($scope.minutes); + }); + } + }); + + }; + + this.render = function() { + var date = ngModelCtrl.$viewValue; + + if (isNaN(date)) { + ngModelCtrl.$setValidity('time', false); + $log.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.'); + } else { + if (date) { + selected = date; + } + + if (selected < min || selected > max) { + ngModelCtrl.$setValidity('time', false); + $scope.invalidHours = true; + $scope.invalidMinutes = true; + } else { + makeValid(); + } + updateTemplate(); + } + }; + + // Call internally when we know that model is valid. + function refresh(keyboardChange) { + makeValid(); + ngModelCtrl.$setViewValue(new Date(selected)); + updateTemplate(keyboardChange); + } + + function makeValid() { + ngModelCtrl.$setValidity('time', true); + $scope.invalidHours = false; + $scope.invalidMinutes = false; + } + + function updateTemplate(keyboardChange) { + var hours = selected.getHours(), minutes = selected.getMinutes(); + + if ($scope.showMeridian) { + hours = (hours === 0 || hours === 12) ? 12 : hours % 12; // Convert 24 to 12 hour system + } + + $scope.hours = keyboardChange === 'h' ? hours : pad(hours); + if (keyboardChange !== 'm') { + $scope.minutes = pad(minutes); + } + $scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1]; + } + + function addMinutes(date, minutes) { + var dt = new Date(date.getTime() + minutes * 60000); + var newDate = new Date(date); + newDate.setHours(dt.getHours(), dt.getMinutes()); + return newDate; + } + + function addMinutesToSelected(minutes) { + selected = addMinutes(selected, minutes); + refresh(); + } + + $scope.showSpinners = angular.isDefined($attrs.showSpinners) ? + $scope.$parent.$eval($attrs.showSpinners) : timepickerConfig.showSpinners; + + $scope.incrementHours = function() { + if (!$scope.noIncrementHours()) { + addMinutesToSelected(hourStep * 60); + } + }; + + $scope.decrementHours = function() { + if (!$scope.noDecrementHours()) { + addMinutesToSelected(-hourStep * 60); + } + }; + + $scope.incrementMinutes = function() { + if (!$scope.noIncrementMinutes()) { + addMinutesToSelected(minuteStep); + } + }; + + $scope.decrementMinutes = function() { + if (!$scope.noDecrementMinutes()) { + addMinutesToSelected(-minuteStep); + } + }; + + $scope.toggleMeridian = function() { + if (!$scope.noToggleMeridian()) { + addMinutesToSelected(12 * 60 * (selected.getHours() < 12 ? 1 : -1)); + } + }; +}]) + +.directive('uibTimepicker', function() { + return { + restrict: 'EA', + require: ['uibTimepicker', '?^ngModel'], + controller: 'UibTimepickerController', + controllerAs: 'timepicker', + replace: true, + scope: {}, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/timepicker/timepicker.html'; + }, + link: function(scope, element, attrs, ctrls) { + var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + if (ngModelCtrl) { + timepickerCtrl.init(ngModelCtrl, element.find('input')); + } + } + }; +}); + +/* Deprecated timepicker below */ + +angular.module('ui.bootstrap.timepicker') + +.value('$timepickerSuppressWarning', false) + +.controller('TimepickerController', ['$scope', '$element', '$attrs', '$controller', '$log', '$timepickerSuppressWarning', function($scope, $element, $attrs, $controller, $log, $timepickerSuppressWarning) { + if (!$timepickerSuppressWarning) { + $log.warn('TimepickerController is now deprecated. Use UibTimepickerController instead.'); + } + + angular.extend(this, $controller('UibTimepickerController', { + $scope: $scope, + $element: $element, + $attrs: $attrs + })); +}]) + +.directive('timepicker', ['$log', '$timepickerSuppressWarning', function($log, $timepickerSuppressWarning) { + return { + restrict: 'EA', + require: ['timepicker', '?^ngModel'], + controller: 'TimepickerController', + controllerAs: 'timepicker', + replace: true, + scope: {}, + templateUrl: function(element, attrs) { + return attrs.templateUrl || 'template/timepicker/timepicker.html'; + }, + link: function(scope, element, attrs, ctrls) { + if (!$timepickerSuppressWarning) { + $log.warn('timepicker is now deprecated. Use uib-timepicker instead.'); + } + var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1]; + + if (ngModelCtrl) { + timepickerCtrl.init(ngModelCtrl, element.find('input')); + } + } + }; +}]); + +angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position']) + +/** + * A helper service that can parse typeahead's syntax (string provided by users) + * Extracted to a separate service for ease of unit testing + */ + .factory('uibTypeaheadParser', ['$parse', function($parse) { + // 00000111000000000000022200000000000000003333333333333330000000000044000 + var TYPEAHEAD_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/; + return { + parse: function(input) { + var match = input.match(TYPEAHEAD_REGEXP); + if (!match) { + throw new Error( + 'Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_"' + + ' but got "' + input + '".'); + } + + return { + itemName: match[3], + source: $parse(match[4]), + viewMapper: $parse(match[2] || match[1]), + modelMapper: $parse(match[1]) + }; + } + }; + }]) + + .controller('UibTypeaheadController', ['$scope', '$element', '$attrs', '$compile', '$parse', '$q', '$timeout', '$document', '$window', '$rootScope', '$uibPosition', 'uibTypeaheadParser', + function(originalScope, element, attrs, $compile, $parse, $q, $timeout, $document, $window, $rootScope, $position, typeaheadParser) { + var HOT_KEYS = [9, 13, 27, 38, 40]; + var eventDebounceTime = 200; + var modelCtrl, ngModelOptions; + //SUPPORTED ATTRIBUTES (OPTIONS) + + //minimal no of characters that needs to be entered before typeahead kicks-in + var minLength = originalScope.$eval(attrs.typeaheadMinLength); + if (!minLength && minLength !== 0) { + minLength = 1; + } + + //minimal wait time after last character typed before typeahead kicks-in + var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0; + + //should it restrict model values to the ones selected from the popup only? + var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false; + + //binding to a variable that indicates if matches are being retrieved asynchronously + var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop; + + //a callback executed when a match is selected + var onSelectCallback = $parse(attrs.typeaheadOnSelect); + + //should it select highlighted popup value when losing focus? + var isSelectOnBlur = angular.isDefined(attrs.typeaheadSelectOnBlur) ? originalScope.$eval(attrs.typeaheadSelectOnBlur) : false; + + //binding to a variable that indicates if there were no results after the query is completed + var isNoResultsSetter = $parse(attrs.typeaheadNoResults).assign || angular.noop; + + var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined; + + var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false; + + var appendToElementId = attrs.typeaheadAppendToElementId || false; + + var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false; + + //If input matches an item of the list exactly, select it automatically + var selectOnExact = attrs.typeaheadSelectOnExact ? originalScope.$eval(attrs.typeaheadSelectOnExact) : false; + + //INTERNAL VARIABLES + + //model setter executed upon match selection + var parsedModel = $parse(attrs.ngModel); + var invokeModelSetter = $parse(attrs.ngModel + '($$$p)'); + var $setModelValue = function(scope, newValue) { + if (angular.isFunction(parsedModel(originalScope)) && + ngModelOptions && ngModelOptions.$options && ngModelOptions.$options.getterSetter) { + return invokeModelSetter(scope, {$$$p: newValue}); + } else { + return parsedModel.assign(scope, newValue); + } + }; + + //expressions used by typeahead + var parserResult = typeaheadParser.parse(attrs.uibTypeahead); + + var hasFocus; + + //Used to avoid bug in iOS webview where iOS keyboard does not fire + //mousedown & mouseup events + //Issue #3699 + var selected; + + //create a child scope for the typeahead directive so we are not polluting original scope + //with typeahead-specific data (matches, query etc.) + var scope = originalScope.$new(); + var offDestroy = originalScope.$on('$destroy', function() { + scope.$destroy(); + }); + scope.$on('$destroy', offDestroy); + + // WAI-ARIA + var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000); + element.attr({ + 'aria-autocomplete': 'list', + 'aria-expanded': false, + 'aria-owns': popupId + }); + + //pop-up element used to display matches + var popUpEl = angular.element('
      '); + popUpEl.attr({ + id: popupId, + matches: 'matches', + active: 'activeIdx', + select: 'select(activeIdx)', + 'move-in-progress': 'moveInProgress', + query: 'query', + position: 'position' + }); + //custom item template + if (angular.isDefined(attrs.typeaheadTemplateUrl)) { + popUpEl.attr('template-url', attrs.typeaheadTemplateUrl); + } + + if (angular.isDefined(attrs.typeaheadPopupTemplateUrl)) { + popUpEl.attr('popup-template-url', attrs.typeaheadPopupTemplateUrl); + } + + var resetMatches = function() { + scope.matches = []; + scope.activeIdx = -1; + element.attr('aria-expanded', false); + }; + + var getMatchId = function(index) { + return popupId + '-option-' + index; + }; + + // Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead. + // This attribute is added or removed automatically when the `activeIdx` changes. + scope.$watch('activeIdx', function(index) { + if (index < 0) { + element.removeAttr('aria-activedescendant'); + } else { + element.attr('aria-activedescendant', getMatchId(index)); + } + }); + + var inputIsExactMatch = function(inputValue, index) { + if (scope.matches.length > index && inputValue) { + return inputValue.toUpperCase() === scope.matches[index].label.toUpperCase(); + } + + return false; + }; + + var getMatchesAsync = function(inputValue) { + var locals = {$viewValue: inputValue}; + isLoadingSetter(originalScope, true); + isNoResultsSetter(originalScope, false); + $q.when(parserResult.source(originalScope, locals)).then(function(matches) { + //it might happen that several async queries were in progress if a user were typing fast + //but we are interested only in responses that correspond to the current view value + var onCurrentRequest = (inputValue === modelCtrl.$viewValue); + if (onCurrentRequest && hasFocus) { + if (matches && matches.length > 0) { + scope.activeIdx = focusFirst ? 0 : -1; + isNoResultsSetter(originalScope, false); + scope.matches.length = 0; + + //transform labels + for (var i = 0; i < matches.length; i++) { + locals[parserResult.itemName] = matches[i]; + scope.matches.push({ + id: getMatchId(i), + label: parserResult.viewMapper(scope, locals), + model: matches[i] + }); + } + + scope.query = inputValue; + //position pop-up with matches - we need to re-calculate its position each time we are opening a window + //with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page + //due to other elements being rendered + recalculatePosition(); + + element.attr('aria-expanded', true); + + //Select the single remaining option if user input matches + if (selectOnExact && scope.matches.length === 1 && inputIsExactMatch(inputValue, 0)) { + scope.select(0); + } + } else { + resetMatches(); + isNoResultsSetter(originalScope, true); + } + } + if (onCurrentRequest) { + isLoadingSetter(originalScope, false); + } + }, function() { + resetMatches(); + isLoadingSetter(originalScope, false); + isNoResultsSetter(originalScope, true); + }); + }; + + // bind events only if appendToBody params exist - performance feature + if (appendToBody) { + angular.element($window).bind('resize', fireRecalculating); + $document.find('body').bind('scroll', fireRecalculating); + } + + // Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later + var timeoutEventPromise; + + // Default progress type + scope.moveInProgress = false; + + function fireRecalculating() { + if (!scope.moveInProgress) { + scope.moveInProgress = true; + scope.$digest(); + } + + // Cancel previous timeout + if (timeoutEventPromise) { + $timeout.cancel(timeoutEventPromise); + } + + // Debounced executing recalculate after events fired + timeoutEventPromise = $timeout(function() { + // if popup is visible + if (scope.matches.length) { + recalculatePosition(); + } + + scope.moveInProgress = false; + }, eventDebounceTime); + } + + // recalculate actual position and set new values to scope + // after digest loop is popup in right position + function recalculatePosition() { + scope.position = appendToBody ? $position.offset(element) : $position.position(element); + scope.position.top += element.prop('offsetHeight'); + } + + //we need to propagate user's query so we can higlight matches + scope.query = undefined; + + //Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later + var timeoutPromise; + + var scheduleSearchWithTimeout = function(inputValue) { + timeoutPromise = $timeout(function() { + getMatchesAsync(inputValue); + }, waitTime); + }; + + var cancelPreviousTimeout = function() { + if (timeoutPromise) { + $timeout.cancel(timeoutPromise); + } + }; + + resetMatches(); + + scope.select = function(activeIdx) { + //called from within the $digest() cycle + var locals = {}; + var model, item; + + selected = true; + locals[parserResult.itemName] = item = scope.matches[activeIdx].model; + model = parserResult.modelMapper(originalScope, locals); + $setModelValue(originalScope, model); + modelCtrl.$setValidity('editable', true); + modelCtrl.$setValidity('parse', true); + + onSelectCallback(originalScope, { + $item: item, + $model: model, + $label: parserResult.viewMapper(originalScope, locals) + }); + + resetMatches(); + + //return focus to the input element if a match was selected via a mouse click event + // use timeout to avoid $rootScope:inprog error + if (scope.$eval(attrs.typeaheadFocusOnSelect) !== false) { + $timeout(function() { element[0].focus(); }, 0, false); + } + }; + + //bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27) + element.bind('keydown', function(evt) { + //typeahead is open and an "interesting" key was pressed + if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) { + return; + } + + // if there's nothing selected (i.e. focusFirst) and enter or tab is hit, clear the results + if (scope.activeIdx === -1 && (evt.which === 9 || evt.which === 13)) { + resetMatches(); + scope.$digest(); + return; + } + + evt.preventDefault(); + + if (evt.which === 40) { + scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length; + scope.$digest(); + } else if (evt.which === 38) { + scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1; + scope.$digest(); + } else if (evt.which === 13 || evt.which === 9) { + scope.$apply(function () { + scope.select(scope.activeIdx); + }); + } else if (evt.which === 27) { + evt.stopPropagation(); + + resetMatches(); + scope.$digest(); + } + }); + + element.bind('blur', function() { + if (isSelectOnBlur && scope.matches.length && scope.activeIdx !== -1 && !selected) { + selected = true; + scope.$apply(function() { + scope.select(scope.activeIdx); + }); + } + hasFocus = false; + selected = false; + }); + + // Keep reference to click handler to unbind it. + var dismissClickHandler = function(evt) { + // Issue #3973 + // Firefox treats right click as a click on document + if (element[0] !== evt.target && evt.which !== 3 && scope.matches.length !== 0) { + resetMatches(); + if (!$rootScope.$$phase) { + scope.$digest(); + } + } + }; + + $document.bind('click', dismissClickHandler); + + originalScope.$on('$destroy', function() { + $document.unbind('click', dismissClickHandler); + if (appendToBody || appendToElementId) { + $popup.remove(); + } + + if (appendToBody) { + angular.element($window).unbind('resize', fireRecalculating); + $document.find('body').unbind('scroll', fireRecalculating); + } + // Prevent jQuery cache memory leak + popUpEl.remove(); + }); + + var $popup = $compile(popUpEl)(scope); + + if (appendToBody) { + $document.find('body').append($popup); + } else if (appendToElementId !== false) { + angular.element($document[0].getElementById(appendToElementId)).append($popup); + } else { + element.after($popup); + } + + this.init = function(_modelCtrl, _ngModelOptions) { + modelCtrl = _modelCtrl; + ngModelOptions = _ngModelOptions; + + //plug into $parsers pipeline to open a typeahead on view changes initiated from DOM + //$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue + modelCtrl.$parsers.unshift(function(inputValue) { + hasFocus = true; + + if (minLength === 0 || inputValue && inputValue.length >= minLength) { + if (waitTime > 0) { + cancelPreviousTimeout(); + scheduleSearchWithTimeout(inputValue); + } else { + getMatchesAsync(inputValue); + } + } else { + isLoadingSetter(originalScope, false); + cancelPreviousTimeout(); + resetMatches(); + } + + if (isEditable) { + return inputValue; + } else { + if (!inputValue) { + // Reset in case user had typed something previously. + modelCtrl.$setValidity('editable', true); + return null; + } else { + modelCtrl.$setValidity('editable', false); + return undefined; + } + } + }); + + modelCtrl.$formatters.push(function(modelValue) { + var candidateViewValue, emptyViewValue; + var locals = {}; + + // The validity may be set to false via $parsers (see above) if + // the model is restricted to selected values. If the model + // is set manually it is considered to be valid. + if (!isEditable) { + modelCtrl.$setValidity('editable', true); + } + + if (inputFormatter) { + locals.$model = modelValue; + return inputFormatter(originalScope, locals); + } else { + //it might happen that we don't have enough info to properly render input value + //we need to check for this situation and simply return model value if we can't apply custom formatting + locals[parserResult.itemName] = modelValue; + candidateViewValue = parserResult.viewMapper(originalScope, locals); + locals[parserResult.itemName] = undefined; + emptyViewValue = parserResult.viewMapper(originalScope, locals); + + return candidateViewValue !== emptyViewValue ? candidateViewValue : modelValue; + } + }); + }; + }]) + + .directive('uibTypeahead', function() { + return { + controller: 'UibTypeaheadController', + require: ['ngModel', '^?ngModelOptions', 'uibTypeahead'], + link: function(originalScope, element, attrs, ctrls) { + ctrls[2].init(ctrls[0], ctrls[1]); + } + }; + }) + + .directive('uibTypeaheadPopup', function() { + return { + scope: { + matches: '=', + query: '=', + active: '=', + position: '&', + moveInProgress: '=', + select: '&' + }, + replace: true, + templateUrl: function(element, attrs) { + return attrs.popupTemplateUrl || 'template/typeahead/typeahead-popup.html'; + }, + link: function(scope, element, attrs) { + scope.templateUrl = attrs.templateUrl; + + scope.isOpen = function() { + return scope.matches.length > 0; + }; + + scope.isActive = function(matchIdx) { + return scope.active == matchIdx; + }; + + scope.selectActive = function(matchIdx) { + scope.active = matchIdx; + }; + + scope.selectMatch = function(activeIdx) { + scope.select({activeIdx:activeIdx}); + }; + } + }; + }) + + .directive('uibTypeaheadMatch', ['$templateRequest', '$compile', '$parse', function($templateRequest, $compile, $parse) { + return { + scope: { + index: '=', + match: '=', + query: '=' + }, + link:function(scope, element, attrs) { + var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html'; + $templateRequest(tplUrl).then(function(tplContent) { + $compile(tplContent.trim())(scope, function(clonedElement) { + element.replaceWith(clonedElement); + }); + }); + } + }; + }]) + + .filter('uibTypeaheadHighlight', ['$sce', '$injector', '$log', function($sce, $injector, $log) { + var isSanitizePresent; + isSanitizePresent = $injector.has('$sanitize'); + + function escapeRegexp(queryToEscape) { + // Regex: capture the whole query string and replace it with the string that will be used to match + // the results, for example if the capture is "a" the result will be \a + return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); + } + + function containsHtml(matchItem) { + return /<.*>/g.test(matchItem); + } + + return function(matchItem, query) { + if (!isSanitizePresent && containsHtml(matchItem)) { + $log.warn('Unsafe use of typeahead please use ngSanitize'); // Warn the user about the danger + } + matchItem = query? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '$&') : matchItem; // Replaces the capture string with a the same string inside of a "strong" tag + if (!isSanitizePresent) { + matchItem = $sce.trustAsHtml(matchItem); // If $sanitize is not present we pack the string in a $sce object for the ng-bind-html directive + } + return matchItem; + }; + }]); + +/* Deprecated typeahead below */ + +angular.module('ui.bootstrap.typeahead') + .value('$typeaheadSuppressWarning', false) + .service('typeaheadParser', ['$parse', 'uibTypeaheadParser', '$log', '$typeaheadSuppressWarning', function($parse, uibTypeaheadParser, $log, $typeaheadSuppressWarning) { + if (!$typeaheadSuppressWarning) { + $log.warn('typeaheadParser is now deprecated. Use uibTypeaheadParser instead.'); + } + + return uibTypeaheadParser; + }]) + + .directive('typeahead', ['$compile', '$parse', '$q', '$timeout', '$document', '$window', '$rootScope', '$uibPosition', 'typeaheadParser', '$log', '$typeaheadSuppressWarning', + function($compile, $parse, $q, $timeout, $document, $window, $rootScope, $position, typeaheadParser, $log, $typeaheadSuppressWarning) { + var HOT_KEYS = [9, 13, 27, 38, 40]; + var eventDebounceTime = 200; + return { + require: ['ngModel', '^?ngModelOptions'], + link: function(originalScope, element, attrs, ctrls) { + if (!$typeaheadSuppressWarning) { + $log.warn('typeahead is now deprecated. Use uib-typeahead instead.'); + } + var modelCtrl = ctrls[0]; + var ngModelOptions = ctrls[1]; + //SUPPORTED ATTRIBUTES (OPTIONS) + + //minimal no of characters that needs to be entered before typeahead kicks-in + var minLength = originalScope.$eval(attrs.typeaheadMinLength); + if (!minLength && minLength !== 0) { + minLength = 1; + } + + //minimal wait time after last character typed before typeahead kicks-in + var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0; + + //should it restrict model values to the ones selected from the popup only? + var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false; + + //binding to a variable that indicates if matches are being retrieved asynchronously + var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop; + + //a callback executed when a match is selected + var onSelectCallback = $parse(attrs.typeaheadOnSelect); + + //should it select highlighted popup value when losing focus? + var isSelectOnBlur = angular.isDefined(attrs.typeaheadSelectOnBlur) ? originalScope.$eval(attrs.typeaheadSelectOnBlur) : false; + + //binding to a variable that indicates if there were no results after the query is completed + var isNoResultsSetter = $parse(attrs.typeaheadNoResults).assign || angular.noop; + + var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined; + + var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false; + + var appendToElementId = attrs.typeaheadAppendToElementId || false; + + var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false; + + //If input matches an item of the list exactly, select it automatically + var selectOnExact = attrs.typeaheadSelectOnExact ? originalScope.$eval(attrs.typeaheadSelectOnExact) : false; + + //INTERNAL VARIABLES + + //model setter executed upon match selection + var parsedModel = $parse(attrs.ngModel); + var invokeModelSetter = $parse(attrs.ngModel + '($$$p)'); + var $setModelValue = function(scope, newValue) { + if (angular.isFunction(parsedModel(originalScope)) && + ngModelOptions && ngModelOptions.$options && ngModelOptions.$options.getterSetter) { + return invokeModelSetter(scope, {$$$p: newValue}); + } else { + return parsedModel.assign(scope, newValue); + } + }; + + //expressions used by typeahead + var parserResult = typeaheadParser.parse(attrs.typeahead); + + var hasFocus; + + //Used to avoid bug in iOS webview where iOS keyboard does not fire + //mousedown & mouseup events + //Issue #3699 + var selected; + + //create a child scope for the typeahead directive so we are not polluting original scope + //with typeahead-specific data (matches, query etc.) + var scope = originalScope.$new(); + var offDestroy = originalScope.$on('$destroy', function() { + scope.$destroy(); + }); + scope.$on('$destroy', offDestroy); + + // WAI-ARIA + var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000); + element.attr({ + 'aria-autocomplete': 'list', + 'aria-expanded': false, + 'aria-owns': popupId + }); + + //pop-up element used to display matches + var popUpEl = angular.element('
      '); + popUpEl.attr({ + id: popupId, + matches: 'matches', + active: 'activeIdx', + select: 'select(activeIdx)', + 'move-in-progress': 'moveInProgress', + query: 'query', + position: 'position' + }); + //custom item template + if (angular.isDefined(attrs.typeaheadTemplateUrl)) { + popUpEl.attr('template-url', attrs.typeaheadTemplateUrl); + } + + if (angular.isDefined(attrs.typeaheadPopupTemplateUrl)) { + popUpEl.attr('popup-template-url', attrs.typeaheadPopupTemplateUrl); + } + + var resetMatches = function() { + scope.matches = []; + scope.activeIdx = -1; + element.attr('aria-expanded', false); + }; + + var getMatchId = function(index) { + return popupId + '-option-' + index; + }; + + // Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead. + // This attribute is added or removed automatically when the `activeIdx` changes. + scope.$watch('activeIdx', function(index) { + if (index < 0) { + element.removeAttr('aria-activedescendant'); + } else { + element.attr('aria-activedescendant', getMatchId(index)); + } + }); + + var inputIsExactMatch = function(inputValue, index) { + if (scope.matches.length > index && inputValue) { + return inputValue.toUpperCase() === scope.matches[index].label.toUpperCase(); + } + + return false; + }; + + var getMatchesAsync = function(inputValue) { + var locals = {$viewValue: inputValue}; + isLoadingSetter(originalScope, true); + isNoResultsSetter(originalScope, false); + $q.when(parserResult.source(originalScope, locals)).then(function(matches) { + //it might happen that several async queries were in progress if a user were typing fast + //but we are interested only in responses that correspond to the current view value + var onCurrentRequest = (inputValue === modelCtrl.$viewValue); + if (onCurrentRequest && hasFocus) { + if (matches && matches.length > 0) { + scope.activeIdx = focusFirst ? 0 : -1; + isNoResultsSetter(originalScope, false); + scope.matches.length = 0; + + //transform labels + for (var i = 0; i < matches.length; i++) { + locals[parserResult.itemName] = matches[i]; + scope.matches.push({ + id: getMatchId(i), + label: parserResult.viewMapper(scope, locals), + model: matches[i] + }); + } + + scope.query = inputValue; + //position pop-up with matches - we need to re-calculate its position each time we are opening a window + //with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page + //due to other elements being rendered + recalculatePosition(); + + element.attr('aria-expanded', true); + + //Select the single remaining option if user input matches + if (selectOnExact && scope.matches.length === 1 && inputIsExactMatch(inputValue, 0)) { + scope.select(0); + } + } else { + resetMatches(); + isNoResultsSetter(originalScope, true); + } + } + if (onCurrentRequest) { + isLoadingSetter(originalScope, false); + } + }, function() { + resetMatches(); + isLoadingSetter(originalScope, false); + isNoResultsSetter(originalScope, true); + }); + }; + + // bind events only if appendToBody params exist - performance feature + if (appendToBody) { + angular.element($window).bind('resize', fireRecalculating); + $document.find('body').bind('scroll', fireRecalculating); + } + + // Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later + var timeoutEventPromise; + + // Default progress type + scope.moveInProgress = false; + + function fireRecalculating() { + if (!scope.moveInProgress) { + scope.moveInProgress = true; + scope.$digest(); + } + + // Cancel previous timeout + if (timeoutEventPromise) { + $timeout.cancel(timeoutEventPromise); + } + + // Debounced executing recalculate after events fired + timeoutEventPromise = $timeout(function() { + // if popup is visible + if (scope.matches.length) { + recalculatePosition(); + } + + scope.moveInProgress = false; + }, eventDebounceTime); + } + + // recalculate actual position and set new values to scope + // after digest loop is popup in right position + function recalculatePosition() { + scope.position = appendToBody ? $position.offset(element) : $position.position(element); + scope.position.top += element.prop('offsetHeight'); + } + + resetMatches(); + + //we need to propagate user's query so we can higlight matches + scope.query = undefined; + + //Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later + var timeoutPromise; + + var scheduleSearchWithTimeout = function(inputValue) { + timeoutPromise = $timeout(function() { + getMatchesAsync(inputValue); + }, waitTime); + }; + + var cancelPreviousTimeout = function() { + if (timeoutPromise) { + $timeout.cancel(timeoutPromise); + } + }; + + //plug into $parsers pipeline to open a typeahead on view changes initiated from DOM + //$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue + modelCtrl.$parsers.unshift(function(inputValue) { + hasFocus = true; + + if (minLength === 0 || inputValue && inputValue.length >= minLength) { + if (waitTime > 0) { + cancelPreviousTimeout(); + scheduleSearchWithTimeout(inputValue); + } else { + getMatchesAsync(inputValue); + } + } else { + isLoadingSetter(originalScope, false); + cancelPreviousTimeout(); + resetMatches(); + } + + if (isEditable) { + return inputValue; + } else { + if (!inputValue) { + // Reset in case user had typed something previously. + modelCtrl.$setValidity('editable', true); + return null; + } else { + modelCtrl.$setValidity('editable', false); + return undefined; + } + } + }); + + modelCtrl.$formatters.push(function(modelValue) { + var candidateViewValue, emptyViewValue; + var locals = {}; + + // The validity may be set to false via $parsers (see above) if + // the model is restricted to selected values. If the model + // is set manually it is considered to be valid. + if (!isEditable) { + modelCtrl.$setValidity('editable', true); + } + + if (inputFormatter) { + locals.$model = modelValue; + return inputFormatter(originalScope, locals); + } else { + //it might happen that we don't have enough info to properly render input value + //we need to check for this situation and simply return model value if we can't apply custom formatting + locals[parserResult.itemName] = modelValue; + candidateViewValue = parserResult.viewMapper(originalScope, locals); + locals[parserResult.itemName] = undefined; + emptyViewValue = parserResult.viewMapper(originalScope, locals); + + return candidateViewValue !== emptyViewValue ? candidateViewValue : modelValue; + } + }); + + scope.select = function(activeIdx) { + //called from within the $digest() cycle + var locals = {}; + var model, item; + + selected = true; + locals[parserResult.itemName] = item = scope.matches[activeIdx].model; + model = parserResult.modelMapper(originalScope, locals); + $setModelValue(originalScope, model); + modelCtrl.$setValidity('editable', true); + modelCtrl.$setValidity('parse', true); + + onSelectCallback(originalScope, { + $item: item, + $model: model, + $label: parserResult.viewMapper(originalScope, locals) + }); + + resetMatches(); + + //return focus to the input element if a match was selected via a mouse click event + // use timeout to avoid $rootScope:inprog error + if (scope.$eval(attrs.typeaheadFocusOnSelect) !== false) { + $timeout(function() { element[0].focus(); }, 0, false); + } + }; + + //bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27) + element.bind('keydown', function(evt) { + //typeahead is open and an "interesting" key was pressed + if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) { + return; + } + + // if there's nothing selected (i.e. focusFirst) and enter or tab is hit, clear the results + if (scope.activeIdx === -1 && (evt.which === 9 || evt.which === 13)) { + resetMatches(); + scope.$digest(); + return; + } + + evt.preventDefault(); + + if (evt.which === 40) { + scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length; + scope.$digest(); + } else if (evt.which === 38) { + scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1; + scope.$digest(); + } else if (evt.which === 13 || evt.which === 9) { + scope.$apply(function () { + scope.select(scope.activeIdx); + }); + } else if (evt.which === 27) { + evt.stopPropagation(); + + resetMatches(); + scope.$digest(); + } + }); + + element.bind('blur', function() { + if (isSelectOnBlur && scope.matches.length && scope.activeIdx !== -1 && !selected) { + selected = true; + scope.$apply(function() { + scope.select(scope.activeIdx); + }); + } + hasFocus = false; + selected = false; + }); + + // Keep reference to click handler to unbind it. + var dismissClickHandler = function(evt) { + // Issue #3973 + // Firefox treats right click as a click on document + if (element[0] !== evt.target && evt.which !== 3 && scope.matches.length !== 0) { + resetMatches(); + if (!$rootScope.$$phase) { + scope.$digest(); + } + } + }; + + $document.bind('click', dismissClickHandler); + + originalScope.$on('$destroy', function() { + $document.unbind('click', dismissClickHandler); + if (appendToBody || appendToElementId) { + $popup.remove(); + } + + if (appendToBody) { + angular.element($window).unbind('resize', fireRecalculating); + $document.find('body').unbind('scroll', fireRecalculating); + } + // Prevent jQuery cache memory leak + popUpEl.remove(); + }); + + var $popup = $compile(popUpEl)(scope); + + if (appendToBody) { + $document.find('body').append($popup); + } else if (appendToElementId !== false) { + angular.element($document[0].getElementById(appendToElementId)).append($popup); + } else { + element.after($popup); + } + } + }; + }]) + + .directive('typeaheadPopup', ['$typeaheadSuppressWarning', '$log', function($typeaheadSuppressWarning, $log) { + return { + scope: { + matches: '=', + query: '=', + active: '=', + position: '&', + moveInProgress: '=', + select: '&' + }, + replace: true, + templateUrl: function(element, attrs) { + return attrs.popupTemplateUrl || 'template/typeahead/typeahead-popup.html'; + }, + link: function(scope, element, attrs) { + + if (!$typeaheadSuppressWarning) { + $log.warn('typeahead-popup is now deprecated. Use uib-typeahead-popup instead.'); + } + scope.templateUrl = attrs.templateUrl; + + scope.isOpen = function() { + return scope.matches.length > 0; + }; + + scope.isActive = function(matchIdx) { + return scope.active == matchIdx; + }; + + scope.selectActive = function(matchIdx) { + scope.active = matchIdx; + }; + + scope.selectMatch = function(activeIdx) { + scope.select({activeIdx:activeIdx}); + }; + } + }; + }]) + + .directive('typeaheadMatch', ['$templateRequest', '$compile', '$parse', '$typeaheadSuppressWarning', '$log', function($templateRequest, $compile, $parse, $typeaheadSuppressWarning, $log) { + return { + restrict: 'EA', + scope: { + index: '=', + match: '=', + query: '=' + }, + link:function(scope, element, attrs) { + if (!$typeaheadSuppressWarning) { + $log.warn('typeahead-match is now deprecated. Use uib-typeahead-match instead.'); + } + + var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html'; + $templateRequest(tplUrl).then(function(tplContent) { + $compile(tplContent.trim())(scope, function(clonedElement) { + element.replaceWith(clonedElement); + }); + }); + } + }; + }]) + + .filter('typeaheadHighlight', ['$sce', '$injector', '$log', '$typeaheadSuppressWarning', function($sce, $injector, $log, $typeaheadSuppressWarning) { + var isSanitizePresent; + isSanitizePresent = $injector.has('$sanitize'); + + function escapeRegexp(queryToEscape) { + // Regex: capture the whole query string and replace it with the string that will be used to match + // the results, for example if the capture is "a" the result will be \a + return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); + } + + function containsHtml(matchItem) { + return /<.*>/g.test(matchItem); + } + + return function(matchItem, query) { + if (!$typeaheadSuppressWarning) { + $log.warn('typeaheadHighlight is now deprecated. Use uibTypeaheadHighlight instead.'); + } + + if (!isSanitizePresent && containsHtml(matchItem)) { + $log.warn('Unsafe use of typeahead please use ngSanitize'); // Warn the user about the danger + } + + matchItem = query? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '$&') : matchItem; // Replaces the capture string with a the same string inside of a "strong" tag + if (!isSanitizePresent) { + matchItem = $sce.trustAsHtml(matchItem); // If $sanitize is not present we pack the string in a $sce object for the ng-bind-html directive + } + + return matchItem; + }; + }]); +!angular.$$csp() && angular.element(document).find('head').prepend(''); \ No newline at end of file diff --git a/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-bootstrap/ui-bootstrap.min.js b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-bootstrap/ui-bootstrap.min.js new file mode 100644 index 00000000..cbabc328 --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-bootstrap/ui-bootstrap.min.js @@ -0,0 +1,11 @@ +/* + * angular-ui-bootstrap + * http://angular-ui.github.io/bootstrap/ + + * Version: 0.14.3 - 2015-10-23 + * License: MIT + */ +angular.module("ui.bootstrap",["ui.bootstrap.collapse","ui.bootstrap.accordion","ui.bootstrap.alert","ui.bootstrap.buttons","ui.bootstrap.carousel","ui.bootstrap.dateparser","ui.bootstrap.position","ui.bootstrap.datepicker","ui.bootstrap.dropdown","ui.bootstrap.stackedMap","ui.bootstrap.modal","ui.bootstrap.pagination","ui.bootstrap.tooltip","ui.bootstrap.popover","ui.bootstrap.progressbar","ui.bootstrap.rating","ui.bootstrap.tabs","ui.bootstrap.timepicker","ui.bootstrap.typeahead"]),angular.module("ui.bootstrap.collapse",[]).directive("uibCollapse",["$animate","$injector",function(a,b){var c=b.has("$animateCss")?b.get("$animateCss"):null;return{link:function(b,d,e){function f(){d.removeClass("collapse").addClass("collapsing").attr("aria-expanded",!0).attr("aria-hidden",!1),c?c(d,{addClass:"in",easing:"ease",to:{height:d[0].scrollHeight+"px"}}).start()["finally"](g):a.addClass(d,"in",{to:{height:d[0].scrollHeight+"px"}}).then(g)}function g(){d.removeClass("collapsing").addClass("collapse").css({height:"auto"})}function h(){return d.hasClass("collapse")||d.hasClass("in")?(d.css({height:d[0].scrollHeight+"px"}).removeClass("collapse").addClass("collapsing").attr("aria-expanded",!1).attr("aria-hidden",!0),void(c?c(d,{removeClass:"in",to:{height:"0"}}).start()["finally"](i):a.removeClass(d,"in",{to:{height:"0"}}).then(i))):i()}function i(){d.css({height:"0"}),d.removeClass("collapsing").addClass("collapse")}b.$watch(e.uibCollapse,function(a){a?h():f()})}}}]),angular.module("ui.bootstrap.collapse").value("$collapseSuppressWarning",!1).directive("collapse",["$animate","$injector","$log","$collapseSuppressWarning",function(a,b,c,d){var e=b.has("$animateCss")?b.get("$animateCss"):null;return{link:function(b,f,g){function h(){f.removeClass("collapse").addClass("collapsing").attr("aria-expanded",!0).attr("aria-hidden",!1),e?e(f,{easing:"ease",to:{height:f[0].scrollHeight+"px"}}).start().done(i):a.animate(f,{},{height:f[0].scrollHeight+"px"}).then(i)}function i(){f.removeClass("collapsing").addClass("collapse in").css({height:"auto"})}function j(){return f.hasClass("collapse")||f.hasClass("in")?(f.css({height:f[0].scrollHeight+"px"}).removeClass("collapse in").addClass("collapsing").attr("aria-expanded",!1).attr("aria-hidden",!0),void(e?e(f,{to:{height:"0"}}).start().done(k):a.animate(f,{},{height:"0"}).then(k))):k()}function k(){f.css({height:"0"}),f.removeClass("collapsing").addClass("collapse")}d||c.warn("collapse is now deprecated. Use uib-collapse instead."),b.$watch(g.collapse,function(a){a?j():h()})}}}]),angular.module("ui.bootstrap.accordion",["ui.bootstrap.collapse"]).constant("uibAccordionConfig",{closeOthers:!0}).controller("UibAccordionController",["$scope","$attrs","uibAccordionConfig",function(a,b,c){this.groups=[],this.closeOthers=function(d){var e=angular.isDefined(b.closeOthers)?a.$eval(b.closeOthers):c.closeOthers;e&&angular.forEach(this.groups,function(a){a!==d&&(a.isOpen=!1)})},this.addGroup=function(a){var b=this;this.groups.push(a),a.$on("$destroy",function(c){b.removeGroup(a)})},this.removeGroup=function(a){var b=this.groups.indexOf(a);-1!==b&&this.groups.splice(b,1)}}]).directive("uibAccordion",function(){return{controller:"UibAccordionController",controllerAs:"accordion",transclude:!0,templateUrl:function(a,b){return b.templateUrl||"template/accordion/accordion.html"}}}).directive("uibAccordionGroup",function(){return{require:"^uibAccordion",transclude:!0,replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/accordion/accordion-group.html"},scope:{heading:"@",isOpen:"=?",isDisabled:"=?"},controller:function(){this.setHeading=function(a){this.heading=a}},link:function(a,b,c,d){d.addGroup(a),a.openClass=c.openClass||"panel-open",a.panelClass=c.panelClass,a.$watch("isOpen",function(c){b.toggleClass(a.openClass,!!c),c&&d.closeOthers(a)}),a.toggleOpen=function(b){a.isDisabled||b&&32!==b.which||(a.isOpen=!a.isOpen)}}}}).directive("uibAccordionHeading",function(){return{transclude:!0,template:"",replace:!0,require:"^uibAccordionGroup",link:function(a,b,c,d,e){d.setHeading(e(a,angular.noop))}}}).directive("uibAccordionTransclude",function(){return{require:["?^uibAccordionGroup","?^accordionGroup"],link:function(a,b,c,d){d=d[0]?d[0]:d[1],a.$watch(function(){return d[c.uibAccordionTransclude]},function(a){a&&(b.find("span").html(""),b.find("span").append(a))})}}}),angular.module("ui.bootstrap.accordion").value("$accordionSuppressWarning",!1).controller("AccordionController",["$scope","$attrs","$controller","$log","$accordionSuppressWarning",function(a,b,c,d,e){e||d.warn("AccordionController is now deprecated. Use UibAccordionController instead."),angular.extend(this,c("UibAccordionController",{$scope:a,$attrs:b}))}]).directive("accordion",["$log","$accordionSuppressWarning",function(a,b){return{restrict:"EA",controller:"AccordionController",controllerAs:"accordion",transclude:!0,replace:!1,templateUrl:function(a,b){return b.templateUrl||"template/accordion/accordion.html"},link:function(){b||a.warn("accordion is now deprecated. Use uib-accordion instead.")}}}]).directive("accordionGroup",["$log","$accordionSuppressWarning",function(a,b){return{require:"^accordion",restrict:"EA",transclude:!0,replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/accordion/accordion-group.html"},scope:{heading:"@",isOpen:"=?",isDisabled:"=?"},controller:function(){this.setHeading=function(a){this.heading=a}},link:function(c,d,e,f){b||a.warn("accordion-group is now deprecated. Use uib-accordion-group instead."),f.addGroup(c),c.openClass=e.openClass||"panel-open",c.panelClass=e.panelClass,c.$watch("isOpen",function(a){d.toggleClass(c.openClass,!!a),a&&f.closeOthers(c)}),c.toggleOpen=function(a){c.isDisabled||a&&32!==a.which||(c.isOpen=!c.isOpen)}}}}]).directive("accordionHeading",["$log","$accordionSuppressWarning",function(a,b){return{restrict:"EA",transclude:!0,template:"",replace:!0,require:"^accordionGroup",link:function(c,d,e,f,g){b||a.warn("accordion-heading is now deprecated. Use uib-accordion-heading instead."),f.setHeading(g(c,angular.noop))}}}]).directive("accordionTransclude",["$log","$accordionSuppressWarning",function(a,b){return{require:"^accordionGroup",link:function(c,d,e,f){b||a.warn("accordion-transclude is now deprecated. Use uib-accordion-transclude instead."),c.$watch(function(){return f[e.accordionTransclude]},function(a){a&&(d.find("span").html(""),d.find("span").append(a))})}}}]),angular.module("ui.bootstrap.alert",[]).controller("UibAlertController",["$scope","$attrs","$interpolate","$timeout",function(a,b,c,d){a.closeable=!!b.close;var e=angular.isDefined(b.dismissOnTimeout)?c(b.dismissOnTimeout)(a.$parent):null;e&&d(function(){a.close()},parseInt(e,10))}]).directive("uibAlert",function(){return{controller:"UibAlertController",controllerAs:"alert",templateUrl:function(a,b){return b.templateUrl||"template/alert/alert.html"},transclude:!0,replace:!0,scope:{type:"@",close:"&"}}}),angular.module("ui.bootstrap.alert").value("$alertSuppressWarning",!1).controller("AlertController",["$scope","$attrs","$controller","$log","$alertSuppressWarning",function(a,b,c,d,e){e||d.warn("AlertController is now deprecated. Use UibAlertController instead."),angular.extend(this,c("UibAlertController",{$scope:a,$attrs:b}))}]).directive("alert",["$log","$alertSuppressWarning",function(a,b){return{controller:"AlertController",controllerAs:"alert",templateUrl:function(a,b){return b.templateUrl||"template/alert/alert.html"},transclude:!0,replace:!0,scope:{type:"@",close:"&"},link:function(){b||a.warn("alert is now deprecated. Use uib-alert instead.")}}}]),angular.module("ui.bootstrap.buttons",[]).constant("uibButtonConfig",{activeClass:"active",toggleEvent:"click"}).controller("UibButtonsController",["uibButtonConfig",function(a){this.activeClass=a.activeClass||"active",this.toggleEvent=a.toggleEvent||"click"}]).directive("uibBtnRadio",function(){return{require:["uibBtnRadio","ngModel"],controller:"UibButtonsController",controllerAs:"buttons",link:function(a,b,c,d){var e=d[0],f=d[1];b.find("input").css({display:"none"}),f.$render=function(){b.toggleClass(e.activeClass,angular.equals(f.$modelValue,a.$eval(c.uibBtnRadio)))},b.on(e.toggleEvent,function(){if(!c.disabled){var d=b.hasClass(e.activeClass);(!d||angular.isDefined(c.uncheckable))&&a.$apply(function(){f.$setViewValue(d?null:a.$eval(c.uibBtnRadio)),f.$render()})}})}}}).directive("uibBtnCheckbox",function(){return{require:["uibBtnCheckbox","ngModel"],controller:"UibButtonsController",controllerAs:"button",link:function(a,b,c,d){function e(){return g(c.btnCheckboxTrue,!0)}function f(){return g(c.btnCheckboxFalse,!1)}function g(b,c){return angular.isDefined(b)?a.$eval(b):c}var h=d[0],i=d[1];b.find("input").css({display:"none"}),i.$render=function(){b.toggleClass(h.activeClass,angular.equals(i.$modelValue,e()))},b.on(h.toggleEvent,function(){c.disabled||a.$apply(function(){i.$setViewValue(b.hasClass(h.activeClass)?f():e()),i.$render()})})}}}),angular.module("ui.bootstrap.buttons").value("$buttonsSuppressWarning",!1).controller("ButtonsController",["$controller","$log","$buttonsSuppressWarning",function(a,b,c){c||b.warn("ButtonsController is now deprecated. Use UibButtonsController instead."),angular.extend(this,a("UibButtonsController"))}]).directive("btnRadio",["$log","$buttonsSuppressWarning",function(a,b){return{require:["btnRadio","ngModel"],controller:"ButtonsController",controllerAs:"buttons",link:function(c,d,e,f){b||a.warn("btn-radio is now deprecated. Use uib-btn-radio instead.");var g=f[0],h=f[1];d.find("input").css({display:"none"}),h.$render=function(){d.toggleClass(g.activeClass,angular.equals(h.$modelValue,c.$eval(e.btnRadio)))},d.bind(g.toggleEvent,function(){if(!e.disabled){var a=d.hasClass(g.activeClass);(!a||angular.isDefined(e.uncheckable))&&c.$apply(function(){h.$setViewValue(a?null:c.$eval(e.btnRadio)),h.$render()})}})}}}]).directive("btnCheckbox",["$document","$log","$buttonsSuppressWarning",function(a,b,c){return{require:["btnCheckbox","ngModel"],controller:"ButtonsController",controllerAs:"button",link:function(d,e,f,g){function h(){return j(f.btnCheckboxTrue,!0)}function i(){return j(f.btnCheckboxFalse,!1)}function j(a,b){var c=d.$eval(a);return angular.isDefined(c)?c:b}c||b.warn("btn-checkbox is now deprecated. Use uib-btn-checkbox instead.");var k=g[0],l=g[1];e.find("input").css({display:"none"}),l.$render=function(){e.toggleClass(k.activeClass,angular.equals(l.$modelValue,h()))},e.bind(k.toggleEvent,function(){f.disabled||d.$apply(function(){l.$setViewValue(e.hasClass(k.activeClass)?i():h()),l.$render()})}),e.on("keypress",function(b){f.disabled||32!==b.which||a[0].activeElement!==e[0]||d.$apply(function(){l.$setViewValue(e.hasClass(k.activeClass)?i():h()),l.$render()})})}}}]),angular.module("ui.bootstrap.carousel",[]).controller("UibCarouselController",["$scope","$element","$interval","$animate",function(a,b,c,d){function e(b,c,e){s||(angular.extend(b,{direction:e,active:!0}),angular.extend(m.currentSlide||{},{direction:e,active:!1}),d.enabled()&&!a.noTransition&&!a.$currentTransition&&b.$element&&m.slides.length>1&&(b.$element.data(q,b.direction),m.currentSlide&&m.currentSlide.$element&&m.currentSlide.$element.data(q,b.direction),a.$currentTransition=!0,o?d.on("addClass",b.$element,function(b,c){"close"===c&&(a.$currentTransition=null,d.off("addClass",b))}):b.$element.one("$animate:close",function(){a.$currentTransition=null})),m.currentSlide=b,r=c,g())}function f(a){if(angular.isUndefined(n[a].index))return n[a];var b;n.length;for(b=0;b0&&(k=c(i,b))}function h(){k&&(c.cancel(k),k=null)}function i(){var b=+a.interval;l&&!isNaN(b)&&b>0&&n.length?a.next():a.pause()}function j(b){b.length||(a.$currentTransition=null)}var k,l,m=this,n=m.slides=a.slides=[],o=angular.version.minor>=4,p="uib-noTransition",q="uib-slideDirection",r=-1;m.currentSlide=null;var s=!1;m.select=a.select=function(b,c){var d=a.indexOfSlide(b);void 0===c&&(c=d>m.getCurrentIndex()?"next":"prev"),b&&b!==m.currentSlide&&!a.$currentTransition&&e(b,d,c)},a.$on("$destroy",function(){s=!0}),m.getCurrentIndex=function(){return m.currentSlide&&angular.isDefined(m.currentSlide.index)?+m.currentSlide.index:r},a.indexOfSlide=function(a){return angular.isDefined(a.index)?+a.index:n.indexOf(a)},a.next=function(){var b=(m.getCurrentIndex()+1)%n.length;return 0===b&&a.noWrap()?void a.pause():m.select(f(b),"next")},a.prev=function(){var b=m.getCurrentIndex()-1<0?n.length-1:m.getCurrentIndex()-1;return a.noWrap()&&b===n.length-1?void a.pause():m.select(f(b),"prev")},a.isActive=function(a){return m.currentSlide===a},a.$watch("interval",g),a.$watchCollection("slides",j),a.$on("$destroy",h),a.play=function(){l||(l=!0,g())},a.pause=function(){a.noPause||(l=!1,h())},m.addSlide=function(b,c){b.$element=c,n.push(b),1===n.length||b.active?(m.select(n[n.length-1]),1===n.length&&a.play()):b.active=!1},m.removeSlide=function(a){angular.isDefined(a.index)&&n.sort(function(a,b){return+a.index>+b.index});var b=n.indexOf(a);n.splice(b,1),n.length>0&&a.active?b>=n.length?m.select(n[b-1]):m.select(n[b]):r>b&&r--,0===n.length&&(m.currentSlide=null)},a.$watch("noTransition",function(a){b.data(p,a)})}]).directive("uibCarousel",[function(){return{transclude:!0,replace:!0,controller:"UibCarouselController",controllerAs:"carousel",require:"carousel",templateUrl:function(a,b){return b.templateUrl||"template/carousel/carousel.html"},scope:{interval:"=",noTransition:"=",noPause:"=",noWrap:"&"}}}]).directive("uibSlide",function(){return{require:"^uibCarousel",restrict:"EA",transclude:!0,replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/carousel/slide.html"},scope:{active:"=?",actual:"=?",index:"=?"},link:function(a,b,c,d){d.addSlide(a,b),a.$on("$destroy",function(){d.removeSlide(a)}),a.$watch("active",function(b){b&&d.select(a)})}}}).animation(".item",["$injector","$animate",function(a,b){function c(a,b,c){a.removeClass(b),c&&c()}var d="uib-noTransition",e="uib-slideDirection",f=null;return a.has("$animateCss")&&(f=a.get("$animateCss")),{beforeAddClass:function(a,g,h){if("active"==g&&a.parent()&&a.parent().parent()&&!a.parent().parent().data(d)){var i=!1,j=a.data(e),k="next"==j?"left":"right",l=c.bind(this,a,k+" "+j,h);return a.addClass(j),f?f(a,{addClass:k}).start().done(l):b.addClass(a,k).then(function(){i||l(),h()}),function(){i=!0}}h()},beforeRemoveClass:function(a,g,h){if("active"===g&&a.parent()&&a.parent().parent()&&!a.parent().parent().data(d)){var i=!1,j=a.data(e),k="next"==j?"left":"right",l=c.bind(this,a,k,h);return f?f(a,{addClass:k}).start().done(l):b.addClass(a,k).then(function(){i||l(),h()}),function(){i=!0}}h()}}}]),angular.module("ui.bootstrap.carousel").value("$carouselSuppressWarning",!1).controller("CarouselController",["$scope","$element","$controller","$log","$carouselSuppressWarning",function(a,b,c,d,e){e||d.warn("CarouselController is now deprecated. Use UibCarouselController instead."),angular.extend(this,c("UibCarouselController",{$scope:a,$element:b}))}]).directive("carousel",["$log","$carouselSuppressWarning",function(a,b){return{transclude:!0,replace:!0,controller:"CarouselController",controllerAs:"carousel",require:"carousel",templateUrl:function(a,b){return b.templateUrl||"template/carousel/carousel.html"},scope:{interval:"=",noTransition:"=",noPause:"=",noWrap:"&"},link:function(){b||a.warn("carousel is now deprecated. Use uib-carousel instead.")}}}]).directive("slide",["$log","$carouselSuppressWarning",function(a,b){return{require:"^carousel",transclude:!0,replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/carousel/slide.html"},scope:{active:"=?",actual:"=?",index:"=?"},link:function(c,d,e,f){b||a.warn("slide is now deprecated. Use uib-slide instead."),f.addSlide(c,d),c.$on("$destroy",function(){f.removeSlide(c)}),c.$watch("active",function(a){a&&f.select(c)})}}}]),angular.module("ui.bootstrap.dateparser",[]).service("uibDateParser",["$log","$locale","orderByFilter",function(a,b,c){function d(a){var b=[],d=a.split("");return angular.forEach(g,function(c,e){var f=a.indexOf(e);if(f>-1){a=a.split(""),d[f]="("+c.regex+")",a[f]="$";for(var g=f+1,h=f+e.length;h>g;g++)d[g]="",a[g]="$";a=a.join(""),b.push({index:f,apply:c.apply})}}),{regex:new RegExp("^"+d.join("")+"$"),map:c(b,"index")}}function e(a,b,c){return 1>c?!1:1===b&&c>28?29===c&&(a%4===0&&a%100!==0||a%400===0):3===b||5===b||8===b||10===b?31>c:!0}var f,g,h=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;this.init=function(){f=b.id,this.parsers={},g={yyyy:{regex:"\\d{4}",apply:function(a){this.year=+a}},yy:{regex:"\\d{2}",apply:function(a){this.year=+a+2e3}},y:{regex:"\\d{1,4}",apply:function(a){this.year=+a}},MMMM:{regex:b.DATETIME_FORMATS.MONTH.join("|"),apply:function(a){this.month=b.DATETIME_FORMATS.MONTH.indexOf(a)}},MMM:{regex:b.DATETIME_FORMATS.SHORTMONTH.join("|"),apply:function(a){this.month=b.DATETIME_FORMATS.SHORTMONTH.indexOf(a)}},MM:{regex:"0[1-9]|1[0-2]",apply:function(a){this.month=a-1}},M:{regex:"[1-9]|1[0-2]",apply:function(a){this.month=a-1}},dd:{regex:"[0-2][0-9]{1}|3[0-1]{1}",apply:function(a){this.date=+a}},d:{regex:"[1-2]?[0-9]{1}|3[0-1]{1}",apply:function(a){this.date=+a}},EEEE:{regex:b.DATETIME_FORMATS.DAY.join("|")},EEE:{regex:b.DATETIME_FORMATS.SHORTDAY.join("|")},HH:{regex:"(?:0|1)[0-9]|2[0-3]",apply:function(a){this.hours=+a}},hh:{regex:"0[0-9]|1[0-2]",apply:function(a){this.hours=+a}},H:{regex:"1?[0-9]|2[0-3]",apply:function(a){this.hours=+a}},h:{regex:"[0-9]|1[0-2]",apply:function(a){this.hours=+a}},mm:{regex:"[0-5][0-9]",apply:function(a){this.minutes=+a}},m:{regex:"[0-9]|[1-5][0-9]",apply:function(a){this.minutes=+a}},sss:{regex:"[0-9][0-9][0-9]",apply:function(a){this.milliseconds=+a}},ss:{regex:"[0-5][0-9]",apply:function(a){this.seconds=+a}},s:{regex:"[0-9]|[1-5][0-9]",apply:function(a){this.seconds=+a}},a:{regex:b.DATETIME_FORMATS.AMPMS.join("|"),apply:function(a){12===this.hours&&(this.hours=0),"PM"===a&&(this.hours+=12)}}}},this.init(),this.parse=function(c,g,i){if(!angular.isString(c)||!g)return c;g=b.DATETIME_FORMATS[g]||g,g=g.replace(h,"\\$&"),b.id!==f&&this.init(),this.parsers[g]||(this.parsers[g]=d(g));var j=this.parsers[g],k=j.regex,l=j.map,m=c.match(k);if(m&&m.length){var n,o;angular.isDate(i)&&!isNaN(i.getTime())?n={year:i.getFullYear(),month:i.getMonth(),date:i.getDate(),hours:i.getHours(),minutes:i.getMinutes(),seconds:i.getSeconds(),milliseconds:i.getMilliseconds()}:(i&&a.warn("dateparser:","baseDate is not a valid date"),n={year:1900,month:0,date:1,hours:0,minutes:0,seconds:0,milliseconds:0});for(var p=1,q=m.length;q>p;p++){var r=l[p-1];r.apply&&r.apply.call(n,m[p])}return e(n.year,n.month,n.date)&&(angular.isDate(i)&&!isNaN(i.getTime())?(o=new Date(i),o.setFullYear(n.year,n.month,n.date,n.hours,n.minutes,n.seconds,n.milliseconds||0)):o=new Date(n.year,n.month,n.date,n.hours,n.minutes,n.seconds,n.milliseconds||0)),o}}}]),angular.module("ui.bootstrap.dateparser").value("$dateParserSuppressWarning",!1).service("dateParser",["$log","$dateParserSuppressWarning","uibDateParser",function(a,b,c){b||a.warn("dateParser is now deprecated. Use uibDateParser instead."),angular.extend(this,c)}]),angular.module("ui.bootstrap.position",[]).factory("$uibPosition",["$document","$window",function(a,b){function c(a,c){return a.currentStyle?a.currentStyle[c]:b.getComputedStyle?b.getComputedStyle(a)[c]:a.style[c]}function d(a){return"static"===(c(a,"position")||"static")}var e=function(b){for(var c=a[0],e=b.offsetParent||c;e&&e!==c&&d(e);)e=e.offsetParent;return e||c};return{position:function(b){var c=this.offset(b),d={top:0,left:0},f=e(b[0]);f!=a[0]&&(d=this.offset(angular.element(f)),d.top+=f.clientTop-f.scrollTop,d.left+=f.clientLeft-f.scrollLeft);var g=b[0].getBoundingClientRect();return{width:g.width||b.prop("offsetWidth"),height:g.height||b.prop("offsetHeight"),top:c.top-d.top,left:c.left-d.left}},offset:function(c){var d=c[0].getBoundingClientRect();return{width:d.width||c.prop("offsetWidth"),height:d.height||c.prop("offsetHeight"),top:d.top+(b.pageYOffset||a[0].documentElement.scrollTop),left:d.left+(b.pageXOffset||a[0].documentElement.scrollLeft)}},positionElements:function(a,b,c,d){var e,f,g,h,i=c.split("-"),j=i[0],k=i[1]||"center";e=d?this.offset(a):this.position(a),f=b.prop("offsetWidth"),g=b.prop("offsetHeight");var l={center:function(){return e.left+e.width/2-f/2},left:function(){return e.left},right:function(){return e.left+e.width}},m={center:function(){return e.top+e.height/2-g/2},top:function(){return e.top},bottom:function(){return e.top+e.height}};switch(j){case"right":h={top:m[k](),left:l[j]()};break;case"left":h={top:m[k](),left:e.left-f};break;case"bottom":h={top:m[j](),left:l[k]()};break;default:h={top:e.top-g,left:l[k]()}}return h}}}]),angular.module("ui.bootstrap.position").value("$positionSuppressWarning",!1).service("$position",["$log","$positionSuppressWarning","$uibPosition",function(a,b,c){b||a.warn("$position is now deprecated. Use $uibPosition instead."),angular.extend(this,c)}]),angular.module("ui.bootstrap.datepicker",["ui.bootstrap.dateparser","ui.bootstrap.position"]).value("$datepickerSuppressError",!1).constant("uibDatepickerConfig",{formatDay:"dd",formatMonth:"MMMM",formatYear:"yyyy",formatDayHeader:"EEE",formatDayTitle:"MMMM yyyy",formatMonthTitle:"yyyy",datepickerMode:"day",minMode:"day",maxMode:"year",showWeeks:!0,startingDay:0,yearRange:20,minDate:null,maxDate:null,shortcutPropagation:!1}).controller("UibDatepickerController",["$scope","$attrs","$parse","$interpolate","$log","dateFilter","uibDatepickerConfig","$datepickerSuppressError",function(a,b,c,d,e,f,g,h){var i=this,j={$setViewValue:angular.noop};this.modes=["day","month","year"],angular.forEach(["formatDay","formatMonth","formatYear","formatDayHeader","formatDayTitle","formatMonthTitle","showWeeks","startingDay","yearRange","shortcutPropagation"],function(c,e){i[c]=angular.isDefined(b[c])?6>e?d(b[c])(a.$parent):a.$parent.$eval(b[c]):g[c]}),angular.forEach(["minDate","maxDate"],function(d){b[d]?a.$parent.$watch(c(b[d]),function(a){i[d]=a?new Date(a):null,i.refreshView()}):i[d]=g[d]?new Date(g[d]):null}),angular.forEach(["minMode","maxMode"],function(d){b[d]?a.$parent.$watch(c(b[d]),function(c){i[d]=angular.isDefined(c)?c:b[d],a[d]=i[d],("minMode"==d&&i.modes.indexOf(a.datepickerMode)i.modes.indexOf(i[d]))&&(a.datepickerMode=i[d])}):(i[d]=g[d]||null,a[d]=i[d])}),a.datepickerMode=a.datepickerMode||g.datepickerMode,a.uniqueId="datepicker-"+a.$id+"-"+Math.floor(1e4*Math.random()),angular.isDefined(b.initDate)?(this.activeDate=a.$parent.$eval(b.initDate)||new Date,a.$parent.$watch(b.initDate,function(a){a&&(j.$isEmpty(j.$modelValue)||j.$invalid)&&(i.activeDate=a,i.refreshView())})):this.activeDate=new Date,a.isActive=function(b){return 0===i.compare(b.date,i.activeDate)?(a.activeDateId=b.uid,!0):!1},this.init=function(a){j=a,j.$render=function(){i.render()}},this.render=function(){if(j.$viewValue){var a=new Date(j.$viewValue),b=!isNaN(a);b?this.activeDate=a:h||e.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.')}this.refreshView()},this.refreshView=function(){if(this.element){this._refreshView();var a=j.$viewValue?new Date(j.$viewValue):null;j.$setValidity("dateDisabled",!a||this.element&&!this.isDisabled(a))}},this.createDateObject=function(a,b){var c=j.$viewValue?new Date(j.$viewValue):null;return{date:a,label:f(a,b),selected:c&&0===this.compare(a,c),disabled:this.isDisabled(a),current:0===this.compare(a,new Date),customClass:this.customClass(a)}},this.isDisabled=function(c){return this.minDate&&this.compare(c,this.minDate)<0||this.maxDate&&this.compare(c,this.maxDate)>0||b.dateDisabled&&a.dateDisabled({date:c,mode:a.datepickerMode})},this.customClass=function(b){return a.customClass({date:b,mode:a.datepickerMode})},this.split=function(a,b){for(var c=[];a.length>0;)c.push(a.splice(0,b));return c},a.select=function(b){if(a.datepickerMode===i.minMode){var c=j.$viewValue?new Date(j.$viewValue):new Date(0,0,0,0,0,0,0);c.setFullYear(b.getFullYear(),b.getMonth(),b.getDate()),j.$setViewValue(c),j.$render()}else i.activeDate=b,a.datepickerMode=i.modes[i.modes.indexOf(a.datepickerMode)-1]},a.move=function(a){var b=i.activeDate.getFullYear()+a*(i.step.years||0),c=i.activeDate.getMonth()+a*(i.step.months||0);i.activeDate.setFullYear(b,c,1),i.refreshView()},a.toggleMode=function(b){b=b||1,a.datepickerMode===i.maxMode&&1===b||a.datepickerMode===i.minMode&&-1===b||(a.datepickerMode=i.modes[i.modes.indexOf(a.datepickerMode)+b])},a.keys={13:"enter",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down"};var k=function(){i.element[0].focus()};a.$on("uib:datepicker.focus",k),a.keydown=function(b){var c=a.keys[b.which];if(c&&!b.shiftKey&&!b.altKey)if(b.preventDefault(),i.shortcutPropagation||b.stopPropagation(),"enter"===c||"space"===c){if(i.isDisabled(i.activeDate))return;a.select(i.activeDate)}else!b.ctrlKey||"up"!==c&&"down"!==c?(i.handleKeyDown(c,b),i.refreshView()):a.toggleMode("up"===c?1:-1)}}]).controller("UibDaypickerController",["$scope","$element","dateFilter",function(a,b,c){function d(a,b){return 1!==b||a%4!==0||a%100===0&&a%400!==0?f[b]:29}function e(a){var b=new Date(a);b.setDate(b.getDate()+4-(b.getDay()||7));var c=b.getTime();return b.setMonth(0),b.setDate(1),Math.floor(Math.round((c-b)/864e5)/7)+1}var f=[31,28,31,30,31,30,31,31,30,31,30,31];this.step={months:1},this.element=b,this.init=function(b){angular.extend(b,this),a.showWeeks=b.showWeeks,b.refreshView()},this.getDates=function(a,b){for(var c,d=new Array(b),e=new Date(a),f=0;b>f;)c=new Date(e),d[f++]=c,e.setDate(e.getDate()+1);return d},this._refreshView=function(){var b=this.activeDate.getFullYear(),d=this.activeDate.getMonth(),f=new Date(this.activeDate);f.setFullYear(b,d,1);var g=this.startingDay-f.getDay(),h=g>0?7-g:-g,i=new Date(f);h>0&&i.setDate(-h+1);for(var j=this.getDates(i,42),k=0;42>k;k++)j[k]=angular.extend(this.createDateObject(j[k],this.formatDay),{secondary:j[k].getMonth()!==d,uid:a.uniqueId+"-"+k});a.labels=new Array(7);for(var l=0;7>l;l++)a.labels[l]={abbr:c(j[l].date,this.formatDayHeader),full:c(j[l].date,"EEEE")};if(a.title=c(this.activeDate,this.formatDayTitle),a.rows=this.split(j,7),a.showWeeks){a.weekNumbers=[];for(var m=(11-this.startingDay)%7,n=a.rows.length,o=0;n>o;o++)a.weekNumbers.push(e(a.rows[o][m].date))}},this.compare=function(a,b){return new Date(a.getFullYear(),a.getMonth(),a.getDate())-new Date(b.getFullYear(),b.getMonth(),b.getDate())},this.handleKeyDown=function(a,b){var c=this.activeDate.getDate();if("left"===a)c-=1;else if("up"===a)c-=7;else if("right"===a)c+=1;else if("down"===a)c+=7;else if("pageup"===a||"pagedown"===a){var e=this.activeDate.getMonth()+("pageup"===a?-1:1);this.activeDate.setMonth(e,1),c=Math.min(d(this.activeDate.getFullYear(),this.activeDate.getMonth()),c)}else"home"===a?c=1:"end"===a&&(c=d(this.activeDate.getFullYear(),this.activeDate.getMonth()));this.activeDate.setDate(c)}}]).controller("UibMonthpickerController",["$scope","$element","dateFilter",function(a,b,c){this.step={years:1},this.element=b,this.init=function(a){angular.extend(a,this),a.refreshView()},this._refreshView=function(){for(var b,d=new Array(12),e=this.activeDate.getFullYear(),f=0;12>f;f++)b=new Date(this.activeDate),b.setFullYear(e,f,1),d[f]=angular.extend(this.createDateObject(b,this.formatMonth),{uid:a.uniqueId+"-"+f});a.title=c(this.activeDate,this.formatMonthTitle),a.rows=this.split(d,3)},this.compare=function(a,b){return new Date(a.getFullYear(),a.getMonth())-new Date(b.getFullYear(),b.getMonth())},this.handleKeyDown=function(a,b){var c=this.activeDate.getMonth();if("left"===a)c-=1;else if("up"===a)c-=3;else if("right"===a)c+=1;else if("down"===a)c+=3;else if("pageup"===a||"pagedown"===a){var d=this.activeDate.getFullYear()+("pageup"===a?-1:1);this.activeDate.setFullYear(d)}else"home"===a?c=0:"end"===a&&(c=11);this.activeDate.setMonth(c)}}]).controller("UibYearpickerController",["$scope","$element","dateFilter",function(a,b,c){function d(a){return parseInt((a-1)/e,10)*e+1}var e;this.element=b,this.yearpickerInit=function(){e=this.yearRange,this.step={years:e}},this._refreshView=function(){for(var b,c=new Array(e),f=0,g=d(this.activeDate.getFullYear());e>f;f++)b=new Date(this.activeDate),b.setFullYear(g+f,0,1),c[f]=angular.extend(this.createDateObject(b,this.formatYear),{uid:a.uniqueId+"-"+f});a.title=[c[0].label,c[e-1].label].join(" - "),a.rows=this.split(c,5)},this.compare=function(a,b){return a.getFullYear()-b.getFullYear()},this.handleKeyDown=function(a,b){var c=this.activeDate.getFullYear();"left"===a?c-=1:"up"===a?c-=5:"right"===a?c+=1:"down"===a?c+=5:"pageup"===a||"pagedown"===a?c+=("pageup"===a?-1:1)*this.step.years:"home"===a?c=d(this.activeDate.getFullYear()):"end"===a&&(c=d(this.activeDate.getFullYear())+e-1),this.activeDate.setFullYear(c)}}]).directive("uibDatepicker",function(){return{replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/datepicker/datepicker.html"},scope:{datepickerMode:"=?",dateDisabled:"&",customClass:"&",shortcutPropagation:"&?"},require:["uibDatepicker","^ngModel"],controller:"UibDatepickerController",controllerAs:"datepicker",link:function(a,b,c,d){var e=d[0],f=d[1];e.init(f)}}}).directive("uibDaypicker",function(){return{replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/datepicker/day.html"},require:["^?uibDatepicker","uibDaypicker","^?datepicker"],controller:"UibDaypickerController",link:function(a,b,c,d){var e=d[0]||d[2],f=d[1];f.init(e)}}}).directive("uibMonthpicker",function(){return{replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/datepicker/month.html"},require:["^?uibDatepicker","uibMonthpicker","^?datepicker"],controller:"UibMonthpickerController",link:function(a,b,c,d){var e=d[0]||d[2],f=d[1];f.init(e)}}}).directive("uibYearpicker",function(){return{replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/datepicker/year.html"},require:["^?uibDatepicker","uibYearpicker","^?datepicker"],controller:"UibYearpickerController",link:function(a,b,c,d){var e=d[0]||d[2];angular.extend(e,d[1]),e.yearpickerInit(),e.refreshView()}}}).constant("uibDatepickerPopupConfig",{datepickerPopup:"yyyy-MM-dd",datepickerPopupTemplateUrl:"template/datepicker/popup.html",datepickerTemplateUrl:"template/datepicker/datepicker.html",html5Types:{date:"yyyy-MM-dd","datetime-local":"yyyy-MM-ddTHH:mm:ss.sss",month:"yyyy-MM"},currentText:"Today",clearText:"Clear",closeText:"Done",closeOnDateSelection:!0,appendToBody:!1,showButtonBar:!0,onOpenFocus:!0}).controller("UibDatepickerPopupController",["$scope","$element","$attrs","$compile","$parse","$document","$rootScope","$uibPosition","dateFilter","uibDateParser","uibDatepickerPopupConfig","$timeout",function(a,b,c,d,e,f,g,h,i,j,k,l){function m(a){return a.replace(/([A-Z])/g,function(a){return"-"+a.toLowerCase()})}function n(b){if(angular.isNumber(b)&&(b=new Date(b)),b){if(angular.isDate(b)&&!isNaN(b))return b;if(angular.isString(b)){var c=j.parse(b,r,a.date);return isNaN(c)?void 0:c}return void 0}return null}function o(a,b){var d=a||b;if(!c.ngRequired&&!d)return!0;if(angular.isNumber(d)&&(d=new Date(d)),d){if(angular.isDate(d)&&!isNaN(d))return!0;if(angular.isString(d)){var e=j.parse(d,r);return!isNaN(e)}return!1}return!0}function p(c){var d=A[0],e=b[0].contains(c.target),f=void 0!==d.contains&&d.contains(c.target);!a.isOpen||e||f||a.$apply(function(){a.isOpen=!1})}function q(c){27===c.which&&a.isOpen?(c.preventDefault(),c.stopPropagation(),a.$apply(function(){a.isOpen=!1}),b[0].focus()):40!==c.which||a.isOpen||(c.preventDefault(),c.stopPropagation(),a.$apply(function(){a.isOpen=!0}))}var r,s,t,u,v,w,x,y,z,A,B={},C=!1;a.watchData={},this.init=function(h){if(z=h,s=angular.isDefined(c.closeOnDateSelection)?a.$parent.$eval(c.closeOnDateSelection):k.closeOnDateSelection, +t=angular.isDefined(c.datepickerAppendToBody)?a.$parent.$eval(c.datepickerAppendToBody):k.appendToBody,u=angular.isDefined(c.onOpenFocus)?a.$parent.$eval(c.onOpenFocus):k.onOpenFocus,v=angular.isDefined(c.datepickerPopupTemplateUrl)?c.datepickerPopupTemplateUrl:k.datepickerPopupTemplateUrl,w=angular.isDefined(c.datepickerTemplateUrl)?c.datepickerTemplateUrl:k.datepickerTemplateUrl,a.showButtonBar=angular.isDefined(c.showButtonBar)?a.$parent.$eval(c.showButtonBar):k.showButtonBar,k.html5Types[c.type]?(r=k.html5Types[c.type],C=!0):(r=c.datepickerPopup||c.uibDatepickerPopup||k.datepickerPopup,c.$observe("uibDatepickerPopup",function(a,b){var c=a||k.datepickerPopup;if(c!==r&&(r=c,z.$modelValue=null,!r))throw new Error("uibDatepickerPopup must have a date format specified.")})),!r)throw new Error("uibDatepickerPopup must have a date format specified.");if(C&&c.datepickerPopup)throw new Error("HTML5 date input types do not support custom formats.");if(x=angular.element("
      "),x.attr({"ng-model":"date","ng-change":"dateSelection(date)","template-url":v}),y=angular.element(x.children()[0]),y.attr("template-url",w),C&&"month"===c.type&&(y.attr("datepicker-mode",'"month"'),y.attr("min-mode","month")),c.datepickerOptions){var l=a.$parent.$eval(c.datepickerOptions);l&&l.initDate&&(a.initDate=l.initDate,y.attr("init-date","initDate"),delete l.initDate),angular.forEach(l,function(a,b){y.attr(m(b),a)})}angular.forEach(["minMode","maxMode","minDate","maxDate","datepickerMode","initDate","shortcutPropagation"],function(b){if(c[b]){var d=e(c[b]);if(a.$parent.$watch(d,function(c){a.watchData[b]=c,("minDate"===b||"maxDate"===b)&&(B[b]=new Date(c))}),y.attr(m(b),"watchData."+b),"datepickerMode"===b){var f=d.assign;a.$watch("watchData."+b,function(b,c){angular.isFunction(f)&&b!==c&&f(a.$parent,b)})}}}),c.dateDisabled&&y.attr("date-disabled","dateDisabled({ date: date, mode: mode })"),c.showWeeks&&y.attr("show-weeks",c.showWeeks),c.customClass&&y.attr("custom-class","customClass({ date: date, mode: mode })"),C?z.$formatters.push(function(b){return a.date=b,b}):(z.$$parserName="date",z.$validators.date=o,z.$parsers.unshift(n),z.$formatters.push(function(b){return a.date=b,z.$isEmpty(b)?b:i(b,r)})),z.$viewChangeListeners.push(function(){a.date=j.parse(z.$viewValue,r,a.date)}),b.bind("keydown",q),A=d(x)(a),x.remove(),t?f.find("body").append(A):b.after(A),a.$on("$destroy",function(){a.isOpen===!0&&(g.$$phase||a.$apply(function(){a.isOpen=!1})),A.remove(),b.unbind("keydown",q),f.unbind("click",p)})},a.getText=function(b){return a[b+"Text"]||k[b+"Text"]},a.isDisabled=function(b){return"today"===b&&(b=new Date),a.watchData.minDate&&a.compare(b,B.minDate)<0||a.watchData.maxDate&&a.compare(b,B.maxDate)>0},a.compare=function(a,b){return new Date(a.getFullYear(),a.getMonth(),a.getDate())-new Date(b.getFullYear(),b.getMonth(),b.getDate())},a.dateSelection=function(c){angular.isDefined(c)&&(a.date=c);var d=a.date?i(a.date,r):null;b.val(d),z.$setViewValue(d),s&&(a.isOpen=!1,b[0].focus())},a.keydown=function(c){27===c.which&&(a.isOpen=!1,b[0].focus())},a.select=function(b){if("today"===b){var c=new Date;angular.isDate(a.date)?(b=new Date(a.date),b.setFullYear(c.getFullYear(),c.getMonth(),c.getDate())):b=new Date(c.setHours(0,0,0,0))}a.dateSelection(b)},a.close=function(){a.isOpen=!1,b[0].focus()},a.$watch("isOpen",function(c){c?(a.position=t?h.offset(b):h.position(b),a.position.top=a.position.top+b.prop("offsetHeight"),l(function(){u&&a.$broadcast("uib:datepicker.focus"),f.bind("click",p)},0,!1)):f.unbind("click",p)})}]).directive("uibDatepickerPopup",function(){return{require:["ngModel","uibDatepickerPopup"],controller:"UibDatepickerPopupController",scope:{isOpen:"=?",currentText:"@",clearText:"@",closeText:"@",dateDisabled:"&",customClass:"&"},link:function(a,b,c,d){var e=d[0],f=d[1];f.init(e)}}}).directive("uibDatepickerPopupWrap",function(){return{replace:!0,transclude:!0,templateUrl:function(a,b){return b.templateUrl||"template/datepicker/popup.html"}}}),angular.module("ui.bootstrap.datepicker").value("$datepickerSuppressWarning",!1).controller("DatepickerController",["$scope","$attrs","$parse","$interpolate","$log","dateFilter","uibDatepickerConfig","$datepickerSuppressError","$datepickerSuppressWarning",function(a,b,c,d,e,f,g,h,i){i||e.warn("DatepickerController is now deprecated. Use UibDatepickerController instead.");var j=this,k={$setViewValue:angular.noop};this.modes=["day","month","year"],angular.forEach(["formatDay","formatMonth","formatYear","formatDayHeader","formatDayTitle","formatMonthTitle","showWeeks","startingDay","yearRange","shortcutPropagation"],function(c,e){j[c]=angular.isDefined(b[c])?6>e?d(b[c])(a.$parent):a.$parent.$eval(b[c]):g[c]}),angular.forEach(["minDate","maxDate"],function(d){b[d]?a.$parent.$watch(c(b[d]),function(a){j[d]=a?new Date(a):null,j.refreshView()}):j[d]=g[d]?new Date(g[d]):null}),angular.forEach(["minMode","maxMode"],function(d){b[d]?a.$parent.$watch(c(b[d]),function(c){j[d]=angular.isDefined(c)?c:b[d],a[d]=j[d],("minMode"==d&&j.modes.indexOf(a.datepickerMode)j.modes.indexOf(j[d]))&&(a.datepickerMode=j[d])}):(j[d]=g[d]||null,a[d]=j[d])}),a.datepickerMode=a.datepickerMode||g.datepickerMode,a.uniqueId="datepicker-"+a.$id+"-"+Math.floor(1e4*Math.random()),angular.isDefined(b.initDate)?(this.activeDate=a.$parent.$eval(b.initDate)||new Date,a.$parent.$watch(b.initDate,function(a){a&&(k.$isEmpty(k.$modelValue)||k.$invalid)&&(j.activeDate=a,j.refreshView())})):this.activeDate=new Date,a.isActive=function(b){return 0===j.compare(b.date,j.activeDate)?(a.activeDateId=b.uid,!0):!1},this.init=function(a){k=a,k.$render=function(){j.render()}},this.render=function(){if(k.$viewValue){var a=new Date(k.$viewValue),b=!isNaN(a);b?this.activeDate=a:h||e.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.')}this.refreshView()},this.refreshView=function(){if(this.element){this._refreshView();var a=k.$viewValue?new Date(k.$viewValue):null;k.$setValidity("dateDisabled",!a||this.element&&!this.isDisabled(a))}},this.createDateObject=function(a,b){var c=k.$viewValue?new Date(k.$viewValue):null;return{date:a,label:f(a,b),selected:c&&0===this.compare(a,c),disabled:this.isDisabled(a),current:0===this.compare(a,new Date),customClass:this.customClass(a)}},this.isDisabled=function(c){return this.minDate&&this.compare(c,this.minDate)<0||this.maxDate&&this.compare(c,this.maxDate)>0||b.dateDisabled&&a.dateDisabled({date:c,mode:a.datepickerMode})},this.customClass=function(b){return a.customClass({date:b,mode:a.datepickerMode})},this.split=function(a,b){for(var c=[];a.length>0;)c.push(a.splice(0,b));return c},this.fixTimeZone=function(a){var b=a.getHours();a.setHours(23===b?b+2:0)},a.select=function(b){if(a.datepickerMode===j.minMode){var c=k.$viewValue?new Date(k.$viewValue):new Date(0,0,0,0,0,0,0);c.setFullYear(b.getFullYear(),b.getMonth(),b.getDate()),k.$setViewValue(c),k.$render()}else j.activeDate=b,a.datepickerMode=j.modes[j.modes.indexOf(a.datepickerMode)-1]},a.move=function(a){var b=j.activeDate.getFullYear()+a*(j.step.years||0),c=j.activeDate.getMonth()+a*(j.step.months||0);j.activeDate.setFullYear(b,c,1),j.refreshView()},a.toggleMode=function(b){b=b||1,a.datepickerMode===j.maxMode&&1===b||a.datepickerMode===j.minMode&&-1===b||(a.datepickerMode=j.modes[j.modes.indexOf(a.datepickerMode)+b])},a.keys={13:"enter",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down"};var l=function(){j.element[0].focus()};a.$on("uib:datepicker.focus",l),a.keydown=function(b){var c=a.keys[b.which];if(c&&!b.shiftKey&&!b.altKey)if(b.preventDefault(),j.shortcutPropagation||b.stopPropagation(),"enter"===c||"space"===c){if(j.isDisabled(j.activeDate))return;a.select(j.activeDate)}else!b.ctrlKey||"up"!==c&&"down"!==c?(j.handleKeyDown(c,b),j.refreshView()):a.toggleMode("up"===c?1:-1)}}]).directive("datepicker",["$log","$datepickerSuppressWarning",function(a,b){return{replace:!0,templateUrl:function(a,b){return b.templateUrl||"template/datepicker/datepicker.html"},scope:{datepickerMode:"=?",dateDisabled:"&",customClass:"&",shortcutPropagation:"&?"},require:["datepicker","^ngModel"],controller:"DatepickerController",controllerAs:"datepicker",link:function(c,d,e,f){b||a.warn("datepicker is now deprecated. Use uib-datepicker instead.");var g=f[0],h=f[1];g.init(h)}}}]).directive("daypicker",["$log","$datepickerSuppressWarning",function(a,b){return{replace:!0,templateUrl:"template/datepicker/day.html",require:["^datepicker","daypicker"],controller:"UibDaypickerController",link:function(c,d,e,f){b||a.warn("daypicker is now deprecated. Use uib-daypicker instead.");var g=f[0],h=f[1];h.init(g)}}}]).directive("monthpicker",["$log","$datepickerSuppressWarning",function(a,b){return{replace:!0,templateUrl:"template/datepicker/month.html",require:["^datepicker","monthpicker"],controller:"UibMonthpickerController",link:function(c,d,e,f){b||a.warn("monthpicker is now deprecated. Use uib-monthpicker instead.");var g=f[0],h=f[1];h.init(g)}}}]).directive("yearpicker",["$log","$datepickerSuppressWarning",function(a,b){return{replace:!0,templateUrl:"template/datepicker/year.html",require:["^datepicker","yearpicker"],controller:"UibYearpickerController",link:function(c,d,e,f){b||a.warn("yearpicker is now deprecated. Use uib-yearpicker instead.");var g=f[0];angular.extend(g,f[1]),g.yearpickerInit(),g.refreshView()}}}]).directive("datepickerPopup",["$log","$datepickerSuppressWarning",function(a,b){return{require:["ngModel","datepickerPopup"],controller:"UibDatepickerPopupController",scope:{isOpen:"=?",currentText:"@",clearText:"@",closeText:"@",dateDisabled:"&",customClass:"&"},link:function(c,d,e,f){b||a.warn("datepicker-popup is now deprecated. Use uib-datepicker-popup instead.");var g=f[0],h=f[1];h.init(g)}}}]).directive("datepickerPopupWrap",["$log","$datepickerSuppressWarning",function(a,b){return{replace:!0,transclude:!0,templateUrl:function(a,b){return b.templateUrl||"template/datepicker/popup.html"},link:function(){b||a.warn("datepicker-popup-wrap is now deprecated. Use uib-datepicker-popup-wrap instead.")}}}]),angular.module("ui.bootstrap.dropdown",["ui.bootstrap.position"]).constant("uibDropdownConfig",{openClass:"open"}).service("uibDropdownService",["$document","$rootScope",function(a,b){var c=null;this.open=function(b){c||(a.bind("click",d),a.bind("keydown",e)),c&&c!==b&&(c.isOpen=!1),c=b},this.close=function(b){c===b&&(c=null,a.unbind("click",d),a.unbind("keydown",e))};var d=function(a){if(c&&(!a||"disabled"!==c.getAutoClose())){var d=c.getToggleElement();if(!(a&&d&&d[0].contains(a.target))){var e=c.getDropdownElement();a&&"outsideClick"===c.getAutoClose()&&e&&e[0].contains(a.target)||(c.isOpen=!1,b.$$phase||c.$apply())}}},e=function(a){27===a.which?(c.focusToggleElement(),d()):c.isKeynavEnabled()&&/(38|40)/.test(a.which)&&c.isOpen&&(a.preventDefault(),a.stopPropagation(),c.focusDropdownEntry(a.which))}}]).controller("UibDropdownController",["$scope","$element","$attrs","$parse","uibDropdownConfig","uibDropdownService","$animate","$uibPosition","$document","$compile","$templateRequest",function(a,b,c,d,e,f,g,h,i,j,k){var l,m,n=this,o=a.$new(),p=e.openClass,q=angular.noop,r=c.onToggle?d(c.onToggle):angular.noop,s=!1,t=!1;b.addClass("dropdown"),this.init=function(){c.isOpen&&(m=d(c.isOpen),q=m.assign,a.$watch(m,function(a){o.isOpen=!!a})),s=angular.isDefined(c.dropdownAppendToBody),t=angular.isDefined(c.uibKeyboardNav),s&&n.dropdownMenu&&(i.find("body").append(n.dropdownMenu),b.on("$destroy",function(){n.dropdownMenu.remove()}))},this.toggle=function(a){return o.isOpen=arguments.length?!!a:!o.isOpen},this.isOpen=function(){return o.isOpen},o.getToggleElement=function(){return n.toggleElement},o.getAutoClose=function(){return c.autoClose||"always"},o.getElement=function(){return b},o.isKeynavEnabled=function(){return t},o.focusDropdownEntry=function(a){var c=n.dropdownMenu?angular.element(n.dropdownMenu).find("a"):angular.element(b).find("ul").eq(0).find("a");switch(a){case 40:angular.isNumber(n.selectedOption)?n.selectedOption=n.selectedOption===c.length-1?n.selectedOption:n.selectedOption+1:n.selectedOption=0;break;case 38:angular.isNumber(n.selectedOption)?n.selectedOption=0===n.selectedOption?0:n.selectedOption-1:n.selectedOption=c.length-1}c[n.selectedOption].focus()},o.getDropdownElement=function(){return n.dropdownMenu},o.focusToggleElement=function(){n.toggleElement&&n.toggleElement[0].focus()},o.$watch("isOpen",function(c,d){if(s&&n.dropdownMenu){var e=h.positionElements(b,n.dropdownMenu,"bottom-left",!0),i={top:e.top+"px",display:c?"block":"none"},m=n.dropdownMenu.hasClass("dropdown-menu-right");m?(i.left="auto",i.right=window.innerWidth-(e.left+b.prop("offsetWidth"))+"px"):(i.left=e.left+"px",i.right="auto"),n.dropdownMenu.css(i)}if(g[c?"addClass":"removeClass"](b,p).then(function(){angular.isDefined(c)&&c!==d&&r(a,{open:!!c})}),c)n.dropdownMenuTemplateUrl&&k(n.dropdownMenuTemplateUrl).then(function(a){l=o.$new(),j(a.trim())(l,function(a){var b=a;n.dropdownMenu.replaceWith(b),n.dropdownMenu=b})}),o.focusToggleElement(),f.open(o);else{if(n.dropdownMenuTemplateUrl){l&&l.$destroy();var t=angular.element('');n.dropdownMenu.replaceWith(t),n.dropdownMenu=t}f.close(o),n.selectedOption=null}angular.isFunction(q)&&q(a,c)}),a.$on("$locationChangeSuccess",function(){"disabled"!==o.getAutoClose()&&(o.isOpen=!1)});var u=a.$on("$destroy",function(){o.$destroy()});o.$on("$destroy",u)}]).directive("uibDropdown",function(){return{controller:"UibDropdownController",link:function(a,b,c,d){d.init()}}}).directive("uibDropdownMenu",function(){return{restrict:"AC",require:"?^uibDropdown",link:function(a,b,c,d){if(d&&!angular.isDefined(c.dropdownNested)){b.addClass("dropdown-menu");var e=c.templateUrl;e&&(d.dropdownMenuTemplateUrl=e),d.dropdownMenu||(d.dropdownMenu=b)}}}}).directive("uibKeyboardNav",function(){return{restrict:"A",require:"?^uibDropdown",link:function(a,b,c,d){b.bind("keydown",function(a){if(-1!==[38,40].indexOf(a.which)){a.preventDefault(),a.stopPropagation();var b=d.dropdownMenu.find("a");switch(a.which){case 40:angular.isNumber(d.selectedOption)?d.selectedOption=d.selectedOption===b.length-1?d.selectedOption:d.selectedOption+1:d.selectedOption=0;break;case 38:angular.isNumber(d.selectedOption)?d.selectedOption=0===d.selectedOption?0:d.selectedOption-1:d.selectedOption=b.length-1}b[d.selectedOption].focus()}})}}}).directive("uibDropdownToggle",function(){return{require:"?^uibDropdown",link:function(a,b,c,d){if(d){b.addClass("dropdown-toggle"),d.toggleElement=b;var e=function(e){e.preventDefault(),b.hasClass("disabled")||c.disabled||a.$apply(function(){d.toggle()})};b.bind("click",e),b.attr({"aria-haspopup":!0,"aria-expanded":!1}),a.$watch(d.isOpen,function(a){b.attr("aria-expanded",!!a)}),a.$on("$destroy",function(){b.unbind("click",e)})}}}}),angular.module("ui.bootstrap.dropdown").value("$dropdownSuppressWarning",!1).service("dropdownService",["$log","$dropdownSuppressWarning","uibDropdownService",function(a,b,c){b||a.warn("dropdownService is now deprecated. Use uibDropdownService instead."),angular.extend(this,c)}]).controller("DropdownController",["$scope","$element","$attrs","$parse","uibDropdownConfig","uibDropdownService","$animate","$uibPosition","$document","$compile","$templateRequest","$log","$dropdownSuppressWarning",function(a,b,c,d,e,f,g,h,i,j,k,l,m){m||l.warn("DropdownController is now deprecated. Use UibDropdownController instead.");var n,o,p=this,q=a.$new(),r=e.openClass,s=angular.noop,t=c.onToggle?d(c.onToggle):angular.noop,u=!1,v=!1;b.addClass("dropdown"),this.init=function(){c.isOpen&&(o=d(c.isOpen),s=o.assign,a.$watch(o,function(a){q.isOpen=!!a})),u=angular.isDefined(c.dropdownAppendToBody),v=angular.isDefined(c.uibKeyboardNav),u&&p.dropdownMenu&&(i.find("body").append(p.dropdownMenu),b.on("$destroy",function(){p.dropdownMenu.remove()}))},this.toggle=function(a){return q.isOpen=arguments.length?!!a:!q.isOpen},this.isOpen=function(){return q.isOpen},q.getToggleElement=function(){return p.toggleElement},q.getAutoClose=function(){return c.autoClose||"always"},q.getElement=function(){return b},q.isKeynavEnabled=function(){return v},q.focusDropdownEntry=function(a){var c=p.dropdownMenu?angular.element(p.dropdownMenu).find("a"):angular.element(b).find("ul").eq(0).find("a");switch(a){case 40:angular.isNumber(p.selectedOption)?p.selectedOption=p.selectedOption===c.length-1?p.selectedOption:p.selectedOption+1:p.selectedOption=0;break;case 38:angular.isNumber(p.selectedOption)?p.selectedOption=0===p.selectedOption?0:p.selectedOption-1:p.selectedOption=c.length-1}c[p.selectedOption].focus()},q.getDropdownElement=function(){return p.dropdownMenu},q.focusToggleElement=function(){p.toggleElement&&p.toggleElement[0].focus()},q.$watch("isOpen",function(c,d){if(u&&p.dropdownMenu){var e=h.positionElements(b,p.dropdownMenu,"bottom-left",!0),i={top:e.top+"px",display:c?"block":"none"},l=p.dropdownMenu.hasClass("dropdown-menu-right");l?(i.left="auto",i.right=window.innerWidth-(e.left+b.prop("offsetWidth"))+"px"):(i.left=e.left+"px",i.right="auto"),p.dropdownMenu.css(i)}if(g[c?"addClass":"removeClass"](b,r).then(function(){angular.isDefined(c)&&c!==d&&t(a,{open:!!c})}),c)p.dropdownMenuTemplateUrl&&k(p.dropdownMenuTemplateUrl).then(function(a){n=q.$new(),j(a.trim())(n,function(a){var b=a;p.dropdownMenu.replaceWith(b),p.dropdownMenu=b})}),q.focusToggleElement(),f.open(q);else{if(p.dropdownMenuTemplateUrl){n&&n.$destroy();var m=angular.element('');p.dropdownMenu.replaceWith(m),p.dropdownMenu=m}f.close(q),p.selectedOption=null}angular.isFunction(s)&&s(a,c)}),a.$on("$locationChangeSuccess",function(){"disabled"!==q.getAutoClose()&&(q.isOpen=!1)});var w=a.$on("$destroy",function(){q.$destroy()});q.$on("$destroy",w)}]).directive("dropdown",["$log","$dropdownSuppressWarning",function(a,b){return{controller:"DropdownController",link:function(c,d,e,f){b||a.warn("dropdown is now deprecated. Use uib-dropdown instead."),f.init()}}}]).directive("dropdownMenu",["$log","$dropdownSuppressWarning",function(a,b){return{restrict:"AC",require:"?^dropdown",link:function(c,d,e,f){if(f&&!angular.isDefined(e.dropdownNested)){b||a.warn("dropdown-menu is now deprecated. Use uib-dropdown-menu instead."),d.addClass("dropdown-menu");var g=e.templateUrl;g&&(f.dropdownMenuTemplateUrl=g),f.dropdownMenu||(f.dropdownMenu=d)}}}}]).directive("keyboardNav",["$log","$dropdownSuppressWarning",function(a,b){return{restrict:"A",require:"?^dropdown",link:function(c,d,e,f){b||a.warn("keyboard-nav is now deprecated. Use uib-keyboard-nav instead."),d.bind("keydown",function(a){if(-1!==[38,40].indexOf(a.which)){a.preventDefault(),a.stopPropagation();var b=f.dropdownMenu.find("a");switch(a.which){case 40:angular.isNumber(f.selectedOption)?f.selectedOption=f.selectedOption===b.length-1?f.selectedOption:f.selectedOption+1:f.selectedOption=0;break;case 38:angular.isNumber(f.selectedOption)?f.selectedOption=0===f.selectedOption?0:f.selectedOption-1:f.selectedOption=b.length-1}b[f.selectedOption].focus()}})}}}]).directive("dropdownToggle",["$log","$dropdownSuppressWarning",function(a,b){return{require:"?^dropdown",link:function(c,d,e,f){if(b||a.warn("dropdown-toggle is now deprecated. Use uib-dropdown-toggle instead."),f){d.addClass("dropdown-toggle"),f.toggleElement=d;var g=function(a){a.preventDefault(),d.hasClass("disabled")||e.disabled||c.$apply(function(){f.toggle()})};d.bind("click",g),d.attr({"aria-haspopup":!0,"aria-expanded":!1}),c.$watch(f.isOpen,function(a){d.attr("aria-expanded",!!a)}),c.$on("$destroy",function(){d.unbind("click",g)})}}}}]),angular.module("ui.bootstrap.stackedMap",[]).factory("$$stackedMap",function(){return{createNew:function(){var a=[];return{add:function(b,c){a.push({key:b,value:c})},get:function(b){for(var c=0;c0&&(b=u.top().value,b.modalDomEl.toggleClass(b.windowTopClass||"",a))}function m(){if(q&&-1==j()){var a=r;n(q,r,function(){a=null}),q=void 0,r=void 0}}function n(b,c,d){function e(){e.done||(e.done=!0,p?p(b,{event:"leave"}).start().then(function(){b.remove()}):a.leave(b),c.$destroy(),d&&d())}var g,h=null,i=function(){return g||(g=f.defer(),h=g.promise),function(){g.resolve()}};return c.$broadcast(w.NOW_CLOSING_EVENT,i),f.when(h).then(e)}function o(a,b,c){return!a.value.modalScope.$broadcast("modal.closing",b,c).defaultPrevented}var p=null;g.has("$animateCss")&&(p=g.get("$animateCss"));var q,r,s,t="modal-open",u=i.createNew(),v=h.createNew(),w={NOW_CLOSING_EVENT:"modal.stack.now-closing"},x=0,y="a[href], area[href], input:not([disabled]), button:not([disabled]),select:not([disabled]), textarea:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable=true]";return e.$watch(j,function(a){r&&(r.index=a)}),c.bind("keydown",function(a){if(a.isDefaultPrevented())return a;var b=u.top();if(b&&b.value.keyboard)switch(a.which){case 27:a.preventDefault(),e.$apply(function(){w.dismiss(b.key,"escape key press")});break;case 9:w.loadFocusElementList(b);var c=!1;a.shiftKey?w.isFocusInFirstItem(a)&&(c=w.focusLastFocusableElement()):w.isFocusInLastItem(a)&&(c=w.focusFirstFocusableElement()),c&&(a.preventDefault(),a.stopPropagation())}}),w.open=function(a,b){var f=c[0].activeElement,g=b.openedClass||t;l(!1),u.add(a,{deferred:b.deferred,renderDeferred:b.renderDeferred,modalScope:b.scope,backdrop:b.backdrop,keyboard:b.keyboard,openedClass:b.openedClass,windowTopClass:b.windowTopClass}),v.put(g,a);var h=c.find("body").eq(0),i=j();if(i>=0&&!q){r=e.$new(!0),r.index=i;var k=angular.element('
      ');k.attr("backdrop-class",b.backdropClass),b.animation&&k.attr("modal-animation","true"),q=d(k)(r),h.append(q)}var m=angular.element('
      ');m.attr({"template-url":b.windowTemplateUrl,"window-class":b.windowClass,"window-top-class":b.windowTopClass,size:b.size,index:u.length()-1,animate:"animate"}).html(b.content),b.animation&&m.attr("modal-animation","true");var n=d(m)(b.scope);u.top().value.modalDomEl=n,u.top().value.modalOpener=f,h.append(n),h.addClass(g),w.clearFocusListCache()},w.close=function(a,b){var c=u.get(a);return c&&o(c,b,!0)?(c.value.modalScope.$$uibDestructionScheduled=!0,c.value.deferred.resolve(b),k(a,c.value.modalOpener),!0):!c},w.dismiss=function(a,b){var c=u.get(a);return c&&o(c,b,!1)?(c.value.modalScope.$$uibDestructionScheduled=!0,c.value.deferred.reject(b),k(a,c.value.modalOpener),!0):!c},w.dismissAll=function(a){for(var b=this.getTop();b&&this.dismiss(b.key,a);)b=this.getTop()},w.getTop=function(){return u.top()},w.modalRendered=function(a){var b=u.get(a);b&&b.value.renderDeferred.resolve()},w.focusFirstFocusableElement=function(){return s.length>0?(s[0].focus(),!0):!1},w.focusLastFocusableElement=function(){return s.length>0?(s[s.length-1].focus(),!0):!1},w.isFocusInFirstItem=function(a){return s.length>0?(a.target||a.srcElement)==s[0]:!1},w.isFocusInLastItem=function(a){return s.length>0?(a.target||a.srcElement)==s[s.length-1]:!1},w.clearFocusListCache=function(){s=[],x=0},w.loadFocusElementList=function(a){if((void 0===s||!s.length)&&a){var b=a.value.modalDomEl;b&&b.length&&(s=b[0].querySelectorAll(y))}},w}]).provider("$uibModal",function(){var a={options:{animation:!0,backdrop:!0,keyboard:!0},$get:["$injector","$rootScope","$q","$templateRequest","$controller","$uibModalStack","$modalSuppressWarning","$log",function(b,c,d,e,f,g,h,i){function j(a){return a.template?d.when(a.template):e(angular.isFunction(a.templateUrl)?a.templateUrl():a.templateUrl)}function k(a){var c=[];return angular.forEach(a,function(a){angular.isFunction(a)||angular.isArray(a)?c.push(d.when(b.invoke(a))):angular.isString(a)?c.push(d.when(b.get(a))):c.push(d.when(a))}),c}var l={},m=null;return l.getPromiseChain=function(){return m},l.open=function(b){function e(){return r}var l=d.defer(),n=d.defer(),o=d.defer(),p={result:l.promise,opened:n.promise,rendered:o.promise,close:function(a){return g.close(p,a)},dismiss:function(a){return g.dismiss(p,a)}};if(b=angular.extend({},a.options,b),b.resolve=b.resolve||{},!b.template&&!b.templateUrl)throw new Error("One of template or templateUrl options is required.");var q,r=d.all([j(b)].concat(k(b.resolve)));return q=m=d.all([m]).then(e,e).then(function(a){var d=(b.scope||c).$new();d.$close=p.close,d.$dismiss=p.dismiss,d.$on("$destroy",function(){d.$$uibDestructionScheduled||d.$dismiss("$uibUnscheduledDestruction")});var e,j={},k=1;b.controller&&(j.$scope=d,j.$uibModalInstance=p,Object.defineProperty(j,"$modalInstance",{get:function(){return h||i.warn("$modalInstance is now deprecated. Use $uibModalInstance instead."),p}}),angular.forEach(b.resolve,function(b,c){j[c]=a[k++]}),e=f(b.controller,j),b.controllerAs&&(b.bindToController&&angular.extend(e,d),d[b.controllerAs]=e)),g.open(p,{scope:d,deferred:l,renderDeferred:o,content:a[0],animation:b.animation,backdrop:b.backdrop,keyboard:b.keyboard,backdropClass:b.backdropClass,windowTopClass:b.windowTopClass,windowClass:b.windowClass,windowTemplateUrl:b.windowTemplateUrl,size:b.size,openedClass:b.openedClass}),n.resolve(!0)},function(a){n.reject(a),l.reject(a)})["finally"](function(){m===q&&(m=null)}),p},l}]};return a}),angular.module("ui.bootstrap.modal").value("$modalSuppressWarning",!1).directive("modalBackdrop",["$animate","$injector","$modalStack","$log","$modalSuppressWarning",function(a,b,c,d,e){function f(b,f,h){e||d.warn("modal-backdrop is now deprecated. Use uib-modal-backdrop instead."),f.addClass("modal-backdrop"),h.modalInClass&&(g?g(f,{addClass:h.modalInClass}).start():a.addClass(f,h.modalInClass),b.$on(c.NOW_CLOSING_EVENT,function(b,c){var d=c();g?g(f,{removeClass:h.modalInClass}).start().then(d):a.removeClass(f,h.modalInClass).then(d)}))}var g=null;return b.has("$animateCss")&&(g=b.get("$animateCss")),{replace:!0,templateUrl:"template/modal/backdrop.html",compile:function(a,b){return a.addClass(b.backdropClass),f}}}]).directive("modalWindow",["$modalStack","$q","$animate","$injector","$log","$modalSuppressWarning",function(a,b,c,d,e,f){var g=null;return d.has("$animateCss")&&(g=d.get("$animateCss")),{scope:{index:"@"},replace:!0,transclude:!0,templateUrl:function(a,b){return b.templateUrl||"template/modal/window.html"},link:function(d,h,i){f||e.warn("modal-window is now deprecated. Use uib-modal-window instead."),h.addClass(i.windowClass||""),h.addClass(i.windowTopClass||""),d.size=i.size,d.close=function(b){var c=a.getTop();c&&c.value.backdrop&&"static"!==c.value.backdrop&&b.target===b.currentTarget&&(b.preventDefault(),b.stopPropagation(),a.dismiss(c.key,"backdrop click"))},h.on("click",d.close),d.$isRendered=!0;var j=b.defer();i.$observe("modalRender",function(a){"true"==a&&j.resolve()}),j.promise.then(function(){var e=null;i.modalInClass&&(e=g?g(h,{addClass:i.modalInClass}).start():c.addClass(h,i.modalInClass),d.$on(a.NOW_CLOSING_EVENT,function(a,b){var d=b();g?g(h,{removeClass:i.modalInClass}).start().then(d):c.removeClass(h,i.modalInClass).then(d)})),b.when(e).then(function(){var a=h[0].querySelector("[autofocus]");a?a.focus():h[0].focus()});var f=a.getTop();f&&a.modalRendered(f.key)})}}}]).directive("modalAnimationClass",["$log","$modalSuppressWarning",function(a,b){return{compile:function(c,d){b||a.warn("modal-animation-class is now deprecated. Use uib-modal-animation-class instead."),d.modalAnimation&&c.addClass(d.modalAnimationClass)}}}]).directive("modalTransclude",["$log","$modalSuppressWarning",function(a,b){return{link:function(c,d,e,f,g){b||a.warn("modal-transclude is now deprecated. Use uib-modal-transclude instead."),g(c.$parent,function(a){d.empty(),d.append(a)})}}}]).service("$modalStack",["$animate","$timeout","$document","$compile","$rootScope","$q","$injector","$$multiMap","$$stackedMap","$uibModalStack","$log","$modalSuppressWarning",function(a,b,c,d,e,f,g,h,i,j,k,l){l||k.warn("$modalStack is now deprecated. Use $uibModalStack instead."),angular.extend(this,j)}]).provider("$modal",["$uibModalProvider",function(a){angular.extend(this,a),this.$get=["$injector","$log","$modalSuppressWarning",function(b,c,d){return d||c.warn("$modal is now deprecated. Use $uibModal instead."),b.invoke(a.$get)}]}]),angular.module("ui.bootstrap.pagination",[]).controller("UibPaginationController",["$scope","$attrs","$parse",function(a,b,c){var d=this,e={$setViewValue:angular.noop},f=b.numPages?c(b.numPages).assign:angular.noop;this.init=function(g,h){e=g,this.config=h,e.$render=function(){d.render()},b.itemsPerPage?a.$parent.$watch(c(b.itemsPerPage),function(b){d.itemsPerPage=parseInt(b,10), +a.totalPages=d.calculateTotalPages()}):this.itemsPerPage=h.itemsPerPage,a.$watch("totalItems",function(){a.totalPages=d.calculateTotalPages()}),a.$watch("totalPages",function(b){f(a.$parent,b),a.page>b?a.selectPage(b):e.$render()})},this.calculateTotalPages=function(){var b=this.itemsPerPage<1?1:Math.ceil(a.totalItems/this.itemsPerPage);return Math.max(b||0,1)},this.render=function(){a.page=parseInt(e.$viewValue,10)||1},a.selectPage=function(b,c){c&&c.preventDefault();var d=!a.ngDisabled||!c;d&&a.page!==b&&b>0&&b<=a.totalPages&&(c&&c.target&&c.target.blur(),e.$setViewValue(b),e.$render())},a.getText=function(b){return a[b+"Text"]||d.config[b+"Text"]},a.noPrevious=function(){return 1===a.page},a.noNext=function(){return a.page===a.totalPages}}]).constant("uibPaginationConfig",{itemsPerPage:10,boundaryLinks:!1,directionLinks:!0,firstText:"First",previousText:"Previous",nextText:"Next",lastText:"Last",rotate:!0}).directive("uibPagination",["$parse","uibPaginationConfig",function(a,b){return{restrict:"EA",scope:{totalItems:"=",firstText:"@",previousText:"@",nextText:"@",lastText:"@",ngDisabled:"="},require:["uibPagination","?ngModel"],controller:"UibPaginationController",controllerAs:"pagination",templateUrl:function(a,b){return b.templateUrl||"template/pagination/pagination.html"},replace:!0,link:function(c,d,e,f){function g(a,b,c){return{number:a,text:b,active:c}}function h(a,b){var c=[],d=1,e=b,f=angular.isDefined(k)&&b>k;f&&(l?(d=Math.max(a-Math.floor(k/2),1),e=d+k-1,e>b&&(e=b,d=e-k+1)):(d=(Math.ceil(a/k)-1)*k+1,e=Math.min(d+k-1,b)));for(var h=d;e>=h;h++){var i=g(h,h,h===a);c.push(i)}if(f&&!l){if(d>1){var j=g(d-1,"...",!1);c.unshift(j)}if(b>e){var m=g(e+1,"...",!1);c.push(m)}}return c}var i=f[0],j=f[1];if(j){var k=angular.isDefined(e.maxSize)?c.$parent.$eval(e.maxSize):b.maxSize,l=angular.isDefined(e.rotate)?c.$parent.$eval(e.rotate):b.rotate;c.boundaryLinks=angular.isDefined(e.boundaryLinks)?c.$parent.$eval(e.boundaryLinks):b.boundaryLinks,c.directionLinks=angular.isDefined(e.directionLinks)?c.$parent.$eval(e.directionLinks):b.directionLinks,i.init(j,b),e.maxSize&&c.$parent.$watch(a(e.maxSize),function(a){k=parseInt(a,10),i.render()});var m=i.render;i.render=function(){m(),c.page>0&&c.page<=c.totalPages&&(c.pages=h(c.page,c.totalPages))}}}}}]).constant("uibPagerConfig",{itemsPerPage:10,previousText:"« Previous",nextText:"Next »",align:!0}).directive("uibPager",["uibPagerConfig",function(a){return{restrict:"EA",scope:{totalItems:"=",previousText:"@",nextText:"@",ngDisabled:"="},require:["uibPager","?ngModel"],controller:"UibPaginationController",controllerAs:"pagination",templateUrl:function(a,b){return b.templateUrl||"template/pagination/pager.html"},replace:!0,link:function(b,c,d,e){var f=e[0],g=e[1];g&&(b.align=angular.isDefined(d.align)?b.$parent.$eval(d.align):a.align,f.init(g,a))}}}]),angular.module("ui.bootstrap.pagination").value("$paginationSuppressWarning",!1).controller("PaginationController",["$scope","$attrs","$parse","$log","$paginationSuppressWarning",function(a,b,c,d,e){e||d.warn("PaginationController is now deprecated. Use UibPaginationController instead.");var f=this,g={$setViewValue:angular.noop},h=b.numPages?c(b.numPages).assign:angular.noop;this.init=function(d,e){g=d,this.config=e,g.$render=function(){f.render()},b.itemsPerPage?a.$parent.$watch(c(b.itemsPerPage),function(b){f.itemsPerPage=parseInt(b,10),a.totalPages=f.calculateTotalPages()}):this.itemsPerPage=e.itemsPerPage,a.$watch("totalItems",function(){a.totalPages=f.calculateTotalPages()}),a.$watch("totalPages",function(b){h(a.$parent,b),a.page>b?a.selectPage(b):g.$render()})},this.calculateTotalPages=function(){var b=this.itemsPerPage<1?1:Math.ceil(a.totalItems/this.itemsPerPage);return Math.max(b||0,1)},this.render=function(){a.page=parseInt(g.$viewValue,10)||1},a.selectPage=function(b,c){c&&c.preventDefault();var d=!a.ngDisabled||!c;d&&a.page!==b&&b>0&&b<=a.totalPages&&(c&&c.target&&c.target.blur(),g.$setViewValue(b),g.$render())},a.getText=function(b){return a[b+"Text"]||f.config[b+"Text"]},a.noPrevious=function(){return 1===a.page},a.noNext=function(){return a.page===a.totalPages}}]).directive("pagination",["$parse","uibPaginationConfig","$log","$paginationSuppressWarning",function(a,b,c,d){return{restrict:"EA",scope:{totalItems:"=",firstText:"@",previousText:"@",nextText:"@",lastText:"@",ngDisabled:"="},require:["pagination","?ngModel"],controller:"PaginationController",controllerAs:"pagination",templateUrl:function(a,b){return b.templateUrl||"template/pagination/pagination.html"},replace:!0,link:function(e,f,g,h){function i(a,b,c){return{number:a,text:b,active:c}}function j(a,b){var c=[],d=1,e=b,f=angular.isDefined(m)&&b>m;f&&(n?(d=Math.max(a-Math.floor(m/2),1),e=d+m-1,e>b&&(e=b,d=e-m+1)):(d=(Math.ceil(a/m)-1)*m+1,e=Math.min(d+m-1,b)));for(var g=d;e>=g;g++){var h=i(g,g,g===a);c.push(h)}if(f&&!n){if(d>1){var j=i(d-1,"...",!1);c.unshift(j)}if(b>e){var k=i(e+1,"...",!1);c.push(k)}}return c}d||c.warn("pagination is now deprecated. Use uib-pagination instead.");var k=h[0],l=h[1];if(l){var m=angular.isDefined(g.maxSize)?e.$parent.$eval(g.maxSize):b.maxSize,n=angular.isDefined(g.rotate)?e.$parent.$eval(g.rotate):b.rotate;e.boundaryLinks=angular.isDefined(g.boundaryLinks)?e.$parent.$eval(g.boundaryLinks):b.boundaryLinks,e.directionLinks=angular.isDefined(g.directionLinks)?e.$parent.$eval(g.directionLinks):b.directionLinks,k.init(l,b),g.maxSize&&e.$parent.$watch(a(g.maxSize),function(a){m=parseInt(a,10),k.render()});var o=k.render;k.render=function(){o(),e.page>0&&e.page<=e.totalPages&&(e.pages=j(e.page,e.totalPages))}}}}}]).directive("pager",["uibPagerConfig","$log","$paginationSuppressWarning",function(a,b,c){return{restrict:"EA",scope:{totalItems:"=",previousText:"@",nextText:"@",ngDisabled:"="},require:["pager","?ngModel"],controller:"PaginationController",controllerAs:"pagination",templateUrl:function(a,b){return b.templateUrl||"template/pagination/pager.html"},replace:!0,link:function(d,e,f,g){c||b.warn("pager is now deprecated. Use uib-pager instead.");var h=g[0],i=g[1];i&&(d.align=angular.isDefined(f.align)?d.$parent.$eval(f.align):a.align,h.init(i,a))}}}]),angular.module("ui.bootstrap.tooltip",["ui.bootstrap.position","ui.bootstrap.stackedMap"]).provider("$uibTooltip",function(){function a(a){var b=/[A-Z]/g,c="-";return a.replace(b,function(a,b){return(b?c:"")+a.toLowerCase()})}var b={placement:"top",animation:!0,popupDelay:0,popupCloseDelay:0,useContentExp:!1},c={mouseenter:"mouseleave",click:"click",focus:"blur",none:""},d={};this.options=function(a){angular.extend(d,a)},this.setTriggers=function(a){angular.extend(c,a)},this.$get=["$window","$compile","$timeout","$document","$uibPosition","$interpolate","$rootScope","$parse","$$stackedMap",function(e,f,g,h,i,j,k,l,m){var n=m.createNew();return h.on("keypress",function(a){if(27===a.which){var b=n.top();b&&(b.value.close(),n.removeTop(),b=null)}}),function(e,k,m,o){function p(a){var b=(a||o.trigger||m).split(" "),d=b.map(function(a){return c[a]||a});return{show:b,hide:d}}o=angular.extend({},b,d,o);var q=a(e),r=j.startSymbol(),s=j.endSymbol(),t="
      ';return{compile:function(a,b){var c=f(t);return function(a,b,d,f){function j(){L.isOpen?q():m()}function m(){(!K||a.$eval(d[k+"Enable"]))&&(u(),x(),L.popupDelay?F||(F=g(r,L.popupDelay,!1)):r())}function q(){s(),L.popupCloseDelay?G||(G=g(t,L.popupCloseDelay,!1)):t()}function r(){return s(),u(),L.content?(v(),void L.$evalAsync(function(){L.isOpen=!0,y(!0),Q()})):angular.noop}function s(){F&&(g.cancel(F),F=null),H&&(g.cancel(H),H=null)}function t(){s(),u(),L&&L.$evalAsync(function(){L.isOpen=!1,y(!1),L.animation?E||(E=g(w,150,!1)):w()})}function u(){G&&(g.cancel(G),G=null),E&&(g.cancel(E),E=null)}function v(){C||(D=L.$new(),C=c(D,function(a){I?h.find("body").append(a):b.after(a)}),z())}function w(){A(),E=null,C&&(C.remove(),C=null),D&&(D.$destroy(),D=null)}function x(){L.title=d[k+"Title"],O?L.content=O(a):L.content=d[e],L.popupClass=d[k+"Class"],L.placement=angular.isDefined(d[k+"Placement"])?d[k+"Placement"]:o.placement;var b=parseInt(d[k+"PopupDelay"],10),c=parseInt(d[k+"PopupCloseDelay"],10);L.popupDelay=isNaN(b)?o.popupDelay:b,L.popupCloseDelay=isNaN(c)?o.popupCloseDelay:c}function y(b){N&&angular.isFunction(N.assign)&&N.assign(a,b)}function z(){P.length=0,O?(P.push(a.$watch(O,function(a){L.content=a,!a&&L.isOpen&&t()})),P.push(D.$watch(function(){M||(M=!0,D.$$postDigest(function(){M=!1,L&&L.isOpen&&Q()}))}))):P.push(d.$observe(e,function(a){L.content=a,!a&&L.isOpen?t():Q()})),P.push(d.$observe(k+"Title",function(a){L.title=a,L.isOpen&&Q()})),P.push(d.$observe(k+"Placement",function(a){L.placement=a?a:o.placement,L.isOpen&&Q()}))}function A(){P.length&&(angular.forEach(P,function(a){a()}),P.length=0)}function B(){var a=d[k+"Trigger"];R(),J=p(a),"none"!==J.show&&J.show.forEach(function(a,c){a===J.hide[c]?b[0].addEventListener(a,j):a&&(b[0].addEventListener(a,m),J.hide[c].split(" ").forEach(function(a){b[0].addEventListener(a,q)})),b.on("keypress",function(a){27===a.which&&q()})})}var C,D,E,F,G,H,I=angular.isDefined(o.appendToBody)?o.appendToBody:!1,J=p(void 0),K=angular.isDefined(d[k+"Enable"]),L=a.$new(!0),M=!1,N=angular.isDefined(d[k+"IsOpen"])?l(d[k+"IsOpen"]):!1,O=o.useContentExp?l(d[e]):!1,P=[],Q=function(){C&&C.html()&&(H||(H=g(function(){C.css({top:0,left:0});var a=i.positionElements(b,C,L.placement,I);a.top+="px",a.left+="px",a.visibility="visible",C.css(a),H=null},0,!1)))};L.origScope=a,L.isOpen=!1,n.add(L,{close:t}),L.contentExp=function(){return L.content},d.$observe("disabled",function(a){a&&s(),a&&L.isOpen&&t()}),N&&a.$watch(N,function(a){L&&!a===L.isOpen&&j()});var R=function(){J.show.forEach(function(a){b.unbind(a,m)}),J.hide.forEach(function(a){a.split(" ").forEach(function(a){b[0].removeEventListener(a,q)})})};B();var S=a.$eval(d[k+"Animation"]);L.animation=angular.isDefined(S)?!!S:o.animation;var T=a.$eval(d[k+"AppendToBody"]);I=angular.isDefined(T)?T:I,I&&a.$on("$locationChangeSuccess",function(){L.isOpen&&t()}),a.$on("$destroy",function(){s(),u(),R(),w(),n.remove(L),L=null})}}}}}]}).directive("uibTooltipTemplateTransclude",["$animate","$sce","$compile","$templateRequest",function(a,b,c,d){return{link:function(e,f,g){var h,i,j,k=e.$eval(g.tooltipTemplateTranscludeScope),l=0,m=function(){i&&(i.remove(),i=null),h&&(h.$destroy(),h=null),j&&(a.leave(j).then(function(){i=null}),i=j,j=null)};e.$watch(b.parseAsResourceUrl(g.uibTooltipTemplateTransclude),function(b){var g=++l;b?(d(b,!0).then(function(d){if(g===l){var e=k.$new(),i=d,n=c(i)(e,function(b){m(),a.enter(b,f)});h=e,j=n,h.$emit("$includeContentLoaded",b)}},function(){g===l&&(m(),e.$emit("$includeContentError",b))}),e.$emit("$includeContentRequested",b)):m()}),e.$on("$destroy",m)}}}]).directive("uibTooltipClasses",function(){return{restrict:"A",link:function(a,b,c){a.placement&&b.addClass(a.placement),a.popupClass&&b.addClass(a.popupClass),a.animation()&&b.addClass(c.tooltipAnimationClass)}}}).directive("uibTooltipPopup",function(){return{replace:!0,scope:{content:"@",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/tooltip/tooltip-popup.html",link:function(a,b){b.addClass("tooltip")}}}).directive("uibTooltip",["$uibTooltip",function(a){return a("uibTooltip","tooltip","mouseenter")}]).directive("uibTooltipTemplatePopup",function(){return{replace:!0,scope:{contentExp:"&",placement:"@",popupClass:"@",animation:"&",isOpen:"&",originScope:"&"},templateUrl:"template/tooltip/tooltip-template-popup.html",link:function(a,b){b.addClass("tooltip")}}}).directive("uibTooltipTemplate",["$uibTooltip",function(a){return a("uibTooltipTemplate","tooltip","mouseenter",{useContentExp:!0})}]).directive("uibTooltipHtmlPopup",function(){return{replace:!0,scope:{contentExp:"&",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/tooltip/tooltip-html-popup.html",link:function(a,b){b.addClass("tooltip")}}}).directive("uibTooltipHtml",["$uibTooltip",function(a){return a("uibTooltipHtml","tooltip","mouseenter",{useContentExp:!0})}]),angular.module("ui.bootstrap.tooltip").value("$tooltipSuppressWarning",!1).provider("$tooltip",["$uibTooltipProvider",function(a){angular.extend(this,a),this.$get=["$log","$tooltipSuppressWarning","$injector",function(b,c,d){return c||b.warn("$tooltip is now deprecated. Use $uibTooltip instead."),d.invoke(a.$get)}]}]).directive("tooltipTemplateTransclude",["$animate","$sce","$compile","$templateRequest","$log","$tooltipSuppressWarning",function(a,b,c,d,e,f){return{link:function(g,h,i){f||e.warn("tooltip-template-transclude is now deprecated. Use uib-tooltip-template-transclude instead.");var j,k,l,m=g.$eval(i.tooltipTemplateTranscludeScope),n=0,o=function(){k&&(k.remove(),k=null),j&&(j.$destroy(),j=null),l&&(a.leave(l).then(function(){k=null}),k=l,l=null)};g.$watch(b.parseAsResourceUrl(i.tooltipTemplateTransclude),function(b){var e=++n;b?(d(b,!0).then(function(d){if(e===n){var f=m.$new(),g=d,i=c(g)(f,function(b){o(),a.enter(b,h)});j=f,l=i,j.$emit("$includeContentLoaded",b)}},function(){e===n&&(o(),g.$emit("$includeContentError",b))}),g.$emit("$includeContentRequested",b)):o()}),g.$on("$destroy",o)}}}]).directive("tooltipClasses",["$log","$tooltipSuppressWarning",function(a,b){return{restrict:"A",link:function(c,d,e){b||a.warn("tooltip-classes is now deprecated. Use uib-tooltip-classes instead."),c.placement&&d.addClass(c.placement),c.popupClass&&d.addClass(c.popupClass),c.animation()&&d.addClass(e.tooltipAnimationClass)}}}]).directive("tooltipPopup",["$log","$tooltipSuppressWarning",function(a,b){return{replace:!0,scope:{content:"@",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/tooltip/tooltip-popup.html",link:function(c,d){b||a.warn("tooltip-popup is now deprecated. Use uib-tooltip-popup instead."),d.addClass("tooltip")}}}]).directive("tooltip",["$tooltip",function(a){return a("tooltip","tooltip","mouseenter")}]).directive("tooltipTemplatePopup",["$log","$tooltipSuppressWarning",function(a,b){return{replace:!0,scope:{contentExp:"&",placement:"@",popupClass:"@",animation:"&",isOpen:"&",originScope:"&"},templateUrl:"template/tooltip/tooltip-template-popup.html",link:function(c,d){b||a.warn("tooltip-template-popup is now deprecated. Use uib-tooltip-template-popup instead."),d.addClass("tooltip")}}}]).directive("tooltipTemplate",["$tooltip",function(a){return a("tooltipTemplate","tooltip","mouseenter",{useContentExp:!0})}]).directive("tooltipHtmlPopup",["$log","$tooltipSuppressWarning",function(a,b){return{replace:!0,scope:{contentExp:"&",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/tooltip/tooltip-html-popup.html",link:function(c,d){b||a.warn("tooltip-html-popup is now deprecated. Use uib-tooltip-html-popup instead."),d.addClass("tooltip")}}}]).directive("tooltipHtml",["$tooltip",function(a){return a("tooltipHtml","tooltip","mouseenter",{useContentExp:!0})}]),angular.module("ui.bootstrap.popover",["ui.bootstrap.tooltip"]).directive("uibPopoverTemplatePopup",function(){return{replace:!0,scope:{title:"@",contentExp:"&",placement:"@",popupClass:"@",animation:"&",isOpen:"&",originScope:"&"},templateUrl:"template/popover/popover-template.html",link:function(a,b){b.addClass("popover")}}}).directive("uibPopoverTemplate",["$uibTooltip",function(a){return a("uibPopoverTemplate","popover","click",{useContentExp:!0})}]).directive("uibPopoverHtmlPopup",function(){return{replace:!0,scope:{contentExp:"&",title:"@",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/popover/popover-html.html",link:function(a,b){b.addClass("popover")}}}).directive("uibPopoverHtml",["$uibTooltip",function(a){return a("uibPopoverHtml","popover","click",{useContentExp:!0})}]).directive("uibPopoverPopup",function(){return{replace:!0,scope:{title:"@",content:"@",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/popover/popover.html",link:function(a,b){b.addClass("popover")}}}).directive("uibPopover",["$uibTooltip",function(a){return a("uibPopover","popover","click")}]),angular.module("ui.bootstrap.popover").value("$popoverSuppressWarning",!1).directive("popoverTemplatePopup",["$log","$popoverSuppressWarning",function(a,b){return{replace:!0,scope:{title:"@",contentExp:"&",placement:"@",popupClass:"@",animation:"&",isOpen:"&",originScope:"&"},templateUrl:"template/popover/popover-template.html",link:function(c,d){b||a.warn("popover-template-popup is now deprecated. Use uib-popover-template-popup instead."),d.addClass("popover")}}}]).directive("popoverTemplate",["$tooltip",function(a){return a("popoverTemplate","popover","click",{useContentExp:!0})}]).directive("popoverHtmlPopup",["$log","$popoverSuppressWarning",function(a,b){return{replace:!0,scope:{contentExp:"&",title:"@",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/popover/popover-html.html",link:function(c,d){b||a.warn("popover-html-popup is now deprecated. Use uib-popover-html-popup instead."),d.addClass("popover")}}}]).directive("popoverHtml",["$tooltip",function(a){return a("popoverHtml","popover","click",{useContentExp:!0})}]).directive("popoverPopup",["$log","$popoverSuppressWarning",function(a,b){return{replace:!0,scope:{title:"@",content:"@",placement:"@",popupClass:"@",animation:"&",isOpen:"&"},templateUrl:"template/popover/popover.html",link:function(c,d){b||a.warn("popover-popup is now deprecated. Use uib-popover-popup instead."),d.addClass("popover")}}}]).directive("popover",["$tooltip",function(a){return a("popover","popover","click")}]),angular.module("ui.bootstrap.progressbar",[]).constant("uibProgressConfig",{animate:!0,max:100}).controller("UibProgressController",["$scope","$attrs","uibProgressConfig",function(a,b,c){var d=this,e=angular.isDefined(b.animate)?a.$parent.$eval(b.animate):c.animate;this.bars=[],a.max=angular.isDefined(a.max)?a.max:c.max,this.addBar=function(b,c,f){e||c.css({transition:"none"}),this.bars.push(b),b.max=a.max,b.title=f&&angular.isDefined(f.title)?f.title:"progressbar",b.$watch("value",function(a){b.recalculatePercentage()}),b.recalculatePercentage=function(){var a=d.bars.reduce(function(a,b){return b.percent=+(100*b.value/b.max).toFixed(2),a+b.percent},0);a>100&&(b.percent-=a-100)},b.$on("$destroy",function(){c=null,d.removeBar(b)})},this.removeBar=function(a){this.bars.splice(this.bars.indexOf(a),1),this.bars.forEach(function(a){a.recalculatePercentage()})},a.$watch("max",function(b){d.bars.forEach(function(b){b.max=a.max,b.recalculatePercentage()})})}]).directive("uibProgress",function(){return{replace:!0,transclude:!0,controller:"UibProgressController",require:"uibProgress",scope:{max:"=?"},templateUrl:"template/progressbar/progress.html"}}).directive("uibBar",function(){return{replace:!0,transclude:!0,require:"^uibProgress",scope:{value:"=",type:"@"},templateUrl:"template/progressbar/bar.html",link:function(a,b,c,d){d.addBar(a,b,c)}}}).directive("uibProgressbar",function(){return{replace:!0,transclude:!0,controller:"UibProgressController",scope:{value:"=",max:"=?",type:"@"},templateUrl:"template/progressbar/progressbar.html",link:function(a,b,c,d){d.addBar(a,angular.element(b.children()[0]),{title:c.title})}}}),angular.module("ui.bootstrap.progressbar").value("$progressSuppressWarning",!1).controller("ProgressController",["$scope","$attrs","uibProgressConfig","$log","$progressSuppressWarning",function(a,b,c,d,e){e||d.warn("ProgressController is now deprecated. Use UibProgressController instead.");var f=this,g=angular.isDefined(b.animate)?a.$parent.$eval(b.animate):c.animate;this.bars=[],a.max=angular.isDefined(a.max)?a.max:c.max,this.addBar=function(b,c,d){g||c.css({transition:"none"}),this.bars.push(b),b.max=a.max,b.title=d&&angular.isDefined(d.title)?d.title:"progressbar",b.$watch("value",function(a){b.recalculatePercentage()}),b.recalculatePercentage=function(){b.percent=+(100*b.value/b.max).toFixed(2);var a=f.bars.reduce(function(a,b){return a+b.percent},0);a>100&&(b.percent-=a-100)},b.$on("$destroy",function(){c=null,f.removeBar(b)})},this.removeBar=function(a){this.bars.splice(this.bars.indexOf(a),1)},a.$watch("max",function(b){f.bars.forEach(function(b){b.max=a.max,b.recalculatePercentage()})})}]).directive("progress",["$log","$progressSuppressWarning",function(a,b){return{replace:!0,transclude:!0,controller:"ProgressController",require:"progress",scope:{max:"=?",title:"@?"},templateUrl:"template/progressbar/progress.html",link:function(){b||a.warn("progress is now deprecated. Use uib-progress instead.")}}}]).directive("bar",["$log","$progressSuppressWarning",function(a,b){return{replace:!0,transclude:!0,require:"^progress",scope:{value:"=",type:"@"},templateUrl:"template/progressbar/bar.html",link:function(c,d,e,f){b||a.warn("bar is now deprecated. Use uib-bar instead."),f.addBar(c,d)}}}]).directive("progressbar",["$log","$progressSuppressWarning",function(a,b){return{replace:!0,transclude:!0,controller:"ProgressController",scope:{value:"=",max:"=?",type:"@"},templateUrl:"template/progressbar/progressbar.html",link:function(c,d,e,f){b||a.warn("progressbar is now deprecated. Use uib-progressbar instead."),f.addBar(c,angular.element(d.children()[0]),{title:e.title})}}}]),angular.module("ui.bootstrap.rating",[]).constant("uibRatingConfig",{max:5,stateOn:null,stateOff:null,titles:["one","two","three","four","five"]}).controller("UibRatingController",["$scope","$attrs","uibRatingConfig",function(a,b,c){var d={$setViewValue:angular.noop};this.init=function(e){d=e,d.$render=this.render,d.$formatters.push(function(a){return angular.isNumber(a)&&a<<0!==a&&(a=Math.round(a)),a}),this.stateOn=angular.isDefined(b.stateOn)?a.$parent.$eval(b.stateOn):c.stateOn,this.stateOff=angular.isDefined(b.stateOff)?a.$parent.$eval(b.stateOff):c.stateOff;var f=angular.isDefined(b.titles)?a.$parent.$eval(b.titles):c.titles;this.titles=angular.isArray(f)&&f.length>0?f:c.titles;var g=angular.isDefined(b.ratingStates)?a.$parent.$eval(b.ratingStates):new Array(angular.isDefined(b.max)?a.$parent.$eval(b.max):c.max);a.range=this.buildTemplateObjects(g)},this.buildTemplateObjects=function(a){for(var b=0,c=a.length;c>b;b++)a[b]=angular.extend({index:b},{stateOn:this.stateOn,stateOff:this.stateOff,title:this.getTitle(b)},a[b]);return a},this.getTitle=function(a){return a>=this.titles.length?a+1:this.titles[a]},a.rate=function(b){!a.readonly&&b>=0&&b<=a.range.length&&(d.$setViewValue(d.$viewValue===b?0:b),d.$render())},a.enter=function(b){a.readonly||(a.value=b),a.onHover({value:b})},a.reset=function(){a.value=d.$viewValue,a.onLeave()},a.onKeydown=function(b){/(37|38|39|40)/.test(b.which)&&(b.preventDefault(),b.stopPropagation(),a.rate(a.value+(38===b.which||39===b.which?1:-1)))},this.render=function(){a.value=d.$viewValue}}]).directive("uibRating",function(){return{require:["uibRating","ngModel"],scope:{readonly:"=?",onHover:"&",onLeave:"&"},controller:"UibRatingController",templateUrl:"template/rating/rating.html",replace:!0,link:function(a,b,c,d){var e=d[0],f=d[1];e.init(f)}}}),angular.module("ui.bootstrap.rating").value("$ratingSuppressWarning",!1).controller("RatingController",["$scope","$attrs","$controller","$log","$ratingSuppressWarning",function(a,b,c,d,e){e||d.warn("RatingController is now deprecated. Use UibRatingController instead."),angular.extend(this,c("UibRatingController",{$scope:a,$attrs:b}))}]).directive("rating",["$log","$ratingSuppressWarning",function(a,b){return{require:["rating","ngModel"],scope:{readonly:"=?",onHover:"&",onLeave:"&"},controller:"RatingController",templateUrl:"template/rating/rating.html",replace:!0,link:function(c,d,e,f){b||a.warn("rating is now deprecated. Use uib-rating instead.");var g=f[0],h=f[1];g.init(h)}}}]),angular.module("ui.bootstrap.tabs",[]).controller("UibTabsetController",["$scope",function(a){var b=this,c=b.tabs=a.tabs=[];b.select=function(a){angular.forEach(c,function(b){b.active&&b!==a&&(b.active=!1,b.onDeselect(),a.selectCalled=!1)}),a.active=!0,a.selectCalled||(a.onSelect(),a.selectCalled=!0)},b.addTab=function(a){c.push(a),1===c.length&&a.active!==!1?a.active=!0:a.active?b.select(a):a.active=!1},b.removeTab=function(a){var e=c.indexOf(a);if(a.active&&c.length>1&&!d){var f=e==c.length-1?e-1:e+1;b.select(c[f])}c.splice(e,1)};var d;a.$on("$destroy",function(){d=!0})}]).directive("uibTabset",function(){return{restrict:"EA",transclude:!0,replace:!0,scope:{type:"@"},controller:"UibTabsetController",templateUrl:"template/tabs/tabset.html",link:function(a,b,c){a.vertical=angular.isDefined(c.vertical)?a.$parent.$eval(c.vertical):!1,a.justified=angular.isDefined(c.justified)?a.$parent.$eval(c.justified):!1}}}).directive("uibTab",["$parse",function(a){return{require:"^uibTabset",restrict:"EA",replace:!0,templateUrl:"template/tabs/tab.html",transclude:!0,scope:{active:"=?",heading:"@",onSelect:"&select",onDeselect:"&deselect"},controller:function(){},link:function(b,c,d,e,f){b.$watch("active",function(a){a&&e.select(b)}),b.disabled=!1,d.disable&&b.$parent.$watch(a(d.disable),function(a){b.disabled=!!a}),b.select=function(){b.disabled||(b.active=!0)},e.addTab(b),b.$on("$destroy",function(){e.removeTab(b)}),b.$transcludeFn=f}}}]).directive("uibTabHeadingTransclude",function(){return{restrict:"A",require:["?^uibTab","?^tab"],link:function(a,b){a.$watch("headingElement",function(a){a&&(b.html(""),b.append(a))})}}}).directive("uibTabContentTransclude",function(){function a(a){return a.tagName&&(a.hasAttribute("tab-heading")||a.hasAttribute("data-tab-heading")||a.hasAttribute("x-tab-heading")||a.hasAttribute("uib-tab-heading")||a.hasAttribute("data-uib-tab-heading")||a.hasAttribute("x-uib-tab-heading")||"tab-heading"===a.tagName.toLowerCase()||"data-tab-heading"===a.tagName.toLowerCase()||"x-tab-heading"===a.tagName.toLowerCase()||"uib-tab-heading"===a.tagName.toLowerCase()||"data-uib-tab-heading"===a.tagName.toLowerCase()||"x-uib-tab-heading"===a.tagName.toLowerCase())}return{restrict:"A",require:["?^uibTabset","?^tabset"],link:function(b,c,d){var e=b.$eval(d.uibTabContentTransclude);e.$transcludeFn(e.$parent,function(b){angular.forEach(b,function(b){a(b)?e.headingElement=b:c.append(b)})})}}}),angular.module("ui.bootstrap.tabs").value("$tabsSuppressWarning",!1).controller("TabsetController",["$scope","$controller","$log","$tabsSuppressWarning",function(a,b,c,d){d||c.warn("TabsetController is now deprecated. Use UibTabsetController instead."),angular.extend(this,b("UibTabsetController",{$scope:a}))}]).directive("tabset",["$log","$tabsSuppressWarning",function(a,b){return{restrict:"EA",transclude:!0,replace:!0,scope:{type:"@"},controller:"TabsetController",templateUrl:"template/tabs/tabset.html",link:function(c,d,e){b||a.warn("tabset is now deprecated. Use uib-tabset instead."),c.vertical=angular.isDefined(e.vertical)?c.$parent.$eval(e.vertical):!1,c.justified=angular.isDefined(e.justified)?c.$parent.$eval(e.justified):!1}}}]).directive("tab",["$parse","$log","$tabsSuppressWarning",function(a,b,c){return{require:"^tabset",restrict:"EA",replace:!0,templateUrl:"template/tabs/tab.html",transclude:!0,scope:{active:"=?",heading:"@",onSelect:"&select",onDeselect:"&deselect"},controller:function(){},link:function(d,e,f,g,h){c||b.warn("tab is now deprecated. Use uib-tab instead."),d.$watch("active",function(a){a&&g.select(d)}),d.disabled=!1,f.disable&&d.$parent.$watch(a(f.disable),function(a){d.disabled=!!a}),d.select=function(){d.disabled||(d.active=!0)},g.addTab(d),d.$on("$destroy",function(){g.removeTab(d)}),d.$transcludeFn=h}}}]).directive("tabHeadingTransclude",["$log","$tabsSuppressWarning",function(a,b){return{restrict:"A",require:"^tab",link:function(c,d){b||a.warn("tab-heading-transclude is now deprecated. Use uib-tab-heading-transclude instead."),c.$watch("headingElement",function(a){a&&(d.html(""),d.append(a))})}}}]).directive("tabContentTransclude",["$log","$tabsSuppressWarning",function(a,b){function c(a){return a.tagName&&(a.hasAttribute("tab-heading")||a.hasAttribute("data-tab-heading")||a.hasAttribute("x-tab-heading")||"tab-heading"===a.tagName.toLowerCase()||"data-tab-heading"===a.tagName.toLowerCase()||"x-tab-heading"===a.tagName.toLowerCase())}return{restrict:"A",require:"^tabset",link:function(d,e,f){b||a.warn("tab-content-transclude is now deprecated. Use uib-tab-content-transclude instead.");var g=d.$eval(f.tabContentTransclude);g.$transcludeFn(g.$parent,function(a){angular.forEach(a,function(a){c(a)?g.headingElement=a:e.append(a)})})}}}]),angular.module("ui.bootstrap.timepicker",[]).constant("uibTimepickerConfig",{hourStep:1,minuteStep:1,showMeridian:!0,meridians:null,readonlyInput:!1,mousewheel:!0,arrowkeys:!0,showSpinners:!0}).controller("UibTimepickerController",["$scope","$element","$attrs","$parse","$log","$locale","uibTimepickerConfig",function(a,b,c,d,e,f,g){function h(){var b=parseInt(a.hours,10),c=a.showMeridian?b>0&&13>b:b>=0&&24>b;return c?(a.showMeridian&&(12===b&&(b=0),a.meridian===r[1]&&(b+=12)),b):void 0}function i(){var b=parseInt(a.minutes,10);return b>=0&&60>b?b:void 0}function j(a){return angular.isDefined(a)&&a.toString().length<2?"0"+a:a.toString()}function k(a){l(),q.$setViewValue(new Date(p)),m(a)}function l(){q.$setValidity("time",!0),a.invalidHours=!1,a.invalidMinutes=!1}function m(b){var c=p.getHours(),d=p.getMinutes();a.showMeridian&&(c=0===c||12===c?12:c%12),a.hours="h"===b?c:j(c),"m"!==b&&(a.minutes=j(d)),a.meridian=p.getHours()<12?r[0]:r[1]}function n(a,b){var c=new Date(a.getTime()+6e4*b),d=new Date(a);return d.setHours(c.getHours(),c.getMinutes()),d}function o(a){p=n(p,a),k()}var p=new Date,q={$setViewValue:angular.noop},r=angular.isDefined(c.meridians)?a.$parent.$eval(c.meridians):g.meridians||f.DATETIME_FORMATS.AMPMS;a.tabindex=angular.isDefined(c.tabindex)?c.tabindex:0,b.removeAttr("tabindex"),this.init=function(b,d){q=b,q.$render=this.render,q.$formatters.unshift(function(a){return a?new Date(a):null});var e=d.eq(0),f=d.eq(1),h=angular.isDefined(c.mousewheel)?a.$parent.$eval(c.mousewheel):g.mousewheel;h&&this.setupMousewheelEvents(e,f);var i=angular.isDefined(c.arrowkeys)?a.$parent.$eval(c.arrowkeys):g.arrowkeys;i&&this.setupArrowkeyEvents(e,f),a.readonlyInput=angular.isDefined(c.readonlyInput)?a.$parent.$eval(c.readonlyInput):g.readonlyInput,this.setupInputEvents(e,f)};var s=g.hourStep;c.hourStep&&a.$parent.$watch(d(c.hourStep),function(a){s=parseInt(a,10)});var t=g.minuteStep;c.minuteStep&&a.$parent.$watch(d(c.minuteStep),function(a){t=parseInt(a,10)});var u;a.$parent.$watch(d(c.min),function(a){var b=new Date(a);u=isNaN(b)?void 0:b});var v;a.$parent.$watch(d(c.max),function(a){var b=new Date(a);v=isNaN(b)?void 0:b}),a.noIncrementHours=function(){var a=n(p,60*s);return a>v||p>a&&u>a},a.noDecrementHours=function(){var a=n(p,60*-s);return u>a||a>p&&a>v},a.noIncrementMinutes=function(){var a=n(p,t);return a>v||p>a&&u>a},a.noDecrementMinutes=function(){var a=n(p,-t);return u>a||a>p&&a>v},a.noToggleMeridian=function(){return p.getHours()<13?n(p,720)>v:n(p,-720)0};b.bind("mousewheel wheel",function(b){a.$apply(d(b)?a.incrementHours():a.decrementHours()),b.preventDefault()}),c.bind("mousewheel wheel",function(b){a.$apply(d(b)?a.incrementMinutes():a.decrementMinutes()),b.preventDefault()})},this.setupArrowkeyEvents=function(b,c){b.bind("keydown",function(b){38===b.which?(b.preventDefault(),a.incrementHours(),a.$apply()):40===b.which&&(b.preventDefault(), +a.decrementHours(),a.$apply())}),c.bind("keydown",function(b){38===b.which?(b.preventDefault(),a.incrementMinutes(),a.$apply()):40===b.which&&(b.preventDefault(),a.decrementMinutes(),a.$apply())})},this.setupInputEvents=function(b,c){if(a.readonlyInput)return a.updateHours=angular.noop,void(a.updateMinutes=angular.noop);var d=function(b,c){q.$setViewValue(null),q.$setValidity("time",!1),angular.isDefined(b)&&(a.invalidHours=b),angular.isDefined(c)&&(a.invalidMinutes=c)};a.updateHours=function(){var a=h(),b=i();angular.isDefined(a)&&angular.isDefined(b)?(p.setHours(a),u>p||p>v?d(!0):k("h")):d(!0)},b.bind("blur",function(b){!a.invalidHours&&a.hours<10&&a.$apply(function(){a.hours=j(a.hours)})}),a.updateMinutes=function(){var a=i(),b=h();angular.isDefined(a)&&angular.isDefined(b)?(p.setMinutes(a),u>p||p>v?d(void 0,!0):k("m")):d(void 0,!0)},c.bind("blur",function(b){!a.invalidMinutes&&a.minutes<10&&a.$apply(function(){a.minutes=j(a.minutes)})})},this.render=function(){var b=q.$viewValue;isNaN(b)?(q.$setValidity("time",!1),e.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.')):(b&&(p=b),u>p||p>v?(q.$setValidity("time",!1),a.invalidHours=!0,a.invalidMinutes=!0):l(),m())},a.showSpinners=angular.isDefined(c.showSpinners)?a.$parent.$eval(c.showSpinners):g.showSpinners,a.incrementHours=function(){a.noIncrementHours()||o(60*s)},a.decrementHours=function(){a.noDecrementHours()||o(60*-s)},a.incrementMinutes=function(){a.noIncrementMinutes()||o(t)},a.decrementMinutes=function(){a.noDecrementMinutes()||o(-t)},a.toggleMeridian=function(){a.noToggleMeridian()||o(720*(p.getHours()<12?1:-1))}}]).directive("uibTimepicker",function(){return{restrict:"EA",require:["uibTimepicker","?^ngModel"],controller:"UibTimepickerController",controllerAs:"timepicker",replace:!0,scope:{},templateUrl:function(a,b){return b.templateUrl||"template/timepicker/timepicker.html"},link:function(a,b,c,d){var e=d[0],f=d[1];f&&e.init(f,b.find("input"))}}}),angular.module("ui.bootstrap.timepicker").value("$timepickerSuppressWarning",!1).controller("TimepickerController",["$scope","$element","$attrs","$controller","$log","$timepickerSuppressWarning",function(a,b,c,d,e,f){f||e.warn("TimepickerController is now deprecated. Use UibTimepickerController instead."),angular.extend(this,d("UibTimepickerController",{$scope:a,$element:b,$attrs:c}))}]).directive("timepicker",["$log","$timepickerSuppressWarning",function(a,b){return{restrict:"EA",require:["timepicker","?^ngModel"],controller:"TimepickerController",controllerAs:"timepicker",replace:!0,scope:{},templateUrl:function(a,b){return b.templateUrl||"template/timepicker/timepicker.html"},link:function(c,d,e,f){b||a.warn("timepicker is now deprecated. Use uib-timepicker instead.");var g=f[0],h=f[1];h&&g.init(h,d.find("input"))}}}]),angular.module("ui.bootstrap.typeahead",["ui.bootstrap.position"]).factory("uibTypeaheadParser",["$parse",function(a){var b=/^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/;return{parse:function(c){var d=c.match(b);if(!d)throw new Error('Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_" but got "'+c+'".');return{itemName:d[3],source:a(d[4]),viewMapper:a(d[2]||d[1]),modelMapper:a(d[1])}}}}]).controller("UibTypeaheadController",["$scope","$element","$attrs","$compile","$parse","$q","$timeout","$document","$window","$rootScope","$uibPosition","uibTypeaheadParser",function(a,b,c,d,e,f,g,h,i,j,k,l){function m(){K.moveInProgress||(K.moveInProgress=!0,K.$digest()),S&&g.cancel(S),S=g(function(){K.matches.length&&n(),K.moveInProgress=!1},r)}function n(){K.position=C?k.offset(b):k.position(b),K.position.top+=b.prop("offsetHeight")}var o,p,q=[9,13,27,38,40],r=200,s=a.$eval(c.typeaheadMinLength);s||0===s||(s=1);var t,u,v=a.$eval(c.typeaheadWaitMs)||0,w=a.$eval(c.typeaheadEditable)!==!1,x=e(c.typeaheadLoading).assign||angular.noop,y=e(c.typeaheadOnSelect),z=angular.isDefined(c.typeaheadSelectOnBlur)?a.$eval(c.typeaheadSelectOnBlur):!1,A=e(c.typeaheadNoResults).assign||angular.noop,B=c.typeaheadInputFormatter?e(c.typeaheadInputFormatter):void 0,C=c.typeaheadAppendToBody?a.$eval(c.typeaheadAppendToBody):!1,D=c.typeaheadAppendToElementId||!1,E=a.$eval(c.typeaheadFocusFirst)!==!1,F=c.typeaheadSelectOnExact?a.$eval(c.typeaheadSelectOnExact):!1,G=e(c.ngModel),H=e(c.ngModel+"($$$p)"),I=function(b,c){return angular.isFunction(G(a))&&p&&p.$options&&p.$options.getterSetter?H(b,{$$$p:c}):G.assign(b,c)},J=l.parse(c.uibTypeahead),K=a.$new(),L=a.$on("$destroy",function(){K.$destroy()});K.$on("$destroy",L);var M="typeahead-"+K.$id+"-"+Math.floor(1e4*Math.random());b.attr({"aria-autocomplete":"list","aria-expanded":!1,"aria-owns":M});var N=angular.element("
      ");N.attr({id:M,matches:"matches",active:"activeIdx",select:"select(activeIdx)","move-in-progress":"moveInProgress",query:"query",position:"position"}),angular.isDefined(c.typeaheadTemplateUrl)&&N.attr("template-url",c.typeaheadTemplateUrl),angular.isDefined(c.typeaheadPopupTemplateUrl)&&N.attr("popup-template-url",c.typeaheadPopupTemplateUrl);var O=function(){K.matches=[],K.activeIdx=-1,b.attr("aria-expanded",!1)},P=function(a){return M+"-option-"+a};K.$watch("activeIdx",function(a){0>a?b.removeAttr("aria-activedescendant"):b.attr("aria-activedescendant",P(a))});var Q=function(a,b){return K.matches.length>b&&a?a.toUpperCase()===K.matches[b].label.toUpperCase():!1},R=function(c){var d={$viewValue:c};x(a,!0),A(a,!1),f.when(J.source(a,d)).then(function(e){var f=c===o.$viewValue;if(f&&t)if(e&&e.length>0){K.activeIdx=E?0:-1,A(a,!1),K.matches.length=0;for(var g=0;g0?K.activeIdx:K.matches.length)-1,K.$digest()):13===a.which||9===a.which?K.$apply(function(){K.select(K.activeIdx)}):27===a.which&&(a.stopPropagation(),O(),K.$digest())}}),b.bind("blur",function(){z&&K.matches.length&&-1!==K.activeIdx&&!u&&(u=!0,K.$apply(function(){K.select(K.activeIdx)})),t=!1,u=!1});var W=function(a){b[0]!==a.target&&3!==a.which&&0!==K.matches.length&&(O(),j.$$phase||K.$digest())};h.bind("click",W),a.$on("$destroy",function(){h.unbind("click",W),(C||D)&&X.remove(),C&&(angular.element(i).unbind("resize",m),h.find("body").unbind("scroll",m)),N.remove()});var X=d(N)(K);C?h.find("body").append(X):D!==!1?angular.element(h[0].getElementById(D)).append(X):b.after(X),this.init=function(b,c){o=b,p=c,o.$parsers.unshift(function(b){return t=!0,0===s||b&&b.length>=s?v>0?(V(),U(b)):R(b):(x(a,!1),V(),O()),w?b:b?void o.$setValidity("editable",!1):(o.$setValidity("editable",!0),null)}),o.$formatters.push(function(b){var c,d,e={};return w||o.$setValidity("editable",!0),B?(e.$model=b,B(a,e)):(e[J.itemName]=b,c=J.viewMapper(a,e),e[J.itemName]=void 0,d=J.viewMapper(a,e),c!==d?c:b)})}}]).directive("uibTypeahead",function(){return{controller:"UibTypeaheadController",require:["ngModel","^?ngModelOptions","uibTypeahead"],link:function(a,b,c,d){d[2].init(d[0],d[1])}}}).directive("uibTypeaheadPopup",function(){return{scope:{matches:"=",query:"=",active:"=",position:"&",moveInProgress:"=",select:"&"},replace:!0,templateUrl:function(a,b){return b.popupTemplateUrl||"template/typeahead/typeahead-popup.html"},link:function(a,b,c){a.templateUrl=c.templateUrl,a.isOpen=function(){return a.matches.length>0},a.isActive=function(b){return a.active==b},a.selectActive=function(b){a.active=b},a.selectMatch=function(b){a.select({activeIdx:b})}}}}).directive("uibTypeaheadMatch",["$templateRequest","$compile","$parse",function(a,b,c){return{scope:{index:"=",match:"=",query:"="},link:function(d,e,f){var g=c(f.templateUrl)(d.$parent)||"template/typeahead/typeahead-match.html";a(g).then(function(a){b(a.trim())(d,function(a){e.replaceWith(a)})})}}}]).filter("uibTypeaheadHighlight",["$sce","$injector","$log",function(a,b,c){function d(a){return a.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")}function e(a){return/<.*>/g.test(a)}var f;return f=b.has("$sanitize"),function(b,g){return!f&&e(b)&&c.warn("Unsafe use of typeahead please use ngSanitize"),b=g?(""+b).replace(new RegExp(d(g),"gi"),"$&"):b,f||(b=a.trustAsHtml(b)),b}}]),angular.module("ui.bootstrap.typeahead").value("$typeaheadSuppressWarning",!1).service("typeaheadParser",["$parse","uibTypeaheadParser","$log","$typeaheadSuppressWarning",function(a,b,c,d){return d||c.warn("typeaheadParser is now deprecated. Use uibTypeaheadParser instead."),b}]).directive("typeahead",["$compile","$parse","$q","$timeout","$document","$window","$rootScope","$uibPosition","typeaheadParser","$log","$typeaheadSuppressWarning",function(a,b,c,d,e,f,g,h,i,j,k){var l=[9,13,27,38,40],m=200;return{require:["ngModel","^?ngModelOptions"],link:function(n,o,p,q){function r(){N.moveInProgress||(N.moveInProgress=!0,N.$digest()),V&&d.cancel(V),V=d(function(){N.matches.length&&s(),N.moveInProgress=!1},m)}function s(){N.position=F?h.offset(o):h.position(o),N.position.top+=o.prop("offsetHeight")}k||j.warn("typeahead is now deprecated. Use uib-typeahead instead.");var t=q[0],u=q[1],v=n.$eval(p.typeaheadMinLength);v||0===v||(v=1);var w,x,y=n.$eval(p.typeaheadWaitMs)||0,z=n.$eval(p.typeaheadEditable)!==!1,A=b(p.typeaheadLoading).assign||angular.noop,B=b(p.typeaheadOnSelect),C=angular.isDefined(p.typeaheadSelectOnBlur)?n.$eval(p.typeaheadSelectOnBlur):!1,D=b(p.typeaheadNoResults).assign||angular.noop,E=p.typeaheadInputFormatter?b(p.typeaheadInputFormatter):void 0,F=p.typeaheadAppendToBody?n.$eval(p.typeaheadAppendToBody):!1,G=p.typeaheadAppendToElementId||!1,H=n.$eval(p.typeaheadFocusFirst)!==!1,I=p.typeaheadSelectOnExact?n.$eval(p.typeaheadSelectOnExact):!1,J=b(p.ngModel),K=b(p.ngModel+"($$$p)"),L=function(a,b){return angular.isFunction(J(n))&&u&&u.$options&&u.$options.getterSetter?K(a,{$$$p:b}):J.assign(a,b)},M=i.parse(p.typeahead),N=n.$new(),O=n.$on("$destroy",function(){N.$destroy()});N.$on("$destroy",O);var P="typeahead-"+N.$id+"-"+Math.floor(1e4*Math.random());o.attr({"aria-autocomplete":"list","aria-expanded":!1,"aria-owns":P});var Q=angular.element("
      ");Q.attr({id:P,matches:"matches",active:"activeIdx",select:"select(activeIdx)","move-in-progress":"moveInProgress",query:"query",position:"position"}),angular.isDefined(p.typeaheadTemplateUrl)&&Q.attr("template-url",p.typeaheadTemplateUrl),angular.isDefined(p.typeaheadPopupTemplateUrl)&&Q.attr("popup-template-url",p.typeaheadPopupTemplateUrl);var R=function(){N.matches=[],N.activeIdx=-1,o.attr("aria-expanded",!1)},S=function(a){return P+"-option-"+a};N.$watch("activeIdx",function(a){0>a?o.removeAttr("aria-activedescendant"):o.attr("aria-activedescendant",S(a))});var T=function(a,b){return N.matches.length>b&&a?a.toUpperCase()===N.matches[b].label.toUpperCase():!1},U=function(a){var b={$viewValue:a};A(n,!0),D(n,!1),c.when(M.source(n,b)).then(function(c){var d=a===t.$viewValue;if(d&&w)if(c&&c.length>0){N.activeIdx=H?0:-1,D(n,!1),N.matches.length=0;for(var e=0;e=v?y>0?(Y(),X(a)):U(a):(A(n,!1),Y(),R()),z?a:a?void t.$setValidity("editable",!1):(t.$setValidity("editable",!0),null)}),t.$formatters.push(function(a){var b,c,d={};return z||t.$setValidity("editable",!0),E?(d.$model=a,E(n,d)):(d[M.itemName]=a,b=M.viewMapper(n,d),d[M.itemName]=void 0,c=M.viewMapper(n,d),b!==c?b:a)}),N.select=function(a){var b,c,e={};x=!0,e[M.itemName]=c=N.matches[a].model,b=M.modelMapper(n,e),L(n,b),t.$setValidity("editable",!0),t.$setValidity("parse",!0),B(n,{$item:c,$model:b,$label:M.viewMapper(n,e)}),R(),N.$eval(p.typeaheadFocusOnSelect)!==!1&&d(function(){o[0].focus()},0,!1)},o.bind("keydown",function(a){if(0!==N.matches.length&&-1!==l.indexOf(a.which)){if(-1===N.activeIdx&&(9===a.which||13===a.which))return R(),void N.$digest();a.preventDefault(),40===a.which?(N.activeIdx=(N.activeIdx+1)%N.matches.length,N.$digest()):38===a.which?(N.activeIdx=(N.activeIdx>0?N.activeIdx:N.matches.length)-1,N.$digest()):13===a.which||9===a.which?N.$apply(function(){N.select(N.activeIdx)}):27===a.which&&(a.stopPropagation(),R(),N.$digest())}}),o.bind("blur",function(){C&&N.matches.length&&-1!==N.activeIdx&&!x&&(x=!0,N.$apply(function(){N.select(N.activeIdx)})),w=!1,x=!1});var Z=function(a){o[0]!==a.target&&3!==a.which&&0!==N.matches.length&&(R(),g.$$phase||N.$digest())};e.bind("click",Z),n.$on("$destroy",function(){e.unbind("click",Z),(F||G)&&$.remove(),F&&(angular.element(f).unbind("resize",r),e.find("body").unbind("scroll",r)),Q.remove()});var $=a(Q)(N);F?e.find("body").append($):G!==!1?angular.element(e[0].getElementById(G)).append($):o.after($)}}}]).directive("typeaheadPopup",["$typeaheadSuppressWarning","$log",function(a,b){return{scope:{matches:"=",query:"=",active:"=",position:"&",moveInProgress:"=",select:"&"},replace:!0,templateUrl:function(a,b){return b.popupTemplateUrl||"template/typeahead/typeahead-popup.html"},link:function(c,d,e){a||b.warn("typeahead-popup is now deprecated. Use uib-typeahead-popup instead."),c.templateUrl=e.templateUrl,c.isOpen=function(){return c.matches.length>0},c.isActive=function(a){return c.active==a},c.selectActive=function(a){c.active=a},c.selectMatch=function(a){c.select({activeIdx:a})}}}}]).directive("typeaheadMatch",["$templateRequest","$compile","$parse","$typeaheadSuppressWarning","$log",function(a,b,c,d,e){return{restrict:"EA",scope:{index:"=",match:"=",query:"="},link:function(f,g,h){d||e.warn("typeahead-match is now deprecated. Use uib-typeahead-match instead.");var i=c(h.templateUrl)(f.$parent)||"template/typeahead/typeahead-match.html";a(i).then(function(a){b(a.trim())(f,function(a){g.replaceWith(a)})})}}}]).filter("typeaheadHighlight",["$sce","$injector","$log","$typeaheadSuppressWarning",function(a,b,c,d){function e(a){return a.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")}function f(a){return/<.*>/g.test(a)}var g;return g=b.has("$sanitize"),function(b,h){return d||c.warn("typeaheadHighlight is now deprecated. Use uibTypeaheadHighlight instead."),!g&&f(b)&&c.warn("Unsafe use of typeahead please use ngSanitize"),b=h?(""+b).replace(new RegExp(e(h),"gi"),"$&"):b,g||(b=a.trustAsHtml(b)),b}}]),!angular.$$csp()&&angular.element(document).find("head").prepend(''); \ No newline at end of file diff --git a/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/angular-patternfly.js b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/angular-patternfly.js new file mode 100644 index 00000000..82f52c99 --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/angular-patternfly.js @@ -0,0 +1,10378 @@ +/** + * @name patternfly card + * + * @description + * Card module for patternfly. + * + */ +angular.module('patternfly.card', []); +;/** + * @name patternfly + * + * @description + * Charts module for patternfly. Must Include d3.js and c3.js to use + * + */ +angular.module('patternfly.charts', ['patternfly.utils', 'ui.bootstrap', 'ngSanitize']); + +;/** + * @name patternfly card + * + * @description + * Filters module for patternfly. + * + */ +angular.module('patternfly.filters', ['patternfly.select', 'ui.bootstrap']); +;/** + * @name patternfly.form + * + * @description + * Module for formting related functionality, primarily filters. + */ +angular.module('patternfly.form', []); +;/** + * @name patternfly + * + * @description + * Modal module for patternfly. + * + */ +angular.module('patternfly.modals', ['ui.bootstrap.modal', 'ui.bootstrap.tpls']); +;/** + * @name patternfly navigation + * + * @description + * Navigation module for patternfly. + * + */ +angular.module('patternfly.navigation', ['ui.bootstrap']); +;/** + * @name patternfly notification + * + * @description + * Notification module for patternfly. + * + */ +angular.module('patternfly.notification', ['patternfly.utils']); +;/** + * @name patternfly + * + * @description + * Base module for patternfly. + */ +angular.module('patternfly', [ + 'patternfly.autofocus', + 'patternfly.card', + 'patternfly.filters', + 'patternfly.form', + 'patternfly.modals', + 'patternfly.navigation', + 'patternfly.notification', + 'patternfly.select', + 'patternfly.sort', + 'patternfly.toolbars', + 'patternfly.utils', + 'patternfly.validation', + 'patternfly.views', + 'patternfly.wizard' +]); + +;/** + * @name patternfly card + * + * @description + * Sort module for patternfly. + * + */ +angular.module('patternfly.sort', ['ui.bootstrap']); +;/** + * @name patternfly toolbars + * + * @description + * Filters module for patternfly. + * + */ +angular.module('patternfly.toolbars', [ + 'patternfly.utils', + 'patternfly.filters', + 'patternfly.sort', + 'patternfly.views']); +; +angular.module( 'patternfly.utils', ['ui.bootstrap'] ); +;/** + * @name patternfly + * + * @description + * Views module for patternfly. + * + */ +angular.module('patternfly.views', ['patternfly.utils', 'patternfly.filters', 'patternfly.sort', 'patternfly.charts']); +;/** + * @name PatternFly Wizard + * + * @description + * Wizard module. + * + */ +angular.module('patternfly.wizard', ['ui.bootstrap.modal', + 'ui.bootstrap.tpls', + 'patternfly.form']); + + +;/** + * @ngdoc directive + * @name patternfly.autofocus:pfFocused + * @restrict A + * @element ANY + * @param {expression=} pfFocused If the expression is true, the element is focused and selected (if possible). + * + * @description + * The focus on element is evaluated from given expression. If the expression provided as an attribute to this directive + * is evaluated as true, the element is selected (and focused). + * + * @example + + + +
      +
      + +
      + +
      + +
      +
      + +
      + +
      + +
      +
      + +
      +
      +
      + +
      + */ + +angular.module('patternfly.autofocus', []).directive('pfFocused', ["$timeout", function ($timeout) { + 'use strict'; + + return { + restrict: 'A', + link: function (scope, element, attrs) { + scope.$watch(attrs.pfFocused, function (newValue) { + $timeout(function () { + if (newValue) { + element[0].focus(); + if (element[0].select) { + element[0].select(); + } + } + }); + }); + } + }; +}]); +;/** + * @ngdoc directive + * @name patternfly.card.directive:pfAggregateStatusCard + * @restrict A + * @element ANY + * @param {object} status Status configuration information
      + *
        + *
      • .title - the main title of the aggregate status card + *
      • .count - the number count of the main statuses + *
      • .href - the href to navigate to if one clicks on the title or count + *
      • .iconClass - an icon to display to the left of the count + *
      • .iconImage - an image to display to the left of the count + *
      • .notifications - an array of status icons & counts + *
          + *
        • .iconClass - an icon to display to the right of the notification count + *
        • .iconImage - an image to display to the left of the notification count + *
        • .count - the number count of the notification status + *
        • .href - href to navigate to if one clicks on the notification status icon or count + *
        + *
      + * When layout='mini', only one notification can be specified:
      + *
        + *
      • ... + *
      • .notification - an object of containing a single notification icon & count + *
          + *
        • .iconClass - an icon to display to the right of the notification count + *
        • .iconImage - an image to display to the left of the notification count + *
        • .count - the number count of the notification status + *
        • .href - href to navigate to if one clicks on the notification status icon or count + *
        + *
      + * @param {boolean=} show-top-border Show/hide the top border, true shows top border, false (default) hides top border + * @param {string=} layout Various alternative layouts the aggregate status card may have:
      + *
        + *
      • 'mini' displays a mini aggregate status card. Note: when using 'mini' layout, only one notification can be specified in the status object + *
      • 'tall' displays a tall aggregate status card. This equals the depreciated 'alt-layout' param.
      • + *
      + * @deprecated {boolean=} alt-layout Display the aggregate status card in a 'alternate tall' layout. false (default) displays normal layout, true displays tall layout + * + * @description + * Directive for easily displaying status information + * + * @example + + + +
      +
      + +
      +
      + +
      +
      + +
      +
      +
      + +
      +
      + + (depreciated, use layout = 'tall' instead) +

      +
      +
      +
      +
      + + + angular.module( 'patternfly.card' ).controller( 'CardDemoCtrl', function( $scope ) { + $scope.status = { + "title":"Nodes", + "count":793, + "href":"#", + "iconClass": "fa fa-shield", + "notifications":[ + { + "iconClass":"pficon pficon-error-circle-o", + "count":4, + "href":"#" + }, + { + "iconClass":"pficon pficon-warning-triangle-o", + "count":1 + } + ] + }; + + $scope.aggStatusAlt = { + "title":"Providers", + "count":3, + "notifications":[ + { + "iconImage":"img/kubernetes.svg", + "count":1, + "href":"#" + }, + { + "iconImage":"img/OpenShift-logo.svg", + "count":2, + "href":"#" + } + ] + }; + + $scope.miniAggStatus = { + "iconClass":"pficon pficon-container-node", + "title":"Nodes", + "count":52, + "href":"#", + "notification": { + "iconClass":"pficon pficon-error-circle-o", + "count":3 + } + }; + + $scope.miniAggStatus2 = { + "iconClass":"pficon pficon-cluster", + "title":"Adipiscing", + "count":9, + "href":"#", + "notification":{ + "iconClass":"pficon pficon-ok" + } + }; + }); + + +
      + */ + +angular.module( 'patternfly.card' ).directive('pfAggregateStatusCard', function () { + 'use strict'; + return { + restrict: 'A', + scope: { + status: '=', + showTopBorder: '@?', + altLayout: '@?', + layout: '@?' + }, + templateUrl: 'card/aggregate-status/aggregate-status-card.html', + link: function (scope) { + scope.shouldShowTopBorder = (scope.showTopBorder === 'true'); + scope.isAltLayout = (scope.altLayout === 'true' || scope.layout === 'tall'); + scope.isMiniLayout = (scope.layout === 'mini'); + } + }; +}); +;/** + * @ngdoc directive + * @name patternfly.card.directive:pfCard - Utilization + * @restrict A + * @element ANY + * @param {string} headTitle Title for the card + * @param {string=} subTitle Sub-Title for the card + * @param {boolean=} showTopBorder Show/Hide the blue top border. True shows top border, false (default) hides top border + * @param {boolean=} showTitlesSeparator Show/Hide the grey line between the title and sub-title. + * True (default) shows the line, false hides the line + * @param {object=} footer footer configuration properties:
      + *
        + *
      • .iconClass - (optional) the icon to show on the bottom left of the footer panel + *
      • .text - (optional) the text to show on the bottom left of the footer panel, to the right of the icon + *
      • .href - (optional) the href link to navigate to when the footer href is clicked + *
      • .callBackFn - (optional) user defined function to call when the footer href is clicked + *
      + * *Note: If a href link and a callBackFn are specified, the href link will be called + * @param {object=} filter filter configuration properties:
      + *
        + *
      • .filters - drop down items for the filter. + *
        + *  Ex:  'filters' : [{label:'Last 30 Days', value:'30'},
        + *                    {label:'Last 15 Days', value:'15'},
        + *                    {label:'Today', value:'today'}]
        + *
      • .defaultFilter - integer, 0 based index into the filters array + *
      • .callBackFn - user defined function to call when a filter is selected + *
      + * @description + * Directive for easily displaying a card with html content + * + * @example + + + +
      + +
      +
      +
      +
      +
      +
      +
      +
      + + angular.module( 'demo', ['patternfly.charts', 'patternfly.card'] ).controller( 'ChartCtrl', function( $scope ) { + + $scope.title2 = 'Memory'; + $scope.units2 = 'GB'; + + $scope.data2 = { + 'used': '25', + 'total': '100' + }; + + $scope.title3 = 'CPU Usage'; + $scope.units3 = 'MHz'; + + $scope.data3 = { + 'used': '420', + 'total': '500', + }; + + $scope.title4 = 'Disk Usage'; + $scope.units4 = 'TB'; + $scope.data4 = { + 'used': '350', + 'total': '500', + }; + + $scope.title5 = 'Disk I/O'; + $scope.units5 = 'I/Ops'; + $scope.data5 = { + 'used': '450', + 'total': '500', + }; + + $scope.layoutInline = { + 'type': 'inline' + }; + }); + +
      + */ +angular.module('patternfly.card').directive('pfCard', function () { + 'use strict'; + + return { + restrict: 'A', + transclude: true, + templateUrl: 'card/basic/card.html', + scope: { + headTitle: '@', + subTitle: '@?', + showTopBorder: '@?', + showTitlesSeparator: '@?', + footer: '=?', + filter: '=?' + }, + controller: ["$scope", function ($scope) { + if ($scope.filter && !$scope.currentFilter) { + if ($scope.filter.defaultFilter) { + $scope.currentFilter = $scope.filter.filters[$scope.filter.defaultFilter]; + } else { + $scope.currentFilter = $scope.filter.filters[0]; + } + } + + $scope.footerCallBackFn = function () { + $scope.footerCallBackResult = $scope.footer.callBackFn(); + }; + + $scope.filterCallBackFn = function (f) { + $scope.currentFilter = f; + if ($scope.filter.callBackFn) { + $scope.filterCallBackResult = $scope.filter.callBackFn(f); + } + }; + + $scope.showHeader = function () { + return ($scope.headTitle || $scope.showFilterInHeader()); + }; + + $scope.showFilterInHeader = function () { + return ($scope.filter && $scope.filter.filters && $scope.filter.position && $scope.filter.position === 'header'); + }; + + $scope.showFilterInFooter = function () { + return ($scope.filter && $scope.filter.filters && (!$scope.filter.position || $scope.filter.position === 'footer')); + }; + }], + link: function (scope) { + scope.shouldShowTitlesSeparator = (!scope.showTitlesSeparator || scope.showTitlesSeparator === 'true'); + } + }; +}); +;/** + * @ngdoc directive + * @name patternfly.card.directive:pfCard - Timeframe Filters + * @restrict A + * @element ANY + * @param {string} headTitle Title for the card + * @param {string=} subTitle Sub-Title for the card + * @param {boolean=} showTopBorder Show/Hide the blue top border. True shows top border, false (default) hides top border + * @param {boolean=} showTitlesSeparator Show/Hide the grey line between the title and sub-title. + * True (default) shows the line, false hides the line + * @param {object=} footer footer configuration properties:
      + *
        + *
      • .iconClass - (optional) the icon to show on the bottom left of the footer panel + *
      • .text - (optional) the text to show on the bottom left of the footer panel, to the right of the icon + *
      • .href - (optional) the href link to navigate to when the footer href is clicked + *
      • .callBackFn - (optional) user defined function to call when the footer href is clicked + *
      + * *Note: If a href link and a callBackFn are specified, the href link will be called + * @param {object=} filter filter configuration properties:
      + *
        + *
      • .filters - drop down items for the filter. + *
        + *  Ex:  'filters' : [{label:'Last 30 Days', value:'30'},
        + *                    {label:'Last 15 Days', value:'15'},
        + *                    {label:'Today', value:'today'}]
        + *
      • .defaultFilter - integer, 0 based index into the filters array + *
      • .callBackFn - user defined function to call when a filter is selected + *
      + * @description + * Directive for easily displaying a card with html content + * + * @example + + + +
      + +
      + Card Contents +
      + +
      + Card Contents +
      +
      +
      + + angular.module( 'demo', ['patternfly.charts', 'patternfly.card'] ).controller( 'ChartCtrl', function( $scope ) { + + $scope.footerConfig = { + 'iconClass' : 'fa fa-flag', + 'text' : 'View All Events', + 'callBackFn': function () { + alert("Footer Callback Fn Called"); + } + } + + $scope.filterConfigHeader = { + 'filters' : [{label:'Last 30 Days', value:'30'}, + {label:'Last 15 Days', value:'15'}, + {label:'Today', value:'today'}], + 'callBackFn': function (f) { + alert("Header Filter Callback Fn Called for '" + f.label + "' value = " + f.value); + }, + 'position' : 'header' + } + + $scope.filterConfig = { + 'filters' : [{label:'Last 30 Days', value:'30'}, + {label:'Last 15 Days', value:'15'}, + {label:'Today', value:'today'}], + 'callBackFn': function (f) { + alert("Filter Callback Fn Called for '" + f.label + "' value = " + f.value); + }, + 'defaultFilter' : '1' + } + }); + +
      + */ +;/** + * @ngdoc directive + * @name patternfly.card.directive:pfCard - Trends + * @restrict A + * @element ANY + * @param {string} headTitle Title for the card + * @param {string=} subTitle Sub-Title for the card + * @param {boolean=} showTopBorder Show/Hide the blue top border. True shows top border, false (default) hides top border + * @param {boolean=} showTitlesSeparator Show/Hide the grey line between the title and sub-title. + * True (default) shows the line, false hides the line + * @param {object=} footer footer configuration properties:
      + *
        + *
      • .iconClass - (optional) the icon to show on the bottom left of the footer panel + *
      • .text - (optional) the text to show on the bottom left of the footer panel, to the right of the icon + *
      • .href - (optional) the href link to navigate to when the footer href is clicked + *
      • .callBackFn - (optional) user defined function to call when the footer href is clicked + *
      + * *Note: If a href link and a callBackFn are specified, the href link will be called + * @param {object=} filter filter configuration properties:
      + *
        + *
      • .filters - drop down items for the filter. + *
        + *  Ex:  'filters' : [{label:'Last 30 Days', value:'30'},
        + *                    {label:'Last 15 Days', value:'15'},
        + *                    {label:'Today', value:'today'}]
        + *
      • .defaultFilter - integer, 0 based index into the filters array + *
      • .callBackFn - user defined function to call when a filter is selected + *
      + * @description + * Directive for easily displaying a card with html content + * + * @example + + + +
      + +
      +
      +
      + +
      +
      +
      +
      +
      +
      + +
      + + angular.module( 'demo', ['patternfly.charts', 'patternfly.card'] ).controller( 'ChartCtrl', function( $scope ) { + + $scope.footerConfig = { + 'iconClass' : 'fa fa-flag', + 'text' : 'View All Events', + 'callBackFn': function () { + alert("Footer Callback Fn Called"); + } + } + + $scope.filterConfig = { + 'filters' : [{label:'Last 30 Days', value:'30'}, + {label:'Last 15 Days', value:'15'}, + {label:'Today', value:'today'}], + 'callBackFn': function (f) { + alert("Filter Callback Fn Called for '" + f.label + "' value = " + f.value); + }, + 'defaultFilter' : '1' + } + + var today = new Date(); + var dates = ['dates']; + for (var d = 20 - 1; d >= 0; d--) { + dates.push(new Date(today.getTime() - (d * 24 * 60 * 60 * 1000))); + } + + $scope.configSingle = { + 'chartId' : 'example2TrendsChart', + 'title' : 'Storage Capacity', + 'layout' : 'compact', + 'valueType' : 'actual', + 'units' : 'TB', + 'tooltipType' : 'percentage' + }; + + $scope.dataSingle = { + 'total': '250', + 'xData': dates, + 'yData': ['used', '90', '20', '30', '20', '20', '10', '14', '20', '25', '68', '44', '56', '78', '56', '67', '88', '76', '65', '87', '76'] + }; + + $scope.configVirtual = { + 'chartId' : 'virtualTrendsChart', + 'layout' : 'inline', + 'trendLabel' : 'Virtual Disk I/O', + 'units' : 'GB', + 'tooltipType' : 'percentage' + }; + + $scope.dataVirtual = { + 'total': '250', + 'xData': dates, + 'yData': ['used', '90', '20', '30', '20', '20', '10', '14', '20', '25', '68', '44', '56', '78', '56', '67', '88', '76', '65', '87', '76'] + }; + + $scope.configPhysical = { + 'chartId' : 'physicalTrendsChart', + 'layout' : 'inline', + 'trendLabel' : 'Physical Disk I/O', + 'units' : 'MHz', + 'tooltipType' : 'percentage' + }; + + $scope.dataPhysical = { + 'total': '250', + 'xData': dates, + 'yData': ['used', '20', '20', '35', '20', '20', '87', '14', '20', '25', '28', '44', '56', '78', '56', '67', '88', '76', '65', '87', '16'] + }; + + $scope.configMemory = { + 'chartId' : 'memoryTrendsChart', + 'layout' : 'inline', + 'trendLabel' : 'Memory Utilization', + 'units' : 'GB', + 'tooltipType' : 'percentage' + }; + + $scope.dataMemory = { + 'total': '250', + 'xData': dates, + 'yData': ['used', '20', '20', '35', '70', '20', '87', '14', '95', '25', '28', '44', '56', '66', '16', '67', '88', '76', '65', '87', '56'] + }; + + $scope.actionBarConfig = { + 'iconClass' : 'fa fa-plus-circle', + 'text' : 'Add New Cluster', + 'callBackFn': function () { + alert("Footer Callback Fn Called"); + } + } + }); + +
      + */ +;(function () { + 'use strict'; + + var patternflyDefaults = $().c3ChartDefaults(); + + angular.module('patternfly.charts').constant('c3ChartDefaults', { + getDefaultColors: patternflyDefaults.getDefaultColors, + getDefaultDonut: patternflyDefaults.getDefaultDonut, + getDefaultDonutSize: patternflyDefaults.getDefaultDonutSize, + getDefaultDonutColor: patternflyDefaults.getDefaultDonutColors, + getDefaultDonutLegend: patternflyDefaults.getDefaultDonutLegend, + getDefaultDonutConfig: patternflyDefaults.getDefaultDonutConfig, + getDefaultSparklineArea: patternflyDefaults.getDefaultSparklineArea, + getDefaultSparklineSize: patternflyDefaults.getDefaultSparklineSize, + getDefaultSparklineAxis: patternflyDefaults.getDefaultSparklineAxis, + getDefaultSparklineColor: patternflyDefaults.getDefaultColors, + getDefaultSparklineLegend: patternflyDefaults.getDefaultSparklineLegend, + getDefaultSparklinePoint: patternflyDefaults.getDefaultSparklinePoint, + getDefaultSparklineTooltip: patternflyDefaults.getDefaultSparklineTooltip, + getDefaultSparklineConfig: patternflyDefaults.getDefaultSparklineConfig, + getDefaultLineConfig: patternflyDefaults.getDefaultLineConfig + }); +})(); +;/** + * @ngdoc directive + * @name patternfly.charts.directive:pfC3Chart + * + * @description + * Directive for wrapping c3 library + * + * Note: The 'patternfly.charts' module is not a dependency in the default angular 'patternfly' module. + * In order to use patternfly charts you must add 'patternfly.charts' as a dependency in your application. + * + * + * @param {string} id the ID of the container that the chart should bind to + * @param {expression} config the c3 configuration options for the chart + * @param {function (chart))=} getChartCallback the callback user function to be called once the chart is generated, containing the c3 chart object + * + * @example + + + +
      +
      + +
      + Total = {{total}}, Used = {{used}}, Available = {{available}} +
      + + +
      + + +
      +
      +
      + + + angular.module( 'patternfly.charts' ).controller( 'ChartCtrl', function( $scope ) { + $scope.used = 950; + $scope.total = 1000; + $scope.available = $scope.total - $scope.used; + + $scope.chartConfig = $().c3ChartDefaults().getDefaultDonutConfig('MHz Used'); + $scope.chartConfig.data = { + type: "donut", + columns: [ + ["Used", $scope.used], + ["Available", $scope.total - $scope.used] + ], + groups: [ + ["used", "available"] + ], + order: null + }; + + $scope.getChart = function (chart) { + $scope.chart = chart; + } + + $scope.focusUsed = function () { + $scope.chart.focus("Used"); + } + + $scope.updateAvailable = function (val) { + $scope.available = $scope.total - $scope.used; + } + + $scope.submitform = function (val) { + $scope.used = val; + $scope.updateAvailable(); + $scope.chartConfig.data.columns = [["Used",$scope.used],["Available",$scope.available]]; + }; + }); + +
      + */ +(function () { + 'use strict'; + + angular.module('patternfly.charts').directive('pfC3Chart', ["$timeout", function ($timeout) { + return { + restrict: 'A', + scope: { + config: '=', + getChartCallback: '=' + }, + template: '
      ', + replace: true, + link: function (scope, element, attrs) { + scope.$watch('config', function () { + $timeout(function () { + // store the chart object + var chart; + //generate c3 chart data + var chartData = scope.config; + if (chartData) { + chartData.bindto = '#' + attrs.id; + chart = c3.generate(chartData); + if (scope.getChartCallback) { + scope.getChartCallback(chart); + } + } + }); + }, true); + } + }; + }]); +}()); +;/** + * @ngdoc directive + * @name patternfly.charts.directive:pfDonutPctChart + * + * @description + * Directive for rendering a percentage used donut/radial chart. The Used Percentage fill starts at 12 o’clock and + * moves clockwise. Whatever portion of the donut not Used, will be represented as Available, and rendered as a + * gray fill. + * There are three possible fill colors for Used Percentage, dependent on whether or not there are thresholds:
      + *
        + *
      • When no thresholds exist, or if the used percentage has not surpassed any thresholds, the indicator is blue. + *
      • When the used percentage has surpassed the warning threshold, but not the error threshold, the indicator is orange. + *
      • When the used percentage has surpassed the error threshold, the indicator is is red. + *
      + * The directive will calculate the Available Percentage (Total - Used), and display it as a grey radial fill. + * + *

      + * See http://c3js.org/reference.html for a full list of C3 chart options. + * + * @param {object} config configuration properties for the donut chart:
      + *
        + *
      • .chartId - the unique id of the donut chart + *
      • .units - unit label for values, ex: 'MHz','GB', etc.. + *
      • .thresholds - warning and error percentage thresholds used to determine the Usage Percentage fill color (optional) + *
      • .tooltipFn(d) - user defined function to customize the tool tip (optional) + *
      • .centerLabelFn - user defined function to customize the text of the center label (optional) + *
      • .onClickFn(d,i) - user defined function to handle when donut arc is clicked upon. + *
      + * + * @param {object} data the Total and Used values for the donut chart. Available is calculated as Total - Used.
      + *
        + *
      • .used - number representing the amount used + *
      • .total - number representing the total amount + *
      • .dataAvailable - Flag if there is data available - default: true + *
      + * + * @param {string=} center-label specifies the contents of the donut's center label.
      + * Values: + *
        + *
      • 'used' - displays the Used amount in the center label (default) + *
      • 'available' - displays the Available amount in the center label + *
      • 'percent' - displays the Usage Percent of the Total amount in the center label + *
      • 'none' - does not display the center label + *
      + * + * @param {int=} chartHeight height of the donut chart + + * @example + + +
      +
      +
      +
      + +
      +
      +
      + +
      +
      +
      + +
      +
      +
      + +
      +
      +
      + +
      +
      +
      +
      +
      + +
      +
      +
      + +
      +
      +
      + +
      +
      +
      + +
      +
      +
      + +
      +
      + +
      +
      +
      +
      +
      + +
      +
      +
      + +
      +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      + +
      + +
      +
      +
      +
      +
      +
      +
      + + + angular.module( 'patternfly.charts' ).controller( 'ChartCtrl', function( $scope ) { + $scope.configErr = { + 'chartId': 'chartErr', + 'units': 'GB', + 'thresholds':{'warning':'60','error':'90'} + }; + + $scope.dataErr = { + 'used': '950', + 'total': '1000' + }; + + $scope.configWarn = { + 'chartId': 'chartWarn', + 'units': 'GB', + 'thresholds':{'warning':'60','error':'90'} + }; + + $scope.dataWarn = { + 'used': '650', + 'total': '1000' + }; + + $scope.configOk = { + 'chartId': 'chartOk', + 'units': 'GB', + 'thresholds':{'warning':'60','error':'90'} + }; + + $scope.dataOk = { + 'used': '550', + 'total': '1000' + }; + + $scope.configNoThresh = { + 'chartId': 'chartNoThresh', + 'units': 'GB', + }; + + $scope.dataNoThresh = { + 'used': '750', + 'total': '1000' + }; + + $scope.usedConfig = { + 'chartId': 'usedChart', + 'units': 'GB', + 'thresholds':{'warning':'60','error':'90'} + }; + + $scope.usedData = { + 'used': '350', + 'total': '1000' + }; + + $scope.usedLabel = "used"; + + $scope.availConfig = { + 'chartId': 'availChart', + 'units': 'GB', + 'thresholds':{'warning':'60','error':'90'} + }; + + $scope.availData = { + 'used': '350', + 'total': '1000' + }; + + $scope.availLabel = "available"; + + $scope.pctConfig = { + 'chartId': 'pctChart', + 'units': 'GB', + 'thresholds':{'warning':'60','error':'90'} + }; + + $scope.pctData = { + 'used': '350', + 'total': '1000' + }; + + $scope.pctLabel = "percent"; + + $scope.noneConfig = { + 'chartId': 'noneChart', + 'units': 'GB', + 'thresholds':{'warning':'60','error':'90'} + }; + + $scope.noneData = { + 'used': '350', + 'total': '1000' + }; + + $scope.noLabel = "none"; + + $scope.custConfig = { + 'chartId': 'custChart', + 'units': 'MHz', + 'thresholds':{'warning':'60','error':'90'}, + "legend":{"show":true}, + 'tooltipFn': function (d) { + return '' + + d[0].value + ' ' + d[0].name + + ''; + }, + 'centerLabelFn': function () { + return $scope.custData.available + " GB"; + }, + 'onClickFn': function (d, i) { + alert("You Clicked On The Donut!"); + } + }; + + $scope.custData = { + 'dataAvailable': true, + 'used': '670', + 'total': '1000' + }; + + $scope.custChartHeight = 200; + }); + +
      + */ +angular.module('patternfly.charts').directive('pfDonutPctChart', ["pfUtils", "$timeout", function (pfUtils, $timeout) { + 'use strict'; + + return { + restrict: 'A', + scope: { + config: '=', + data: '=', + chartHeight: '=?', + centerLabel: '=?' + }, + replace: true, + templateUrl: 'charts/donut/donut-pct-chart.html', + controller: ['$scope', + function ($scope) { + var donutTooltip; + + $scope.donutChartId = 'donutChart'; + if ($scope.config.chartId) { + $scope.donutChartId = $scope.config.chartId + $scope.donutChartId; + } + + $scope.updateAvailable = function () { + $scope.data.available = $scope.data.total - $scope.data.used; + }; + + if ($scope.data.available === undefined) { + $scope.updateAvailable(); + } + + $scope.getStatusColor = function (used, thresholds) { + var color = pfUtils.colorPalette.blue; + + if (thresholds) { + color = pfUtils.colorPalette.green; + if (used >= thresholds.error) { + color = pfUtils.colorPalette.red; + } else if (used >= thresholds.warning) { + color = pfUtils.colorPalette.orange; + } + } + + return color; + }; + + $scope.statusDonutColor = function (scope) { + var color, percentUsed; + + color = { pattern: [] }; + percentUsed = scope.data.used / scope.data.total * 100.0; + color.pattern[0] = $scope.getStatusColor(percentUsed, scope.config.thresholds); + color.pattern[1] = pfUtils.colorPalette.black300; + return color; + }; + + donutTooltip = function (scope) { + return { + contents: function (d) { + var tooltipHtml; + + if (scope.config.tooltipFn) { + tooltipHtml = '' + + scope.config.tooltipFn(d) + + ''; + } else { + tooltipHtml = '' + + Math.round(d[0].ratio * 100) + '%' + ' ' + $scope.config.units + ' ' + d[0].name + + ''; + } + + return tooltipHtml; + } + }; + }; + + $scope.getDonutData = function (scope) { + return { + columns: [ + ['Used', scope.data.used], + ['Available', scope.data.available] + ], + type: 'donut', + donut: { + label: { + show: false + } + }, + groups: [ + ['used', 'available'] + ], + order: null + }; + }; + + $scope.getCenterLabelText = function () { + var centerLabelText; + + // default to 'used' info. + centerLabelText = { bigText: $scope.data.used, + smText: $scope.config.units + ' Used' }; + + if ($scope.config.centerLabelFn) { + centerLabelText.bigText = $scope.config.centerLabelFn(); + centerLabelText.smText = ''; + } else if ($scope.centerLabel === 'none') { + centerLabelText.bigText = ''; + centerLabelText.smText = ''; + } else if ($scope.centerLabel === 'available') { + centerLabelText.bigText = $scope.data.available; + centerLabelText.smText = $scope.config.units + ' Available'; + } else if ($scope.centerLabel === 'percent') { + centerLabelText.bigText = Math.round($scope.data.used / $scope.data.total * 100.0) + '%'; + centerLabelText.smText = 'of ' + $scope.data.total + ' ' + $scope.config.units; + } + + return centerLabelText; + }; + + + $scope.updateAll = function (scope) { + $scope.updateAvailable(); + $scope.config.data = pfUtils.merge($scope.config.data, $scope.getDonutData($scope)); + $scope.config.color = $scope.statusDonutColor($scope); + $scope.config.tooltip = donutTooltip(scope); + $scope.config.data.onclick = $scope.config.onClickFn; + }; + + $scope.config = pfUtils.merge($().c3ChartDefaults().getDefaultDonutConfig(), $scope.config); + $scope.updateAll($scope); + + + } + ], + link: function (scope, element) { + var setupDonutChartTitle = function () { + $timeout(function () { + var donutChartTitle, centerLabelText; + + donutChartTitle = d3.select(element[0]).select('text.c3-chart-arcs-title'); + if (!donutChartTitle) { + return; + } + + centerLabelText = scope.getCenterLabelText(); + + // Remove any existing title. + donutChartTitle.selectAll('*').remove(); + if (centerLabelText.bigText && !centerLabelText.smText) { + donutChartTitle.text(centerLabelText.bigText); + } else { + donutChartTitle.insert('tspan').text(centerLabelText.bigText).classed('donut-title-big-pf', true).attr('dy', 0).attr('x', 0); + donutChartTitle.insert('tspan').text(centerLabelText.smText).classed('donut-title-small-pf', true).attr('dy', 20).attr('x', 0); + } + }, 300); + }; + + scope.$watch('config', function () { + scope.updateAll(scope); + setupDonutChartTitle(); + }, true); + scope.$watch('chartHeight', function () { + if (scope.chartHeight) { + scope.config.size.height = scope.chartHeight; + } + }); + scope.$watch('data', function () { + scope.updateAll(scope); + setupDonutChartTitle(); + }, true); + + scope.$watch('centerLabel', function () { + setupDonutChartTitle(); + }); + } + }; +}]); +;/** + * + * @description + * Directive for rendering an empty chart. This is used by chart directives when the data + * available flag is set to false. + * + * @param {string=} chartHeight height of the chart (no units) - default: 40 + */ +angular.module('patternfly.charts').directive('pfEmptyChart', function () { + 'use strict'; + return { + restrict: 'A', + scope: { + chartHeight: '=?' + }, + replace: true, + templateUrl: 'charts/empty-chart.html', + controller: ["$scope", function ($scope) { + $scope.setSizeStyles = function () { + var height = $scope.chartHeight || 40; + var topPadding = Math.min(Math.round((height - 40) / 2), 20); + $scope.sizeStyles = { + height: height + 'px', + 'padding-top': topPadding + 'px' + }; + }; + $scope.setSizeStyles(); + }], + link: function (scope) { + scope.$watch('chartHeight', function () { + scope.setSizeStyles(); + }); + } + }; +}); +;angular.module('patternfly.charts').directive('pfHeatmapLegend', + function () { + 'use strict'; + return { + restrict: 'A', + scope: { + legend: '=?', + legendColors: '=?' + }, + templateUrl: 'charts/heatmap/heatmap-legend.html', + controller: ["$scope", function ($scope) { + var heatmapColorPatternDefaults = ['#d4f0fa', '#F9D67A', '#EC7A08', '#CE0000']; + var legendLabelDefaults = ['< 70%', '70-80%' ,'80-90%', '> 90%']; + + //Allow overriding of defaults + if (!$scope.legendColors) { + $scope.legendColors = heatmapColorPatternDefaults; + } + if (!$scope.legend) { + $scope.legend = legendLabelDefaults; + } + }], + link: function ($scope) { + var items = []; + var index; + for (index = $scope.legend.length - 1; index >= 0; index--) { + items.push({ + text: $scope.legend[index], + color: $scope.legendColors[index] + }); + } + $scope.legendItems = items; + } + }; + } +); +;/** + * @ngdoc directive + * @name patternfly.charts.directive:pfHeatMap + * + * @description + * Directive for rendering a heatmap chart. + * + * @param {object} data data for the chart:
      + *
        + *
      • .id - the id of the measurement + *
      • .value - the value of the measurement + *
      • .tooltip - message to be displayed on hover + *
      + * + * @param {boolean=} chartDataAvailable flag if the chart data is available - default: true + * @param {number=} height height of the chart (no units) - default: 200 + * @param {string=} chartTitle title of the chart + * @param {boolean=} showLegend flag to show the legend, defaults to true + * @param {array=} legendLabels the labels for the legend - defaults: ['< 70%', '70-80%' ,'80-90%', '> 90%'] + * @param {number=} maxBlockSize the maximum size for blocks in the heatmap. Default: 50, Range: 5 - 50 + * @param {number=} minBlockSize the minimum size for blocks in the heatmap. Default: 2 + * @param {number=} blockPadding the padding in pixels between blocks (default: 2) + * @param {array=} thresholds the threshold values for the heapmap - defaults: [0.7, 0.8, 0.9] + * @param {array=} heatmapColorPattern the colors that correspond to the various threshold values (lowest to hightest value ex: <70& to >90%) - defaults: ['#d4f0fa', '#F9D67A', '#EC7A08', '#CE0000'] + * @param {function=} clickAction function(block) function to call when a block is clicked on + * @param {number=} rangeHoverSize the maximum size for highlighting blocks in the same range. Default: 15 + * @param {boolean=} rangeOnHover flag to highlight blocks in the same range on hover, defaults to true + * @param {array=} rangeTooltips the tooltips for blocks in the same range - defaults: ['< 70%', '70-80%' ,'80-90%', '> 90%'] + * @example + + +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      + + angular.module( 'patternfly.charts' ).controller( 'ChartCtrl', function( $scope) { + $scope.data = [ + {'id': 9,'value': 0.96,'tooltip': 'Node 8 : My OpenShift Provider96% : 96 Used of 100 Total4 Available'}, + {'id': 44, 'value': 0.94, 'tooltip': 'Node 19 : My Kubernetes Provider94% : 94 Used of 100 Total6 Available'}, + {'id': 0, 'value': 0.91, 'tooltip': 'Node 9 : My OpenShift Provider91% : 91 Used of 100 Total9 Available'}, + {'id': 43, 'value': 0.9, 'tooltip': 'Node 18 : My Kubernetes Provider90% : 90 Used of 100 Total10 Available'}, + {'id': 7, 'value': 0.89, 'tooltip': 'Node 12 : My OpenShift Provider89% : 89 Used of 100 Total11 Available'}, + {'id': 41, 'value': 0.82, 'tooltip': 'Node 16 : My Kubernetes Provider82% : 82 Used of 100 Total18 Available'}, + {'id': 21, 'value': 0.81, 'tooltip': 'Node 21 : My OpenShift Provider81% : 81 Used of 100 Total19 Available'}, + {'id': 26, 'value': 0.8, 'tooltip': 'Node 1 : My Kubernetes Provider80% : 80 Used of 100 Total20 Available'}, + {'id': 48, 'value': 0.74, 'tooltip': 'Node 23 : My Kubernetes Provider74% : 74 Used of 100 Total26 Available'}, + {'id': 27, 'value': 0.72, 'tooltip': 'Node 2 : My Kubernetes Provider72% : 72 Used of 100 Total28 Available'}, + {'id': 42, 'value': 0.71, 'tooltip': 'Node 17 : My Kubernetes Provider71% : 71 Used of 100 Total29 Available'}, + {'id': 23, 'value': 0.71, 'tooltip': 'Node 23 : My OpenShift Provider71% : 71 Used of 100 Total29 Available'}, + {'id': 22, 'value': 0.69, 'tooltip': 'Node 22 : My OpenShift Provider69% : 69 Used of 100 Total31 Available'}, + {'id': 2, 'value': 0.66, 'tooltip': 'Node 2 : M8y OpenShift Provider66% : 66 Used of 100 Total34 Available'}, + {'id': 39, 'value': 0.66, 'tooltip': 'Node 14 : My Kubernetes Provider66% : 66 Used of 100 Total34 Available'}, + {'id': 3, 'value': 0.65, 'tooltip': 'Node 39 : My OpenShift Provider65% : 65 Used of 100 Total35 Available'}, + {'id': 29, 'value': 0.65, 'tooltip': 'Node 4 : My Kubernetes Provider65% : 65 Used of 100 Total35 Available'}, + {'id': 32, 'value': 0.56, 'tooltip': 'Node 7 : My Kubernetes Provider56% : 56 Used of 100 Total44 Available'}, + {'id': 13, 'value': 0.56, 'tooltip': 'Node 13 : My OpenShift Provider56% : 56 Used of 100 Total44 Available'}, + {'id': 49, 'value': 0.52, 'tooltip': 'Node 24 : My Kubernetes Provider52% : 52 Used of 100 Total48 Available'}, + {'id': 36, 'value': 0.5, 'tooltip': 'Node 11 : My Kubernetes Provider50% : 50 Used of 100 Total50 Available'}, + {'id': 6, 'value': 0.5, 'tooltip': 'Node 5 : My OpenShift Provider50% : 50 Used of 100 Total50 Available'}, + {'id': 38, 'value': 0.49, 'tooltip': 'Node 13 : My Kubernetes Provider49% : 49 Used of 100 Total51 Available'}, + {'id': 15, 'value': 0.48, 'tooltip': 'Node 15 : My OpenShift Provider48% : 48 Used of 100 Total52 Available'}, + {'id': 30, 'value': 0.48, 'tooltip': 'Node 5 : My Kubernetes Provider48% : 48 Used of 100 Total52 Available'}, + {'id': 11, 'value': 0.47, 'tooltip': 'Node 11 : My OpenShift Provider47% : 47 Used of 100 Total53 Available'}, + {'id': 17, 'value': 0.46, 'tooltip': 'Node 17 : My OpenShift Provider46% : 46 Used of 100 Total54 Available'}, + {'id': 25, 'value': 0.45, 'tooltip': 'Node 0 : My Kubernetes Provider45% : 45 Used of 100 Total55 Available'}, + {'id': 50, 'value': 0.45, 'tooltip': 'Node 25 : My Kubernetes Provider45% : 45 Used of 100 Total55 Available'}, + {'id': 46, 'value': 0.45, 'tooltip': 'Node 21 : My Kubernetes Provider45% : 45 Used of 100 Total55 Available'}, + {'id': 47, 'value': 0.45, 'tooltip': 'Node 22 : My Kubernetes Provider45% : 45 Used of 100 Total55 Available'}, + {'id': 1, 'value': 0.44, 'tooltip': 'Node 1 : My OpenShift Provider44% : 44 Used of 100 Total56 Available'}, + {'id': 31, 'value': 0.44, 'tooltip': 'Node 6 : My Kubernetes Provider44% : 44 Used of 100 Total56 Available'}, + {'id': 37, 'value': 0.44, 'tooltip': 'Node 12 : My Kubernetes Provider44% : 44 Used of 100 Total56 Available'}, + {'id': 24, 'value': 0.44, 'tooltip': 'Node 24 : My OpenShift Provider44% : 44 Used of 100 Total56 Available'}, + {'id': 40, 'value': 0.43, 'tooltip': 'Node 40 : My Kubernetes Provider43% : 43 Used of 100 Total57 Available'}, + {'id': 20, 'value': 0.39, 'tooltip': 'Node 20 : My OpenShift Provider39% : 39 Used of 100 Total61 Available'}, + {'id': 8, 'value': 0.39, 'tooltip': 'Node 8 : My OpenShift Provider39% : 39 Used of 100 Total61 Available'}, + {'id': 5, 'value': 0.38, 'tooltip': 'Node 5 : My OpenShift Provider38% : 38 Used of 100 Total62 Available'}, + {'id': 45, 'value': 0.37, 'tooltip': 'Node 20 : My Kubernetes Provider37% : 37 Used of 100 Total63 Available'}, + {'id': 12, 'value': 0.37, 'tooltip': 'Node 12 : My OpenShift Provider37% : 37 Used of 100 Total63 Available'}, + {'id': 34, 'value': 0.37, 'tooltip': 'Node 9 : My Kubernetes Provider37% : 37 Used of 100 Total63 Available'}, + {'id': 33, 'value': 0.33, 'tooltip': 'Node 8 : My Kubernetes Provider33% : 33 Used of 100 Total67 Available'}, + {'id': 16, 'value': 0.32, 'tooltip': 'Node 16 : My OpenShift Provider32% : 32 Used of 100 Total68 Available'}, + {'id': 10, 'value': 0.29, 'tooltip': 'Node 10 : My OpenShift Provider28% : 29 Used of 100 Total71 Available'}, + {'id': 35, 'value': 0.28, 'tooltip': 'Node 35 : My Kubernetes Provider28% : 28 Used of 100 Total72 Available'}, + {'id': 18, 'value': 0.27, 'tooltip': 'Node 18 : My OpenShift Provider27% : 27 Used of 100 Total73 Available'}, + {'id': 4, 'value': 0.26, 'tooltip': 'Node 4 : My OpenShift Provider26% : 26 Used of 100 Total74 Available'}, + {'id': 19, 'value': 0.25, 'tooltip': 'Node 19 : My OpenShift Provider25% : 25 Used of 100 Total75 Available'}, + {'id': 28, 'value': 0.25, 'tooltip': 'Node 3 : My Kubernetes Provider25% : 25 Used of 100 Total75 Available'}, + {'id': 51, 'value': 0.22, 'tooltip': 'Node 26 : My Kubernetes Provider22% : 22 Used of 100 Total78 Available'}, + {'id': 14, 'value': 0.2, 'tooltip': 'Node 14 : My OpenShift Provider20% : 20 Used of 100 Total80 Available'}]; + + $scope.dataAvailable = true; + $scope.title = 'Utilization - Using Defaults'; + $scope.titleAlt = 'Utilization - Overriding Defaults'; + $scope.titleSmall = 'Utilization - Small Blocks'; + $scope.legendLabels = ['< 60%','70%', '70-80%' ,'80-90%', '> 90%']; + $scope.rangeTooltips = ['Memory Utilization < 70%40 Nodes', 'Memory Utilization 70-80%4 Nodes', 'Memory Utilization 80-90%4 Nodes', 'Memory Utilization > 90%4 Nodes']; + $scope.thresholds = [0.6, 0.7, 0.8, 0.9]; + $scope.heatmapColorPattern = ['#d4f0fa', '#F9D67A', '#EC7A08', '#CE0000', '#f00']; + + $scope.showLegends = true; + var clickAction = function (block) { + console.log(block); + }; + $scope.clickAction = clickAction; + }); + +
      + */ +angular.module('patternfly.charts').directive('pfHeatmap', ["$compile", "$window", function ($compile, $window) { + 'use strict'; + return { + restrict: 'A', + scope: { + data: '=', + chartDataAvailable: '=?', + height: '=?', + chartTitle: '=?', + showLegend: '=?', + legendLabels: '=?', + maxBlockSize: '@', + minBlockSize: '@', + blockPadding: '@', + thresholds: '=?', + heatmapColorPattern: '=?', + clickAction: '=?', + rangeOnHover: '=?', + rangeHoverSize: '@', + rangeTooltips: '=?' + }, + templateUrl: 'charts/heatmap/heatmap.html', + controller: ["$scope", function ($scope) { + var thresholdDefaults = [0.7, 0.8, 0.9]; + var heatmapColorPatternDefaults = ['#d4f0fa', '#F9D67A', '#EC7A08', '#CE0000']; + var legendLabelDefaults = ['< 70%', '70-80%' ,'80-90%', '> 90%']; + var rangeTooltipDefaults = ['< 70%', '70-80%' ,'80-90%', '> 90%']; + var heightDefault = 200; + + //Allow overriding of defaults + if ($scope.maxBlockSize === undefined || isNaN($scope.maxBlockSize)) { + $scope.maxSize = 64; + } else { + $scope.maxSize = parseInt($scope.maxBlockSize); + if ($scope.maxSize < 5) { + $scope.maxSize = 5; + } else if ($scope.maxSize > 50) { + $scope.maxSize = 50; + } + } + + if ($scope.minBlockSize === undefined || isNaN($scope.minBlockSize)) { + $scope.minSize = 2; + } else { + $scope.minSize = parseInt($scope.minBlockSize); + } + + if ($scope.blockPadding === undefined || isNaN($scope.blockPadding)) { + $scope.padding = 2; + } else { + $scope.padding = parseInt($scope.blockPadding); + } + + if ($scope.rangeHoverSize === undefined || isNaN($scope.rangeHoverSize)) { + $scope.rangeHoverSize = 15; + } else { + $scope.rangeHoverSize = parseInt($scope.rangeHoverSize); + } + + $scope.rangeOnHover = ($scope.rangeOnHover === undefined || $scope.rangeOnHover) ? true : false; + + if (!$scope.rangeTooltips) { + $scope.rangeTooltips = rangeTooltipDefaults; + } + + if (!$scope.thresholds) { + $scope.thresholds = thresholdDefaults; + } + + if (!$scope.heatmapColorPattern) { + $scope.heatmapColorPattern = heatmapColorPatternDefaults; + } + + if (!$scope.legendLabels) { + $scope.legendLabels = legendLabelDefaults; + } + $scope.height = $scope.height || heightDefault; + $scope.showLegend = $scope.showLegend || ($scope.showLegend === undefined); + $scope.loadingDone = false; + }], + link: function (scope, element, attrs) { + var thisComponent = element[0].querySelector('.heatmap-pf-svg'); + var containerWidth, containerHeight, blockSize, numberOfRows; + + var setStyles = function () { + scope.containerStyles = { + height: scope.height + 'px', + display: scope.chartDataAvailable === false ? 'none' : 'block' + }; + }; + + var setSizes = function () { + var parentContainer = element[0].querySelector('.heatmap-container'); + containerWidth = parentContainer.clientWidth; + containerHeight = parentContainer.clientHeight; + blockSize = determineBlockSize(); + + if ((blockSize - scope.padding) > scope.maxSize) { + blockSize = scope.padding + scope.maxSize; + + // Attempt to square off the area, check if square fits + numberOfRows = Math.ceil(Math.sqrt(scope.data.length)); + if (blockSize * numberOfRows > containerWidth || + blockSize * numberOfRows > containerHeight) { + numberOfRows = (blockSize === 0) ? 0 : Math.floor(containerHeight / blockSize); + } + } else if ((blockSize - scope.padding) < scope.minSize) { + blockSize = scope.padding + scope.minSize; + + // Attempt to square off the area, check if square fits + numberOfRows = Math.ceil(Math.sqrt(scope.data.length)); + if (blockSize * numberOfRows > containerWidth || + blockSize * numberOfRows > containerHeight) { + numberOfRows = (blockSize === 0) ? 0 : Math.floor(containerHeight / blockSize); + } + } else { + numberOfRows = (blockSize === 0) ? 0 : Math.floor(containerHeight / blockSize); + } + }; + + var determineBlockSize = function () { + var x = containerWidth; + var y = containerHeight; + var n = scope.data ? scope.data.length : 0; + var px = Math.ceil(Math.sqrt(n * x / y)); + var py = Math.ceil(Math.sqrt(n * y / x)); + var sx, sy; + + if (Math.floor(px * y / x) * px < n) { + sx = y / Math.ceil(px * y / x); + } else { + sx = x / px; + } + + if (Math.floor(py * x / y) * py < n) { + sy = x / Math.ceil(x * py / y); + } else { + sy = y / py; + } + return Math.max(sx, sy); + }; + + var redraw = function () { + var data = scope.data; + var color = d3.scale.threshold().domain(scope.thresholds).range(scope.heatmapColorPattern); + var rangeTooltip = d3.scale.threshold().domain(scope.thresholds).range(scope.rangeTooltips); + var blocks; + var fillSize = blockSize - scope.padding; + var highlightBlock = function (block, active) { + block.style('fill-opacity', active ? 1 : 0.4); + }; + var highlightBlockColor = function (block, fillColor) { + // Get fill color from given block + var blockColor = color(block.map(function (d) { + return d[0].__data__.value; + })); + // If given color matches, apply highlight + if (blockColor === fillColor) { + block.style('fill-opacity', 1); + } + }; + + var svg = window.d3.select(thisComponent); + svg.selectAll('*').remove(); + blocks = svg.selectAll('rect').data(data).enter().append('rect'); + blocks.attr('x', function (d, i) { + return Math.floor(i / numberOfRows) * blockSize; + }).attr('y', function (d, i) { + return i % numberOfRows * blockSize; + }).attr('width', fillSize).attr('height', fillSize).style('fill', function (d) { + return color(d.value); + }).attr('uib-tooltip-html', function (d, i) { //tooltip-html is throwing an exception + if (scope.rangeOnHover && fillSize <= scope.rangeHoverSize) { + return '"' + rangeTooltip(d.value) + '"'; + } + return "'" + d.tooltip + "'"; + }).attr('tooltip-append-to-body', function (d, i) { + return true; + }).attr('tooltip-animation', function (d, i) { + return false; + }); + + //Adding events + blocks.on('mouseover', function () { + var fillColor; + blocks.call(highlightBlock, false); + if (scope.rangeOnHover && fillSize <= scope.rangeHoverSize) { + // Get fill color for current block + fillColor = color(d3.select(this).map(function (d) { + return d[0].__data__.value; + })); + // Highlight all blocks matching fill color + blocks[0].forEach(function (block) { + highlightBlockColor(d3.select(block), fillColor); + }); + } else { + d3.select(this).call(highlightBlock, true); + } + }); + blocks.on('click', function (d) { + if (scope.clickAction) { + scope.clickAction(d); + } + }); + + //Compiles the tooltips + angular.forEach(angular.element(blocks), function (block) { + var el = angular.element(block); + $compile(el)(scope); + }); + + svg.on('mouseleave', function () { + blocks.call(highlightBlock, true); + }); + }; + + scope.$watch('data', function (newVal, oldVal) { + if (typeof(newVal) !== 'undefined') { + scope.loadingDone = true; + setStyles(); + if (scope.chartDataAvailable !== false) { + setSizes(); + redraw(); + } + } + }); + scope.$watch('chartDataAvailable', function () { + if (scope.chartDataAvailable === false) { + scope.loadingDone = true; + } + setStyles(); + }); + + angular.element($window).bind('resize', function () { + setSizes(); + redraw(); + }); + + scope.$watch( + function () { + return [element[0].offsetWidth, element[0].offsetHeight].join('x'); + }, + function (value) { + setSizes(); + redraw(); + } + ); + } + }; +}]); +;/** + * @ngdoc directive + * @name patternfly.charts.directive:pfLineChart + * + * @description + * Directive for rendering a line chart. + *

      + * See http://c3js.org/reference.html for a full list of C3 chart options. + * + * @param {object} config configuration settings for the line chart:
      + *
        + *
      • .chartId - the ID of the container that the chart should bind to + *
      • .units - unit label for values, ex: 'MHz','GB', etc.. + *
      • .tooltipFn - (optional) override the tooltip contents generation functions. Should take a data point and + * return HTML markup for the tooltip contents. Setting this overrides the tooltipType value. + *
      • .area - (optional) overrides the default Area properties of the C3 chart + *
      • .size - (optional) overrides the default Size properties of the C3 chart + *
      • .axis - (optional) overrides the default Axis properties of the C3 chart + *
      • .color - (optional) overrides the default Color properties of the C3 chart + *
      • .legend - (optional) overrides the default Legend properties of the C3 chart + *
      • .point - (optional) overrides the default Point properties of the C3 chart + *
      + * + * @param {object} chartData the data to be shown as an area chart
      + * First and second Array elements, xData and yData, must exist, next data arrays are optional.
      + *
        + *
      • .xData - Array, X values for the data points, first element must be the name of the data + *
      • .yData - Array, Y Values for the data points, first element must be the name of the data + *
      • .yData1 - Array, Y Values for the data points, first element must be the name of the data + *
      • .[...] - Array, Y Values for the data points, first element must be the name of the data + *
      + * + * @param {boolean=} showXAxis override config settings for showing the X Axis + * @param {boolean=} showYAxis override config settings for showing the Y Axis + * @param {boolean=} setAreaChart override config settings for showing area type chart + + * @example + + +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + + + +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      +
      + + + angular.module( 'patternfly.charts' ).controller( 'ChartCtrl', function( $scope, pfUtils ) { + + $scope.config = { + chartId: 'exampleLine', + grid: {y: {show: false}}, + point: {r: 1}, + color: {pattern: [pfUtils.colorPalette.blue, pfUtils.colorPalette.green]} + }; + + var today = new Date(); + var dates = ['dates']; + for (var d = 20 - 1; d >= 0; d--) { + dates.push(new Date(today.getTime() - (d * 24 * 60 * 60 * 1000))); + } + + $scope.data = { + dataAvailable: true, + xData: dates, + yData0: ['Created', 12, 10,10, 62, 17, 10, 15, 13, 17, 10, 12, 10, 10, 12, 17, 16, 15, 13, 17, 10], + yData1: ['Deleted', 10, 17, 76,14, 10, 10, 10, 10, 10, 10, 10, 17, 17, 14, 10, 10, 10, 10, 10, 10] + }; + + $scope.custShowXAxis = false; + $scope.custShowYAxis = false; + $scope.custAreaChart = false; + + $scope.addDataPoint = function () { + $scope.data.xData.push(new Date($scope.data.xData[$scope.data.xData.length - 1].getTime() + (24 * 60 * 60 * 1000))); + $scope.data.yData0.push(Math.round(Math.random() * 100)); + $scope.data.yData1.push(Math.round(Math.random() * 100)); + }; + }); + +
      + */ +angular.module('patternfly.charts').directive('pfLineChart', ["pfUtils", function (pfUtils) { + 'use strict'; + return { + restrict: 'A', + scope: { + config: '=', + chartData: '=', + showXAxis: '=?', + showYAxis: '=?', + setAreaChart: '=?' + }, + replace: true, + templateUrl: 'charts/line/line-chart.html', + controller: ['$scope', + function ($scope) { + + // Create an ID for the chart based on the chartId in the config if given + $scope.lineChartId = 'lineChart'; + if ($scope.config.chartId) { + $scope.lineChartId = $scope.config.chartId + $scope.lineChartId; + } + + /* + * Convert the config data to C3 Data + */ + $scope.getLineData = function (chartData) { + var lineData = { + type: $scope.setAreaChart ? "area" : "line" + }; + + if (chartData && chartData.dataAvailable !== false && chartData.xData) { + lineData.x = chartData.xData[0]; + // Convert the chartData dictionary into a C3 columns data arrays + lineData.columns = Object.keys (chartData).map (function (key) { + return chartData[key]; + }); + } + + return lineData; + }; + + /* + * Setup Axis options. Default is to not show either axis. This can be overridden in two ways: + * 1) in the config, setting showAxis to true will show both axes + * 2) in the attributes showXAxis and showYAxis will override the config if set + * + * By default only line and the tick marks are shown, no labels. This is a line and should be used + * only to show a brief idea of trending. This can be overridden by setting the config.axis options per C3 + */ + + if ($scope.showXAxis === undefined) { + $scope.showXAxis = ($scope.config.showAxis !== undefined) && $scope.config.showAxis; + } + + if ($scope.showYAxis === undefined) { + $scope.showYAxis = ($scope.config.showAxis !== undefined) && $scope.config.showAxis; + } + + $scope.defaultConfig = $().c3ChartDefaults().getDefaultLineConfig(); + $scope.defaultConfig.axis = { + x: { + show: $scope.showXAxis === true, + type: 'timeseries', + tick: { + format: function () { + return ''; + } + } + }, + y: { + show: $scope.showYAxis === true, + tick: { + format: function () { + return ''; + } + } + } + }; + + /* + * Setup Chart type option. Default is Line Chart. + */ + if ($scope.setAreaChart === undefined) { + $scope.setAreaChart = ($scope.config.setAreaChart !== undefined) && $scope.config.setAreaChart; + } + + // Convert the given data to C3 chart format + $scope.config.data = pfUtils.merge($scope.config.data, $scope.getLineData($scope.chartData)); + + // Override defaults with callers specifications + $scope.defaultConfig = pfUtils.merge($scope.defaultConfig, $scope.config); + } + ], + + link: function (scope) { + scope.$watch('config', function () { + scope.config.data = pfUtils.merge(scope.config.data, scope.getLineData(scope.chartData)); + scope.chartConfig = pfUtils.merge(scope.defaultConfig, scope.config); + }, true); + scope.$watch('showXAxis', function () { + scope.chartConfig.axis.x.show = scope.showXAxis === true; + }); + scope.$watch('showYAxis', function () { + scope.chartConfig.axis.y.show = scope.showYAxis === true; + }); + scope.$watch('setAreaChart', function () { + scope.chartConfig.data.type = scope.setAreaChart ? "area" : "line"; + }); + scope.$watch('chartData', function () { + scope.chartConfig.data = pfUtils.merge(scope.chartConfig.data, scope.getLineData(scope.chartData)); + }, true); + } + }; +}] +); +;/** + * @ngdoc directive + * @name patternfly.charts.directive:pfSparklineChart + * + * @description + * Directive for rendering a sparkline chart. + *

      + * See http://c3js.org/reference.html for a full list of C3 chart options. + * + * @param {object} config configuration settings for the sparkline chart:
      + *
        + *
      • .chartId - the ID of the container that the chart should bind to + *
      • .units - unit label for values, ex: 'MHz','GB', etc.. + *
      • .tooltipType - (optional) set the type of tooltip, valid values: + *
          + *
        • 'default' - show the data point value and the data point name. + *
        • 'usagePerDay' - show the date, percent used, and used value for the data point. + *
        • 'valuePerDay' - show the date and value for the data point. + *
        • 'percentage' - show the current data point as a percentage. + *
        + *
      • .tooltipFn - (optional) override the tooltip contents generation functions. Should take a data point and + * return HTML markup for the tooltip contents. Setting this overrides the tooltipType value. + *
      • .area - (optional) overrides the default Area properties of the C3 chart + *
      • .size - (optional) overrides the default Size properties of the C3 chart + *
      • .axis - (optional) overrides the default Axis properties of the C3 chart + *
      • .color - (optional) overrides the default Color properties of the C3 chart + *
      • .legend - (optional) overrides the default Legend properties of the C3 chart + *
      • .point - (optional) overrides the default Point properties of the C3 chart + *
      + * + * @param {object} chartData the data to be shown as an area chart
      + *
        + *
      • .xData - Array, X values for the data points, first element must be the name of the data + *
      • .yData - Array, Y Values for the data points, first element must be the name of the data + *
      • .total - (optional) The Total amount, used when determining percentages + *
      • .dataAvailable - Flag if there is data available - default: true + *
      + * + * @param {int=} chartHeight height of the sparkline chart + * @param {boolean=} showXAxis override config settings for showing the X Axis + * @param {boolean=} showYAxis override config settings for showing the Y Axis + + * @example + + +
      +
      +
      +
      +
      +
      +
      +
      + +
      + + + + +
      +
      +
      +
      +
      +
      + +
      + + +
      +
      +
      +
      +
      +
      + +
      + +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      +
      + + + angular.module( 'patternfly.charts' ).controller( 'ChartCtrl', function( $scope ) { + + $scope.config = { + chartId: 'exampleSparkline', + tooltipType: 'default' + }; + + var today = new Date(); + var dates = ['dates']; + for (var d = 20 - 1; d >= 0; d--) { + dates.push(new Date(today.getTime() - (d * 24 * 60 * 60 * 1000))); + } + + $scope.data = { + dataAvailable: true, + total: 100, + xData: dates, + yData: ['used', 10, 20, 30, 20, 30, 10, 14, 20, 25, 68, 54, 56, 78, 56, 67, 88, 76, 65, 87, 76] + }; + + $scope.custShowXAxis = false; + $scope.custShowYAxis = false; + $scope.custChartHeight = 60; + + $scope.addDataPoint = function () { + $scope.data.xData.push(new Date($scope.data.xData[$scope.data.xData.length - 1].getTime() + (24 * 60 * 60 * 1000))); + $scope.data.yData.push(Math.round(Math.random() * 100)); + }; + }); + +
      + */ +angular.module('patternfly.charts').directive('pfSparklineChart', ["pfUtils", function (pfUtils) { + 'use strict'; + return { + restrict: 'A', + scope: { + config: '=', + chartData: '=', + chartHeight: '=?', + showXAxis: '=?', + showYAxis: '=?' + }, + replace: true, + templateUrl: 'charts/sparkline/sparkline-chart.html', + controller: ['$scope', + function ($scope) { + + // Create an ID for the chart based on the chartId in the config if given + $scope.sparklineChartId = 'sparklineChart'; + if ($scope.config.chartId) { + $scope.sparklineChartId = $scope.config.chartId + $scope.sparklineChartId; + } + + /* + * Convert the config data to C3 Data + */ + $scope.getSparklineData = function (chartData) { + var sparklineData = { + type: 'area' + }; + + if (chartData && chartData.dataAvailable !== false && chartData.xData && chartData.yData) { + sparklineData.x = chartData.xData[0]; + sparklineData.columns = [ + chartData.xData, + chartData.yData + ]; + } + + return sparklineData; + }; + + $scope.getTooltipTableHTML = function (tipRows) { + return '
      ' + + ' ' + + ' ' + + tipRows + + ' ' + + '
      ' + + '
      '; + }; + + $scope.sparklineTooltip = function () { + return { + contents: function (d) { + var tipRows; + var percentUsed = 0; + + if ($scope.config.tooltipFn) { + tipRows = $scope.config.tooltipFn(d); + } else { + switch ($scope.config.tooltipType) { + case 'usagePerDay': + if ($scope.chartData.dataAvailable !== false && $scope.chartData.total > 0) { + percentUsed = Math.round(d[0].value / $scope.chartData.total * 100.0); + } + tipRows = + '' + + ' ' + d[0].x.toLocaleDateString() + '' + + '' + + '' + + ' ' + percentUsed + '%:' + '' + + ' ' + d[0].value + ' ' + ($scope.config.units ? $scope.config.units + ' ' : '') + d[0].name + '' + + ''; + break; + case 'valuePerDay': + tipRows = + '' + + ' ' + d[0].x.toLocaleDateString() + '' + + ' ' + d[0].value + ' ' + d[0].name + '' + + ''; + break; + case 'percentage': + percentUsed = Math.round(d[0].value / $scope.chartData.total * 100.0); + tipRows = + '' + + ' ' + percentUsed + '%' + '' + + ''; + break; + default: + tipRows = $().c3ChartDefaults().getDefaultSparklineTooltip().contents(d); + } + } + return $scope.getTooltipTableHTML(tipRows); + }, + position: function (data, width, height, element) { + var center; + var top; + var chartBox; + var graphOffsetX; + var x; + + try { + center = parseInt(element.getAttribute('x')); + top = parseInt(element.getAttribute('y')); + chartBox = document.querySelector('#' + $scope.sparklineChartId).getBoundingClientRect(); + graphOffsetX = document.querySelector('#' + $scope.sparklineChartId + ' g.c3-axis-y').getBoundingClientRect().right; + x = Math.max(0, center + graphOffsetX - chartBox.left - Math.floor(width / 2)); + + return { + top: top - height, + left: Math.min(x, chartBox.width - width) + }; + } catch (e) { + } + } + }; + }; + + /* + * Setup Axis options. Default is to not show either axis. This can be overridden in two ways: + * 1) in the config, setting showAxis to true will show both axes + * 2) in the attributes showXAxis and showYAxis will override the config if set + * + * By default only line and the tick marks are shown, no labels. This is a sparkline and should be used + * only to show a brief idea of trending. This can be overridden by setting the config.axis options per C3 + */ + + if ($scope.showXAxis === undefined) { + $scope.showXAxis = ($scope.config.showAxis !== undefined) && $scope.config.showAxis; + } + + if ($scope.showYAxis === undefined) { + $scope.showYAxis = ($scope.config.showAxis !== undefined) && $scope.config.showAxis; + } + + $scope.defaultConfig = $().c3ChartDefaults().getDefaultSparklineConfig(); + $scope.defaultConfig.axis = { + x: { + show: $scope.showXAxis === true, + type: 'timeseries', + tick: { + format: function () { + return ''; + } + } + }, + y: { + show: $scope.showYAxis === true, + tick: { + format: function () { + return ''; + } + } + } + }; + + // Setup the default configuration + $scope.defaultConfig.tooltip = $scope.sparklineTooltip(); + if ($scope.chartHeight) { + $scope.defaultConfig.size.height = $scope.chartHeight; + } + $scope.defaultConfig.units = ''; + + // Convert the given data to C3 chart format + $scope.config.data = pfUtils.merge($scope.config.data, $scope.getSparklineData($scope.chartData)); + + // Override defaults with callers specifications + $scope.chartConfig = pfUtils.merge($scope.defaultConfig, $scope.config); + } + ], + + link: function (scope) { + scope.$watch('config', function () { + scope.config.data = pfUtils.merge(scope.config.data, scope.getSparklineData(scope.chartData)); + scope.chartConfig = pfUtils.merge(scope.defaultConfig, scope.config); + }, true); + scope.$watch('chartHeight', function () { + if (scope.chartHeight) { + scope.chartConfig.size.height = scope.chartHeight; + } + }); + scope.$watch('showXAxis', function () { + scope.chartConfig.axis.x.show = scope.showXAxis === true; + }); + scope.$watch('showYAxis', function () { + scope.chartConfig.axis.y.show = scope.showYAxis === true; + }); + scope.$watch('chartData', function () { + scope.chartConfig.data = pfUtils.merge(scope.chartConfig.data, scope.getSparklineData(scope.chartData)); + }, true); + } + }; +}] +); +;/** + * @ngdoc directive + * @name patternfly.charts.directive:pfTrendsChart + * + * @description + * Directive for rendering a trend chart. The trend chart combines overall data with a + * pfSparklineChart. + *

      + * See http://c3js.org/reference.html for a full list of C3 chart options.
      + * See also: {@link patternfly.charts.directive:pfSparklineChart} + * + * @param {object} config configuration settings for the trends chart:
      + *
        + *
      • .chartId - the unique id of this trends chart + *
      • .title - (optional) title of the Trends chart + *
      • .layout - (optional) the layout and sizes of titles and chart. Values are 'large' (default), 'small', 'compact', and 'inline' + *
      • .trendLabel - (optional) the trend label used in the 'inline' layout + *
      • .timeFrame - (optional) the time frame for the data in the pfSparklineChart, ex: 'Last 30 Days' + *
      • .units - unit label for values, ex: 'MHz','GB', etc.. + *
      • .valueType - (optional) the format of the latest data point which is shown in the title. Values are 'actual'(default) or 'percentage' + *
      + * + * @param {object} chartData the data to be shown in the sparkline charts
      + *
        + *
      • .total - number representing the total amount + *
      • .xData - Array, X values for the data points, first element must be the name of the data + *
      • .yData - Array, Y Values for the data points, first element must be the name of the data + *
      • .dataAvailable - Flag if there is data available - default: true + *
      + * + * @param {int=} chartHeight height of the sparkline chart + * @param {boolean=} showXAxis override sparkline config settings for showing the X Axis + * @param {boolean=} showYAxis override sparkline config settings for showing the Y Axis + * @example + + +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + + +
      +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      +
      + + angular.module( 'demo', ['patternfly.charts', 'patternfly.card'] ).controller( 'ChartCtrl', function( $scope ) { + + $scope.config = { + chartId : 'exampleTrendsChart', + title : 'Network Utilization Trends', + layout : 'large', + trendLabel : 'Virtual Disk I/O', + valueType : 'actual', + timeFrame : 'Last 15 Minutes', + units : 'MHz', + tooltipType : 'percentage' + }; + + $scope.footerConfig = { + iconClass : 'fa fa-plus-circle', + text : 'Add New Cluster', + callBackFn: function () { + alert("Footer Callback Fn Called"); + } + } + + $scope.filterConfig = { + filters : [{label:'Last 30 Days', value:'30'}, + {label:'Last 15 Days', value:'15'}, + {label:'Today', value:'today'}], + callBackFn: function (f) { + alert("Filter Callback Fn Called for '" + f.label + "' value = " + f.value); + } + } + + var today = new Date(); + var dates = ['dates']; + for (var d = 20 - 1; d >= 0; d--) { + dates.push(new Date(today.getTime() - (d * 24 * 60 * 60 * 1000))); + } + + $scope.data = { + dataAvailable: true, + total: 250, + xData: dates, + yData: ['used', 10, 20, 30, 20, 30, 10, 14, 20, 25, 68, 54, 56, 78, 56, 67, 88, 76, 65, 87, 76] + }; + + $scope.custShowXAxis = false; + $scope.custShowYAxis = false; + + $scope.addDataPoint = function () { + $scope.data.xData.push(new Date($scope.data.xData[$scope.data.xData.length - 1].getTime() + (24 * 60 * 60 * 1000))); + $scope.data.yData.push(Math.round(Math.random() * 100)); + }; + + $scope.$watch('valueType', function (newValue) { + $scope.config.valueType = newValue; + }); + + $scope.$watch('layout', function (newValue) { + $scope.config.layout = newValue; + }); + + }); + +
      + */ +angular.module('patternfly.charts').directive('pfTrendsChart', function () { + 'use strict'; + return { + restrict: 'A', + scope: { + config: '=', + chartData: '=', + chartHeight: '=?', + showXAxis: '=?', + showYAxis: '=?' + }, + replace: true, + templateUrl: 'charts/trends/trends-chart.html', + controller: ["$scope", function ($scope) { + var SMALL = 30, LARGE = 60; + + $scope.getPercentageValue = function () { + var pctValue = 0; + + if ($scope.chartData.dataAvailable !== false && $scope.chartData.total > 0) { + pctValue = Math.round($scope.getLatestValue() / $scope.chartData.total * 100.0); + } + return pctValue; + }; + $scope.getLatestValue = function () { + var latestValue = 0; + if ($scope.chartData.yData && $scope.chartData.yData.length > 0) { + latestValue = $scope.chartData.yData[$scope.chartData.yData.length - 1]; + } + return latestValue; + }; + $scope.getChartHeight = function () { + var retValue = LARGE; + if ($scope.chartHeight) { + retValue = $scope.chartHeight; + } else if ($scope.config.layout === 'small') { + retValue = SMALL; + } + return retValue; + }; + }], + link: function (scope) { + scope.$watch('config', function () { + scope.showLargeCardLayout = (!scope.config.layout || scope.config.layout === 'large'); + scope.showSmallCardLayout = (scope.config.layout === 'small'); + scope.showActualValue = (!scope.config.valueType || scope.config.valueType === 'actual'); + scope.showPercentageValue = (scope.config.valueType === 'percentage'); + }, true); + } + }; +}); +;/** + * @ngdoc directive + * @name patternfly.charts.directive:pfUtilizationBarChart + * + * @description + * Directive for rendering a utilization bar chart + * There are three possible fill colors for Used Percentage, dependent on whether or not there are thresholds:
      + *
        + *
      • When no thresholds exist, or if the used percentage has not surpassed any thresholds, the indicator is blue. + *
      • When the used percentage has surpassed the warning threshold, but not the error threshold, the indicator is orange. + *
      • When the used percentage has surpassed the error threshold, the indicator is is red. + *
      + * + * @param {object} chartData the data to be shown in the utilization bar chart
      + *
        + *
      • .used - number representing the amount used + *
      • .total - number representing the total amount + *
      • .dataAvailable - Flag if there is data available - default: true + *
      + * + * @param {object=} chart-title The title displayed on the left-hand side of the chart + * @param {object=} chart-footer The label displayed on the right-hand side of the chart. If chart-footer is not + * specified, the automatic footer-label-format will be used. + * @param {object=} layout Various alternative layouts the utilization bar chart may have:
      + *
        + *
      • .type - The type of layout to use. Valid values are 'regular' (default) displays the standard chart layout, + * and 'inline' displays a smaller, inline layout.
      • + *
      • .titleLabelWidth - Width of the left-hand title label when using 'inline' layout. Example values are "120px", "20%", "10em", etc..
      • + *
      • .footerLabelWidth - Width of the right-hand used label when using 'inline' layout. Example values are "120px", "20%", "10em", etc..
      • + *
      + * @param {string=} footer-label-format The auto-format of the label on the right side of the bar chart when chart-footer + * has not been specified. Values may be:
      + *
        + *
      • 'actual' - (default) displays the standard label of '(n) of (m) (units) Used'. + *
      • 'percent' - displays a percentage label of '(n)% Used'.
      • + *
      + * @param {object=} units to be displayed on the chart. Examples: "GB", "MHz", "I/Ops", etc... + * @param {string=} threshold-error The percentage used, when reached, denotes an error. Valid values are 1-100. When the error threshold + * has been reached, the used donut arc will be red. + * @param {string=} threshold-warning The percentage usage, when reached, denotes a warning. Valid values are 1-100. When the warning threshold + * has been reached, the used donut arc will be orange. + * + * @example + + +
      + + +
      +
      + +
      ../utilization-trend/utilization-trend-chart-directive.js
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      + + + angular.module( 'patternfly.example', ['patternfly.charts', 'patternfly.card']); + + angular.module( 'patternfly.example' ).controller( 'ChartCtrl', function( $scope ) { + + $scope.title1 = 'RAM Usage'; + $scope.units1 = 'MB'; + + $scope.data1 = { + 'dataAvailable': true, + 'used': '8', + 'total': '24' + }; + + $scope.title2 = 'Memory'; + $scope.units2 = 'GB'; + + $scope.data2 = { + 'used': '25', + 'total': '100' + }; + + $scope.title3 = 'CPU Usage'; + $scope.units3 = 'MHz'; + + $scope.data3 = { + 'used': '420', + 'total': '500', + }; + + $scope.title4 = 'Disk Usage'; + $scope.units4 = 'TB'; + $scope.data4 = { + 'used': '350', + 'total': '500', + }; + + $scope.title5 = 'Disk I/O'; + $scope.units5 = 'I/Ops'; + $scope.data5 = { + 'used': '450', + 'total': '500', + }; + + $scope.layoutInline = { + 'type': 'inline' + }; + + $scope.footer1 = '500 TB Total'; + $scope.footer2 = '450 of 500 Total'; + + }); + +
      +*/ + +angular.module('patternfly.charts').directive('pfUtilizationBarChart', ["$timeout", function ($timeout) { + 'use strict'; + return { + restrict: 'A', + scope: { + chartData: '=', + chartTitle: '=', + chartFooter: '=', + units: '=', + thresholdError: '=?', + thresholdWarning: '=?', + footerLabelFormat: '@?', + layout: '=?' + }, + + templateUrl: 'charts/utilization-bar/utilization-bar-chart.html', + link: function (scope) { + scope.$watch('chartData', function (newVal, oldVal) { + if (typeof(newVal) !== 'undefined') { + //Calculate the percentage used + scope.chartData.percentageUsed = Math.round(100 * (scope.chartData.used / scope.chartData.total)); + + if (scope.thresholdError || scope.thresholdWarning) { + scope.isError = (scope.chartData.percentageUsed >= scope.thresholdError); + scope.isWarn = (scope.chartData.percentageUsed >= scope.thresholdWarning && + scope.chartData.percentageUsed < scope.thresholdError); + scope.isOk = (scope.chartData.percentageUsed < scope.thresholdWarning); + } + + //Animate in the chart load. + scope.animate = true; + $timeout(function () { + scope.animate = false; + }, 0); + } + }); + + + } + }; +}]); +;/** + * @ngdoc directive + * @name patternfly.charts.directive:pfUtilizationTrendChart + * + * @description + * Directive for rendering a utilization trend chart. The utilization trend chart combines overall + * data with a pfDonutPctChart and a pfSparklineChart. Add the options for the pfDonutChart via + * the donutConfig parameter. Add the options for the pfSparklineChart via the sparklineConfig + * parameter. + *

      + * See http://c3js.org/reference.html for a full list of C3 chart options. + * + * @param {object} config configuration settings for the utilization trend chart:
      + *
        + *
      • .title - title of the Utilization chart + *
      • .units - unit label for values, ex: 'MHz','GB', etc.. + *
      + * + * @param {object} donutConfig configuration settings for the donut pct chart, see pfDonutPctChart for specifics
      + * @param {object} sparklineConfig configuration settings for the sparkline chart, see pfSparklineChart for specifics
      + * + * @param {object} chartData the data to be shown in the donut and sparkline charts
      + *
        + *
      • .used - number representing the amount used + *
      • .total - number representing the total amount + *
      • .xData - Array, X values for the data points, first element must be the name of the data + *
      • .yData - Array, Y Values for the data points, first element must be the name of the data + *
      • .dataAvailable - Flag if there is data available - default: true + *
      + * + * @param {string=} donutCenterLabel specifies the contents of the donut's center label.
      + * Values: + *
        + *
      • 'used' - displays the Used amount in the center label (default) + *
      • 'available' - displays the Available amount in the center label + *
      • 'percent' - displays the Usage Percent of the Total amount in the center label + *
      • 'none' - does not display the center label + *
      + * @param {int=} sparklineChartHeight height of the sparkline chart + * @param {boolean=} showSparklineXAxis override sparkline config settings for showing the X Axis + * @param {boolean=} showSparklineYAxis override sparkline config settings for showing the Y Axis + + * @example + + +
      +
      +
      +
      +
      +
      +
      +
      +
      + +
      + + + + +
      +
      +
      +
      + +
      + + + + +
      +
      +
      +
      +
      +
      + +
      + + +
      +
      +
      +
      +
      +
      + +
      + +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      + + + + angular.module( 'patternfly.charts' ).controller( 'ChartCtrl', function( $scope ) { + $scope.config = { + title: 'Memory', + units: 'GB' + }; + $scope.donutConfig = { + chartId: 'chartA', + thresholds: {'warning':'60','error':'90'} + }; + $scope.sparklineConfig = { + 'chartId': 'exampleSparkline', + 'tooltipType': 'default', + 'units': 'GB' + }; + + var today = new Date(); + var dates = ['dates']; + for (var d = 20 - 1; d >= 0; d--) { + dates.push(new Date(today.getTime() - (d * 24 * 60 * 60 * 1000))); + } + + $scope.data = { + dataAvailable: true, + used: 76, + total: 100, + xData: dates, + yData: ['used', '10', '20', '30', '20', '30', '10', '14', '20', '25', '68', '54', '56', '78', '56', '67', '88', '76', '65', '87', '76'] + }; + + $scope.centerLabel = 'used'; + + $scope.custShowXAxis = false; + $scope.custShowYAxis = false; + $scope.custChartHeight = 60; + + $scope.addDataPoint = function () { + var newData = Math.round(Math.random() * 100); + var newDate = new Date($scope.data.xData[$scope.data.xData.length - 1].getTime() + (24 * 60 * 60 * 1000)); + + $scope.data.used = newData; + $scope.data.xData.push(newDate); + $scope.data.yData.push(newData); + }; + }); + + + */ +angular.module('patternfly.charts').directive('pfUtilizationTrendChart', function () { + 'use strict'; + return { + restrict: 'A', + scope: { + chartData: '=', + config: '=', + centerLabel: '=?', + donutConfig: '=', + sparklineConfig: '=', + sparklineChartHeight: '=?', + showSparklineXAxis: '=?', + showSparklineYAxis: '=?' + }, + replace: true, + templateUrl: 'charts/utilization-trend/utilization-trend-chart.html', + controller: ['$scope', + function ($scope) { + if ($scope.centerLabel === undefined) { + $scope.centerLabel = 'used'; + + } + if ($scope.donutConfig.units === undefined) { + $scope.donutConfig.units = $scope.config.units; + } + if ($scope.chartData.available === undefined) { + $scope.chartData.available = $scope.chartData.total - $scope.chartData.used; + } + $scope.config.units = $scope.config.units || $scope.units; + } + ], + link: function (scope, element) { + var setupCurrentValues = function () { + if (scope.centerLabel === 'available') { + scope.currentValue = scope.chartData.used; + scope.currentText = 'Used'; + } else { + scope.currentValue = scope.chartData.total - scope.chartData.used; + scope.currentText = 'Available'; + } + }; + scope.$watchGroup(['centerLabel', 'chartData.used', 'chartData.available', 'chartData.total'], function () { + setupCurrentValues(); + }); + } + }; +}); +;/** + * @ngdoc directive + * @name patternfly.filters.directive:pfFilter + * + * @description + * Directive for a filter bar + *

      + * + * @param {object} config configuration settings for the filters:
      + *
        + *
      • .fields - (Array) List of filterable fields containing: + *
          + *
        • .id - (String) Optional unique Id for the filter field, useful for comparisons + *
        • .title - (String) The title to display for the filter field + *
        • .placeholder - (String) Text to display when no filter value has been entered + *
        • .filterType - (String) The filter input field type (any html input type, or 'select' for a single select box) + *
        • .filterValues - (Array) List of valid select values used when filterType is 'select' + *
        + *
      • .appliedFilters - (Array) List of the currently applied filters + *
      • .resultsCount - (int) The number of results returned after the current applied filters have been applied + *
      • .onFilterChange - ( function(array of filters) ) Function to call when the applied filters list changes + *
      + * + * @example + + +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      + {{item.name}} +
      +
      + {{item.address}} +
      +
      + {{item.birthMonth}} +
      +
      +
      +
      +

      +
      + +
      +
      + +
      +
      +
      + + + angular.module('patternfly.filters').controller('ViewCtrl', ['$scope', + function ($scope) { + $scope.filtersText = ''; + + $scope.allItems = [ + { + name: "Fred Flintstone", + address: "20 Dinosaur Way, Bedrock, Washingstone", + birthMonth: 'February' + }, + { + name: "John Smith", + address: "415 East Main Street, Norfolk, Virginia", + birthMonth: 'October' + }, + { + name: "Frank Livingston", + address: "234 Elm Street, Pittsburgh, Pennsylvania", + birthMonth: 'March' + }, + { + name: "Judy Green", + address: "2 Apple Boulevard, Cincinatti, Ohio", + birthMonth: 'December' + }, + { + name: "Pat Thomas", + address: "50 Second Street, New York, New York", + birthMonth: 'February' + } + ]; + $scope.items = $scope.allItems; + + var matchesFilter = function (item, filter) { + var match = true; + + if (filter.id === 'name') { + match = item.name.match(filter.value) !== null; + } else if (filter.id === 'address') { + match = item.address.match(filter.value) !== null; + } else if (filter.id === 'birthMonth') { + match = item.birthMonth === filter.value; + } + return match; + }; + + var matchesFilters = function (item, filters) { + var matches = true; + + filters.forEach(function(filter) { + if (!matchesFilter(item, filter)) { + matches = false; + return false; + } + }); + return matches; + }; + + var applyFilters = function (filters) { + $scope.items = []; + if (filters && filters.length > 0) { + $scope.allItems.forEach(function (item) { + if (matchesFilters(item, filters)) { + $scope.items.push(item); + } + }); + } else { + $scope.items = $scope.allItems; + } + $scope.filterConfig.resultsCount = $scope.items.length; + }; + + var filterChange = function (filters) { + $scope.filtersText = ""; + filters.forEach(function (filter) { + $scope.filtersText += filter.title + " : " + filter.value + "\n"; + }); + applyFilters(filters); + }; + + $scope.filterConfig = { + fields: [ + { + id: 'name', + title: 'Name', + placeholder: 'Filter by Name', + filterType: 'text' + }, + { + id: 'address', + title: 'Address', + placeholder: 'Filter by Address', + filterType: 'text' + }, + { + id: 'birthMonth', + title: 'Birth Month', + placeholder: 'Filter by Birth Month', + filterType: 'select', + filterValues: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] + } + ], + resultsCount: $scope.items.length, + appliedFilters: [], + onFilterChange: filterChange + }; + } + ]); + +
      + */ +angular.module('patternfly.filters').directive('pfFilter', function () { + 'use strict'; + return { + restrict: 'A', + scope: { + config: '=' + }, + templateUrl: 'filters/filter.html', + controller: ["$scope", function ($scope) { + $scope.filterExists = function (filter) { + var foundFilter = _.findWhere($scope.config.appliedFilters, {title: filter.title, value: filter.value}); + return foundFilter !== undefined; + }; + + $scope.enforceSingleSelect = function (filter) { + _.remove($scope.config.appliedFilters, {title: filter.title}); + }; + + $scope.addFilter = function (field, value) { + var newFilter = { + id: field.id, + title: field.title, + type: field.filterType, + value: value + }; + if (!$scope.filterExists(newFilter)) { + + if (newFilter.type === 'select') { + $scope.enforceSingleSelect(newFilter); + } + + $scope.config.appliedFilters.push(newFilter); + + if ($scope.config.onFilterChange) { + $scope.config.onFilterChange($scope.config.appliedFilters); + } + } + }; + }] + }; +}); +;/** + * @ngdoc directive + * @name patternfly.filters.directive:pfFilterFields + * + * @description + * Directive for the filter bar's filter entry components + *

      + * + * @param {object} config configuration settings for the filters:
      + *
        + *
      • .fields - (Array) List of filterable fields containing: + *
          + *
        • .id - (String) Optional unique Id for the filter field, useful for comparisons + *
        • .title - (String) The title to display for the filter field + *
        • .placeholder - (String) Text to display when no filter value has been entered + *
        • .filterType - (String) The filter input field type (any html input type, or 'select' for a select box) + *
        • .filterValues - (Array) List of valid select values used when filterType is 'select' + *
        + *
      • .appliedFilters - (Array) List of the currently applied filters + *
      + * + */ +angular.module('patternfly.filters').directive('pfFilterFields', function () { + 'use strict'; + return { + restrict: 'A', + scope: { + config: '=', + addFilterFn: '=' + }, + templateUrl: 'filters/filter-fields.html', + controller: ["$scope", function ($scope) { + $scope.setupConfig = function () { + if ($scope.fields === undefined) { + $scope.fields = []; + } + if (!$scope.currentField) { + $scope.currentField = $scope.config.fields[0]; + $scope.config.currentValue = null; + } + + if ($scope.config.currentValue === undefined) { + $scope.config.currentValue = null; + } + }; + + $scope.$watch('config', function () { + $scope.setupConfig(); + }, true); + }], + + link: function (scope, element, attrs) { + scope.selectField = function (item) { + scope.currentField = item; + scope.config.currentValue = null; + }; + + scope.selectValue = function (filterValue) { + scope.addFilterFn(scope.currentField, filterValue); + scope.config.currentValue = null; + }; + + scope.onValueKeyPress = function (keyEvent) { + if (keyEvent.which === 13) { + scope.addFilterFn(scope.currentField, scope.config.currentValue); + scope.config.currentValue = undefined; + } + }; + } + }; +}); +;/** + * @ngdoc directive + * @name patternfly.filters.directive:pfFilterResults + * + * @description + * Directive for the filter results components + *

      + * + * @param {object} config configuration settings for the filter results:
      + *
        + *
      • .fields - (Array) List of filterable fields containing: + *
          + *
        • .id - (String) Optional unique Id for the filter field, useful for comparisons + *
        • .title - (String) The title to display for the filter field + *
        • .placeholder - (String) Text to display when no filter value has been entered + *
        • .filterType - (String) The filter input field type (any html input type, or 'select' for a select box) + *
        • .filterValues - (Array) List of valid select values used when filterType is 'select' + *
        + *
      • .appliedFilters - (Array) List of the currently applied filters + *
      • .resultsCount - (int) The number of results returned after the current applied filters have been applied + *
      • .onFilterChange - ( function(array of filters) ) Function to call when the applied filters list changes + *
      + * + */ +angular.module('patternfly.filters').directive('pfFilterResults', function () { + 'use strict'; + return { + restrict: 'A', + scope: { + config: '=' + }, + templateUrl: 'filters/filter-results.html', + controller: ["$scope", function ($scope) { + $scope.setupConfig = function () { + if (!$scope.config.appliedFilters) { + $scope.config.appliedFilters = []; + } + if ($scope.config.resultsCount === undefined) { + $scope.config.resultsCount = 0; + } + }; + + $scope.$watch('config', function () { + $scope.setupConfig(); + }, true); + }], + link: function (scope, element, attrs) { + scope.clearFilter = function (item) { + var newFilters = []; + scope.config.appliedFilters.forEach(function (filter) { + if (item.title !== filter.title || item.value !== filter.value) { + newFilters.push(filter); + } + }); + scope.config.appliedFilters = newFilters; + + if (scope.config.onFilterChange) { + scope.config.onFilterChange(scope.config.appliedFilters); + } + }; + + scope.clearAllFilters = function () { + scope.config.appliedFilters = []; + + if (scope.config.onFilterChange) { + scope.config.onFilterChange(scope.config.appliedFilters); + } + }; + } + }; +}); +;/** + * @ngdoc directive + * @name patternfly.form.directive:pfDatepicker + * + * @description + * Angular directive to wrap the bootstrap datepicker http://bootstrap-datepicker.readthedocs.org/en/latest/ + * + * @param {string} date the date model + * @param {string} options the configuration options for the date picker + * + * @example + + +
      +
      + +
      + Date: +
      +
      +
      + + + angular.module( 'patternfly.form' ).controller( 'FormDemoCtrl', function( $scope ) { + $scope.setToday = function () { + $scope.date = new Date(); + } + + $scope.options = { + autoclose: true, + todayBtn: 'linked', + todayHighlight: true + }; + }); + +
      + */ +angular.module('patternfly.form').directive('pfDatepicker', function () { + 'use strict'; + + return { + replace: true, + restrict: 'A', + require: '^form', + templateUrl: 'form/datepicker/datepicker.html', + scope: { + options: '=', + date: '=' + }, + link: function ($scope, element) { + + //Make sure the date picker is set with the correct options + element.datepicker($scope.options); + + //Set the initial value of the date picker + element.datepicker('update', $scope.date); + + //Change happened on the date picker side. Update the underlying date model + element.datepicker($scope.date).on('changeDate clearDate', function (elem) { + $scope.$apply(function () { + $scope.date = elem.date; + }); + }); + + //Update the date picker if there is a change on the date model + $scope.$watch('date', function (newValue, oldValue) { + var elemDate; + if (oldValue !== newValue) { + elemDate = element.datepicker('getDate'); + if (!elemDate || !newValue || elemDate.getTime() !== newValue.getTime()) { + //Update date picker value only when there is a change + //to avoid resetting when a wrong date is typed + //into input. + element.datepicker('update', newValue); + } + } + }); + } + }; +}); +;/** + * @ngdoc directive + * @name patternfly.form.directive:pfDateTimepicker + * + * @description + * Angular directive to wrap the bootstrap datetimepicker http://eonasdan.github.io/bootstrap-datetimepicker/ + * + * @param {object} date date and time moment object + * @param {string} options the configuration options for the date picker + * + * @example + + +
      + Date and Time: +
      +
      +
      + + + angular.module( 'patternfly.form' ).controller( 'FormDemoCtrl', function( $scope ) { + $scope.options = { + format: 'HH:mm' + }; + $scope.date = moment(); + }); + +
      + */ +angular.module('patternfly.form').directive('pfDateTimepicker', function () { + 'use strict'; + + return { + replace: true, + restrict: 'A', + require: '^form', + templateUrl: 'form/datetimepicker/datetimepicker.html', + scope: { + options: '=', + date: '=' + }, + link: function ($scope, element) { + //Make sure the date picker is set with the correct options + element.datetimepicker($scope.options); + + //Set the initial value of the date picker + element.datetimepicker('date', $scope.date || null); + + //Change happened on the date picker side. Update the underlying date model + element.on('dp.change', function (elem) { + $scope.$apply(function () { + $scope.date = elem.date; + }); + }); + } + }; +}); +;/** + * @ngdoc directive + * @name patternfly.form.directive:pfFormButtons + * + * @description + * Encapsulates the standard structure and styling for create and cancel buttons + * when used with a form. + * + * This directive creates new scope. + * + * @param {function} pfHandleCancel function to call when the user clicks cancel. + * @param {function} pfHandleSave function to call when the user clicks save. + * @param {expression} pfWorking the model to store the working status in. + * @param {string} pfButtonClass the class of the button container. + * + * @example + + + +
      +

      Saved?

      +

      {{ status }}

      +
      +
      Input + +
      +
      +
      +
      +
      + + + angular.module( 'patternfly.form' ).controller( 'FormButtonCtrl', function( $scope, $timeout ) { + $scope.status = 'Not yet Saved' + $scope.working = false; + + $scope.save = function (item) { + $scope.status = 'saved'; + $scope.working = true; + + $timeout(function () { + $scope.working = false; + }, 1000); + }; + + $scope.cancel = function () { + $scope.status = 'cancelled'; + $scope.input = null; + }; + }); + +
      + */ +angular.module('patternfly.form').directive('pfFormButtons', function () { + 'use strict'; + + return { + replace: true, + require: '^form', + templateUrl: 'form/form-buttons/form-buttons.html', + scope: { + pfHandleCancel: '&pfOnCancel', + pfHandleSave: '&pfOnSave', + pfWorking: '=', + pfButtonContainerClass: '@' + }, + link: function (scope, iElement, iAttrs, controller) { + if (scope.pfWorking === undefined) { + scope.pfWorking = false; + } + + scope.isInvalid = function () { + var invalid = controller.$invalid; + + angular.forEach(controller, function (value) { + if (value && value.$error) { + if (value.$error.server) { + invalid = false; + } + } + }); + + return invalid; + }; + } + }; +}); +;/** + * @ngdoc directive + * @name patternfly.form.directive:pfFormGroup + * + * @description + * Encapsulates the structure and styling for a label + input used within a + * Bootstrap3 based form. + * + * This directive creates new scope. + * + * @param {string} pfLabel the text for the
      + +
      + +
      + +
      +
      + +
      + +
      + +
      +
      + + + +

      Your preferred pet is {{pet}}.

      + + +
      + + + angular.module( 'patternfly.select' ).controller( 'SelectDemoCtrl', function( $scope ) { + $scope.drinks = ['tea', 'coffee', 'water']; + $scope.pets = ['Dog', 'Cat', 'Chicken']; + $scope.pet = $scope.pets[0]; + $scope.fruit = 'orange'; + }); + + +
      + */ +angular.module('patternfly.select', []).directive('pfSelect', ["$timeout", function ($timeout) { + 'use strict'; + + return { + restrict: 'A', + require: '?ngModel', + scope: { + selectPickerOptions: '=pfSelect' + }, + link: function (scope, element, attrs, ngModel) { + var optionCollectionList, optionCollectionExpr, optionCollection, $render = ngModel.$render; + + var selectpickerRefresh = function (argument) { + scope.$applyAsync(function () { + element.selectpicker('refresh'); + }); + }; + + var selectpickerDestroy = function () { + element.selectpicker('destroy'); + }; + + element.selectpicker(scope.selectPickerOptions); + + ngModel.$render = function () { + $render.apply(this, arguments); + selectpickerRefresh(); + }; + + if (attrs.ngOptions) { + optionCollectionList = attrs.ngOptions.split('in '); + optionCollectionExpr = optionCollectionList[optionCollectionList.length - 1].split(/track by|\|/); + optionCollection = optionCollectionExpr[0]; + + scope.$parent.$watchCollection(optionCollection, selectpickerRefresh); + } + + if (attrs.ngModel) { + scope.$parent.$watch(attrs.ngModel, selectpickerRefresh); + } + + attrs.$observe('disabled', selectpickerRefresh); + + scope.$on('$destroy', selectpickerDestroy); + } + }; +}]); +;/** + * @ngdoc directive + * @name patternfly.sort.directive:pfSort + * + * @description + * Directive for a sort component + *

      + * + * @param {object} config configuration settings for the sort:
      + *
        + *
      • .fields - (Array) List of sortable fields containing: + *
          + *
        • .id - (String) Unique Id for the sort field + *
        • .title - (String) The title to display for the sort field + *
        • .sortType - (String) The sort type, 'alpha' or 'numeric' + *
        + *
      • .currentField - (Object) Currently selected field + *
      • .isAscending - (boolean) Current sort direction is ascending. True for ascending, False for descending + *
      • .onSortChange - ( function(sortId, sortDirection ) Function to call when the current sort params change + *
      + * + * @example + + +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      + {{item.name}} +
      +
      + {{item.count}} +
      +
      + {{item.description}} +
      +
      +
      +
      +
      +
      + + + angular.module('patternfly.sort').controller('ViewCtrl', ['$scope', + function ($scope) { + $scope.items = [ + { + name: "Item 7", + count: 432, + description: 'Very nice item' + }, + { + name: "Item 6", + count: 22, + description: 'It lasts forever' + }, + { + name: "Item 3", + count: 632, + description: 'Good stuff cheap' + }, + { + name: "Item 2", + count: 12, + description: 'Fantastic' + }, + { + name: "Item 9", + count: 99, + description: 'It does alright' + }, + { + name: "Item 4", + count: 442, + description: 'Horrible' + }, + { + name: "Item 1", + count: 42, + description: 'Most excellent' + }, + { + name: "Item 8", + count: 2, + description: 'Get it while it lasts' + }, + { + name: "Item 5", + count: 321, + description: 'Beautiful style' + } + ]; + + var compareFn = function(item1, item2) { + var compValue = 0; + if ($scope.sortConfig.currentField.id === 'name') { + compValue = item1.name.localeCompare(item2.name); + } else if ($scope.sortConfig.currentField.id === 'count') { + compValue = item1.count - item2.count; + } else if ($scope.sortConfig.currentField.id === 'description') { + compValue = item1.description.localeCompare(item2.description); + } + + if (!$scope.sortConfig.isAscending) { + compValue = compValue * -1; + } + + return compValue; + }; + + var sortChange = function (sortId, isAscending) { + $scope.items.sort(compareFn); + }; + + $scope.sortConfig = { + fields: [ + { + id: 'name', + title: 'Name', + sortType: 'alpha' + }, + { + id: 'count', + title: 'Count', + sortType: 'numeric' + }, + { + id: 'description', + title: 'Description', + sortType: 'alpha' + } + ], + onSortChange: sortChange + }; + } + ]); + +
      + */ +angular.module('patternfly.sort').directive('pfSort', function () { + 'use strict'; + return { + restrict: 'A', + scope: { + config: '=' + }, + templateUrl: 'sort/sort.html', + controller: ["$scope", function ($scope) { + + $scope.setupConfig = function () { + var updated = false; + + if ($scope.config.fields === undefined) { + $scope.config.fields = []; + } + + if ($scope.config.fields.length > 0) { + if ($scope.config.currentField === undefined) { + $scope.config.currentField = $scope.config.fields[0]; + updated = true; + } + if ($scope.config.isAscending === undefined) { + $scope.config.isAscending = true; + updated = true; + } + } + + if (updated === true && $scope.config.onSortChange) { + $scope.config.onSortChange($scope.config.currentField, $scope.config.isAscending); + } + }; + + $scope.selectField = function (field) { + $scope.config.currentField = field; + + if ($scope.config.onSortChange) { + $scope.config.onSortChange($scope.config.currentField, $scope.config.isAscending); + } + }; + + $scope.changeDirection = function () { + $scope.config.isAscending = !$scope.config.isAscending; + + if ($scope.config.onSortChange) { + $scope.config.onSortChange($scope.config.currentField, $scope.config.isAscending); + } + }; + + $scope.getSortIconClass = function () { + var iconClass; + + if ($scope.config.currentField.sortType === 'numeric') { + if ($scope.config.isAscending) { + iconClass = 'fa fa-sort-numeric-asc'; + } else { + iconClass = 'fa fa-sort-numeric-desc'; + } + } else { + if ($scope.config.isAscending) { + iconClass = 'fa fa-sort-alpha-asc'; + } else { + iconClass = 'fa fa-sort-alpha-desc'; + } + } + + return iconClass; + }; + + $scope.setupConfig(); + }], + + link: function (scope, element, attrs) { + scope.$watch('config', function () { + scope.setupConfig(); + }, true); + } + }; +}); +;/** + * @ngdoc directive + * @name patternfly.toolbars.directive:pfToolbar + * + * @description + * Directive for standard toolbar. Includes filtering and view selection capabilities + *

      + * + * @param {object} config configuration settings for the toolbar:
      + *
        + *
      • .filterConfig - (Object) Optional filter config. If undefined, no filtering capabilities are shown. + * See pfSimpleFilter for filter config options. + *
      • .sortConfig - (Object) Optional sort config. If undefined, no sort capabilities are shown. + * See pfSort for sort config options. + *
      • .viewsConfig - (Object) Optional configuration settings for view type selection + *
          + *
        • .views - (Array) List of available views for selection. See pfViewUtils for standard available views + *
            + *
          • .id - (String) Unique id for the view, used for comparisons + *
          • .title - (String) Optional title, uses as a tooltip for the view selector + *
          • .iconClass - (String) Icon class to use for the view selector + *
          + *
        • .onViewSelect - ( function(view) ) Function to call when a view is selected + *
        • .currentView - the id of the currently selected view + *
        + *
      • .actionsConfig - (Object) Optional configuration settings for toolbar actions + *
          + *
        • .primaryActions - (Array) List of primary actions to display on the toolbar + *
            + *
          • .name - (String) The name of the action, displayed on the button + *
          • .title - (String) Optional title, used for the tooltip + *
          • .actionFn - (function(action)) Function to invoke when the action selected + *
          • .isDisabled - (Boolean) set to true to disable the action + *
          + *
        • .moreActions - (Array) List of secondary actions to display on the toolbar action pulldown menu + *
            + *
          • .name - (String) The name of the action, displayed on the button + *
          • .title - (String) Optional title, used for the tooltip + *
          • .actionFn - (function(action)) Function to invoke when the action selected + *
          • .isDisabled - (Boolean) set to true to disable the action + *
          • .isSeparator - (Boolean) set to true if this is a placehodler for a separator rather than an action + *
          + *
        • .actionsInclude - (Boolean) set to true if using the actions transclude to add custom action buttons (only available if using Angular 1.5 or later) + *
        + *
      + * + * @example + + +
      +
      +
      + + + + + + + +
      +
      +
      +
      + +
      +
      +
      +
      +
      + {{item.name}} +
      +
      + {{item.address}} +
      +
      +
      +
      + {{item.age}} +
      +
      + {{item.birthMonth}} +
      +
      +
      +
      +
      +
      +
      + {{item.name}} +
      +
      + {{item.address}} +
      +
      + {{item.birthMonth}} +
      +
      +
      +
      + +
      +
      + +
      +
      + +
      +
      + +
      +
      +
      + + + angular.module('patternfly.toolbars').controller('ViewCtrl', ['$scope', 'pfViewUtils', + function ($scope, pfViewUtils) { + $scope.filtersText = ''; + + $scope.allItems = [ + { + name: "Fred Flintstone", + age: 57, + address: "20 Dinosaur Way, Bedrock, Washingstone", + birthMonth: 'February' + }, + { + name: "John Smith", + age: 23, + address: "415 East Main Street, Norfolk, Virginia", + birthMonth: 'October' + }, + { + name: "Frank Livingston", + age: 71, + address: "234 Elm Street, Pittsburgh, Pennsylvania", + birthMonth: 'March' + }, + { + name: "Judy Green", + age: 21, + address: "2 Apple Boulevard, Cincinatti, Ohio", + birthMonth: 'December' + }, + { + name: "Pat Thomas", + age: 19, + address: "50 Second Street, New York, New York", + birthMonth: 'February' + } + ]; + $scope.items = $scope.allItems; + + var matchesFilter = function (item, filter) { + var match = true; + + if (filter.id === 'name') { + match = item.name.match(filter.value) !== null; + } else if (filter.id === 'age') { + match = item.age === parseInt(filter.value); + } else if (filter.id === 'address') { + match = item.address.match(filter.value) !== null; + } else if (filter.id === 'birthMonth') { + match = item.birthMonth === filter.value; + } + return match; + }; + + var matchesFilters = function (item, filters) { + var matches = true; + + filters.forEach(function(filter) { + if (!matchesFilter(item, filter)) { + matches = false; + return false; + } + }); + return matches; + }; + + var applyFilters = function (filters) { + $scope.items = []; + if (filters && filters.length > 0) { + $scope.allItems.forEach(function (item) { + if (matchesFilters(item, filters)) { + $scope.items.push(item); + } + }); + } else { + $scope.items = $scope.allItems; + } + }; + + var filterChange = function (filters) { + $scope.filtersText = ""; + filters.forEach(function (filter) { + $scope.filtersText += filter.title + " : " + filter.value + "\n"; + }); + applyFilters(filters); + $scope.toolbarConfig.filterConfig.resultsCount = $scope.items.length; + }; + + $scope.filterConfig = { + fields: [ + { + id: 'name', + title: 'Name', + placeholder: 'Filter by Name...', + filterType: 'text' + }, + { + id: 'age', + title: 'Age', + placeholder: 'Filter by Age...', + filterType: 'text' + }, + { + id: 'address', + title: 'Address', + placeholder: 'Filter by Address...', + filterType: 'text' + }, + { + id: 'birthMonth', + title: 'Birth Month', + placeholder: 'Filter by Birth Month...', + filterType: 'select', + filterValues: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] + } + ], + resultsCount: $scope.items.length, + appliedFilters: [], + onFilterChange: filterChange + }; + + var viewSelected = function(viewId) { + $scope.viewType = viewId + }; + + $scope.viewsConfig = { + views: [pfViewUtils.getListView(), pfViewUtils.getCardView()], + onViewSelect: viewSelected + }; + $scope.viewsConfig.currentView = $scope.viewsConfig.views[0].id; + $scope.viewType = $scope.viewsConfig.currentView; + + var monthVals = { + 'January': 1, + 'February': 2, + 'March': 3, + 'April': 4, + 'May': 5, + 'June': 6, + 'July': 7, + 'August': 8, + 'September': 9, + 'October': 10, + 'November': 11, + 'December': 12 + }; + var compareFn = function(item1, item2) { + var compValue = 0; + if ($scope.sortConfig.currentField.id === 'name') { + compValue = item1.name.localeCompare(item2.name); + } else if ($scope.sortConfig.currentField.id === 'age') { + compValue = item1.age - item2.age; + } else if ($scope.sortConfig.currentField.id === 'address') { + compValue = item1.address.localeCompare(item2.address); + } else if ($scope.sortConfig.currentField.id === 'birthMonth') { + compValue = monthVals[item1.birthMonth] - monthVals[item2.birthMonth]; + } + + if (!$scope.sortConfig.isAscending) { + compValue = compValue * -1; + } + + return compValue; + }; + + var sortChange = function (sortId, isAscending) { + $scope.items.sort(compareFn); + }; + + $scope.sortConfig = { + fields: [ + { + id: 'name', + title: 'Name', + sortType: 'alpha' + }, + { + id: 'age', + title: 'Age', + sortType: 'numeric' + }, + { + id: 'address', + title: 'Address', + sortType: 'alpha' + }, + { + id: 'birthMonth', + title: 'Birth Month', + sortType: 'alpha' + } + ], + onSortChange: sortChange + }; + + $scope.actionsText = ""; + var performAction = function (action) { + $scope.actionsText = action.name + "\n" + $scope.actionsText; + }; + + $scope.actionsConfig = { + primaryActions: [ + { + name: 'Action 1', + title: 'Do the first thing', + actionFn: performAction + }, + { + name: 'Action 2', + title: 'Do something else', + actionFn: performAction + } + ], + moreActions: [ + { + name: 'Action', + title: 'Perform an action', + actionFn: performAction + }, + { + name: 'Another Action', + title: 'Do something else', + actionFn: performAction + }, + { + name: 'Disabled Action', + title: 'Unavailable action', + actionFn: performAction, + isDisabled: true + }, + { + name: 'Something Else', + title: '', + actionFn: performAction + }, + { + isSeparator: true + }, + { + name: 'Grouped Action 1', + title: 'Do something', + actionFn: performAction + }, + { + name: 'Grouped Action 2', + title: 'Do something similar', + actionFn: performAction + } + ], + actionsInclude: true + }; + + $scope.toolbarConfig = { + viewsConfig: $scope.viewsConfig, + filterConfig: $scope.filterConfig, + sortConfig: $scope.sortConfig, + actionsConfig: $scope.actionsConfig + }; + + $scope.listConfig = { + selectionMatchProp: 'name', + checkDisabled: false + }; + + $scope.doAdd = function () { + $scope.actionsText = "Add Action\n" + $scope.actionsText; + }; + $scope.optionSelected = function (option) { + $scope.actionsText = "Option " + option + " selected\n" + $scope.actionsText; + }; + } + ]); + +
      + */ +angular.module('patternfly.toolbars').directive('pfToolbar', function () { + 'use strict'; + return { + restrict: 'A', + scope: { + config: '=' + }, + replace: true, + transclude: { + 'actions': '?' + }, + templateUrl: 'toolbars/toolbar.html', + controller: ["$scope", function ($scope) { + $scope.viewSelected = function (viewId) { + $scope.config.viewsConfig.currentView = viewId; + if ($scope.config.viewsConfig.onViewSelect && !$scope.checkViewDisabled(viewId)) { + $scope.config.viewsConfig.onViewSelect(viewId); + } + }; + + $scope.isViewSelected = function (viewId) { + return $scope.config.viewsConfig && ($scope.config.viewsConfig.currentView === viewId); + }; + + $scope.checkViewDisabled = function (view) { + return $scope.config.viewsConfig.checkViewDisabled && $scope.config.viewsConfig.checkViewDisabled(view); + }; + + $scope.filterExists = function (filter) { + var foundFilter = _.findWhere($scope.config.filterConfig.appliedFilters, {title: filter.title, value: filter.value}); + return foundFilter !== undefined; + }; + + $scope.addFilter = function (field, value) { + var newFilter = { + id: field.id, + title: field.title, + value: value + }; + if (!$scope.filterExists(newFilter)) { + $scope.config.filterConfig.appliedFilters.push(newFilter); + + if ($scope.config.filterConfig.onFilterChange) { + $scope.config.filterConfig.onFilterChange($scope.config.filterConfig.appliedFilters); + } + } + }; + + $scope.handleAction = function (action) { + if (action && action.actionFn && (action.isDisabled !== true)) { + action.actionFn(action); + } + }; + }], + + link: function (scope, element, attrs) { + scope.$watch('config', function () { + if (scope.config && scope.config.viewsConfig && scope.config.viewsConfig.views) { + scope.config.viewsConfig.viewsList = angular.copy(scope.config.viewsConfig.views); + + if (!scope.config.viewsConfig.currentView) { + scope.config.viewsConfig.currentView = scope.config.viewsConfig.viewsList[0]; + } + } + }, true); + } + }; +}); +;/** + * @ngdoc directive + * @name patternfly.utils:pfFixedAccordion + * @restrict A + * @element ANY + * @param {string} scrollSelector specifies the selector to be used to find the element that should scroll (optional, the entire collapse area scrolls by default) + * @param {string} groupHeight Height to set for uib-accordion group (optional) + * @param {string} groupClass Class to set for uib-accordion group (optional) + * + * @description + * Directive for setting a ui-bootstrap uib-accordion to use a fixed height (collapse elements scroll when necessary) + * + * @example + + +
      +
      + + + Praesent sagittis est et arcu fringilla placerat. Cras erat ante, dapibus non mauris ac, volutpat sollicitudin ligula. Morbi gravida nisl vel risus tempor, sit amet luctus erat tempus. Curabitur blandit sem non pretium bibendum. Donec eleifend non turpis vitae vestibulum. Vestibulum ut sem ac nunc posuere blandit sed porta lorem. Cras rutrum velit vel leo iaculis imperdiet. + + + Donec consequat dignissim neque, sed suscipit quam egestas in. Fusce bibendum laoreet lectus commodo interdum. Vestibulum odio ipsum, tristique et ante vel, iaculis placerat nulla. Suspendisse iaculis urna feugiat lorem semper, ut iaculis risus tempus. + + + Curabitur nisl quam, interdum a venenatis a, consequat a ligula. Nunc nec lorem in erat rhoncus lacinia at ac orci. Sed nec augue congue, vehicula justo quis, venenatis turpis. Nunc quis consectetur purus. Nam vitae viverra lacus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum eu augue felis. Maecenas in dignissim purus, quis pulvinar lectus. Vivamus euismod ultrices diam, in mattis nibh. + + + Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. + + + Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas ligula massa, varius a, semper congue, euismod non, mi. Proin porttitor, orci nec nonummy molestie, enim est eleifend mi, non fermentum diam nisl sit amet erat. Duis semper. Duis arcu massa, scelerisque vitae, consequat in, pretium a, enim. Pellentesque congue. Ut in risus volutpat libero pharetra tempor. Cras vestibulum bibendum augue. Praesent egestas leo in pede. Praesent blandit odio eu enim. Pellentesque sed dui ut augue blandit sodales. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam nibh. Mauris ac mauris sed pede pellentesque fermentum. Maecenas adipiscing ante non diam sodales hendrerit. + + + Ut velit mauris, egestas sed, gravida nec, ornare ut, mi. Aenean ut orci vel massa suscipit pulvinar. Nulla sollicitudin. Fusce varius, ligula non tempus aliquam, nunc turpis ullamcorper nibh, in tempus sapien eros vitae ligula. Pellentesque rhoncus nunc et augue. Integer id felis. Curabitur aliquet pellentesque diam. Integer quis metus vitae elit lobortis egestas. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi vel erat non mauris convallis vehicula. Nulla et sapien. Integer tortor tellus, aliquam faucibus, convallis id, congue eu, quam. Mauris ullamcorper felis vitae erat. Proin feugiat, augue non elementum posuere, metus purus iaculis lectus, et tristique ligula justo vitae magna. + + + Aliquam convallis sollicitudin purus. Praesent aliquam, enim at fermentum mollis, ligula massa adipiscing nisl, ac euismod nibh nisl eu lectus. Fusce vulputate sem at sapien. Vivamus leo. Aliquam euismod libero eu enim. Nulla nec felis sed leo placerat imperdiet. Aenean suscipit nulla in justo. Suspendisse cursus rutrum augue. Nulla tincidunt tincidunt mi. Curabitur iaculis, lorem vel rhoncus faucibus, felis magna fermentum augue, et ultricies lacus lorem varius purus. Curabitur eu amet. + + + Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed at ante. Mauris eleifend, quam a vulputate dictum, massa quam dapibus leo, eget vulputate orci purus ut lorem. In fringilla mi in ligula. Pellentesque aliquam quam vel dolor. Nunc adipiscing. Sed quam odio, tempus ac, aliquam molestie, varius ac, tellus. Vestibulum ut nulla aliquam risus rutrum interdum. Pellentesque lorem. Curabitur sit amet erat quis risus feugiat viverra. Pellentesque augue justo, sagittis et, lacinia at, venenatis non, arcu. Nunc nec libero. In cursus dictum risus. Etiam tristique nisl a nulla. Ut a orci. Curabitur dolor nunc, egestas at, accumsan at, malesuada nec, magna. + + +
      +
      +
      + + + angular.module('patternfly.utils').controller( 'AccordionCntrl', function($scope) { + }); + +
      + */ +angular.module('patternfly.utils').directive('pfFixedAccordion', ["$window", "$timeout", function ($window, $timeout) { + 'use strict'; + return { + restrict: 'A', + scope: { + scrollSelector: '@', + groupHeight: '@', + groupClass: '@' + }, + link: function ($scope, $element, $attrs) { + var setCollapseHeights = function () { + var componentSelector, height, openPanel, contentHeight, bodyHeight, overflowY = 'hidden', parentElement = $element.find('.panel-group'); + + height = parentElement.height(); + + // Close any open panel + openPanel = parentElement.find('.collapse.in'); + if (openPanel && openPanel.length > 0) { + openPanel.removeClass('in'); + } + + // Determine the necessary height for the closed content + contentHeight = 0; + parentElement.children().each(function (index, groupHeading) { + var headingElement = angular.element(groupHeading); + contentHeight += headingElement.prop('offsetHeight'); + contentHeight += parseInt(headingElement.css('margin-top')); + contentHeight += parseInt(headingElement.css('margin-bottom')); + }); + + // Determine the height remaining for opened collapse panels + bodyHeight = height - contentHeight; + + // Make sure we have enough height to be able to scroll the contents if necessary + if (bodyHeight < 25) { + bodyHeight = 25; + + // Allow the parent to scroll so the child elements are accessible + overflowY = 'auto'; + } + + // Reopen the initially opened panel + if (openPanel && openPanel.length > 0) { + openPanel.addClass("in"); + } + + $timeout(function () { + // Set the max-height for the fixed height components + parentElement.find('.panel-collapse').each(function (index, collapsePanel) { + var $panel = angular.element(collapsePanel); + var scrollElement = $panel; + var innerHeight = 0; + var selected; + var $sibling; + + if (angular.isDefined($scope.scrollSelector)) { + selected = angular.element($panel.find($scope.scrollSelector)); + if (selected.length === 1) { + scrollElement = angular.element(selected[0]); + $panel.children().each(function (j, sibling) { + if (sibling !== scrollElement[0]) { + $sibling = angular.element(sibling); + innerHeight += $sibling.prop('offsetHeight'); + innerHeight += parseInt($sibling.css('margin-top')); + innerHeight += parseInt($sibling.css('margin-bottom')); + } + }); + } + } + + // set the max-height + angular.element(scrollElement).css('max-height', (bodyHeight - innerHeight) + 'px'); + angular.element(scrollElement).css('overflow-y', 'auto'); + }); + }); + + angular.element(parentElement).css('overflow-y', overflowY); + }; + + if ($scope.groupHeight) { + $element.find('.panel-group').css("height", $scope.groupHeight); + } + if ($scope.groupClass) { + $element.find('.panel-group').addClass($scope.groupClass); + } + + $timeout(function () { + setCollapseHeights(); + }, 100); + + // Update on window resizing + angular.element($window).bind('resize', function () { + setCollapseHeights(); + }); + } + }; +}]); +; +/** + * @ngdoc directive + * @name patternfly.utils.directive:pfTransclude + * @restrict A + * @element ANY + * @param {string} pfTransclude specifies the type of transclusion to use.
      + * Values: + *
        + *
      • 'sibling' - The transcluded contents scope is a sibling one to the element where transclusion happens (default) + *
      • 'parent' - The transcluded contents scope is that of the element where transclusion happens. + *
      • 'child' - The transcluded contents scope is child scope to the scope of the element where transclusion happens. + *
      + * + * @description + * Directive for transcluding in directives and setting up scope of children of parent directives. This is a workaround + * for https://github.com/angular/angular.js/issues/5489 + * + * @example + + +
      + Here the scope id is: {{$id}} + + +
      This content was transcluded using pf-transclude or pf-transclude="sibling".
      Its scope is: {{$id}} the parent of which is {{$parent.$id}}
      +
      + + +
      This content was transcluded using pf-transclude="parent".
      Its scope is: {{$id}} the parent of which is {{$parent.$id}}
      +
      + + +
      This content was transcluded using pf-transclude="child".
      Its scope is: {{$id}} the parent of which is {{$parent.$id}}
      +
      +
      +
      + + + angular.module('patternfly.utils') + .controller( 'UtilCtrl', function($scope) { + + }) + + .config(function($provide){ + $provide.decorator('ngTranscludeDirective', ['$delegate', function($delegate) { + // Remove the original directive + $delegate.shift(); + return $delegate; + }]); + }) + + .directive( 'transcludeSibling', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + template: + '
      ' + + '

      I am a directive with scope {{$id}}

      ' + + '' + + '
      ' + } + }) + + .directive( 'transcludeParent', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + template: + '
      ' + + '

      I am a directive with scope {{$id}}

      ' + + '' + + '
      ' + } + }) + + .directive( 'transcludeChild', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + template: + '
      ' + + '

      I am a directive with scope {{$id}}

      ' + + '' + + '
      ' + } + }) + ; +
      +
      + */ +angular + .module('patternfly.utils').directive('pfTransclude', function () { + 'use strict'; + return { + restrict: 'A', + link: function ($scope, $element, $attrs, controller, $transclude) { + var iChildScope; + var iScopeType; + + if (!$transclude) { + throw new Error('pfTransclude - ' + + 'Illegal use of pfTransclude directive in the template! ' + + 'No parent directive that requires a transclusion found. ' + + 'Element: {0}'); + } + + iScopeType = $attrs.pfTransclude || 'sibling'; + + switch (iScopeType) { + case 'sibling': + $transclude(function (clone) { + $element.empty(); + $element.append(clone); + }); + break; + case 'parent': + $transclude($scope, function (clone) { + $element.empty(); + $element.append( clone ); + }); + break; + case 'child': + iChildScope = $scope.$new(); + $transclude( iChildScope, function (clone) { + $element.empty(); + $element.append( clone ); + $element.on( '$destroy', function () { + iChildScope.$destroy(); + }); + }); + break; + } + } + }; + }); +;(function () { + 'use strict'; + + angular.module('patternfly.utils').constant('pfUtils', { + merge: function (source1, source2) { + var retValue; + + if (typeof angular.merge === 'function') { + retValue = this.angularMerge(source1, source2); + } else if (typeof _.merge === 'function') { + retValue = this._merge(source1, source2); + } else if (typeof $.extend === 'function') { + retValue = this.$extend(source1, source2); + } else { + retValue = this.mergeDeep(source1, source2); + } + + return retValue; + }, + angularMerge: function (source1, source2) { + return angular.merge({}, source1, source2); + }, + _merge: function (source1, source2) { + return _.merge({}, source1, source2); + }, + $extend: function (source1, source2) { + return $.extend(true, angular.copy(source1), source2); + }, + mergeDeep: function (source1, source2) { + return mergeDeep({}, angular.copy(source1), angular.copy(source2)); + }, + + colorPalette: $.pfPaletteColors + }); +})(); + +/* This function does not merge/concat Arrays. + * It replaces the earlier Array with any latter Array. + */ +function mergeDeep (dst) { + 'use strict'; + angular.forEach(arguments, function (obj) { + if (obj !== dst) { + angular.forEach(obj, function (value, key) { + if (dst[key] && dst[key].constructor && dst[key].constructor === Object) { + mergeDeep(dst[key], value); + } else { + dst[key] = value; + } + }); + } + }); + return dst; +} +;/** + * @ngdoc directive + * @name patternfly.validation:pfValidation + * @restrict E + * @element INPUT + * @scope + * + * @description + * Directive used for input validation based on custom function. + * + * @param {expression=} pfValidationDisabled If true, the validation is disabled, it is enabled otherwise. + * + * @example + + + +
      +
      + +
      + +
      + + The value you typed is not a number. +
      +
      + +
      + +
      + + The value you typed is not a number. +
      +
      + +
      + +
      + + The value you typed is not a number. +
      +
      + +
      + +
      + +
      +
      +
      +
      +
      + + + angular.module( 'patternfly.validation' ).controller( 'ValidationDemoCtrl', function( $scope ) { + $scope.myValue = "Change this value to be a number"; + $scope.myValueValid = 42; + $scope.isValidationDisabled = false; + + $scope.isNumber = function (value) { + if (isNaN(value)) { + return false; + } + + return true; + } + }); + + +
      + */ +angular.module('patternfly.validation', []).directive('pfValidation', ["$timeout", function ($timeout) { + 'use strict'; + + return { + restrict: 'A', + require: 'ngModel', + scope: { + pfValidation: '&', + pfValidationDisabled: '=' + }, + link: function (scope, element, attrs, ctrl) { + + scope.inputCtrl = ctrl; + scope.valEnabled = !attrs.pfValidationDisabled; + + scope.$watch('pfValidationDisabled', function (newVal) { + scope.valEnabled = !newVal; + if (newVal) { + scope.inputCtrl.$setValidity('pfValidation', true); + toggleErrorClass(false); + } else { + validate(); + } + }); + + // If validation function is set + if (attrs.pfValidation) { + // using $timeout(0) to get the actual $modelValue + $timeout(function () { + validate(); + }, 0); + } else if (!scope.inputCtrl.$valid && scope.inputCtrl.$dirty) { + toggleErrorClass(true); + } + + scope.$watch('inputCtrl.$valid', function (isValid) { + if (isValid) { + toggleErrorClass(false); + } else { + toggleErrorClass(true); + } + }); + + scope.$watch('inputCtrl.$modelValue', function () { + validate(); + }); + + function validate () { + var valid; + + var val = scope.inputCtrl.$modelValue; + + var valFunc = scope.pfValidation({'input': val}); + + if (!attrs.pfValidation) { + valFunc = true; + } + + valid = !val || valFunc || val === ''; + + if (scope.valEnabled && !valid) { + toggleErrorClass(true); + } else { + toggleErrorClass(false); + } + } + + function toggleErrorClass (add) { + var messageElement = element.next(); + var parentElement = element.parent(); + var hasErrorM = parentElement.hasClass('has-error'); + var wasHidden = messageElement.hasClass('ng-hide'); + + scope.inputCtrl.$setValidity('pf-validation', !add); + + if (add) { + if (!hasErrorM) { + parentElement.addClass('has-error'); + } + if (wasHidden) { + messageElement.removeClass('ng-hide'); + } + } + + if (!add) { + if (hasErrorM) { + parentElement.removeClass('has-error'); + } + if (!wasHidden) { + messageElement.addClass('ng-hide'); + } + } + } + } + }; +}]); +;/** + * @ngdoc directive + * @name patternfly.views.directive:pfCardView + * + * @description + * Directive for rendering cards in a view + *

      + * + * @param {object} config configuration settings for the cards:
      + *
        + *
      • .showSelectBox - (boolean) Show item selection boxes for each item, default is true + *
      • .selectItems - (boolean) Allow card selection, default is false + *
      • .dlbClick - (boolean) Handle double clicking (item remains selected on a double click). Default is false. + *
      • .multiSelect - (boolean) Allow multiple card selections, selectItems must also be set, not applicable when dblClick is true. Default is false + *
      • .selectionMatchProp - (string) Property of the items to use for determining matching, default is 'uuid' + *
      • .selectedItems - (array) Current set of selected items + *
      • .checkDisabled - ( function(item) ) Function to call to determine if an item is disabled, default is none + *
      • .onCheckBoxChange - ( function(item) ) Called to notify when a checkbox selection changes, default is none + *
      • .onSelect - ( function(item, event) ) Called to notify of item selection, default is none + *
      • .onSelectionChange - ( function(items) ) Called to notify when item selections change, default is none + *
      • .onClick - ( function(item, event) ) Called to notify when an item is clicked, default is none + *
      • .onDblClick - ( function(item, event) ) Called to notify when an item is double clicked, default is none + *
      + * + * @param {Array} items the data to be shown in the cards
      + * + * @example + + + +
      +
      +
      +
      + {{item.name}} +
      +
      + {{item.address}} +
      +
      + {{item.city}}, {{item.state}} +
      +
      +
      +
      +
      +
      +
      + +
      + + + +
      +
      +
      +
      +
      +
      + + +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      + +
      +
      + +
      +
      +
      + + + angular.module('patternfly.views').controller('ViewCtrl', ['$scope', + function ($scope) { + $scope.eventText = ''; + var handleSelect = function (item, e) { + $scope.eventText = item.name + ' selected\n' + $scope.eventText; + }; + var handleSelectionChange = function (selectedItems, e) { + $scope.eventText = selectedItems.length + ' items selected\n' + $scope.eventText; + }; + var handleClick = function (item, e) { + $scope.eventText = item.name + ' clicked\n' + $scope.eventText; + }; + var handleDblClick = function (item, e) { + $scope.eventText = item.name + ' double clicked\n' + $scope.eventText; + }; + var handleCheckBoxChange = function (item, selected, e) { + $scope.eventText = item.name + ' checked: ' + item.selected + '\n' + $scope.eventText; + }; + + var checkDisabledItem = function(item) { + return $scope.showDisabled && (item.name === "John Smith"); + }; + + $scope.selectType = 'checkbox'; + $scope.updateSelectionType = function() { + if ($scope.selectType === 'checkbox') { + $scope.config.selectItems = false; + $scope.config.showSelectBox = true; + } else if ($scope.selectType === 'card') { + $scope.config.selectItems = true; + $scope.config.showSelectBox = false; + } else { + $scope.config.selectItems = false + $scope.config.showSelectBox = false; + } + }; + + $scope.showDisabled = false; + + $scope.config = { + selectItems: false, + multiSelect: false, + dblClick: false, + selectionMatchProp: 'name', + selectedItems: [], + checkDisabled: checkDisabledItem, + showSelectBox: true, + onSelect: handleSelect, + onSelectionChange: handleSelectionChange, + onCheckBoxChange: handleCheckBoxChange, + onClick: handleClick, + onDblClick: handleDblClick + }; + + $scope.items = [ + { + name: "Fred Flintstone", + address: "20 Dinosaur Way", + city: "Bedrock", + state: "Washingstone" + }, + { + name: "John Smith", + address: "415 East Main Street", + city: "Norfolk", + state: "Virginia" + }, + { + name: "Frank Livingston", + address: "234 Elm Street", + city: "Pittsburgh", + state: "Pennsylvania" + }, + { + name: "Judy Green", + address: "2 Apple Boulevard", + city: "Cincinatti", + state: "Ohio" + }, + { + name: "Pat Thomas", + address: "50 Second Street", + city: "New York", + state: "New York" + }, + ] + } + ]); + +
      + */ +angular.module('patternfly.views').directive('pfCardView', ["pfUtils", function (pfUtils) { + 'use strict'; + return { + restrict: 'A', + scope: { + config: '=?', + items: '=', + eventId: '@id' + }, + transclude: true, + templateUrl: 'views/cardview/card-view.html', + controller: ["$scope", function ($scope) { + $scope.defaultConfig = { + selectItems: false, + multiSelect: false, + dblClick: false, + selectionMatchProp: 'uuid', + selectedItems: [], + checkDisabled: false, + showSelectBox: true, + onSelect: null, + onSelectionChange: null, + onCheckBoxChange: null, + onClick: null, + onDblClick: null + }; + + $scope.config = pfUtils.merge($scope.defaultConfig, $scope.config); + if ($scope.config.selectItems && $scope.config.showSelectBox) { + throw new Error('pfCardView - ' + + 'Illegal use of pfCardView directive! ' + + 'Cannot allow both select box and click selection in the same card view.'); + } + }], + link: function (scope, element, attrs) { + attrs.$observe('config', function () { + scope.config = pfUtils.merge(scope.defaultConfig, scope.config); + if (!scope.config.selectItems) { + scope.config.selectedItems = []; + } + if (!scope.config.multiSelect && scope.config.selectedItems && scope.config.selectedItems.length > 0) { + scope.config.selectedItems = [scope.config.selectedItems[0]]; + } + }); + + scope.itemClick = function (e, item) { + var alreadySelected; + var selectionChanged = false; + var continueEvent = true; + + // Ignore disabled item clicks completely + if (scope.checkDisabled(item)) { + return continueEvent; + } + + if (scope.config && scope.config.selectItems && item) { + if (scope.config.multiSelect && !scope.config.dblClick) { + + alreadySelected = _.find(scope.config.selectedItems, function (itemObj) { + return itemObj === item; + }); + + if (alreadySelected) { + // already selected so deselect + scope.config.selectedItems = _.without(scope.config.selectedItems, item); + } else { + // add the item to the selected items + scope.config.selectedItems.push(item); + selectionChanged = true; + } + } else { + if (scope.config.selectedItems[0] === item) { + if (!scope.config.dblClick) { + scope.config.selectedItems = []; + selectionChanged = true; + } + continueEvent = false; + } else { + scope.config.selectedItems = [item]; + selectionChanged = true; + } + } + + if (selectionChanged && scope.config.onSelect) { + scope.config.onSelect(item, e); + } + if (selectionChanged && scope.config.onSelectionChange) { + scope.config.onSelectionChange(scope.config.selectedItems, e); + } + } + if (scope.config.onClick) { + scope.config.onClick(item, e); + } + + return continueEvent; + }; + + scope.dblClick = function (e, item) { + if (scope.config.onDblClick) { + scope.config.onDblClick(item, e); + } + }; + + scope.checkBoxChange = function (item) { + if (scope.config.onCheckBoxChange) { + scope.config.onCheckBoxChange(item); + } + }; + + scope.isSelected = function (item) { + var matchProp = scope.config.selectionMatchProp; + var selected = false; + + if (scope.config.showSelectBox) { + selected = item.selected; + } else { + if (scope.config.selectedItems.length) { + return _.find(scope.config.selectedItems, function (itemObj) { + return itemObj[matchProp] === item[matchProp]; + }); + } + } + return selected; + }; + + scope.checkDisabled = function (item) { + return scope.config.checkDisabled && scope.config.checkDisabled(item); + }; + } + }; +}]); +;/** + * @ngdoc directive + * @name patternfly.views.directive:pfListView + * + * @description + * Directive for rendering a list view. + * Pass a customScope object containing any scope variables/functions you need to access from the transcluded source, access these + * via 'customScope' in your transcluded hmtl. + *

      + * If using expanding rows, use a list-expanded-content element containing expandable content for each row. Item data can be accessed inside list-expanded-content by using $parent.item.property. For each item in the items array, the expansion can be disabled by setting disableRowExpansion to true on the item. + * + * @param {array} items Array of items to display in the list view. If an item in the array has a 'rowClass' field, the value of this field will be used as a class specified on the row (list-group-item). + * @param {object} config Configuration settings for the list view: + *
        + *
      • .showSelectBox - (boolean) Show item selection boxes for each item, default is true + *
      • .selectItems - (boolean) Allow row selection, default is false + *
      • .dlbClick - (boolean) Handle double clicking (item remains selected on a double click). Default is false. + *
      • .multiSelect - (boolean) Allow multiple row selections, selectItems must also be set, not applicable when dblClick is true. Default is false + *
      • .useExpandingRows - (boolean) Allow row expansion for each list item. + *
      • .selectionMatchProp - (string) Property of the items to use for determining matching, default is 'uuid' + *
      • .selectedItems - (array) Current set of selected items + *
      • .checkDisabled - ( function(item) ) Function to call to determine if an item is disabled, default is none + *
      • .onCheckBoxChange - ( function(item) ) Called to notify when a checkbox selection changes, default is none + *
      • .onSelect - ( function(item, event) ) Called to notify of item selection, default is none + *
      • .onSelectionChange - ( function(items) ) Called to notify when item selections change, default is none + *
      • .onClick - ( function(item, event) ) Called to notify when an item is clicked, default is none + *
      • .onDblClick - ( function(item, event) ) Called to notify when an item is double clicked, default is none + *
      + * @param {array} actionButtons List of action buttons in each row + *
        + *
      • .name - (String) The name of the action, displayed on the button + *
      • .title - (String) Optional title, used for the tooltip + *
      • .class - (String) Optional class to add to the action button + *
      • .include - (String) Optional include src for the button. Used for custom button layouts (icons, dropdowns, etc) + *
      • .includeClass - (String) Optional class to set on the include src div (only relevant when include is set). + *
      • .actionFn - (function(action)) Function to invoke when the action selected + *
      + * @param {function (action, item))} enableButtonForItemFn function(action, item) Used to enabled/disable an action button based on the current item + * @param {array} menuActions List of actions for dropdown menu in each row + *
        + *
      • .name - (String) The name of the action, displayed on the button + *
      • .title - (String) Optional title, used for the tooltip + *
      • .actionFn - (function(action)) Function to invoke when the action selected + *
      • .isVisible - (Boolean) set to false to hide the action + *
      • .isDisabled - (Boolean) set to true to disable the action + *
      • .isSeparator - (Boolean) set to true if this is a placeholder for a separator rather than an action + *
      + * @param {function (item))} hideMenuForItemFn function(item) Used to hide all menu actions for a particular item + * @param {function (item))} menuClassForItemFn function(item) Used to specify a class for an item's dropdown kebab + * @param {function (action, item))} updateMenuActionForItemFn function(action, item) Used to update a menu action based on the current item + * @param {object} customScope Object containing any variables/functions used by the transcluded html, access via customScope. + * @example + + +
      +
      +
      +
      +
      + {{item.name}} +
      +
      + {{item.address}} +
      +
      +
      +
      + {{item.city}} +
      +
      + {{item.state}} +
      +
      + +
      +
      +
      +
      +
      +
      +
      Host
      +
      {{$parent.item.city}}
      +
      Admin
      +
      {{$parent.item.name}}
      +
      Time
      +
      January 15, 2016 10:45:11 AM
      +
      Severity
      +
      Warning
      +
      Cluster
      +
      Cluster 1
      +
      +

      + Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod + tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, + quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo + consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse + cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non + proident, sunt in culpa qui officia deserunt mollit anim id est laborum. +

      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +
      + + + +
      +
      +
      +
      +
      +
      + + +
      +
      +
      +
      +
      +
      + + +
      +
      +
      +
      + +
      +
      + +
      +
      +
      + + + angular.module('patternfly.views').controller('ViewCtrl', ['$scope', '$templateCache', + function ($scope, $templateCache) { + $scope.eventText = ''; + var handleSelect = function (item, e) { + $scope.eventText = item.name + ' selected\r\n' + $scope.eventText; + }; + var handleSelectionChange = function (selectedItems, e) { + $scope.eventText = selectedItems.length + ' items selected\r\n' + $scope.eventText; + }; + var handleClick = function (item, e) { + $scope.eventText = item.name + ' clicked\r\n' + $scope.eventText; + }; + var handleDblClick = function (item, e) { + $scope.eventText = item.name + ' double clicked\r\n' + $scope.eventText; + }; + var handleCheckBoxChange = function (item, selected, e) { + $scope.eventText = item.name + ' checked: ' + item.selected + '\r\n' + $scope.eventText; + }; + + var checkDisabledItem = function(item) { + return $scope.showDisabled && (item.name === "John Smith"); + }; + + $scope.enableButtonForItemFn = function(action, item) { + return !((action.name ==='Action 2') && (item.name === "Frank Livingston")) && + !(action.name === 'Start' && item.started); + }; + + $scope.updateMenuActionForItemFn = function(action, item) { + if (action.name === 'Another Action') { + action.isVisible = (item.name !== "John Smith"); + } + }; + + $scope.exampleChartConfig = { + 'chartId': 'pctChart', + 'units': 'GB', + 'thresholds': { + 'warning':'60', + 'error':'90' + } + }; + + $scope.selectType = 'checkbox'; + $scope.updateSelectionType = function() { + if ($scope.selectType === 'checkbox') { + $scope.config.selectItems = false; + $scope.config.showSelectBox = true; + } else if ($scope.selectType === 'row') { + $scope.config.selectItems = true; + $scope.config.showSelectBox = false; + } else { + $scope.config.selectItems = false + $scope.config.showSelectBox = false; + } + }; + + $scope.showDisabled = false; + + $scope.config = { + selectItems: false, + multiSelect: false, + dblClick: false, + selectionMatchProp: 'name', + selectedItems: [], + checkDisabled: checkDisabledItem, + showSelectBox: true, + useExpandingRows: false, + onSelect: handleSelect, + onSelectionChange: handleSelectionChange, + onCheckBoxChange: handleCheckBoxChange, + onClick: handleClick, + onDblClick: handleDblClick + }; + + $scope.items = [ + { + name: "Fred Flintstone", + address: "20 Dinosaur Way", + city: "Bedrock", + state: "Washingstone" + }, + { + name: "John Smith", + address: "415 East Main Street", + city: "Norfolk", + state: "Virginia", + disableRowExpansion: true + }, + { + name: "Frank Livingston", + address: "234 Elm Street", + city: "Pittsburgh", + state: "Pennsylvania" + }, + { + name: "Linda McGovern", + address: "22 Oak Street", + city: "Denver", + state: "Colorado" + }, + { + name: "Jim Brown", + address: "72 Bourbon Way", + city: "Nashville", + state: "Tennessee" + }, + { + name: "Holly Nichols", + address: "21 Jump Street", + city: "Hollywood", + state: "California" + }, + { + name: "Marie Edwards", + address: "17 Cross Street", + city: "Boston", + state: "Massachusetts" + }, + { + name: "Pat Thomas", + address: "50 Second Street", + city: "New York", + state: "New York" + }, + ]; + + $scope.getMenuClass = function (item) { + var menuClass = ""; + if (item.name === "Jim Brown") { + menuClass = 'red'; + } + return menuClass; + }; + + $scope.hideMenuActions = function (item) { + return (item.name === "Marie Edwards"); + }; + + var performAction = function (action, item) { + $scope.eventText = item.name + " : " + action.name + "\r\n" + $scope.eventText; + }; + + var startServer = function (action, item) { + $scope.eventText = item.name + " : " + action.name + "\r\n" + $scope.eventText; + item.started = true; + }; + + var buttonInclude = '{{actionButton.name}}'; + $templateCache.put('my-button-template', buttonInclude); + + var startButtonInclude = '{{item.started ? "Starting" : "Start"}}'; + $templateCache.put('start-button-template', startButtonInclude); + + $scope.actionButtons = [ + { + name: 'Start', + class: 'btn-primary', + include: 'start-button-template', + title: 'Start the server', + actionFn: startServer + }, + { + name: 'Action 1', + title: 'Perform an action', + actionFn: performAction + }, + { + name: 'Action 2', + title: 'Do something else', + actionFn: performAction + }, + { + name: 'Action 3', + include: 'my-button-template', + title: 'Do something special', + actionFn: performAction + } + ]; + $scope.menuActions = [ + { + name: 'Action', + title: 'Perform an action', + actionFn: performAction + }, + { + name: 'Another Action', + title: 'Do something else', + actionFn: performAction + }, + { + name: 'Disabled Action', + title: 'Unavailable action', + actionFn: performAction, + isDisabled: true + }, + { + name: 'Something Else', + title: '', + actionFn: performAction + }, + { + isSeparator: true + }, + { + name: 'Grouped Action 1', + title: 'Do something', + actionFn: performAction + }, + { + name: 'Grouped Action 2', + title: 'Do something similar', + actionFn: performAction + } + ]; + } + ]); + +
      + */ +angular.module('patternfly.views').directive('pfListView', ["$timeout", "$window", "pfUtils", function ($timeout, $window, pfUtils) { + 'use strict'; + return { + restrict: 'A', + scope: { + config: '=?', + items: '=', + actionButtons: '=?', + enableButtonForItemFn: '=?', + menuActions: '=?', + hideMenuForItemFn: '=?', + menuClassForItemFn: '=?', + updateMenuActionForItemFn: '=?', + actions: '=?', + updateActionForItemFn: '=?', + customScope: '=?' + }, + transclude: { + expandedContent: '?listExpandedContent' + }, + templateUrl: 'views/listview/list-view.html', + controller: + ["$scope", "$element", function ($scope, $element) { + var setDropMenuLocation = function (parentDiv) { + var dropButton = parentDiv.querySelector('.dropdown-toggle'); + var dropMenu = parentDiv.querySelector('.dropdown-menu'); + var parentRect = $element[0].getBoundingClientRect(); + var buttonRect = dropButton.getBoundingClientRect(); + var menuRect = dropMenu.getBoundingClientRect(); + var menuTop = buttonRect.top - menuRect.height; + var menuBottom = buttonRect.top + buttonRect.height + menuRect.height; + + if ((menuBottom <= parentRect.top + parentRect.height) || (menuTop < parentRect.top)) { + $scope.dropdownClass = 'dropdown'; + } else { + $scope.dropdownClass = 'dropup'; + } + }; + + $scope.defaultConfig = { + selectItems: false, + multiSelect: false, + dblClick: false, + selectionMatchProp: 'uuid', + selectedItems: [], + checkDisabled: false, + useExpandingRows: false, + showSelectBox: true, + onSelect: null, + onSelectionChange: null, + onCheckBoxChange: null, + onClick: null, + onDblClick: null + }; + + $scope.config = pfUtils.merge($scope.defaultConfig, $scope.config); + if ($scope.config.selectItems && $scope.config.showSelectBox) { + throw new Error('pfListView - ' + + 'Illegal use of pListView directive! ' + + 'Cannot allow both select box and click selection in the same list view.'); + } + $scope.dropdownClass = 'dropdown'; + + $scope.handleButtonAction = function (action, item) { + if (!$scope.checkDisabled(item) && action && action.actionFn && $scope.enableButtonForItem(action, item)) { + action.actionFn(action, item); + } + }; + + $scope.handleMenuAction = function (action, item) { + if (!$scope.checkDisabled(item) && action && action.actionFn && (action.isDisabled !== true)) { + action.actionFn(action, item); + } + }; + + $scope.enableButtonForItem = function (action, item) { + var enable = true; + if (typeof $scope.enableButtonForItemFn === 'function') { + return $scope.enableButtonForItemFn(action, item); + } + return enable; + }; + + $scope.updateActions = function (item) { + if (typeof $scope.updateMenuActionForItemFn === 'function') { + $scope.menuActions.forEach(function (action) { + $scope.updateMenuActionForItemFn(action, item); + }); + } + }; + + $scope.getMenuClassForItem = function (item) { + var menuClass = ''; + if (angular.isFunction($scope.menuClassForItemFn)) { + menuClass = $scope.menuClassForItemFn(item); + } + + return menuClass; + }; + + $scope.hideMenuForItem = function (item) { + var hideMenu = false; + if (angular.isFunction($scope.hideMenuForItemFn)) { + hideMenu = $scope.hideMenuForItemFn(item); + } + + return hideMenu; + }; + + $scope.toggleItemExpansion = function (item) { + item.isExpanded = !item.isExpanded; + }; + + $scope.setupActions = function (item, event) { + // Ignore disabled items completely + if ($scope.checkDisabled(item)) { + return; + } + + // update the actions based on the current item + $scope.updateActions(item); + + $timeout(function () { + var parentDiv = undefined; + var nextElement; + + nextElement = event.target; + while (nextElement && !parentDiv) { + if (nextElement.className.indexOf('dropdown-kebab-pf') !== -1) { + parentDiv = nextElement; + if (nextElement.className.indexOf('open') !== -1) { + setDropMenuLocation (parentDiv); + } + } + nextElement = nextElement.parentElement; + } + }); + }; + }], + + link: function (scope, element, attrs) { + attrs.$observe('config', function () { + scope.config = pfUtils.merge(scope.defaultConfig, scope.config); + if (!scope.config.selectItems) { + scope.config.selectedItems = []; + } + if (!scope.config.multiSelect && scope.config.selectedItems && scope.config.selectedItems.length > 0) { + scope.config.selectedItems = [scope.config.selectedItems[0]]; + } + }); + + scope.itemClick = function (e, item) { + var alreadySelected; + var selectionChanged = false; + var continueEvent = true; + + // Ignore disabled item clicks completely + if (scope.checkDisabled(item)) { + return continueEvent; + } + + if (scope.config && scope.config.selectItems && item) { + if (scope.config.multiSelect && !scope.config.dblClick) { + + alreadySelected = _.find(scope.config.selectedItems, function (itemObj) { + return itemObj === item; + }); + + if (alreadySelected) { + // already selected so deselect + scope.config.selectedItems = _.without(scope.config.selectedItems, item); + } else { + // add the item to the selected items + scope.config.selectedItems.push(item); + selectionChanged = true; + } + } else { + if (scope.config.selectedItems[0] === item) { + if (!scope.config.dblClick) { + scope.config.selectedItems = []; + selectionChanged = true; + } + continueEvent = false; + } else { + scope.config.selectedItems = [item]; + selectionChanged = true; + } + } + + if (selectionChanged && scope.config.onSelect) { + scope.config.onSelect(item, e); + } + if (selectionChanged && scope.config.onSelectionChange) { + scope.config.onSelectionChange(scope.config.selectedItems, e); + } + } + if (scope.config.onClick) { + scope.config.onClick(item, e); + } + + return continueEvent; + }; + + scope.dblClick = function (e, item) { + // Ignore disabled item clicks completely + if (scope.checkDisabled(item)) { + return continueEvent; + } + + if (scope.config.onDblClick) { + scope.config.onDblClick(item, e); + } + }; + + scope.checkBoxChange = function (item) { + if (scope.config.onCheckBoxChange) { + scope.config.onCheckBoxChange(item); + } + }; + + scope.isSelected = function (item) { + var matchProp = scope.config.selectionMatchProp; + var selected = false; + + if (scope.config.showSelectBox) { + selected = item.selected; + } else if (scope.config.selectItems && scope.config.selectedItems.length) { + selected = _.find(scope.config.selectedItems, function (itemObj) { + return itemObj[matchProp] === item[matchProp]; + }); + } + return selected; + }; + + scope.checkDisabled = function (item) { + return scope.config.checkDisabled && scope.config.checkDisabled(item); + }; + } + }; +}]); +;(function () { + 'use strict'; + + angular.module('patternfly.views').constant('pfViewUtils', { + getDashboardView: function (title) { + return { + id: 'dashboardView', + title: title || 'Dashboard View', + iconClass: 'fa fa-dashboard' + }; + }, + getCardView: function (title) { + return { + id: 'cardView', + title: title || 'Card View', + iconClass: 'fa fa-th' + }; + }, + getListView: function (title) { + return { + id: 'listView', + title: title || 'List View', + iconClass: 'fa fa-th-list' + }; + }, + getTableView: function (title) { + return { + id: 'tableView', + title: title || 'Table View', + iconClass: 'fa fa-table' + }; + }, + getTopologyView: function (title) { + return { + id: 'topologyView', + title: title || 'Topology View', + iconClass: 'fa fa-sitemap' + }; + } + }); +})(); +;(function () { + 'use strict'; + function pfWizardButtonDirective (action) { + angular.module('patternfly.wizard') + .directive(action, function () { + return { + restrict: 'A', + require: '^pf-wizard', + scope: { + callback: "=?" + }, + link: function ($scope, $element, $attrs, wizard) { + $element.on("click", function (e) { + e.preventDefault(); + $scope.$apply(function () { + // scope apply in button module + $scope.$eval($attrs[action]); + wizard[action.replace("pfWiz", "").toLowerCase()]($scope.callback); + }); + }); + } + }; + }); + } + + pfWizardButtonDirective('pfWizNext'); + pfWizardButtonDirective('pfWizPrevious'); + pfWizardButtonDirective('pfWizFinish'); + pfWizardButtonDirective('pfWizCancel'); + pfWizardButtonDirective('pfWizReset'); +})(); +;/** + * @ngdoc directive + * @name patternfly.wizard.directive:pfWizard + * + * @description + * Directive for rendering a Wizard modal. Each wizard dynamically creates the step navigation both in the header and the left-hand side based on nested steps. + * Use the pf-wizardstep to define individual steps within a wizard and pf-wizardsubstep to define portions of pf-wizardsteps if so desired. For instance, Step one can have two substeps - 1A and 1B when it is logical to group those together. + *

      + * The basic structure should be: + *
      +  * 
      + *
      + *
      + *
      + *
      + *
      + *
      + *
      + *
      + * + * @param {string} title The wizard title displayed in the header + * @param {boolean=} hideIndicators Hides the step indicators in the header of the wizard + * @param {string=} currentStep The current step can be changed externally - this is the title of the step to switch the wizard to + * @param {string=} cancelTitle The text to display on the cancel button + * @param {string=} backTitle The text to display on the back button + * @param {string=} nextTitle The text to display on the next button + * @param {function(step)=} backCallback Called to notify when the back button is clicked + * @param {function(step)=} nextCallback Called to notify when the next button is clicked + * @param {function()=} onFinish Called to notify when when the wizard is complete. Returns a boolean value to indicate if the finish operation is complete + * @param {function()=} onCancel Called when the wizard is canceled, returns a boolean value to indicate if cancel is successful + * @param {boolean} wizardReady Value that is set when the wizard is ready + * @param {boolean=} wizardDone Value that is set when the wizard is done + * @param {string} loadingWizardTitle The text displayed when the wizard is loading + * @param {string=} loadingSecondaryInformation Secondary descriptive information to display when the wizard is loading + * @param {string=} contentHeight The height the wizard content should be set to. This defaults to 300px if the property is not supplied. + * @param {boolean=} embedInPage Value that indicates wizard is embedded in a page (not a modal). This moves the navigation buttons to the left hand side of the footer and removes the close button. + * + * @example + + +
      + +
      +
      + +
      +
      +
      +
      +
      +
      +
      + +
      +
      + +
      +
      +
      +
      +
      +
      +

      Wizards should make use of substeps consistently throughout (either using them or not using them). This is an example only.

      +
      + +
      +
      + +
      +
      +
      +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      + +
      +
      + +
      +
      +
      +
      +
      + +
      +
      +
      + Name: + {{data.name}} +
      +
      + Description: + {{data.description}} +
      +
      +
      +
      + +
      +
      +
      + Lorem: + {{data.lorem}} +
      +
      + Ipsum: + {{data.ipsum}} +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      +

      Deployment in progress

      +

      Lorem ipsum dolor sit amet, porta at suspendisse ac, ut wisi vivamus, lorem sociosqu eget nunc amet.

      +
      +
      +
      +

      Deployment was successful

      +

      Lorem ipsum dolor sit amet, porta at suspendisse ac, ut wisi vivamus, lorem sociosqu eget nunc amet.

      + +
      +
      +
      +
      +
      + + angular.module('patternfly.wizard').controller('WizardModalController', ['$scope', '$timeout', '$uibModal', '$rootScope', + function ($scope, $timeout, $uibModal, $rootScope) { + $scope.openWizardModel = function () { + var wizardDoneListener, + modalInstance = $uibModal.open({ + animation: true, + backdrop: 'static', + templateUrl: 'wizard-container.html', + controller: 'WizardController', + size: 'lg' + }); + + var closeWizard = function (e, reason) { + modalInstance.dismiss(reason); + wizardDoneListener(); + }; + + modalInstance.result.then(function () { }, function () { }); + + wizardDoneListener = $rootScope.$on('wizard.done', closeWizard); + }; + } + ]); + angular.module('patternfly.wizard').controller('WizardController', ['$scope', '$timeout', '$rootScope', + function ($scope, $timeout, $rootScope) { + + + var initializeWizard = function () { + $scope.data = { + name: '', + description: '', + lorem: 'default setting', + ipsum: '' + }; + $scope.secondaryLoadInformation = 'ipsum dolor sit amet, porta at suspendisse ac, ut wisi vivamus, lorem sociosqu eget nunc amet.'; + $timeout(function () { + $scope.deployReady = true; + }, 1000); + $scope.nextButtonTitle = "Next >"; + }; + + var startDeploy = function () { + $timeout(function() { }, 2000); + $scope.deployInProgress = true; + }; + + $scope.data = {}; + + $scope.nextCallback = function (step) { + // call startdeploy after deploy button is clicked on review-summary tab + if (step.stepId === 'review-summary') { + startDeploy(); + } + return true; + }; + $scope.backCallback = function (step) { + return true; + }; + + $scope.$on("wizard:stepChanged", function (e, parameters) { + if (parameters.step.stepId === 'review-summary') { + $scope.nextButtonTitle = "Deploy"; + } else if (parameters.step.stepId === 'review-progress') { + $scope.nextButtonTitle = "Close"; + } else { + $scope.nextButtonTitle = "Next >"; + } + }); + + $scope.cancelDeploymentWizard = function () { + $rootScope.$emit('wizard.done', 'cancel'); + }; + + $scope.finishedWizard = function () { + $rootScope.$emit('wizard.done', 'done'); + return true; + }; + + initializeWizard(); + } + ]); + + angular.module('patternfly.wizard').controller('DetailsGeneralController', ['$rootScope', '$scope', + function ($rootScope, $scope) { + 'use strict'; + + $scope.reviewTemplate = "review-template.html"; + $scope.detailsGeneralComplete = false; + + $scope.onShow = function() { }; + + $scope.updateName = function() { + $scope.detailsGeneralComplete = angular.isDefined($scope.data.name) && $scope.data.name.length > 0; + }; + } + ]); + + angular.module('patternfly.wizard').controller('DetailsReviewController', ['$rootScope', '$scope', + function ($rootScope, $scope) { + 'use strict'; + + // Find the data! + var next = $scope; + while (angular.isUndefined($scope.data)) { + next = next.$parent; + if (angular.isUndefined(next)) { + $scope.data = {}; + } else { + $scope.data = next.wizardData; + } + } + } + ]); + + angular.module('patternfly.wizard').controller('SummaryController', ['$rootScope', '$scope', '$timeout', + function ($rootScope, $scope, $timeout) { + 'use strict'; + $scope.pageShown = false; + + $scope.onShow = function () { + $scope.pageShown = true; + $timeout(function () { + $scope.pageShown = false; // done so the next time the page is shown it updates + }); + } + } + ]); + + angular.module('patternfly.wizard').controller('DeploymentController', ['$rootScope', '$scope', '$timeout', + function ($rootScope, $scope, $timeout) { + 'use strict'; + + $scope.onShow = function() { + $scope.deploymentComplete = false; + $timeout(function() { + $scope.deploymentComplete = true; + }, 2500); + }; + } + ]); + +
      +*/ + +angular.module('patternfly.wizard').directive('pfWizard', ["$window", function ($window) { + 'use strict'; + return { + restrict: 'A', + transclude: true, + scope: { + title: '@', + hideIndicators: '=?', + currentStep: '=?', + cancelTitle: '=?', + backTitle: '=?', + nextTitle: '=?', + backCallback: '=?', + nextCallback: '=?', + onFinish: '&', + onCancel: '&', + wizardReady: '=?', + wizardDone: '=?', + loadingWizardTitle: '=?', + loadingSecondaryInformation: '=?', + contentHeight: '=?', + embedInPage: '=?' + }, + templateUrl: 'wizard/wizard.html', + controller: ["$scope", "$timeout", function ($scope, $timeout) { + var firstRun = true; + + var stepIdx = function (step) { + var idx = 0; + var res = -1; + angular.forEach($scope.getEnabledSteps(), function (currStep) { + if (currStep === step) { + res = idx; + } + idx++; + }); + return res; + }; + + var unselectAll = function () { + //traverse steps array and set each "selected" property to false + angular.forEach($scope.getEnabledSteps(), function (step) { + step.selected = false; + }); + //set selectedStep variable to null + $scope.selectedStep = null; + }; + + var watchSelectedStep = function () { + // Remove any previous watchers + if ($scope.nextStepEnabledWatcher) { + $scope.nextStepEnabledWatcher(); + } + if ($scope.nextStepTooltipWatcher) { + $scope.nextStepTooltipWatcher(); + } + if ($scope.prevStepEnabledWatcher) { + $scope.prevStepEnabledWatcher(); + } + if ($scope.prevStepTooltipWatcher) { + $scope.prevStepTooltipWatcher(); + } + + // Add watchers for the selected step + $scope.nextStepEnabledWatcher = $scope.$watch('selectedStep.nextEnabled', function (value) { + $scope.nextEnabled = value; + }); + $scope.nextStepTooltipWatcher = $scope.$watch('selectedStep.nextTooltip', function (value) { + $scope.nextTooltip = value; + }); + $scope.prevStepEnabledWatcher = $scope.$watch('selectedStep.prevEnabled', function (value) { + $scope.prevEnabled = value; + }); + $scope.prevStepTooltipWatcher = $scope.$watch('selectedStep.prevTooltip', function (value) { + $scope.prevTooltip = value; + }); + }; + + var stepByTitle = function (titleToFind) { + var foundStep = null; + angular.forEach($scope.getEnabledSteps(), function (step) { + if (step.title === titleToFind) { + foundStep = step; + } + }); + return foundStep; + }; + + $scope.steps = []; + $scope.context = {}; + this.context = $scope.context; + + if (angular.isUndefined($scope.wizardReady)) { + $scope.wizardReady = true; + } + + if (angular.isUndefined($scope.contentHeight)) { + $scope.contentHeight = '300px'; + } + this.contentHeight = $scope.contentHeight; + $scope.contentStyle = { + 'height': $scope.contentHeight, + 'max-height': $scope.contentHeight, + 'overflow-y': 'auto' + }; + this.contentStyle = $scope.contentStyle; + + $scope.nextEnabled = false; + $scope.prevEnabled = false; + + if (!$scope.cancelTitle) { + $scope.cancelTitle = "Cancel"; + } + if (!$scope.backTitle) { + $scope.backTitle = "< Back"; + } + if (!$scope.nextTitle) { + $scope.nextTitle = "Next >"; + } + + $scope.getEnabledSteps = function () { + return $scope.steps.filter(function (step) { + return step.disabled !== 'true'; + }); + }; + + this.getReviewSteps = function () { + return $scope.steps.filter(function (step) { + return !step.disabled && + (!angular.isUndefined(step.reviewTemplate) || step.getReviewSteps().length > 0); + }); + }; + + $scope.currentStepNumber = function () { + //retrieve current step number + return stepIdx($scope.selectedStep) + 1; + }; + + $scope.getStepNumber = function (step) { + return stepIdx(step) + 1; + }; + + //watching changes to currentStep + $scope.$watch('currentStep', function (step) { + //checking to make sure currentStep is truthy value + if (!step) { + return; + } + + //setting stepTitle equal to current step title or default title + if ($scope.selectedStep && $scope.selectedStep.title !== $scope.currentStep) { + $scope.goTo(stepByTitle($scope.currentStep)); + } + }); + + //watching steps array length and editMode value, if edit module is undefined or null the nothing is done + //if edit mode is truthy, then all steps are marked as completed + $scope.$watch('[editMode, steps.length]', function () { + var editMode = $scope.editMode; + if (angular.isUndefined(editMode) || (editMode === null)) { + return; + } + + if (editMode) { + angular.forEach($scope.getEnabledSteps(), function (step) { + step.completed = true; + }); + } else { + angular.forEach($scope.getEnabledSteps(), function (step, stepIndex) { + if (stepIndex >= ($scope.currentStepNumber() - 1)) { + step.completed = false; + } + }); + } + }, true); + + $scope.goTo = function (step, resetStepNav) { + if ($scope.wizardDone || ($scope.selectedStep && !$scope.selectedStep.okToNavAway) || step === $scope.selectedStep) { + return; + } + + if (firstRun || ($scope.getStepNumber(step) < $scope.currentStepNumber() && $scope.selectedStep.isPrevEnabled()) || $scope.selectedStep.isNextEnabled()) { + unselectAll(); + + if (!firstRun && resetStepNav && step.substeps) { + step.resetNav(); + } + + $scope.selectedStep = step; + step.selected = true; + + $timeout(function () { + if (angular.isFunction(step.onShow)) { + step.onShow(); + } + }, 100); + + watchSelectedStep(); + + // Make sure current step is not undefined + $scope.currentStep = step.title; + + //emit event upwards with data on goTo() invocation + if (!step.substeps) { + $scope.$emit('wizard:stepChanged', {step: step, index: stepIdx(step)}); + } + firstRun = false; + } + + if (!$scope.selectedStep.substeps) { + $scope.firstStep = stepIdx($scope.selectedStep) === 0; + } else { + $scope.firstStep = stepIdx($scope.selectedStep) === 0 && $scope.selectedStep.currentStepNumber() === 1; + } + }; + + $scope.stepClick = function (step) { + if (step.allowClickNav) { + $scope.goTo(step, true); + } + }; + + this.addStep = function (step) { + // Insert the step into step array + var insertBefore = _.find($scope.steps, function (nextStep) { + return nextStep.stepPriority > step.stepPriority; + }); + if (insertBefore) { + $scope.steps.splice($scope.steps.indexOf(insertBefore), 0, step); + } else { + $scope.steps.push(step); + } + + if ($scope.wizardReady && ($scope.getEnabledSteps().length > 0) && (step === $scope.getEnabledSteps()[0])) { + $scope.goTo($scope.getEnabledSteps()[0]); + } + }; + + this.isWizardDone = function () { + return $scope.wizardDone; + }; + + this.updateSubStepNumber = function (value) { + $scope.firstStep = stepIdx($scope.selectedStep) === 0 && value === 0; + }; + + this.currentStepTitle = function () { + return $scope.selectedStep.title; + }; + + this.currentStepDescription = function () { + return $scope.selectedStep.description; + }; + + this.currentStep = function () { + return $scope.selectedStep; + }; + + this.totalStepCount = function () { + return $scope.getEnabledSteps().length; + }; + + this.getEnabledSteps = function () { + return $scope.getEnabledSteps(); + }; + + //Access to current step number from outside + this.currentStepNumber = function () { + return $scope.currentStepNumber(); + }; + + this.getStepNumber = function (step) { + return $scope.getStepNumber(step); + }; + + // Allow access to any step + this.goTo = function (step, resetStepNav) { + var enabledSteps = $scope.getEnabledSteps(); + var stepTo; + + if (angular.isNumber(step)) { + stepTo = enabledSteps[step]; + } else { + stepTo = stepByTitle(step); + } + + $scope.goTo(stepTo, resetStepNav); + }; + + // Method used for next button within step + this.next = function (callback) { + var enabledSteps = $scope.getEnabledSteps(); + + // Save the step you were on when next() was invoked + var index = stepIdx($scope.selectedStep); + + if ($scope.selectedStep.substeps) { + if ($scope.selectedStep.next(callback)) { + return; + } + } + + // Check if callback is a function + if (angular.isFunction(callback)) { + if (callback($scope.selectedStep)) { + if (index === enabledSteps.length - 1) { + this.finish(); + } else { + // Go to the next step + if (enabledSteps[index + 1].substeps) { + enabledSteps[index + 1].resetNav(); + } + } + } else { + return; + } + } + + // Completed property set on scope which is used to add class/remove class from progress bar + $scope.selectedStep.completed = true; + + // Check to see if this is the last step. If it is next behaves the same as finish() + if (index === enabledSteps.length - 1) { + this.finish(); + } else { + // Go to the next step + $scope.goTo(enabledSteps[index + 1]); + } + }; + + this.previous = function (callback) { + var index = stepIdx($scope.selectedStep); + + if ($scope.selectedStep.substeps) { + if ($scope.selectedStep.previous(callback)) { + return; + } + } + + // Check if callback is a function + if (angular.isFunction(callback)) { + if (callback($scope.selectedStep)) { + if (index === 0) { + throw new Error("Can't go back. It's already in step 0"); + } else { + $scope.goTo($scope.getEnabledSteps()[index - 1]); + } + } + } + }; + + this.finish = function () { + if ($scope.onFinish) { + if ($scope.onFinish() !== false) { + this.reset(); + } + } + }; + + this.cancel = function () { + if ($scope.onCancel) { + if ($scope.onCancel() !== false) { + this.reset(); + } + } + }; + + //reset + this.reset = function () { + //traverse steps array and set each "completed" property to false + angular.forEach($scope.getEnabledSteps(), function (step) { + step.completed = false; + }); + //go to first step + this.goTo(0); + }; + }], + link: function ($scope) { + $scope.$watch('wizardReady', function () { + if ($scope.wizardReady) { + $scope.goTo($scope.getEnabledSteps()[0]); + } + }); + } + }; +}]); +;/** + * @ngdoc directive + * @name patternfly.wizard.directive:pfWizardReviewPage + * + * @description + * Directive for rendering a Wizard Review Page - should only be used within a wizard. + * + * @param {boolean} shown Value watched internally by the wizard review page to know when it is visible. + * @param {object} wizardData Sets the internal content of the review page to apply wizard data to the review templates. + * + */ +angular.module('patternfly.wizard').directive('pfWizardReviewPage', function () { + 'use strict'; + return { + restrict: 'A', + scope: { + shown: '=', + wizardData: "=" + }, + require: '^pf-wizard', + templateUrl: 'wizard/wizard-review-page.html', + controller: ["$scope", function ($scope) { + $scope.toggleShowReviewDetails = function (step) { + if (step.showReviewDetails === true) { + step.showReviewDetails = false; + } else { + step.showReviewDetails = true; + } + }; + $scope.getSubStepNumber = function (step, substep) { + return step.getStepDisplayNumber(substep); + }; + $scope.getReviewSubSteps = function (reviewStep) { + return reviewStep.getReviewSteps(); + }; + $scope.reviewSteps = []; + $scope.updateReviewSteps = function (wizard) { + $scope.reviewSteps = wizard.getReviewSteps(); + }; + }], + link: function ($scope, $element, $attrs, wizard) { + $scope.$watch('shown', function (value) { + if (value) { + $scope.updateReviewSteps(wizard); + } + }); + } + }; +}); +;/** + * @ngdoc directive + * @name patternfly.wizard.directive:pfWizardStep + * + * @description + * Directive for rendering a Wizard step. Each step can stand alone or have substeps. This directive can only be used as a child of pf-wizard. + * + * @param {string} stepTitle The step title displayed in the header and used for the review screen when displayed + * @param {string} stepId Sets the text identifier of the step + * @param {number} stepPriority This sets the priority of this wizard step relative to other wizard steps. They should be numbered sequentially in the order they should be viewed. + * @param {boolean} substeps Sets whether this step has substeps + * @param {boolean=} nextEnabled Sets whether the next button should be enabled when this step is first displayed + * @param {boolean=} prevEnabled Sets whether the back button should be enabled when this step is first displayed + * @param {string=} nextTooltip The text to display as a tooltip on the next button + * @param {string=} prevTooltip The text to display as a tooltip on the back button + * @param {boolean=} wzDisabled Disables the wizard when this page is shown + * @param {boolean} okToNavAway Sets whether or not it's ok for the user to leave this page + * @param {boolean} allowClickNav Sets whether the user can click on the numeric step indicators to navigate directly to this step + * @param {string=} description The step description (optional) + * @param {object} wizardData Data passed to the step that is shared by the entire wizard + * @param {function()=} onShow The function called when the wizard shows this step + * @param {boolean=} showReview Indicates whether review information should be displayed for this step when the review step is reached + * @param {boolean=} showReviewDetails Indicators whether the review information should be expanded by default when the review step is reached + * @param {string=} reviewTemplate The template that should be used for the review details screen + */ +angular.module('patternfly.wizard').directive('pfWizardStep', function () { + 'use strict'; + return { + restrict: 'A', + transclude: true, + scope: { + stepTitle: '@', + stepId: '@', + stepPriority: '@', + substeps: '=?', + nextEnabled: '=?', + prevEnabled: '=?', + nextTooltip: '=?', + prevTooltip: '=?', + disabled: '@?wzDisabled', + okToNavAway: '=?', + allowClickNav: '=?', + description: '@', + wizardData: '=', + onShow: '=?', + showReview: '@?', + showReviewDetails: '@?', + reviewTemplate: '@?' + }, + require: '^pf-wizard', + templateUrl: 'wizard/wizard-step.html', + controller: ["$scope", "$timeout", function ($scope, $timeout) { + var firstRun = true; + + var stepIdx = function (step) { + var idx = 0; + var res = -1; + angular.forEach($scope.getEnabledSteps(), function (currStep) { + if (currStep === step) { + res = idx; + } + idx++; + }); + return res; + }; + + var unselectAll = function () { + //traverse steps array and set each "selected" property to false + angular.forEach($scope.getEnabledSteps(), function (step) { + step.selected = false; + }); + //set selectedStep variable to null + $scope.selectedStep = null; + }; + + var watchSelectedStep = function () { + // Remove any previous watchers + if ($scope.nextStepEnabledWatcher) { + $scope.nextStepEnabledWatcher(); + } + if ($scope.nextStepTooltipWatcher) { + $scope.nextStepTooltipWatcher(); + } + if ($scope.prevStepEnabledWatcher) { + $scope.prevStepEnabledWatcher(); + } + if ($scope.prevStepTooltipWatcher) { + $scope.prevStepTooltipWatcher(); + } + + // Add watchers for the selected step + $scope.nextStepEnabledWatcher = $scope.$watch('selectedStep.nextEnabled', function (value) { + $scope.nextEnabled = value; + }); + $scope.nextStepTooltipWatcher = $scope.$watch('selectedStep.nextTooltip', function (value) { + $scope.nextTooltip = value; + }); + $scope.prevStepEnabledWatcher = $scope.$watch('selectedStep.prevEnabled', function (value) { + $scope.prevEnabled = value; + }); + $scope.prevStepTooltipWatcher = $scope.$watch('selectedStep.prevTooltip', function (value) { + $scope.prevTooltip = value; + }); + }; + + var stepByTitle = function (titleToFind) { + var foundStep = null; + angular.forEach($scope.getEnabledSteps(), function (step) { + if (step.stepTitle === titleToFind) { + foundStep = step; + } + }); + return foundStep; + }; + + $scope.steps = []; + $scope.context = {}; + this.context = $scope.context; + + if (angular.isUndefined($scope.nextEnabled)) { + $scope.nextEnabled = true; + } + if (angular.isUndefined($scope.prevEnabled)) { + $scope.prevEnabled = true; + } + if (angular.isUndefined($scope.showReview)) { + $scope.showReview = false; + } + if (angular.isUndefined($scope.showReviewDetails)) { + $scope.showReviewDetails = false; + } + if (angular.isUndefined($scope.stepPriority)) { + $scope.stepPriority = 999; + } else { + $scope.stepPriority = parseInt($scope.stepPriority); + } + if (angular.isUndefined($scope.okToNavAway)) { + $scope.okToNavAway = true; + } + if (angular.isUndefined($scope.allowClickNav)) { + $scope.allowClickNav = true; + } + + $scope.getEnabledSteps = function () { + return $scope.steps.filter(function (step) { + return step.disabled !== 'true'; + }); + }; + + $scope.getReviewSteps = function () { + var reviewSteps = $scope.getEnabledSteps().filter(function (step) { + return !angular.isUndefined(step.reviewTemplate); + }); + return reviewSteps; + }; + + $scope.resetNav = function () { + $scope.goTo($scope.getEnabledSteps()[0]); + }; + + $scope.currentStepNumber = function () { + //retreive current step number + return stepIdx($scope.selectedStep) + 1; + }; + + $scope.getStepNumber = function (step) { + return stepIdx(step) + 1; + }; + + $scope.isNextEnabled = function () { + var enabled = angular.isUndefined($scope.nextEnabled) || $scope.nextEnabled; + if ($scope.substeps) { + angular.forEach($scope.getEnabledSteps(), function (step) { + enabled = enabled && step.nextEnabled; + }); + } + return enabled; + }; + + $scope.isPrevEnabled = function () { + var enabled = angular.isUndefined($scope.prevEnabled) || $scope.prevEnabled; + if ($scope.substeps) { + angular.forEach($scope.getEnabledSteps(), function (step) { + enabled = enabled && step.prevEnabled; + }); + } + return enabled; + }; + + $scope.getStepDisplayNumber = function (step) { + return $scope.pageNumber + String.fromCharCode(65 + stepIdx(step)) + "."; + }; + + //watching changes to currentStep + $scope.$watch('currentStep', function (step) { + //checking to make sure currentStep is truthy value + if (!step) { + return; + } + + //setting stepTitle equal to current step title or default title + if ($scope.selectedStep && $scope.selectedStep.stepTitle !== $scope.currentStep) { + $scope.goTo(stepByTitle($scope.currentStep)); + } + }); + + //watching steps array length and editMode value, if edit module is undefined or null the nothing is done + //if edit mode is truthy, then all steps are marked as completed + $scope.$watch('[editMode, steps.length]', function () { + var editMode = $scope.editMode; + if (angular.isUndefined(editMode) || (editMode === null)) { + return; + } + + if (editMode) { + angular.forEach($scope.getEnabledSteps(), function (step) { + step.completed = true; + }); + } else { + angular.forEach($scope.getEnabledSteps(), function (step, stepIndex) { + if (stepIndex >= $scope.currentStepNumber() - 1) { + step.completed = false; + } + }); + } + }, true); + + $scope.prevStepsComplete = function (nextStep) { + var nextIdx = stepIdx(nextStep); + var complete = true; + angular.forEach($scope.getEnabledSteps(), function (step, stepIndex) { + if (stepIndex < nextIdx) { + complete = complete && step.nextEnabled; + } + }); + return complete; + }; + + $scope.goTo = function (step) { + if ($scope.wizard.isWizardDone() || !step.okToNavAway || step === $scope.selectedStep) { + return; + } + + if (firstRun || ($scope.getStepNumber(step) < $scope.currentStepNumber() && $scope.selectedStep.prevEnabled) || $scope.prevStepsComplete(step)) { + unselectAll(); + + $scope.selectedStep = step; + if (step) { + step.selected = true; + + if (angular.isFunction ($scope.selectedStep.onShow)) { + $scope.selectedStep.onShow(); + } + + watchSelectedStep(); + $scope.currentStep = step.stepTitle; + + //emit event upwards with data on goTo() invocation + if ($scope.selected) { + $scope.$emit('wizard:stepChanged', {step: step, index: stepIdx(step)}); + firstRun = false; + } + } + $scope.wizard.updateSubStepNumber (stepIdx($scope.selectedStep)); + } + }; + + $scope.stepClick = function (step) { + if (step.allowClickNav) { + $scope.goTo(step); + } + }; + + $scope.$watch('selected', function () { + if ($scope.selected && $scope.selectedStep) { + $scope.$emit('wizard:stepChanged', {step: $scope.selectedStep, index: stepIdx( $scope.selectedStep)}); + } + }); + + this.addStep = function (step) { + // Insert the step into step array + var insertBefore = _.find($scope.steps, function (nextStep) { + return nextStep.stepPriority > step.stepPriority; + }); + if (insertBefore) { + $scope.steps.splice($scope.steps.indexOf(insertBefore), 0, step); + } else { + $scope.steps.push(step); + } + }; + + this.currentStepTitle = function () { + return $scope.selectedStep.stepTitle; + }; + + this.currentStepDescription = function () { + return $scope.selectedStep.description; + }; + + this.currentStep = function () { + return $scope.selectedStep; + }; + + this.totalStepCount = function () { + return $scope.getEnabledSteps().length; + }; + + this.getEnabledSteps = function () { + return $scope.getEnabledSteps(); + }; + + //Access to current step number from outside + this.currentStepNumber = function () { + return $scope.currentStepNumber(); + }; + + // Allow access to any step + this.goTo = function (step) { + var enabledSteps = $scope.getEnabledSteps(); + var stepTo; + + if (angular.isNumber(step)) { + stepTo = enabledSteps[step]; + } else { + stepTo = stepByTitle(step); + } + + $scope.goTo(stepTo); + }; + + // Method used for next button within step + $scope.next = function (callback) { + var enabledSteps = $scope.getEnabledSteps(); + + // Save the step you were on when next() was invoked + var index = stepIdx($scope.selectedStep); + + // Check if callback is a function + if (angular.isFunction (callback)) { + if (callback($scope.selectedStep)) { + if (index === enabledSteps.length - 1) { + return false; + } + // Go to the next step + $scope.goTo(enabledSteps[index + 1]); + return true; + } + return true; + } + + // Completed property set on scope which is used to add class/remove class from progress bar + $scope.selectedStep.completed = true; + + // Check to see if this is the last step. If it is next behaves the same as finish() + if (index === enabledSteps.length - 1) { + return false; + } + // Go to the next step + $scope.goTo(enabledSteps[index + 1]); + return true; + }; + + $scope.previous = function (callback) { + var index = stepIdx($scope.selectedStep); + var goPrev = false; + + // Check if callback is a function + if (angular.isFunction (callback)) { + if (callback($scope.selectedStep)) { + if (index !== 0) { + $scope.goTo($scope.getEnabledSteps()[index - 1]); + goPrev = true; + } + } + } + + return goPrev; + }; + + if ($scope.substeps && !$scope.onShow) { + $scope.onShow = function () { + $timeout(function () { + if (!$scope.selectedStep) { + $scope.goTo($scope.getEnabledSteps()[0]); + } + }, 10); + }; + } + }], + link: function ($scope, $element, $attrs, wizard) { + $scope.$watch($attrs.ngShow, function (value) { + $scope.pageNumber = wizard.getStepNumber($scope); + }); + $scope.title = $scope.stepTitle; + $scope.contentStyle = wizard.contentStyle; + wizard.addStep($scope); + $scope.wizard = wizard; + } + }; +}); +;/** @ngdoc directive +* @name patternfly.wizard.directive:pfWizardSubstep +* +* @description +* Directive for rendering a Wizard substep. Each substep must be a child of a pf-wizardstep in a pf-wizard directive. +* +* @param {string} stepTitle The step title displayed in the header and used for the review screen when displayed +* @param {string} stepId Sets the text identifier of the step +* @param {number} stepPriority This sets the priority of this wizard step relative to other wizard steps. They should be numbered sequentially in the order they should be viewed. +* @param {boolean=} nextEnabled Sets whether the next button should be enabled when this step is first displayed +* @param {boolean=} prevEnabled Sets whether the back button should be enabled when this step is first displayed +* @param {boolean=} wzDisabled Disables the wizard when this page is shown +* @param {boolean} okToNavAway Sets whether or not it's ok for the user to leave this page +* @param {boolean=} allowClickNav Sets whether the user can click on the numeric step indicators to navigate directly to this step +* @param {string=} description The step description +* @param {object} wizardData Data passed to the step that is shared by the entire wizard +* @param {function()=} onShow The function called when the wizard shows this step +* @param {boolean=} showReviewDetails Indicators whether the review information should be expanded by default when the review step is reached +* @param {string=} reviewTemplate The template that should be used for the review details screen +*/ +angular.module('patternfly.wizard').directive('pfWizardSubstep', function () { + 'use strict'; + + return { + restrict: 'A', + transclude: true, + scope: { + stepTitle: '@', + stepId: '@', + stepPriority: '@', + nextEnabled: '=?', + prevEnabled: '=?', + okToNavAway: '=?', + allowClickNav: '=?', + disabled: '@?wzDisabled', + description: '@', + wizardData: '=', + onShow: '=?', + showReviewDetails: '@?', + reviewTemplate: '@?' + }, + require: '^pf-wizard-step', + templateUrl: 'wizard/wizard-substep.html', + controller: ["$scope", function ($scope) { + if (angular.isUndefined($scope.nextEnabled)) { + $scope.nextEnabled = true; + } + if (angular.isUndefined($scope.prevEnabled)) { + $scope.prevEnabled = true; + } + if (angular.isUndefined($scope.showReviewDetails)) { + $scope.showReviewDetails = false; + } + if (angular.isUndefined($scope.stepPriority)) { + $scope.stepPriority = 999; + } else { + $scope.stepPriority = parseInt($scope.stepPriority); + } + if (angular.isUndefined($scope.okToNavAway)) { + $scope.okToNavAway = true; + } + if (angular.isUndefined($scope.allowClickNav)) { + $scope.allowClickNav = true; + } + + $scope.isPrevEnabled = function () { + var enabled = angular.isUndefined($scope.prevEnabled) || $scope.prevEnabled; + if ($scope.substeps) { + angular.forEach($scope.getEnabledSteps(), function (step) { + enabled = enabled && step.prevEnabled; + }); + } + return enabled; + }; + + }], + link: function ($scope, $element, $attrs, step) { + $scope.title = $scope.stepTitle; + step.addStep($scope); + } + }; +}); +;angular.module('patternfly.card').run(['$templateCache', function($templateCache) { + 'use strict'; + + $templateCache.put('card/aggregate-status/aggregate-status-card.html', + "

      \"\" {{status.count}} {{status.title}} \"\" {{status.count}} {{status.title}}

      \"\"{{ notification.count }} \"\"{{ notification.count }}

      \"\" {{status.count}} {{status.title}} {{status.count}} {{status.title}}

      \"\"{{status.notification.count}} \"\"{{status.notification.count}}

      " + ); + + + $templateCache.put('card/basic/card-filter.html', + "
      " + ); + + + $templateCache.put('card/basic/card.html', + "

      {{headTitle}}

      {{subTitle}}
      " + ); + +}]); +;angular.module('patternfly.charts').run(['$templateCache', function($templateCache) { + 'use strict'; + + $templateCache.put('charts/donut/donut-pct-chart.html', + "
      " + ); + + + $templateCache.put('charts/empty-chart.html', + "
      No data available
      " + ); + + + $templateCache.put('charts/heatmap/heatmap-legend.html', + "
      • {{item.text}}
      " + ); + + + $templateCache.put('charts/heatmap/heatmap.html', + "

      {{chartTitle}}

      " + ); + + + $templateCache.put('charts/line/line-chart.html', + "
      " + ); + + + $templateCache.put('charts/sparkline/sparkline-chart.html', + "
      " + ); + + + $templateCache.put('charts/trends/trends-chart.html', + "
      {{config.title}} {{getLatestValue()}} {{config.units}} {{getPercentageValue() + '%'}} of {{chartData.total + ' ' + config.units}}
      {{config.timeFrame}}
      {{getLatestValue()}} {{config.units}} {{getPercentageValue() + '%'}} of {{chartData.total + ' ' + config.units}} {{config.title}}
      {{getPercentageValue() + '%'}}
      {{config.trendLabel}} {{getLatestValue()}} of {{chartData.total + ' ' + config.units}}
      " + ); + + + $templateCache.put('charts/utilization-bar/utilization-bar-chart.html', + "
      {{chartTitle}}
      {{chartData.used}} of {{chartData.total}} {{units}} Used {{chartData.percentageUsed}}% Used
      {{chartTitle}}
      {{chartData.used}} {{units}} Used {{chartData.percentageUsed}}% Used
      " + ); + + + $templateCache.put('charts/utilization-trend/utilization-trend-chart.html', + "

      {{config.title}}

      {{currentValue}}

      {{currentText}}
      of {{chartData.total}} {{config.units}}
      {{legendLeftText}} {{legendRightText}}
      " + ); + +}]); +;angular.module('patternfly.filters').run(['$templateCache', function($templateCache) { + 'use strict'; + + $templateCache.put('filters/filter-fields.html', + "
      " + ); + + + $templateCache.put('filters/filter-results.html', + "
      {{config.resultsCount}} Results

      0\">Active filters:

      • {{filter.title}}: {{filter.value}}

      0\">Clear All Filters

      " + ); + + + $templateCache.put('filters/filter.html', + "
      " + ); + +}]); +;angular.module('patternfly.form').run(['$templateCache', function($templateCache) { + 'use strict'; + + $templateCache.put('form/datepicker/datepicker.html', + "
      " + ); + + + $templateCache.put('form/datetimepicker/datetimepicker.html', + "
      " + ); + + + $templateCache.put('form/form-buttons/form-buttons.html', + "
      " + ); + + + $templateCache.put('form/form-group/form-group.html', + "
      • {{ message }}
      " + ); + +}]); +;angular.module('patternfly.modals').run(['$templateCache', function($templateCache) { + 'use strict'; + + $templateCache.put('modals/about-modal.html', + "" + ); + +}]); +;angular.module('patternfly.navigation').run(['$templateCache', function($templateCache) { + 'use strict'; + + $templateCache.put('navigation/vertical-navigation.html', + "
      " + ); + +}]); +;angular.module('patternfly.notification').run(['$templateCache', function($templateCache) { + 'use strict'; + + $templateCache.put('notification/inline-notification.html', + "
      {{pfNotificationHeader}} {{pfNotificationMessage}}
      " + ); + + + $templateCache.put('notification/notification-drawer.html', + "

      {{drawerTitle}}

      " + ); + + + $templateCache.put('notification/notification-list.html', + "
      0\">
      " + ); + + + $templateCache.put('notification/notification.html', + "
      {{pfNotificationHeader}} {{pfNotificationMessage}}
      " + ); + + + $templateCache.put('notification/toast-notification-list.html', + "
      0\">
      0)}}\" close-callback=handleClose action-title={{notification.actionTitle}} action-callback=notification.actionCallback menu-actions=notification.menuActions update-viewing=handleViewingChange data=notification>
      " + ); + + + $templateCache.put('notification/toast-notification.html', + "
      {{header}} {{message}} {{message}}
      " + ); + +}]); +;angular.module('patternfly.sort').run(['$templateCache', function($templateCache) { + 'use strict'; + + $templateCache.put('sort/sort.html', + "
      " + ); + +}]); +;angular.module('patternfly.toolbars').run(['$templateCache', function($templateCache) { + 'use strict'; + + $templateCache.put('toolbars/toolbar.html', + "
      0) ||\n" + + " (config.actionsConfig.moreActions && config.actionsConfig.moreActions.length > 0) ||\n" + + " config.actionsConfig.actionsInclude)\">
      " + ); + +}]); +;angular.module('patternfly.views').run(['$templateCache', function($templateCache) { + 'use strict'; + + $templateCache.put('views/cardview/card-view.html', + "
      " + ); + + + $templateCache.put('views/listview/list-view.html', + "
      0) || (menuActions && menuActions.length > 0)\">
      " + ); + +}]); +;angular.module('patternfly.wizard').run(['$templateCache', function($templateCache) { + 'use strict'; + + $templateCache.put('wizard/wizard-review-page.html', + "" + ); + + + $templateCache.put('wizard/wizard-step.html', + "
      " + ); + + + $templateCache.put('wizard/wizard-substep.html', + "" + ); + + + $templateCache.put('wizard/wizard.html', + "

      {{loadingWizardTitle}}

      {{loadingSecondaryInformation}}

      " + ); + +}]); diff --git a/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/angular-patternfly.min.js b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/angular-patternfly.min.js new file mode 100644 index 00000000..fd366237 --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/angular-patternfly.min.js @@ -0,0 +1,4 @@ +function mergeDeep(dst){"use strict";return angular.forEach(arguments,function(obj){obj!==dst&&angular.forEach(obj,function(value,key){dst[key]&&dst[key].constructor&&dst[key].constructor===Object?mergeDeep(dst[key],value):dst[key]=value})}),dst}angular.module("patternfly.card",[]),angular.module("patternfly.charts",["patternfly.utils","ui.bootstrap","ngSanitize"]),angular.module("patternfly.filters",["patternfly.select","ui.bootstrap"]),angular.module("patternfly.form",[]),angular.module("patternfly.modals",["ui.bootstrap.modal","ui.bootstrap.tpls"]),angular.module("patternfly.navigation",["ui.bootstrap"]),angular.module("patternfly.notification",["patternfly.utils"]),angular.module("patternfly",["patternfly.autofocus","patternfly.card","patternfly.filters","patternfly.form","patternfly.modals","patternfly.navigation","patternfly.notification","patternfly.select","patternfly.sort","patternfly.toolbars","patternfly.utils","patternfly.validation","patternfly.views","patternfly.wizard"]),angular.module("patternfly.sort",["ui.bootstrap"]),angular.module("patternfly.toolbars",["patternfly.utils","patternfly.filters","patternfly.sort","patternfly.views"]),angular.module("patternfly.utils",["ui.bootstrap"]),angular.module("patternfly.views",["patternfly.utils","patternfly.filters","patternfly.sort","patternfly.charts"]),angular.module("patternfly.wizard",["ui.bootstrap.modal","ui.bootstrap.tpls","patternfly.form"]),angular.module("patternfly.autofocus",[]).directive("pfFocused",["$timeout",function($timeout){"use strict";return{restrict:"A",link:function(scope,element,attrs){scope.$watch(attrs.pfFocused,function(newValue){$timeout(function(){newValue&&(element[0].focus(),element[0].select&&element[0].select())})})}}}]),angular.module("patternfly.card").directive("pfAggregateStatusCard",function(){"use strict";return{restrict:"A",scope:{status:"=",showTopBorder:"@?",altLayout:"@?",layout:"@?"},templateUrl:"card/aggregate-status/aggregate-status-card.html",link:function(scope){scope.shouldShowTopBorder="true"===scope.showTopBorder,scope.isAltLayout="true"===scope.altLayout||"tall"===scope.layout,scope.isMiniLayout="mini"===scope.layout}}}),angular.module("patternfly.card").directive("pfCard",function(){"use strict";return{restrict:"A",transclude:!0,templateUrl:"card/basic/card.html",scope:{headTitle:"@",subTitle:"@?",showTopBorder:"@?",showTitlesSeparator:"@?",footer:"=?",filter:"=?"},controller:["$scope",function($scope){$scope.filter&&!$scope.currentFilter&&($scope.filter.defaultFilter?$scope.currentFilter=$scope.filter.filters[$scope.filter.defaultFilter]:$scope.currentFilter=$scope.filter.filters[0]),$scope.footerCallBackFn=function(){$scope.footerCallBackResult=$scope.footer.callBackFn()},$scope.filterCallBackFn=function(f){$scope.currentFilter=f,$scope.filter.callBackFn&&($scope.filterCallBackResult=$scope.filter.callBackFn(f))},$scope.showHeader=function(){return $scope.headTitle||$scope.showFilterInHeader()},$scope.showFilterInHeader=function(){return $scope.filter&&$scope.filter.filters&&$scope.filter.position&&"header"===$scope.filter.position},$scope.showFilterInFooter=function(){return $scope.filter&&$scope.filter.filters&&(!$scope.filter.position||"footer"===$scope.filter.position)}}],link:function(scope){scope.shouldShowTitlesSeparator=!scope.showTitlesSeparator||"true"===scope.showTitlesSeparator}}}),function(){"use strict";var patternflyDefaults=$().c3ChartDefaults();angular.module("patternfly.charts").constant("c3ChartDefaults",{getDefaultColors:patternflyDefaults.getDefaultColors,getDefaultDonut:patternflyDefaults.getDefaultDonut,getDefaultDonutSize:patternflyDefaults.getDefaultDonutSize,getDefaultDonutColor:patternflyDefaults.getDefaultDonutColors,getDefaultDonutLegend:patternflyDefaults.getDefaultDonutLegend,getDefaultDonutConfig:patternflyDefaults.getDefaultDonutConfig,getDefaultSparklineArea:patternflyDefaults.getDefaultSparklineArea,getDefaultSparklineSize:patternflyDefaults.getDefaultSparklineSize,getDefaultSparklineAxis:patternflyDefaults.getDefaultSparklineAxis,getDefaultSparklineColor:patternflyDefaults.getDefaultColors,getDefaultSparklineLegend:patternflyDefaults.getDefaultSparklineLegend,getDefaultSparklinePoint:patternflyDefaults.getDefaultSparklinePoint,getDefaultSparklineTooltip:patternflyDefaults.getDefaultSparklineTooltip,getDefaultSparklineConfig:patternflyDefaults.getDefaultSparklineConfig,getDefaultLineConfig:patternflyDefaults.getDefaultLineConfig})}(),function(){"use strict";angular.module("patternfly.charts").directive("pfC3Chart",["$timeout",function($timeout){return{restrict:"A",scope:{config:"=",getChartCallback:"="},template:'
      ',replace:!0,link:function(scope,element,attrs){scope.$watch("config",function(){$timeout(function(){var chart,chartData=scope.config;chartData&&(chartData.bindto="#"+attrs.id,chart=c3.generate(chartData),scope.getChartCallback&&scope.getChartCallback(chart))})},!0)}}}])}(),angular.module("patternfly.charts").directive("pfDonutPctChart",["pfUtils","$timeout",function(pfUtils,$timeout){"use strict";return{restrict:"A",scope:{config:"=",data:"=",chartHeight:"=?",centerLabel:"=?"},replace:!0,templateUrl:"charts/donut/donut-pct-chart.html",controller:["$scope",function($scope){var donutTooltip;$scope.donutChartId="donutChart",$scope.config.chartId&&($scope.donutChartId=$scope.config.chartId+$scope.donutChartId),$scope.updateAvailable=function(){$scope.data.available=$scope.data.total-$scope.data.used},void 0===$scope.data.available&&$scope.updateAvailable(),$scope.getStatusColor=function(used,thresholds){var color=pfUtils.colorPalette.blue;return thresholds&&(color=pfUtils.colorPalette.green,used>=thresholds.error?color=pfUtils.colorPalette.red:used>=thresholds.warning&&(color=pfUtils.colorPalette.orange)),color},$scope.statusDonutColor=function(scope){var color,percentUsed;return color={pattern:[]},percentUsed=scope.data.used/scope.data.total*100,color.pattern[0]=$scope.getStatusColor(percentUsed,scope.config.thresholds),color.pattern[1]=pfUtils.colorPalette.black300,color},donutTooltip=function(scope){return{contents:function(d){var tooltipHtml;return tooltipHtml=scope.config.tooltipFn?''+scope.config.tooltipFn(d)+"":''+Math.round(100*d[0].ratio)+"% "+$scope.config.units+" "+d[0].name+""}}},$scope.getDonutData=function(scope){return{columns:[["Used",scope.data.used],["Available",scope.data.available]],type:"donut",donut:{label:{show:!1}},groups:[["used","available"]],order:null}},$scope.getCenterLabelText=function(){var centerLabelText;return centerLabelText={bigText:$scope.data.used,smText:$scope.config.units+" Used"},$scope.config.centerLabelFn?(centerLabelText.bigText=$scope.config.centerLabelFn(),centerLabelText.smText=""):"none"===$scope.centerLabel?(centerLabelText.bigText="",centerLabelText.smText=""):"available"===$scope.centerLabel?(centerLabelText.bigText=$scope.data.available,centerLabelText.smText=$scope.config.units+" Available"):"percent"===$scope.centerLabel&&(centerLabelText.bigText=Math.round($scope.data.used/$scope.data.total*100)+"%",centerLabelText.smText="of "+$scope.data.total+" "+$scope.config.units),centerLabelText},$scope.updateAll=function(scope){$scope.updateAvailable(),$scope.config.data=pfUtils.merge($scope.config.data,$scope.getDonutData($scope)),$scope.config.color=$scope.statusDonutColor($scope),$scope.config.tooltip=donutTooltip(scope),$scope.config.data.onclick=$scope.config.onClickFn},$scope.config=pfUtils.merge($().c3ChartDefaults().getDefaultDonutConfig(),$scope.config),$scope.updateAll($scope)}],link:function(scope,element){var setupDonutChartTitle=function(){$timeout(function(){var donutChartTitle,centerLabelText;donutChartTitle=d3.select(element[0]).select("text.c3-chart-arcs-title"),donutChartTitle&&(centerLabelText=scope.getCenterLabelText(),donutChartTitle.selectAll("*").remove(),centerLabelText.bigText&&!centerLabelText.smText?donutChartTitle.text(centerLabelText.bigText):(donutChartTitle.insert("tspan").text(centerLabelText.bigText).classed("donut-title-big-pf",!0).attr("dy",0).attr("x",0),donutChartTitle.insert("tspan").text(centerLabelText.smText).classed("donut-title-small-pf",!0).attr("dy",20).attr("x",0)))},300)};scope.$watch("config",function(){scope.updateAll(scope),setupDonutChartTitle()},!0),scope.$watch("chartHeight",function(){scope.chartHeight&&(scope.config.size.height=scope.chartHeight)}),scope.$watch("data",function(){scope.updateAll(scope),setupDonutChartTitle()},!0),scope.$watch("centerLabel",function(){setupDonutChartTitle()})}}}]),angular.module("patternfly.charts").directive("pfEmptyChart",function(){"use strict";return{restrict:"A",scope:{chartHeight:"=?"},replace:!0,templateUrl:"charts/empty-chart.html",controller:["$scope",function($scope){$scope.setSizeStyles=function(){var height=$scope.chartHeight||40,topPadding=Math.min(Math.round((height-40)/2),20);$scope.sizeStyles={height:height+"px","padding-top":topPadding+"px"}},$scope.setSizeStyles()}],link:function(scope){scope.$watch("chartHeight",function(){scope.setSizeStyles()})}}}),angular.module("patternfly.charts").directive("pfHeatmapLegend",function(){"use strict";return{restrict:"A",scope:{legend:"=?",legendColors:"=?"},templateUrl:"charts/heatmap/heatmap-legend.html",controller:["$scope",function($scope){var heatmapColorPatternDefaults=["#d4f0fa","#F9D67A","#EC7A08","#CE0000"],legendLabelDefaults=["< 70%","70-80%","80-90%","> 90%"];$scope.legendColors||($scope.legendColors=heatmapColorPatternDefaults),$scope.legend||($scope.legend=legendLabelDefaults)}],link:function($scope){var index,items=[];for(index=$scope.legend.length-1;index>=0;index--)items.push({text:$scope.legend[index],color:$scope.legendColors[index]});$scope.legendItems=items}}}),angular.module("patternfly.charts").directive("pfHeatmap",["$compile","$window",function($compile,$window){"use strict";return{restrict:"A",scope:{data:"=",chartDataAvailable:"=?",height:"=?",chartTitle:"=?",showLegend:"=?",legendLabels:"=?",maxBlockSize:"@",minBlockSize:"@",blockPadding:"@",thresholds:"=?",heatmapColorPattern:"=?",clickAction:"=?",rangeOnHover:"=?",rangeHoverSize:"@",rangeTooltips:"=?"},templateUrl:"charts/heatmap/heatmap.html",controller:["$scope",function($scope){var thresholdDefaults=[.7,.8,.9],heatmapColorPatternDefaults=["#d4f0fa","#F9D67A","#EC7A08","#CE0000"],legendLabelDefaults=["< 70%","70-80%","80-90%","> 90%"],rangeTooltipDefaults=["< 70%","70-80%","80-90%","> 90%"],heightDefault=200;void 0===$scope.maxBlockSize||isNaN($scope.maxBlockSize)?$scope.maxSize=64:($scope.maxSize=parseInt($scope.maxBlockSize),$scope.maxSize<5?$scope.maxSize=5:$scope.maxSize>50&&($scope.maxSize=50)),void 0===$scope.minBlockSize||isNaN($scope.minBlockSize)?$scope.minSize=2:$scope.minSize=parseInt($scope.minBlockSize),void 0===$scope.blockPadding||isNaN($scope.blockPadding)?$scope.padding=2:$scope.padding=parseInt($scope.blockPadding),void 0===$scope.rangeHoverSize||isNaN($scope.rangeHoverSize)?$scope.rangeHoverSize=15:$scope.rangeHoverSize=parseInt($scope.rangeHoverSize),$scope.rangeOnHover=void 0===$scope.rangeOnHover||$scope.rangeOnHover?!0:!1,$scope.rangeTooltips||($scope.rangeTooltips=rangeTooltipDefaults),$scope.thresholds||($scope.thresholds=thresholdDefaults),$scope.heatmapColorPattern||($scope.heatmapColorPattern=heatmapColorPatternDefaults),$scope.legendLabels||($scope.legendLabels=legendLabelDefaults),$scope.height=$scope.height||heightDefault,$scope.showLegend=$scope.showLegend||void 0===$scope.showLegend,$scope.loadingDone=!1}],link:function(scope,element,attrs){var containerWidth,containerHeight,blockSize,numberOfRows,thisComponent=element[0].querySelector(".heatmap-pf-svg"),setStyles=function(){scope.containerStyles={height:scope.height+"px",display:scope.chartDataAvailable===!1?"none":"block"}},setSizes=function(){var parentContainer=element[0].querySelector(".heatmap-container");containerWidth=parentContainer.clientWidth,containerHeight=parentContainer.clientHeight,blockSize=determineBlockSize(),blockSize-scope.padding>scope.maxSize?(blockSize=scope.padding+scope.maxSize,numberOfRows=Math.ceil(Math.sqrt(scope.data.length)),(blockSize*numberOfRows>containerWidth||blockSize*numberOfRows>containerHeight)&&(numberOfRows=0===blockSize?0:Math.floor(containerHeight/blockSize))):blockSize-scope.paddingcontainerWidth||blockSize*numberOfRows>containerHeight)&&(numberOfRows=0===blockSize?0:Math.floor(containerHeight/blockSize))):numberOfRows=0===blockSize?0:Math.floor(containerHeight/blockSize)},determineBlockSize=function(){var sx,sy,x=containerWidth,y=containerHeight,n=scope.data?scope.data.length:0,px=Math.ceil(Math.sqrt(n*x/y)),py=Math.ceil(Math.sqrt(n*y/x));return sx=Math.floor(px*y/x)*px '+tipRows+"
      "},$scope.sparklineTooltip=function(){return{contents:function(d){var tipRows,percentUsed=0;if($scope.config.tooltipFn)tipRows=$scope.config.tooltipFn(d);else switch($scope.config.tooltipType){case"usagePerDay":$scope.chartData.dataAvailable!==!1&&$scope.chartData.total>0&&(percentUsed=Math.round(d[0].value/$scope.chartData.total*100)),tipRows=' '+d[0].x.toLocaleDateString()+' '+percentUsed+'%: '+d[0].value+" "+($scope.config.units?$scope.config.units+" ":"")+d[0].name+"";break;case"valuePerDay":tipRows=' '+d[0].x.toLocaleDateString()+' '+d[0].value+" "+d[0].name+"";break;case"percentage":percentUsed=Math.round(d[0].value/$scope.chartData.total*100),tipRows=' '+percentUsed+"%";break;default:tipRows=$().c3ChartDefaults().getDefaultSparklineTooltip().contents(d)}return $scope.getTooltipTableHTML(tipRows)},position:function(data,width,height,element){var center,top,chartBox,graphOffsetX,x;try{return center=parseInt(element.getAttribute("x")),top=parseInt(element.getAttribute("y")),chartBox=document.querySelector("#"+$scope.sparklineChartId).getBoundingClientRect(),graphOffsetX=document.querySelector("#"+$scope.sparklineChartId+" g.c3-axis-y").getBoundingClientRect().right,x=Math.max(0,center+graphOffsetX-chartBox.left-Math.floor(width/2)),{top:top-height,left:Math.min(x,chartBox.width-width)}}catch(e){}}}},void 0===$scope.showXAxis&&($scope.showXAxis=void 0!==$scope.config.showAxis&&$scope.config.showAxis),void 0===$scope.showYAxis&&($scope.showYAxis=void 0!==$scope.config.showAxis&&$scope.config.showAxis),$scope.defaultConfig=$().c3ChartDefaults().getDefaultSparklineConfig(),$scope.defaultConfig.axis={x:{show:$scope.showXAxis===!0,type:"timeseries",tick:{format:function(){return""}}},y:{show:$scope.showYAxis===!0,tick:{format:function(){return""}}}},$scope.defaultConfig.tooltip=$scope.sparklineTooltip(),$scope.chartHeight&&($scope.defaultConfig.size.height=$scope.chartHeight),$scope.defaultConfig.units="",$scope.config.data=pfUtils.merge($scope.config.data,$scope.getSparklineData($scope.chartData)),$scope.chartConfig=pfUtils.merge($scope.defaultConfig,$scope.config)}],link:function(scope){scope.$watch("config",function(){scope.config.data=pfUtils.merge(scope.config.data,scope.getSparklineData(scope.chartData)),scope.chartConfig=pfUtils.merge(scope.defaultConfig,scope.config)},!0),scope.$watch("chartHeight",function(){scope.chartHeight&&(scope.chartConfig.size.height=scope.chartHeight)}),scope.$watch("showXAxis",function(){scope.chartConfig.axis.x.show=scope.showXAxis===!0}),scope.$watch("showYAxis",function(){scope.chartConfig.axis.y.show=scope.showYAxis===!0}),scope.$watch("chartData",function(){scope.chartConfig.data=pfUtils.merge(scope.chartConfig.data,scope.getSparklineData(scope.chartData))},!0)}}}]),angular.module("patternfly.charts").directive("pfTrendsChart",function(){"use strict";return{restrict:"A",scope:{config:"=",chartData:"=",chartHeight:"=?",showXAxis:"=?",showYAxis:"=?"},replace:!0,templateUrl:"charts/trends/trends-chart.html",controller:["$scope",function($scope){var SMALL=30,LARGE=60;$scope.getPercentageValue=function(){var pctValue=0;return $scope.chartData.dataAvailable!==!1&&$scope.chartData.total>0&&(pctValue=Math.round($scope.getLatestValue()/$scope.chartData.total*100)),pctValue},$scope.getLatestValue=function(){var latestValue=0;return $scope.chartData.yData&&$scope.chartData.yData.length>0&&(latestValue=$scope.chartData.yData[$scope.chartData.yData.length-1]),latestValue},$scope.getChartHeight=function(){var retValue=LARGE;return $scope.chartHeight?retValue=$scope.chartHeight:"small"===$scope.config.layout&&(retValue=SMALL),retValue}}],link:function(scope){scope.$watch("config",function(){scope.showLargeCardLayout=!scope.config.layout||"large"===scope.config.layout,scope.showSmallCardLayout="small"===scope.config.layout,scope.showActualValue=!scope.config.valueType||"actual"===scope.config.valueType,scope.showPercentageValue="percentage"===scope.config.valueType},!0)}}}),angular.module("patternfly.charts").directive("pfUtilizationBarChart",["$timeout",function($timeout){"use strict";return{restrict:"A",scope:{chartData:"=",chartTitle:"=",chartFooter:"=",units:"=",thresholdError:"=?",thresholdWarning:"=?",footerLabelFormat:"@?",layout:"=?"},templateUrl:"charts/utilization-bar/utilization-bar-chart.html",link:function(scope){scope.$watch("chartData",function(newVal,oldVal){"undefined"!=typeof newVal&&(scope.chartData.percentageUsed=Math.round(100*(scope.chartData.used/scope.chartData.total)),(scope.thresholdError||scope.thresholdWarning)&&(scope.isError=scope.chartData.percentageUsed>=scope.thresholdError,scope.isWarn=scope.chartData.percentageUsed>=scope.thresholdWarning&&scope.chartData.percentageUsedcharsMaxLimit&&($scope.ngModel=$scope.ngModel.substring(0,charsMaxLimit),charsLength=$scope.ngModel.length,remainingChars=charsMaxLimit-charsLength),$scope.remainingChars=remainingChars,$scope.remainingCharsWarning=charsWarnRemaining>=remainingChars?!0:!1,countRemainingFld.text(remainingChars),countRemainingFld.toggleClass("chars-warn-remaining-pf",charsWarnRemaining>=remainingChars),0>remainingChars?$scope.$emit("overCharsMaxLimit",$attributes.id):$scope.$emit("underCharsMaxLimit",$attributes.id)};$scope.$watch("ngModel",function(){checkCharactersRemaining()}),$element.bind("keypress",function(event){blockInputAtMaxLimit&&$element.val().length>=charsMaxLimit&&8!==event.keyCode&&event.preventDefault()})}}}]),angular.module("patternfly.modals").directive("pfAboutModalTransclude",["$parse",function($parse){"use strict";return{link:function(scope,element,attrs){element.append($parse(attrs.pfAboutModalTransclude)(scope))}}}]).directive("pfAboutModal",function(){"use strict";return{restrict:"A",scope:{additionalInfo:"=?",copyright:"=?",close:"&onClose",imgAlt:"=?",imgSrc:"=?",isOpen:"=?",productInfo:"=",title:"=?"},templateUrl:"modals/about-modal.html",transclude:!0,controller:["$scope","$uibModal","$transclude",function($scope,$uibModal,$transclude){void 0===$scope.isOpen&&($scope.isOpen=!1),$scope.openModal=function(){$uibModal.open({controller:["$scope","$uibModalInstance","content",function($scope,$uibModalInstance,content){$scope.template=content,$scope.close=function(){$uibModalInstance.close()},$scope.$watch(function(){return $scope.isOpen},function(newValue){newValue===!1&&$uibModalInstance.close()})}],resolve:{content:function(){var transcludedContent;return $transclude(function(clone){transcludedContent=clone; +}),transcludedContent}},scope:$scope,templateUrl:"about-modal-template.html"}).result.then(function(){$scope.close()},function(){$scope.close()})}}],link:function(scope,element,attrs){var isOpenListener=scope.$watch("isOpen",function(newVal,oldVal){newVal===!0&&scope.openModal()});scope.$on("$destroy",isOpenListener)}}}),angular.module("patternfly.navigation").directive("pfVerticalNavigation",["$location","$rootScope","$window","$document","$timeout","$injector",function(location,rootScope,$window,$document,$timeout,$injector){"use strict";var $state;return $injector.has("$state")&&($state=$injector.get("$state")),{restrict:"A",scope:{brandSrc:"@",brandAlt:"@",showBadges:"@",persistentSecondary:"@",pinnableMenus:"@",hiddenIcons:"@",items:"=",navigateCallback:"=?",itemClickCallback:"=?",updateActiveItemsOnClick:"@",ignoreMobile:"@"},replace:!0,templateUrl:"navigation/vertical-navigation.html",transclude:!0,controller:["$scope",function($scope){var routeChangeListener;$scope.showBadges="true"===$scope.showBadges,$scope.persistentSecondary="true"===$scope.persistentSecondary,$scope.pinnableMenus="true"===$scope.pinnableMenus,$scope.hiddenIcons="true"===$scope.hiddenIcons,$scope.updateActiveItemsOnClick="true"===$scope.updateActiveItemsOnClick,$scope.ignoreMobile="true"===$scope.ignoreMobile,$scope.activeSecondary=!1,$scope.clearActiveItems=function(){$scope.items.forEach(function(item){item.isActive=!1,item.children&&item.children.forEach(function(secondary){secondary.isActive=!1,secondary.children&&secondary.children.forEach(function(tertiary){tertiary.isActive=!1})})})},$scope.setActiveItems=function(){var updatedRoute="#"+location.path();$scope.items.forEach(function(topLevel){updatedRoute.indexOf(topLevel.href)>-1&&(topLevel.isActive=!0),topLevel.children&&topLevel.children.forEach(function(secondLevel){updatedRoute.indexOf(secondLevel.href)>-1&&(secondLevel.isActive=!0,topLevel.isActive=!0),secondLevel.children&&secondLevel.children.forEach(function(thirdLevel){updatedRoute.indexOf(thirdLevel.href)>-1&&(thirdLevel.isActive=!0,secondLevel.isActive=!0,topLevel.isActive=!0)})})})},$scope.updateActiveItemsOnClick||(routeChangeListener=rootScope.$on("$routeChangeSuccess",function(event,next,current){$scope.clearActiveItems(),$scope.setActiveItems()}),$scope.$on("$destroy",routeChangeListener))}],link:function($scope){var breakpoints={tablet:768,desktop:1200},getBodyContentElement=function(){return angular.element(document.querySelector(".container-pf-nav-pf-vertical"))},explicitCollapse=!1,hoverDelay=500,hideDelay=hoverDelay+200,initBodyElement=function(){var bodyContentElement=getBodyContentElement();$scope.showBadges&&bodyContentElement.addClass("nav-pf-vertical-with-badges"),$scope.persistentSecondary&&bodyContentElement.addClass("nav-pf-persistent-secondary"),$scope.hiddenIcons&&bodyContentElement.addClass("hidden-icons-pf")},updateMobileMenu=function(selected,secondaryItem){$scope.items.forEach(function(item){item.isMobileItem=!1,item.children&&item.children.forEach(function(nextSecondary){nextSecondary.isMobileItem=!1})}),selected?(selected.isMobileItem=!0,secondaryItem?(secondaryItem.isMobileItem=!0,$scope.showMobileSecondary=!1,$scope.showMobileTertiary=!0):($scope.showMobileSecondary=!0,$scope.showMobileTertiary=!1)):($scope.showMobileSecondary=!1,$scope.showMobileTertiary=!1)},checkNavState=function(){var width=$window.innerWidth,bodyContentElement=getBodyContentElement();!$scope.ignoreMobile&&width0&&item.children.forEach(function(secondaryItem){secondaryItem.isHover&&(hover=!0)})}),hover},updateSecondaryCollapsedState=function(setCollapsed,collapsedItem){var bodyContentElement=getBodyContentElement();collapsedItem&&(collapsedItem.secondaryCollapsed=setCollapsed),setCollapsed?($scope.collapsedSecondaryNav=!0,bodyContentElement.addClass("collapsed-secondary-nav-pf")):($scope.items&&$scope.items.forEach(function(item){item.secondaryCollasped=!1}),$scope.collapsedSecondaryNav=!1,bodyContentElement.removeClass("collapsed-secondary-nav-pf"))},updateTertiaryCollapsedState=function(setCollapsed,collapsedItem){var bodyContentElement=getBodyContentElement();collapsedItem&&(collapsedItem.tertiaryCollapsed=setCollapsed),setCollapsed?($scope.collapsedTertiaryNav=!0,bodyContentElement.addClass("collapsed-tertiary-nav-pf"),updateSecondaryCollapsedState(!1)):($scope.items&&$scope.items.forEach(function(item){item.children&&item.children.length>0&&item.children.forEach(function(secondaryItem){secondaryItem.tertiaryCollasped=!1})}),$scope.collapsedTertiaryNav=!1,bodyContentElement.removeClass("collapsed-tertiary-nav-pf"))};$scope.showMobileNav=!1,$scope.showMobileSecondary=!1,$scope.showMobileTertiary=!1,$scope.hoverSecondaryNav=!1,$scope.hoverTertiaryNav=!1,$scope.collapsedSecondaryNav=!1,$scope.collapsedTertiaryNav=!1,$scope.navCollapsed=!1,$scope.forceHidden=!1,$scope.handleNavBarToggleClick=function(){$scope.inMobileState?$scope.showMobileNav?$scope.showMobileNav=!1:(updateMobileMenu(),$scope.showMobileNav=!0):$scope.navCollapsed?expandMenu():collapseMenu()},$scope.handlePrimaryClick=function(item,event){$scope.inMobileState?item.children&&item.children.length>0?updateMobileMenu(item):(updateMobileMenu(),navigateToItem(item)):navigateToItem(item)},$scope.handleSecondaryClick=function(primary,secondary,event){$scope.inMobileState?secondary.children&&secondary.children.length>0?updateMobileMenu(primary,secondary):(updateMobileMenu(),navigateToItem(secondary)):navigateToItem(secondary)},$scope.handleTertiaryClick=function(primary,secondary,tertiary,event){$scope.inMobileState&&updateMobileMenu(),navigateToItem(tertiary)},$scope.handlePrimaryHover=function(item){item.children&&item.children.length>0&&($scope.inMobileState||(void 0!==item.navUnHoverTimeout?($timeout.cancel(item.navUnHoverTimeout),item.navUnHoverTimeout=void 0):void 0!==$scope.navHoverTimeout||item.isHover||(item.navHoverTimeout=$timeout(function(){$scope.hoverSecondaryNav=!0,item.isHover=!0,item.navHoverTimeout=void 0},hoverDelay))))},$scope.handlePrimaryUnHover=function(item){item.children&&item.children.length>0&&(void 0!==item.navHoverTimeout?($timeout.cancel(item.navHoverTimeout),item.navHoverTimeout=void 0):void 0===item.navUnHoverTimeout&&item.isHover&&(item.navUnHoverTimeout=$timeout(function(){item.isHover=!1,primaryHover()||($scope.hoverSecondaryNav=!1),item.navUnHoverTimeout=void 0},hideDelay)))},$scope.handleSecondaryHover=function(item){item.children&&item.children.length>0&&($scope.inMobileState||(void 0!==item.navUnHoverTimeout?($timeout.cancel(item.navUnHoverTimeout),item.navUnHoverTimeout=void 0):void 0===$scope.navHoverTimeout&&(item.navHoverTimeout=$timeout(function(){$scope.hoverTertiaryNav=!0,item.isHover=!0,item.navHoverTimeout=void 0},hoverDelay))))},$scope.handleSecondaryUnHover=function(item){item.children&&item.children.length>0&&(void 0!==item.navHoverTimeout?($timeout.cancel(item.navHoverTimeout),item.navHoverTimeout=void 0):void 0===item.navUnHoverTimeout&&(item.navUnHoverTimeout=$timeout(function(){item.isHover=!1,secondaryHover()||($scope.hoverTertiaryNav=!1),item.navUnHoverTimeout=void 0},hideDelay)))},$scope.collapseSecondaryNav=function(item,event){$scope.inMobileState?updateMobileMenu():item.secondaryCollapsed?(updateSecondaryCollapsedState(!1,item),forceHideSecondaryMenu()):updateSecondaryCollapsedState(!0,item),$scope.hoverSecondaryNav=!1,event.stopImmediatePropagation()},$scope.collapseTertiaryNav=function(item,event){$scope.inMobileState?$scope.items.forEach(function(primaryItem){primaryItem.children&&primaryItem.children.forEach(function(secondaryItem){secondaryItem===item&&updateMobileMenu(primaryItem)})}):item.tertiaryCollapsed?(updateTertiaryCollapsedState(!1,item),forceHideSecondaryMenu()):updateTertiaryCollapsedState(!0,item),$scope.hoverSecondaryNav=!1,$scope.hoverTertiaryNav=!1,event.stopImmediatePropagation()},initBodyElement(),checkNavState(),angular.element($window).bind("resize",function(){checkNavState(),$timeout(function(){try{$scope.$apply()}catch(e){}})})}}}]),angular.module("patternfly.notification").directive("pfInlineNotification",function(){"use strict";return{scope:{pfNotificationType:"=",pfNotificationMessage:"=",pfNotificationHeader:"=",pfNotificationPersistent:"=",pfNotificationIndex:"="},restrict:"E",templateUrl:"notification/inline-notification.html"}}),angular.module("patternfly.notification").directive("pfNotificationDrawer",["$window","$timeout",function($window,$timeout){"use strict";return{restrict:"A",scope:{drawerHidden:"=?",allowExpand:"=?",drawerExpanded:"=?",drawerTitle:"@",notificationGroups:"=",actionButtonTitle:"@",actionButtonCallback:"=?",titleInclude:"@",headingInclude:"@",subheadingInclude:"@",notificationBodyInclude:"@",notificationFooterInclude:"@",customScope:"=?"},templateUrl:"notification/notification-drawer.html",controller:["$scope",function($scope){(!$scope.allowExpand||angular.isUndefined($scope.drawerExpanded))&&($scope.drawerExpanded=!1)}],link:function(scope,element){scope.$watch("notificationGroups",function(){var openFound=!1;scope.notificationGroups.forEach(function(group){group.open&&(openFound?group.open=!1:openFound=!0)})}),scope.$watch("drawerHidden",function(){$timeout(function(){angular.element($window).triggerHandler("resize")},100)}),scope.toggleCollapse=function(selectedGroup){selectedGroup.open?selectedGroup.open=!1:(scope.notificationGroups.forEach(function(group){group.open=!1}),selectedGroup.open=!0)},scope.toggleExpandDrawer=function(){scope.drawerExpanded=!scope.drawerExpanded},scope.groupHeight&&element.find(".panel-group").css("height",scope.groupHeight),scope.groupClass&&element.find(".panel-group").addClass(scope.groupClass)}}}]),angular.module("patternfly.notification").provider("Notifications",function(){"use strict";this.delay=8e3,this.verbose=!0,this.notifications={},this.persist={error:!0,httpError:!0},this.setDelay=function(delay){return this.delay=delay,this},this.setVerbose=function(verbose){return this.verbose=verbose,this},this.setPersist=function(persist){this.persist=persist},this.$get=["$rootScope","$timeout","$log",function($rootScope,$timeout,$log){function createNotifyMethod(mode){return function(message,header,persistent,closeCallback,actionTitle,actionCallback,menuActions){angular.isUndefined(header)&&(header=modes[mode].header),angular.isUndefined(persistent)&&(persistent=persist[mode]),notifications.message(modes[mode].type,header,message,persistent,closeCallback,actionTitle,actionCallback,menuActions),verbose&&$log[modes[mode].log](message)}}var delay=this.delay,notifications=this.notifications,verbose=this.verbose,persist=this.persist,modes={info:{type:"info",header:"Info!",log:"info"},success:{type:"success",header:"Success!",log:"info"},error:{type:"danger",header:"Error!",log:"error"},warn:{type:"warning",header:"Warning!",log:"warn"}};return $rootScope.notifications={},$rootScope.notifications.data=[],$rootScope.notifications.remove=function(index){$rootScope.notifications.data.splice(index,1)},$rootScope.notifications||($rootScope.notifications.data=[]),notifications.message=function(type,header,message,isPersistent,closeCallback,actionTitle,actionCallback,menuActions){var notification={type:type,header:header,message:message,isPersistent:isPersistent,closeCallback:closeCallback,actionTitle:actionTitle,actionCallback:actionCallback,menuActions:menuActions};notification.show=!0,$rootScope.notifications.data.push(notification),notification.isPersistent||(notification.viewing=!1,$timeout(function(){notification.show=!1,notification.viewing||notifications.remove(notification)},delay))},angular.forEach(modes,function(mode,index){notifications[index]=createNotifyMethod(index)}),notifications.httpError=function(message,httpResponse){message+=" ("+(httpResponse.data.message||httpResponse.data.cause||httpResponse.data.cause||httpResponse.data.errorMessage)+")",notifications.message("danger","Error!",message,persist.httpError),verbose&&$log.error(message)},notifications.remove=function(notification){var index=$rootScope.notifications.data.indexOf(notification);-1!==index&¬ifications.removeIndex(index)},notifications.removeIndex=function(index){$rootScope.notifications.remove(index)},notifications.setViewing=function(notification,viewing){notification.viewing=viewing,viewing||notification.show||notifications.remove(notification)},notifications.data=$rootScope.notifications.data,notifications}]}),angular.module("patternfly.notification").directive("pfNotificationList",function(){"use strict";function NotificationListController($scope,$rootScope){$scope.notifications=$rootScope.notifications}return NotificationListController.$inject=["$scope","$rootScope"],{restrict:"E",controller:NotificationListController,templateUrl:"notification/notification-list.html"}}),angular.module("patternfly.notification").directive("pfToastNotificationList",function(){"use strict";return{restrict:"A",scope:{notifications:"=",showClose:"=?",closeCallback:"=?",updateViewing:"=?"},templateUrl:"notification/toast-notification-list.html",controller:["$scope",function($scope){$scope.handleClose=function(notification){angular.isFunction($scope.closeCallback)&&$scope.closeCallback(notification)},$scope.handleViewingChange=function(isViewing,notification){angular.isFunction($scope.updateViewing)&&$scope.updateViewing(isViewing,notification)}}]}}),angular.module("patternfly.notification").directive("pfToastNotification",function(){"use strict";return{scope:{notificationType:"@",message:"@",header:"@",showClose:"@",closeCallback:"=?",actionTitle:"@",actionCallback:"=?",menuActions:"=?",updateViewing:"=?",data:"=?"},restrict:"A",templateUrl:"notification/toast-notification.html",controller:["$scope",function($scope){$scope.notificationType=$scope.notificationType||"info",$scope.updateShowClose=function(){$scope.showCloseButton="true"===$scope.showClose&&(angular.isUndefined($scope.menuActions)||$scope.menuActions.length<1)},$scope.handleClose=function(){angular.isFunction($scope.closeCallback)&&$scope.closeCallback($scope.data)},$scope.handleAction=function(){angular.isFunction($scope.actionCallback)&&$scope.actionCallback($scope.data)},$scope.handleMenuAction=function(menuAction){menuAction&&angular.isFunction(menuAction.actionFn)&&menuAction.isDisabled!==!0&&menuAction.actionFn(menuAction,$scope.data)},$scope.handleEnter=function(){angular.isFunction($scope.updateViewing)&&$scope.updateViewing(!0,$scope.data)},$scope.handleLeave=function(){angular.isFunction($scope.updateViewing)&&$scope.updateViewing(!1,$scope.data)},$scope.updateShowClose()}],link:function(scope){scope.$watch("showClose",function(){scope.updateShowClose()}),scope.$watch("menuActions",function(){scope.updateShowClose()})}}}),angular.module("patternfly.select",[]).directive("pfSelect",["$timeout",function($timeout){"use strict";return{restrict:"A",require:"?ngModel",scope:{selectPickerOptions:"=pfSelect"},link:function(scope,element,attrs,ngModel){var optionCollectionList,optionCollectionExpr,optionCollection,$render=ngModel.$render,selectpickerRefresh=function(argument){scope.$applyAsync(function(){element.selectpicker("refresh")})},selectpickerDestroy=function(){element.selectpicker("destroy")};element.selectpicker(scope.selectPickerOptions),ngModel.$render=function(){$render.apply(this,arguments),selectpickerRefresh()},attrs.ngOptions&&(optionCollectionList=attrs.ngOptions.split("in "),optionCollectionExpr=optionCollectionList[optionCollectionList.length-1].split(/track by|\|/),optionCollection=optionCollectionExpr[0],scope.$parent.$watchCollection(optionCollection,selectpickerRefresh)),attrs.ngModel&&scope.$parent.$watch(attrs.ngModel,selectpickerRefresh),attrs.$observe("disabled",selectpickerRefresh),scope.$on("$destroy",selectpickerDestroy)}}}]),angular.module("patternfly.sort").directive("pfSort",function(){"use strict";return{restrict:"A",scope:{config:"="},templateUrl:"sort/sort.html",controller:["$scope",function($scope){$scope.setupConfig=function(){var updated=!1;void 0===$scope.config.fields&&($scope.config.fields=[]),$scope.config.fields.length>0&&(void 0===$scope.config.currentField&&($scope.config.currentField=$scope.config.fields[0],updated=!0),void 0===$scope.config.isAscending&&($scope.config.isAscending=!0,updated=!0)),updated===!0&&$scope.config.onSortChange&&$scope.config.onSortChange($scope.config.currentField,$scope.config.isAscending)},$scope.selectField=function(field){$scope.config.currentField=field,$scope.config.onSortChange&&$scope.config.onSortChange($scope.config.currentField,$scope.config.isAscending)},$scope.changeDirection=function(){$scope.config.isAscending=!$scope.config.isAscending,$scope.config.onSortChange&&$scope.config.onSortChange($scope.config.currentField,$scope.config.isAscending)},$scope.getSortIconClass=function(){var iconClass;return iconClass="numeric"===$scope.config.currentField.sortType?$scope.config.isAscending?"fa fa-sort-numeric-asc":"fa fa-sort-numeric-desc":$scope.config.isAscending?"fa fa-sort-alpha-asc":"fa fa-sort-alpha-desc"},$scope.setupConfig()}],link:function(scope,element,attrs){scope.$watch("config",function(){scope.setupConfig()},!0)}}}),angular.module("patternfly.toolbars").directive("pfToolbar",function(){"use strict";return{restrict:"A",scope:{config:"="},replace:!0,transclude:{actions:"?"},templateUrl:"toolbars/toolbar.html",controller:["$scope",function($scope){$scope.viewSelected=function(viewId){$scope.config.viewsConfig.currentView=viewId,$scope.config.viewsConfig.onViewSelect&&!$scope.checkViewDisabled(viewId)&&$scope.config.viewsConfig.onViewSelect(viewId)},$scope.isViewSelected=function(viewId){return $scope.config.viewsConfig&&$scope.config.viewsConfig.currentView===viewId},$scope.checkViewDisabled=function(view){return $scope.config.viewsConfig.checkViewDisabled&&$scope.config.viewsConfig.checkViewDisabled(view)},$scope.filterExists=function(filter){var foundFilter=_.findWhere($scope.config.filterConfig.appliedFilters,{title:filter.title,value:filter.value});return void 0!==foundFilter},$scope.addFilter=function(field,value){var newFilter={id:field.id,title:field.title,value:value};$scope.filterExists(newFilter)||($scope.config.filterConfig.appliedFilters.push(newFilter),$scope.config.filterConfig.onFilterChange&&$scope.config.filterConfig.onFilterChange($scope.config.filterConfig.appliedFilters))},$scope.handleAction=function(action){action&&action.actionFn&&action.isDisabled!==!0&&action.actionFn(action)}}],link:function(scope,element,attrs){scope.$watch("config",function(){scope.config&&scope.config.viewsConfig&&scope.config.viewsConfig.views&&(scope.config.viewsConfig.viewsList=angular.copy(scope.config.viewsConfig.views),scope.config.viewsConfig.currentView||(scope.config.viewsConfig.currentView=scope.config.viewsConfig.viewsList[0]))},!0)}}}),angular.module("patternfly.utils").directive("pfFixedAccordion",["$window","$timeout",function($window,$timeout){"use strict";return{restrict:"A",scope:{scrollSelector:"@",groupHeight:"@",groupClass:"@"},link:function($scope,$element,$attrs){var setCollapseHeights=function(){var height,openPanel,contentHeight,bodyHeight,overflowY="hidden",parentElement=$element.find(".panel-group");height=parentElement.height(),openPanel=parentElement.find(".collapse.in"),openPanel&&openPanel.length>0&&openPanel.removeClass("in"),contentHeight=0,parentElement.children().each(function(index,groupHeading){var headingElement=angular.element(groupHeading);contentHeight+=headingElement.prop("offsetHeight"),contentHeight+=parseInt(headingElement.css("margin-top")),contentHeight+=parseInt(headingElement.css("margin-bottom"))}),bodyHeight=height-contentHeight,25>bodyHeight&&(bodyHeight=25,overflowY="auto"),openPanel&&openPanel.length>0&&openPanel.addClass("in"),$timeout(function(){parentElement.find(".panel-collapse").each(function(index,collapsePanel){var selected,$sibling,$panel=angular.element(collapsePanel),scrollElement=$panel,innerHeight=0;angular.isDefined($scope.scrollSelector)&&(selected=angular.element($panel.find($scope.scrollSelector)),1===selected.length&&(scrollElement=angular.element(selected[0]),$panel.children().each(function(j,sibling){sibling!==scrollElement[0]&&($sibling=angular.element(sibling),innerHeight+=$sibling.prop("offsetHeight"),innerHeight+=parseInt($sibling.css("margin-top")),innerHeight+=parseInt($sibling.css("margin-bottom")))}))),angular.element(scrollElement).css("max-height",bodyHeight-innerHeight+"px"),angular.element(scrollElement).css("overflow-y","auto")})}),angular.element(parentElement).css("overflow-y",overflowY)};$scope.groupHeight&&$element.find(".panel-group").css("height",$scope.groupHeight),$scope.groupClass&&$element.find(".panel-group").addClass($scope.groupClass),$timeout(function(){setCollapseHeights()},100),angular.element($window).bind("resize",function(){setCollapseHeights()})}}}]),angular.module("patternfly.utils").directive("pfTransclude",function(){"use strict";return{restrict:"A",link:function($scope,$element,$attrs,controller,$transclude){var iChildScope,iScopeType;if(!$transclude)throw new Error("pfTransclude - Illegal use of pfTransclude directive in the template! No parent directive that requires a transclusion found. Element: {0}");switch(iScopeType=$attrs.pfTransclude||"sibling"){case"sibling":$transclude(function(clone){$element.empty(),$element.append(clone)});break;case"parent":$transclude($scope,function(clone){$element.empty(),$element.append(clone)});break;case"child":iChildScope=$scope.$new(),$transclude(iChildScope,function(clone){$element.empty(),$element.append(clone),$element.on("$destroy",function(){iChildScope.$destroy()})})}}}}),function(){"use strict";angular.module("patternfly.utils").constant("pfUtils",{merge:function(source1,source2){var retValue;return retValue="function"==typeof angular.merge?this.angularMerge(source1,source2):"function"==typeof _.merge?this._merge(source1,source2):"function"==typeof $.extend?this.$extend(source1,source2):this.mergeDeep(source1,source2)},angularMerge:function(source1,source2){return angular.merge({},source1,source2)},_merge:function(source1,source2){return _.merge({},source1,source2)},$extend:function(source1,source2){return $.extend(!0,angular.copy(source1),source2)},mergeDeep:function(source1,source2){return mergeDeep({},angular.copy(source1),angular.copy(source2))},colorPalette:$.pfPaletteColors})}(),angular.module("patternfly.validation",[]).directive("pfValidation",["$timeout",function($timeout){"use strict";return{restrict:"A",require:"ngModel",scope:{pfValidation:"&",pfValidationDisabled:"="},link:function(scope,element,attrs,ctrl){function validate(){var valid,val=scope.inputCtrl.$modelValue,valFunc=scope.pfValidation({input:val});attrs.pfValidation||(valFunc=!0),valid=!val||valFunc||""===val,toggleErrorClass(scope.valEnabled&&!valid?!0:!1)}function toggleErrorClass(add){var messageElement=element.next(),parentElement=element.parent(),hasErrorM=parentElement.hasClass("has-error"),wasHidden=messageElement.hasClass("ng-hide");scope.inputCtrl.$setValidity("pf-validation",!add),add&&(hasErrorM||parentElement.addClass("has-error"),wasHidden&&messageElement.removeClass("ng-hide")),add||(hasErrorM&&parentElement.removeClass("has-error"),wasHidden||messageElement.addClass("ng-hide"))}scope.inputCtrl=ctrl,scope.valEnabled=!attrs.pfValidationDisabled,scope.$watch("pfValidationDisabled",function(newVal){scope.valEnabled=!newVal,newVal?(scope.inputCtrl.$setValidity("pfValidation",!0),toggleErrorClass(!1)):validate()}),attrs.pfValidation?$timeout(function(){validate()},0):!scope.inputCtrl.$valid&&scope.inputCtrl.$dirty&&toggleErrorClass(!0),scope.$watch("inputCtrl.$valid",function(isValid){toggleErrorClass(isValid?!1:!0)}),scope.$watch("inputCtrl.$modelValue",function(){validate()})}}}]),angular.module("patternfly.views").directive("pfCardView",["pfUtils",function(pfUtils){"use strict";return{restrict:"A",scope:{config:"=?",items:"=",eventId:"@id"},transclude:!0,templateUrl:"views/cardview/card-view.html",controller:["$scope",function($scope){if($scope.defaultConfig={selectItems:!1,multiSelect:!1,dblClick:!1,selectionMatchProp:"uuid",selectedItems:[],checkDisabled:!1,showSelectBox:!0,onSelect:null,onSelectionChange:null,onCheckBoxChange:null,onClick:null,onDblClick:null},$scope.config=pfUtils.merge($scope.defaultConfig,$scope.config),$scope.config.selectItems&&$scope.config.showSelectBox)throw new Error("pfCardView - Illegal use of pfCardView directive! Cannot allow both select box and click selection in the same card view.")}],link:function(scope,element,attrs){attrs.$observe("config",function(){scope.config=pfUtils.merge(scope.defaultConfig,scope.config),scope.config.selectItems||(scope.config.selectedItems=[]),!scope.config.multiSelect&&scope.config.selectedItems&&scope.config.selectedItems.length>0&&(scope.config.selectedItems=[scope.config.selectedItems[0]])}),scope.itemClick=function(e,item){var alreadySelected,selectionChanged=!1,continueEvent=!0;return scope.checkDisabled(item)?continueEvent:(scope.config&&scope.config.selectItems&&item&&(scope.config.multiSelect&&!scope.config.dblClick?(alreadySelected=_.find(scope.config.selectedItems,function(itemObj){return itemObj===item}),alreadySelected?scope.config.selectedItems=_.without(scope.config.selectedItems,item):(scope.config.selectedItems.push(item),selectionChanged=!0)):scope.config.selectedItems[0]===item?(scope.config.dblClick||(scope.config.selectedItems=[],selectionChanged=!0),continueEvent=!1):(scope.config.selectedItems=[item],selectionChanged=!0),selectionChanged&&scope.config.onSelect&&scope.config.onSelect(item,e),selectionChanged&&scope.config.onSelectionChange&&scope.config.onSelectionChange(scope.config.selectedItems,e)),scope.config.onClick&&scope.config.onClick(item,e),continueEvent)},scope.dblClick=function(e,item){scope.config.onDblClick&&scope.config.onDblClick(item,e)},scope.checkBoxChange=function(item){scope.config.onCheckBoxChange&&scope.config.onCheckBoxChange(item)},scope.isSelected=function(item){var matchProp=scope.config.selectionMatchProp,selected=!1;if(scope.config.showSelectBox)selected=item.selected;else if(scope.config.selectedItems.length)return _.find(scope.config.selectedItems,function(itemObj){return itemObj[matchProp]===item[matchProp]});return selected},scope.checkDisabled=function(item){return scope.config.checkDisabled&&scope.config.checkDisabled(item)}}}}]),angular.module("patternfly.views").directive("pfListView",["$timeout","$window","pfUtils",function($timeout,$window,pfUtils){"use strict";return{restrict:"A",scope:{config:"=?",items:"=",actionButtons:"=?",enableButtonForItemFn:"=?",menuActions:"=?",hideMenuForItemFn:"=?",menuClassForItemFn:"=?",updateMenuActionForItemFn:"=?",actions:"=?",updateActionForItemFn:"=?",customScope:"=?"},transclude:{expandedContent:"?listExpandedContent"},templateUrl:"views/listview/list-view.html",controller:["$scope","$element",function($scope,$element){var setDropMenuLocation=function(parentDiv){var dropButton=parentDiv.querySelector(".dropdown-toggle"),dropMenu=parentDiv.querySelector(".dropdown-menu"),parentRect=$element[0].getBoundingClientRect(),buttonRect=dropButton.getBoundingClientRect(),menuRect=dropMenu.getBoundingClientRect(),menuTop=buttonRect.top-menuRect.height,menuBottom=buttonRect.top+buttonRect.height+menuRect.height;menuBottom<=parentRect.top+parentRect.height||menuTop0&&(scope.config.selectedItems=[scope.config.selectedItems[0]])}),scope.itemClick=function(e,item){var alreadySelected,selectionChanged=!1,continueEvent=!0;return scope.checkDisabled(item)?continueEvent:(scope.config&&scope.config.selectItems&&item&&(scope.config.multiSelect&&!scope.config.dblClick?(alreadySelected=_.find(scope.config.selectedItems,function(itemObj){return itemObj===item}),alreadySelected?scope.config.selectedItems=_.without(scope.config.selectedItems,item):(scope.config.selectedItems.push(item),selectionChanged=!0)):scope.config.selectedItems[0]===item?(scope.config.dblClick||(scope.config.selectedItems=[],selectionChanged=!0),continueEvent=!1):(scope.config.selectedItems=[item],selectionChanged=!0),selectionChanged&&scope.config.onSelect&&scope.config.onSelect(item,e),selectionChanged&&scope.config.onSelectionChange&&scope.config.onSelectionChange(scope.config.selectedItems,e)),scope.config.onClick&&scope.config.onClick(item,e),continueEvent)},scope.dblClick=function(e,item){return scope.checkDisabled(item)?continueEvent:void(scope.config.onDblClick&&scope.config.onDblClick(item,e))},scope.checkBoxChange=function(item){scope.config.onCheckBoxChange&&scope.config.onCheckBoxChange(item)},scope.isSelected=function(item){var matchProp=scope.config.selectionMatchProp,selected=!1;return scope.config.showSelectBox?selected=item.selected:scope.config.selectItems&&scope.config.selectedItems.length&&(selected=_.find(scope.config.selectedItems,function(itemObj){return itemObj[matchProp]===item[matchProp]})),selected},scope.checkDisabled=function(item){return scope.config.checkDisabled&&scope.config.checkDisabled(item)}}}}]),function(){"use strict";angular.module("patternfly.views").constant("pfViewUtils",{getDashboardView:function(title){return{id:"dashboardView",title:title||"Dashboard View",iconClass:"fa fa-dashboard"}},getCardView:function(title){return{id:"cardView",title:title||"Card View",iconClass:"fa fa-th"}},getListView:function(title){return{id:"listView",title:title||"List View",iconClass:"fa fa-th-list"}},getTableView:function(title){return{id:"tableView",title:title||"Table View",iconClass:"fa fa-table"}},getTopologyView:function(title){return{id:"topologyView",title:title||"Topology View",iconClass:"fa fa-sitemap"}}})}(),function(){"use strict";function pfWizardButtonDirective(action){angular.module("patternfly.wizard").directive(action,function(){return{restrict:"A",require:"^pf-wizard",scope:{callback:"=?"},link:function($scope,$element,$attrs,wizard){$element.on("click",function(e){e.preventDefault(),$scope.$apply(function(){$scope.$eval($attrs[action]),wizard[action.replace("pfWiz","").toLowerCase()]($scope.callback)})})}}})}pfWizardButtonDirective("pfWizNext"),pfWizardButtonDirective("pfWizPrevious"),pfWizardButtonDirective("pfWizFinish"),pfWizardButtonDirective("pfWizCancel"),pfWizardButtonDirective("pfWizReset")}(),angular.module("patternfly.wizard").directive("pfWizard",["$window",function($window){"use strict";return{restrict:"A",transclude:!0,scope:{title:"@",hideIndicators:"=?",currentStep:"=?",cancelTitle:"=?",backTitle:"=?",nextTitle:"=?",backCallback:"=?",nextCallback:"=?",onFinish:"&",onCancel:"&",wizardReady:"=?",wizardDone:"=?",loadingWizardTitle:"=?",loadingSecondaryInformation:"=?",contentHeight:"=?",embedInPage:"=?"},templateUrl:"wizard/wizard.html",controller:["$scope","$timeout",function($scope,$timeout){var firstRun=!0,stepIdx=function(step){var idx=0,res=-1;return angular.forEach($scope.getEnabledSteps(),function(currStep){currStep===step&&(res=idx),idx++}),res},unselectAll=function(){angular.forEach($scope.getEnabledSteps(),function(step){step.selected=!1}),$scope.selectedStep=null},watchSelectedStep=function(){$scope.nextStepEnabledWatcher&&$scope.nextStepEnabledWatcher(),$scope.nextStepTooltipWatcher&&$scope.nextStepTooltipWatcher(),$scope.prevStepEnabledWatcher&&$scope.prevStepEnabledWatcher(),$scope.prevStepTooltipWatcher&&$scope.prevStepTooltipWatcher(),$scope.nextStepEnabledWatcher=$scope.$watch("selectedStep.nextEnabled",function(value){$scope.nextEnabled=value}),$scope.nextStepTooltipWatcher=$scope.$watch("selectedStep.nextTooltip",function(value){$scope.nextTooltip=value}),$scope.prevStepEnabledWatcher=$scope.$watch("selectedStep.prevEnabled",function(value){$scope.prevEnabled=value}),$scope.prevStepTooltipWatcher=$scope.$watch("selectedStep.prevTooltip",function(value){$scope.prevTooltip=value})},stepByTitle=function(titleToFind){var foundStep=null;return angular.forEach($scope.getEnabledSteps(),function(step){step.title===titleToFind&&(foundStep=step)}),foundStep};$scope.steps=[],$scope.context={},this.context=$scope.context,angular.isUndefined($scope.wizardReady)&&($scope.wizardReady=!0),angular.isUndefined($scope.contentHeight)&&($scope.contentHeight="300px"),this.contentHeight=$scope.contentHeight,$scope.contentStyle={height:$scope.contentHeight,"max-height":$scope.contentHeight,"overflow-y":"auto"},this.contentStyle=$scope.contentStyle,$scope.nextEnabled=!1,$scope.prevEnabled=!1,$scope.cancelTitle||($scope.cancelTitle="Cancel"),$scope.backTitle||($scope.backTitle="< Back"),$scope.nextTitle||($scope.nextTitle="Next >"),$scope.getEnabledSteps=function(){return $scope.steps.filter(function(step){return"true"!==step.disabled})},this.getReviewSteps=function(){return $scope.steps.filter(function(step){return!step.disabled&&(!angular.isUndefined(step.reviewTemplate)||step.getReviewSteps().length>0)})},$scope.currentStepNumber=function(){return stepIdx($scope.selectedStep)+1},$scope.getStepNumber=function(step){return stepIdx(step)+1},$scope.$watch("currentStep",function(step){step&&$scope.selectedStep&&$scope.selectedStep.title!==$scope.currentStep&&$scope.goTo(stepByTitle($scope.currentStep))}),$scope.$watch("[editMode, steps.length]",function(){var editMode=$scope.editMode;angular.isUndefined(editMode)||null===editMode||(editMode?angular.forEach($scope.getEnabledSteps(),function(step){step.completed=!0}):angular.forEach($scope.getEnabledSteps(),function(step,stepIndex){stepIndex>=$scope.currentStepNumber()-1&&(step.completed=!1)}))},!0),$scope.goTo=function(step,resetStepNav){$scope.wizardDone||$scope.selectedStep&&!$scope.selectedStep.okToNavAway||step===$scope.selectedStep||((firstRun||$scope.getStepNumber(step)<$scope.currentStepNumber()&&$scope.selectedStep.isPrevEnabled()||$scope.selectedStep.isNextEnabled())&&(unselectAll(),!firstRun&&resetStepNav&&step.substeps&&step.resetNav(),$scope.selectedStep=step,step.selected=!0,$timeout(function(){angular.isFunction(step.onShow)&&step.onShow()},100),watchSelectedStep(),$scope.currentStep=step.title,step.substeps||$scope.$emit("wizard:stepChanged",{step:step,index:stepIdx(step)}),firstRun=!1),$scope.selectedStep.substeps?$scope.firstStep=0===stepIdx($scope.selectedStep)&&1===$scope.selectedStep.currentStepNumber():$scope.firstStep=0===stepIdx($scope.selectedStep))},$scope.stepClick=function(step){step.allowClickNav&&$scope.goTo(step,!0)},this.addStep=function(step){var insertBefore=_.find($scope.steps,function(nextStep){return nextStep.stepPriority>step.stepPriority});insertBefore?$scope.steps.splice($scope.steps.indexOf(insertBefore),0,step):$scope.steps.push(step),$scope.wizardReady&&$scope.getEnabledSteps().length>0&&step===$scope.getEnabledSteps()[0]&&$scope.goTo($scope.getEnabledSteps()[0])},this.isWizardDone=function(){return $scope.wizardDone},this.updateSubStepNumber=function(value){$scope.firstStep=0===stepIdx($scope.selectedStep)&&0===value},this.currentStepTitle=function(){return $scope.selectedStep.title},this.currentStepDescription=function(){return $scope.selectedStep.description},this.currentStep=function(){return $scope.selectedStep},this.totalStepCount=function(){return $scope.getEnabledSteps().length},this.getEnabledSteps=function(){return $scope.getEnabledSteps()},this.currentStepNumber=function(){return $scope.currentStepNumber()},this.getStepNumber=function(step){return $scope.getStepNumber(step)},this.goTo=function(step,resetStepNav){var stepTo,enabledSteps=$scope.getEnabledSteps();stepTo=angular.isNumber(step)?enabledSteps[step]:stepByTitle(step),$scope.goTo(stepTo,resetStepNav)},this.next=function(callback){var enabledSteps=$scope.getEnabledSteps(),index=stepIdx($scope.selectedStep);if(!$scope.selectedStep.substeps||!$scope.selectedStep.next(callback)){if(angular.isFunction(callback)){if(!callback($scope.selectedStep))return;index===enabledSteps.length-1?this.finish():enabledSteps[index+1].substeps&&enabledSteps[index+1].resetNav()}$scope.selectedStep.completed=!0,index===enabledSteps.length-1?this.finish():$scope.goTo(enabledSteps[index+1])}},this.previous=function(callback){var index=stepIdx($scope.selectedStep);if((!$scope.selectedStep.substeps||!$scope.selectedStep.previous(callback))&&angular.isFunction(callback)&&callback($scope.selectedStep)){if(0===index)throw new Error("Can't go back. It's already in step 0");$scope.goTo($scope.getEnabledSteps()[index-1])}},this.finish=function(){$scope.onFinish&&$scope.onFinish()!==!1&&this.reset()},this.cancel=function(){$scope.onCancel&&$scope.onCancel()!==!1&&this.reset()},this.reset=function(){angular.forEach($scope.getEnabledSteps(),function(step){step.completed=!1}),this.goTo(0)}}],link:function($scope){$scope.$watch("wizardReady",function(){$scope.wizardReady&&$scope.goTo($scope.getEnabledSteps()[0])})}}}]),angular.module("patternfly.wizard").directive("pfWizardReviewPage",function(){"use strict";return{restrict:"A",scope:{shown:"=",wizardData:"="},require:"^pf-wizard",templateUrl:"wizard/wizard-review-page.html",controller:["$scope",function($scope){$scope.toggleShowReviewDetails=function(step){step.showReviewDetails===!0?step.showReviewDetails=!1:step.showReviewDetails=!0},$scope.getSubStepNumber=function(step,substep){return step.getStepDisplayNumber(substep)},$scope.getReviewSubSteps=function(reviewStep){return reviewStep.getReviewSteps()},$scope.reviewSteps=[],$scope.updateReviewSteps=function(wizard){$scope.reviewSteps=wizard.getReviewSteps()}}],link:function($scope,$element,$attrs,wizard){$scope.$watch("shown",function(value){value&&$scope.updateReviewSteps(wizard)})}}}),angular.module("patternfly.wizard").directive("pfWizardStep",function(){"use strict";return{restrict:"A",transclude:!0,scope:{stepTitle:"@",stepId:"@",stepPriority:"@",substeps:"=?",nextEnabled:"=?",prevEnabled:"=?",nextTooltip:"=?",prevTooltip:"=?",disabled:"@?wzDisabled",okToNavAway:"=?",allowClickNav:"=?",description:"@",wizardData:"=",onShow:"=?",showReview:"@?",showReviewDetails:"@?",reviewTemplate:"@?"},require:"^pf-wizard",templateUrl:"wizard/wizard-step.html",controller:["$scope","$timeout",function($scope,$timeout){var firstRun=!0,stepIdx=function(step){var idx=0,res=-1;return angular.forEach($scope.getEnabledSteps(),function(currStep){currStep===step&&(res=idx),idx++}),res},unselectAll=function(){angular.forEach($scope.getEnabledSteps(),function(step){step.selected=!1}),$scope.selectedStep=null},watchSelectedStep=function(){$scope.nextStepEnabledWatcher&&$scope.nextStepEnabledWatcher(),$scope.nextStepTooltipWatcher&&$scope.nextStepTooltipWatcher(),$scope.prevStepEnabledWatcher&&$scope.prevStepEnabledWatcher(),$scope.prevStepTooltipWatcher&&$scope.prevStepTooltipWatcher(),$scope.nextStepEnabledWatcher=$scope.$watch("selectedStep.nextEnabled",function(value){$scope.nextEnabled=value}),$scope.nextStepTooltipWatcher=$scope.$watch("selectedStep.nextTooltip",function(value){$scope.nextTooltip=value}),$scope.prevStepEnabledWatcher=$scope.$watch("selectedStep.prevEnabled",function(value){$scope.prevEnabled=value}),$scope.prevStepTooltipWatcher=$scope.$watch("selectedStep.prevTooltip",function(value){$scope.prevTooltip=value})},stepByTitle=function(titleToFind){var foundStep=null;return angular.forEach($scope.getEnabledSteps(),function(step){step.stepTitle===titleToFind&&(foundStep=step)}),foundStep};$scope.steps=[],$scope.context={},this.context=$scope.context,angular.isUndefined($scope.nextEnabled)&&($scope.nextEnabled=!0),angular.isUndefined($scope.prevEnabled)&&($scope.prevEnabled=!0),angular.isUndefined($scope.showReview)&&($scope.showReview=!1),angular.isUndefined($scope.showReviewDetails)&&($scope.showReviewDetails=!1),angular.isUndefined($scope.stepPriority)?$scope.stepPriority=999:$scope.stepPriority=parseInt($scope.stepPriority),angular.isUndefined($scope.okToNavAway)&&($scope.okToNavAway=!0),angular.isUndefined($scope.allowClickNav)&&($scope.allowClickNav=!0),$scope.getEnabledSteps=function(){return $scope.steps.filter(function(step){return"true"!==step.disabled})},$scope.getReviewSteps=function(){var reviewSteps=$scope.getEnabledSteps().filter(function(step){return!angular.isUndefined(step.reviewTemplate)});return reviewSteps},$scope.resetNav=function(){$scope.goTo($scope.getEnabledSteps()[0])},$scope.currentStepNumber=function(){return stepIdx($scope.selectedStep)+1},$scope.getStepNumber=function(step){return stepIdx(step)+1},$scope.isNextEnabled=function(){var enabled=angular.isUndefined($scope.nextEnabled)||$scope.nextEnabled;return $scope.substeps&&angular.forEach($scope.getEnabledSteps(),function(step){enabled=enabled&&step.nextEnabled}),enabled},$scope.isPrevEnabled=function(){var enabled=angular.isUndefined($scope.prevEnabled)||$scope.prevEnabled;return $scope.substeps&&angular.forEach($scope.getEnabledSteps(),function(step){enabled=enabled&&step.prevEnabled}),enabled},$scope.getStepDisplayNumber=function(step){return $scope.pageNumber+String.fromCharCode(65+stepIdx(step))+"."},$scope.$watch("currentStep",function(step){step&&$scope.selectedStep&&$scope.selectedStep.stepTitle!==$scope.currentStep&&$scope.goTo(stepByTitle($scope.currentStep))}),$scope.$watch("[editMode, steps.length]",function(){var editMode=$scope.editMode;angular.isUndefined(editMode)||null===editMode||(editMode?angular.forEach($scope.getEnabledSteps(),function(step){step.completed=!0}):angular.forEach($scope.getEnabledSteps(),function(step,stepIndex){stepIndex>=$scope.currentStepNumber()-1&&(step.completed=!1)}))},!0),$scope.prevStepsComplete=function(nextStep){var nextIdx=stepIdx(nextStep),complete=!0;return angular.forEach($scope.getEnabledSteps(),function(step,stepIndex){nextIdx>stepIndex&&(complete=complete&&step.nextEnabled)}),complete},$scope.goTo=function(step){!$scope.wizard.isWizardDone()&&step.okToNavAway&&step!==$scope.selectedStep&&(firstRun||$scope.getStepNumber(step)<$scope.currentStepNumber()&&$scope.selectedStep.prevEnabled||$scope.prevStepsComplete(step))&&(unselectAll(),$scope.selectedStep=step,step&&(step.selected=!0,angular.isFunction($scope.selectedStep.onShow)&&$scope.selectedStep.onShow(),watchSelectedStep(),$scope.currentStep=step.stepTitle,$scope.selected&&($scope.$emit("wizard:stepChanged",{step:step,index:stepIdx(step)}),firstRun=!1)),$scope.wizard.updateSubStepNumber(stepIdx($scope.selectedStep)))},$scope.stepClick=function(step){step.allowClickNav&&$scope.goTo(step)},$scope.$watch("selected",function(){$scope.selected&&$scope.selectedStep&&$scope.$emit("wizard:stepChanged",{step:$scope.selectedStep,index:stepIdx($scope.selectedStep)})}),this.addStep=function(step){var insertBefore=_.find($scope.steps,function(nextStep){return nextStep.stepPriority>step.stepPriority});insertBefore?$scope.steps.splice($scope.steps.indexOf(insertBefore),0,step):$scope.steps.push(step)},this.currentStepTitle=function(){return $scope.selectedStep.stepTitle},this.currentStepDescription=function(){return $scope.selectedStep.description},this.currentStep=function(){return $scope.selectedStep},this.totalStepCount=function(){return $scope.getEnabledSteps().length},this.getEnabledSteps=function(){return $scope.getEnabledSteps()},this.currentStepNumber=function(){return $scope.currentStepNumber()},this.goTo=function(step){var stepTo,enabledSteps=$scope.getEnabledSteps();stepTo=angular.isNumber(step)?enabledSteps[step]:stepByTitle(step),$scope.goTo(stepTo)},$scope.next=function(callback){var enabledSteps=$scope.getEnabledSteps(),index=stepIdx($scope.selectedStep);return angular.isFunction(callback)?callback($scope.selectedStep)?index===enabledSteps.length-1?!1:($scope.goTo(enabledSteps[index+1]),!0):!0:($scope.selectedStep.completed=!0,index===enabledSteps.length-1?!1:($scope.goTo(enabledSteps[index+1]),!0))},$scope.previous=function(callback){var index=stepIdx($scope.selectedStep),goPrev=!1;return angular.isFunction(callback)&&callback($scope.selectedStep)&&0!==index&&($scope.goTo($scope.getEnabledSteps()[index-1]),goPrev=!0),goPrev},$scope.substeps&&!$scope.onShow&&($scope.onShow=function(){$timeout(function(){$scope.selectedStep||$scope.goTo($scope.getEnabledSteps()[0])},10)})}],link:function($scope,$element,$attrs,wizard){$scope.$watch($attrs.ngShow,function(value){$scope.pageNumber=wizard.getStepNumber($scope)}),$scope.title=$scope.stepTitle,$scope.contentStyle=wizard.contentStyle,wizard.addStep($scope),$scope.wizard=wizard}}}),angular.module("patternfly.wizard").directive("pfWizardSubstep",function(){"use strict";return{restrict:"A",transclude:!0,scope:{stepTitle:"@",stepId:"@",stepPriority:"@",nextEnabled:"=?",prevEnabled:"=?",okToNavAway:"=?",allowClickNav:"=?",disabled:"@?wzDisabled",description:"@",wizardData:"=",onShow:"=?",showReviewDetails:"@?",reviewTemplate:"@?"},require:"^pf-wizard-step",templateUrl:"wizard/wizard-substep.html",controller:["$scope",function($scope){angular.isUndefined($scope.nextEnabled)&&($scope.nextEnabled=!0),angular.isUndefined($scope.prevEnabled)&&($scope.prevEnabled=!0),angular.isUndefined($scope.showReviewDetails)&&($scope.showReviewDetails=!1),angular.isUndefined($scope.stepPriority)?$scope.stepPriority=999:$scope.stepPriority=parseInt($scope.stepPriority),angular.isUndefined($scope.okToNavAway)&&($scope.okToNavAway=!0),angular.isUndefined($scope.allowClickNav)&&($scope.allowClickNav=!0),$scope.isPrevEnabled=function(){var enabled=angular.isUndefined($scope.prevEnabled)||$scope.prevEnabled;return $scope.substeps&&angular.forEach($scope.getEnabledSteps(),function(step){enabled=enabled&&step.prevEnabled}),enabled}}],link:function($scope,$element,$attrs,step){$scope.title=$scope.stepTitle,step.addStep($scope)}}}),angular.module("patternfly.card").run(["$templateCache",function($templateCache){"use strict";$templateCache.put("card/aggregate-status/aggregate-status-card.html",'

      {{status.count}} {{status.title}} {{status.count}} {{status.title}}

      {{ notification.count }} {{ notification.count }}

      {{status.count}} {{status.title}} {{status.count}} {{status.title}}

      {{status.notification.count}} {{status.notification.count}}

      '),$templateCache.put("card/basic/card-filter.html",'
      '),$templateCache.put("card/basic/card.html","

      {{headTitle}}

      {{subTitle}}
      ")}]),angular.module("patternfly.charts").run(["$templateCache",function($templateCache){"use strict";$templateCache.put("charts/donut/donut-pct-chart.html",'
      '),$templateCache.put("charts/empty-chart.html",'
      No data available
      '),$templateCache.put("charts/heatmap/heatmap-legend.html",'
      • {{item.text}}
      '),$templateCache.put("charts/heatmap/heatmap.html",'

      {{chartTitle}}

      '),$templateCache.put("charts/line/line-chart.html",'
      '),$templateCache.put("charts/sparkline/sparkline-chart.html",'
      '),$templateCache.put("charts/trends/trends-chart.html",'
      {{config.title}} {{getLatestValue()}} {{config.units}} {{getPercentageValue() + \'%\'}} of {{chartData.total + \' \' + config.units}}
      {{config.timeFrame}}
      {{getLatestValue()}} {{config.units}} {{getPercentageValue() + \'%\'}} of {{chartData.total + \' \' + config.units}} {{config.title}}
      {{getPercentageValue() + \'%\'}}
      {{config.trendLabel}} {{getLatestValue()}} of {{chartData.total + \' \' + config.units}}
      '),$templateCache.put("charts/utilization-bar/utilization-bar-chart.html",'
      {{chartTitle}}
      {{chartData.used}} of {{chartData.total}} {{units}} Used {{chartData.percentageUsed}}% Used
      {{chartTitle}}
      {{chartData.used}} {{units}} Used {{chartData.percentageUsed}}% Used
      '),$templateCache.put("charts/utilization-trend/utilization-trend-chart.html",'

      {{config.title}}

      {{currentValue}}

      {{currentText}}
      of {{chartData.total}} {{config.units}}
      {{legendLeftText}} {{legendRightText}}
      '); +}]),angular.module("patternfly.filters").run(["$templateCache",function($templateCache){"use strict";$templateCache.put("filters/filter-fields.html",'
      '),$templateCache.put("filters/filter-results.html",'
      {{config.resultsCount}} Results

      Active filters:

      • {{filter.title}}: {{filter.value}}

      Clear All Filters

      '),$templateCache.put("filters/filter.html","
      ")}]),angular.module("patternfly.form").run(["$templateCache",function($templateCache){"use strict";$templateCache.put("form/datepicker/datepicker.html",'
      '),$templateCache.put("form/datetimepicker/datetimepicker.html",'
      '),$templateCache.put("form/form-buttons/form-buttons.html",'
      '),$templateCache.put("form/form-group/form-group.html",'
      • {{ message }}
      ')}]),angular.module("patternfly.modals").run(["$templateCache",function($templateCache){"use strict";$templateCache.put("modals/about-modal.html",'')}]),angular.module("patternfly.navigation").run(["$templateCache",function($templateCache){"use strict";$templateCache.put("navigation/vertical-navigation.html","
      ')}]),angular.module("patternfly.notification").run(["$templateCache",function($templateCache){"use strict";$templateCache.put("notification/inline-notification.html",'
      {{pfNotificationHeader}} {{pfNotificationMessage}}
      '),$templateCache.put("notification/notification-drawer.html",'

      {{drawerTitle}}

      '),$templateCache.put("notification/notification-list.html",'
      '),$templateCache.put("notification/notification.html",'
      {{pfNotificationHeader}} {{pfNotificationMessage}}
      '),$templateCache.put("notification/toast-notification-list.html",'
      '),$templateCache.put("notification/toast-notification.html",'
      {{header}} {{message}} {{message}}
      ')}]),angular.module("patternfly.sort").run(["$templateCache",function($templateCache){"use strict";$templateCache.put("sort/sort.html",'
      ')}]),angular.module("patternfly.toolbars").run(["$templateCache",function($templateCache){"use strict";$templateCache.put("toolbars/toolbar.html",'
      ')}]),angular.module("patternfly.views").run(["$templateCache",function($templateCache){"use strict";$templateCache.put("views/cardview/card-view.html",'
      '),$templateCache.put("views/listview/list-view.html",'
      ')}]),angular.module("patternfly.wizard").run(["$templateCache",function($templateCache){"use strict";$templateCache.put("wizard/wizard-review-page.html",''),$templateCache.put("wizard/wizard-step.html",'
      '),$templateCache.put("wizard/wizard-substep.html",''),$templateCache.put("wizard/wizard.html",'
      ')}]); diff --git a/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/angular-animate.js b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/angular-animate.js new file mode 100644 index 00000000..bbe4c3f6 --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/angular-animate.js @@ -0,0 +1,4152 @@ +/** + * @license AngularJS v1.5.11 + * (c) 2010-2017 Google, Inc. http://angularjs.org + * License: MIT + */ +(function(window, angular) {'use strict'; + +var ELEMENT_NODE = 1; +var COMMENT_NODE = 8; + +var ADD_CLASS_SUFFIX = '-add'; +var REMOVE_CLASS_SUFFIX = '-remove'; +var EVENT_CLASS_PREFIX = 'ng-'; +var ACTIVE_CLASS_SUFFIX = '-active'; +var PREPARE_CLASS_SUFFIX = '-prepare'; + +var NG_ANIMATE_CLASSNAME = 'ng-animate'; +var NG_ANIMATE_CHILDREN_DATA = '$$ngAnimateChildren'; + +// Detect proper transitionend/animationend event names. +var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT; + +// If unprefixed events are not supported but webkit-prefixed are, use the latter. +// Otherwise, just use W3C names, browsers not supporting them at all will just ignore them. +// Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend` +// but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`. +// Register both events in case `window.onanimationend` is not supported because of that, +// do the same for `transitionend` as Safari is likely to exhibit similar behavior. +// Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit +// therefore there is no reason to test anymore for other vendor prefixes: +// http://caniuse.com/#search=transition +if ((window.ontransitionend === undefined) && (window.onwebkittransitionend !== undefined)) { + CSS_PREFIX = '-webkit-'; + TRANSITION_PROP = 'WebkitTransition'; + TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend'; +} else { + TRANSITION_PROP = 'transition'; + TRANSITIONEND_EVENT = 'transitionend'; +} + +if ((window.onanimationend === undefined) && (window.onwebkitanimationend !== undefined)) { + CSS_PREFIX = '-webkit-'; + ANIMATION_PROP = 'WebkitAnimation'; + ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend'; +} else { + ANIMATION_PROP = 'animation'; + ANIMATIONEND_EVENT = 'animationend'; +} + +var DURATION_KEY = 'Duration'; +var PROPERTY_KEY = 'Property'; +var DELAY_KEY = 'Delay'; +var TIMING_KEY = 'TimingFunction'; +var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount'; +var ANIMATION_PLAYSTATE_KEY = 'PlayState'; +var SAFE_FAST_FORWARD_DURATION_VALUE = 9999; + +var ANIMATION_DELAY_PROP = ANIMATION_PROP + DELAY_KEY; +var ANIMATION_DURATION_PROP = ANIMATION_PROP + DURATION_KEY; +var TRANSITION_DELAY_PROP = TRANSITION_PROP + DELAY_KEY; +var TRANSITION_DURATION_PROP = TRANSITION_PROP + DURATION_KEY; + +var ngMinErr = angular.$$minErr('ng'); +function assertArg(arg, name, reason) { + if (!arg) { + throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required')); + } + return arg; +} + +function mergeClasses(a,b) { + if (!a && !b) return ''; + if (!a) return b; + if (!b) return a; + if (isArray(a)) a = a.join(' '); + if (isArray(b)) b = b.join(' '); + return a + ' ' + b; +} + +function packageStyles(options) { + var styles = {}; + if (options && (options.to || options.from)) { + styles.to = options.to; + styles.from = options.from; + } + return styles; +} + +function pendClasses(classes, fix, isPrefix) { + var className = ''; + classes = isArray(classes) + ? classes + : classes && isString(classes) && classes.length + ? classes.split(/\s+/) + : []; + forEach(classes, function(klass, i) { + if (klass && klass.length > 0) { + className += (i > 0) ? ' ' : ''; + className += isPrefix ? fix + klass + : klass + fix; + } + }); + return className; +} + +function removeFromArray(arr, val) { + var index = arr.indexOf(val); + if (val >= 0) { + arr.splice(index, 1); + } +} + +function stripCommentsFromElement(element) { + if (element instanceof jqLite) { + switch (element.length) { + case 0: + return element; + + case 1: + // there is no point of stripping anything if the element + // is the only element within the jqLite wrapper. + // (it's important that we retain the element instance.) + if (element[0].nodeType === ELEMENT_NODE) { + return element; + } + break; + + default: + return jqLite(extractElementNode(element)); + } + } + + if (element.nodeType === ELEMENT_NODE) { + return jqLite(element); + } +} + +function extractElementNode(element) { + if (!element[0]) return element; + for (var i = 0; i < element.length; i++) { + var elm = element[i]; + if (elm.nodeType === ELEMENT_NODE) { + return elm; + } + } +} + +function $$addClass($$jqLite, element, className) { + forEach(element, function(elm) { + $$jqLite.addClass(elm, className); + }); +} + +function $$removeClass($$jqLite, element, className) { + forEach(element, function(elm) { + $$jqLite.removeClass(elm, className); + }); +} + +function applyAnimationClassesFactory($$jqLite) { + return function(element, options) { + if (options.addClass) { + $$addClass($$jqLite, element, options.addClass); + options.addClass = null; + } + if (options.removeClass) { + $$removeClass($$jqLite, element, options.removeClass); + options.removeClass = null; + } + }; +} + +function prepareAnimationOptions(options) { + options = options || {}; + if (!options.$$prepared) { + var domOperation = options.domOperation || noop; + options.domOperation = function() { + options.$$domOperationFired = true; + domOperation(); + domOperation = noop; + }; + options.$$prepared = true; + } + return options; +} + +function applyAnimationStyles(element, options) { + applyAnimationFromStyles(element, options); + applyAnimationToStyles(element, options); +} + +function applyAnimationFromStyles(element, options) { + if (options.from) { + element.css(options.from); + options.from = null; + } +} + +function applyAnimationToStyles(element, options) { + if (options.to) { + element.css(options.to); + options.to = null; + } +} + +function mergeAnimationDetails(element, oldAnimation, newAnimation) { + var target = oldAnimation.options || {}; + var newOptions = newAnimation.options || {}; + + var toAdd = (target.addClass || '') + ' ' + (newOptions.addClass || ''); + var toRemove = (target.removeClass || '') + ' ' + (newOptions.removeClass || ''); + var classes = resolveElementClasses(element.attr('class'), toAdd, toRemove); + + if (newOptions.preparationClasses) { + target.preparationClasses = concatWithSpace(newOptions.preparationClasses, target.preparationClasses); + delete newOptions.preparationClasses; + } + + // noop is basically when there is no callback; otherwise something has been set + var realDomOperation = target.domOperation !== noop ? target.domOperation : null; + + extend(target, newOptions); + + // TODO(matsko or sreeramu): proper fix is to maintain all animation callback in array and call at last,but now only leave has the callback so no issue with this. + if (realDomOperation) { + target.domOperation = realDomOperation; + } + + if (classes.addClass) { + target.addClass = classes.addClass; + } else { + target.addClass = null; + } + + if (classes.removeClass) { + target.removeClass = classes.removeClass; + } else { + target.removeClass = null; + } + + oldAnimation.addClass = target.addClass; + oldAnimation.removeClass = target.removeClass; + + return target; +} + +function resolveElementClasses(existing, toAdd, toRemove) { + var ADD_CLASS = 1; + var REMOVE_CLASS = -1; + + var flags = {}; + existing = splitClassesToLookup(existing); + + toAdd = splitClassesToLookup(toAdd); + forEach(toAdd, function(value, key) { + flags[key] = ADD_CLASS; + }); + + toRemove = splitClassesToLookup(toRemove); + forEach(toRemove, function(value, key) { + flags[key] = flags[key] === ADD_CLASS ? null : REMOVE_CLASS; + }); + + var classes = { + addClass: '', + removeClass: '' + }; + + forEach(flags, function(val, klass) { + var prop, allow; + if (val === ADD_CLASS) { + prop = 'addClass'; + allow = !existing[klass] || existing[klass + REMOVE_CLASS_SUFFIX]; + } else if (val === REMOVE_CLASS) { + prop = 'removeClass'; + allow = existing[klass] || existing[klass + ADD_CLASS_SUFFIX]; + } + if (allow) { + if (classes[prop].length) { + classes[prop] += ' '; + } + classes[prop] += klass; + } + }); + + function splitClassesToLookup(classes) { + if (isString(classes)) { + classes = classes.split(' '); + } + + var obj = {}; + forEach(classes, function(klass) { + // sometimes the split leaves empty string values + // incase extra spaces were applied to the options + if (klass.length) { + obj[klass] = true; + } + }); + return obj; + } + + return classes; +} + +function getDomNode(element) { + return (element instanceof jqLite) ? element[0] : element; +} + +function applyGeneratedPreparationClasses(element, event, options) { + var classes = ''; + if (event) { + classes = pendClasses(event, EVENT_CLASS_PREFIX, true); + } + if (options.addClass) { + classes = concatWithSpace(classes, pendClasses(options.addClass, ADD_CLASS_SUFFIX)); + } + if (options.removeClass) { + classes = concatWithSpace(classes, pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX)); + } + if (classes.length) { + options.preparationClasses = classes; + element.addClass(classes); + } +} + +function clearGeneratedClasses(element, options) { + if (options.preparationClasses) { + element.removeClass(options.preparationClasses); + options.preparationClasses = null; + } + if (options.activeClasses) { + element.removeClass(options.activeClasses); + options.activeClasses = null; + } +} + +function blockTransitions(node, duration) { + // we use a negative delay value since it performs blocking + // yet it doesn't kill any existing transitions running on the + // same element which makes this safe for class-based animations + var value = duration ? '-' + duration + 's' : ''; + applyInlineStyle(node, [TRANSITION_DELAY_PROP, value]); + return [TRANSITION_DELAY_PROP, value]; +} + +function blockKeyframeAnimations(node, applyBlock) { + var value = applyBlock ? 'paused' : ''; + var key = ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY; + applyInlineStyle(node, [key, value]); + return [key, value]; +} + +function applyInlineStyle(node, styleTuple) { + var prop = styleTuple[0]; + var value = styleTuple[1]; + node.style[prop] = value; +} + +function concatWithSpace(a,b) { + if (!a) return b; + if (!b) return a; + return a + ' ' + b; +} + +var $$rAFSchedulerFactory = ['$$rAF', function($$rAF) { + var queue, cancelFn; + + function scheduler(tasks) { + // we make a copy since RAFScheduler mutates the state + // of the passed in array variable and this would be difficult + // to track down on the outside code + queue = queue.concat(tasks); + nextTick(); + } + + queue = scheduler.queue = []; + + /* waitUntilQuiet does two things: + * 1. It will run the FINAL `fn` value only when an uncanceled RAF has passed through + * 2. It will delay the next wave of tasks from running until the quiet `fn` has run. + * + * The motivation here is that animation code can request more time from the scheduler + * before the next wave runs. This allows for certain DOM properties such as classes to + * be resolved in time for the next animation to run. + */ + scheduler.waitUntilQuiet = function(fn) { + if (cancelFn) cancelFn(); + + cancelFn = $$rAF(function() { + cancelFn = null; + fn(); + nextTick(); + }); + }; + + return scheduler; + + function nextTick() { + if (!queue.length) return; + + var items = queue.shift(); + for (var i = 0; i < items.length; i++) { + items[i](); + } + + if (!cancelFn) { + $$rAF(function() { + if (!cancelFn) nextTick(); + }); + } + } +}]; + +/** + * @ngdoc directive + * @name ngAnimateChildren + * @restrict AE + * @element ANY + * + * @description + * + * ngAnimateChildren allows you to specify that children of this element should animate even if any + * of the children's parents are currently animating. By default, when an element has an active `enter`, `leave`, or `move` + * (structural) animation, child elements that also have an active structural animation are not animated. + * + * Note that even if `ngAnimateChildren` is set, no child animations will run when the parent element is removed from the DOM (`leave` animation). + * + * + * @param {string} ngAnimateChildren If the value is empty, `true` or `on`, + * then child animations are allowed. If the value is `false`, child animations are not allowed. + * + * @example + * + +
      + + +
      +
      +
      + List of items: +
      Item {{item}}
      +
      +
      +
      +
      + + + .container.ng-enter, + .container.ng-leave { + transition: all ease 1.5s; + } + + .container.ng-enter, + .container.ng-leave-active { + opacity: 0; + } + + .container.ng-leave, + .container.ng-enter-active { + opacity: 1; + } + + .item { + background: firebrick; + color: #FFF; + margin-bottom: 10px; + } + + .item.ng-enter, + .item.ng-leave { + transition: transform 1.5s ease; + } + + .item.ng-enter { + transform: translateX(50px); + } + + .item.ng-enter-active { + transform: translateX(0); + } + + + angular.module('ngAnimateChildren', ['ngAnimate']) + .controller('MainController', function MainController() { + this.animateChildren = false; + this.enterElement = false; + }); + +
      + */ +var $$AnimateChildrenDirective = ['$interpolate', function($interpolate) { + return { + link: function(scope, element, attrs) { + var val = attrs.ngAnimateChildren; + if (isString(val) && val.length === 0) { //empty attribute + element.data(NG_ANIMATE_CHILDREN_DATA, true); + } else { + // Interpolate and set the value, so that it is available to + // animations that run right after compilation + setData($interpolate(val)(scope)); + attrs.$observe('ngAnimateChildren', setData); + } + + function setData(value) { + value = value === 'on' || value === 'true'; + element.data(NG_ANIMATE_CHILDREN_DATA, value); + } + } + }; +}]; + +/* exported $AnimateCssProvider */ + +var ANIMATE_TIMER_KEY = '$$animateCss'; + +/** + * @ngdoc service + * @name $animateCss + * @kind object + * + * @description + * The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes + * from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT + * to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or + * directives to create more complex animations that can be purely driven using CSS code. + * + * Note that only browsers that support CSS transitions and/or keyframe animations are capable of + * rendering animations triggered via `$animateCss` (bad news for IE9 and lower). + * + * ## Usage + * Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that + * is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however, + * any automatic control over cancelling animations and/or preventing animations from being run on + * child elements will not be handled by Angular. For this to work as expected, please use `$animate` to + * trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger + * the CSS animation. + * + * The example below shows how we can create a folding animation on an element using `ng-if`: + * + * ```html + * + *
      + * This element will go BOOM + *
      + * + * ``` + * + * Now we create the **JavaScript animation** that will trigger the CSS transition: + * + * ```js + * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) { + * return { + * enter: function(element, doneFn) { + * var height = element[0].offsetHeight; + * return $animateCss(element, { + * from: { height:'0px' }, + * to: { height:height + 'px' }, + * duration: 1 // one second + * }); + * } + * } + * }]); + * ``` + * + * ## More Advanced Uses + * + * `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks + * like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code. + * + * This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation, + * applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with + * `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order + * to provide a working animation that will run in CSS. + * + * The example below showcases a more advanced version of the `.fold-animation` from the example above: + * + * ```js + * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) { + * return { + * enter: function(element, doneFn) { + * var height = element[0].offsetHeight; + * return $animateCss(element, { + * addClass: 'red large-text pulse-twice', + * easing: 'ease-out', + * from: { height:'0px' }, + * to: { height:height + 'px' }, + * duration: 1 // one second + * }); + * } + * } + * }]); + * ``` + * + * Since we're adding/removing CSS classes then the CSS transition will also pick those up: + * + * ```css + * /* since a hardcoded duration value of 1 was provided in the JavaScript animation code, + * the CSS classes below will be transitioned despite them being defined as regular CSS classes */ + * .red { background:red; } + * .large-text { font-size:20px; } + * + * /* we can also use a keyframe animation and $animateCss will make it work alongside the transition */ + * .pulse-twice { + * animation: 0.5s pulse linear 2; + * -webkit-animation: 0.5s pulse linear 2; + * } + * + * @keyframes pulse { + * from { transform: scale(0.5); } + * to { transform: scale(1.5); } + * } + * + * @-webkit-keyframes pulse { + * from { -webkit-transform: scale(0.5); } + * to { -webkit-transform: scale(1.5); } + * } + * ``` + * + * Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen. + * + * ## How the Options are handled + * + * `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation + * works with the options provided. Say for example we were adding a class that contained a keyframe value and we wanted to also animate some inline + * styles using the `from` and `to` properties. + * + * ```js + * var animator = $animateCss(element, { + * from: { background:'red' }, + * to: { background:'blue' } + * }); + * animator.start(); + * ``` + * + * ```css + * .rotating-animation { + * animation:0.5s rotate linear; + * -webkit-animation:0.5s rotate linear; + * } + * + * @keyframes rotate { + * from { transform: rotate(0deg); } + * to { transform: rotate(360deg); } + * } + * + * @-webkit-keyframes rotate { + * from { -webkit-transform: rotate(0deg); } + * to { -webkit-transform: rotate(360deg); } + * } + * ``` + * + * The missing pieces here are that we do not have a transition set (within the CSS code nor within the `$animateCss` options) and the duration of the animation is + * going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition + * style matching the duration detected from the keyframe style (which is present in the CSS class that is being added) and then prepare both the transition + * and keyframe animations to run in parallel on the element. Then when the animation is underway the provided `from` and `to` CSS styles will be applied + * and spread across the transition and keyframe animation. + * + * ## What is returned + * + * `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually + * start the animation. All that is going on here is that the element is being prepared for the animation (which means that the generated CSS classes are + * added and removed on the element). Once `$animateCss` is called it will return an object with the following properties: + * + * ```js + * var animator = $animateCss(element, { ... }); + * ``` + * + * Now what do the contents of our `animator` variable look like: + * + * ```js + * { + * // starts the animation + * start: Function, + * + * // ends (aborts) the animation + * end: Function + * } + * ``` + * + * To actually start the animation we need to run `animation.start()` which will then return a promise that we can hook into to detect when the animation ends. + * If we choose not to run the animation then we MUST run `animation.end()` to perform a cleanup on the element (since some CSS classes and styles may have been + * applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties + * and that changing them will not reconfigure the parameters of the animation. + * + * ### runner.done() vs runner.then() + * It is documented that `animation.start()` will return a promise object and this is true, however, there is also an additional method available on the + * runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**. + * Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()` + * unless you really need a digest to kick off afterwards. + * + * Keep in mind that, to make this easier, ngAnimate has tweaked the JS animations API to recognize when a runner instance is returned from $animateCss + * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code). + * Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works. + * + * @param {DOMElement} element the element that will be animated + * @param {object} options the animation-related options that will be applied during the animation + * + * * `event` - The DOM event (e.g. enter, leave, move). When used, a generated CSS class of `ng-EVENT` and `ng-EVENT-active` will be applied + * to the element during the animation. Multiple events can be provided when spaces are used as a separator. (Note that this will not perform any DOM operation.) + * * `structural` - Indicates that the `ng-` prefix will be added to the event class. Setting to `false` or omitting will turn `ng-EVENT` and + * `ng-EVENT-active` in `EVENT` and `EVENT-active`. Unused if `event` is omitted. + * * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both). + * * `transitionStyle` - The raw CSS transition style that will be used (e.g. `1s linear all`). + * * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`). + * * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation. + * * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition. + * * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation. + * * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation. + * * `duration` - A number value representing the total duration of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `0` + * is provided then the animation will be skipped entirely. + * * `delay` - A number value representing the total delay of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `true` is + * used then whatever delay value is detected from the CSS classes will be mirrored on the elements styles (e.g. by setting delay true then the style value + * of the element will be `transition-delay: DETECTED_VALUE`). Using `true` is useful when you want the CSS classes and inline styles to all share the same + * CSS delay value. + * * `stagger` - A numeric time value representing the delay between successively animated elements + * ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.}) + * * `staggerIndex` - The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item in the stagger; therefore when a + * `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`) + * * `applyClassesEarly` - Whether or not the classes being added or removed will be used when detecting the animation. This is set by `$animate` when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time. (Note that this will prevent any transitions from occurring on the classes being added and removed.) + * * `cleanupStyles` - Whether or not the provided `from` and `to` styles will be removed once + * the animation is closed. This is useful for when the styles are used purely for the sake of + * the animation and do not have a lasting visual effect on the element (e.g. a collapse and open animation). + * By default this value is set to `false`. + * + * @return {object} an object with start and end methods and details about the animation. + * + * * `start` - The method to start the animation. This will return a `Promise` when called. + * * `end` - This method will cancel the animation and remove all applied CSS classes and styles. + */ +var ONE_SECOND = 1000; + +var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3; +var CLOSING_TIME_BUFFER = 1.5; + +var DETECT_CSS_PROPERTIES = { + transitionDuration: TRANSITION_DURATION_PROP, + transitionDelay: TRANSITION_DELAY_PROP, + transitionProperty: TRANSITION_PROP + PROPERTY_KEY, + animationDuration: ANIMATION_DURATION_PROP, + animationDelay: ANIMATION_DELAY_PROP, + animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY +}; + +var DETECT_STAGGER_CSS_PROPERTIES = { + transitionDuration: TRANSITION_DURATION_PROP, + transitionDelay: TRANSITION_DELAY_PROP, + animationDuration: ANIMATION_DURATION_PROP, + animationDelay: ANIMATION_DELAY_PROP +}; + +function getCssKeyframeDurationStyle(duration) { + return [ANIMATION_DURATION_PROP, duration + 's']; +} + +function getCssDelayStyle(delay, isKeyframeAnimation) { + var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP; + return [prop, delay + 's']; +} + +function computeCssStyles($window, element, properties) { + var styles = Object.create(null); + var detectedStyles = $window.getComputedStyle(element) || {}; + forEach(properties, function(formalStyleName, actualStyleName) { + var val = detectedStyles[formalStyleName]; + if (val) { + var c = val.charAt(0); + + // only numerical-based values have a negative sign or digit as the first value + if (c === '-' || c === '+' || c >= 0) { + val = parseMaxTime(val); + } + + // by setting this to null in the event that the delay is not set or is set directly as 0 + // then we can still allow for negative values to be used later on and not mistake this + // value for being greater than any other negative value. + if (val === 0) { + val = null; + } + styles[actualStyleName] = val; + } + }); + + return styles; +} + +function parseMaxTime(str) { + var maxValue = 0; + var values = str.split(/\s*,\s*/); + forEach(values, function(value) { + // it's always safe to consider only second values and omit `ms` values since + // getComputedStyle will always handle the conversion for us + if (value.charAt(value.length - 1) === 's') { + value = value.substring(0, value.length - 1); + } + value = parseFloat(value) || 0; + maxValue = maxValue ? Math.max(value, maxValue) : value; + }); + return maxValue; +} + +function truthyTimingValue(val) { + return val === 0 || val != null; +} + +function getCssTransitionDurationStyle(duration, applyOnlyDuration) { + var style = TRANSITION_PROP; + var value = duration + 's'; + if (applyOnlyDuration) { + style += DURATION_KEY; + } else { + value += ' linear all'; + } + return [style, value]; +} + +function createLocalCacheLookup() { + var cache = Object.create(null); + return { + flush: function() { + cache = Object.create(null); + }, + + count: function(key) { + var entry = cache[key]; + return entry ? entry.total : 0; + }, + + get: function(key) { + var entry = cache[key]; + return entry && entry.value; + }, + + put: function(key, value) { + if (!cache[key]) { + cache[key] = { total: 1, value: value }; + } else { + cache[key].total++; + } + } + }; +} + +// we do not reassign an already present style value since +// if we detect the style property value again we may be +// detecting styles that were added via the `from` styles. +// We make use of `isDefined` here since an empty string +// or null value (which is what getPropertyValue will return +// for a non-existing style) will still be marked as a valid +// value for the style (a falsy value implies that the style +// is to be removed at the end of the animation). If we had a simple +// "OR" statement then it would not be enough to catch that. +function registerRestorableStyles(backup, node, properties) { + forEach(properties, function(prop) { + backup[prop] = isDefined(backup[prop]) + ? backup[prop] + : node.style.getPropertyValue(prop); + }); +} + +var $AnimateCssProvider = ['$animateProvider', /** @this */ function($animateProvider) { + var gcsLookup = createLocalCacheLookup(); + var gcsStaggerLookup = createLocalCacheLookup(); + + this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout', + '$$forceReflow', '$sniffer', '$$rAFScheduler', '$$animateQueue', + function($window, $$jqLite, $$AnimateRunner, $timeout, + $$forceReflow, $sniffer, $$rAFScheduler, $$animateQueue) { + + var applyAnimationClasses = applyAnimationClassesFactory($$jqLite); + + var parentCounter = 0; + function gcsHashFn(node, extraClasses) { + var KEY = '$$ngAnimateParentKey'; + var parentNode = node.parentNode; + var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter); + return parentID + '-' + node.getAttribute('class') + '-' + extraClasses; + } + + function computeCachedCssStyles(node, className, cacheKey, properties) { + var timings = gcsLookup.get(cacheKey); + + if (!timings) { + timings = computeCssStyles($window, node, properties); + if (timings.animationIterationCount === 'infinite') { + timings.animationIterationCount = 1; + } + } + + // we keep putting this in multiple times even though the value and the cacheKey are the same + // because we're keeping an internal tally of how many duplicate animations are detected. + gcsLookup.put(cacheKey, timings); + return timings; + } + + function computeCachedCssStaggerStyles(node, className, cacheKey, properties) { + var stagger; + + // if we have one or more existing matches of matching elements + // containing the same parent + CSS styles (which is how cacheKey works) + // then staggering is possible + if (gcsLookup.count(cacheKey) > 0) { + stagger = gcsStaggerLookup.get(cacheKey); + + if (!stagger) { + var staggerClassName = pendClasses(className, '-stagger'); + + $$jqLite.addClass(node, staggerClassName); + + stagger = computeCssStyles($window, node, properties); + + // force the conversion of a null value to zero incase not set + stagger.animationDuration = Math.max(stagger.animationDuration, 0); + stagger.transitionDuration = Math.max(stagger.transitionDuration, 0); + + $$jqLite.removeClass(node, staggerClassName); + + gcsStaggerLookup.put(cacheKey, stagger); + } + } + + return stagger || {}; + } + + var rafWaitQueue = []; + function waitUntilQuiet(callback) { + rafWaitQueue.push(callback); + $$rAFScheduler.waitUntilQuiet(function() { + gcsLookup.flush(); + gcsStaggerLookup.flush(); + + // DO NOT REMOVE THIS LINE OR REFACTOR OUT THE `pageWidth` variable. + // PLEASE EXAMINE THE `$$forceReflow` service to understand why. + var pageWidth = $$forceReflow(); + + // we use a for loop to ensure that if the queue is changed + // during this looping then it will consider new requests + for (var i = 0; i < rafWaitQueue.length; i++) { + rafWaitQueue[i](pageWidth); + } + rafWaitQueue.length = 0; + }); + } + + function computeTimings(node, className, cacheKey) { + var timings = computeCachedCssStyles(node, className, cacheKey, DETECT_CSS_PROPERTIES); + var aD = timings.animationDelay; + var tD = timings.transitionDelay; + timings.maxDelay = aD && tD + ? Math.max(aD, tD) + : (aD || tD); + timings.maxDuration = Math.max( + timings.animationDuration * timings.animationIterationCount, + timings.transitionDuration); + + return timings; + } + + return function init(element, initialOptions) { + // all of the animation functions should create + // a copy of the options data, however, if a + // parent service has already created a copy then + // we should stick to using that + var options = initialOptions || {}; + if (!options.$$prepared) { + options = prepareAnimationOptions(copy(options)); + } + + var restoreStyles = {}; + var node = getDomNode(element); + if (!node + || !node.parentNode + || !$$animateQueue.enabled()) { + return closeAndReturnNoopAnimator(); + } + + var temporaryStyles = []; + var classes = element.attr('class'); + var styles = packageStyles(options); + var animationClosed; + var animationPaused; + var animationCompleted; + var runner; + var runnerHost; + var maxDelay; + var maxDelayTime; + var maxDuration; + var maxDurationTime; + var startTime; + var events = []; + + if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) { + return closeAndReturnNoopAnimator(); + } + + var method = options.event && isArray(options.event) + ? options.event.join(' ') + : options.event; + + var isStructural = method && options.structural; + var structuralClassName = ''; + var addRemoveClassName = ''; + + if (isStructural) { + structuralClassName = pendClasses(method, EVENT_CLASS_PREFIX, true); + } else if (method) { + structuralClassName = method; + } + + if (options.addClass) { + addRemoveClassName += pendClasses(options.addClass, ADD_CLASS_SUFFIX); + } + + if (options.removeClass) { + if (addRemoveClassName.length) { + addRemoveClassName += ' '; + } + addRemoveClassName += pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX); + } + + // there may be a situation where a structural animation is combined together + // with CSS classes that need to resolve before the animation is computed. + // However this means that there is no explicit CSS code to block the animation + // from happening (by setting 0s none in the class name). If this is the case + // we need to apply the classes before the first rAF so we know to continue if + // there actually is a detected transition or keyframe animation + if (options.applyClassesEarly && addRemoveClassName.length) { + applyAnimationClasses(element, options); + } + + var preparationClasses = [structuralClassName, addRemoveClassName].join(' ').trim(); + var fullClassName = classes + ' ' + preparationClasses; + var activeClasses = pendClasses(preparationClasses, ACTIVE_CLASS_SUFFIX); + var hasToStyles = styles.to && Object.keys(styles.to).length > 0; + var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0; + + // there is no way we can trigger an animation if no styles and + // no classes are being applied which would then trigger a transition, + // unless there a is raw keyframe value that is applied to the element. + if (!containsKeyframeAnimation + && !hasToStyles + && !preparationClasses) { + return closeAndReturnNoopAnimator(); + } + + var cacheKey, stagger; + if (options.stagger > 0) { + var staggerVal = parseFloat(options.stagger); + stagger = { + transitionDelay: staggerVal, + animationDelay: staggerVal, + transitionDuration: 0, + animationDuration: 0 + }; + } else { + cacheKey = gcsHashFn(node, fullClassName); + stagger = computeCachedCssStaggerStyles(node, preparationClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES); + } + + if (!options.$$skipPreparationClasses) { + $$jqLite.addClass(element, preparationClasses); + } + + var applyOnlyDuration; + + if (options.transitionStyle) { + var transitionStyle = [TRANSITION_PROP, options.transitionStyle]; + applyInlineStyle(node, transitionStyle); + temporaryStyles.push(transitionStyle); + } + + if (options.duration >= 0) { + applyOnlyDuration = node.style[TRANSITION_PROP].length > 0; + var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration); + + // we set the duration so that it will be picked up by getComputedStyle later + applyInlineStyle(node, durationStyle); + temporaryStyles.push(durationStyle); + } + + if (options.keyframeStyle) { + var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle]; + applyInlineStyle(node, keyframeStyle); + temporaryStyles.push(keyframeStyle); + } + + var itemIndex = stagger + ? options.staggerIndex >= 0 + ? options.staggerIndex + : gcsLookup.count(cacheKey) + : 0; + + var isFirst = itemIndex === 0; + + // this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY + // without causing any combination of transitions to kick in. By adding a negative delay value + // it forces the setup class' transition to end immediately. We later then remove the negative + // transition delay to allow for the transition to naturally do it's thing. The beauty here is + // that if there is no transition defined then nothing will happen and this will also allow + // other transitions to be stacked on top of each other without any chopping them out. + if (isFirst && !options.skipBlocking) { + blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE); + } + + var timings = computeTimings(node, fullClassName, cacheKey); + var relativeDelay = timings.maxDelay; + maxDelay = Math.max(relativeDelay, 0); + maxDuration = timings.maxDuration; + + var flags = {}; + flags.hasTransitions = timings.transitionDuration > 0; + flags.hasAnimations = timings.animationDuration > 0; + flags.hasTransitionAll = flags.hasTransitions && timings.transitionProperty === 'all'; + flags.applyTransitionDuration = hasToStyles && ( + (flags.hasTransitions && !flags.hasTransitionAll) + || (flags.hasAnimations && !flags.hasTransitions)); + flags.applyAnimationDuration = options.duration && flags.hasAnimations; + flags.applyTransitionDelay = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions); + flags.applyAnimationDelay = truthyTimingValue(options.delay) && flags.hasAnimations; + flags.recalculateTimingStyles = addRemoveClassName.length > 0; + + if (flags.applyTransitionDuration || flags.applyAnimationDuration) { + maxDuration = options.duration ? parseFloat(options.duration) : maxDuration; + + if (flags.applyTransitionDuration) { + flags.hasTransitions = true; + timings.transitionDuration = maxDuration; + applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0; + temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration)); + } + + if (flags.applyAnimationDuration) { + flags.hasAnimations = true; + timings.animationDuration = maxDuration; + temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration)); + } + } + + if (maxDuration === 0 && !flags.recalculateTimingStyles) { + return closeAndReturnNoopAnimator(); + } + + if (options.delay != null) { + var delayStyle; + if (typeof options.delay !== 'boolean') { + delayStyle = parseFloat(options.delay); + // number in options.delay means we have to recalculate the delay for the closing timeout + maxDelay = Math.max(delayStyle, 0); + } + + if (flags.applyTransitionDelay) { + temporaryStyles.push(getCssDelayStyle(delayStyle)); + } + + if (flags.applyAnimationDelay) { + temporaryStyles.push(getCssDelayStyle(delayStyle, true)); + } + } + + // we need to recalculate the delay value since we used a pre-emptive negative + // delay value and the delay value is required for the final event checking. This + // property will ensure that this will happen after the RAF phase has passed. + if (options.duration == null && timings.transitionDuration > 0) { + flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst; + } + + maxDelayTime = maxDelay * ONE_SECOND; + maxDurationTime = maxDuration * ONE_SECOND; + if (!options.skipBlocking) { + flags.blockTransition = timings.transitionDuration > 0; + flags.blockKeyframeAnimation = timings.animationDuration > 0 && + stagger.animationDelay > 0 && + stagger.animationDuration === 0; + } + + if (options.from) { + if (options.cleanupStyles) { + registerRestorableStyles(restoreStyles, node, Object.keys(options.from)); + } + applyAnimationFromStyles(element, options); + } + + if (flags.blockTransition || flags.blockKeyframeAnimation) { + applyBlocking(maxDuration); + } else if (!options.skipBlocking) { + blockTransitions(node, false); + } + + // TODO(matsko): for 1.5 change this code to have an animator object for better debugging + return { + $$willAnimate: true, + end: endFn, + start: function() { + if (animationClosed) return; + + runnerHost = { + end: endFn, + cancel: cancelFn, + resume: null, //this will be set during the start() phase + pause: null + }; + + runner = new $$AnimateRunner(runnerHost); + + waitUntilQuiet(start); + + // we don't have access to pause/resume the animation + // since it hasn't run yet. AnimateRunner will therefore + // set noop functions for resume and pause and they will + // later be overridden once the animation is triggered + return runner; + } + }; + + function endFn() { + close(); + } + + function cancelFn() { + close(true); + } + + function close(rejected) { + // if the promise has been called already then we shouldn't close + // the animation again + if (animationClosed || (animationCompleted && animationPaused)) return; + animationClosed = true; + animationPaused = false; + + if (!options.$$skipPreparationClasses) { + $$jqLite.removeClass(element, preparationClasses); + } + $$jqLite.removeClass(element, activeClasses); + + blockKeyframeAnimations(node, false); + blockTransitions(node, false); + + forEach(temporaryStyles, function(entry) { + // There is only one way to remove inline style properties entirely from elements. + // By using `removeProperty` this works, but we need to convert camel-cased CSS + // styles down to hyphenated values. + node.style[entry[0]] = ''; + }); + + applyAnimationClasses(element, options); + applyAnimationStyles(element, options); + + if (Object.keys(restoreStyles).length) { + forEach(restoreStyles, function(value, prop) { + if (value) { + node.style.setProperty(prop, value); + } else { + node.style.removeProperty(prop); + } + }); + } + + // the reason why we have this option is to allow a synchronous closing callback + // that is fired as SOON as the animation ends (when the CSS is removed) or if + // the animation never takes off at all. A good example is a leave animation since + // the element must be removed just after the animation is over or else the element + // will appear on screen for one animation frame causing an overbearing flicker. + if (options.onDone) { + options.onDone(); + } + + if (events && events.length) { + // Remove the transitionend / animationend listener(s) + element.off(events.join(' '), onAnimationProgress); + } + + //Cancel the fallback closing timeout and remove the timer data + var animationTimerData = element.data(ANIMATE_TIMER_KEY); + if (animationTimerData) { + $timeout.cancel(animationTimerData[0].timer); + element.removeData(ANIMATE_TIMER_KEY); + } + + // if the preparation function fails then the promise is not setup + if (runner) { + runner.complete(!rejected); + } + } + + function applyBlocking(duration) { + if (flags.blockTransition) { + blockTransitions(node, duration); + } + + if (flags.blockKeyframeAnimation) { + blockKeyframeAnimations(node, !!duration); + } + } + + function closeAndReturnNoopAnimator() { + runner = new $$AnimateRunner({ + end: endFn, + cancel: cancelFn + }); + + // should flush the cache animation + waitUntilQuiet(noop); + close(); + + return { + $$willAnimate: false, + start: function() { + return runner; + }, + end: endFn + }; + } + + function onAnimationProgress(event) { + event.stopPropagation(); + var ev = event.originalEvent || event; + + // we now always use `Date.now()` due to the recent changes with + // event.timeStamp in Firefox, Webkit and Chrome (see #13494 for more info) + var timeStamp = ev.$manualTimeStamp || Date.now(); + + /* Firefox (or possibly just Gecko) likes to not round values up + * when a ms measurement is used for the animation */ + var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES)); + + /* $manualTimeStamp is a mocked timeStamp value which is set + * within browserTrigger(). This is only here so that tests can + * mock animations properly. Real events fallback to event.timeStamp, + * or, if they don't, then a timeStamp is automatically created for them. + * We're checking to see if the timeStamp surpasses the expected delay, + * but we're using elapsedTime instead of the timeStamp on the 2nd + * pre-condition since animationPauseds sometimes close off early */ + if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) { + // we set this flag to ensure that if the transition is paused then, when resumed, + // the animation will automatically close itself since transitions cannot be paused. + animationCompleted = true; + close(); + } + } + + function start() { + if (animationClosed) return; + if (!node.parentNode) { + close(); + return; + } + + // even though we only pause keyframe animations here the pause flag + // will still happen when transitions are used. Only the transition will + // not be paused since that is not possible. If the animation ends when + // paused then it will not complete until unpaused or cancelled. + var playPause = function(playAnimation) { + if (!animationCompleted) { + animationPaused = !playAnimation; + if (timings.animationDuration) { + var value = blockKeyframeAnimations(node, animationPaused); + if (animationPaused) { + temporaryStyles.push(value); + } else { + removeFromArray(temporaryStyles, value); + } + } + } else if (animationPaused && playAnimation) { + animationPaused = false; + close(); + } + }; + + // checking the stagger duration prevents an accidentally cascade of the CSS delay style + // being inherited from the parent. If the transition duration is zero then we can safely + // rely that the delay value is an intentional stagger delay style. + var maxStagger = itemIndex > 0 + && ((timings.transitionDuration && stagger.transitionDuration === 0) || + (timings.animationDuration && stagger.animationDuration === 0)) + && Math.max(stagger.animationDelay, stagger.transitionDelay); + if (maxStagger) { + $timeout(triggerAnimationStart, + Math.floor(maxStagger * itemIndex * ONE_SECOND), + false); + } else { + triggerAnimationStart(); + } + + // this will decorate the existing promise runner with pause/resume methods + runnerHost.resume = function() { + playPause(true); + }; + + runnerHost.pause = function() { + playPause(false); + }; + + function triggerAnimationStart() { + // just incase a stagger animation kicks in when the animation + // itself was cancelled entirely + if (animationClosed) return; + + applyBlocking(false); + + forEach(temporaryStyles, function(entry) { + var key = entry[0]; + var value = entry[1]; + node.style[key] = value; + }); + + applyAnimationClasses(element, options); + $$jqLite.addClass(element, activeClasses); + + if (flags.recalculateTimingStyles) { + fullClassName = node.className + ' ' + preparationClasses; + cacheKey = gcsHashFn(node, fullClassName); + + timings = computeTimings(node, fullClassName, cacheKey); + relativeDelay = timings.maxDelay; + maxDelay = Math.max(relativeDelay, 0); + maxDuration = timings.maxDuration; + + if (maxDuration === 0) { + close(); + return; + } + + flags.hasTransitions = timings.transitionDuration > 0; + flags.hasAnimations = timings.animationDuration > 0; + } + + if (flags.applyAnimationDelay) { + relativeDelay = typeof options.delay !== 'boolean' && truthyTimingValue(options.delay) + ? parseFloat(options.delay) + : relativeDelay; + + maxDelay = Math.max(relativeDelay, 0); + timings.animationDelay = relativeDelay; + delayStyle = getCssDelayStyle(relativeDelay, true); + temporaryStyles.push(delayStyle); + node.style[delayStyle[0]] = delayStyle[1]; + } + + maxDelayTime = maxDelay * ONE_SECOND; + maxDurationTime = maxDuration * ONE_SECOND; + + if (options.easing) { + var easeProp, easeVal = options.easing; + if (flags.hasTransitions) { + easeProp = TRANSITION_PROP + TIMING_KEY; + temporaryStyles.push([easeProp, easeVal]); + node.style[easeProp] = easeVal; + } + if (flags.hasAnimations) { + easeProp = ANIMATION_PROP + TIMING_KEY; + temporaryStyles.push([easeProp, easeVal]); + node.style[easeProp] = easeVal; + } + } + + if (timings.transitionDuration) { + events.push(TRANSITIONEND_EVENT); + } + + if (timings.animationDuration) { + events.push(ANIMATIONEND_EVENT); + } + + startTime = Date.now(); + var timerTime = maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime; + var endTime = startTime + timerTime; + + var animationsData = element.data(ANIMATE_TIMER_KEY) || []; + var setupFallbackTimer = true; + if (animationsData.length) { + var currentTimerData = animationsData[0]; + setupFallbackTimer = endTime > currentTimerData.expectedEndTime; + if (setupFallbackTimer) { + $timeout.cancel(currentTimerData.timer); + } else { + animationsData.push(close); + } + } + + if (setupFallbackTimer) { + var timer = $timeout(onAnimationExpired, timerTime, false); + animationsData[0] = { + timer: timer, + expectedEndTime: endTime + }; + animationsData.push(close); + element.data(ANIMATE_TIMER_KEY, animationsData); + } + + if (events.length) { + element.on(events.join(' '), onAnimationProgress); + } + + if (options.to) { + if (options.cleanupStyles) { + registerRestorableStyles(restoreStyles, node, Object.keys(options.to)); + } + applyAnimationToStyles(element, options); + } + } + + function onAnimationExpired() { + var animationsData = element.data(ANIMATE_TIMER_KEY); + + // this will be false in the event that the element was + // removed from the DOM (via a leave animation or something + // similar) + if (animationsData) { + for (var i = 1; i < animationsData.length; i++) { + animationsData[i](); + } + element.removeData(ANIMATE_TIMER_KEY); + } + } + } + }; + }]; +}]; + +var $$AnimateCssDriverProvider = ['$$animationProvider', /** @this */ function($$animationProvider) { + $$animationProvider.drivers.push('$$animateCssDriver'); + + var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim'; + var NG_ANIMATE_ANCHOR_CLASS_NAME = 'ng-anchor'; + + var NG_OUT_ANCHOR_CLASS_NAME = 'ng-anchor-out'; + var NG_IN_ANCHOR_CLASS_NAME = 'ng-anchor-in'; + + function isDocumentFragment(node) { + return node.parentNode && node.parentNode.nodeType === 11; + } + + this.$get = ['$animateCss', '$rootScope', '$$AnimateRunner', '$rootElement', '$sniffer', '$$jqLite', '$document', + function($animateCss, $rootScope, $$AnimateRunner, $rootElement, $sniffer, $$jqLite, $document) { + + // only browsers that support these properties can render animations + if (!$sniffer.animations && !$sniffer.transitions) return noop; + + var bodyNode = $document[0].body; + var rootNode = getDomNode($rootElement); + + var rootBodyElement = jqLite( + // this is to avoid using something that exists outside of the body + // we also special case the doc fragment case because our unit test code + // appends the $rootElement to the body after the app has been bootstrapped + isDocumentFragment(rootNode) || bodyNode.contains(rootNode) ? rootNode : bodyNode + ); + + return function initDriverFn(animationDetails) { + return animationDetails.from && animationDetails.to + ? prepareFromToAnchorAnimation(animationDetails.from, + animationDetails.to, + animationDetails.classes, + animationDetails.anchors) + : prepareRegularAnimation(animationDetails); + }; + + function filterCssClasses(classes) { + //remove all the `ng-` stuff + return classes.replace(/\bng-\S+\b/g, ''); + } + + function getUniqueValues(a, b) { + if (isString(a)) a = a.split(' '); + if (isString(b)) b = b.split(' '); + return a.filter(function(val) { + return b.indexOf(val) === -1; + }).join(' '); + } + + function prepareAnchoredAnimation(classes, outAnchor, inAnchor) { + var clone = jqLite(getDomNode(outAnchor).cloneNode(true)); + var startingClasses = filterCssClasses(getClassVal(clone)); + + outAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME); + inAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME); + + clone.addClass(NG_ANIMATE_ANCHOR_CLASS_NAME); + + rootBodyElement.append(clone); + + var animatorIn, animatorOut = prepareOutAnimation(); + + // the user may not end up using the `out` animation and + // only making use of the `in` animation or vice-versa. + // In either case we should allow this and not assume the + // animation is over unless both animations are not used. + if (!animatorOut) { + animatorIn = prepareInAnimation(); + if (!animatorIn) { + return end(); + } + } + + var startingAnimator = animatorOut || animatorIn; + + return { + start: function() { + var runner; + + var currentAnimation = startingAnimator.start(); + currentAnimation.done(function() { + currentAnimation = null; + if (!animatorIn) { + animatorIn = prepareInAnimation(); + if (animatorIn) { + currentAnimation = animatorIn.start(); + currentAnimation.done(function() { + currentAnimation = null; + end(); + runner.complete(); + }); + return currentAnimation; + } + } + // in the event that there is no `in` animation + end(); + runner.complete(); + }); + + runner = new $$AnimateRunner({ + end: endFn, + cancel: endFn + }); + + return runner; + + function endFn() { + if (currentAnimation) { + currentAnimation.end(); + } + } + } + }; + + function calculateAnchorStyles(anchor) { + var styles = {}; + + var coords = getDomNode(anchor).getBoundingClientRect(); + + // we iterate directly since safari messes up and doesn't return + // all the keys for the coords object when iterated + forEach(['width','height','top','left'], function(key) { + var value = coords[key]; + switch (key) { + case 'top': + value += bodyNode.scrollTop; + break; + case 'left': + value += bodyNode.scrollLeft; + break; + } + styles[key] = Math.floor(value) + 'px'; + }); + return styles; + } + + function prepareOutAnimation() { + var animator = $animateCss(clone, { + addClass: NG_OUT_ANCHOR_CLASS_NAME, + delay: true, + from: calculateAnchorStyles(outAnchor) + }); + + // read the comment within `prepareRegularAnimation` to understand + // why this check is necessary + return animator.$$willAnimate ? animator : null; + } + + function getClassVal(element) { + return element.attr('class') || ''; + } + + function prepareInAnimation() { + var endingClasses = filterCssClasses(getClassVal(inAnchor)); + var toAdd = getUniqueValues(endingClasses, startingClasses); + var toRemove = getUniqueValues(startingClasses, endingClasses); + + var animator = $animateCss(clone, { + to: calculateAnchorStyles(inAnchor), + addClass: NG_IN_ANCHOR_CLASS_NAME + ' ' + toAdd, + removeClass: NG_OUT_ANCHOR_CLASS_NAME + ' ' + toRemove, + delay: true + }); + + // read the comment within `prepareRegularAnimation` to understand + // why this check is necessary + return animator.$$willAnimate ? animator : null; + } + + function end() { + clone.remove(); + outAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME); + inAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME); + } + } + + function prepareFromToAnchorAnimation(from, to, classes, anchors) { + var fromAnimation = prepareRegularAnimation(from, noop); + var toAnimation = prepareRegularAnimation(to, noop); + + var anchorAnimations = []; + forEach(anchors, function(anchor) { + var outElement = anchor['out']; + var inElement = anchor['in']; + var animator = prepareAnchoredAnimation(classes, outElement, inElement); + if (animator) { + anchorAnimations.push(animator); + } + }); + + // no point in doing anything when there are no elements to animate + if (!fromAnimation && !toAnimation && anchorAnimations.length === 0) return; + + return { + start: function() { + var animationRunners = []; + + if (fromAnimation) { + animationRunners.push(fromAnimation.start()); + } + + if (toAnimation) { + animationRunners.push(toAnimation.start()); + } + + forEach(anchorAnimations, function(animation) { + animationRunners.push(animation.start()); + }); + + var runner = new $$AnimateRunner({ + end: endFn, + cancel: endFn // CSS-driven animations cannot be cancelled, only ended + }); + + $$AnimateRunner.all(animationRunners, function(status) { + runner.complete(status); + }); + + return runner; + + function endFn() { + forEach(animationRunners, function(runner) { + runner.end(); + }); + } + } + }; + } + + function prepareRegularAnimation(animationDetails) { + var element = animationDetails.element; + var options = animationDetails.options || {}; + + if (animationDetails.structural) { + options.event = animationDetails.event; + options.structural = true; + options.applyClassesEarly = true; + + // we special case the leave animation since we want to ensure that + // the element is removed as soon as the animation is over. Otherwise + // a flicker might appear or the element may not be removed at all + if (animationDetails.event === 'leave') { + options.onDone = options.domOperation; + } + } + + // We assign the preparationClasses as the actual animation event since + // the internals of $animateCss will just suffix the event token values + // with `-active` to trigger the animation. + if (options.preparationClasses) { + options.event = concatWithSpace(options.event, options.preparationClasses); + } + + var animator = $animateCss(element, options); + + // the driver lookup code inside of $$animation attempts to spawn a + // driver one by one until a driver returns a.$$willAnimate animator object. + // $animateCss will always return an object, however, it will pass in + // a flag as a hint as to whether an animation was detected or not + return animator.$$willAnimate ? animator : null; + } + }]; +}]; + +// TODO(matsko): use caching here to speed things up for detection +// TODO(matsko): add documentation +// by the time... + +var $$AnimateJsProvider = ['$animateProvider', /** @this */ function($animateProvider) { + this.$get = ['$injector', '$$AnimateRunner', '$$jqLite', + function($injector, $$AnimateRunner, $$jqLite) { + + var applyAnimationClasses = applyAnimationClassesFactory($$jqLite); + // $animateJs(element, 'enter'); + return function(element, event, classes, options) { + var animationClosed = false; + + // the `classes` argument is optional and if it is not used + // then the classes will be resolved from the element's className + // property as well as options.addClass/options.removeClass. + if (arguments.length === 3 && isObject(classes)) { + options = classes; + classes = null; + } + + options = prepareAnimationOptions(options); + if (!classes) { + classes = element.attr('class') || ''; + if (options.addClass) { + classes += ' ' + options.addClass; + } + if (options.removeClass) { + classes += ' ' + options.removeClass; + } + } + + var classesToAdd = options.addClass; + var classesToRemove = options.removeClass; + + // the lookupAnimations function returns a series of animation objects that are + // matched up with one or more of the CSS classes. These animation objects are + // defined via the module.animation factory function. If nothing is detected then + // we don't return anything which then makes $animation query the next driver. + var animations = lookupAnimations(classes); + var before, after; + if (animations.length) { + var afterFn, beforeFn; + if (event === 'leave') { + beforeFn = 'leave'; + afterFn = 'afterLeave'; // TODO(matsko): get rid of this + } else { + beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1); + afterFn = event; + } + + if (event !== 'enter' && event !== 'move') { + before = packageAnimations(element, event, options, animations, beforeFn); + } + after = packageAnimations(element, event, options, animations, afterFn); + } + + // no matching animations + if (!before && !after) return; + + function applyOptions() { + options.domOperation(); + applyAnimationClasses(element, options); + } + + function close() { + animationClosed = true; + applyOptions(); + applyAnimationStyles(element, options); + } + + var runner; + + return { + $$willAnimate: true, + end: function() { + if (runner) { + runner.end(); + } else { + close(); + runner = new $$AnimateRunner(); + runner.complete(true); + } + return runner; + }, + start: function() { + if (runner) { + return runner; + } + + runner = new $$AnimateRunner(); + var closeActiveAnimations; + var chain = []; + + if (before) { + chain.push(function(fn) { + closeActiveAnimations = before(fn); + }); + } + + if (chain.length) { + chain.push(function(fn) { + applyOptions(); + fn(true); + }); + } else { + applyOptions(); + } + + if (after) { + chain.push(function(fn) { + closeActiveAnimations = after(fn); + }); + } + + runner.setHost({ + end: function() { + endAnimations(); + }, + cancel: function() { + endAnimations(true); + } + }); + + $$AnimateRunner.chain(chain, onComplete); + return runner; + + function onComplete(success) { + close(success); + runner.complete(success); + } + + function endAnimations(cancelled) { + if (!animationClosed) { + (closeActiveAnimations || noop)(cancelled); + onComplete(cancelled); + } + } + } + }; + + function executeAnimationFn(fn, element, event, options, onDone) { + var args; + switch (event) { + case 'animate': + args = [element, options.from, options.to, onDone]; + break; + + case 'setClass': + args = [element, classesToAdd, classesToRemove, onDone]; + break; + + case 'addClass': + args = [element, classesToAdd, onDone]; + break; + + case 'removeClass': + args = [element, classesToRemove, onDone]; + break; + + default: + args = [element, onDone]; + break; + } + + args.push(options); + + var value = fn.apply(fn, args); + if (value) { + if (isFunction(value.start)) { + value = value.start(); + } + + if (value instanceof $$AnimateRunner) { + value.done(onDone); + } else if (isFunction(value)) { + // optional onEnd / onCancel callback + return value; + } + } + + return noop; + } + + function groupEventedAnimations(element, event, options, animations, fnName) { + var operations = []; + forEach(animations, function(ani) { + var animation = ani[fnName]; + if (!animation) return; + + // note that all of these animations will run in parallel + operations.push(function() { + var runner; + var endProgressCb; + + var resolved = false; + var onAnimationComplete = function(rejected) { + if (!resolved) { + resolved = true; + (endProgressCb || noop)(rejected); + runner.complete(!rejected); + } + }; + + runner = new $$AnimateRunner({ + end: function() { + onAnimationComplete(); + }, + cancel: function() { + onAnimationComplete(true); + } + }); + + endProgressCb = executeAnimationFn(animation, element, event, options, function(result) { + var cancelled = result === false; + onAnimationComplete(cancelled); + }); + + return runner; + }); + }); + + return operations; + } + + function packageAnimations(element, event, options, animations, fnName) { + var operations = groupEventedAnimations(element, event, options, animations, fnName); + if (operations.length === 0) { + var a, b; + if (fnName === 'beforeSetClass') { + a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass'); + b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass'); + } else if (fnName === 'setClass') { + a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass'); + b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass'); + } + + if (a) { + operations = operations.concat(a); + } + if (b) { + operations = operations.concat(b); + } + } + + if (operations.length === 0) return; + + // TODO(matsko): add documentation + return function startAnimation(callback) { + var runners = []; + if (operations.length) { + forEach(operations, function(animateFn) { + runners.push(animateFn()); + }); + } + + if (runners.length) { + $$AnimateRunner.all(runners, callback); + } else { + callback(); + } + + return function endFn(reject) { + forEach(runners, function(runner) { + if (reject) { + runner.cancel(); + } else { + runner.end(); + } + }); + }; + }; + } + }; + + function lookupAnimations(classes) { + classes = isArray(classes) ? classes : classes.split(' '); + var matches = [], flagMap = {}; + for (var i = 0; i < classes.length; i++) { + var klass = classes[i], + animationFactory = $animateProvider.$$registeredAnimations[klass]; + if (animationFactory && !flagMap[klass]) { + matches.push($injector.get(animationFactory)); + flagMap[klass] = true; + } + } + return matches; + } + }]; +}]; + +var $$AnimateJsDriverProvider = ['$$animationProvider', /** @this */ function($$animationProvider) { + $$animationProvider.drivers.push('$$animateJsDriver'); + this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) { + return function initDriverFn(animationDetails) { + if (animationDetails.from && animationDetails.to) { + var fromAnimation = prepareAnimation(animationDetails.from); + var toAnimation = prepareAnimation(animationDetails.to); + if (!fromAnimation && !toAnimation) return; + + return { + start: function() { + var animationRunners = []; + + if (fromAnimation) { + animationRunners.push(fromAnimation.start()); + } + + if (toAnimation) { + animationRunners.push(toAnimation.start()); + } + + $$AnimateRunner.all(animationRunners, done); + + var runner = new $$AnimateRunner({ + end: endFnFactory(), + cancel: endFnFactory() + }); + + return runner; + + function endFnFactory() { + return function() { + forEach(animationRunners, function(runner) { + // at this point we cannot cancel animations for groups just yet. 1.5+ + runner.end(); + }); + }; + } + + function done(status) { + runner.complete(status); + } + } + }; + } else { + return prepareAnimation(animationDetails); + } + }; + + function prepareAnimation(animationDetails) { + // TODO(matsko): make sure to check for grouped animations and delegate down to normal animations + var element = animationDetails.element; + var event = animationDetails.event; + var options = animationDetails.options; + var classes = animationDetails.classes; + return $$animateJs(element, event, classes, options); + } + }]; +}]; + +var NG_ANIMATE_ATTR_NAME = 'data-ng-animate'; +var NG_ANIMATE_PIN_DATA = '$ngAnimatePin'; +var $$AnimateQueueProvider = ['$animateProvider', /** @this */ function($animateProvider) { + var PRE_DIGEST_STATE = 1; + var RUNNING_STATE = 2; + var ONE_SPACE = ' '; + + var rules = this.rules = { + skip: [], + cancel: [], + join: [] + }; + + function makeTruthyCssClassMap(classString) { + if (!classString) { + return null; + } + + var keys = classString.split(ONE_SPACE); + var map = Object.create(null); + + forEach(keys, function(key) { + map[key] = true; + }); + return map; + } + + function hasMatchingClasses(newClassString, currentClassString) { + if (newClassString && currentClassString) { + var currentClassMap = makeTruthyCssClassMap(currentClassString); + return newClassString.split(ONE_SPACE).some(function(className) { + return currentClassMap[className]; + }); + } + } + + function isAllowed(ruleType, element, currentAnimation, previousAnimation) { + return rules[ruleType].some(function(fn) { + return fn(element, currentAnimation, previousAnimation); + }); + } + + function hasAnimationClasses(animation, and) { + var a = (animation.addClass || '').length > 0; + var b = (animation.removeClass || '').length > 0; + return and ? a && b : a || b; + } + + rules.join.push(function(element, newAnimation, currentAnimation) { + // if the new animation is class-based then we can just tack that on + return !newAnimation.structural && hasAnimationClasses(newAnimation); + }); + + rules.skip.push(function(element, newAnimation, currentAnimation) { + // there is no need to animate anything if no classes are being added and + // there is no structural animation that will be triggered + return !newAnimation.structural && !hasAnimationClasses(newAnimation); + }); + + rules.skip.push(function(element, newAnimation, currentAnimation) { + // why should we trigger a new structural animation if the element will + // be removed from the DOM anyway? + return currentAnimation.event === 'leave' && newAnimation.structural; + }); + + rules.skip.push(function(element, newAnimation, currentAnimation) { + // if there is an ongoing current animation then don't even bother running the class-based animation + return currentAnimation.structural && currentAnimation.state === RUNNING_STATE && !newAnimation.structural; + }); + + rules.cancel.push(function(element, newAnimation, currentAnimation) { + // there can never be two structural animations running at the same time + return currentAnimation.structural && newAnimation.structural; + }); + + rules.cancel.push(function(element, newAnimation, currentAnimation) { + // if the previous animation is already running, but the new animation will + // be triggered, but the new animation is structural + return currentAnimation.state === RUNNING_STATE && newAnimation.structural; + }); + + rules.cancel.push(function(element, newAnimation, currentAnimation) { + // cancel the animation if classes added / removed in both animation cancel each other out, + // but only if the current animation isn't structural + + if (currentAnimation.structural) return false; + + var nA = newAnimation.addClass; + var nR = newAnimation.removeClass; + var cA = currentAnimation.addClass; + var cR = currentAnimation.removeClass; + + // early detection to save the global CPU shortage :) + if ((isUndefined(nA) && isUndefined(nR)) || (isUndefined(cA) && isUndefined(cR))) { + return false; + } + + return hasMatchingClasses(nA, cR) || hasMatchingClasses(nR, cA); + }); + + this.$get = ['$$rAF', '$rootScope', '$rootElement', '$document', '$$HashMap', + '$$animation', '$$AnimateRunner', '$templateRequest', '$$jqLite', '$$forceReflow', + function($$rAF, $rootScope, $rootElement, $document, $$HashMap, + $$animation, $$AnimateRunner, $templateRequest, $$jqLite, $$forceReflow) { + + var activeAnimationsLookup = new $$HashMap(); + var disabledElementsLookup = new $$HashMap(); + var animationsEnabled = null; + + function postDigestTaskFactory() { + var postDigestCalled = false; + return function(fn) { + // we only issue a call to postDigest before + // it has first passed. This prevents any callbacks + // from not firing once the animation has completed + // since it will be out of the digest cycle. + if (postDigestCalled) { + fn(); + } else { + $rootScope.$$postDigest(function() { + postDigestCalled = true; + fn(); + }); + } + }; + } + + // Wait until all directive and route-related templates are downloaded and + // compiled. The $templateRequest.totalPendingRequests variable keeps track of + // all of the remote templates being currently downloaded. If there are no + // templates currently downloading then the watcher will still fire anyway. + var deregisterWatch = $rootScope.$watch( + function() { return $templateRequest.totalPendingRequests === 0; }, + function(isEmpty) { + if (!isEmpty) return; + deregisterWatch(); + + // Now that all templates have been downloaded, $animate will wait until + // the post digest queue is empty before enabling animations. By having two + // calls to $postDigest calls we can ensure that the flag is enabled at the + // very end of the post digest queue. Since all of the animations in $animate + // use $postDigest, it's important that the code below executes at the end. + // This basically means that the page is fully downloaded and compiled before + // any animations are triggered. + $rootScope.$$postDigest(function() { + $rootScope.$$postDigest(function() { + // we check for null directly in the event that the application already called + // .enabled() with whatever arguments that it provided it with + if (animationsEnabled === null) { + animationsEnabled = true; + } + }); + }); + } + ); + + var callbackRegistry = Object.create(null); + + // remember that the classNameFilter is set during the provider/config + // stage therefore we can optimize here and setup a helper function + var classNameFilter = $animateProvider.classNameFilter(); + var isAnimatableClassName = !classNameFilter + ? function() { return true; } + : function(className) { + return classNameFilter.test(className); + }; + + var applyAnimationClasses = applyAnimationClassesFactory($$jqLite); + + function normalizeAnimationDetails(element, animation) { + return mergeAnimationDetails(element, animation, {}); + } + + // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259. + var contains = window.Node.prototype.contains || /** @this */ function(arg) { + // eslint-disable-next-line no-bitwise + return this === arg || !!(this.compareDocumentPosition(arg) & 16); + }; + + function findCallbacks(parent, element, event) { + var targetNode = getDomNode(element); + var targetParentNode = getDomNode(parent); + + var matches = []; + var entries = callbackRegistry[event]; + if (entries) { + forEach(entries, function(entry) { + if (contains.call(entry.node, targetNode)) { + matches.push(entry.callback); + } else if (event === 'leave' && contains.call(entry.node, targetParentNode)) { + matches.push(entry.callback); + } + }); + } + + return matches; + } + + function filterFromRegistry(list, matchContainer, matchCallback) { + var containerNode = extractElementNode(matchContainer); + return list.filter(function(entry) { + var isMatch = entry.node === containerNode && + (!matchCallback || entry.callback === matchCallback); + return !isMatch; + }); + } + + function cleanupEventListeners(phase, element) { + if (phase === 'close' && !element[0].parentNode) { + // If the element is not attached to a parentNode, it has been removed by + // the domOperation, and we can safely remove the event callbacks + $animate.off(element); + } + } + + var $animate = { + on: function(event, container, callback) { + var node = extractElementNode(container); + callbackRegistry[event] = callbackRegistry[event] || []; + callbackRegistry[event].push({ + node: node, + callback: callback + }); + + // Remove the callback when the element is removed from the DOM + jqLite(container).on('$destroy', function() { + var animationDetails = activeAnimationsLookup.get(node); + + if (!animationDetails) { + // If there's an animation ongoing, the callback calling code will remove + // the event listeners. If we'd remove here, the callbacks would be removed + // before the animation ends + $animate.off(event, container, callback); + } + }); + }, + + off: function(event, container, callback) { + if (arguments.length === 1 && !isString(arguments[0])) { + container = arguments[0]; + for (var eventType in callbackRegistry) { + callbackRegistry[eventType] = filterFromRegistry(callbackRegistry[eventType], container); + } + + return; + } + + var entries = callbackRegistry[event]; + if (!entries) return; + + callbackRegistry[event] = arguments.length === 1 + ? null + : filterFromRegistry(entries, container, callback); + }, + + pin: function(element, parentElement) { + assertArg(isElement(element), 'element', 'not an element'); + assertArg(isElement(parentElement), 'parentElement', 'not an element'); + element.data(NG_ANIMATE_PIN_DATA, parentElement); + }, + + push: function(element, event, options, domOperation) { + options = options || {}; + options.domOperation = domOperation; + return queueAnimation(element, event, options); + }, + + // this method has four signatures: + // () - global getter + // (bool) - global setter + // (element) - element getter + // (element, bool) - element setter + enabled: function(element, bool) { + var argCount = arguments.length; + + if (argCount === 0) { + // () - Global getter + bool = !!animationsEnabled; + } else { + var hasElement = isElement(element); + + if (!hasElement) { + // (bool) - Global setter + bool = animationsEnabled = !!element; + } else { + var node = getDomNode(element); + + if (argCount === 1) { + // (element) - Element getter + bool = !disabledElementsLookup.get(node); + } else { + // (element, bool) - Element setter + disabledElementsLookup.put(node, !bool); + } + } + } + + return bool; + } + }; + + return $animate; + + function queueAnimation(element, event, initialOptions) { + // we always make a copy of the options since + // there should never be any side effects on + // the input data when running `$animateCss`. + var options = copy(initialOptions); + + var node, parent; + element = stripCommentsFromElement(element); + if (element) { + node = getDomNode(element); + parent = element.parent(); + } + + options = prepareAnimationOptions(options); + + // we create a fake runner with a working promise. + // These methods will become available after the digest has passed + var runner = new $$AnimateRunner(); + + // this is used to trigger callbacks in postDigest mode + var runInNextPostDigestOrNow = postDigestTaskFactory(); + + if (isArray(options.addClass)) { + options.addClass = options.addClass.join(' '); + } + + if (options.addClass && !isString(options.addClass)) { + options.addClass = null; + } + + if (isArray(options.removeClass)) { + options.removeClass = options.removeClass.join(' '); + } + + if (options.removeClass && !isString(options.removeClass)) { + options.removeClass = null; + } + + if (options.from && !isObject(options.from)) { + options.from = null; + } + + if (options.to && !isObject(options.to)) { + options.to = null; + } + + // there are situations where a directive issues an animation for + // a jqLite wrapper that contains only comment nodes... If this + // happens then there is no way we can perform an animation + if (!node) { + close(); + return runner; + } + + var className = [node.className, options.addClass, options.removeClass].join(' '); + if (!isAnimatableClassName(className)) { + close(); + return runner; + } + + var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0; + + var documentHidden = $document[0].hidden; + + // this is a hard disable of all animations for the application or on + // the element itself, therefore there is no need to continue further + // past this point if not enabled + // Animations are also disabled if the document is currently hidden (page is not visible + // to the user), because browsers slow down or do not flush calls to requestAnimationFrame + var skipAnimations = !animationsEnabled || documentHidden || disabledElementsLookup.get(node); + var existingAnimation = (!skipAnimations && activeAnimationsLookup.get(node)) || {}; + var hasExistingAnimation = !!existingAnimation.state; + + // there is no point in traversing the same collection of parent ancestors if a followup + // animation will be run on the same element that already did all that checking work + if (!skipAnimations && (!hasExistingAnimation || existingAnimation.state !== PRE_DIGEST_STATE)) { + skipAnimations = !areAnimationsAllowed(element, parent, event); + } + + if (skipAnimations) { + // Callbacks should fire even if the document is hidden (regression fix for issue #14120) + if (documentHidden) notifyProgress(runner, event, 'start'); + close(); + if (documentHidden) notifyProgress(runner, event, 'close'); + return runner; + } + + if (isStructural) { + closeChildAnimations(element); + } + + var newAnimation = { + structural: isStructural, + element: element, + event: event, + addClass: options.addClass, + removeClass: options.removeClass, + close: close, + options: options, + runner: runner + }; + + if (hasExistingAnimation) { + var skipAnimationFlag = isAllowed('skip', element, newAnimation, existingAnimation); + if (skipAnimationFlag) { + if (existingAnimation.state === RUNNING_STATE) { + close(); + return runner; + } else { + mergeAnimationDetails(element, existingAnimation, newAnimation); + return existingAnimation.runner; + } + } + var cancelAnimationFlag = isAllowed('cancel', element, newAnimation, existingAnimation); + if (cancelAnimationFlag) { + if (existingAnimation.state === RUNNING_STATE) { + // this will end the animation right away and it is safe + // to do so since the animation is already running and the + // runner callback code will run in async + existingAnimation.runner.end(); + } else if (existingAnimation.structural) { + // this means that the animation is queued into a digest, but + // hasn't started yet. Therefore it is safe to run the close + // method which will call the runner methods in async. + existingAnimation.close(); + } else { + // this will merge the new animation options into existing animation options + mergeAnimationDetails(element, existingAnimation, newAnimation); + + return existingAnimation.runner; + } + } else { + // a joined animation means that this animation will take over the existing one + // so an example would involve a leave animation taking over an enter. Then when + // the postDigest kicks in the enter will be ignored. + var joinAnimationFlag = isAllowed('join', element, newAnimation, existingAnimation); + if (joinAnimationFlag) { + if (existingAnimation.state === RUNNING_STATE) { + normalizeAnimationDetails(element, newAnimation); + } else { + applyGeneratedPreparationClasses(element, isStructural ? event : null, options); + + event = newAnimation.event = existingAnimation.event; + options = mergeAnimationDetails(element, existingAnimation, newAnimation); + + //we return the same runner since only the option values of this animation will + //be fed into the `existingAnimation`. + return existingAnimation.runner; + } + } + } + } else { + // normalization in this case means that it removes redundant CSS classes that + // already exist (addClass) or do not exist (removeClass) on the element + normalizeAnimationDetails(element, newAnimation); + } + + // when the options are merged and cleaned up we may end up not having to do + // an animation at all, therefore we should check this before issuing a post + // digest callback. Structural animations will always run no matter what. + var isValidAnimation = newAnimation.structural; + if (!isValidAnimation) { + // animate (from/to) can be quickly checked first, otherwise we check if any classes are present + isValidAnimation = (newAnimation.event === 'animate' && Object.keys(newAnimation.options.to || {}).length > 0) + || hasAnimationClasses(newAnimation); + } + + if (!isValidAnimation) { + close(); + clearElementAnimationState(element); + return runner; + } + + // the counter keeps track of cancelled animations + var counter = (existingAnimation.counter || 0) + 1; + newAnimation.counter = counter; + + markElementAnimationState(element, PRE_DIGEST_STATE, newAnimation); + + $rootScope.$$postDigest(function() { + var animationDetails = activeAnimationsLookup.get(node); + var animationCancelled = !animationDetails; + animationDetails = animationDetails || {}; + + // if addClass/removeClass is called before something like enter then the + // registered parent element may not be present. The code below will ensure + // that a final value for parent element is obtained + var parentElement = element.parent() || []; + + // animate/structural/class-based animations all have requirements. Otherwise there + // is no point in performing an animation. The parent node must also be set. + var isValidAnimation = parentElement.length > 0 + && (animationDetails.event === 'animate' + || animationDetails.structural + || hasAnimationClasses(animationDetails)); + + // this means that the previous animation was cancelled + // even if the follow-up animation is the same event + if (animationCancelled || animationDetails.counter !== counter || !isValidAnimation) { + // if another animation did not take over then we need + // to make sure that the domOperation and options are + // handled accordingly + if (animationCancelled) { + applyAnimationClasses(element, options); + applyAnimationStyles(element, options); + } + + // if the event changed from something like enter to leave then we do + // it, otherwise if it's the same then the end result will be the same too + if (animationCancelled || (isStructural && animationDetails.event !== event)) { + options.domOperation(); + runner.end(); + } + + // in the event that the element animation was not cancelled or a follow-up animation + // isn't allowed to animate from here then we need to clear the state of the element + // so that any future animations won't read the expired animation data. + if (!isValidAnimation) { + clearElementAnimationState(element); + } + + return; + } + + // this combined multiple class to addClass / removeClass into a setClass event + // so long as a structural event did not take over the animation + event = !animationDetails.structural && hasAnimationClasses(animationDetails, true) + ? 'setClass' + : animationDetails.event; + + markElementAnimationState(element, RUNNING_STATE); + var realRunner = $$animation(element, event, animationDetails.options); + + // this will update the runner's flow-control events based on + // the `realRunner` object. + runner.setHost(realRunner); + notifyProgress(runner, event, 'start', {}); + + realRunner.done(function(status) { + close(!status); + var animationDetails = activeAnimationsLookup.get(node); + if (animationDetails && animationDetails.counter === counter) { + clearElementAnimationState(getDomNode(element)); + } + notifyProgress(runner, event, 'close', {}); + }); + }); + + return runner; + + function notifyProgress(runner, event, phase, data) { + runInNextPostDigestOrNow(function() { + var callbacks = findCallbacks(parent, element, event); + if (callbacks.length) { + // do not optimize this call here to RAF because + // we don't know how heavy the callback code here will + // be and if this code is buffered then this can + // lead to a performance regression. + $$rAF(function() { + forEach(callbacks, function(callback) { + callback(element, phase, data); + }); + cleanupEventListeners(phase, element); + }); + } else { + cleanupEventListeners(phase, element); + } + }); + runner.progress(event, phase, data); + } + + function close(reject) { + clearGeneratedClasses(element, options); + applyAnimationClasses(element, options); + applyAnimationStyles(element, options); + options.domOperation(); + runner.complete(!reject); + } + } + + function closeChildAnimations(element) { + var node = getDomNode(element); + var children = node.querySelectorAll('[' + NG_ANIMATE_ATTR_NAME + ']'); + forEach(children, function(child) { + var state = parseInt(child.getAttribute(NG_ANIMATE_ATTR_NAME), 10); + var animationDetails = activeAnimationsLookup.get(child); + if (animationDetails) { + switch (state) { + case RUNNING_STATE: + animationDetails.runner.end(); + /* falls through */ + case PRE_DIGEST_STATE: + activeAnimationsLookup.remove(child); + break; + } + } + }); + } + + function clearElementAnimationState(element) { + var node = getDomNode(element); + node.removeAttribute(NG_ANIMATE_ATTR_NAME); + activeAnimationsLookup.remove(node); + } + + function isMatchingElement(nodeOrElmA, nodeOrElmB) { + return getDomNode(nodeOrElmA) === getDomNode(nodeOrElmB); + } + + /** + * This fn returns false if any of the following is true: + * a) animations on any parent element are disabled, and animations on the element aren't explicitly allowed + * b) a parent element has an ongoing structural animation, and animateChildren is false + * c) the element is not a child of the body + * d) the element is not a child of the $rootElement + */ + function areAnimationsAllowed(element, parentElement, event) { + var bodyElement = jqLite($document[0].body); + var bodyElementDetected = isMatchingElement(element, bodyElement) || element[0].nodeName === 'HTML'; + var rootElementDetected = isMatchingElement(element, $rootElement); + var parentAnimationDetected = false; + var animateChildren; + var elementDisabled = disabledElementsLookup.get(getDomNode(element)); + + var parentHost = jqLite.data(element[0], NG_ANIMATE_PIN_DATA); + if (parentHost) { + parentElement = parentHost; + } + + parentElement = getDomNode(parentElement); + + while (parentElement) { + if (!rootElementDetected) { + // angular doesn't want to attempt to animate elements outside of the application + // therefore we need to ensure that the rootElement is an ancestor of the current element + rootElementDetected = isMatchingElement(parentElement, $rootElement); + } + + if (parentElement.nodeType !== ELEMENT_NODE) { + // no point in inspecting the #document element + break; + } + + var details = activeAnimationsLookup.get(parentElement) || {}; + // either an enter, leave or move animation will commence + // therefore we can't allow any animations to take place + // but if a parent animation is class-based then that's ok + if (!parentAnimationDetected) { + var parentElementDisabled = disabledElementsLookup.get(parentElement); + + if (parentElementDisabled === true && elementDisabled !== false) { + // disable animations if the user hasn't explicitly enabled animations on the + // current element + elementDisabled = true; + // element is disabled via parent element, no need to check anything else + break; + } else if (parentElementDisabled === false) { + elementDisabled = false; + } + parentAnimationDetected = details.structural; + } + + if (isUndefined(animateChildren) || animateChildren === true) { + var value = jqLite.data(parentElement, NG_ANIMATE_CHILDREN_DATA); + if (isDefined(value)) { + animateChildren = value; + } + } + + // there is no need to continue traversing at this point + if (parentAnimationDetected && animateChildren === false) break; + + if (!bodyElementDetected) { + // we also need to ensure that the element is or will be a part of the body element + // otherwise it is pointless to even issue an animation to be rendered + bodyElementDetected = isMatchingElement(parentElement, bodyElement); + } + + if (bodyElementDetected && rootElementDetected) { + // If both body and root have been found, any other checks are pointless, + // as no animation data should live outside the application + break; + } + + if (!rootElementDetected) { + // If no rootElement is detected, check if the parentElement is pinned to another element + parentHost = jqLite.data(parentElement, NG_ANIMATE_PIN_DATA); + if (parentHost) { + // The pin target element becomes the next parent element + parentElement = getDomNode(parentHost); + continue; + } + } + + parentElement = parentElement.parentNode; + } + + var allowAnimation = (!parentAnimationDetected || animateChildren) && elementDisabled !== true; + return allowAnimation && rootElementDetected && bodyElementDetected; + } + + function markElementAnimationState(element, state, details) { + details = details || {}; + details.state = state; + + var node = getDomNode(element); + node.setAttribute(NG_ANIMATE_ATTR_NAME, state); + + var oldValue = activeAnimationsLookup.get(node); + var newValue = oldValue + ? extend(oldValue, details) + : details; + activeAnimationsLookup.put(node, newValue); + } + }]; +}]; + +/* exported $$AnimationProvider */ + +var $$AnimationProvider = ['$animateProvider', /** @this */ function($animateProvider) { + var NG_ANIMATE_REF_ATTR = 'ng-animate-ref'; + + var drivers = this.drivers = []; + + var RUNNER_STORAGE_KEY = '$$animationRunner'; + + function setRunner(element, runner) { + element.data(RUNNER_STORAGE_KEY, runner); + } + + function removeRunner(element) { + element.removeData(RUNNER_STORAGE_KEY); + } + + function getRunner(element) { + return element.data(RUNNER_STORAGE_KEY); + } + + this.$get = ['$$jqLite', '$rootScope', '$injector', '$$AnimateRunner', '$$HashMap', '$$rAFScheduler', + function($$jqLite, $rootScope, $injector, $$AnimateRunner, $$HashMap, $$rAFScheduler) { + + var animationQueue = []; + var applyAnimationClasses = applyAnimationClassesFactory($$jqLite); + + function sortAnimations(animations) { + var tree = { children: [] }; + var i, lookup = new $$HashMap(); + + // this is done first beforehand so that the hashmap + // is filled with a list of the elements that will be animated + for (i = 0; i < animations.length; i++) { + var animation = animations[i]; + lookup.put(animation.domNode, animations[i] = { + domNode: animation.domNode, + fn: animation.fn, + children: [] + }); + } + + for (i = 0; i < animations.length; i++) { + processNode(animations[i]); + } + + return flatten(tree); + + function processNode(entry) { + if (entry.processed) return entry; + entry.processed = true; + + var elementNode = entry.domNode; + var parentNode = elementNode.parentNode; + lookup.put(elementNode, entry); + + var parentEntry; + while (parentNode) { + parentEntry = lookup.get(parentNode); + if (parentEntry) { + if (!parentEntry.processed) { + parentEntry = processNode(parentEntry); + } + break; + } + parentNode = parentNode.parentNode; + } + + (parentEntry || tree).children.push(entry); + return entry; + } + + function flatten(tree) { + var result = []; + var queue = []; + var i; + + for (i = 0; i < tree.children.length; i++) { + queue.push(tree.children[i]); + } + + var remainingLevelEntries = queue.length; + var nextLevelEntries = 0; + var row = []; + + for (i = 0; i < queue.length; i++) { + var entry = queue[i]; + if (remainingLevelEntries <= 0) { + remainingLevelEntries = nextLevelEntries; + nextLevelEntries = 0; + result.push(row); + row = []; + } + row.push(entry.fn); + entry.children.forEach(function(childEntry) { + nextLevelEntries++; + queue.push(childEntry); + }); + remainingLevelEntries--; + } + + if (row.length) { + result.push(row); + } + + return result; + } + } + + // TODO(matsko): document the signature in a better way + return function(element, event, options) { + options = prepareAnimationOptions(options); + var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0; + + // there is no animation at the current moment, however + // these runner methods will get later updated with the + // methods leading into the driver's end/cancel methods + // for now they just stop the animation from starting + var runner = new $$AnimateRunner({ + end: function() { close(); }, + cancel: function() { close(true); } + }); + + if (!drivers.length) { + close(); + return runner; + } + + setRunner(element, runner); + + var classes = mergeClasses(element.attr('class'), mergeClasses(options.addClass, options.removeClass)); + var tempClasses = options.tempClasses; + if (tempClasses) { + classes += ' ' + tempClasses; + options.tempClasses = null; + } + + var prepareClassName; + if (isStructural) { + prepareClassName = 'ng-' + event + PREPARE_CLASS_SUFFIX; + $$jqLite.addClass(element, prepareClassName); + } + + animationQueue.push({ + // this data is used by the postDigest code and passed into + // the driver step function + element: element, + classes: classes, + event: event, + structural: isStructural, + options: options, + beforeStart: beforeStart, + close: close + }); + + element.on('$destroy', handleDestroyedElement); + + // we only want there to be one function called within the post digest + // block. This way we can group animations for all the animations that + // were apart of the same postDigest flush call. + if (animationQueue.length > 1) return runner; + + $rootScope.$$postDigest(function() { + var animations = []; + forEach(animationQueue, function(entry) { + // the element was destroyed early on which removed the runner + // form its storage. This means we can't animate this element + // at all and it already has been closed due to destruction. + if (getRunner(entry.element)) { + animations.push(entry); + } else { + entry.close(); + } + }); + + // now any future animations will be in another postDigest + animationQueue.length = 0; + + var groupedAnimations = groupAnimations(animations); + var toBeSortedAnimations = []; + + forEach(groupedAnimations, function(animationEntry) { + toBeSortedAnimations.push({ + domNode: getDomNode(animationEntry.from ? animationEntry.from.element : animationEntry.element), + fn: function triggerAnimationStart() { + // it's important that we apply the `ng-animate` CSS class and the + // temporary classes before we do any driver invoking since these + // CSS classes may be required for proper CSS detection. + animationEntry.beforeStart(); + + var startAnimationFn, closeFn = animationEntry.close; + + // in the event that the element was removed before the digest runs or + // during the RAF sequencing then we should not trigger the animation. + var targetElement = animationEntry.anchors + ? (animationEntry.from.element || animationEntry.to.element) + : animationEntry.element; + + if (getRunner(targetElement)) { + var operation = invokeFirstDriver(animationEntry); + if (operation) { + startAnimationFn = operation.start; + } + } + + if (!startAnimationFn) { + closeFn(); + } else { + var animationRunner = startAnimationFn(); + animationRunner.done(function(status) { + closeFn(!status); + }); + updateAnimationRunners(animationEntry, animationRunner); + } + } + }); + }); + + // we need to sort each of the animations in order of parent to child + // relationships. This ensures that the child classes are applied at the + // right time. + $$rAFScheduler(sortAnimations(toBeSortedAnimations)); + }); + + return runner; + + // TODO(matsko): change to reference nodes + function getAnchorNodes(node) { + var SELECTOR = '[' + NG_ANIMATE_REF_ATTR + ']'; + var items = node.hasAttribute(NG_ANIMATE_REF_ATTR) + ? [node] + : node.querySelectorAll(SELECTOR); + var anchors = []; + forEach(items, function(node) { + var attr = node.getAttribute(NG_ANIMATE_REF_ATTR); + if (attr && attr.length) { + anchors.push(node); + } + }); + return anchors; + } + + function groupAnimations(animations) { + var preparedAnimations = []; + var refLookup = {}; + forEach(animations, function(animation, index) { + var element = animation.element; + var node = getDomNode(element); + var event = animation.event; + var enterOrMove = ['enter', 'move'].indexOf(event) >= 0; + var anchorNodes = animation.structural ? getAnchorNodes(node) : []; + + if (anchorNodes.length) { + var direction = enterOrMove ? 'to' : 'from'; + + forEach(anchorNodes, function(anchor) { + var key = anchor.getAttribute(NG_ANIMATE_REF_ATTR); + refLookup[key] = refLookup[key] || {}; + refLookup[key][direction] = { + animationID: index, + element: jqLite(anchor) + }; + }); + } else { + preparedAnimations.push(animation); + } + }); + + var usedIndicesLookup = {}; + var anchorGroups = {}; + forEach(refLookup, function(operations, key) { + var from = operations.from; + var to = operations.to; + + if (!from || !to) { + // only one of these is set therefore we can't have an + // anchor animation since all three pieces are required + var index = from ? from.animationID : to.animationID; + var indexKey = index.toString(); + if (!usedIndicesLookup[indexKey]) { + usedIndicesLookup[indexKey] = true; + preparedAnimations.push(animations[index]); + } + return; + } + + var fromAnimation = animations[from.animationID]; + var toAnimation = animations[to.animationID]; + var lookupKey = from.animationID.toString(); + if (!anchorGroups[lookupKey]) { + var group = anchorGroups[lookupKey] = { + structural: true, + beforeStart: function() { + fromAnimation.beforeStart(); + toAnimation.beforeStart(); + }, + close: function() { + fromAnimation.close(); + toAnimation.close(); + }, + classes: cssClassesIntersection(fromAnimation.classes, toAnimation.classes), + from: fromAnimation, + to: toAnimation, + anchors: [] // TODO(matsko): change to reference nodes + }; + + // the anchor animations require that the from and to elements both have at least + // one shared CSS class which effectively marries the two elements together to use + // the same animation driver and to properly sequence the anchor animation. + if (group.classes.length) { + preparedAnimations.push(group); + } else { + preparedAnimations.push(fromAnimation); + preparedAnimations.push(toAnimation); + } + } + + anchorGroups[lookupKey].anchors.push({ + 'out': from.element, 'in': to.element + }); + }); + + return preparedAnimations; + } + + function cssClassesIntersection(a,b) { + a = a.split(' '); + b = b.split(' '); + var matches = []; + + for (var i = 0; i < a.length; i++) { + var aa = a[i]; + if (aa.substring(0,3) === 'ng-') continue; + + for (var j = 0; j < b.length; j++) { + if (aa === b[j]) { + matches.push(aa); + break; + } + } + } + + return matches.join(' '); + } + + function invokeFirstDriver(animationDetails) { + // we loop in reverse order since the more general drivers (like CSS and JS) + // may attempt more elements, but custom drivers are more particular + for (var i = drivers.length - 1; i >= 0; i--) { + var driverName = drivers[i]; + var factory = $injector.get(driverName); + var driver = factory(animationDetails); + if (driver) { + return driver; + } + } + } + + function beforeStart() { + element.addClass(NG_ANIMATE_CLASSNAME); + if (tempClasses) { + $$jqLite.addClass(element, tempClasses); + } + if (prepareClassName) { + $$jqLite.removeClass(element, prepareClassName); + prepareClassName = null; + } + } + + function updateAnimationRunners(animation, newRunner) { + if (animation.from && animation.to) { + update(animation.from.element); + update(animation.to.element); + } else { + update(animation.element); + } + + function update(element) { + var runner = getRunner(element); + if (runner) runner.setHost(newRunner); + } + } + + function handleDestroyedElement() { + var runner = getRunner(element); + if (runner && (event !== 'leave' || !options.$$domOperationFired)) { + runner.end(); + } + } + + function close(rejected) { + element.off('$destroy', handleDestroyedElement); + removeRunner(element); + + applyAnimationClasses(element, options); + applyAnimationStyles(element, options); + options.domOperation(); + + if (tempClasses) { + $$jqLite.removeClass(element, tempClasses); + } + + element.removeClass(NG_ANIMATE_CLASSNAME); + runner.complete(!rejected); + } + }; + }]; +}]; + +/** + * @ngdoc directive + * @name ngAnimateSwap + * @restrict A + * @scope + * + * @description + * + * ngAnimateSwap is a animation-oriented directive that allows for the container to + * be removed and entered in whenever the associated expression changes. A + * common usecase for this directive is a rotating banner or slider component which + * contains one image being present at a time. When the active image changes + * then the old image will perform a `leave` animation and the new element + * will be inserted via an `enter` animation. + * + * @animations + * | Animation | Occurs | + * |----------------------------------|--------------------------------------| + * | {@link ng.$animate#enter enter} | when the new element is inserted to the DOM | + * | {@link ng.$animate#leave leave} | when the old element is removed from the DOM | + * + * @example + * + * + *
      + *
      + * {{ number }} + *
      + *
      + *
      + * + * angular.module('ngAnimateSwapExample', ['ngAnimate']) + * .controller('AppCtrl', ['$scope', '$interval', function($scope, $interval) { + * $scope.number = 0; + * $interval(function() { + * $scope.number++; + * }, 1000); + * + * var colors = ['red','blue','green','yellow','orange']; + * $scope.colorClass = function(number) { + * return colors[number % colors.length]; + * }; + * }]); + * + * + * .container { + * height:250px; + * width:250px; + * position:relative; + * overflow:hidden; + * border:2px solid black; + * } + * .container .cell { + * font-size:150px; + * text-align:center; + * line-height:250px; + * position:absolute; + * top:0; + * left:0; + * right:0; + * border-bottom:2px solid black; + * } + * .swap-animation.ng-enter, .swap-animation.ng-leave { + * transition:0.5s linear all; + * } + * .swap-animation.ng-enter { + * top:-250px; + * } + * .swap-animation.ng-enter-active { + * top:0px; + * } + * .swap-animation.ng-leave { + * top:0px; + * } + * .swap-animation.ng-leave-active { + * top:250px; + * } + * .red { background:red; } + * .green { background:green; } + * .blue { background:blue; } + * .yellow { background:yellow; } + * .orange { background:orange; } + * + *
      + */ +var ngAnimateSwapDirective = ['$animate', '$rootScope', function($animate, $rootScope) { + return { + restrict: 'A', + transclude: 'element', + terminal: true, + priority: 600, // we use 600 here to ensure that the directive is caught before others + link: function(scope, $element, attrs, ctrl, $transclude) { + var previousElement, previousScope; + scope.$watchCollection(attrs.ngAnimateSwap || attrs['for'], function(value) { + if (previousElement) { + $animate.leave(previousElement); + } + if (previousScope) { + previousScope.$destroy(); + previousScope = null; + } + if (value || value === 0) { + previousScope = scope.$new(); + $transclude(previousScope, function(element) { + previousElement = element; + $animate.enter(element, null, $element); + }); + } + }); + } + }; +}]; + +/** + * @ngdoc module + * @name ngAnimate + * @description + * + * The `ngAnimate` module provides support for CSS-based animations (keyframes and transitions) as well as JavaScript-based animations via + * callback hooks. Animations are not enabled by default, however, by including `ngAnimate` the animation hooks are enabled for an Angular app. + * + *
      + * + * # Usage + * Simply put, there are two ways to make use of animations when ngAnimate is used: by using **CSS** and **JavaScript**. The former works purely based + * using CSS (by using matching CSS selectors/styles) and the latter triggers animations that are registered via `module.animation()`. For + * both CSS and JS animations the sole requirement is to have a matching `CSS class` that exists both in the registered animation and within + * the HTML element that the animation will be triggered on. + * + * ## Directive Support + * The following directives are "animation aware": + * + * | Directive | Supported Animations | + * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------| + * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move | + * | {@link ngRoute.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:ngClass#animations ngClass} | add and remove (the CSS class(es) present) | + * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide} | add and remove (the ng-hide class value) | + * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) | + * | {@link module:ngMessages#animations ngMessages} | add and remove (ng-active & ng-inactive) | + * | {@link module:ngMessages#animations ngMessage} | enter and leave | + * + * (More information can be found by visiting each the documentation associated with each directive.) + * + * ## CSS-based Animations + * + * CSS-based animations with ngAnimate are unique since they require no JavaScript code at all. By using a CSS class that we reference between our HTML + * and CSS code we can create an animation that will be picked up by Angular when an underlying directive performs an operation. + * + * The example below shows how an `enter` animation can be made possible on an element using `ng-if`: + * + * ```html + *
      + * Fade me in out + *
      + * + * + * ``` + * + * Notice the CSS class **fade**? We can now create the CSS transition code that references this class: + * + * ```css + * /* The starting CSS styles for the enter animation */ + * .fade.ng-enter { + * transition:0.5s linear all; + * opacity:0; + * } + * + * /* The finishing CSS styles for the enter animation */ + * .fade.ng-enter.ng-enter-active { + * opacity:1; + * } + * ``` + * + * The key thing to remember here is that, depending on the animation event (which each of the directives above trigger depending on what's going on) two + * generated CSS classes will be applied to the element; in the example above we have `.ng-enter` and `.ng-enter-active`. For CSS transitions, the transition + * code **must** be defined within the starting CSS class (in this case `.ng-enter`). The destination class is what the transition will animate towards. + * + * If for example we wanted to create animations for `leave` and `move` (ngRepeat triggers move) then we can do so using the same CSS naming conventions: + * + * ```css + * /* now the element will fade out before it is removed from the DOM */ + * .fade.ng-leave { + * transition:0.5s linear all; + * opacity:1; + * } + * .fade.ng-leave.ng-leave-active { + * opacity:0; + * } + * ``` + * + * We can also make use of **CSS Keyframes** by referencing the keyframe animation within the starting CSS class: + * + * ```css + * /* there is no need to define anything inside of the destination + * CSS class since the keyframe will take charge of the animation */ + * .fade.ng-leave { + * animation: my_fade_animation 0.5s linear; + * -webkit-animation: my_fade_animation 0.5s linear; + * } + * + * @keyframes my_fade_animation { + * from { opacity:1; } + * to { opacity:0; } + * } + * + * @-webkit-keyframes my_fade_animation { + * from { opacity:1; } + * to { opacity:0; } + * } + * ``` + * + * Feel free also mix transitions and keyframes together as well as any other CSS classes on the same element. + * + * ### CSS Class-based Animations + * + * Class-based animations (animations that are triggered via `ngClass`, `ngShow`, `ngHide` and some other directives) have a slightly different + * naming convention. Class-based animations are basic enough that a standard transition or keyframe can be referenced on the class being added + * and removed. + * + * For example if we wanted to do a CSS animation for `ngHide` then we place an animation on the `.ng-hide` CSS class: + * + * ```html + *
      + * Show and hide me + *
      + * + * + * + * ``` + * + * All that is going on here with ngShow/ngHide behind the scenes is the `.ng-hide` class is added/removed (when the hidden state is valid). Since + * ngShow and ngHide are animation aware then we can match up a transition and ngAnimate handles the rest. + * + * In addition the addition and removal of the CSS class, ngAnimate also provides two helper methods that we can use to further decorate the animation + * with CSS styles. + * + * ```html + *
      + * Highlight this box + *
      + * + * + * + * ``` + * + * We can also make use of CSS keyframes by placing them within the CSS classes. + * + * + * ### CSS Staggering Animations + * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a + * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be + * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for + * the animation. The style property expected within the stagger class can either be a **transition-delay** or an + * **animation-delay** property (or both if your animation contains both transitions and keyframe animations). + * + * ```css + * .my-animation.ng-enter { + * /* standard transition code */ + * transition: 1s linear all; + * opacity:0; + * } + * .my-animation.ng-enter-stagger { + * /* this will have a 100ms delay between each successive leave animation */ + * transition-delay: 0.1s; + * + * /* As of 1.4.4, this must always be set: it signals ngAnimate + * to not accidentally inherit a delay property from another CSS class */ + * transition-duration: 0s; + * } + * .my-animation.ng-enter.ng-enter-active { + * /* standard transition styles */ + * opacity:1; + * } + * ``` + * + * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations + * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this + * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation + * will also be reset if one or more animation frames have passed since the multiple calls to `$animate` were fired. + * + * The following code will issue the **ng-leave-stagger** event on the element provided: + * + * ```js + * var kids = parent.children(); + * + * $animate.leave(kids[0]); //stagger index=0 + * $animate.leave(kids[1]); //stagger index=1 + * $animate.leave(kids[2]); //stagger index=2 + * $animate.leave(kids[3]); //stagger index=3 + * $animate.leave(kids[4]); //stagger index=4 + * + * window.requestAnimationFrame(function() { + * //stagger has reset itself + * $animate.leave(kids[5]); //stagger index=0 + * $animate.leave(kids[6]); //stagger index=1 + * + * $scope.$digest(); + * }); + * ``` + * + * Stagger animations are currently only supported within CSS-defined animations. + * + * ### The `ng-animate` CSS class + * + * When ngAnimate is animating an element it will apply the `ng-animate` CSS class to the element for the duration of the animation. + * This is a temporary CSS class and it will be removed once the animation is over (for both JavaScript and CSS-based animations). + * + * Therefore, animations can be applied to an element using this temporary class directly via CSS. + * + * ```css + * .zipper.ng-animate { + * transition:0.5s linear all; + * } + * .zipper.ng-enter { + * opacity:0; + * } + * .zipper.ng-enter.ng-enter-active { + * opacity:1; + * } + * .zipper.ng-leave { + * opacity:1; + * } + * .zipper.ng-leave.ng-leave-active { + * opacity:0; + * } + * ``` + * + * (Note that the `ng-animate` CSS class is reserved and it cannot be applied on an element directly since ngAnimate will always remove + * the CSS class once an animation has completed.) + * + * + * ### The `ng-[event]-prepare` class + * + * This is a special class that can be used to prevent unwanted flickering / flash of content before + * the actual animation starts. The class is added as soon as an animation is initialized, but removed + * before the actual animation starts (after waiting for a $digest). + * It is also only added for *structural* animations (`enter`, `move`, and `leave`). + * + * In practice, flickering can appear when nesting elements with structural animations such as `ngIf` + * into elements that have class-based animations such as `ngClass`. + * + * ```html + *
      + *
      + *
      + *
      + *
      + * ``` + * + * It is possible that during the `enter` animation, the `.message` div will be briefly visible before it starts animating. + * In that case, you can add styles to the CSS that make sure the element stays hidden before the animation starts: + * + * ```css + * .message.ng-enter-prepare { + * opacity: 0; + * } + * + * ``` + * + * ## JavaScript-based Animations + * + * ngAnimate also allows for animations to be consumed by JavaScript code. The approach is similar to CSS-based animations (where there is a shared + * CSS class that is referenced in our HTML code) but in addition we need to register the JavaScript animation on the module. By making use of the + * `module.animation()` module function we can register the animation. + * + * Let's see an example of a enter/leave animation using `ngRepeat`: + * + * ```html + *
      + * {{ item }} + *
      + * ``` + * + * See the **slide** CSS class? Let's use that class to define an animation that we'll structure in our module code by using `module.animation`: + * + * ```js + * myModule.animation('.slide', [function() { + * return { + * // make note that other events (like addClass/removeClass) + * // have different function input parameters + * enter: function(element, doneFn) { + * jQuery(element).fadeIn(1000, doneFn); + * + * // remember to call doneFn so that angular + * // knows that the animation has concluded + * }, + * + * move: function(element, doneFn) { + * jQuery(element).fadeIn(1000, doneFn); + * }, + * + * leave: function(element, doneFn) { + * jQuery(element).fadeOut(1000, doneFn); + * } + * } + * }]); + * ``` + * + * The nice thing about JS-based animations is that we can inject other services and make use of advanced animation libraries such as + * greensock.js and velocity.js. + * + * If our animation code class-based (meaning that something like `ngClass`, `ngHide` and `ngShow` triggers it) then we can still define + * our animations inside of the same registered animation, however, the function input arguments are a bit different: + * + * ```html + *
      + * this box is moody + *
      + * + * + * + * ``` + * + * ```js + * myModule.animation('.colorful', [function() { + * return { + * addClass: function(element, className, doneFn) { + * // do some cool animation and call the doneFn + * }, + * removeClass: function(element, className, doneFn) { + * // do some cool animation and call the doneFn + * }, + * setClass: function(element, addedClass, removedClass, doneFn) { + * // do some cool animation and call the doneFn + * } + * } + * }]); + * ``` + * + * ## CSS + JS Animations Together + * + * AngularJS 1.4 and higher has taken steps to make the amalgamation of CSS and JS animations more flexible. However, unlike earlier versions of Angular, + * defining CSS and JS animations to work off of the same CSS class will not work anymore. Therefore the example below will only result in **JS animations taking + * charge of the animation**: + * + * ```html + *
      + * Slide in and out + *
      + * ``` + * + * ```js + * myModule.animation('.slide', [function() { + * return { + * enter: function(element, doneFn) { + * jQuery(element).slideIn(1000, doneFn); + * } + * } + * }]); + * ``` + * + * ```css + * .slide.ng-enter { + * transition:0.5s linear all; + * transform:translateY(-100px); + * } + * .slide.ng-enter.ng-enter-active { + * transform:translateY(0); + * } + * ``` + * + * Does this mean that CSS and JS animations cannot be used together? Do JS-based animations always have higher priority? We can make up for the + * lack of CSS animations by using the `$animateCss` service to trigger our own tweaked-out, CSS-based animations directly from + * our own JS-based animation code: + * + * ```js + * myModule.animation('.slide', ['$animateCss', function($animateCss) { + * return { + * enter: function(element) { +* // this will trigger `.slide.ng-enter` and `.slide.ng-enter-active`. + * return $animateCss(element, { + * event: 'enter', + * structural: true + * }); + * } + * } + * }]); + * ``` + * + * The nice thing here is that we can save bandwidth by sticking to our CSS-based animation code and we don't need to rely on a 3rd-party animation framework. + * + * The `$animateCss` service is very powerful since we can feed in all kinds of extra properties that will be evaluated and fed into a CSS transition or + * keyframe animation. For example if we wanted to animate the height of an element while adding and removing classes then we can do so by providing that + * data into `$animateCss` directly: + * + * ```js + * myModule.animation('.slide', ['$animateCss', function($animateCss) { + * return { + * enter: function(element) { + * return $animateCss(element, { + * event: 'enter', + * structural: true, + * addClass: 'maroon-setting', + * from: { height:0 }, + * to: { height: 200 } + * }); + * } + * } + * }]); + * ``` + * + * Now we can fill in the rest via our transition CSS code: + * + * ```css + * /* the transition tells ngAnimate to make the animation happen */ + * .slide.ng-enter { transition:0.5s linear all; } + * + * /* this extra CSS class will be absorbed into the transition + * since the $animateCss code is adding the class */ + * .maroon-setting { background:red; } + * ``` + * + * And `$animateCss` will figure out the rest. Just make sure to have the `done()` callback fire the `doneFn` function to signal when the animation is over. + * + * To learn more about what's possible be sure to visit the {@link ngAnimate.$animateCss $animateCss service}. + * + * ## Animation Anchoring (via `ng-animate-ref`) + * + * ngAnimate in AngularJS 1.4 comes packed with the ability to cross-animate elements between + * structural areas of an application (like views) by pairing up elements using an attribute + * called `ng-animate-ref`. + * + * Let's say for example we have two views that are managed by `ng-view` and we want to show + * that there is a relationship between two components situated in within these views. By using the + * `ng-animate-ref` attribute we can identify that the two components are paired together and we + * can then attach an animation, which is triggered when the view changes. + * + * Say for example we have the following template code: + * + * ```html + * + *
      + *
      + * + * + * + * + * + * + * + * + * ``` + * + * Now, when the view changes (once the link is clicked), ngAnimate will examine the + * HTML contents to see if there is a match reference between any components in the view + * that is leaving and the view that is entering. It will scan both the view which is being + * removed (leave) and inserted (enter) to see if there are any paired DOM elements that + * contain a matching ref value. + * + * The two images match since they share the same ref value. ngAnimate will now create a + * transport element (which is a clone of the first image element) and it will then attempt + * to animate to the position of the second image element in the next view. For the animation to + * work a special CSS class called `ng-anchor` will be added to the transported element. + * + * We can now attach a transition onto the `.banner.ng-anchor` CSS class and then + * ngAnimate will handle the entire transition for us as well as the addition and removal of + * any changes of CSS classes between the elements: + * + * ```css + * .banner.ng-anchor { + * /* this animation will last for 1 second since there are + * two phases to the animation (an `in` and an `out` phase) */ + * transition:0.5s linear all; + * } + * ``` + * + * We also **must** include animations for the views that are being entered and removed + * (otherwise anchoring wouldn't be possible since the new view would be inserted right away). + * + * ```css + * .view-animation.ng-enter, .view-animation.ng-leave { + * transition:0.5s linear all; + * position:fixed; + * left:0; + * top:0; + * width:100%; + * } + * .view-animation.ng-enter { + * transform:translateX(100%); + * } + * .view-animation.ng-leave, + * .view-animation.ng-enter.ng-enter-active { + * transform:translateX(0%); + * } + * .view-animation.ng-leave.ng-leave-active { + * transform:translateX(-100%); + * } + * ``` + * + * Now we can jump back to the anchor animation. When the animation happens, there are two stages that occur: + * an `out` and an `in` stage. The `out` stage happens first and that is when the element is animated away + * from its origin. Once that animation is over then the `in` stage occurs which animates the + * element to its destination. The reason why there are two animations is to give enough time + * for the enter animation on the new element to be ready. + * + * The example above sets up a transition for both the in and out phases, but we can also target the out or + * in phases directly via `ng-anchor-out` and `ng-anchor-in`. + * + * ```css + * .banner.ng-anchor-out { + * transition: 0.5s linear all; + * + * /* the scale will be applied during the out animation, + * but will be animated away when the in animation runs */ + * transform: scale(1.2); + * } + * + * .banner.ng-anchor-in { + * transition: 1s linear all; + * } + * ``` + * + * + * + * + * ### Anchoring Demo + * + + + Home +
      +
      +
      +
      +
      + + angular.module('anchoringExample', ['ngAnimate', 'ngRoute']) + .config(['$routeProvider', function($routeProvider) { + $routeProvider.when('/', { + templateUrl: 'home.html', + controller: 'HomeController as home' + }); + $routeProvider.when('/profile/:id', { + templateUrl: 'profile.html', + controller: 'ProfileController as profile' + }); + }]) + .run(['$rootScope', function($rootScope) { + $rootScope.records = [ + { id: 1, title: 'Miss Beulah Roob' }, + { id: 2, title: 'Trent Morissette' }, + { id: 3, title: 'Miss Ava Pouros' }, + { id: 4, title: 'Rod Pouros' }, + { id: 5, title: 'Abdul Rice' }, + { id: 6, title: 'Laurie Rutherford Sr.' }, + { id: 7, title: 'Nakia McLaughlin' }, + { id: 8, title: 'Jordon Blanda DVM' }, + { id: 9, title: 'Rhoda Hand' }, + { id: 10, title: 'Alexandrea Sauer' } + ]; + }]) + .controller('HomeController', [function() { + //empty + }]) + .controller('ProfileController', ['$rootScope', '$routeParams', + function ProfileController($rootScope, $routeParams) { + var index = parseInt($routeParams.id, 10); + var record = $rootScope.records[index - 1]; + + this.title = record.title; + this.id = record.id; + }]); + + +

      Welcome to the home page

      +

      Please click on an element

      + + {{ record.title }} + +
      + +
      + {{ profile.title }} +
      +
      + + .record { + display:block; + font-size:20px; + } + .profile { + background:black; + color:white; + font-size:100px; + } + .view-container { + position:relative; + } + .view-container > .view.ng-animate { + position:absolute; + top:0; + left:0; + width:100%; + min-height:500px; + } + .view.ng-enter, .view.ng-leave, + .record.ng-anchor { + transition:0.5s linear all; + } + .view.ng-enter { + transform:translateX(100%); + } + .view.ng-enter.ng-enter-active, .view.ng-leave { + transform:translateX(0%); + } + .view.ng-leave.ng-leave-active { + transform:translateX(-100%); + } + .record.ng-anchor-out { + background:red; + } + +
      + * + * ### How is the element transported? + * + * When an anchor animation occurs, ngAnimate will clone the starting element and position it exactly where the starting + * element is located on screen via absolute positioning. The cloned element will be placed inside of the root element + * of the application (where ng-app was defined) and all of the CSS classes of the starting element will be applied. The + * element will then animate into the `out` and `in` animations and will eventually reach the coordinates and match + * the dimensions of the destination element. During the entire animation a CSS class of `.ng-animate-shim` will be applied + * to both the starting and destination elements in order to hide them from being visible (the CSS styling for the class + * is: `visibility:hidden`). Once the anchor reaches its destination then it will be removed and the destination element + * will become visible since the shim class will be removed. + * + * ### How is the morphing handled? + * + * CSS Anchoring relies on transitions and keyframes and the internal code is intelligent enough to figure out + * what CSS classes differ between the starting element and the destination element. These different CSS classes + * will be added/removed on the anchor element and a transition will be applied (the transition that is provided + * in the anchor class). Long story short, ngAnimate will figure out what classes to add and remove which will + * make the transition of the element as smooth and automatic as possible. Be sure to use simple CSS classes that + * do not rely on DOM nesting structure so that the anchor element appears the same as the starting element (since + * the cloned element is placed inside of root element which is likely close to the body element). + * + * Note that if the root element is on the `` element then the cloned node will be placed inside of body. + * + * + * ## Using $animate in your directive code + * + * So far we've explored how to feed in animations into an Angular application, but how do we trigger animations within our own directives in our application? + * By injecting the `$animate` service into our directive code, we can trigger structural and class-based hooks which can then be consumed by animations. Let's + * imagine we have a greeting box that shows and hides itself when the data changes + * + * ```html + * Hi there + * ``` + * + * ```js + * ngModule.directive('greetingBox', ['$animate', function($animate) { + * return function(scope, element, attrs) { + * attrs.$observe('active', function(value) { + * value ? $animate.addClass(element, 'on') : $animate.removeClass(element, 'on'); + * }); + * }); + * }]); + * ``` + * + * Now the `on` CSS class is added and removed on the greeting box component. Now if we add a CSS class on top of the greeting box element + * in our HTML code then we can trigger a CSS or JS animation to happen. + * + * ```css + * /* normally we would create a CSS class to reference on the element */ + * greeting-box.on { transition:0.5s linear all; background:green; color:white; } + * ``` + * + * The `$animate` service contains a variety of other methods like `enter`, `leave`, `animate` and `setClass`. To learn more about what's + * possible be sure to visit the {@link ng.$animate $animate service API page}. + * + * + * ## Callbacks and Promises + * + * When `$animate` is called it returns a promise that can be used to capture when the animation has ended. Therefore if we were to trigger + * an animation (within our directive code) then we can continue performing directive and scope related activities after the animation has + * ended by chaining onto the returned promise that animation method returns. + * + * ```js + * // somewhere within the depths of the directive + * $animate.enter(element, parent).then(function() { + * //the animation has completed + * }); + * ``` + * + * (Note that earlier versions of Angular prior to v1.4 required the promise code to be wrapped using `$scope.$apply(...)`. This is not the case + * anymore.) + * + * In addition to the animation promise, we can also make use of animation-related callbacks within our directives and controller code by registering + * an event listener using the `$animate` service. Let's say for example that an animation was triggered on our view + * routing controller to hook into that: + * + * ```js + * ngModule.controller('HomePageController', ['$animate', function($animate) { + * $animate.on('enter', ngViewElement, function(element) { + * // the animation for this route has completed + * }]); + * }]) + * ``` + * + * (Note that you will need to trigger a digest within the callback to get angular to notice any scope-related changes.) + */ + +var copy; +var extend; +var forEach; +var isArray; +var isDefined; +var isElement; +var isFunction; +var isObject; +var isString; +var isUndefined; +var jqLite; +var noop; + +/** + * @ngdoc service + * @name $animate + * @kind object + * + * @description + * The ngAnimate `$animate` service documentation is the same for the core `$animate` service. + * + * Click here {@link ng.$animate to learn more about animations with `$animate`}. + */ +angular.module('ngAnimate', [], function initAngularHelpers() { + // Access helpers from angular core. + // Do it inside a `config` block to ensure `window.angular` is available. + noop = angular.noop; + copy = angular.copy; + extend = angular.extend; + jqLite = angular.element; + forEach = angular.forEach; + isArray = angular.isArray; + isString = angular.isString; + isObject = angular.isObject; + isUndefined = angular.isUndefined; + isDefined = angular.isDefined; + isFunction = angular.isFunction; + isElement = angular.isElement; +}) + .directive('ngAnimateSwap', ngAnimateSwapDirective) + + .directive('ngAnimateChildren', $$AnimateChildrenDirective) + .factory('$$rAFScheduler', $$rAFSchedulerFactory) + + .provider('$$animateQueue', $$AnimateQueueProvider) + .provider('$$animation', $$AnimationProvider) + + .provider('$animateCss', $AnimateCssProvider) + .provider('$$animateCssDriver', $$AnimateCssDriverProvider) + + .provider('$$animateJs', $$AnimateJsProvider) + .provider('$$animateJsDriver', $$AnimateJsDriverProvider); + + +})(window, window.angular); diff --git a/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/angular-bootstrap-prettify.js b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/angular-bootstrap-prettify.js new file mode 100644 index 00000000..850c04a2 --- /dev/null +++ b/resources/projects/js-static-files-in-java-app/src/main/resources/META-INF/resources/bower_components/angular-patternfly/dist/docs/grunt-scripts/angular-bootstrap-prettify.js @@ -0,0 +1,323 @@ +'use strict'; + +var directive = {}; +var service = { value: {} }; + +var DEPENDENCIES = { + 'angular.js': 'http://code.angularjs.org/' + angular.version.full + '/angular.min.js', + 'angular-resource.js': 'http://code.angularjs.org/' + angular.version.full + '/angular-resource.min.js', + 'angular-route.js': 'http://code.angularjs.org/' + angular.version.full + '/angular-route.min.js', + 'angular-animate.js': 'http://code.angularjs.org/' + angular.version.full + '/angular-animate.min.js', + 'angular-sanitize.js': 'http://code.angularjs.org/' + angular.version.full + '/angular-sanitize.min.js', + 'angular-cookies.js': 'http://code.angularjs.org/' + angular.version.full + '/angular-cookies.min.js' +}; + + +function escape(text) { + return text. + replace(/\&/g, '&'). + replace(/\/g, '>'). + replace(/"/g, '"'); +} + +/** + * http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie + * http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript + */ +function setHtmlIe8SafeWay(element, html) { + var newElement = angular.element('
      ' + html + '
      '); + + element.empty(); + element.append(newElement.contents()); + return element; +} + + +directive.jsFiddle = function(getEmbeddedTemplate, escape, script) { + return { + terminal: true, + link: function(scope, element, attr) { + var name = '', + stylesheet = '\n', + fields = { + html: '', + css: '', + js: '' + }; + + angular.forEach(attr.jsFiddle.split(' '), function(file, index) { + var fileType = file.split('.')[1]; + + if (fileType == 'html') { + if (index == 0) { + fields[fileType] += + '
      \n' + + getEmbeddedTemplate(file, 2); + } else { + fields[fileType] += '\n\n\n \n' + + ' \n'; + } + } else { + fields[fileType] += getEmbeddedTemplate(file) + '\n'; + } + }); + + fields.html += '
      \n'; + + setHtmlIe8SafeWay(element, + '
      ' + + hiddenField('title', 'AngularJS Example: ' + name) + + hiddenField('css', ' \n' + + stylesheet + + script.angular + + (attr.resource ? script.resource : '') + + ' + +
      + Max limit: 20, warn when 5 or less remaining, disable button after max limit +
      +
      + + +
      + + +
      + + + + + + +
      +
      +
      + Max limit: 10, warn when 2 or less remaining, block input after max limit +
      +
      +
      +
      + + +
      + + + + + + +
      +
      +
      +
      + Max limit: 10, warn when 5 or less remaining, block input after max limit +
      +
      + + Remaining +
      +
      +
      + + + + angular.module( 'patternfly.example', ['patternfly.form']); + + angular.module( 'patternfly.example' ).controller( 'DemoCtrl', function( $scope ) { + $scope.messageArea1text = "Initial Text"; + $scope.messageArea2text = ""; + $scope.messageInput3text = ""; + + $scope.charsMaxLimitExceeded = false; + + // 'tfId' will equal the id of the text area/input field which + // triggered the event + $scope.$on('overCharsMaxLimit', function (event, tfId) { + if(!$scope.charsMaxLimitExceeded){ + $scope.charsMaxLimitExceeded = true; + } + }); + + // 'tfId' will equal the id of the text area/input field which + // triggered the event + $scope.$on('underCharsMaxLimit', function (event, tfId) { + if($scope.charsMaxLimitExceeded){ + $scope.charsMaxLimitExceeded = false; + } + }); + + }); + + + +*/ + +angular.module('patternfly.form').directive('pfRemainingCharsCount', ["$timeout", function ($timeout) { + 'use strict'; + return { + restrict: 'A', + require: 'ngModel', + scope: { + ngModel: "=" + }, + link: function ($scope, $element, $attributes) { + var charsMaxLimit = $attributes.charsMaxLimit; + var charsWarnRemaining = $attributes.charsWarnRemaining; + var countRemainingFld = angular.element(document.getElementById($attributes.countFld)); + var blockInputAtMaxLimit = ($attributes.blockInputAtMaxLimit === 'true'); + var checkCharactersRemaining = function () { + var charsLength = $scope.ngModel.length; + var remainingChars = charsMaxLimit - charsLength; + + // trim if blockInputAtMaxLimit and over limit + if (blockInputAtMaxLimit && charsLength > charsMaxLimit) { + $scope.ngModel = $scope.ngModel.substring(0, charsMaxLimit); + charsLength = $scope.ngModel.length; + remainingChars = charsMaxLimit - charsLength; + } + + // creating scope vars for unit testing + $scope.remainingChars = remainingChars; + $scope.remainingCharsWarning = (remainingChars <= charsWarnRemaining ? true : false); + + countRemainingFld.text(remainingChars); + countRemainingFld.toggleClass('chars-warn-remaining-pf', remainingChars <= charsWarnRemaining); + + if (remainingChars < 0) { + $scope.$emit('overCharsMaxLimit', $attributes.id); + } else { + $scope.$emit('underCharsMaxLimit', $attributes.id); + } + }; + + $scope.$watch('ngModel', function () { + checkCharactersRemaining(); + }); + + $element.bind('keypress', function (event) { + // Once the charsMaxLimit has been met or exceeded, prevent all keypresses from working + if (blockInputAtMaxLimit && $element.val().length >= charsMaxLimit) { + // Except backspace + if (event.keyCode !== 8) { + event.preventDefault(); + } + } + }); + } + }; +}]); +;/** + * @ngdoc directive + * @name patternfly.modals.directive:pfAboutModal + * + * @description + * Directive for rendering modal windows. + * + * @param {string=} additionalInfo Text explaining the version or copyright + * @param {string=} copyright Product copyright information + * @param {string=} imgAlt The alt text for the corner grahpic + * @param {string=} imgSrc The source for the corner grahpic + * @param {boolean=} isOpen Flag indicating that the modal should be opened + * @param {function=} onClose Function to call when modal is closed + * @param {object=} productInfo data for the modal:
      + *
        + *
      • .product - the product label + *
      • .version - the product version + *
      + * @param {string=} title The product title for the modal + * + * @example + + +
      + +
      +
      +
      + + angular.module('patternfly.modals').controller('ModalCtrl', function ($scope) { + $scope.additionalInfo = "Donec consequat dignissim neque, sed suscipit quam egestas in. Fusce bibendum " + + "laoreet lectus commodo interdum. Vestibulum odio ipsum, tristique et ante vel, iaculis placerat nulla. " + + "Suspendisse iaculis urna feugiat lorem semper, ut iaculis risus tempus."; + $scope.copyright = "Trademark and Copyright Information"; + $scope.imgAlt = "Patternfly Symbol"; + $scope.imgSrc = "img/logo-alt.svg"; + $scope.title = "Product Title"; + $scope.productInfo = [ + { name: 'Version', value: '1.0.0.0.20160819142038_51be77c' }, + { name: 'Server Name', value: 'Localhost' }, + { name: 'User Name', value: 'admin' }, + { name: 'User Role', value: 'Administrator' }]; + $scope.open = function () { + $scope.isOpen = true; + } + $scope.onClose = function() { + $scope.isOpen = false; + } + }); + +
      + */ +angular.module('patternfly.modals') + +.directive("pfAboutModalTransclude", ["$parse", function ($parse) { + 'use strict'; + return { + link: function (scope, element, attrs) { + element.append($parse(attrs.pfAboutModalTransclude)(scope)); + } + }; +}]) + +.directive('pfAboutModal', function () { + 'use strict'; + return { + restrict: 'A', + scope: { + additionalInfo: '=?', + copyright: '=?', + close: "&onClose", + imgAlt: '=?', + imgSrc: '=?', + isOpen: '=?', + productInfo: '=', + title: '=?' + }, + templateUrl: 'modals/about-modal.html', + transclude: true, + controller: ['$scope', '$uibModal', '$transclude', function ($scope, $uibModal, $transclude) { + if ($scope.isOpen === undefined) { + $scope.isOpen = false; + } + + // The ui-bootstrap modal only supports either template or templateUrl as a way to specify the content. + // When the content is retrieved, it is compiled and linked against the provided scope by the $uibModal service. + // Unfortunately, there is no way to provide transclusion there. + // + // The solution below embeds a placeholder directive (i.e., pfAboutModalTransclude) to append the transcluded DOM. + // The transcluded DOM is from a different location than the modal, so it needs to be handed over to the + // placeholder directive. Thus, we're passing the actual DOM, not the parsed HTML. + $scope.openModal = function () { + $uibModal.open({ + controller: ['$scope', '$uibModalInstance', 'content', function ($scope, $uibModalInstance, content) { + $scope.template = content; + $scope.close = function () { + $uibModalInstance.close(); + }; + $scope.$watch( + function () { + return $scope.isOpen; + }, + function (newValue) { + if (newValue === false) { + $uibModalInstance.close(); + } + } + ); + }], + resolve: { + content: function () { + var transcludedContent; + $transclude(function (clone) { + transcludedContent = clone; + }); + return transcludedContent; + } + }, + scope: $scope, + templateUrl: "about-modal-template.html" + }) + .result.then( + function () { + $scope.close(); // closed + }, + function () { + $scope.close(); // dismissed + } + ); + }; + }], + link: function (scope, element, attrs) { + // watching isOpen attribute to dispay modal when needed + var isOpenListener = scope.$watch('isOpen', function (newVal, oldVal) { + if (newVal === true) { + scope.openModal(); + } + }); + scope.$on('$destroy', isOpenListener); + } + }; +}); +;/** + * @ngdoc directive + * @name patternfly.navigation.directive:pfVerticalNavigation - Basic + * + * @description + * Directive for vertical navigation. This sets up the nav bar header with the collapse button (hamburger) and the + * application brand image (or text) as well as the vertical navigation bar containing the navigation items. This + * directive supports primary, secondary, and tertiary navigation with options to allow pinning of the secondary and + * tertiary navigation menus as well as the option for persistent secondary menus. + *

      + * The remaining parts of the navbar header can be transcluded. + *

      + * Tha navigation items are marked active based on the current location and the href value for the item. If not using + * href's on the items to navigate, set update-active-items-on-click to "true". + *

      + * This directive works in conjunction with the main content container if the 'container-pf-nav-pf-vertical' class + * selector is added to the main content container. + * + * @param {string} brandSrc src for brand image + * @param {string} brandAlt Text for product name when brand image is not available + * @param {boolean} showBadges Flag if badges are used on navigation items, default: false + * @param {boolean} persistentSecondary Flag to use persistent secondary menus, default: false + * @param {boolean} hiddenIcons Flag to not show icons on the primary menu, default: false + * @param {array} items List of navigation items + *
        + *
      • .title - (string) Name of item to be displayed on the menu + *
      • .iconClass - (string) Classes for icon to be shown on the menu (ex. "fa fa-dashboard") + *
      • .href - (string) href link to navigate to on click + *
      • .children - (array) Submenu items (same structure as top level items) + *
      • .badges - (array) Badges to display for the item, badges with a zero count are not displayed. + *
          + *
        • .count - (number) Count to display in the badge + *
        • .iconClass - (string) Class to use for showing an icon before the count + *
        • .tooltip - (string) Tooltip to display for the badge + *
        • .badgeClass: - (string) Additional class(es) to add to the badge container + *
        + *
      + * @param {function} navigateCallback function(item) Callback method invoked on a navigation item click (one with no submenus) + * @param {function} itemClickCallback function(item) Callback method invoked on an item click + * @param {boolean} updateActiveItemsOnClick Flag if active items should be marked on click rather than on navigation change, default: false + * @param {boolean} ignoreMobile Flag if mobile state should be ignored (use only if absolutely necessary) default: false + * + * @example + + +
      + + + +
      + +
      + + angular.module('patternfly.navigation').controller('vertNavController', ['$scope', + function ($scope) { + $scope.navigationItems = [ + { + title: "Dashboard", + iconClass: "fa fa-dashboard", + href: "#/dashboard" + }, + { + title: "Dolor", + iconClass : "fa fa-shield", + href: "#/dolor", + badges: [ + { + count: 1283, + tooltip: "Total number of items" + } + ] + }, + { + title: "Ipsum", + iconClass: "fa fa-space-shuttle", + children: [ + { + title: "Intellegam", + children: [ + { + title: "Recteque", + href: "#/ipsum/intellegam/recteque", + badges: [ + { + count: 6, + tooltip: "Total number of error items", + badgeClass: 'example-error-background' + } + ] + }, + { + title: "Suavitate", + href: "#/ipsum/intellegam/suavitate", + badges: [ + { + count: 2, + tooltip: "Total number of items" + } + ] + }, + { + title: "Vituperatoribus", + href: "#/ipsum/intellegam/vituperatoribus", + badges: [ + { + count: 18, + tooltip: "Total number of warning items", + badgeClass: 'example-warning-background' + } + ] + } + ] + }, + { + title: "Copiosae", + children: [ + { + title: "Exerci", + href: "#/ipsum/copiosae/exerci", + badges: [ + { + count: 2, + tooltip: "Total number of error items", + iconClass: 'pficon pficon-error-circle-o' + }, + { + count: 6, + tooltip: "Total number warning error items", + iconClass: 'pficon pficon-warning-triangle-o' + } + ] + }, + { + title: "Quaeque", + href: "#/ipsum/copiosae/quaeque", + badges: [ + { + count: 0, + tooltip: "Total number of error items", + iconClass: 'pficon pficon-error-circle-o' + }, + { + count: 4, + tooltip: "Total number warning error items", + iconClass: 'pficon pficon-warning-triangle-o' + } + ] + }, + { + title: "Utroque", + href: "#/ipsum/copiosae/utroque", + badges: [ + { + count: 1, + tooltip: "Total number of error items", + iconClass: 'pficon pficon-error-circle-o' + }, + { + count: 2, + tooltip: "Total number warning error items", + iconClass: 'pficon pficon-warning-triangle-o' + } + ] + } + ] + }, + { + title: "Patrioque", + children: [ + { + title: "Novum", + href: "#/ipsum/patrioque/novum" + }, + { + title: "Pericula", + href: "#/ipsum/patrioque/pericula" + }, + { + title: "Gubergren", + href: "#/ipsum/patrioque/gubergren" + } + ] + }, + { + title: "Accumsan", + href: "#/ipsum/Accumsan", + badges: [ + { + count: 2, + tooltip: "Total number of error items", + iconClass: 'pficon pficon-error-circle-o' + }, + { + count: 6, + tooltip: "Total number warning error items", + iconClass: 'pficon pficon-warning-triangle-o' + } + ] + } + ] + }, + { + title: "Amet", + iconClass: "fa fa-paper-plane", + children: [ + { + title: "Detracto", + children: [ + { + title: "Delicatissimi", + href: "#/amet/detracto/delicatissimi" + }, + { + title: "Aliquam", + href: "#/amet/detracto/aliquam" + }, + { + title: "Principes", + href: "#/amet/detracto/principes" + } + ] + }, + { + title: "Mediocrem", + children: [ + { + title: "Convenire", + href: "#/amet/mediocrem/convenire" + }, + { + title: "Nonumy", + href: "#/amet/mediocrem/nonumy" + }, + { + title: "Deserunt", + href: "#/amet/mediocrem/deserunt" + } + ] + }, + { + title: "Corrumpit", + children: [ + { + title: "Aeque", + href: "#/amet/corrumpit/aeque" + }, + { + title: "Delenit", + href: "#/amet/corrumpit/delenit" + }, + { + title: "Qualisque", + href: "#/amet/corrumpit/qualisque" + } + ] + }, + { + title: "urbanitas", + href: "#/amet/urbanitas" + } + ] + }, + { + title: "Adipscing", + iconClass: "fa fa-graduation-cap", + href: "#/adipscing" + }, + { + title: "Lorem", + iconClass: "fa fa-gamepad", + href: "#/lorem" + }, + { + title: "Exit Demo" + } + ]; + $scope.handleNavigateClick = function (item) { + if (item.title === "Exit Demo") { + angular.element(document.querySelector("#verticalNavLayout")).addClass("hidden"); + } + }; + } + ]); + + + $(document).ready(function() { + $("#includedContent")[0].innerHTML = '\ +
      \ +
      \ +
      \ +

      \ + 0 Ipsum\ +

      \ +
      \ +

      \ + \ +

      \ +
      \ +
      \ +
      \ +
      \ +
      \ +

      \ + 20 Amet\ +

      \ +
      \ +

      \ + 4\ + 1\ +

      \ +
      \ +
      \ +
      \ +
      \ +
      \ +

      \ + 9 Adipiscing\ +

      \ +
      \ +

      \ + \ +

      \ +
      \ +
      \ +
      \ +
      \ +
      \ +

      \ + 12 Lorem\ +

      \ +
      \ +

      \ + 1\ +

      \ +
      \ +
      \ +
      \ +
      \ +
      \ +
      \ +
      \ +

      \ + \ + 0 Ipsum\ +

      \ +
      \ +

      \ + \ +

      \ +
      \ +
      \ +
      \ +
      \ +
      \ +

      \ + \ + \ + 20 Amet\ + \ +

      \ +
      \ +

      \ + 4\ +

      \ +
      \ +
      \ +
      \ +
      \ +
      \ +

      \ + \ + \ + 9 Adipiscing\ + \ +

      \ +
      \ +

      \ + \ +

      \ +
      \ +
      \ +
      \ +
      \ +
      \ +

      \ + \ + \ + 12 Lorem\ + \ +

      \ +
      \ +

      \ + 1\ +

      \ +
      \ +
      \ +
      \ +
      \ +
      \ +
      \ +
      \ +
      \ +

      \ + Top Utilized\ +

      \ +
      \ +
      \ +
      \ + Ipsum\ +
      \ +
      \ +
      \ + 190.0 of 200.0 GB Used\ +
      \ +
      \ + 5% Available\ +
      \ +
      \ +
      \ + Amet\ +
      \ +
      \ +
      \ + 100.0 of 200.0 GB Used\ +
      \ +
      \ + 50% Available\ +
      \ +
      \ +
      \ + Adipiscing\ +
      \ +
      \ +
      \ + 140.0 of 200.0 GB Used\ +
      \ +
      \ + 30% Available\ +
      \ +
      \ +
      \ + Lorem\ +
      \ +
      \ +
      \ + 153.0 of 200.0 GB Used\ +
      \ +
      \ + 23.5% Available\ +
      \ +
      \ +
      \ +
      \ +
      \ +
      \ +
      \ +
      \ +

      \ + Quotas\ +

      \ +
      \ +
      \ +
      \ +
      \ + Ipsum\ +
      \ +
      \ +
      \ + 115 of 460 MHz\ +
      \ +
      \ + 75% Available\ +
      \ +
      \ +
      \ +
      \ +
      \ + Amet\ +
      \ +
      \ +
      \ + 8 of 16 GB\ +
      \ +
      \ + 50% Available\ +
      \ +
      \ +
      \ +
      \ +
      \ + Adipiscing\ +
      \ +
      \ +
      \ + 5 of 8 Total\ +
      \ +
      \ + 37.5% Available\ +
      \ +
      \ +
      \ +
      \ +
      \ + Lorem\ +
      \ +
      \ +
      \ + 2 of 2 Total\ +
      \ +
      \ +
      \ +
      \ +
      \ +
      \ +
      \ + '; + }); +
      + + $(document).ready(function() { + $(document).on('click', '#showVerticalNav', function() { + $(document.getElementById("verticalNavLayout")).removeClass("hidden"); + }); + $(document).on('click', '#hideVerticalNav', function() { + $(document.getElementById("verticalNavLayout")).addClass("hidden"); + }); + }); + +
      +*/ +;/** + * @ngdoc directive + * @name patternfly.navigation.directive:pfVerticalNavigation - Router + * + * @description + * This example shows how to use pfVerticalNavigation with angular-ui-router's $states and uiSrefs. + * + * @param {string} brandSrc src for brand image + * @param {string} brandAlt Text for product name when brand image is not available + * @param {boolean} showBadges Flag if badges are used on navigation items, default: false + * @param {boolean} persistentSecondary Flag to use persistent secondary menus, default: false + * @param {boolean} hiddenIcons Flag to not show icons on the primary menu, default: false + * @param {array} items List of navigation items + *
        + *
      • .title - (string) Name of item to be displayed on the menu + *
      • .iconClass - (string) Classes for icon to be shown on the menu (ex. "fa fa-dashboard") + *
      • .href - (string) href link to navigate to on click + *
      • .children - (array) Submenu items (same structure as top level items) + *
      • .badges - (array) Badges to display for the item, badges with a zero count are not displayed. + *
          + *
        • .count - (number) Count to display in the badge + *
        • .iconClass - (string) Class to use for showing an icon before the count + *
        • .tooltip - (string) Tooltip to display for the badge + *
        • .badgeClass: - (string) Additional class(es) to add to the badge container + *
        + *
      • .uiSref - (string) Optional Angular UI Router state name. If specified, href must be not defined, and vice versa. + *
      • .uiSrefOptions - (object) Optional object to be passed to Angular UI Router $state.go() function + *
      + * @param {function} navigateCallback function(item) Callback method invoked on a navigation item click (one with no submenus) + * @param {function} itemClickCallback function(item) Callback method invoked on an item click + * @param {boolean} updateActiveItemsOnClick Flag if active items should be marked on click rather than on navigation change, default: false + * @param {boolean} ignoreMobile Flag if mobile state should be ignored (use only if absolutely necessary) default: false + * + * @example + + +
      + + + +
      + +
      + + angular.module('myApp',['patternfly.navigation', 'ui.router']) + .config(function($stateProvider, $urlRouterProvider) { + $urlRouterProvider.otherwise('dashboard'); + + $stateProvider + .state('dashboard', { + url: '/dashboard', + template: '
      \ +
      \ +

      \ + State: Dashboard\ +

      \ +
      \ +
      ' + }) + .state('dolor', { + url: '/dolor', + template: '
      \ +
      \ +

      \ + State: Dolor\ +

      \ +
      \ +
      ' + }) + .state('ipsum', { + url: '/ipsum', + template: '
      \ +
      \ +

      \ + State: Ipsum\ +

      \ +
      \ +
      ' + }); + }) + .controller('vertNavWithRouterController', ['$scope', + function ($scope) { + $scope.navigationItems = [ + { + title: "Dashboard", + iconClass: "fa fa-dashboard", + uiSref: "dashboard", + uiSrefOptions: { someKey: 'SomeValue' } + }, + { + title: "Dolor", + iconClass : "fa fa-shield", + uiSref: "dolor" + }, + { + title: "Ipsum", + iconClass : "fa fa-space-shuttle", + uiSref: "ipsum" + }, + { + title: "Exit Demo" + } + ]; + $scope.handleNavigateClickRouter = function (item) { + if (item.title === "Exit Demo") { + angular.element(document.querySelector("#verticalNavWithRouterLayout")).addClass("hidden"); + } + }; + } + ]); +
      + + $(document).ready(function() { + $(document).on('click', '#showVerticalNavWithRouter', function() { + $(document.getElementById("verticalNavWithRouterLayout")).removeClass("hidden"); + }); + $(document).on('click', '#hideVerticalNavWithRouter', function() { + $(document.getElementById("verticalNavWithRouterLayout")).addClass("hidden"); + }); + }); + +
      +*/ +;angular.module('patternfly.navigation').directive('pfVerticalNavigation', ['$location', '$rootScope', '$window', '$document', '$timeout', '$injector', + function (location, rootScope, $window, $document, $timeout, $injector) { + 'use strict'; + var $state; + + // Optional dependency on $state + if ($injector.has("$state")) { + $state = $injector.get("$state"); + } + + return { + restrict: 'A', + scope: { + brandSrc: '@', + brandAlt: '@', + showBadges: '@', + persistentSecondary: '@', + pinnableMenus: '@', + hiddenIcons: '@', + items: '=', + navigateCallback: '=?', + itemClickCallback: '=?', + updateActiveItemsOnClick: '@', + ignoreMobile: '@' + }, + replace: true, + templateUrl: 'navigation/vertical-navigation.html', + transclude: true, + controller: ["$scope", function ($scope) { + var routeChangeListener; + + $scope.showBadges = $scope.showBadges === 'true'; + $scope.persistentSecondary = $scope.persistentSecondary === 'true'; + $scope.pinnableMenus = $scope.pinnableMenus === 'true'; + $scope.hiddenIcons = $scope.hiddenIcons === 'true'; + $scope.updateActiveItemsOnClick = $scope.updateActiveItemsOnClick === 'true'; + $scope.ignoreMobile = $scope.ignoreMobile === 'true'; + $scope.activeSecondary = false; + + $scope.clearActiveItems = function () { + $scope.items.forEach(function (item) { + item.isActive = false; + if (item.children) { + item.children.forEach(function (secondary) { + secondary.isActive = false; + if (secondary.children) { + secondary.children.forEach(function (tertiary) { + tertiary.isActive = false; + }); + } + }); + } + }); + }; + + $scope.setActiveItems = function () { + var updatedRoute = "#" + location.path(); + //Setting active state on load + $scope.items.forEach(function (topLevel) { + if (updatedRoute.indexOf(topLevel.href) > -1) { + topLevel.isActive = true; + } + if (topLevel.children) { + topLevel.children.forEach(function (secondLevel) { + if (updatedRoute.indexOf(secondLevel.href) > -1) { + secondLevel.isActive = true; + topLevel.isActive = true; + } + if (secondLevel.children) { + secondLevel.children.forEach(function (thirdLevel) { + if (updatedRoute.indexOf(thirdLevel.href) > -1) { + thirdLevel.isActive = true; + secondLevel.isActive = true; + topLevel.isActive = true; + } + }); + } + }); + } + }); + }; + + if (!$scope.updateActiveItemsOnClick) { + routeChangeListener = rootScope.$on( "$routeChangeSuccess", function (event, next, current) { + $scope.clearActiveItems(); + $scope.setActiveItems(); + }); + + $scope.$on('$destroy', routeChangeListener); + } + }], + link: function ($scope) { + var breakpoints = { + 'tablet': 768, + 'desktop': 1200 + }; + + var getBodyContentElement = function () { + return angular.element(document.querySelector('.container-pf-nav-pf-vertical')); + }; + + var explicitCollapse = false; + var hoverDelay = 500; + var hideDelay = hoverDelay + 200; + + var initBodyElement = function () { + var bodyContentElement = getBodyContentElement(); + if ($scope.showBadges) { + bodyContentElement.addClass('nav-pf-vertical-with-badges'); + } + if ($scope.persistentSecondary) { + bodyContentElement.addClass('nav-pf-persistent-secondary'); + } + if ($scope.hiddenIcons) { + bodyContentElement.addClass('hidden-icons-pf'); + } + }; + + var updateMobileMenu = function (selected, secondaryItem) { + $scope.items.forEach(function (item) { + item.isMobileItem = false; + if (item.children) { + item.children.forEach(function (nextSecondary) { + nextSecondary.isMobileItem = false; + }); + } + }); + + if (selected) { + selected.isMobileItem = true; + if (secondaryItem) { + secondaryItem.isMobileItem = true; + $scope.showMobileSecondary = false; + $scope.showMobileTertiary = true; + } else { + $scope.showMobileSecondary = true; + $scope.showMobileTertiary = false; + } + } else { + $scope.showMobileSecondary = false; + $scope.showMobileTertiary = false; + } + }; + + var checkNavState = function () { + var width = $window.innerWidth; + var bodyContentElement = getBodyContentElement(); + + // Check to see if we need to enter/exit the mobile state + if (!$scope.ignoreMobile && width < breakpoints.tablet) { + if (!$scope.inMobileState) { + $scope.inMobileState = true; + + //Set the body class to the correct state + bodyContentElement.removeClass('collapsed-nav'); + bodyContentElement.addClass('hidden-nav'); + + // Reset the collapsed states + updateSecondaryCollapsedState(false); + updateTertiaryCollapsedState(false); + + explicitCollapse = false; + } + } else { + $scope.inMobileState = false; + $scope.showMobileNav = false; + + // Set the body class back to the default + bodyContentElement.removeClass('hidden-nav'); + } + + if (explicitCollapse) { + $scope.navCollapsed = true; + bodyContentElement.addClass('collapsed-nav'); + } else { + $scope.navCollapsed = false; + bodyContentElement.removeClass('collapsed-nav'); + } + }; + + var collapseMenu = function () { + var bodyContentElement = getBodyContentElement(); + $scope.navCollapsed = true; + + //Set the body class to the correct state + bodyContentElement.addClass('collapsed-nav'); + + explicitCollapse = true; + }; + + var expandMenu = function () { + var bodyContentElement = getBodyContentElement(); + $scope.navCollapsed = false; + + //Set the body class to the correct state + bodyContentElement.removeClass('collapsed-nav'); + + explicitCollapse = false; + + // Dispatch a resize event when showing the expanding then menu to + // allow content to adjust to the menu sizing + angular.element($window).triggerHandler('resize'); + }; + + var forceHideSecondaryMenu = function () { + $scope.forceHidden = true; + $timeout(function () { + $scope.forceHidden = false; + }, 500); + }; + + var setParentActive = function (item) { + $scope.items.forEach(function (topLevel) { + if (topLevel.children) { + topLevel.children.forEach(function (secondLevel) { + if (secondLevel === item) { + topLevel.isActive = true; + } + if (secondLevel.children) { + secondLevel.children.forEach(function (thirdLevel) { + if (thirdLevel === item) { + topLevel.isActive = true; + secondLevel.isActive = true; + } + }); + } + }); + } + }); + }; + + var getFirstNavigateChild = function (item) { + var firstChild; + if (!item.children || item.children.length < 1) { + firstChild = item; + } else { + firstChild = getFirstNavigateChild(item.children[0]); + } + return firstChild; + }; + + var setSecondaryItemVisible = function () { + var bodyContentElement = getBodyContentElement(); + $scope.activeSecondary = false; + + if ($scope.persistentSecondary && !$scope.inMobileState) { + $scope.items.forEach(function (topLevel) { + if (topLevel.children) { + topLevel.children.forEach(function (secondLevel) { + if (secondLevel.isActive) { + $scope.activeSecondary = true; + } + }); + } + }); + if ($scope.activeSecondary) { + bodyContentElement.addClass('secondary-visible-pf'); + } else { + bodyContentElement.removeClass('secondary-visible-pf'); + } + } + }; + + var navigateToItem = function (item) { + var navItem = getFirstNavigateChild(item); + var navTo; + if (navItem) { + $scope.showMobileNav = false; + if (navItem.uiSref && navItem.href) { + throw new Error('Using both uiSref and href on an item is not supported.'); + } + if (navItem.uiSref) { + if ($state === undefined) { + throw new Error('uiSref is defined on item, but no $state has been injected. ' + + 'Did you declare a dependency on "ui.router" module in your app?'); + } + $state.go(navItem.uiSref, navItem.uiSrefOptions); + } else { + navTo = navItem.href; + if (navTo) { + if (navTo.startsWith('#/')) { + navTo = navTo.substring(2); + } + location.path(navTo); + } + } + if ($scope.navigateCallback) { + $scope.navigateCallback(navItem); + } + } + + if ($scope.itemClickCallback) { + $scope.itemClickCallback(item); + } + + if ($scope.updateActiveItemsOnClick ) { + $scope.clearActiveItems(); + navItem.isActive = true; + setParentActive(navItem); + setSecondaryItemVisible(); + } + setSecondaryItemVisible(); + }; + + var primaryHover = function () { + var hover = false; + $scope.items.forEach(function (item) { + if (item.isHover) { + hover = true; + } + }); + return hover; + }; + + var secondaryHover = function () { + var hover = false; + $scope.items.forEach(function (item) { + if (item.children && item.children.length > 0) { + item.children.forEach(function (secondaryItem) { + if (secondaryItem.isHover) { + hover = true; + } + }); + } + }); + return hover; + }; + + var updateSecondaryCollapsedState = function (setCollapsed, collapsedItem) { + var bodyContentElement = getBodyContentElement(); + if (collapsedItem) { + collapsedItem.secondaryCollapsed = setCollapsed; + } + if (setCollapsed) { + $scope.collapsedSecondaryNav = true; + + bodyContentElement.addClass('collapsed-secondary-nav-pf'); + } else { + // Remove any collapsed secondary menus + if ($scope.items) { + $scope.items.forEach(function (item) { + item.secondaryCollasped = false; + }); + } + $scope.collapsedSecondaryNav = false; + + bodyContentElement.removeClass('collapsed-secondary-nav-pf'); + } + }; + + var updateTertiaryCollapsedState = function (setCollapsed, collapsedItem) { + var bodyContentElement = getBodyContentElement(); + if (collapsedItem) { + collapsedItem.tertiaryCollapsed = setCollapsed; + } + if (setCollapsed) { + $scope.collapsedTertiaryNav = true; + + bodyContentElement.addClass('collapsed-tertiary-nav-pf'); + updateSecondaryCollapsedState(false); + } else { + // Remove any collapsed secondary menus + if ($scope.items) { + $scope.items.forEach(function (item) { + if (item.children && item.children.length > 0) { + item.children.forEach(function (secondaryItem) { + secondaryItem.tertiaryCollasped = false; + }); + } + }); + } + $scope.collapsedTertiaryNav = false; + + bodyContentElement.removeClass('collapsed-tertiary-nav-pf'); + } + }; + + $scope.showMobileNav = false; + $scope.showMobileSecondary = false; + $scope.showMobileTertiary = false; + $scope.hoverSecondaryNav = false; + $scope.hoverTertiaryNav = false; + $scope.collapsedSecondaryNav = false; + $scope.collapsedTertiaryNav = false; + $scope.navCollapsed = false; + $scope.forceHidden = false; + + $scope.handleNavBarToggleClick = function () { + + if ($scope.inMobileState) { + // Toggle the mobile nav + if ($scope.showMobileNav) { + $scope.showMobileNav = false; + } else { + // Always start at the primary menu + updateMobileMenu(); + $scope.showMobileNav = true; + } + } else if ($scope.navCollapsed) { + expandMenu(); + } else { + collapseMenu(); + } + }; + + $scope.handlePrimaryClick = function (item, event) { + if ($scope.inMobileState) { + if (item.children && item.children.length > 0) { + updateMobileMenu(item); + } else { + updateMobileMenu(); + navigateToItem(item); + } + } else { + navigateToItem(item); + } + }; + + $scope.handleSecondaryClick = function (primary, secondary, event) { + if ($scope.inMobileState) { + if (secondary.children && secondary.children.length > 0) { + updateMobileMenu(primary, secondary); + } else { + updateMobileMenu(); + navigateToItem(secondary); + } + } else { + navigateToItem(secondary); + } + }; + + $scope.handleTertiaryClick = function (primary, secondary, tertiary, event) { + if ($scope.inMobileState) { + updateMobileMenu(); + } + + navigateToItem(tertiary); + }; + + // Show secondary nav bar on hover of primary nav items + $scope.handlePrimaryHover = function (item) { + if (item.children && item.children.length > 0) { + if (!$scope.inMobileState) { + if (item.navUnHoverTimeout !== undefined) { + $timeout.cancel(item.navUnHoverTimeout); + item.navUnHoverTimeout = undefined; + } else if ($scope.navHoverTimeout === undefined && !item.isHover) { + item.navHoverTimeout = $timeout(function () { + $scope.hoverSecondaryNav = true; + item.isHover = true; + item.navHoverTimeout = undefined; + }, hoverDelay); + } + } + } + }; + + $scope.handlePrimaryUnHover = function (item) { + if (item.children && item.children.length > 0) { + if (item.navHoverTimeout !== undefined) { + $timeout.cancel(item.navHoverTimeout); + item.navHoverTimeout = undefined; + } else if (item.navUnHoverTimeout === undefined && item.isHover) { + item.navUnHoverTimeout = $timeout(function () { + item.isHover = false; + if (!primaryHover()) { + $scope.hoverSecondaryNav = false; + } + item.navUnHoverTimeout = undefined; + }, hideDelay); + } + } + }; + + // Show tertiary nav bar on hover of secondary nav items + $scope.handleSecondaryHover = function (item) { + if (item.children && item.children.length > 0) { + if (!$scope.inMobileState) { + if (item.navUnHoverTimeout !== undefined) { + $timeout.cancel(item.navUnHoverTimeout); + item.navUnHoverTimeout = undefined; + } else if ($scope.navHoverTimeout === undefined) { + item.navHoverTimeout = $timeout(function () { + $scope.hoverTertiaryNav = true; + item.isHover = true; + item.navHoverTimeout = undefined; + }, hoverDelay); + } + } + } + }; + + $scope.handleSecondaryUnHover = function (item) { + if (item.children && item.children.length > 0) { + if (item.navHoverTimeout !== undefined) { + $timeout.cancel(item.navHoverTimeout); + item.navHoverTimeout = undefined; + } else if (item.navUnHoverTimeout === undefined) { + item.navUnHoverTimeout = $timeout(function () { + item.isHover = false; + if (!secondaryHover()) { + $scope.hoverTertiaryNav = false; + } + item.navUnHoverTimeout = undefined; + }, hideDelay); + } + } + }; + + $scope.collapseSecondaryNav = function (item, event) { + if ($scope.inMobileState) { + updateMobileMenu(); + } else { + if (item.secondaryCollapsed) { + updateSecondaryCollapsedState(false, item); + forceHideSecondaryMenu(); + } else { + updateSecondaryCollapsedState(true, item); + } + } + + $scope.hoverSecondaryNav = false; + event.stopImmediatePropagation(); + }; + + $scope.collapseTertiaryNav = function (item, event) { + if ($scope.inMobileState) { + $scope.items.forEach(function (primaryItem) { + if (primaryItem.children) { + primaryItem.children.forEach(function (secondaryItem) { + if (secondaryItem === item) { + updateMobileMenu(primaryItem); + } + }); + } + }); + } else { + if (item.tertiaryCollapsed) { + updateTertiaryCollapsedState(false, item); + forceHideSecondaryMenu(); + } else { + updateTertiaryCollapsedState(true, item); + } + } + + $scope.hoverSecondaryNav = false; + $scope.hoverTertiaryNav = false; + event.stopImmediatePropagation(); + }; + + initBodyElement(); + checkNavState(); + + angular.element($window).bind('resize', function () { + checkNavState(); + $timeout(function () { + try { + $scope.$apply(); + } catch (e) { + // Ignore, if we already applied, that is fine. + } + }); + }); + } + }; + }]); + +;/** + * @ngdoc directive + * @name patternfly.notification.directive:pfInlineNotification + * @restrict E + * @scope + * + * @param {expression=} pfNotificationType The type of the notification message. Allowed value is one of these: 'success','info','danger', 'warning'. + * @param {expression=} pfNotificationMessage The main text message of the notification. + * @param {expression=} pfNotificationHeader The header text of the notification. + * @param {expression=} pfNotificationPersistent The notification won't disappear after delay timeout, but has to be closed manually with the close button. + * + * @description + * The main visual element of the notification message. + * + * @example + + + +
      + + + + +
      +
      + +
      + +
      +
      +
      + +
      + +
      +
      +
      + +
      + +
      +
      +
      + +
      + +
      +
      +
      +
      +
      + + + angular.module( 'patternfly.notification' ).controller( 'NotificationDemoCtrl', function( $scope, Notifications ) { + $scope.types = ['success','info','danger', 'warning']; + $scope.type = $scope.types[0]; + $scope.isPersistent = false; + + $scope.header = 'Default Header.'; + $scope.message = 'Default Message.'; + }); + + +
      + */ +angular.module( 'patternfly.notification' ).directive('pfInlineNotification', function () { + 'use strict'; + + return { + scope: { + 'pfNotificationType': '=', + 'pfNotificationMessage': '=', + 'pfNotificationHeader': '=', + 'pfNotificationPersistent': '=', + 'pfNotificationIndex': '=' + }, + restrict: 'E', + templateUrl: 'notification/inline-notification.html' + }; +}); +;/** + * @ngdoc directive + * @name patternfly.notification.directive:pfNotificationDrawer + * + * @description + * Directive for rendering a notification drawer. This provides a common mechanism to handle how the notification + * drawer should look and behave without mandating the look of the notification group heading or notification body. + *

      + * An array of notification groups must be passed to create each group in the drawer. Each notification + * group must include an array of notifications to be shown for that group, the array MUST be called 'notifications'. + * You must provide the source for the heading, sub-heading, and notification body to show the content you desire for each. + * Pass a customScope object containing any scope variables/functions you need to access from the included source, access these + * via hanlders. in your included source. + *

      + * + * @param {boolean} drawerHidden Flag if the drawer is currently hidden + * @param {boolean} allowExpand Flag if the drawer can be expanded. Optional, default: false + * @param {boolean} drawExpanded Flag if the drawer is expanded (only valid if allowExpand is true). Optional, default: false + * @param {string} drawerTitle Title to display for the drawer (leaving this blank will remove the provided expand capability) + * @param {object} notificationGroups Array of notification groups to add to the drawer + * @param {string} actionButtonTitle Text for the lower action button of the drawer (optional, if not specified there will be no action button) + * @param {function} actionButtonCallback function(notificationGroup) Callback method for action button for each group, the notificationGroup is passed (Optional) + * @param {string} titleInclude Include src for the title area for the notification drawer, use this to customize the drawer title area + * @param {string} headingInclude Include src for the heading area for each notification group, access the group via notificationGroup + * @param {string} subheadingInclude Include src for the sub-heading area for each notification group, access the group via notificationGroup + * @param {string} notificationBodyInclude Include src for the notification body for each notification, access the notification via notification + * @param {string} notificationFooterInclude Include src for the notification footer for each notification, access the notification via notification + * @param {object} customScope Object containing any variables/functions used by the included src, access via customScope. + * + * @example + + +
      +
      + +
      + +
      + +
      +
      + +
      +
      + +
      +
      +
      + + {{notificationGroup.heading}} + + + {{notificationGroup.subHeading}} + + + + + Clear All + + + +
      + + + {{notification.message}} +
      + {{notification.timeStamp | date:'MM/dd/yyyy'}} + {{notification.timeStamp | date:'h:mm:ss a'}} +
      +
      +
      +
      +
      + + + {{notification.message}} + +
      +
      +
      + {{notification.timeStamp | date:'MM/dd/yyyy'}} + {{notification.timeStamp | date:'h:mm:ss a'}} +
      + +
      +
      +
      +
      + + angular.module('patternfly.notification').controller('DrawerCtrl', ['$scope', + function ($scope) { + var currentTime = (new Date()).getTime(); + $scope.hideDrawer = true; + $scope.toggleShowDrawer = function () { + $scope.hideDrawer = !$scope.hideDrawer; + }; + + var menuActions = [ + { + name: 'Action', + title: 'Perform an action' + }, + { + name: 'Another Action', + title: 'Do something else' + }, + { + name: 'Disabled Action', + title: 'Unavailable action', + isDisabled: true + }, + { + name: 'Something Else', + title: '' + }, + { + isSeparator: true + }, + { + name: 'Grouped Action 1', + title: 'Do something' + }, + { + name: 'Grouped Action 2', + title: 'Do something similar' + } + ]; + + + $scope.groups = [ + { + heading: "Notification Tab 1", + subHeading: "5 New Events", + notifications: [ + { + unread: true, + message: "A New Event! Huzzah! Bold", + status: 'info', + actions: menuActions, + timeStamp: currentTime - (1 * 60 * 60 * 1000) + }, + { + unread: true, + message: "Another Event Notification", + status: 'ok', + actions: menuActions, + timeStamp: currentTime - (2 * 60 * 60 * 1000) + }, + { + unread: false, + message: "Another Event Notification", + status: 'warning', + actions: menuActions, + timeStamp: currentTime - (10 * 60 * 60 * 1000) + }, + { + unread: false, + message: "Another Event Notification", + status: 'error', + actions: menuActions, + timeStamp: currentTime - (12 * 60 * 60 * 1000) + }, + { + unread: true, + message: "A New Event! Huzzah! Bold", + status: 'info', + actions: menuActions, + timeStamp: currentTime - (1 * 60 * 60 * 1000) + }, + { + unread: true, + message: "Another Event Notification", + status: 'error', + actions: menuActions, + timeStamp: currentTime - (2 * 60 * 60 * 1000) + }, + { + unread: false, + message: "Another Event Notification", + status: 'ok', + actions: menuActions, + timeStamp: currentTime - (10 * 60 * 60 * 1000) + }, + { + unread: false, + message: "Another Event Notification", + status: 'warning', + actions: menuActions, + timeStamp: currentTime - (12 * 60 * 60 * 1000) + }, + { + unread: true, + message: "Another Event Notification", + status: 'info', + actions: menuActions, + timeStamp: currentTime - (240 * 60 * 60 * 1000) + } + ], + isLoading: true + }, + { + heading: "Notification Tab 2", + subHeading: "3 New Events", + notifications: [ + { + unread: true, + message: "A New Event! Huzzah! Bold", + status: 'info', + actions: menuActions, + timeStamp: currentTime - (1 * 60 * 60 * 1000) + }, + { + unread: true, + message: "Another Event Notification", + status: 'error', + actions: menuActions, + timeStamp: currentTime - (2 * 60 * 60 * 1000) + }, + { + unread: false, + message: "Another Event Notification", + status: 'warning', + actions: menuActions, + timeStamp: currentTime - (10 * 60 * 60 * 1000) + }, + { + unread: false, + message: "Another Event Notification", + status: 'ok', + actions: menuActions, + timeStamp: currentTime - (12 * 60 * 60 * 1000) + }, + { + unread: true, + message: "Another Event Notification", + status: 'warning', + actions: menuActions, + timeStamp: currentTime - (240 * 60 * 60 * 1000) + } + ] + }, + { + heading: "Notification Tab 3", + subHeading: "3 New Events", + notifications: [ + { + unread: true, + message: "A New Event! Huzzah! Bold", + status: 'ok', + actions: menuActions, + timeStamp: currentTime - (1 * 60 * 60 * 1000) + }, + { + unread: true, + message: "Another Event Notification", + status: 'warning', + actions: menuActions, + timeStamp: currentTime - (2 * 60 * 60 * 1000) + }, + { + unread: false, + message: "Another Event Notification", + status: 'info', + actions: menuActions, + timeStamp: currentTime - (10 * 60 * 60 * 1000) + }, + { + unread: false, + message: "Another Event Notification", + status: 'ok', + actions: menuActions, + timeStamp: currentTime - (12 * 60 * 60 * 1000) + }, + { + unread: true, + message: "Another Event Notification", + status: 'error', + actions: menuActions, + timeStamp: currentTime - (240 * 60 * 60 * 1000) + } + ] + }, + { + heading: "Notification Tab 4", + subHeading: "3 New Events", + notifications: [ + { + unread: true, + message: "A New Event! Huzzah! Bold", + status: 'warning', + actions: menuActions, + timeStamp: currentTime - (1 * 60 * 60 * 1000) + }, + { + unread: true, + message: "Another Event Notification", + status: 'ok', + actions: menuActions, + timeStamp: currentTime - (2 * 60 * 60 * 1000) + }, + { + unread: false, + message: "Another Event Notification", + status: 'ok', + actions: menuActions, + timeStamp: currentTime - (10 * 60 * 60 * 1000) + }, + { + unread: false, + message: "Another Event Notification", + status: 'error', + actions: menuActions, + timeStamp: currentTime - (12 * 60 * 60 * 1000) + }, + { + unread: true, + message: "Another Event Notification", + status: 'info', + actions: menuActions, + timeStamp: currentTime - (240 * 60 * 60 * 1000) + } + ] + }, + { + heading: "Notification Tab 5", + subHeading: "3 New Events", + notifications: [ + { + unread: true, + message: "A New Event! Huzzah! Bold", + status: 'error', + actions: menuActions, + timeStamp: currentTime - (1 * 60 * 60 * 1000) + }, + { + unread: true, + message: "Another Event Notification", + status: 'error', + actions: menuActions, + timeStamp: currentTime - (2 * 60 * 60 * 1000) + }, + { + unread: false, + message: "Another Event Notification", + status: 'warning', + actions: menuActions, + timeStamp: currentTime - (10 * 60 * 60 * 1000) + }, + { + unread: false, + message: "Another Event Notification", + status: 'warning', + actions: menuActions, + timeStamp: currentTime - (12 * 60 * 60 * 1000) + }, + { + unread: true, + message: "Another Event Notification", + status: 'error', + actions: menuActions, + timeStamp: currentTime - (240 * 60 * 60 * 1000) + } + ] + } + ]; + + $scope.actionsText = ""; + $scope.actionButtonCB = function (group) { + $scope.actionsText = "Action Button clicked: " + group.heading + "\n" + $scope.actionsText; + group.notifications.forEach(function(nextNotification) { + nextNotification.unread = false; + }); + group.subHeading = "0 New Events"; + }; + + // + // Define customScope to contain anything that needs to be accessed from the included source + // html files (heading, subheading, or notificaton body). + // + + $scope.customScope = {}; + $scope.customScope.getNotficationStatusIconClass = function (notification) { + var retClass = ''; + if (notification && notification.status) { + if (notification.status === 'info') { + retClass = "pficon pficon-info"; + } else if (notification.status === 'error') { + retClass = "pficon pficon-error-circle-o"; + } else if (notification.status === 'warning') { + retClass = "pficon pficon-warning-triangle-o"; + } else if (notification.status === 'ok') { + retClass = "pficon pficon-ok"; + } + } + return retClass; + }; + $scope.customScope.handleAction = function (notification, action) { + if (action.isDisabled) { + return; + } + var newText = notification.message + " - " + action.name; + $scope.actionsText = newText + "\n" + $scope.actionsText; + }; + $scope.customScope.clearAll = function (group) { + var newText = group.heading + " - Clear All"; + $scope.actionsText = newText + "\n" + $scope.actionsText; + group.notifications = []; + group.subHeading = "0 New Events"; + }; + + $scope.customScope.markRead = function (notification) { + if (notification.unread) { + notification.unread = false; + $scope.actionsText = "Mark notification read" + "\n" + $scope.actionsText; + var notificationGroup = $scope.groups.find(function(group) { + return group.notifications.find(function(nextNotification) { + return notification == nextNotification; + }); + }); + var unread = notificationGroup.notifications.filter(function(nextNotification) { + return nextNotification.unread; + }); + notificationGroup.subHeading = unread.length + " New Events"; + } + }; + } + ]); + +
      +*/ +angular.module('patternfly.notification').directive('pfNotificationDrawer', ["$window", "$timeout", function ($window, $timeout) { + 'use strict'; + return { + restrict: 'A', + scope: { + drawerHidden: '=?', + allowExpand: '=?', + drawerExpanded: '=?', + drawerTitle: '@', + notificationGroups: '=', + actionButtonTitle: '@', + actionButtonCallback: '=?', + titleInclude: '@', + headingInclude: '@', + subheadingInclude: '@', + notificationBodyInclude: '@', + notificationFooterInclude: '@', + customScope: '=?' + }, + templateUrl: 'notification/notification-drawer.html', + controller: ["$scope", function ($scope) { + if (!$scope.allowExpand || angular.isUndefined($scope.drawerExpanded)) { + $scope.drawerExpanded = false; + } + }], + link: function (scope, element) { + + scope.$watch('notificationGroups', function () { + var openFound = false; + scope.notificationGroups.forEach(function (group) { + if (group.open) { + if (openFound) { + group.open = false; + } else { + openFound = true; + } + } + }); + }); + + scope.$watch('drawerHidden', function () { + $timeout(function () { + angular.element($window).triggerHandler('resize'); + }, 100); + }); + + scope.toggleCollapse = function (selectedGroup) { + if (selectedGroup.open) { + selectedGroup.open = false; + } else { + scope.notificationGroups.forEach(function (group) { + group.open = false; + }); + selectedGroup.open = true; + } + }; + + scope.toggleExpandDrawer = function () { + scope.drawerExpanded = !scope.drawerExpanded; + }; + + if (scope.groupHeight) { + element.find('.panel-group').css("height", scope.groupHeight); + } + if (scope.groupClass) { + element.find('.panel-group').addClass(scope.groupClass); + } + } + }; +}]); +;/** + * @ngdoc service + * @name patternfly.notification.Notification + * @requires $rootScope + * + * @description + * Notification service used to notify user about important events in the application. + * + * ## Configuring the service + * + * You can configure the service with: setDelay, setVerbose and setPersist. + * + * ### Notifications.setDelay + * Set the delay after which the notification is dismissed. The argument of this method expects miliseconds. Default + * delay is 5000 ms. + * + * ### Notifications.setVerbose + * Set the verbose mode to on (default) or off. During the verbose mode, each notification is printed in the console, + * too. This is done using the default angular.js $log service. + * + * ### Notifications.setPersist + * Sets persist option for particular modes. Notification with persistent mode won't be dismissed after delay, but has + * to be closed manually with the close button. By default, the "error" and "httpError" modes are set to persistent. + * The input is an object in format {mode: persistValue}. + * + * ## Configuration Example + * ```js + * angular.module('myApp', []).config(function (NotificationsProvider) { + * NotificationsProvider.setDelay(10000).setVerbose(false).setPersist({'error': true, 'httpError': true, 'warn': true}); + * }); + * ``` + * @example + + + +
      + + +
      +
      + +
      + +
      +
      +
      + +
      + +
      +
      +
      +
      + +
      +
      +
      +
      +
      + + + angular.module( 'patternfly.notification' ).controller( 'NotificationDemoCtrl', function( $scope, Notifications ) { + + var typeMap = { 'Info': Notifications.info, + 'Success': Notifications.success, + 'Warning': Notifications.warn, + 'Danger': Notifications.error }; + + $scope.types = Object.keys(typeMap); + + $scope.type = $scope.types[0]; + $scope.message = 'Default notification message.'; + + $scope.notify = function () { + typeMap[$scope.type]($scope.message); + } + }); + + +
      + */ +angular.module('patternfly.notification').provider('Notifications', function () { + 'use strict'; + + // time (in ms) the notifications are shown + this.delay = 8000; + this.verbose = true; + this.notifications = {}; + this.persist = {'error': true, 'httpError': true}; + + this.setDelay = function (delay) { + this.delay = delay; + return this; + }; + + this.setVerbose = function (verbose) { + this.verbose = verbose; + return this; + }; + + this.setPersist = function (persist) { + this.persist = persist; + }; + + this.$get = ['$rootScope', '$timeout', '$log', function ($rootScope, $timeout, $log) { + var delay = this.delay; + var notifications = this.notifications; + var verbose = this.verbose; + var persist = this.persist; + + var modes = { + info: { type: 'info', header: 'Info!', log: 'info'}, + success: { type: 'success', header: 'Success!', log: 'info'}, + error: { type: 'danger', header: 'Error!', log: 'error'}, + warn: { type: 'warning', header: 'Warning!', log: 'warn'} + }; + + $rootScope.notifications = {}; + $rootScope.notifications.data = []; + + $rootScope.notifications.remove = function (index) { + $rootScope.notifications.data.splice(index, 1); + }; + + if (!$rootScope.notifications) { + $rootScope.notifications.data = []; + } + + notifications.message = function (type, header, message, isPersistent, closeCallback, actionTitle, actionCallback, menuActions) { + var notification = { + type : type, + header: header, + message : message, + isPersistent: isPersistent, + closeCallback: closeCallback, + actionTitle: actionTitle, + actionCallback: actionCallback, + menuActions: menuActions + }; + + notification.show = true; + $rootScope.notifications.data.push(notification); + + if (!notification.isPersistent) { + notification.viewing = false; + $timeout(function () { + notification.show = false; + if (!notification.viewing) { + notifications.remove(notification); + } + }, delay); + } + }; + + function createNotifyMethod (mode) { + return function (message, header, persistent, closeCallback, actionTitle, actionCallback, menuActions) { + if (angular.isUndefined(header)) { + header = modes[mode].header; + } + if (angular.isUndefined(persistent)) { + persistent = persist[mode]; + } + notifications.message(modes[mode].type, header, message, persistent, closeCallback, actionTitle, actionCallback, menuActions); + if (verbose) { + $log[modes[mode].log](message); + } + }; + } + + angular.forEach(modes, function (mode, index) { + notifications[index] = createNotifyMethod(index); + }); + + + notifications.httpError = function (message, httpResponse) { + message += ' (' + (httpResponse.data.message || httpResponse.data.cause || httpResponse.data.cause || httpResponse.data.errorMessage) + ')'; + notifications.message('danger', 'Error!', message, persist.httpError); + if (verbose) { + $log.error(message); + } + }; + + notifications.remove = function (notification) { + var index = $rootScope.notifications.data.indexOf(notification); + if (index !== -1) { + notifications.removeIndex(index); + } + }; + + notifications.removeIndex = function (index) { + $rootScope.notifications.remove(index); + }; + + notifications.setViewing = function (notification, viewing) { + notification.viewing = viewing; + if (!viewing && !notification.show) { + notifications.remove(notification); + } + }; + + notifications.data = $rootScope.notifications.data; + + return notifications; + }]; + +}); + +/** + * @ngdoc directive + * @name patternfly.notification.directive:pfNotificationList + * @restrict E + * + * @description + * Using this directive automatically creates a list of notifications generated by the {@link api/patternfly.notification.Notification notification} service. + * + * @example + + + +
      + + + +
      +
      + +
      + +
      +
      +
      + +
      + +
      +
      +
      +
      + +
      +
      +
      +
      +
      + + + angular.module('patternfly.notification').controller( 'NotificationDemoCtrl', function( $scope, Notifications ) { + $scope.message = 'Default Message.'; + + var typeMap = { 'Info': Notifications.info, + 'Success': Notifications.success, + 'Warning': Notifications.warn, + 'Danger': Notifications.error }; + + $scope.types = Object.keys(typeMap); + + $scope.type = $scope.types[0]; + $scope.message = 'Default notification message.'; + + $scope.notify = function () { + typeMap[$scope.type]($scope.message); + } + }); + + +
      + */ +angular.module('patternfly.notification').directive('pfNotificationList', function () { + 'use strict'; + + NotificationListController.$inject = ["$scope", "$rootScope"]; + return { + restrict: 'E', + controller: NotificationListController, + templateUrl: 'notification/notification-list.html' + }; + + function NotificationListController ($scope, $rootScope) { + $scope.notifications = $rootScope.notifications; + } +}); +;/** + * @ngdoc directive + * @name patternfly.notification.directive:pfToastNotificationList + * @restrict A + * @scope + * + * @param {Array} notifications The list of current notifcations to display. Each notification should have the following (see pfToastNotification): + *
        + *
      • .type - (String) The type of the notification message. Allowed value is one of these: 'success','info','danger', 'warning' + *
      • .header - (String) The header to display for the notification (optional) + *
      • .message - (String) The main text message of the notification. + *
      • .actionTitle Text to show for the primary action, optional. + *
      • .actionCallback (function(this notification)) Function to invoke when primary action is selected, optional + *
      • .menuActions Optional list of actions to place in the kebab menu:
        + *
          + *
        • .name - (String) The name of the action, displayed on the button + *
        • .actionFn - (function(action, this notification)) Function to invoke when the action selected + *
        • .isDisabled - (Boolean) set to true to disable the action + *
        • .isSeparator - (Boolean) set to true if this is a placehodler for a separator rather than an action + *
        + *
      • .isPersistent Flag to show close button for the notification even if showClose is false. + *
      + * @param {Boolean} showClose Flag to show the close button on all notifications (not shown if the notification has menu actions) + * @param {function} closeCallback (function(data)) Function to invoke when closes a toast notification + * @param {function} updateViewing (function(boolean, data)) Function to invoke when user is viewing/not-viewing (hovering on) a toast notification + * + * @description + * Using this directive displayes a list of toast notifications + * + * @example + + + +
      +
      +
      +
      +
      +
      + +
      + +
      +
      +
      + +
      + +
      +
      +
      + +
      + +
      +
      +
      + +
      + +
      +
      +
      + +
      + +
      +
      +
      + +
      + +
      + +
      + +
      +
      +
      +
      + +
      +
      +
      +
      +
      + +
      +
      + +
      +
      +
      +
      + + + angular.module('patternfly.notification').controller( 'ToastNotificationListDemoCtrl', function( $scope, $rootScope, Notifications ) { + $scope.message = 'Default Message.'; + + var typeMap = { 'Info': 'info', + 'Success': 'success', + 'Warning': 'warning', + 'Danger': 'danger' }; + + $scope.types = Object.keys(typeMap); + + $scope.type = $scope.types[0]; + $scope.header = 'Default header.'; + $scope.message = 'Default notification message.'; + $scope.showClose = false; + $scope.persistent = false; + + $scope.primaryAction = ''; + + $scope.showMenu = false; + var performAction = function (menuAction, data) { + $scope.actionText += menuAction.name + ": " + data.message + '\n'; + }; + $scope.menuActions = [ + { + name: 'Action', + title: 'Perform an action', + actionFn: performAction + }, + { + name: 'Another Action', + title: 'Do something else', + actionFn: performAction + }, + { + name: 'Disabled Action', + title: 'Unavailable action', + actionFn: performAction, + isDisabled: true + }, + { + name: 'Something Else', + title: '', + actionFn: performAction + }, + { + isSeparator: true + }, + { + name: 'Grouped Action 1', + title: 'Do something', + actionFn: performAction + }, + { + name: 'Grouped Action 2', + title: 'Do something similar', + actionFn: performAction + } + ]; + + $scope.actionText = ""; + + $scope.handleAction = function (data) { + $scope.actionText = $scope.primaryAction + ": " + data.message + '\n' + $scope.actionText; + }; + $scope.handleClose = function (data) { + $scope.actionText = "Closed: " + data.message + '\n'+ $scope.actionText; + Notifications.remove(data); + }; + $scope.updateViewing = function (viewing, data) { + Notifications.setViewing(data, viewing); + }; + + $scope.notify = function () { + Notifications.message ( + typeMap[$scope.type], + $scope.header, + $scope.message, + $scope.persistent, + $scope.handleClose, + $scope.primaryAction, + $scope.handleAction, + ($scope.showMenu ? $scope.menuActions : undefined) + ); + } + + $scope.notifications = Notifications.data; + }); + + +
      + */ +angular.module('patternfly.notification').directive('pfToastNotificationList', function () { + 'use strict'; + + return { + restrict: 'A', + scope: { + notifications: '=', + showClose: '=?', + closeCallback: '=?', + updateViewing: '=?' + }, + templateUrl: 'notification/toast-notification-list.html', + controller: ["$scope", function ($scope) { + $scope.handleClose = function (notification) { + if (angular.isFunction($scope.closeCallback)) { + $scope.closeCallback(notification); + } + }; + $scope.handleViewingChange = function (isViewing, notification) { + if (angular.isFunction($scope.updateViewing)) { + $scope.updateViewing(isViewing, notification); + } + }; + }] + }; +}); +;/** + * @ngdoc directive + * @name patternfly.notification.directive:pfToastNotification + * @restrict E + * @scope + * + * @param {string} notificationType The type of the notification message. Allowed value is one of these: 'success','info','danger', 'warning' + * @param {string} header The header text of the notification. + * @param {string} message The main text message of the notification. + * @param {boolean} showClose Flag to show the close button, default: true + * @param {function} closeCallback (function(data)) Function to invoke when close action is selected, optional + * @param {string} actionTitle Text to show for the primary action, optional. + * @param {function} actionCallback (function(data)) Function to invoke when primary action is selected, optional + * @param {Array} menuActions Optional list of actions to place in the kebab menu:
      + *
        + *
      • .name - (String) The name of the action, displayed on the button + *
      • .actionFn - (function(action, data)) Function to invoke when the action selected + *
      • .isDisabled - (Boolean) set to true to disable the action + *
      • .isSeparator - (Boolean) set to true if this is a placehodler for a separator rather than an action + *
      + * @param {function} updateViewing (function(boolean, data)) Function to invoke when user is viewing/no-viewing (hovering on) the toast + * @param {object} data Any data needed by the callbacks (optional) + * + * @description + * Toast notifications are used to notify users of a system occurence. Toast notifications should be transient and stay on the screen for 8 seconds, + * so that they do not block the information behind them for too long, but allows the user to read the message. + * The pfToastNotification directive allows status, header, message, primary action and menu actions for the notification. The notification can also + * allow the user to close the notification. + * + * Note: Using the kebab menu (menu actions) with the close button is not currently supported. If both are specified the close button will not be shown. + * Add a close menu item if you want to have both capabilities. + * + * @example + + + +
      +
      +
      +
      + +
      +
      + +
      + +
      +
      +
      + +
      + +
      +
      +
      + +
      + +
      +
      +
      + +
      + +
      +
      +
      + +
      + +
      + +
      + +
      +
      +
      +
      +
      + +
      +
      + +
      +
      +
      + + + angular.module( 'patternfly.notification' ).controller( 'ToastNotificationDemoCtrl', function( $scope, Notifications ) { + $scope.types = ['success','info','danger', 'warning']; + $scope.type = $scope.types[0]; + $scope.showClose = false; + + $scope.header = 'Default Header.'; + $scope.message = 'Default Message.'; + $scope.primaryAction = ''; + + $scope.showMenu = false; + var performAction = function (menuAction) { + $scope.actionText += menuAction.name + '\n'; + }; + var menuActions = [ + { + name: 'Action', + title: 'Perform an action', + actionFn: performAction + }, + { + name: 'Another Action', + title: 'Do something else', + actionFn: performAction + }, + { + name: 'Disabled Action', + title: 'Unavailable action', + actionFn: performAction, + isDisabled: true + }, + { + name: 'Something Else', + title: '', + actionFn: performAction + }, + { + isSeparator: true + }, + { + name: 'Grouped Action 1', + title: 'Do something', + actionFn: performAction + }, + { + name: 'Grouped Action 2', + title: 'Do something similar', + actionFn: performAction + } + ]; + + $scope.$watch('showMenu', function () { + if ($scope.showMenu) { + $scope.menuActions = menuActions; + } else { + $scope.menuActions = undefined; + } + }); + + $scope.actionText = ""; + + $scope.handleAction = function () { + $scope.actionText = $scope.primaryAction + '\n' + $scope.actionText; + }; + $scope.closeCallback = function () { + $scope.actionText = "Close" + '\n' + $scope.actionText; + }; + }); + + +
      + */ +angular.module( 'patternfly.notification' ).directive('pfToastNotification', function () { + 'use strict'; + + return { + scope: { + 'notificationType': '@', + 'message': '@', + 'header': '@', + 'showClose': '@', + 'closeCallback': '=?', + 'actionTitle': '@', + 'actionCallback': '=?', + 'menuActions': '=?', + 'updateViewing': '=?', + 'data': '=?' + }, + restrict: 'A', + templateUrl: 'notification/toast-notification.html', + controller: ["$scope", function ($scope) { + $scope.notificationType = $scope.notificationType || 'info'; + + $scope.updateShowClose = function () { + $scope.showCloseButton = ($scope.showClose === 'true') && (angular.isUndefined($scope.menuActions) || $scope.menuActions.length < 1); + }; + + $scope.handleClose = function () { + if (angular.isFunction($scope.closeCallback)) { + $scope.closeCallback($scope.data); + } + }; + + $scope.handleAction = function () { + if (angular.isFunction($scope.actionCallback)) { + $scope.actionCallback($scope.data); + } + }; + + $scope.handleMenuAction = function (menuAction) { + if (menuAction && angular.isFunction(menuAction.actionFn) && (menuAction.isDisabled !== true)) { + menuAction.actionFn(menuAction, $scope.data); + } + }; + + $scope.handleEnter = function () { + if (angular.isFunction($scope.updateViewing)) { + $scope.updateViewing(true, $scope.data); + } + }; + $scope.handleLeave = function () { + if (angular.isFunction($scope.updateViewing)) { + $scope.updateViewing(false, $scope.data); + } + }; + + $scope.updateShowClose (); + }], + link: function (scope) { + scope.$watch('showClose', function () { + scope.updateShowClose(); + }); + scope.$watch('menuActions', function () { + scope.updateShowClose(); + }); + } + }; +}); +;/** + * @ngdoc directive + * @name patternfly.select:pfSelect + * @element select + * + * @param {string} ngModel Model binding using the {@link https://docs.angularjs.org/api/ng/type/ngModel.NgModelController/ NgModelController} is mandatory. + * @param {string=} ngOptions The `{@link https://docs.angularjs.org/api/ng/directive/select/ ngOptions}` attribute can be used to dynamically generate a list of `