From 8e83c25788017acd56271a72286f7dcbc974e76d Mon Sep 17 00:00:00 2001 From: Sudarshan Kumar Date: Tue, 18 Feb 2020 16:16:26 +0530 Subject: [PATCH] Changes made to upgrade pom version Upgraded pom version Issue-ID: PORTAL-769 Change-Id: I65ae68acda464531d699dcb459d328de19a3c7c7 Signed-off-by: Sudarshan Kumar --- deliveries/.env | 2 +- deliveries/Dockerfile.mariadb | 10 +- deliveries/Dockerfile.widgetms | 5 +- deliveries/os_docker_base.sh | 102 +- deliveries/os_docker_push.sh | 5 +- deliveries/os_docker_release.sh | 5 +- ecomp-portal-BE-common/.gitignore | 1 + ecomp-portal-BE-common/pom.xml | 12 +- .../onap/portalapp/music/service/MusicService.java | 688 + .../onap/portalapp/music/util/MusicProperties.java | 225 - .../org/onap/portalapp/music/util/MusicUtil.java | 220 - .../controller/ExternalAppsRestfulController.java | 31 + .../controller/FunctionalMenuController.java | 12 +- .../portal/controller/HealthCheckController.java | 21 +- .../controller/WebAnalyticsExtAppController.java | 41 +- .../portalapp/portal/domain/EPServiceCookie.java | 54 + .../exceptions/NoHealthyServiceException.java | 4 +- .../interceptor/PortalResourceInterceptor.java | 1 + .../portalapp/portal/listener/HealthMonitor.java | 25 +- .../portal/scheduler/SchedulerRestInterface.java | 104 +- .../scheduler/SchedulerRestInterfaceIfc.java | 5 +- .../portal/scheduler/client/HttpBasicClient.java | 15 +- .../service/ExternalAccessRolesServiceImpl.java | 2 +- .../portal/service/UserRolesCommonServiceImpl.java | 34 +- .../portalapp/portal/service/WidgetMService.java | 18 +- .../portal/service/WidgetMServiceImpl.java | 9 + .../portal/transport/AppWithRolesForUser.java | 3 +- .../portal/transport/FunctionalMenuItem.java | 7 +- .../portal/utils/EPCommonSystemProperties.java | 6 + .../portalapp/portal/utils/EcompPortalUtils.java | 18 + .../utils/MusicCookieCsrfTokenRepository.java | 28 +- .../portalapp/util/CommonSessionCookieUtil.java | 151 + .../src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml | 6 + .../fusion/external/angular-1.5/angular-animate.js | 4121 -- .../external/angular-1.5/angular-animate.min.js | 56 - .../fusion/external/angular-1.5/angular-aria.js | 398 - .../external/angular-1.5/angular-aria.min.js | 14 - .../fusion/external/angular-1.5/angular-cookies.js | 322 - .../external/angular-1.5/angular-cookies.min.js | 9 - .../fusion/external/angular-1.5/angular-csp.css | 21 - .../fusion/external/angular-1.5/angular-loader.js | 484 - .../external/angular-1.5/angular-loader.min.js | 10 - .../external/angular-1.5/angular-message-format.js | 980 - .../angular-1.5/angular-message-format.min.js | 26 - .../external/angular-1.5/angular-messages.js | 687 - .../external/angular-1.5/angular-messages.min.js | 12 - .../fusion/external/angular-1.5/angular-mocks.js | 2842 -- .../external/angular-1.5/angular-resource.js | 768 - .../external/angular-1.5/angular-resource.min.js | 15 - .../fusion/external/angular-1.5/angular-route.js | 1016 - .../external/angular-1.5/angular-route.min.js | 15 - .../external/angular-1.5/angular-sanitize.js | 717 - .../external/angular-1.5/angular-sanitize.min.js | 15 - .../external/angular-1.5/angular-scenario.js | 41849 ------------------- .../fusion/external/angular-1.5/angular-touch.js | 729 - .../external/angular-1.5/angular-touch.min.js | 14 - .../app/fusion/external/angular-1.5/angular.js | 30428 -------------- .../app/fusion/external/angular-1.5/angular.min.js | 307 - .../app/fusion/external/angular-1.5/errors.json | 1 - .../app/fusion/external/angular-1.5/version.json | 1 - .../app/fusion/external/angular-1.5/version.txt | 1 - .../angular-ui/ui-bootstrap-tpls-1.1.2.min.js | 10 - .../angular-ui/ui-bootstrap-tpls-1.2.4.min.js | 10 - .../angular-ui/ui-sortable/v0.13.4/sortable.min.js | 8 - .../static/ebz/angular_js/angular-sanitize.js | 647 - .../main/webapp/static/ebz/angular_js/angular.js | 22024 ---------- .../main/webapp/static/ebz/angular_js/gestures.js | 1495 - .../conf/MusicSessionRepositoryHandlerTest.java | 6 +- .../controller/FunctionalMenuControllerTest.java | 39 +- .../WebAnalyticsExtAppControllerTest.java | 37 +- .../portal/controller/WidgetMSControllerTest.java | 23 +- .../controller/WidgetsCatalogControllerTest.java | 8 +- .../service/UserRolesCommonServiceImplTest.java | 15 +- .../portal/service/WidgetMServiceImplTest.java | 32 +- .../portal/transport/AppWithRolesForUserTest.java | 4 +- ecomp-portal-BE-os/pom.xml | 28 +- .../org/onap/portalapp/util/SessionCookieUtil.java | 43 +- .../src/main/webapp/WEB-INF/conf/system.properties | 6 +- ecomp-portal-BE-os/src/main/webapp/WEB-INF/web.xml | 18 +- .../external/b2b/css/b2b-angular/font_icons.css | 1 - .../ds2/css/digital-ng-library/ecomp-ionicons.css | 159 - .../ds2/css/digital-ng-library/ionicons.css | 1480 - .../app/fusion/external/ds2/css/fonts/ionicons.eot | Bin 120724 -> 0 bytes .../app/fusion/external/ds2/css/fonts/ionicons.svg | 2230 - .../app/fusion/external/ds2/css/fonts/ionicons.ttf | Bin 188508 -> 0 bytes .../fusion/external/ds2/css/fonts/ionicons.woff | Bin 67904 -> 0 bytes .../portalapp/utils/SessionCookieUtilTest.java | 10 +- .../PortalDMLMySql_2_6_Common.sql | 4 +- ecomp-portal-DB-os/PortalDMLMySql_2_6_OS.sql | 7 +- ecomp-portal-FE-os/pom.xml | 2 +- ecomp-portal-widget-ms/common-widgets/pom.xml | 2 +- ecomp-portal-widget-ms/pom.xml | 2 +- ecomp-portal-widget-ms/widget-ms/pom.xml | 12 +- .../src/main/resources/application.properties | 14 +- pom.xml | 62 +- .../app/pages/get-access/get-access.component.ts | 7 +- portal-FE-os/src/environments/environment.prod.ts | 8 +- portal-FE-os/src/environments/environment.ts | 10 +- 98 files changed, 1494 insertions(+), 114697 deletions(-) create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/service/MusicService.java delete mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicProperties.java delete mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicUtil.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPServiceCookie.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/CommonSessionCookieUtil.java delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-animate.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-animate.min.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-aria.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-aria.min.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-cookies.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-cookies.min.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-csp.css delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-loader.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-loader.min.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-message-format.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-message-format.min.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-messages.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-messages.min.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-mocks.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-resource.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-resource.min.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-route.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-route.min.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-sanitize.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-sanitize.min.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-scenario.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-touch.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-touch.min.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular.min.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/errors.json delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/version.json delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/version.txt delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-ui/ui-bootstrap-tpls-1.1.2.min.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-ui/ui-bootstrap-tpls-1.2.4.min.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-ui/ui-sortable/v0.13.4/sortable.min.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/ebz/angular_js/angular-sanitize.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/ebz/angular_js/angular.js delete mode 100644 ecomp-portal-BE-common/src/main/webapp/static/ebz/angular_js/gestures.js delete mode 100644 ecomp-portal-BE-os/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/font_icons.css delete mode 100644 ecomp-portal-BE-os/src/main/webapp/app/fusion/external/ds2/css/digital-ng-library/ecomp-ionicons.css delete mode 100644 ecomp-portal-BE-os/src/main/webapp/app/fusion/external/ds2/css/digital-ng-library/ionicons.css delete mode 100644 ecomp-portal-BE-os/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.eot delete mode 100644 ecomp-portal-BE-os/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.svg delete mode 100644 ecomp-portal-BE-os/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.ttf delete mode 100644 ecomp-portal-BE-os/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.woff diff --git a/deliveries/.env b/deliveries/.env index c5961d33..47a0924f 100644 --- a/deliveries/.env +++ b/deliveries/.env @@ -18,7 +18,7 @@ SDK_WAR_DIR=sdk/ecomp-sdk/epsdk-app-os/target SDK_WAR_FILE=epsdk-app-os.war BE_WAR_DIR=ecomp-portal-BE-os/target BE_WAR_FILE=portal-be-os.war -FE_DIR=ecomp-portal-FE-os/dist/public +FE_DIR=portal-FE-os/dist/public WIDGET_MS_JAR_DIR=ecomp-portal-widget-ms/widget-ms/target WIDGET_MS_JAR_FILE=widget-ms.jar diff --git a/deliveries/Dockerfile.mariadb b/deliveries/Dockerfile.mariadb index 66fdc486..1506ec4f 100644 --- a/deliveries/Dockerfile.mariadb +++ b/deliveries/Dockerfile.mariadb @@ -8,7 +8,7 @@ COPY my.cnf /etc/mysql/my.cnf # Scripts are executed in alphabetical order -# Portal DDL and DML at v2.1 +# Portal DDL and DML at v2.6 COPY ${DB_SCRIPT_DIR}/PortalDDLMySql_2_6_Common.sql /docker-entrypoint-initdb.d/ COPY ${DB_SCRIPT_DIR}/PortalDDLMySql_2_6_OS.sql /docker-entrypoint-initdb.d/ COPY ${DB_SCRIPT_DIR}/PortalDMLMySql_2_6_Common.sql /docker-entrypoint-initdb.d/ @@ -16,7 +16,7 @@ COPY ${DB_SCRIPT_DIR}/PortalDMLMySql_2_6_OS.sql /docker-entrypoint-initdb.d/ # Do not copy the onboarding script here; it's mounted as a volume # SDK App DDL and DML -COPY ${DB_SCRIPT_DIR}/EcompSdkDDLMySql_2_6_Common.sql /docker-entrypoint-initdb.d/ -COPY ${DB_SCRIPT_DIR}/EcompSdkDDLMySql_2_6_OS.sql /docker-entrypoint-initdb.d/ -COPY ${DB_SCRIPT_DIR}/EcompSdkDMLMySql_2_6_Common.sql /docker-entrypoint-initdb.d/ -COPY ${DB_SCRIPT_DIR}/EcompSdkDMLMySql_2_6_OS.sql /docker-entrypoint-initdb.d/ +COPY ${DB_SCRIPT_DIR}/EcompSdkDDLMySql_2_5_Common.sql /docker-entrypoint-initdb.d/ +COPY ${DB_SCRIPT_DIR}/EcompSdkDDLMySql_2_5_OS.sql /docker-entrypoint-initdb.d/ +COPY ${DB_SCRIPT_DIR}/EcompSdkDMLMySql_2_5_Common.sql /docker-entrypoint-initdb.d/ +COPY ${DB_SCRIPT_DIR}/EcompSdkDMLMySql_2_5_OS.sql /docker-entrypoint-initdb.d/ diff --git a/deliveries/Dockerfile.widgetms b/deliveries/Dockerfile.widgetms index 49c899ea..82a2e4c6 100644 --- a/deliveries/Dockerfile.widgetms +++ b/deliveries/Dockerfile.widgetms @@ -1,7 +1,8 @@ # Large image # FROM openjdk:8-jdk # Tiny image; it includes java and nc -FROM openjdk:8-alpine +#FROM frolvlad/alpine-oraclejdk8:slim +FROM openjdk:8-jdk-alpine # Arguments are supplied by build script; # the defaults below only support testing @@ -13,5 +14,7 @@ RUN sh -c 'touch /app.jar' # Launch script COPY start-wms.sh / +RUN addgroup -g 1000 -S portal && adduser -u 1000 -S portal -G portal && mkdir logs / && chown -R portal:portal /start-wms.sh /tmp /etc/ssl/certs/java /logs && chmod -R 755 /start-wms.sh /etc/ssl/certs/java /logs /tmp + # Define default command CMD /start-wms.sh diff --git a/deliveries/os_docker_base.sh b/deliveries/os_docker_base.sh index 94832ff5..b2a32a78 100755 --- a/deliveries/os_docker_base.sh +++ b/deliveries/os_docker_base.sh @@ -14,48 +14,86 @@ if [ -z "$LATEST" ]; then exit 1 fi -# ONAP docker registry for pushing; may need to move -# this into os_docker_push, os_docker_release scripts -NEXUS_REPO=nexus3.onap.org:10003 - -# Build the containers -./build_portalapps_dockers.sh +# ONAP docker registry for pushing; has been moved to +# .env (or other .env override file from command line) +# NEXUS_REPO=nexus3.onap.org:10003 # Establish environment variables source $(dirname $0)/.env +if [ $1 ]; then + source $(dirname $0)/$1 +fi + +# Build the containers +if [ "$SKIP_BUILD_BEFORE_PUSH" = "please" ]; then + echo "SKIPPING DOCKER IMAGE BUILD!" +else + ./build_portalapps_dockers.sh $1 +fi + +if [ "${PORTAL_DOCKERFILE}" != "skip" ] && [ "${EP_IMG_NAME}" != "skip" ]; then + APP_VERSION="${NEXUS_REPO}/${EP_IMG_NAME}:${VERSION}" + APP_LATEST="${NEXUS_REPO}/${EP_IMG_NAME}:${LATEST}" + + docker tag ${EP_IMG_NAME}:${PORTAL_TAG} ${APP_VERSION} + docker tag ${EP_IMG_NAME}:${PORTAL_TAG} ${APP_LATEST} + + docker push ${APP_VERSION} + docker push ${APP_LATEST} +fi -APP_VERSION="${NEXUS_REPO}/${EP_IMG_NAME}:${VERSION}" -SDK_VERSION="${NEXUS_REPO}/${SDK_IMG_NAME}:${VERSION}" -DB_VERSION="${NEXUS_REPO}/${DB_IMG_NAME}:${VERSION}" -WMS_VERSION="${NEXUS_REPO}/${WMS_IMG_NAME}:${VERSION}" +if [ "${SDK_DOCKERFILE}" != "skip" ] && [ "${SDK_IMG_NAME}" != "skip" ]; then + SDK_VERSION="${NEXUS_REPO}/${SDK_IMG_NAME}:${VERSION}" + SDK_LATEST="${NEXUS_REPO}/${SDK_IMG_NAME}:${LATEST}" -APP_LATEST="${NEXUS_REPO}/${EP_IMG_NAME}:${LATEST}" -SDK_LATEST="${NEXUS_REPO}/${SDK_IMG_NAME}:${LATEST}" -DB_LATEST="${NEXUS_REPO}/${DB_IMG_NAME}:${LATEST}" -WMS_LATEST="${NEXUS_REPO}/${WMS_IMG_NAME}:${LATEST}" + docker tag ${SDK_IMG_NAME}:${PORTAL_TAG} ${SDK_VERSION} + docker tag ${SDK_IMG_NAME}:${PORTAL_TAG} ${SDK_LATEST} -# tag versions -docker tag ${EP_IMG_NAME}:${PORTAL_TAG} ${APP_VERSION} -docker tag ${EP_IMG_NAME}:${PORTAL_TAG} ${APP_LATEST} + docker push ${SDK_VERSION} + docker push ${SDK_LATEST} +fi + +if [ "${FE_DOCKERFILE}" != "skip" ] && [ "${FE_IMG_NAME}" != "skip" ]; then + FE_VERSION="${NEXUS_REPO}/${FE_IMG_NAME}:${VERSION}" + FE_LATEST="${NEXUS_REPO}/${FE_IMG_NAME}:${LATEST}" + + docker tag ${FE_IMG_NAME}:${PORTAL_TAG} ${FE_VERSION} + docker tag ${FE_IMG_NAME}:${PORTAL_TAG} ${FE_LATEST} -docker tag ${SDK_IMG_NAME}:${PORTAL_TAG} ${SDK_VERSION} -docker tag ${SDK_IMG_NAME}:${PORTAL_TAG} ${SDK_LATEST} + docker push ${FE_VERSION} + docker push ${FE_LATEST} +fi -docker tag ${DB_IMG_NAME}:${PORTAL_TAG} ${DB_VERSION} -docker tag ${DB_IMG_NAME}:${PORTAL_TAG} ${DB_LATEST} +if [ "${BE_DOCKERFILE}" != "skip" ] && [ "${BE_IMG_NAME}" != "skip" ]; then + BE_VERSION="${NEXUS_REPO}/${BE_IMG_NAME}:${VERSION}" + BE_LATEST="${NEXUS_REPO}/${BE_IMG_NAME}:${LATEST}" -docker tag ${WMS_IMG_NAME}:${PORTAL_TAG} ${WMS_VERSION} -docker tag ${WMS_IMG_NAME}:${PORTAL_TAG} ${WMS_LATEST} + docker tag ${BE_IMG_NAME}:${PORTAL_TAG} ${BE_VERSION} + docker tag ${BE_IMG_NAME}:${PORTAL_TAG} ${BE_LATEST} -# push to registry -docker push ${APP_VERSION} -docker push ${APP_LATEST} + docker push ${BE_VERSION} + docker push ${BE_LATEST} +fi -docker push ${SDK_VERSION} -docker push ${SDK_LATEST} +if [ "${DB_DOCKERFILE}" != "skip" ] && [ "${DB_IMG_NAME}" != "skip" ]; then + DB_VERSION="${NEXUS_REPO}/${DB_IMG_NAME}:${VERSION}" + DB_LATEST="${NEXUS_REPO}/${DB_IMG_NAME}:${LATEST}" -docker push ${DB_VERSION} -docker push ${DB_LATEST} + docker tag ${DB_IMG_NAME}:${PORTAL_TAG} ${DB_VERSION} + docker tag ${DB_IMG_NAME}:${PORTAL_TAG} ${DB_LATEST} + + docker push ${DB_VERSION} + docker push ${DB_LATEST} +fi + +if [ "${WMS_DOCKERFILE}" != "skip" ] && [ "${WMS_IMG_NAME}" != "skip" ]; then + WMS_VERSION="${NEXUS_REPO}/${WMS_IMG_NAME}:${VERSION}" + WMS_LATEST="${NEXUS_REPO}/${WMS_IMG_NAME}:${LATEST}" + + docker tag ${WMS_IMG_NAME}:${PORTAL_TAG} ${WMS_VERSION} + docker tag ${WMS_IMG_NAME}:${PORTAL_TAG} ${WMS_LATEST} + + docker push ${WMS_VERSION} + docker push ${WMS_LATEST} +fi -docker push ${WMS_VERSION} -docker push ${WMS_LATEST} diff --git a/deliveries/os_docker_push.sh b/deliveries/os_docker_push.sh index 0978ad83..1d1f3293 100755 --- a/deliveries/os_docker_push.sh +++ b/deliveries/os_docker_push.sh @@ -6,6 +6,9 @@ set -x # Establish environment variables source $(dirname $0)/.env +if [ $1 ]; then + source $(dirname $0)/$1 +fi if [ -z "$PORTAL_VERSION" ]; then echo "PORTAL_VERSION not set" @@ -20,4 +23,4 @@ TIMESTAMP=$(date +%C%y%m%dT%H%M%S) export VERSION="${PORTAL_VERSION}-STAGING-${TIMESTAMP}" export LATEST="${PORTAL_VERSION}-STAGING-latest" -exec ./os_docker_base.sh +./os_docker_base.sh $1 diff --git a/deliveries/os_docker_release.sh b/deliveries/os_docker_release.sh index 3ff88b2d..1fb8a9a5 100755 --- a/deliveries/os_docker_release.sh +++ b/deliveries/os_docker_release.sh @@ -6,6 +6,9 @@ set -x # Establish environment variables source $(dirname $0)/.env +if [ $1 ]; then + source $(dirname $0)/$1 +fi if [ -z "$PORTAL_VERSION" ]; then echo "PORTAL_VERSION not set" @@ -16,4 +19,4 @@ TIMESTAMP=$(date +%C%y%m%dT%H%M%S) export VERSION="${PORTAL_VERSION}-${TIMESTAMP}" export LATEST="${PORTAL_VERSION}" -exec ./os_docker_base.sh +./os_docker_base.sh $1 diff --git a/ecomp-portal-BE-common/.gitignore b/ecomp-portal-BE-common/.gitignore index 297f3102..81425ea0 100644 --- a/ecomp-portal-BE-common/.gitignore +++ b/ecomp-portal-BE-common/.gitignore @@ -3,6 +3,7 @@ .classpath .project .settings/ +/.factorypath /debug-logs/ /logs/ /bin/ diff --git a/ecomp-portal-BE-common/pom.xml b/ecomp-portal-BE-common/pom.xml index 070ee05c..d36d740b 100644 --- a/ecomp-portal-BE-common/pom.xml +++ b/ecomp-portal-BE-common/pom.xml @@ -5,7 +5,7 @@ org.onap.portal onap-portal-parent - 2.6.0 + 3.2.0 portal-be-common @@ -422,7 +422,7 @@ org.quartz-scheduler quartz - 2.3.1 + 2.3.2 @@ -564,7 +564,7 @@ commons-beanutils 1.9.4 - + commons-fileupload commons-fileupload @@ -582,12 +582,12 @@ io.springfox springfox-swagger2 - 2.7.0 + 2.9.2 io.springfox springfox-swagger-ui - 2.7.0 + 2.9.2 diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/service/MusicService.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/service/MusicService.java new file mode 100644 index 00000000..323a71fe --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/service/MusicService.java @@ -0,0 +1,688 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + *. + */ + +package org.onap.portalapp.music.service; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicQueryException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicCore; +import org.onap.music.main.ResultType; +import org.onap.music.main.ReturnType; +import org.onap.portalapp.music.conf.MusicSession; +import org.onap.portalapp.music.model.RestResponse; +import org.onap.portalapp.music.model.RestStatusEnum; +import org.onap.portalapp.music.util.MusicProperties; +import org.onap.portalapp.music.util.MusicUtil; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.session.Session; +import org.springframework.web.client.RestTemplate; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class MusicService { + static RestTemplate template = new RestTemplate(); + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicService.class); + + private static boolean isAtomicPut = MusicUtil.isAtomicPut(); + private static boolean isAtomicGet = MusicUtil.isAtomicGet(); + private static String musicKeySpace = MusicProperties.getProperty(MusicProperties.MUSIC_SESSION_KEYSPACE); + private static String musicMetaTable = MusicProperties.getProperty(MusicProperties.MUSIC_SESSION_META_TABLES); + private static String musicAttrTable = MusicProperties.getProperty(MusicProperties.MUSIC_SESSION_ATTR_TABLES); + + private static final String WITH_SESSION_ID = " with session id: "; + private static final String RESULT = "result:"; + private static final String WHERE = " WHERE "; + private static final String FROM = " FROM "; + private static final String DELETE = "DELETE "; + private static final String REMOVE_SESSION = "removeSession: "; + private static final String SUCCESS = "success"; + public static final String ATOMIC = "atomic"; + public static final String EVENTUAL = "eventual"; + public static final String CRITICAL = "critical"; + + /** + * Store session attribute name and values into Cassandra via Music + * + * @param attributeName + * @param value + * @param sessionId + * @return ReturnType that includes required body information for Music api + * @throws Exception + */ + public static ReturnType setAttribute(String attributeName, Object value, String sessionId) throws MusicLockingException { + logger.debug(EELFLoggerDelegate.debugLogger, "setAttribute: start with id " + sessionId); + String tableName = null; + ReturnType result = null; + boolean isMeta = MusicUtil.isSessionMetaAttr(attributeName); + PreparedQueryObject queryObject = new PreparedQueryObject(); + StringBuilder querySB = new StringBuilder(); + querySB.append("INSERT INTO ").append(musicKeySpace).append(".").append(getTableName(isMeta)) + .append(getInsertQuery(isMeta, attributeName)); + + queryObject.appendQueryString(querySB.toString()); + if (isMeta) { + queryObject.addValue(sessionId); + queryObject.addValue(String.valueOf(value)); + tableName = musicMetaTable; + } else { + queryObject.addValue(sessionId); + queryObject.addValue(attributeName); + queryObject.addValue(MusicUtil.musicSerialize(value)); + tableName = musicAttrTable; + + } + if (isAtomicPut) + result = MusicCore.atomicPut(musicKeySpace, tableName, sessionId, queryObject, null); + else + result = modEventualPut(queryObject); + logger.debug(EELFLoggerDelegate.debugLogger, "setAttribute: attributeName: " + attributeName + + WITH_SESSION_ID + sessionId + RESULT + result.getMessage()); + return result; + } + + /** + * Store session meta data values into Cassandra via Music + * + * @param session + * @return ReturnType that includes required body information for Music api + * @throws Exception + */ + public static ReturnType setMetaAttribute(Session session) throws MusicLockingException { + logger.debug(EELFLoggerDelegate.debugLogger, "setMetaAttribute: start with session id: " + session.getId()); + ReturnType result = null; + PreparedQueryObject queryObject = new PreparedQueryObject(); + StringBuilder querySB = new StringBuilder(); + querySB.append("INSERT INTO ").append(musicKeySpace).append(".").append(musicMetaTable).append("(") + .append(MusicProperties.PRIMARY_ID).append(",").append(MusicProperties.CREATION_TIME).append(",") + .append(MusicProperties.LAST_ACCESS_TIME).append(",").append(MusicProperties.MAX_INACTIVE_INTERVAL) + .append(",").append(MusicProperties.SESSION_ID).append(") VALUES (?,?,?,?,?);"); + + queryObject.appendQueryString(querySB.toString()); + queryObject.addValue(session.getId()); + queryObject.addValue(String.valueOf(session.getCreationTime())); + queryObject.addValue(String.valueOf(session.getLastAccessedTime())); + queryObject.addValue(String.valueOf(session.getMaxInactiveInterval())); + queryObject.addValue(session.getId()); + if (isAtomicPut) + result = MusicCore.atomicPut(musicKeySpace, musicMetaTable, session.getId(), queryObject, null); + else + result = modEventualPut(queryObject); + logger.debug(EELFLoggerDelegate.debugLogger, + "setMetaAttribute: with session id: " + session + RESULT + result.getMessage()); + + return result; + } + + /** + * Retrieve session meta data from Cassandra via Music + * + * @param sessionId + * @return MusicSession + * @throws Exception + */ + public static MusicSession getMetaAttribute(String sessionId) throws MusicLockingException,MusicServiceException { + logger.debug(EELFLoggerDelegate.debugLogger, "getMetaAttribute: start with session Id: "+ sessionId); + ResultSet result = null; + PreparedQueryObject queryObject = new PreparedQueryObject(); + StringBuilder querySB = new StringBuilder(); + querySB.append("SELECT * FROM ").append(musicKeySpace).append(".").append(musicMetaTable).append(WHERE) + .append(MusicProperties.PRIMARY_ID).append("=?;"); + queryObject.appendQueryString(querySB.toString()); + queryObject.addValue(sessionId); + if (isAtomicGet) + result = MusicCore.atomicGet(musicKeySpace, musicMetaTable, sessionId, queryObject); + else + result = modEventualGet(queryObject); + logger.debug(EELFLoggerDelegate.debugLogger, "getMetaAttribute: with session id: " + sessionId); + return MusicUtil.parseMetaData(result.one()); + } + + + /** + * Get proper column names (from meta or attribute table) base on isMeta + * + * @param isMeta + * @param attributeName + * @return String + */ + private static String getInsertQuery(boolean isMeta, String attributeName) { + logger.debug(EELFLoggerDelegate.debugLogger, "getInsertQuery: start inserting : " + attributeName); + StringBuilder querySB = new StringBuilder(); + if (isMeta) { + querySB.append(" (").append(MusicProperties.PRIMARY_ID).append(",").append(attributeName) + .append(") VALUES (?,?);"); + } else { + querySB.append(" (").append(MusicProperties.PRIMARY_ID).append(",").append(MusicProperties.ATTRIBUTE_NAME) + .append(",").append(MusicProperties.ATTRIBUTE_BYTES).append(") VALUES (?,?,?);"); + } + return querySB.toString(); + } + + /** + * Retrieve session attribute data from Cassandra via Music + * + * @param attributeName + * @param sessionId + * @return attribute value with T type + * @throws Exception + */ + public static T getAttribute(String attributeName, String sessionId) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "getAttribute: start with session id: " + sessionId); + ResultSet result = null; + String tableName = null; + boolean isMeta = MusicUtil.isSessionMetaAttr(attributeName); + PreparedQueryObject queryObject = new PreparedQueryObject(); + StringBuilder querySB = new StringBuilder(); + querySB.append("SELECT ").append(getColumn(attributeName, isMeta)).append(FROM).append(musicKeySpace) + .append(".").append(getTableName(isMeta)).append(WHERE).append(MusicProperties.PRIMARY_ID) + .append("= ?"); + + queryObject.addValue(sessionId); + if (!isMeta) { + querySB.append(" and ").append(MusicProperties.ATTRIBUTE_NAME).append("= ?"); + queryObject.addValue(attributeName); + tableName = musicAttrTable; + } else + tableName = musicMetaTable; + + queryObject.appendQueryString(querySB.toString()); + if (isAtomicGet) + result = MusicCore.atomicGet(musicKeySpace, tableName, sessionId, queryObject); + else + result = modEventualGet(queryObject); + return MusicUtil.musicRestResponseDataParsing(result, attributeName); + + } + + /** + * Remove session attribute data from Cassandra via Music + * + * @param attributeName + * @param sessionId + * @return ReturnType + * @throws MusicServiceException + * @throws MusicLockingException + */ + public static ReturnType removeAttribute(String attributeName, String sessionId) throws MusicLockingException { + logger.debug(EELFLoggerDelegate.debugLogger, "removeAttribute: start with session id: " + sessionId); + boolean isMeta = MusicUtil.isSessionMetaAttr(attributeName); + ReturnType result = null; + String tableName = null; + PreparedQueryObject queryObject = new PreparedQueryObject(); + StringBuilder querySB = new StringBuilder(); + querySB.append(DELETE).append(getDelColumn(isMeta, attributeName)).append(FROM).append(musicKeySpace) + .append(".").append(getTableName(isMeta)).append(WHERE).append(MusicProperties.PRIMARY_ID) + .append("= ? "); + queryObject.addValue(sessionId); + + if (!isMeta) { + querySB.append(" and ").append(MusicProperties.ATTRIBUTE_NAME).append("= ?"); + queryObject.addValue(attributeName); + tableName = musicAttrTable; + } else + tableName = musicMetaTable; + queryObject.appendQueryString(querySB.toString()); + if (isAtomicPut) + result = MusicCore.atomicPut(musicKeySpace, tableName, sessionId, queryObject, null); + else + result = modEventualPut(queryObject); + logger.debug(EELFLoggerDelegate.debugLogger, + REMOVE_SESSION + attributeName + WITH_SESSION_ID + sessionId + RESULT + result.getMessage()); + + return result; + } + + /** + * Remove entire session from Cassandra via Music + * + * @param sessionId + * @return ReturnType + * @throws MusicServiceException + * @throws MusicLockingException + */ + public static ReturnType removeSession(String sessionId) throws MusicLockingException { + ReturnType result = null; + boolean isAtomic = isAtomicPut; + logger.debug(EELFLoggerDelegate.debugLogger, "removeSession: start with session id: " + sessionId); + PreparedQueryObject queryObject = new PreparedQueryObject(); + StringBuilder querySB = new StringBuilder(); + querySB.append(DELETE).append(FROM).append(musicKeySpace).append(".").append(musicMetaTable) + .append(WHERE).append(MusicProperties.PRIMARY_ID).append("= ? "); + queryObject.appendQueryString(querySB.toString()); + queryObject.addValue(sessionId); + if (isAtomic) + result = MusicCore.atomicPut(musicKeySpace, musicMetaTable, sessionId, queryObject, null); + else + result = modEventualPut(queryObject); + logger.debug(EELFLoggerDelegate.debugLogger, REMOVE_SESSION + musicMetaTable + WITH_SESSION_ID + + sessionId + RESULT + result.getMessage()); + + queryObject = new PreparedQueryObject(); + querySB = new StringBuilder(); + querySB.append(DELETE).append(FROM).append(musicKeySpace).append(".").append(musicAttrTable) + .append(WHERE).append(MusicProperties.PRIMARY_ID).append("= ? "); + queryObject.appendQueryString(querySB.toString()); + queryObject.addValue(sessionId); + if (isAtomic) + result = MusicCore.atomicPut(musicKeySpace, musicAttrTable, sessionId, queryObject, null); + else + result = modEventualPut(queryObject); + + logger.debug(EELFLoggerDelegate.debugLogger, REMOVE_SESSION + musicAttrTable + WITH_SESSION_ID + + sessionId + RESULT + result.getMessage()); + + return result; + } + + /** + * Get proper table name (Meta or Attribute) base on isMeta. + * + * @param isMeta + * @return String + */ + private static String getTableName(boolean isMeta) { + StringBuilder querySB = new StringBuilder(); + if (isMeta) + querySB.append(musicMetaTable); + else + querySB.append(musicAttrTable); + return querySB.toString(); + } + + /** + * Get proper column name (Meta or Attribute) base on isMeta. + * + * @param attributeName + * @param isMeta + * @return String + */ + private static String getColumn(String attributeName, boolean isMeta) { + StringBuilder querySB = new StringBuilder(); + if (isMeta) + querySB.append(attributeName); + else + querySB.append("attribute_bytes"); + return querySB.toString(); + } + + /** + * Get proper column name (Meta or Attribute) base on isMeta for removing. + * + * @param attributeName + * @param isMeta + * @return String + */ + private static String getDelColumn(boolean isMeta, String attributeName) { + StringBuilder querySB = new StringBuilder(); + if (isMeta) + querySB.append(attributeName); + return querySB.toString(); + } + + /** + * To set session attributes in Music + * + * @param attributeName + * @param value + * @param session + * @param sessionId + * @param isMeta + * @return RestResponse + * @throws JsonProcessingException + */ + + public static RestResponse setAttributeAPI(String attributeName, Object value, Session session, + String sessionId, String className, boolean isMeta) throws JsonProcessingException { + logger.debug(EELFLoggerDelegate.debugLogger, "setAttribute: " + attributeName); + RestResponse portalRestResponse = null; + HttpEntity> entity = new HttpEntity<>( + getMusicRestBody(attributeName, value, sessionId, session, className, isMeta), getMusicHeader()); + String url = getInsertUrl(isMeta); + ResponseEntity response = null; + try { + response = template.exchange(url, HttpMethod.POST, entity, String.class); + portalRestResponse = new RestResponse<>(RestStatusEnum.OK, SUCCESS, response.getBody()); + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, e.getLocalizedMessage()); + portalRestResponse = new RestResponse<>(RestStatusEnum.ERROR, e.getMessage(), null); + } + return portalRestResponse; + } + + /** + * To get session attribute in Music + * + * @param attributeName + * @param value + * @param sessionId + * @param isMeta + * @return RestResponse + */ + + public static RestResponse getAttributeAPI(String attributeName, Object value, String sessionId, + boolean isMeta) { + logger.debug(EELFLoggerDelegate.debugLogger, "setAttribute: " + attributeName); + RestResponse portalRestResponse = null; + HttpEntity entity = new HttpEntity<>(null, getMusicHeader()); + ResponseEntity response = null; + String url = getSelectSessionIdUrl(attributeName, sessionId, isMeta); + try { + response = template.exchange(url, HttpMethod.GET, entity, String.class); + portalRestResponse = new RestResponse<>(RestStatusEnum.OK, SUCCESS, response.getBody()); + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, e.getLocalizedMessage()); + portalRestResponse = new RestResponse<>(RestStatusEnum.ERROR, e.getMessage(), null); + } + return portalRestResponse; + } + + /** + * To remove session attribute or session meta in Music + * + * @param attributeName + * @param sessionId + * @param isMeta + * @return RestResponse + */ + public static RestResponse removeAttributeAPI(String attributeName, String sessionId, boolean isMeta) { + RestResponse portalRestResponse = null; + HttpEntity> entity = new HttpEntity<>(getMusicDelRestBody(null), getMusicHeader()); + ResponseEntity response = null; + String url = getSelectSessionIdUrl(attributeName, sessionId, true); + try { + url = getSelectSessionIdUrl(attributeName, sessionId, false); + response = template.exchange(url, HttpMethod.DELETE, entity, String.class); + portalRestResponse = new RestResponse<>(RestStatusEnum.OK, SUCCESS, response.getBody()); + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, e.getLocalizedMessage()); + portalRestResponse = new RestResponse<>(RestStatusEnum.ERROR, e.getMessage(), null); + } + return portalRestResponse; + } + + /** + * Generate body for Music api calls + * + * @return String that includes required body information for Music api + * calls + * @throws JsonProcessingException + */ + public static Map getMusicRestBody(String attributeName, Object value, String sessionId, + Session session, String className, boolean isMeta) throws JsonProcessingException { + Map map = new HashMap<>(); + /* Set up column values */ + Map valueMap = new HashMap<>(); + if (isMeta) { + valueMap.put(MusicProperties.PRIMARY_ID, session.getId()); + valueMap.put(MusicProperties.SESSION_ID, session.getId()); + valueMap.put(MusicProperties.CREATION_TIME, session.getCreationTime().toString()); + valueMap.put(MusicProperties.LAST_ACCESS_TIME, session.getLastAccessedTime().toString()); + valueMap.put(MusicProperties.MAX_INACTIVE_INTERVAL, session.getMaxInactiveInterval().toString()); + } else { + ObjectMapper mapper = new ObjectMapper(); + valueMap.put(MusicProperties.PRIMARY_ID, sessionId); + valueMap.put(MusicProperties.ATTRIBUTE_NAME, attributeName); + valueMap.put(MusicProperties.ATTRIBUTE_BYTES, mapper.writeValueAsString(value)); + valueMap.put(MusicProperties.ATTRIBUTE_CLASS, className); + } + map.put("values", valueMap); + /* Set up consistency setting */ + Map consistencyInfoMap = new HashMap<>(); + consistencyInfoMap.put(MusicProperties.getProperty(MusicProperties.MUSIC_CONSISTENCYINFO), + MusicProperties.getProperty(MusicProperties.MUSIC_CONSISTENCYINFO_VALUE)); + map.put("consistencyInfo", consistencyInfoMap); + return map; + } + + /** + * Generate body for Music delete api calls + * + * @return String that includes required body information for Music api + * calls + * @throws JsonProcessingException + */ + public static Map getMusicDelRestBody(String attributeName) { + Map map = new HashMap<>(); + Map consistencyInfoMap = new HashMap<>(); + consistencyInfoMap.put(MusicProperties.getProperty(MusicProperties.MUSIC_CONSISTENCYINFO), + MusicProperties.getProperty(MusicProperties.MUSIC_CONSISTENCYINFO_VALUE)); + if (attributeName != null && !attributeName.isEmpty()) { + Map conditionsMap = new HashMap<>(); + conditionsMap.put("attribute_name", attributeName); + map.put("conditions", conditionsMap); + } + map.put("consistencyInfo", consistencyInfoMap); + return map; + } + + private static String getSelectSessionIdUrl(String attributeName, String sessionId, boolean isMeta) { + String path = constructPath(isMeta); + StringBuilder attriPath = new StringBuilder(); + attriPath.append(path).append(MusicProperties.getProperty(MusicProperties.MUSIC_ROWS)).append("?") + .append(MusicProperties.PRIMARY_ID).append("=").append(sessionId); + return attriPath.toString(); + } + + private static String getInsertUrl(boolean isMeta) { + String path = constructPath(isMeta); + StringBuilder attriPath = new StringBuilder(); + attriPath.append(path); + attriPath.append(MusicProperties.getProperty(MusicProperties.MUSIC_ROWS)); + return attriPath.toString(); + } + + /** + * Generate header for Music api calls + * + * @return header that contains required header information for Music api + * calls + */ + private static HttpHeaders getMusicHeader() { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.add("X-minorVersion", MusicProperties.getProperty(MusicProperties.MUSIC_X_MINOR_VERSION)); + headers.add("X-patchVersion", MusicProperties.getProperty(MusicProperties.MUSIC_X_PATCH_VERSION)); + headers.add("ns", MusicProperties.getProperty(MusicProperties.MUSIC_NS)); + headers.add("userId", MusicProperties.getProperty(MusicProperties.MUSIC_USER_ID)); + headers.add("password", MusicProperties.getProperty(MusicProperties.MUSIC_PASSWORD)); + return headers; + } + + /** + * Construct URL for Music api calls + * + * @return path + */ + private static String constructPath(boolean isMeta) { + StringBuilder path = new StringBuilder(); + path.append(MusicProperties.getProperty(MusicProperties.MUSIC_ENDPOINT)) + .append(MusicProperties.getProperty(MusicProperties.MUSIC_VERSION)).append("/") + .append(MusicProperties.getProperty(MusicProperties.MUSIC_KEYSPACE)).append("/").append(musicKeySpace) + .append("/").append(MusicProperties.getProperty(MusicProperties.MUSIC_TABLES)).append("/"); + if (isMeta) + path.append(musicMetaTable); + else + path.append(musicAttrTable); + path.append("/"); + return path.toString(); + } + + /** + * Get a list of sessions that need to be cleaned up + * + * @return List + */ + private static List getSessionToBeDeleted(){ + logger.debug(EELFLoggerDelegate.debugLogger, "initial getSessionToBeDeleted ..."); + + PreparedQueryObject queryObject = new PreparedQueryObject(); + ResultSet result = null; + List sessionIDList = new ArrayList<>(); + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + StringBuilder querySB = new StringBuilder(); + String cleanUpThreshold = MusicProperties.getProperty(MusicProperties.MUSIC_CLEAN_UP_THRESHOLD); //Clean up sessions that's cleanUpThreshold hours ago + Date dateForCleanup = new Date(System.currentTimeMillis() - 3600 * 1000 * Integer.valueOf(cleanUpThreshold)); // Get the threshold date that needs to be clean up + String dateForCleanupCondition = dateFormat.format(dateForCleanup); + querySB.append("SELECT ").append(MusicProperties.PRIMARY_ID).append(FROM).append(musicKeySpace) + .append(".").append(getTableName(true)).append(WHERE).append(MusicProperties.LAST_ACCESS_TIME) + .append("< ? ").append(" ALLOW FILTERING"); + queryObject.appendQueryString(querySB.toString()); + queryObject.addValue(dateForCleanupCondition); + + try{ + if (isAtomicGet) + result = MusicCore.atomicGet(musicKeySpace, musicMetaTable, null, queryObject); + else + result = modEventualGet(queryObject); + Row row = result.one(); + while(row!=null){ + sessionIDList.add(row.get(MusicProperties.PRIMARY_ID, String.class)); + row = result.one(); + } + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Error while cleaning up music tables" , e); + } + return sessionIDList; + } + + /** + * Remove session data in music base on the defined frequency + * + * @return List + */ + public static void cleanUpMusic() { + boolean timeToCleanUp = MusicUtil.cleanUp(); // Decide whether to clean up or not + + if(timeToCleanUp){ + /**Getting a list of sessions that need to be cleaned up*/ + List sessionIDList = getSessionToBeDeleted(); + if(sessionIDList!=null || !sessionIDList.isEmpty()){ + StringBuilder sessionIDListCondition = new StringBuilder(); + sessionIDListCondition.append("('"); + for(String s : sessionIDList){ + sessionIDListCondition.append(s); + sessionIDListCondition.append("','"); + } + sessionIDListCondition.deleteCharAt(sessionIDListCondition.length()-1); + sessionIDListCondition.deleteCharAt(sessionIDListCondition.length()-1); + sessionIDListCondition.append(")"); + StringBuilder querySB = new StringBuilder(); + PreparedQueryObject queryObject = new PreparedQueryObject(); + /**Deleting attributes table**/ + querySB = new StringBuilder(); + queryObject = new PreparedQueryObject(); + querySB.append("DELETE FROM ").append(musicKeySpace) + .append(".").append(getTableName(false)).append(WHERE).append(MusicProperties.PRIMARY_ID) + .append(" in ").append(sessionIDListCondition); + queryObject.appendQueryString(querySB.toString()); + try{ + if (isAtomicPut) + MusicCore.atomicPut(musicKeySpace, null, null, queryObject, null); + else + modEventualPut(queryObject); + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Error while cleaning up music attributes tables" , e); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Music sessions have been cleaned up !"); + + /**Deleting meta table**/ + logger.debug(EELFLoggerDelegate.debugLogger, "Cleaning up meta table ..."); + querySB = new StringBuilder(); + queryObject = new PreparedQueryObject(); + querySB.append("DELETE FROM ").append(musicKeySpace) + .append(".").append(getTableName(true)).append(WHERE).append(MusicProperties.PRIMARY_ID) + .append(" in ").append(sessionIDListCondition); + queryObject.appendQueryString(querySB.toString()); + try{ + if (isAtomicPut) + MusicCore.atomicPut(musicKeySpace, null, null, queryObject, null); + else + modEventualPut(queryObject); + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Error while cleaning up music meta tables" , e); + } + + logger.debug(EELFLoggerDelegate.debugLogger, "Cleaned up attributes table ... "); + }else{ + logger.debug(EELFLoggerDelegate.debugLogger, "No Session needs to be cleaned up"); + } + + } + } + + public static ReturnType modEventualPut(PreparedQueryObject queryObject) { + boolean result = false; + try { + result = MusicCore.getDSHandle().executePut(queryObject,CRITICAL); + } catch (MusicServiceException | MusicQueryException ex) { + logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + " " + ex.getCause() + " " + ex); + return new ReturnType(ResultType.FAILURE, ex.getMessage()); + } + if (result) { + return new ReturnType(ResultType.SUCCESS, "Success"); + } else { + return new ReturnType(ResultType.FAILURE, "Failure"); + } + } + + public static ResultSet modEventualGet(PreparedQueryObject queryObject) throws MusicServiceException { + ResultSet result; + result = MusicCore.quorumGet(queryObject); + return result; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicProperties.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicProperties.java deleted file mode 100644 index e867deb1..00000000 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicProperties.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * ============LICENSE_START========================================== - * ONAP Portal - * =================================================================== - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * =================================================================== - * - * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the "License"); - * you may not use this software except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); - * you may not use this documentation except in compliance with the License. - * You may obtain a copy of the License at - * - * https://creativecommons.org/licenses/by/4.0/ - * - * Unless required by applicable law or agreed to in writing, documentation - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================ - * - * - */ - -package org.onap.portalapp.music.util; - - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.portalapp.music.service.MusicService; - - -public class MusicProperties { - - public static final String MUSIC_ENDPOINT = "music.endpoint"; - - public static final String MUSIC_VERSION = "music.version"; - - public static final String MUSIC_KEYSPACE = "music.keyspace"; - - public static final String MUSIC_SESSION_KEYSPACE = "music.session.keyspace"; - - public static final String MUSIC_TABLES = "TABLES"; - - public static final String MUSIC_SESSION_ATTR_TABLES = "music.session.attr.tables"; - - public static final String MUSIC_SESSION_META_TABLES = "music.session.meta.tables"; - - public static final String MUSIC_ROWS = "ROW"; - - public static final String MUSIC_SESSION_ROW = "music.sesion.rows"; - - public static final String MUSIC_X_MINOR_VERSION = "music.x.minor.version"; - - public static final String MUSIC_X_PATCH_VERSION = "music.x.patch.version"; - - public static final String MUSIC_AID = "AID"; - - public static final String MUSIC_NS = "music.ns"; - - public static final String MUSIC_USER_ID = "music.user.id"; - - public static final String MUSIC_PASSWORD = "music.password"; - - public static final String MUSIC_CONSISTENCYINFO = "music.consistency.info"; - - public static final String MUSIC_CONSISTENCYINFO_VALUE = "music.consistency.info.value"; - - public static final String MUSIC_CACHE = "music.cache"; - - public static final String MUSIC_SERIALIZE_COMPRESS = "music.serialize.compress"; - - public static final String MUSIC_ATOMIC_GET = "music.atomic.get"; - - public static final String MUSIC_ATOMIC_PUT = "music.atomic.put"; - - public static final String MUSIC_ATOMIC_POST = "music.atomic.post"; - - public static final String MUSIC_EXCLUDE_API = "music.exclude.api"; - - public static final String MUSIC_CLEAN_UP_FREQUENCY = "music.cleanup.frequency"; - - public static final String MUSIC_CLEAN_UP_THRESHOLD = "music.cleanup.threshold"; - - public static final String MUSIC_ENABLE = "music.enable"; - - public static final String SESSION_MAX_INACTIVE_INTERVAL_SECONDS = "music.session.max.inactive.interval.seconds"; - - public static final String ATTRIBUTE_NAME = "ATTRIBUTE_NAME"; - - public static final String ATTRIBUTE_BYTES = "ATTRIBUTE_BYTES"; - - public static final String ATTRIBUTE_CLASS = "ATTRIBUTE_CLASS"; - - public static final String PRIMARY_ID = "PRIMARY_ID"; - - public static final String SESSION_ID = "SESSION_ID"; - - public static final String CREATION_TIME = "CREATION_TIME"; - - public static final String LAST_ACCESS_TIME = "LAST_ACCESS_TIME"; - - public static final String MAX_INACTIVE_INTERVAL = "MAX_INACTIVE_INTERVAL"; - - public static final String EXPIRY_TIME = "EXPIRY_TIME"; - - public static final String PRINCIPAL_NAME = "PRINCIPAL_NAME"; - - private MusicProperties(){} - - private static Properties properties; - - private static String propertyFileName = "music.properties"; - - private static final Object lockObject = new Object(); - - private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicProperties.class); - - /** - * Gets the property value for the specified key. If a value is found, leading - * and trailing space is trimmed. - * - * @param property - * Property key - * @return Value for the named property; null if the property file was not - * loaded or the key was not found. - */ - public static String getProperty(String property) { - if (properties == null) { - synchronized (lockObject) { - try { - if (!initialize()) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + propertyFileName); - return null; - } - } catch (IOException e) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + propertyFileName ,e); - return null; - } - } - } - String value = properties.getProperty(property); - if (value != null) - value = value.trim(); - return value; - } - - /** - * Reads properties from a portal.properties file on the classpath. - * - * Clients do NOT need to call this method. Clients MAY call this method to test - * whether the properties file can be loaded successfully. - * - * @return True if properties were successfully loaded, else false. - * @throws IOException - * On failure - */ - private static boolean initialize() throws IOException { - if (properties != null) - return true; - InputStream in = MusicProperties.class.getClassLoader().getResourceAsStream(propertyFileName); - if (in == null) - return false; - properties = new Properties(); - try { - properties.load(in); - } finally { - in.close(); - } - return true; - } - - /** - * Tests whether a property value is available for the specified key. - * - * @param key - * Property key - * @return True if the key is known, otherwise false. - */ -/* public static boolean containsProperty(String key) { - return environment.containsProperty(key); - }*/ - - /** - * Returns the property value associated with the given key (never - * {@code null}), after trimming any trailing space. - * - * @param key - * Property key - * @return Property value; the empty string if the environment was not - * autowired, which should never happen. - * @throws IllegalStateException - * if the key is not found - */ -/* public static String getProperty(String key) { - String value = ""; - if (environment == null) { - // logger.error(EELFLoggerDelegate.errorLogger, "getProperty: environment is null, should never happen!"); - } else { - value = environment.getRequiredProperty(key); - // java.util.Properties preserves trailing space - if (value != null) - value = value.trim(); - } - return value; - }*/ - -} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicUtil.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicUtil.java deleted file mode 100644 index 9667bfef..00000000 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicUtil.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * ============LICENSE_START========================================== - * ONAP Portal - * =================================================================== - * Copyright © 2018 AT&T Intellectual Property. All rights reserved. - * =================================================================== - * - * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the "License"); - * you may not use this software except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); - * you may not use this documentation except in compliance with the License. - * You may obtain a copy of the License at - * - * https://creativecommons.org/licenses/by/4.0/ - * - * Unless required by applicable law or agreed to in writing, documentation - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================ - * - * - */ -package org.onap.portalapp.music.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.nio.ByteBuffer; -import java.time.Duration; -import java.time.Instant; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.portalapp.music.conf.MusicSession; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; - -public class MusicUtil { - private static final Set sessionAttrNameSet = new HashSet<>(Arrays.asList("CREATION_TIME", "LAST_ACCESS_TIME","MAX_INACTIVE_INTERVAL","EXPIRY_TIME","PRINCIPAL_NAME")); - - private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); - private static String atomicPut = MusicProperties.getProperty(MusicProperties.MUSIC_ATOMIC_PUT); - private static String atomicGet = MusicProperties.getProperty(MusicProperties.MUSIC_ATOMIC_GET); - private static String cached = MusicProperties.getProperty(MusicProperties.MUSIC_CACHE); - private static String cleanUpFreq = MusicProperties.getProperty(MusicProperties.MUSIC_CLEAN_UP_FREQUENCY); - private static String musicSerializeCompress = MusicProperties.getProperty(MusicProperties.MUSIC_SERIALIZE_COMPRESS); - private static String musicEnable = MusicProperties.getProperty(MusicProperties.MUSIC_ENABLE); - private static final int MILLIS_IN_HOUR = 3600000; - - public static boolean isSessionMetaAttr(String key){ - return sessionAttrNameSet.contains(key); - } - - public static T musicRestResponseDataParsing(ResultSet rs, String attributeName) throws Exception{ - logger.debug(EELFLoggerDelegate.debugLogger, "musicRestResponseDataParsing: start"); - Row row = rs.one(); - if(!sessionAttrNameSet.contains(attributeName)){ - if(row!=null) - return MusicUtil.musicDeserialize(row.getBytes("attribute_bytes")); - }else{ - return (T) row.getString(attributeName); - } - return null; - } - - public static T musicDeserialize (ByteBuffer byteBuf) throws Exception{ - logger.debug(EELFLoggerDelegate.debugLogger, "musicDeserialize: start"); - ByteArrayInputStream byteArr = new ByteArrayInputStream(byteBuf.array()); - ObjectInputStream ois = null; - if(isMusicSerializeCompress()){ - GZIPInputStream zos = new GZIPInputStream(byteArr); - ois = new ObjectInputStream(zos); - }else{ - ois = new ObjectInputStream(byteArr); - } - return (T) ois.readObject(); - } - - public static ByteBuffer musicSerialize (Object value) throws Exception{ - logger.debug(EELFLoggerDelegate.debugLogger, "musicSerialize: start"); - ByteArrayOutputStream bo = new ByteArrayOutputStream(); - try { - if(isMusicSerializeCompress()){ - GZIPOutputStream zos = new GZIPOutputStream(bo); - ObjectOutputStream oos = new ObjectOutputStream(zos); - oos.writeObject(value); - oos.flush(); - zos.finish(); - }else{ - ObjectOutputStream oos = new ObjectOutputStream(bo); - oos.writeObject(value); - oos.flush(); - } - } catch (IOException e) { - String message="Failed to serialize "; - logger.error(EELFLoggerDelegate.errorLogger, message, e); - } - return ByteBuffer.wrap(bo.toByteArray()); - } - - public static MusicSession parseMetaData (Row row) throws Exception{ - logger.debug(EELFLoggerDelegate.debugLogger, "parseMetaData: start"); - - if(row==null) - return null; - String sessionId = row.getString("primary_id"); - MusicSession musicSession = new MusicSession(sessionId); - musicSession.setCreationTime(Instant.parse(row.getString("creation_time"))); - musicSession.setLastAccessedTime(Instant.parse(row.getString("last_access_time"))); - musicSession.setMaxInactiveInterval(Duration.parse(row.getString("max_inactive_interval"))); - return musicSession; - } - - public static Set getMusicExcludedAPI(){ - Set excludedApiSet = new HashSet<>(); - String musicExcludedApi = MusicProperties.getProperty(MusicProperties.MUSIC_EXCLUDE_API); - String[] musicExcludedApiArray = musicExcludedApi.split(","); - if(musicExcludedApiArray.length>0){ - for(String str : musicExcludedApiArray){ - excludedApiSet.add(str.trim()); - } - } - return excludedApiSet; - } - - public static boolean isExcludedApi(String api){ - Set excludedApiSet = getMusicExcludedAPI(); - for(String str: excludedApiSet){ - if(api.matches(str)) - return true; - } - return false; - } - - - public static boolean isMusicSerializeCompress(){ - if(musicSerializeCompress==null){ - logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_SERIALIZE_COMPRESS +" fall back to eventual put"); - return false; - } - return musicSerializeCompress.trim().equalsIgnoreCase("true"); - } - - public static boolean isAtomicPut(){ - if(atomicPut==null){ - logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_ATOMIC_PUT +" fall back to eventual put"); - return false; - } - return atomicPut.trim().equalsIgnoreCase("true"); - } - - public static boolean isAtomicGet(){ - if(atomicGet==null){ - logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_ATOMIC_GET +" fall back to eventual get"); - return false; - } - return atomicGet.trim().equalsIgnoreCase("true"); - } - - public static boolean isCached(){ - if(cached==null){ - logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_CACHE +" fall back to non cache"); - return false; - } - return cached.trim().equalsIgnoreCase("true"); - } - - public static int convertHoursToMillSec(int hour){ - return hour* MILLIS_IN_HOUR; - } - - public static boolean cleanUp(){ - Date lastCleanUpDate = MusicCleanUp.getInstance().getLastCleanUpTime(); - if(lastCleanUpDate==null) - return false; - else{ - int cleanUpDurationMili = convertHoursToMillSec(Integer.valueOf(cleanUpFreq)); - Date currentTime = new Date(); - long diffInMillies = Math.abs(currentTime.getTime() - lastCleanUpDate.getTime()); - if(diffInMillies > cleanUpDurationMili){ - MusicCleanUp.getInstance().updateLastCleanUpTimeToCurrent(); - return true; - } - else - return false; - } - } - - public static boolean isMusicEnable(){ - if(musicEnable==null) - return false; - if(musicEnable.equals("true")) - return true; - else - return false; - } -} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulController.java index 7615b660..5aea7f1c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulController.java @@ -50,8 +50,11 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.onap.portalapp.controller.EPRestrictedRESTfulBaseController; +import org.onap.portalapp.music.conf.MusicSession; +import org.onap.portalapp.music.util.MusicUtil; import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPRole; +import org.onap.portalapp.portal.domain.EPServiceCookie; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.logging.aop.EPAuditLog; import org.onap.portalapp.portal.service.AdminRolesService; @@ -70,6 +73,8 @@ import org.onap.portalapp.validation.DataValidator; import org.onap.portalapp.validation.SecureString; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; +import org.onap.portalsdk.core.util.SystemProperties; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; @@ -240,4 +245,30 @@ public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseContro logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e); response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage()); } + + @EPAuditLog + @RequestMapping(value = { "/validateCookie" }, method = RequestMethod.POST) + public boolean validateCookie(@RequestBody EPServiceCookie epServiceCookie, HttpServletRequest request) throws Exception { + Map epServiceCookieValueMap = epServiceCookie.getValue(); + if(epServiceCookieValueMap!=null) { + String multifactorauthfrontendurl = SystemProperties.getProperty("frontend_url"); + String encryptedJSessionId = epServiceCookieValueMap.get(multifactorauthfrontendurl); + if(encryptedJSessionId != null) { + String jSessionId = CipherUtil.decryptPKC(encryptedJSessionId); + if(jSessionId != null) { + if(jSessionId.equals(request.getSession().getId())) { + if(MusicUtil.isMusicEnable()) { + MusicSession musicSession = new MusicSession(); + String sessionId = musicSession.getAttribute(encryptedJSessionId); + logger.info(EELFLoggerDelegate.errorLogger, "Music sessionid : "+sessionId); + return (sessionId != null); + } else { + return true; + } + } + } + } + } + return false; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/FunctionalMenuController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/FunctionalMenuController.java index 97af4373..5e13127c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/FunctionalMenuController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/FunctionalMenuController.java @@ -49,6 +49,7 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.Response; import org.json.JSONObject; import org.onap.portalapp.controller.EPRestrictedBaseController; @@ -74,6 +75,7 @@ import org.onap.portalapp.util.EPUserUtils; import org.onap.portalapp.validation.DataValidator; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.web.support.UserUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @@ -641,10 +643,18 @@ public class FunctionalMenuController extends EPRestrictedBaseController { */ @RequestMapping(value = { "/portalApi/userApplicationRoles" }, method = RequestMethod.GET, produces = "application/json") - public List getAppList(HttpServletRequest request, + public List getAppList(HttpServletRequest request, HttpServletResponse response, @RequestParam("userId") String userId) throws IOException { List AppRoles = null; + + if(!UserUtils.getUserSession(request).getOrgUserId().equalsIgnoreCase(userId)) { + logger.error(EELFLoggerDelegate.errorLogger, "Not authorized to view roles of others "); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + response.getWriter().flush(); + return null; + } + try { List userAppRoleList = functionalMenuService.getUserAppRolesList(userId); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java index 6818d505..ca66809f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java @@ -192,16 +192,17 @@ public class HealthCheckController extends EPUnRestrictedBaseController { } statusCollection.add(CassandraStatusInfo); - HealthStatusInfo zookeeperStatusInfo = new HealthStatusInfo("Music-zookeeper"); - //zookeeperStatusInfo.hostName = EcompPortalUtils.getMyHostName(); - zookeeperStatusInfo.ipAddress = MusicUtil.getMyZkHost(); - if (!HealthMonitor.isZookeeperStatusOk()) { - overallStatus = false; - zookeeperStatusInfo.healthCheckStatus = statusDown; - zookeeperStatusInfo.description = "Check the logs for more details"; - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.MusicHealthCheckZookeeperError); - } - statusCollection.add(zookeeperStatusInfo); + /* + * HealthStatusInfo zookeeperStatusInfo = new + * HealthStatusInfo("Music-zookeeper"); --zookeeperStatusInfo.hostName = + * EcompPortalUtils.getMyHostName(); zookeeperStatusInfo.ipAddress = + * MusicUtil.getMyZkHost(); if (!HealthMonitor.isZookeeperStatusOk()) { + * overallStatus = false; zookeeperStatusInfo.healthCheckStatus = statusDown; + * zookeeperStatusInfo.description = "Check the logs for more details"; + * EPLogUtil.logEcompError(logger, + * EPAppMessagesEnum.MusicHealthCheckZookeeperError); } + * statusCollection.add(zookeeperStatusInfo); + */ } String json = ""; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java index 41273ecf..92449a3a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java @@ -89,12 +89,12 @@ import org.springframework.web.client.AsyncRestTemplate; @EPAuditLog @NoArgsConstructor public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController { + public static final String FEED_ML = "feed.ml"; private WidgetMService widgetMService; private AppsCacheService appCacheService; private static final String MACHINE_LEARNING_SERVICE_CTX = "/ml_api"; private static final String REGISTER_ACTION = MACHINE_LEARNING_SERVICE_CTX + "/" + "registerAction"; - private static final String CONSUL_ML_SERVICE_ID = "machine-learning"; private static final String APP_KEY = "uebkey"; private static final String ERROR_MSG = " Error retrieving Application to capture app name for analytics; Proceeding with empty app name"; private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class); @@ -102,7 +102,6 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl private final SuccessCallback> successCallback = arg -> logger.info(EELFLoggerDelegate.debugLogger, arg.getBody()); private final FailureCallback failureCallback = arg -> logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg); - @Autowired public WebAnalyticsExtAppController(AppsCacheService appCacheService, WidgetMService consulHealthService) { this.appCacheService = appCacheService; @@ -170,19 +169,23 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl try { MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); String appName = ""; - try { - appName = getAppName(request, appName); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, + try { + appName = getAppName(request, appName); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, ERROR_MSG, e); - } + } - try { - storeAuxAnalytics(analyticsMap, appName); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, + try { + if(SystemProperties.containsProperty(FEED_ML) && + SystemProperties.getProperty(FEED_ML).equals("true")) { + storeAuxAnalytics(analyticsMap, appName); + } + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, ERROR_MSG, e); - } + } MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); @@ -218,7 +221,7 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl private EPApp getApp(HttpServletRequest request) { String appKeyValue = request.getHeader(APP_KEY); EPApp appRecord = null; - if (appKeyValue == null || "".equals(appKeyValue)) { + if (appKeyValue == null || appKeyValue.equals("")) { logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name"); } else { appRecord = appCacheService.getAppFromUeb(appKeyValue); @@ -226,15 +229,16 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl return appRecord; } - private void storeAuxAnalytics(Analytics analyticsMap, String appName) { + protected void storeAuxAnalytics(Analytics analyticsMap, String appName) { logger.info(EELFLoggerDelegate.debugLogger, " Registering an action for recommendation: AppName/Function/UserId " + appName + "/" + analyticsMap.getFunction() + "/" + analyticsMap.getUserid()); + Map requestMapping = new HashMap<>(); requestMapping.put("id", analyticsMap.getUserid()); requestMapping.put("action", appName + "|" + analyticsMap.getFunction()); - + HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); @@ -243,12 +247,11 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl // send it! ListenableFuture> out = restTemplate.exchange( - EcompPortalUtils.widgetMsProtocol() + "://" - + widgetMService.getServiceLocation(CONSUL_ML_SERVICE_ID, - SystemProperties.getProperty("microservices.m-learn.local.port")) + EcompPortalUtils.widgetMLProtocol() + "://" + + widgetMService.getMLServiceLocation() + REGISTER_ACTION, HttpMethod.POST, entity, String.class); out.addCallback(successCallback, failureCallback); } -} +} \ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPServiceCookie.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPServiceCookie.java new file mode 100644 index 00000000..b4eb6fcc --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPServiceCookie.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portalapp.portal.domain; + +import java.util.Map; + + +public class EPServiceCookie { + Map value; + + public Map getValue() { + return value; + } + + public void setValue(Map value) { + this.value = value; + } + +} \ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/NoHealthyServiceException.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/NoHealthyServiceException.java index 2f78f807..3a4dc174 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/NoHealthyServiceException.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/NoHealthyServiceException.java @@ -37,9 +37,9 @@ */ package org.onap.portalapp.portal.exceptions; -import com.ecwid.consul.ConsulException; -public class NoHealthyServiceException extends ConsulException{ + +public class NoHealthyServiceException extends Exception{ private static final long serialVersionUID = -7089437673127729813L; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java index 39c906a1..3209f35a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java @@ -42,6 +42,7 @@ package org.onap.portalapp.portal.interceptor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.HashMap; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java index 4805a77d..31a323e4 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java @@ -143,18 +143,18 @@ public class HealthMonitor { } if(org.onap.portalapp.music.util.MusicUtil.isMusicEnable()){ - zookeeperStatusOk = checkZookeeperStatus(); - - if (!zookeeperStatusOk) { - if ((numIntervalsZookeeperNotHealthy % numIntervalsBetweenAlerts) == 0) { - logger.debug(EELFLoggerDelegate.debugLogger, - "monitorEPHealth: cluster nodes down, logging to error log to trigger alert."); - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.MusicHealthCheckZookeeperError); - numIntervalsZookeeperNotHealthy++; - } else { - numIntervalsZookeeperNotHealthy = 0; - } - } + /* + * zookeeperStatusOk = checkZookeeperStatus(); + * + * if (!zookeeperStatusOk) { if ((numIntervalsZookeeperNotHealthy % + * numIntervalsBetweenAlerts) == 0) { + * logger.debug(EELFLoggerDelegate.debugLogger, + * "monitorEPHealth: cluster nodes down, logging to error log to trigger alert." + * ); EPLogUtil.logEcompError(logger, + * EPAppMessagesEnum.MusicHealthCheckZookeeperError); + * numIntervalsZookeeperNotHealthy++; } else { numIntervalsZookeeperNotHealthy = + * 0; } } + */ cassandraStatusOk = checkCassandraStatus(); if (!cassandraStatusOk) { @@ -257,6 +257,7 @@ public class HealthMonitor { String state = zkNodeStatistics.substring(zkNodeStatistics.indexOf("Mode:"), zkNodeStatistics.indexOf("Node")); logger.info(EELFLoggerDelegate.applicationLogger, + "Getting Status for zookeeper :" + zookeeperNode.trim() + ":------:" + state); if (state.contains("leader") || state.contains("follower")) { return true; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java index 14dfebee..93310a97 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java @@ -37,32 +37,34 @@ */ package org.onap.portalapp.portal.scheduler; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializer; import java.util.Collections; import java.util.Date; + import javax.security.auth.login.CredentialException; -import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.Response; -import lombok.NoArgsConstructor; + import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; +import org.apache.cxf.jaxrs.client.WebClient; +import org.apache.cxf.jaxrs.impl.ResponseImpl; import org.eclipse.jetty.util.security.Password; import org.json.simple.JSONObject; import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum; import org.onap.portalapp.portal.logging.logic.EPLogUtil; -import org.onap.portalapp.portal.scheduler.client.HttpBasicClient; -import org.onap.portalapp.portal.scheduler.client.HttpsBasicClient; import org.onap.portalapp.portal.scheduler.restobjects.RestObject; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializer; + +import lombok.NoArgsConstructor; + @SuppressWarnings("MalformedFormatString") @Service @NoArgsConstructor @@ -73,10 +75,10 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { + " MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON"; private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class); - private static Client client = null; + private static WebClient client = null; private static Gson gson = null; - private MultivaluedHashMap commonHeaders; + private MultivaluedHashMap commonHeaders; private static void init() { logger.debug(EELFLoggerDelegate.debugLogger, "initializing"); @@ -89,7 +91,7 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { gson = builder.create(); } - public void initRestClient() { + public void initRestClient(String URI) { logger.debug(EELFLoggerDelegate.debugLogger, "Starting to initialize rest client"); init(); @@ -130,19 +132,28 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { commonHeaders = new MultivaluedHashMap<>(); commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc))); - try { - if (!username.isEmpty()) { - - client = HttpBasicClient.getClient(); - } else { - - client = HttpsBasicClient.getClient(); - } - } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest client",e.getMessage()); - - } + // try { + // if (!username.isEmpty()) { + // + // client = HttpBasicClient.getClient(); + // } else { + // + // client = HttpsBasicClient.getClient(); + // } + // } catch (Exception e) { + // logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest client",e.getMessage()); + // + // } + + client = WebClient.create(URI); + client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON); + //client.path(""); + client.headers(commonHeaders); + logger.debug(EELFLoggerDelegate.debugLogger, "Client Initialized"); + + + } @@ -155,10 +166,13 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url); try { - initRestClient(); - - final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get(); + initRestClient(url); + + + //final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get(); + final ResponseImpl cres = (ResponseImpl)client.get(); + logger.debug(EELFLoggerDelegate.debugLogger, "The implemenation class of Response : ", cres.getClass().getName()); int status = cres.getStatus(); restObject.setStatusCode(status); @@ -211,11 +225,10 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { try { - initRestClient(); + initRestClient(url); // Change the content length - final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders) - .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON)); + final ResponseImpl cres = (ResponseImpl)client.post(requestDetails.toJSONString()); if (cres != null && cres.getEntity() != null) { @@ -268,38 +281,5 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { throw new UnsupportedOperationException(); } - @SuppressWarnings("unchecked") - public void Delete(T t, JSONObject requestDetails, String sourceID, String path, RestObject restObject) { - - String methodName = "Delete"; - String url = ""; - Response cres; - - try { - initRestClient(); - - url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; - - cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders) - // .entity(r) - .build("DELETE", Entity.entity(requestDetails, MediaType.APPLICATION_JSON)).invoke(); - - int status = cres.getStatus(); - restObject.setStatusCode(status); - if (cres.getEntity() != null) { - t = (T) cres.readEntity(t.getClass()); - restObject.set(t); - } - - } catch (HttpClientErrorException e) { - logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception For the Delete", - methodName, url, e); - EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value()); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Exception For the Delete", methodName, url, e); - EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value()); - throw e; - } - } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java index 8d37a125..77ebe6a0 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java @@ -45,13 +45,10 @@ import org.springframework.stereotype.Service; @Service public interface SchedulerRestInterfaceIfc { - void initRestClient(); + void initRestClient(String URI); void Get(T t, String sourceId, String path, org.onap.portalapp.portal.scheduler.restobjects.RestObject restObject ) throws Exception; - void Delete(T t, JSONObject requestDetails, String sourceID, String path, RestObject restObject) - throws Exception; - void Post(T t, JSONObject r, String path, RestObject restObject) throws Exception; void logRequest(JSONObject requestDetails); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java index 17dc3f1e..b2fff55f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java @@ -42,10 +42,11 @@ package org.onap.portalapp.portal.scheduler.client; import javax.servlet.ServletContext; +import javax.ws.rs.RuntimeType; import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import org.glassfish.jersey.client.ClientConfig; +import org.apache.cxf.jaxrs.client.spec.ClientBuilderImpl; +import org.apache.cxf.jaxrs.impl.ConfigurationImpl; import org.glassfish.jersey.client.ClientProperties; import org.onap.portalapp.portal.scheduler.util.CustomJacksonJaxBJsonProvider; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -71,10 +72,14 @@ public class HttpBasicClient{ */ public static Client getClient() throws Exception { - ClientConfig config = new ClientConfig(); - config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); + //ClientConfig config = new ClientConfig(); + + ConfigurationImpl config = new ConfigurationImpl(RuntimeType.CLIENT); + config.setProperty(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); + ClientBuilderImpl impl = new ClientBuilderImpl(); - return ClientBuilder.newClient(config) + Class.forName(org.apache.cxf.jaxrs.impl.ResponseImpl.class.getName()); + return impl.withConfig(config).build() .register(CustomJacksonJaxBJsonProvider.class); } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java index 9784356c..4e83b921 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java @@ -2893,7 +2893,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null); } - if (!roleFunction.isEmpty()) { + if (!roleFunction.isEmpty() && roleId != null) { EPAppRoleFunction apRoleFunction = new EPAppRoleFunction(); apRoleFunction.setAppId(app.getId()); apRoleFunction.setRoleId(roleId); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java index bfc232aa..ab688820 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java @@ -1084,7 +1084,7 @@ public class UserRolesCommonServiceImpl { applyChangesToUserAppRolesForMyLoginsRequest(user, appId); - boolean systemUser = newAppRolesForUser.isSystemUser(); + Boolean systemUser = (newAppRolesForUser.getIsSystemUser() != null ? newAppRolesForUser.getIsSystemUser() : false); if ((app.getCentralAuth() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) { @@ -2303,10 +2303,15 @@ public class UserRolesCommonServiceImpl { EPApp app = appsService.getApp(appId); //If local or centralized application if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) { + Map params = new HashMap<>(); + params.put("id", app.getId()); + params.put("active", true); @SuppressWarnings("unchecked") - List userList = (List) dataAccessService.executeNamedQuery("getActiveUsers", null, null); + //List userList = (List) dataAccessService.executeNamedQuery("getActiveUsers", null, null); + //List userList = (List) dataAccessService.executeNamedQuery("getActiveUsersForApp", params, null); + List userList = (List) dataAccessService.executeNamedQuery("getActiveUsersForApp", params, null); for (EPUser user : userList) { - UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app); + UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(user, app.getId()); if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0) userApplicationRoles.add(userWithAppRoles); } @@ -2334,6 +2339,29 @@ public class UserRolesCommonServiceImpl { return userApplicationRoles; } + /** + * + * @param user + * @param app_id + * @return + */ + private UserApplicationRoles convertToUserApplicationRoles(EPUser user, Long appId) { + UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles(); + userWithRemoteAppRoles.setAppId(appId); + userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId()); + userWithRemoteAppRoles.setFirstName(user.getFirstName()); + userWithRemoteAppRoles.setLastName(user.getLastName()); + List roleList = new ArrayList(); + for(EPUserApp userApp :user.getEPUserApps()) { + RemoteRole remoteRole = new RemoteRole(); + remoteRole.setName(userApp.getRole().getName()); + remoteRole.setId(userApp.getRole().getId()); + roleList.add(remoteRole); + } + userWithRemoteAppRoles.setRoles(roleList); + return userWithRemoteAppRoles; + } + /** * * @param appId diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMService.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMService.java index dd03d06d..1c53a0c3 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMService.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMService.java @@ -37,17 +37,12 @@ */ package org.onap.portalapp.portal.service; -import java.util.List; - import org.onap.portalapp.portal.exceptions.NoHealthyServiceException; -import com.ecwid.consul.ConsulException; -import com.orbitz.consul.model.health.ServiceHealth; - public interface WidgetMService { /** - * This method returns the location of one healthy node if found in Consul - - * If not found in / by Consul, it falls back to 'localhost' + * This method returns the location of Widget MS - + * * * @param service * @param fallbackPortOnLocalhost @@ -56,4 +51,13 @@ public interface WidgetMService { */ public String getServiceLocation(String service, String fallbackPortOnLocalhost) throws NoHealthyServiceException; + + /** + * This method returns the location of Machine learning - + * + * + * @return Service location + */ + public String getMLServiceLocation(); + } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMServiceImpl.java index 21f1648d..29180d5e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMServiceImpl.java @@ -39,6 +39,7 @@ package org.onap.portalapp.portal.service; import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.stereotype.Component; @Component @@ -53,5 +54,13 @@ public class WidgetMServiceImpl implements WidgetMService { logger.debug(logger.debugLogger, "returned service location: "+ localFallbackServiceLocation); return localFallbackServiceLocation; } + + @Override + public String getMLServiceLocation() { + logger.debug(logger.debugLogger, "Requested Service: ML"); + String localFallbackServiceLocation = EcompPortalUtils.mlLocalOrDockerHost() + ":" + SystemProperties.getProperty("microservices.ml.port"); + logger.debug(logger.debugLogger, "returned service location: "+ localFallbackServiceLocation); + return localFallbackServiceLocation; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java index cbfe1787..3d7363e2 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java @@ -53,9 +53,8 @@ import lombok.ToString; @ToString public class AppWithRolesForUser { private String orgUserId; - private boolean isSystemUser; + private Boolean isSystemUser; private Long appId; private String appName; private List appRoles; - } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FunctionalMenuItem.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FunctionalMenuItem.java index 14ad2f4c..a2148c2f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FunctionalMenuItem.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FunctionalMenuItem.java @@ -73,7 +73,7 @@ public class FunctionalMenuItem implements Serializable { public Integer column; @Column(name = "TEXT") - @Max(value = 100) + //@Max(value = 100) @SafeHtml @NotNull public String text; @@ -83,13 +83,13 @@ public class FunctionalMenuItem implements Serializable { public Integer parentMenuId; @Column(name = "URL") - @Max(value = 128) + //@Max(value = 128) @SafeHtml @NotNull public String url; @Column(name="ACTIVE_YN") - @Max(value = 1) + //@Max(value = 1) @SafeHtml @NotNull public String active_yn; @@ -134,4 +134,5 @@ public class FunctionalMenuItem implements Serializable { public void setRestrictedApp(Boolean restrictedApp) { this.restrictedApp = restrictedApp; } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EPCommonSystemProperties.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EPCommonSystemProperties.java index e253bfcf..981a2ac6 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EPCommonSystemProperties.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EPCommonSystemProperties.java @@ -90,6 +90,9 @@ public class EPCommonSystemProperties extends SystemProperties { public static final String WIDGET_MS_PROTOCOL = "microservices.widget.protocol"; public static final String WIDGET_MS_HOSTNAME = "microservices.widget.hostname"; + public static final String WIDGET_ML_PROTOCOL = "microservices.ml.protocol"; + public static final String WIDGET_ML_HOSTNAME = "microservices.ml.hostname"; + public static final String WIDGET_ML_PORT = "microservices.ml.port"; public static final String REMOTE_CENTRALIZED_SYSTEM_ACCESS = "remote_centralized_system_access"; public static final String APP_DISPLAY_PASSWORD = "*******"; @@ -102,4 +105,7 @@ public class EPCommonSystemProperties extends SystemProperties { public static final String PASSWORD = "password"; public static final String PORTAL_LEFT_MENU = "portal_left_menu"; + public static final String EPSERVICE_COOKIE_SECURE = "epsservice.cookie.secure"; + public static final String MULTI_FACTOR_AUTH_FRONTEND_URL = "frontend_url"; + } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java index 30eeac04..7c9aa76b 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java @@ -376,6 +376,15 @@ public class EcompPortalUtils { public static String widgetMsProtocol() { return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_PROTOCOL, "https"); } + + /** + * Answers the protocol to use. + * + * @return Protocol name from property file; defaults to https. + */ + public static String widgetMLProtocol() { + return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_ML_PROTOCOL, "https"); + } /** * Answers the host to use. @@ -385,6 +394,15 @@ public class EcompPortalUtils { public static String localOrDockerHost() { return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_HOSTNAME, "localhost"); } + + /** + * Answers the host to use. + * + * @return Host name from property file; defaults to localhost. + */ + public static String mlLocalOrDockerHost() { + return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_ML_HOSTNAME, "localhost"); + } /** * It returns headers where username and password of external central auth is diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/MusicCookieCsrfTokenRepository.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/MusicCookieCsrfTokenRepository.java index 988b97a5..891f6d78 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/MusicCookieCsrfTokenRepository.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/MusicCookieCsrfTokenRepository.java @@ -50,6 +50,20 @@ import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.csrf.DefaultCsrfToken; import org.springframework.util.StringUtils; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.util.HashMap; +import java.util.Map; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; + public final class MusicCookieCsrfTokenRepository implements CsrfTokenRepository { static final String CSRF_COOKIE_NAME = "XSRF-TOKEN"; @@ -111,12 +125,22 @@ public final class MusicCookieCsrfTokenRepository implements CsrfTokenRepository return new MusicCookieCsrfTokenRepository(result); } - private String getSessionIdFromCookie (HttpServletRequest request){ + private String getSessionIdFromCookie (HttpServletRequest request) throws JsonParseException, JsonMappingException, UnsupportedEncodingException, IOException, CipherUtilException{ Cookie cookies[] = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (EP_SERVICE.equals(cookie.getName())) { - return cookie.getValue(); + ObjectMapper mapper = new ObjectMapper(); + Map epServiceCookieValueMap = mapper.readValue(URLDecoder.decode(cookie.getValue(), "UTF-8"),HashMap.class); + String sessionId = null; + if(epServiceCookieValueMap!=null) { + String multifactorauthfrontendurl = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.MULTI_FACTOR_AUTH_FRONTEND_URL); + String encryptedJSessionId = epServiceCookieValueMap.get(multifactorauthfrontendurl); + if(encryptedJSessionId != null) { + sessionId = CipherUtil.decryptPKC(encryptedJSessionId); + } + } + return sessionId; } } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/CommonSessionCookieUtil.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/CommonSessionCookieUtil.java new file mode 100644 index 00000000..e0b712a2 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/CommonSessionCookieUtil.java @@ -0,0 +1,151 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (c) 2019 Samsung. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portalapp.util; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; +import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; +import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; +import org.onap.portalsdk.core.web.support.AppUtils; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class CommonSessionCookieUtil { + + public static final String EP_SERVICE = "EPService"; + public static Integer cookieMaxAge = -1; + public static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CommonSessionCookieUtil.class); + public static boolean EP_SERVICE_SECURE = false; + + public static void setUpEPServiceCookie(HttpServletRequest request, HttpServletResponse response) throws CipherUtilException, JsonParseException, JsonMappingException, IOException { + //set up EPService cookie + EP_SERVICE_SECURE = Boolean.parseBoolean(EPCommonSystemProperties.getProperty(EPCommonSystemProperties.EPSERVICE_COOKIE_SECURE)); + String multifactorauthfrontendurl = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.MULTI_FACTOR_AUTH_FRONTEND_URL); + String domainName = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.COOKIE_DOMAIN); + Cookie epCookie = getCookie(request, EP_SERVICE); + ObjectMapper objectMapper = new ObjectMapper(); + if(epCookie != null) { + //If cookie already exist then add the current env and jsessionId to this + String jSessionId = getJessionId(request); + String jsonValue = URLDecoder.decode(epCookie.getValue(),"UTF-8"); + Map valueMap = null; + // if the value is encoded + if(jsonValue.startsWith("{")) { + valueMap = objectMapper.readValue(jsonValue, HashMap.class); + }else { + valueMap = new HashMap<>(); + } + valueMap.put(multifactorauthfrontendurl, CipherUtil.encryptPKC(jSessionId)); + saveOrUpdateEPServiceCookie(response, domainName, objectMapper, valueMap); + }else { + //If cookie does not exist create a cookie with current env and jsessionId + String jSessionId = getJessionId(request); + Map valueMap = new HashMap<>(); + valueMap.put(multifactorauthfrontendurl, CipherUtil.encryptPKC(jSessionId)); + saveOrUpdateEPServiceCookie(response, domainName, objectMapper, valueMap); + } + } + + private static void saveOrUpdateEPServiceCookie(HttpServletResponse response, String domainName, + ObjectMapper objectMapper, Map valueMap) + throws UnsupportedEncodingException, JsonProcessingException { + Cookie cookie1 = new Cookie(EP_SERVICE, URLEncoder.encode(objectMapper.writeValueAsString(valueMap), "UTF-8")); + cookie1.setMaxAge(cookieMaxAge); + cookie1.setDomain(domainName); + cookie1.setPath("/"); + cookie1.setSecure(EP_SERVICE_SECURE); + response.addCookie(cookie1); + } + + //Get cookie from request object on the basis of cookie name + private static Cookie getCookie(HttpServletRequest request, String cookieName) { + Cookie[] cookies = request.getCookies(); + if (cookies != null) + for (Cookie cookie : cookies) + if (cookie.getName().equals(cookieName)) + return cookie; + + return null; + } + + protected static void initateSessionMgtHandler(HttpServletRequest request) { + String jSessionId = getJessionId(request); + storeMaxInactiveTime(request); + PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request)); + } + + protected static void storeMaxInactiveTime(HttpServletRequest request) { + HttpSession session = AppUtils.getSession(request); + if(session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME) == null) + session.setAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME,session.getMaxInactiveInterval()); + } + + public static void resetSessionMaxIdleTimeOut(HttpServletRequest request) { + try { + HttpSession session = AppUtils.getSession(request); + final Object maxIdleAttribute = session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME); + if(session != null && maxIdleAttribute != null) { + session.setMaxInactiveInterval(Integer.parseInt(maxIdleAttribute.toString())); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "resetSessionMaxIdleTimeOut failed", e); + } + + } + + public static String getJessionId(HttpServletRequest request){ + return request.getSession().getId(); + } +} \ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml index e03c9762..961006cc 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml @@ -571,6 +571,12 @@ from Language where languageId = :language_id ]]> + + + + diff --git a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-animate.js b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-animate.js deleted file mode 100644 index 2778fc56..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-animate.js +++ /dev/null @@ -1,4121 +0,0 @@ -/** - * @license AngularJS v1.5.0 - * (c) 2010-2016 Google, Inc. http://angularjs.org - * License: MIT - */ -(function(window, angular, undefined) {'use strict'; - -/* jshint ignore:start */ -var noop = angular.noop; -var copy = angular.copy; -var extend = angular.extend; -var jqLite = angular.element; -var forEach = angular.forEach; -var isArray = angular.isArray; -var isString = angular.isString; -var isObject = angular.isObject; -var isUndefined = angular.isUndefined; -var isDefined = angular.isDefined; -var isFunction = angular.isFunction; -var isElement = angular.isElement; - -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 (isUndefined(window.ontransitionend) && isDefined(window.onwebkittransitionend)) { - CSS_PREFIX = '-webkit-'; - TRANSITION_PROP = 'WebkitTransition'; - TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend'; -} else { - TRANSITION_PROP = 'transition'; - TRANSITIONEND_EVENT = 'transitionend'; -} - -if (isUndefined(window.onanimationend) && isDefined(window.onwebkitanimationend)) { - 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 isPromiseLike = function(p) { - return p && p.then ? true : false; -}; - -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 []; - break; - - 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)); - break; - } - } - - 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]; - } else if (val === REMOVE_CLASS) { - prop = 'removeClass'; - allow = existing[klass]; - } - 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 angular.element) ? 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 `ngAnimteChildren` 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() { - this.animateChildren = false; - this.enterElement = false; - }); - -
- */ -var $$AnimateChildrenDirective = ['$interpolate', function($interpolate) { - return { - link: function(scope, element, attrs) { - var val = attrs.ngAnimateChildren; - if (angular.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); - } - } - }; -}]; - -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 BASE_TEN = 10; - -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', 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 cancelLastRAFRequest; - 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) { // jshint ignore:line - // 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) { - value ? node.style.setProperty(prop, value) - : 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); - animationPaused - ? temporaryStyles.push(value) - : 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', 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 - ); - - var applyAnimationClasses = applyAnimationClassesFactory($$jqLite); - - 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', 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()); - }); - } - - runners.length ? $$AnimateRunner.all(runners, callback) : callback(); - - return function endFn(reject) { - forEach(runners, function(runner) { - reject ? runner.cancel() : 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', 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', 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) { - 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 = {}; - - // 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 = Node.prototype.contains || function(arg) { - // jshint bitwise: false - return this === arg || !!(this.compareDocumentPosition(arg) & 16); - // jshint bitwise: true - }; - - 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; - } - - return { - on: function(event, container, callback) { - var node = extractElementNode(container); - callbackRegistry[event] = callbackRegistry[event] || []; - callbackRegistry[event].push({ - node: node, - callback: callback - }); - }, - - off: function(event, container, callback) { - var entries = callbackRegistry[event]; - if (!entries) return; - - callbackRegistry[event] = arguments.length === 1 - ? null - : filterFromRegistry(entries, container, callback); - - 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; - }); - } - }, - - 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); - var recordExists = disabledElementsLookup.get(node); - - if (argCount === 1) { - // (element) - Element getter - bool = !recordExists; - } else { - // (element, bool) - Element setter - disabledElementsLookup.put(node, !bool); - } - } - } - - return bool; - } - }; - - 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; - - // 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 || $document[0].hidden || 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) { - 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); - - realRunner.done(function(status) { - close(!status); - var animationDetails = activeAnimationsLookup.get(node); - if (animationDetails && animationDetails.counter === counter) { - clearElementAnimationState(getDomNode(element)); - } - notifyProgress(runner, event, 'close', {}); - }); - - // this will update the runner's flow-control events based on - // the `realRunner` object. - runner.setHost(realRunner); - notifyProgress(runner, event, 'start', {}); - }); - - 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); - }); - }); - } - }); - runner.progress(event, phase, data); - } - - function close(reject) { // jshint ignore:line - 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)); - 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 = element.data(NG_ANIMATE_PIN_DATA); - if (parentHost) { - parentElement = parentHost; - } - - while (parentElement && parentElement.length) { - 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); - } - - var parentNode = parentElement[0]; - if (parentNode.nodeType !== ELEMENT_NODE) { - // no point in inspecting the #document element - break; - } - - var details = activeAnimationsLookup.get(parentNode) || {}; - // 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(parentNode); - - 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 = parentElement.data(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 = parentElement.data(NG_ANIMATE_PIN_DATA); - if (parentHost) { - // The pin target element becomes the next parent element - parentElement = parentHost; - continue; - } - } - - parentElement = parentElement.parent(); - } - - 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); - } - }]; -}]; - -var $$AnimationProvider = ['$animateProvider', 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]; - if (!$injector.has(driverName)) continue; // TODO(matsko): remove this check - - 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) { - getRunner(element).setHost(newRunner); - } - } - - function handleDestroyedElement() { - var runner = getRunner(element); - if (runner && (event !== 'leave' || !options.$$domOperationFired)) { - runner.end(); - } - } - - function close(rejected) { // jshint ignore:line - 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 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. - * - * @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); - }); - } - }); - } - }; -}]; - -/* global angularAnimateModule: true, - - ngAnimateSwapDirective, - $$AnimateAsyncRunFactory, - $$rAFSchedulerFactory, - $$AnimateChildrenDirective, - $$AnimateQueueProvider, - $$AnimationProvider, - $AnimateCssProvider, - $$AnimateCssDriverProvider, - $$AnimateJsProvider, - $$AnimateJsDriverProvider, -*/ - -/** - * @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 the 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($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}. - * - * - * ### Preventing Collisions With Third Party Libraries - * - * Some third-party frameworks place animation duration defaults across many element or className - * selectors in order to make their code small and reuseable. This can lead to issues with ngAnimate, which - * is expecting actual animations on these elements and has to wait for their completion. - * - * You can prevent this unwanted behavior by using a prefix on all your animation classes: - * - * ```css - * /* prefixed with animate- */ - * .animate-fade-add.animate-fade-add-active { - * transition:1s linear all; - * opacity:0; - * } - * ``` - * - * You then configure `$animate` to enforce this prefix: - * - * ```js - * $animateProvider.classNameFilter(/animate-/); - * ``` - * - * This also may provide your application with a speed boost since only specific elements containing CSS class prefix - * will be evaluated for animation when any DOM changes occur in the application. - * - * ## 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.) - */ - -/** - * @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', []) - .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/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-animate.min.js b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-animate.min.js deleted file mode 100644 index 8e8e41df..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-animate.min.js +++ /dev/null @@ -1,56 +0,0 @@ -/* - AngularJS v1.5.0 - (c) 2010-2016 Google, Inc. http://angularjs.org - License: MIT -*/ -(function(D,r,Va){'use strict';function ya(a,b,c){if(!a)throw Ka("areq",b||"?",c||"required");return a}function za(a,b){if(!a&&!b)return"";if(!a)return b;if(!b)return a;ba(a)&&(a=a.join(" "));ba(b)&&(b=b.join(" "));return a+" "+b}function La(a){var b={};a&&(a.to||a.from)&&(b.to=a.to,b.from=a.from);return b}function X(a,b,c){var d="";a=ba(a)?a:a&&R(a)&&a.length?a.split(/\s+/):[];s(a,function(a,g){a&&0=a&&(a=e,e=0,b.push(t),t=[]);t.push(g.fn);g.children.forEach(function(a){e++; -c.push(a)});a--}t.length&&b.push(t);return b}(c)}var M=[],r=U(a);return function(u,A,v){function z(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 K(a){var b=[],c={};s(a,function(a,f){var d=G(a.element),h=0<=["enter","move"].indexOf(a.event),d=a.structural?z(d):[];if(d.length){var e=h?"to":"from";s(d,function(a){var b=a.getAttribute("ng-animate-ref");c[b]=c[b]|| -{};c[b][e]={animationID:f,element:I(a)}})}else b.push(a)});var d={},h={};s(c,function(c,e){var l=c.from,t=c.to;if(l&&t){var g=a[l.animationID],E=a[t.animationID],k=l.animationID.toString();if(!h[k]){var z=h[k]={structural:!0,beforeStart:function(){g.beforeStart();E.beforeStart()},close:function(){g.close();E.close()},classes:J(g.classes,E.classes),from:g,to:E,anchors:[]};z.classes.length?b.push(z):(b.push(g),b.push(E))}h[k].anchors.push({out:l.element,"in":t.element})}else l=l?l.animationID:t.animationID, -t=l.toString(),d[t]||(d[t]=!0,b.push(a[l]))});return b}function J(a,b){a=a.split(" ");b=b.split(" ");for(var c=[],d=0;d=P&&b>=O&&(wa=!0,q())}function L(){function b(){if(!A){t(!1);s(m, -function(a){l.style[a[0]]=a[1]});z(a,f);e.addClass(a,ca);if(p.recalculateTimingStyles){ja=l.className+" "+da;ga=r(l,ja);F=v(l,ja,ga);$=F.maxDelay;n=Math.max($,0);O=F.maxDuration;if(0===O){q();return}p.hasTransitions=0B.expectedEndTime)?H.cancel(B.timer):g.push(q)}L&&(k=H(c,k,!1),g[0]={timer:k,expectedEndTime:d},g.push(q),a.data("$$animateCss",g));if(ea.length)a.on(ea.join(" "),E);f.to&&(f.cleanupStyles&&Ga(x,l,Object.keys(f.to)),Ba(a, -f))}}function c(){var b=a.data("$$animateCss");if(b){for(var d=1;dARIA](http://www.w3.org/TR/wai-aria/) - * attributes that convey state or semantic information about the application for users - * of assistive technologies, such as screen readers. - * - *
- * - * ## Usage - * - * For ngAria to do its magic, simply include the module `ngAria` as a dependency. The following - * directives are supported: - * `ngModel`, `ngChecked`, `ngRequired`, `ngValue`, `ngDisabled`, `ngShow`, `ngHide`, `ngClick`, - * `ngDblClick`, and `ngMessages`. - * - * Below is a more detailed breakdown of the attributes handled by ngAria: - * - * | Directive | Supported Attributes | - * |---------------------------------------------|----------------------------------------------------------------------------------------| - * | {@link ng.directive:ngModel ngModel} | aria-checked, aria-valuemin, aria-valuemax, aria-valuenow, aria-invalid, aria-required, input roles | - * | {@link ng.directive:ngDisabled ngDisabled} | aria-disabled | - * | {@link ng.directive:ngRequired ngRequired} | aria-required | - * | {@link ng.directive:ngChecked ngChecked} | aria-checked | - * | {@link ng.directive:ngValue ngValue} | aria-checked | - * | {@link ng.directive:ngShow ngShow} | aria-hidden | - * | {@link ng.directive:ngHide ngHide} | aria-hidden | - * | {@link ng.directive:ngDblclick ngDblclick} | tabindex | - * | {@link module:ngMessages ngMessages} | aria-live | - * | {@link ng.directive:ngClick ngClick} | tabindex, keypress event, button role | - * - * Find out more information about each directive by reading the - * {@link guide/accessibility ngAria Developer Guide}. - * - * ##Example - * Using ngDisabled with ngAria: - * ```html - * - * ``` - * Becomes: - * ```html - * - * ``` - * - * ##Disabling Attributes - * It's possible to disable individual attributes added by ngAria with the - * {@link ngAria.$ariaProvider#config config} method. For more details, see the - * {@link guide/accessibility Developer Guide}. - */ - /* global -ngAriaModule */ -var ngAriaModule = angular.module('ngAria', ['ng']). - provider('$aria', $AriaProvider); - -/** -* Internal Utilities -*/ -var nodeBlackList = ['BUTTON', 'A', 'INPUT', 'TEXTAREA', 'SELECT', 'DETAILS', 'SUMMARY']; - -var isNodeOneOf = function(elem, nodeTypeArray) { - if (nodeTypeArray.indexOf(elem[0].nodeName) !== -1) { - return true; - } -}; -/** - * @ngdoc provider - * @name $ariaProvider - * - * @description - * - * Used for configuring the ARIA attributes injected and managed by ngAria. - * - * ```js - * angular.module('myApp', ['ngAria'], function config($ariaProvider) { - * $ariaProvider.config({ - * ariaValue: true, - * tabindex: false - * }); - * }); - *``` - * - * ## Dependencies - * Requires the {@link ngAria} module to be installed. - * - */ -function $AriaProvider() { - var config = { - ariaHidden: true, - ariaChecked: true, - ariaDisabled: true, - ariaRequired: true, - ariaInvalid: true, - ariaValue: true, - tabindex: true, - bindKeypress: true, - bindRoleForClick: true - }; - - /** - * @ngdoc method - * @name $ariaProvider#config - * - * @param {object} config object to enable/disable specific ARIA attributes - * - * - **ariaHidden** – `{boolean}` – Enables/disables aria-hidden tags - * - **ariaChecked** – `{boolean}` – Enables/disables aria-checked tags - * - **ariaDisabled** – `{boolean}` – Enables/disables aria-disabled tags - * - **ariaRequired** – `{boolean}` – Enables/disables aria-required tags - * - **ariaInvalid** – `{boolean}` – Enables/disables aria-invalid tags - * - **ariaValue** – `{boolean}` – Enables/disables aria-valuemin, aria-valuemax and aria-valuenow tags - * - **tabindex** – `{boolean}` – Enables/disables tabindex tags - * - **bindKeypress** – `{boolean}` – Enables/disables keypress event binding on `div` and - * `li` elements with ng-click - * - **bindRoleForClick** – `{boolean}` – Adds role=button to non-interactive elements like `div` - * using ng-click, making them more accessible to users of assistive technologies - * - * @description - * Enables/disables various ARIA attributes - */ - this.config = function(newConfig) { - config = angular.extend(config, newConfig); - }; - - function watchExpr(attrName, ariaAttr, nodeBlackList, negate) { - return function(scope, elem, attr) { - var ariaCamelName = attr.$normalize(ariaAttr); - if (config[ariaCamelName] && !isNodeOneOf(elem, nodeBlackList) && !attr[ariaCamelName]) { - scope.$watch(attr[attrName], function(boolVal) { - // ensure boolean value - boolVal = negate ? !boolVal : !!boolVal; - elem.attr(ariaAttr, boolVal); - }); - } - }; - } - /** - * @ngdoc service - * @name $aria - * - * @description - * @priority 200 - * - * The $aria service contains helper methods for applying common - * [ARIA](http://www.w3.org/TR/wai-aria/) attributes to HTML directives. - * - * ngAria injects common accessibility attributes that tell assistive technologies when HTML - * elements are enabled, selected, hidden, and more. To see how this is performed with ngAria, - * let's review a code snippet from ngAria itself: - * - *```js - * ngAriaModule.directive('ngDisabled', ['$aria', function($aria) { - * return $aria.$$watchExpr('ngDisabled', 'aria-disabled', nodeBlackList, false); - * }]) - *``` - * Shown above, the ngAria module creates a directive with the same signature as the - * traditional `ng-disabled` directive. But this ngAria version is dedicated to - * solely managing accessibility attributes on custom elements. The internal `$aria` service is - * used to watch the boolean attribute `ngDisabled`. If it has not been explicitly set by the - * developer, `aria-disabled` is injected as an attribute with its value synchronized to the - * value in `ngDisabled`. - * - * Because ngAria hooks into the `ng-disabled` directive, developers do not have to do - * anything to enable this feature. The `aria-disabled` attribute is automatically managed - * simply as a silent side-effect of using `ng-disabled` with the ngAria module. - * - * The full list of directives that interface with ngAria: - * * **ngModel** - * * **ngChecked** - * * **ngRequired** - * * **ngDisabled** - * * **ngValue** - * * **ngShow** - * * **ngHide** - * * **ngClick** - * * **ngDblclick** - * * **ngMessages** - * - * Read the {@link guide/accessibility ngAria Developer Guide} for a thorough explanation of each - * directive. - * - * - * ## Dependencies - * Requires the {@link ngAria} module to be installed. - */ - this.$get = function() { - return { - config: function(key) { - return config[key]; - }, - $$watchExpr: watchExpr - }; - }; -} - - -ngAriaModule.directive('ngShow', ['$aria', function($aria) { - return $aria.$$watchExpr('ngShow', 'aria-hidden', [], true); -}]) -.directive('ngHide', ['$aria', function($aria) { - return $aria.$$watchExpr('ngHide', 'aria-hidden', [], false); -}]) -.directive('ngValue', ['$aria', function($aria) { - return $aria.$$watchExpr('ngValue', 'aria-checked', nodeBlackList, false); -}]) -.directive('ngChecked', ['$aria', function($aria) { - return $aria.$$watchExpr('ngChecked', 'aria-checked', nodeBlackList, false); -}]) -.directive('ngRequired', ['$aria', function($aria) { - return $aria.$$watchExpr('ngRequired', 'aria-required', nodeBlackList, false); -}]) -.directive('ngModel', ['$aria', function($aria) { - - function shouldAttachAttr(attr, normalizedAttr, elem, allowBlacklistEls) { - return $aria.config(normalizedAttr) && !elem.attr(attr) && (allowBlacklistEls || !isNodeOneOf(elem, nodeBlackList)); - } - - function shouldAttachRole(role, elem) { - // if element does not have role attribute - // AND element type is equal to role (if custom element has a type equaling shape) <-- remove? - // AND element is not INPUT - return !elem.attr('role') && (elem.attr('type') === role) && (elem[0].nodeName !== 'INPUT'); - } - - function getShape(attr, elem) { - var type = attr.type, - role = attr.role; - - return ((type || role) === 'checkbox' || role === 'menuitemcheckbox') ? 'checkbox' : - ((type || role) === 'radio' || role === 'menuitemradio') ? 'radio' : - (type === 'range' || role === 'progressbar' || role === 'slider') ? 'range' : ''; - } - - return { - restrict: 'A', - require: 'ngModel', - priority: 200, //Make sure watches are fired after any other directives that affect the ngModel value - compile: function(elem, attr) { - var shape = getShape(attr, elem); - - return { - pre: function(scope, elem, attr, ngModel) { - if (shape === 'checkbox') { - //Use the input[checkbox] $isEmpty implementation for elements with checkbox roles - ngModel.$isEmpty = function(value) { - return value === false; - }; - } - }, - post: function(scope, elem, attr, ngModel) { - var needsTabIndex = shouldAttachAttr('tabindex', 'tabindex', elem, false); - - function ngAriaWatchModelValue() { - return ngModel.$modelValue; - } - - function getRadioReaction(newVal) { - var boolVal = (attr.value == ngModel.$viewValue); - elem.attr('aria-checked', boolVal); - } - - function getCheckboxReaction() { - elem.attr('aria-checked', !ngModel.$isEmpty(ngModel.$viewValue)); - } - - switch (shape) { - case 'radio': - case 'checkbox': - if (shouldAttachRole(shape, elem)) { - elem.attr('role', shape); - } - if (shouldAttachAttr('aria-checked', 'ariaChecked', elem, false)) { - scope.$watch(ngAriaWatchModelValue, shape === 'radio' ? - getRadioReaction : getCheckboxReaction); - } - if (needsTabIndex) { - elem.attr('tabindex', 0); - } - break; - case 'range': - if (shouldAttachRole(shape, elem)) { - elem.attr('role', 'slider'); - } - if ($aria.config('ariaValue')) { - var needsAriaValuemin = !elem.attr('aria-valuemin') && - (attr.hasOwnProperty('min') || attr.hasOwnProperty('ngMin')); - var needsAriaValuemax = !elem.attr('aria-valuemax') && - (attr.hasOwnProperty('max') || attr.hasOwnProperty('ngMax')); - var needsAriaValuenow = !elem.attr('aria-valuenow'); - - if (needsAriaValuemin) { - attr.$observe('min', function ngAriaValueMinReaction(newVal) { - elem.attr('aria-valuemin', newVal); - }); - } - if (needsAriaValuemax) { - attr.$observe('max', function ngAriaValueMinReaction(newVal) { - elem.attr('aria-valuemax', newVal); - }); - } - if (needsAriaValuenow) { - scope.$watch(ngAriaWatchModelValue, function ngAriaValueNowReaction(newVal) { - elem.attr('aria-valuenow', newVal); - }); - } - } - if (needsTabIndex) { - elem.attr('tabindex', 0); - } - break; - } - - if (!attr.hasOwnProperty('ngRequired') && ngModel.$validators.required - && shouldAttachAttr('aria-required', 'ariaRequired', elem, false)) { - // ngModel.$error.required is undefined on custom controls - attr.$observe('required', function() { - elem.attr('aria-required', !!attr['required']); - }); - } - - if (shouldAttachAttr('aria-invalid', 'ariaInvalid', elem, true)) { - scope.$watch(function ngAriaInvalidWatch() { - return ngModel.$invalid; - }, function ngAriaInvalidReaction(newVal) { - elem.attr('aria-invalid', !!newVal); - }); - } - } - }; - } - }; -}]) -.directive('ngDisabled', ['$aria', function($aria) { - return $aria.$$watchExpr('ngDisabled', 'aria-disabled', nodeBlackList, false); -}]) -.directive('ngMessages', function() { - return { - restrict: 'A', - require: '?ngMessages', - link: function(scope, elem, attr, ngMessages) { - if (!elem.attr('aria-live')) { - elem.attr('aria-live', 'assertive'); - } - } - }; -}) -.directive('ngClick',['$aria', '$parse', function($aria, $parse) { - return { - restrict: 'A', - compile: function(elem, attr) { - var fn = $parse(attr.ngClick, /* interceptorFn */ null, /* expensiveChecks */ true); - return function(scope, elem, attr) { - - if (!isNodeOneOf(elem, nodeBlackList)) { - - if ($aria.config('bindRoleForClick') && !elem.attr('role')) { - elem.attr('role', 'button'); - } - - if ($aria.config('tabindex') && !elem.attr('tabindex')) { - elem.attr('tabindex', 0); - } - - if ($aria.config('bindKeypress') && !attr.ngKeypress) { - elem.on('keypress', function(event) { - var keyCode = event.which || event.keyCode; - if (keyCode === 32 || keyCode === 13) { - scope.$apply(callback); - } - - function callback() { - fn(scope, { $event: event }); - } - }); - } - } - }; - } - }; -}]) -.directive('ngDblclick', ['$aria', function($aria) { - return function(scope, elem, attr) { - if ($aria.config('tabindex') && !elem.attr('tabindex') && !isNodeOneOf(elem, nodeBlackList)) { - elem.attr('tabindex', 0); - } - }; -}]); - - -})(window, window.angular); diff --git a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-aria.min.js b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-aria.min.js deleted file mode 100644 index cf0fd742..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-aria.min.js +++ /dev/null @@ -1,14 +0,0 @@ -/* - AngularJS v1.5.0 - (c) 2010-2016 Google, Inc. http://angularjs.org - License: MIT -*/ -(function(s,q,t){'use strict';var f="BUTTON A INPUT TEXTAREA SELECT DETAILS SUMMARY".split(" "),l=function(a,c){if(-1!==c.indexOf(a[0].nodeName))return!0};q.module("ngAria",["ng"]).provider("$aria",function(){function a(a,h,p,n){return function(d,e,b){var g=b.$normalize(h);!c[g]||l(e,p)||b[g]||d.$watch(b[a],function(b){b=n?!b:!!b;e.attr(h,b)})}}var c={ariaHidden:!0,ariaChecked:!0,ariaDisabled:!0,ariaRequired:!0,ariaInvalid:!0,ariaValue:!0,tabindex:!0,bindKeypress:!0,bindRoleForClick:!0};this.config= -function(a){c=q.extend(c,a)};this.$get=function(){return{config:function(a){return c[a]},$$watchExpr:a}}}).directive("ngShow",["$aria",function(a){return a.$$watchExpr("ngShow","aria-hidden",[],!0)}]).directive("ngHide",["$aria",function(a){return a.$$watchExpr("ngHide","aria-hidden",[],!1)}]).directive("ngValue",["$aria",function(a){return a.$$watchExpr("ngValue","aria-checked",f,!1)}]).directive("ngChecked",["$aria",function(a){return a.$$watchExpr("ngChecked","aria-checked",f,!1)}]).directive("ngRequired", -["$aria",function(a){return a.$$watchExpr("ngRequired","aria-required",f,!1)}]).directive("ngModel",["$aria",function(a){function c(c,n,d,e){return a.config(n)&&!d.attr(c)&&(e||!l(d,f))}function m(a,c){return!c.attr("role")&&c.attr("type")===a&&"INPUT"!==c[0].nodeName}function h(a,c){var d=a.type,e=a.role;return"checkbox"===(d||e)||"menuitemcheckbox"===e?"checkbox":"radio"===(d||e)||"menuitemradio"===e?"radio":"range"===d||"progressbar"===e||"slider"===e?"range":""}return{restrict:"A",require:"ngModel", -priority:200,compile:function(f,n){var d=h(n,f);return{pre:function(a,b,c,k){"checkbox"===d&&(k.$isEmpty=function(a){return!1===a})},post:function(e,b,g,k){function f(){return k.$modelValue}function h(a){b.attr("aria-checked",g.value==k.$viewValue)}function n(){b.attr("aria-checked",!k.$isEmpty(k.$viewValue))}var l=c("tabindex","tabindex",b,!1);switch(d){case "radio":case "checkbox":m(d,b)&&b.attr("role",d);c("aria-checked","ariaChecked",b,!1)&&e.$watch(f,"radio"===d?h:n);l&&b.attr("tabindex",0); -break;case "range":m(d,b)&&b.attr("role","slider");if(a.config("ariaValue")){var p=!b.attr("aria-valuemin")&&(g.hasOwnProperty("min")||g.hasOwnProperty("ngMin")),q=!b.attr("aria-valuemax")&&(g.hasOwnProperty("max")||g.hasOwnProperty("ngMax")),r=!b.attr("aria-valuenow");p&&g.$observe("min",function(a){b.attr("aria-valuemin",a)});q&&g.$observe("max",function(a){b.attr("aria-valuemax",a)});r&&e.$watch(f,function(a){b.attr("aria-valuenow",a)})}l&&b.attr("tabindex",0)}!g.hasOwnProperty("ngRequired")&& -k.$validators.required&&c("aria-required","ariaRequired",b,!1)&&g.$observe("required",function(){b.attr("aria-required",!!g.required)});c("aria-invalid","ariaInvalid",b,!0)&&e.$watch(function(){return k.$invalid},function(a){b.attr("aria-invalid",!!a)})}}}}}]).directive("ngDisabled",["$aria",function(a){return a.$$watchExpr("ngDisabled","aria-disabled",f,!1)}]).directive("ngMessages",function(){return{restrict:"A",require:"?ngMessages",link:function(a,c,f,h){c.attr("aria-live")||c.attr("aria-live", -"assertive")}}}).directive("ngClick",["$aria","$parse",function(a,c){return{restrict:"A",compile:function(m,h){var p=c(h.ngClick,null,!0);return function(c,d,e){if(!l(d,f)&&(a.config("bindRoleForClick")&&!d.attr("role")&&d.attr("role","button"),a.config("tabindex")&&!d.attr("tabindex")&&d.attr("tabindex",0),a.config("bindKeypress")&&!e.ngKeypress))d.on("keypress",function(a){function d(){p(c,{$event:a})}var e=a.which||a.keyCode;32!==e&&13!==e||c.$apply(d)})}}}}]).directive("ngDblclick",["$aria",function(a){return function(c, -m,h){!a.config("tabindex")||m.attr("tabindex")||l(m,f)||m.attr("tabindex",0)}}])})(window,window.angular); -//# sourceMappingURL=angular-aria.min.js.map diff --git a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-cookies.js b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-cookies.js deleted file mode 100644 index 2157ef03..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-cookies.js +++ /dev/null @@ -1,322 +0,0 @@ -/** - * @license AngularJS v1.5.0 - * (c) 2010-2016 Google, Inc. http://angularjs.org - * License: MIT - */ -(function(window, angular, undefined) {'use strict'; - -/** - * @ngdoc module - * @name ngCookies - * @description - * - * # ngCookies - * - * The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies. - * - * - *
- * - * See {@link ngCookies.$cookies `$cookies`} for usage. - */ - - -angular.module('ngCookies', ['ng']). - /** - * @ngdoc provider - * @name $cookiesProvider - * @description - * Use `$cookiesProvider` to change the default behavior of the {@link ngCookies.$cookies $cookies} service. - * */ - provider('$cookies', [function $CookiesProvider() { - /** - * @ngdoc property - * @name $cookiesProvider#defaults - * @description - * - * Object containing default options to pass when setting cookies. - * - * The object may have following properties: - * - * - **path** - `{string}` - The cookie will be available only for this path and its - * sub-paths. By default, this is the URL that appears in your `` tag. - * - **domain** - `{string}` - The cookie will be available only for this domain and - * its sub-domains. For security reasons the user agent will not accept the cookie - * if the current domain is not a sub-domain of this domain or equal to it. - * - **expires** - `{string|Date}` - String of the form "Wdy, DD Mon YYYY HH:MM:SS GMT" - * or a Date object indicating the exact date/time this cookie will expire. - * - **secure** - `{boolean}` - If `true`, then the cookie will only be available through a - * secured connection. - * - * Note: By default, the address that appears in your `` tag will be used as the path. - * This is important so that cookies will be visible for all routes when html5mode is enabled. - * - **/ - var defaults = this.defaults = {}; - - function calcOptions(options) { - return options ? angular.extend({}, defaults, options) : defaults; - } - - /** - * @ngdoc service - * @name $cookies - * - * @description - * Provides read/write access to browser's cookies. - * - *
- * Up until Angular 1.3, `$cookies` exposed properties that represented the - * current browser cookie values. In version 1.4, this behavior has changed, and - * `$cookies` now provides a standard api of getters, setters etc. - *
- * - * Requires the {@link ngCookies `ngCookies`} module to be installed. - * - * @example - * - * ```js - * angular.module('cookiesExample', ['ngCookies']) - * .controller('ExampleController', ['$cookies', function($cookies) { - * // Retrieving a cookie - * var favoriteCookie = $cookies.get('myFavorite'); - * // Setting a cookie - * $cookies.put('myFavorite', 'oatmeal'); - * }]); - * ``` - */ - this.$get = ['$$cookieReader', '$$cookieWriter', function($$cookieReader, $$cookieWriter) { - return { - /** - * @ngdoc method - * @name $cookies#get - * - * @description - * Returns the value of given cookie key - * - * @param {string} key Id to use for lookup. - * @returns {string} Raw cookie value. - */ - get: function(key) { - return $$cookieReader()[key]; - }, - - /** - * @ngdoc method - * @name $cookies#getObject - * - * @description - * Returns the deserialized value of given cookie key - * - * @param {string} key Id to use for lookup. - * @returns {Object} Deserialized cookie value. - */ - getObject: function(key) { - var value = this.get(key); - return value ? angular.fromJson(value) : value; - }, - - /** - * @ngdoc method - * @name $cookies#getAll - * - * @description - * Returns a key value object with all the cookies - * - * @returns {Object} All cookies - */ - getAll: function() { - return $$cookieReader(); - }, - - /** - * @ngdoc method - * @name $cookies#put - * - * @description - * Sets a value for given cookie key - * - * @param {string} key Id for the `value`. - * @param {string} value Raw value to be stored. - * @param {Object=} options Options object. - * See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults} - */ - put: function(key, value, options) { - $$cookieWriter(key, value, calcOptions(options)); - }, - - /** - * @ngdoc method - * @name $cookies#putObject - * - * @description - * Serializes and sets a value for given cookie key - * - * @param {string} key Id for the `value`. - * @param {Object} value Value to be stored. - * @param {Object=} options Options object. - * See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults} - */ - putObject: function(key, value, options) { - this.put(key, angular.toJson(value), options); - }, - - /** - * @ngdoc method - * @name $cookies#remove - * - * @description - * Remove given cookie - * - * @param {string} key Id of the key-value pair to delete. - * @param {Object=} options Options object. - * See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults} - */ - remove: function(key, options) { - $$cookieWriter(key, undefined, calcOptions(options)); - } - }; - }]; - }]); - -angular.module('ngCookies'). -/** - * @ngdoc service - * @name $cookieStore - * @deprecated - * @requires $cookies - * - * @description - * Provides a key-value (string-object) storage, that is backed by session cookies. - * Objects put or retrieved from this storage are automatically serialized or - * deserialized by angular's toJson/fromJson. - * - * Requires the {@link ngCookies `ngCookies`} module to be installed. - * - *
- * **Note:** The $cookieStore service is **deprecated**. - * Please use the {@link ngCookies.$cookies `$cookies`} service instead. - *
- * - * @example - * - * ```js - * angular.module('cookieStoreExample', ['ngCookies']) - * .controller('ExampleController', ['$cookieStore', function($cookieStore) { - * // Put cookie - * $cookieStore.put('myFavorite','oatmeal'); - * // Get cookie - * var favoriteCookie = $cookieStore.get('myFavorite'); - * // Removing a cookie - * $cookieStore.remove('myFavorite'); - * }]); - * ``` - */ - factory('$cookieStore', ['$cookies', function($cookies) { - - return { - /** - * @ngdoc method - * @name $cookieStore#get - * - * @description - * Returns the value of given cookie key - * - * @param {string} key Id to use for lookup. - * @returns {Object} Deserialized cookie value, undefined if the cookie does not exist. - */ - get: function(key) { - return $cookies.getObject(key); - }, - - /** - * @ngdoc method - * @name $cookieStore#put - * - * @description - * Sets a value for given cookie key - * - * @param {string} key Id for the `value`. - * @param {Object} value Value to be stored. - */ - put: function(key, value) { - $cookies.putObject(key, value); - }, - - /** - * @ngdoc method - * @name $cookieStore#remove - * - * @description - * Remove given cookie - * - * @param {string} key Id of the key-value pair to delete. - */ - remove: function(key) { - $cookies.remove(key); - } - }; - - }]); - -/** - * @name $$cookieWriter - * @requires $document - * - * @description - * This is a private service for writing cookies - * - * @param {string} name Cookie name - * @param {string=} value Cookie value (if undefined, cookie will be deleted) - * @param {Object=} options Object with options that need to be stored for the cookie. - */ -function $$CookieWriter($document, $log, $browser) { - var cookiePath = $browser.baseHref(); - var rawDocument = $document[0]; - - function buildCookieString(name, value, options) { - var path, expires; - options = options || {}; - expires = options.expires; - path = angular.isDefined(options.path) ? options.path : cookiePath; - if (angular.isUndefined(value)) { - expires = 'Thu, 01 Jan 1970 00:00:00 GMT'; - value = ''; - } - if (angular.isString(expires)) { - expires = new Date(expires); - } - - var str = encodeURIComponent(name) + '=' + encodeURIComponent(value); - str += path ? ';path=' + path : ''; - str += options.domain ? ';domain=' + options.domain : ''; - str += expires ? ';expires=' + expires.toUTCString() : ''; - str += options.secure ? ';secure' : ''; - - // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: - // - 300 cookies - // - 20 cookies per unique domain - // - 4096 bytes per cookie - var cookieLength = str.length + 1; - if (cookieLength > 4096) { - $log.warn("Cookie '" + name + - "' possibly not set or overflowed because it was too large (" + - cookieLength + " > 4096 bytes)!"); - } - - return str; - } - - return function(name, value, options) { - rawDocument.cookie = buildCookieString(name, value, options); - }; -} - -$$CookieWriter.$inject = ['$document', '$log', '$browser']; - -angular.module('ngCookies').provider('$$cookieWriter', function $$CookieWriterProvider() { - this.$get = $$CookieWriter; -}); - - -})(window, window.angular); diff --git a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-cookies.min.js b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-cookies.min.js deleted file mode 100644 index d0f126a9..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-cookies.min.js +++ /dev/null @@ -1,9 +0,0 @@ -/* - AngularJS v1.5.0 - (c) 2010-2016 Google, Inc. http://angularjs.org - License: MIT -*/ -(function(p,c,n){'use strict';function l(b,a,g){var d=g.baseHref(),k=b[0];return function(b,e,f){var g,h;f=f||{};h=f.expires;g=c.isDefined(f.path)?f.path:d;c.isUndefined(e)&&(h="Thu, 01 Jan 1970 00:00:00 GMT",e="");c.isString(h)&&(h=new Date(h));e=encodeURIComponent(b)+"="+encodeURIComponent(e);e=e+(g?";path="+g:"")+(f.domain?";domain="+f.domain:"");e+=h?";expires="+h.toUTCString():"";e+=f.secure?";secure":"";f=e.length+1;4096 4096 bytes)!");k.cookie=e}}c.module("ngCookies",["ng"]).provider("$cookies",[function(){var b=this.defaults={};this.$get=["$$cookieReader","$$cookieWriter",function(a,g){return{get:function(d){return a()[d]},getObject:function(d){return(d=this.get(d))?c.fromJson(d):d},getAll:function(){return a()},put:function(d,a,m){g(d,a,m?c.extend({},b,m):b)},putObject:function(d,b,a){this.put(d,c.toJson(b),a)},remove:function(a,k){g(a,n,k?c.extend({},b,k):b)}}}]}]);c.module("ngCookies").factory("$cookieStore", -["$cookies",function(b){return{get:function(a){return b.getObject(a)},put:function(a,c){b.putObject(a,c)},remove:function(a){b.remove(a)}}}]);l.$inject=["$document","$log","$browser"];c.module("ngCookies").provider("$$cookieWriter",function(){this.$get=l})})(window,window.angular); -//# sourceMappingURL=angular-cookies.min.js.map diff --git a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-csp.css b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-csp.css deleted file mode 100644 index f3cd926c..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-csp.css +++ /dev/null @@ -1,21 +0,0 @@ -/* Include this file in your html if you are using the CSP mode. */ - -@charset "UTF-8"; - -[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], -.ng-cloak, .x-ng-cloak, -.ng-hide:not(.ng-hide-animate) { - display: none !important; -} - -ng\:form { - display: block; -} - -.ng-animate-shim { - visibility:hidden; -} - -.ng-anchor { - position:absolute; -} diff --git a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-loader.js b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-loader.js deleted file mode 100644 index 77948fd5..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-loader.js +++ /dev/null @@ -1,484 +0,0 @@ -/** - * @license AngularJS v1.5.0 - * (c) 2010-2016 Google, Inc. http://angularjs.org - * License: MIT - */ - -(function() {'use strict'; - function isFunction(value) {return typeof value === 'function';}; - -/* global: toDebugString: true */ - -function serializeObject(obj) { - var seen = []; - - return JSON.stringify(obj, function(key, val) { - val = toJsonReplacer(key, val); - if (isObject(val)) { - - if (seen.indexOf(val) >= 0) return '...'; - - seen.push(val); - } - return val; - }); -} - -function toDebugString(obj) { - if (typeof obj === 'function') { - return obj.toString().replace(/ \{[\s\S]*$/, ''); - } else if (isUndefined(obj)) { - return 'undefined'; - } else if (typeof obj !== 'string') { - return serializeObject(obj); - } - return obj; -} - -/** - * @description - * - * This object provides a utility for producing rich Error messages within - * Angular. It can be called as follows: - * - * var exampleMinErr = minErr('example'); - * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); - * - * The above creates an instance of minErr in the example namespace. The - * resulting error will have a namespaced error code of example.one. The - * resulting error will replace {0} with the value of foo, and {1} with the - * value of bar. The object is not restricted in the number of arguments it can - * take. - * - * If fewer arguments are specified than necessary for interpolation, the extra - * interpolation markers will be preserved in the final string. - * - * Since data will be parsed statically during a build step, some restrictions - * are applied with respect to how minErr instances are created and called. - * Instances should have names of the form namespaceMinErr for a minErr created - * using minErr('namespace') . Error codes, namespaces and template strings - * should all be static strings, not variables or general expressions. - * - * @param {string} module The namespace to use for the new minErr instance. - * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning - * error from returned function, for cases when a particular type of error is useful. - * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance - */ - -function minErr(module, ErrorConstructor) { - ErrorConstructor = ErrorConstructor || Error; - return function() { - var SKIP_INDEXES = 2; - - var templateArgs = arguments, - code = templateArgs[0], - message = '[' + (module ? module + ':' : '') + code + '] ', - template = templateArgs[1], - paramPrefix, i; - - message += template.replace(/\{\d+\}/g, function(match) { - var index = +match.slice(1, -1), - shiftedIndex = index + SKIP_INDEXES; - - if (shiftedIndex < templateArgs.length) { - return toDebugString(templateArgs[shiftedIndex]); - } - - return match; - }); - - message += '\nhttp://errors.angularjs.org/1.5.0/' + - (module ? module + '/' : '') + code; - - for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') { - message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' + - encodeURIComponent(toDebugString(templateArgs[i])); - } - - return new ErrorConstructor(message); - }; -} - -/** - * @ngdoc type - * @name angular.Module - * @module ng - * @description - * - * Interface for configuring angular {@link angular.module modules}. - */ - -function setupModuleLoader(window) { - - var $injectorMinErr = minErr('$injector'); - var ngMinErr = minErr('ng'); - - function ensure(obj, name, factory) { - return obj[name] || (obj[name] = factory()); - } - - var angular = ensure(window, 'angular', Object); - - // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap - angular.$$minErr = angular.$$minErr || minErr; - - return ensure(angular, 'module', function() { - /** @type {Object.} */ - var modules = {}; - - /** - * @ngdoc function - * @name angular.module - * @module ng - * @description - * - * The `angular.module` is a global place for creating, registering and retrieving Angular - * modules. - * All modules (angular core or 3rd party) that should be available to an application must be - * registered using this mechanism. - * - * Passing one argument retrieves an existing {@link angular.Module}, - * whereas passing more than one argument creates a new {@link angular.Module} - * - * - * # Module - * - * A module is a collection of services, directives, controllers, filters, and configuration information. - * `angular.module` is used to configure the {@link auto.$injector $injector}. - * - * ```js - * // Create a new module - * var myModule = angular.module('myModule', []); - * - * // register a new service - * myModule.value('appName', 'MyCoolApp'); - * - * // configure existing services inside initialization blocks. - * myModule.config(['$locationProvider', function($locationProvider) { - * // Configure existing providers - * $locationProvider.hashPrefix('!'); - * }]); - * ``` - * - * Then you can create an injector and load your modules like this: - * - * ```js - * var injector = angular.injector(['ng', 'myModule']) - * ``` - * - * However it's more likely that you'll just use - * {@link ng.directive:ngApp ngApp} or - * {@link angular.bootstrap} to simplify this process for you. - * - * @param {!string} name The name of the module to create or retrieve. - * @param {!Array.=} requires If specified then new module is being created. If - * unspecified then the module is being retrieved for further configuration. - * @param {Function=} configFn Optional configuration function for the module. Same as - * {@link angular.Module#config Module#config()}. - * @returns {angular.Module} new module with the {@link angular.Module} api. - */ - return function module(name, requires, configFn) { - var assertNotHasOwnProperty = function(name, context) { - if (name === 'hasOwnProperty') { - throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); - } - }; - - assertNotHasOwnProperty(name, 'module'); - if (requires && modules.hasOwnProperty(name)) { - modules[name] = null; - } - return ensure(modules, name, function() { - if (!requires) { - throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + - "the module name or forgot to load it. If registering a module ensure that you " + - "specify the dependencies as the second argument.", name); - } - - /** @type {!Array.>} */ - var invokeQueue = []; - - /** @type {!Array.} */ - var configBlocks = []; - - /** @type {!Array.} */ - var runBlocks = []; - - var config = invokeLater('$injector', 'invoke', 'push', configBlocks); - - /** @type {angular.Module} */ - var moduleInstance = { - // Private state - _invokeQueue: invokeQueue, - _configBlocks: configBlocks, - _runBlocks: runBlocks, - - /** - * @ngdoc property - * @name angular.Module#requires - * @module ng - * - * @description - * Holds the list of modules which the injector will load before the current module is - * loaded. - */ - requires: requires, - - /** - * @ngdoc property - * @name angular.Module#name - * @module ng - * - * @description - * Name of the module. - */ - name: name, - - - /** - * @ngdoc method - * @name angular.Module#provider - * @module ng - * @param {string} name service name - * @param {Function} providerType Construction function for creating new instance of the - * service. - * @description - * See {@link auto.$provide#provider $provide.provider()}. - */ - provider: invokeLaterAndSetModuleName('$provide', 'provider'), - - /** - * @ngdoc method - * @name angular.Module#factory - * @module ng - * @param {string} name service name - * @param {Function} providerFunction Function for creating new instance of the service. - * @description - * See {@link auto.$provide#factory $provide.factory()}. - */ - factory: invokeLaterAndSetModuleName('$provide', 'factory'), - - /** - * @ngdoc method - * @name angular.Module#service - * @module ng - * @param {string} name service name - * @param {Function} constructor A constructor function that will be instantiated. - * @description - * See {@link auto.$provide#service $provide.service()}. - */ - service: invokeLaterAndSetModuleName('$provide', 'service'), - - /** - * @ngdoc method - * @name angular.Module#value - * @module ng - * @param {string} name service name - * @param {*} object Service instance object. - * @description - * See {@link auto.$provide#value $provide.value()}. - */ - value: invokeLater('$provide', 'value'), - - /** - * @ngdoc method - * @name angular.Module#constant - * @module ng - * @param {string} name constant name - * @param {*} object Constant value. - * @description - * Because the constants are fixed, they get applied before other provide methods. - * See {@link auto.$provide#constant $provide.constant()}. - */ - constant: invokeLater('$provide', 'constant', 'unshift'), - - /** - * @ngdoc method - * @name angular.Module#decorator - * @module ng - * @param {string} The name of the service to decorate. - * @param {Function} This function will be invoked when the service needs to be - * instantiated and should return the decorated service instance. - * @description - * See {@link auto.$provide#decorator $provide.decorator()}. - */ - decorator: invokeLaterAndSetModuleName('$provide', 'decorator'), - - /** - * @ngdoc method - * @name angular.Module#animation - * @module ng - * @param {string} name animation name - * @param {Function} animationFactory Factory function for creating new instance of an - * animation. - * @description - * - * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. - * - * - * Defines an animation hook that can be later used with - * {@link $animate $animate} service and directives that use this service. - * - * ```js - * module.animation('.animation-name', function($inject1, $inject2) { - * return { - * eventName : function(element, done) { - * //code to run the animation - * //once complete, then run done() - * return function cancellationFunction(element) { - * //code to cancel the animation - * } - * } - * } - * }) - * ``` - * - * See {@link ng.$animateProvider#register $animateProvider.register()} and - * {@link ngAnimate ngAnimate module} for more information. - */ - animation: invokeLaterAndSetModuleName('$animateProvider', 'register'), - - /** - * @ngdoc method - * @name angular.Module#filter - * @module ng - * @param {string} name Filter name - this must be a valid angular expression identifier - * @param {Function} filterFactory Factory function for creating new instance of filter. - * @description - * See {@link ng.$filterProvider#register $filterProvider.register()}. - * - *
- * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`. - * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace - * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores - * (`myapp_subsection_filterx`). - *
- */ - filter: invokeLaterAndSetModuleName('$filterProvider', 'register'), - - /** - * @ngdoc method - * @name angular.Module#controller - * @module ng - * @param {string|Object} name Controller name, or an object map of controllers where the - * keys are the names and the values are the constructors. - * @param {Function} constructor Controller constructor function. - * @description - * See {@link ng.$controllerProvider#register $controllerProvider.register()}. - */ - controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'), - - /** - * @ngdoc method - * @name angular.Module#directive - * @module ng - * @param {string|Object} name Directive name, or an object map of directives where the - * keys are the names and the values are the factories. - * @param {Function} directiveFactory Factory function for creating new instance of - * directives. - * @description - * See {@link ng.$compileProvider#directive $compileProvider.directive()}. - */ - directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'), - - /** - * @ngdoc method - * @name angular.Module#component - * @module ng - * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp) - * @param {Object} options Component definition object (a simplified - * {@link ng.$compile#directive-definition-object directive definition object}) - * - * @description - * See {@link ng.$compileProvider#component $compileProvider.component()}. - */ - component: invokeLaterAndSetModuleName('$compileProvider', 'component'), - - /** - * @ngdoc method - * @name angular.Module#config - * @module ng - * @param {Function} configFn Execute this function on module load. Useful for service - * configuration. - * @description - * Use this method to register work which needs to be performed on module loading. - * For more about how to configure services, see - * {@link providers#provider-recipe Provider Recipe}. - */ - config: config, - - /** - * @ngdoc method - * @name angular.Module#run - * @module ng - * @param {Function} initializationFn Execute this function after injector creation. - * Useful for application initialization. - * @description - * Use this method to register work which should be performed when the injector is done - * loading all modules. - */ - run: function(block) { - runBlocks.push(block); - return this; - } - }; - - if (configFn) { - config(configFn); - } - - return moduleInstance; - - /** - * @param {string} provider - * @param {string} method - * @param {String=} insertMethod - * @returns {angular.Module} - */ - function invokeLater(provider, method, insertMethod, queue) { - if (!queue) queue = invokeQueue; - return function() { - queue[insertMethod || 'push']([provider, method, arguments]); - return moduleInstance; - }; - } - - /** - * @param {string} provider - * @param {string} method - * @returns {angular.Module} - */ - function invokeLaterAndSetModuleName(provider, method) { - return function(recipeName, factoryFunction) { - if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name; - invokeQueue.push([provider, method, arguments]); - return moduleInstance; - }; - } - }); - }; - }); - -} - -setupModuleLoader(window); -})(window); - -/** - * Closure compiler type information - * - * @typedef { { - * requires: !Array., - * invokeQueue: !Array.>, - * - * service: function(string, Function):angular.Module, - * factory: function(string, Function):angular.Module, - * value: function(string, *):angular.Module, - * - * filter: function(string, Function):angular.Module, - * - * init: function(Function):angular.Module - * } } - */ -angular.Module; - diff --git a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-loader.min.js b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-loader.min.js deleted file mode 100644 index 316ee26e..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-loader.min.js +++ /dev/null @@ -1,10 +0,0 @@ -/* - AngularJS v1.5.0 - (c) 2010-2016 Google, Inc. http://angularjs.org - License: MIT -*/ -(function(){'use strict';function d(b){return function(){var a=arguments[0],e;e="["+(b?b+":":"")+a+"] http://errors.angularjs.org/1.5.0/"+(b?b+"/":"")+a;for(a=1;a= line.length) { - index -= line.length; - } else { - return { line: i + 1, column: index + 1 }; - } - } -} -var PARSE_CACHE_FOR_TEXT_LITERALS = Object.create(null); - -function parseTextLiteral(text) { - var cachedFn = PARSE_CACHE_FOR_TEXT_LITERALS[text]; - if (cachedFn != null) { - return cachedFn; - } - function parsedFn(context) { return text; } - parsedFn['$$watchDelegate'] = function watchDelegate(scope, listener, objectEquality) { - var unwatch = scope['$watch'](noop, - function textLiteralWatcher() { - if (isFunction(listener)) { listener.call(null, text, text, scope); } - unwatch(); - }, - objectEquality); - return unwatch; - }; - PARSE_CACHE_FOR_TEXT_LITERALS[text] = parsedFn; - parsedFn['exp'] = text; // Needed to pretend to be $interpolate for tests copied from interpolateSpec.js - parsedFn['expressions'] = []; // Require this to call $compile.$$addBindingInfo() which allows Protractor to find elements by binding. - return parsedFn; -} - -function subtractOffset(expressionFn, offset) { - if (offset === 0) { - return expressionFn; - } - function minusOffset(value) { - return (value == void 0) ? value : value - offset; - } - function parsedFn(context) { return minusOffset(expressionFn(context)); } - var unwatch; - parsedFn['$$watchDelegate'] = function watchDelegate(scope, listener, objectEquality) { - unwatch = scope['$watch'](expressionFn, - function pluralExpressionWatchListener(newValue, oldValue) { - if (isFunction(listener)) { listener.call(null, minusOffset(newValue), minusOffset(oldValue), scope); } - }, - objectEquality); - return unwatch; - }; - return parsedFn; -} - -// NOTE: ADVANCED_OPTIMIZATIONS mode. -// -// This file is compiled with Closure compiler's ADVANCED_OPTIMIZATIONS flag! Be wary of using -// constructs incompatible with that mode. - -/* global $interpolateMinErr: false */ -/* global isFunction: false */ -/* global noop: false */ - -/** - * @constructor - * @private - */ -function MessageSelectorBase(expressionFn, choices) { - var self = this; - this.expressionFn = expressionFn; - this.choices = choices; - if (choices["other"] === void 0) { - throw $interpolateMinErr('reqother', '“other” is a required option.'); - } - this.parsedFn = function(context) { return self.getResult(context); }; - this.parsedFn['$$watchDelegate'] = function $$watchDelegate(scope, listener, objectEquality) { - return self.watchDelegate(scope, listener, objectEquality); - }; - this.parsedFn['exp'] = expressionFn['exp']; - this.parsedFn['expressions'] = expressionFn['expressions']; -} - -MessageSelectorBase.prototype.getMessageFn = function getMessageFn(value) { - return this.choices[this.categorizeValue(value)]; -}; - -MessageSelectorBase.prototype.getResult = function getResult(context) { - return this.getMessageFn(this.expressionFn(context))(context); -}; - -MessageSelectorBase.prototype.watchDelegate = function watchDelegate(scope, listener, objectEquality) { - var watchers = new MessageSelectorWatchers(this, scope, listener, objectEquality); - return function() { watchers.cancelWatch(); }; -}; - -/** - * @constructor - * @private - */ -function MessageSelectorWatchers(msgSelector, scope, listener, objectEquality) { - var self = this; - this.scope = scope; - this.msgSelector = msgSelector; - this.listener = listener; - this.objectEquality = objectEquality; - this.lastMessage = void 0; - this.messageFnWatcher = noop; - var expressionFnListener = function(newValue, oldValue) { return self.expressionFnListener(newValue, oldValue); }; - this.expressionFnWatcher = scope['$watch'](msgSelector.expressionFn, expressionFnListener, objectEquality); -} - -MessageSelectorWatchers.prototype.expressionFnListener = function expressionFnListener(newValue, oldValue) { - var self = this; - this.messageFnWatcher(); - var messageFnListener = function(newMessage, oldMessage) { return self.messageFnListener(newMessage, oldMessage); }; - var messageFn = this.msgSelector.getMessageFn(newValue); - this.messageFnWatcher = this.scope['$watch'](messageFn, messageFnListener, this.objectEquality); -}; - -MessageSelectorWatchers.prototype.messageFnListener = function messageFnListener(newMessage, oldMessage) { - if (isFunction(this.listener)) { - this.listener.call(null, newMessage, newMessage === oldMessage ? newMessage : this.lastMessage, this.scope); - } - this.lastMessage = newMessage; -}; - -MessageSelectorWatchers.prototype.cancelWatch = function cancelWatch() { - this.expressionFnWatcher(); - this.messageFnWatcher(); -}; - -/** - * @constructor - * @extends MessageSelectorBase - * @private - */ -function SelectMessage(expressionFn, choices) { - MessageSelectorBase.call(this, expressionFn, choices); -} - -function SelectMessageProto() {} -SelectMessageProto.prototype = MessageSelectorBase.prototype; - -SelectMessage.prototype = new SelectMessageProto(); -SelectMessage.prototype.categorizeValue = function categorizeSelectValue(value) { - return (this.choices[value] !== void 0) ? value : "other"; -}; - -/** - * @constructor - * @extends MessageSelectorBase - * @private - */ -function PluralMessage(expressionFn, choices, offset, pluralCat) { - MessageSelectorBase.call(this, expressionFn, choices); - this.offset = offset; - this.pluralCat = pluralCat; -} - -function PluralMessageProto() {} -PluralMessageProto.prototype = MessageSelectorBase.prototype; - -PluralMessage.prototype = new PluralMessageProto(); -PluralMessage.prototype.categorizeValue = function categorizePluralValue(value) { - if (isNaN(value)) { - return "other"; - } else if (this.choices[value] !== void 0) { - return value; - } else { - var category = this.pluralCat(value - this.offset); - return (this.choices[category] !== void 0) ? category : "other"; - } -}; - -// NOTE: ADVANCED_OPTIMIZATIONS mode. -// -// This file is compiled with Closure compiler's ADVANCED_OPTIMIZATIONS flag! Be wary of using -// constructs incompatible with that mode. - -/* global $interpolateMinErr: false */ -/* global isFunction: false */ -/* global parseTextLiteral: false */ - -/** - * @constructor - * @private - */ -function InterpolationParts(trustedContext, allOrNothing) { - this.trustedContext = trustedContext; - this.allOrNothing = allOrNothing; - this.textParts = []; - this.expressionFns = []; - this.expressionIndices = []; - this.partialText = ''; - this.concatParts = null; -} - -InterpolationParts.prototype.flushPartialText = function flushPartialText() { - if (this.partialText) { - if (this.concatParts == null) { - this.textParts.push(this.partialText); - } else { - this.textParts.push(this.concatParts.join('')); - this.concatParts = null; - } - this.partialText = ''; - } -}; - -InterpolationParts.prototype.addText = function addText(text) { - if (text.length) { - if (!this.partialText) { - this.partialText = text; - } else if (this.concatParts) { - this.concatParts.push(text); - } else { - this.concatParts = [this.partialText, text]; - } - } -}; - -InterpolationParts.prototype.addExpressionFn = function addExpressionFn(expressionFn) { - this.flushPartialText(); - this.expressionIndices.push(this.textParts.length); - this.expressionFns.push(expressionFn); - this.textParts.push(''); -}; - -InterpolationParts.prototype.getExpressionValues = function getExpressionValues(context) { - var expressionValues = new Array(this.expressionFns.length); - for (var i = 0; i < this.expressionFns.length; i++) { - expressionValues[i] = this.expressionFns[i](context); - } - return expressionValues; -}; - -InterpolationParts.prototype.getResult = function getResult(expressionValues) { - for (var i = 0; i < this.expressionIndices.length; i++) { - var expressionValue = expressionValues[i]; - if (this.allOrNothing && expressionValue === void 0) return; - this.textParts[this.expressionIndices[i]] = expressionValue; - } - return this.textParts.join(''); -}; - - -InterpolationParts.prototype.toParsedFn = function toParsedFn(mustHaveExpression, originalText) { - var self = this; - this.flushPartialText(); - if (mustHaveExpression && this.expressionFns.length === 0) { - return void 0; - } - if (this.textParts.length === 0) { - return parseTextLiteral(''); - } - if (this.trustedContext && this.textParts.length > 1) { - $interpolateMinErr['throwNoconcat'](originalText); - } - if (this.expressionFns.length === 0) { - if (this.textParts.length != 1) { this.errorInParseLogic(); } - return parseTextLiteral(this.textParts[0]); - } - var parsedFn = function(context) { - return self.getResult(self.getExpressionValues(context)); - }; - parsedFn['$$watchDelegate'] = function $$watchDelegate(scope, listener, objectEquality) { - return self.watchDelegate(scope, listener, objectEquality); - }; - - parsedFn['exp'] = originalText; // Needed to pretend to be $interpolate for tests copied from interpolateSpec.js - parsedFn['expressions'] = new Array(this.expressionFns.length); // Require this to call $compile.$$addBindingInfo() which allows Protractor to find elements by binding. - for (var i = 0; i < this.expressionFns.length; i++) { - parsedFn['expressions'][i] = this.expressionFns[i]['exp']; - } - - return parsedFn; -}; - -InterpolationParts.prototype.watchDelegate = function watchDelegate(scope, listener, objectEquality) { - var watcher = new InterpolationPartsWatcher(this, scope, listener, objectEquality); - return function() { watcher.cancelWatch(); }; -}; - -function InterpolationPartsWatcher(interpolationParts, scope, listener, objectEquality) { - this.interpolationParts = interpolationParts; - this.scope = scope; - this.previousResult = (void 0); - this.listener = listener; - var self = this; - this.expressionFnsWatcher = scope['$watchGroup'](interpolationParts.expressionFns, function(newExpressionValues, oldExpressionValues) { - self.watchListener(newExpressionValues, oldExpressionValues); - }); -} - -InterpolationPartsWatcher.prototype.watchListener = function watchListener(newExpressionValues, oldExpressionValues) { - var result = this.interpolationParts.getResult(newExpressionValues); - if (isFunction(this.listener)) { - this.listener.call(null, result, newExpressionValues === oldExpressionValues ? result : this.previousResult, this.scope); - } - this.previousResult = result; -}; - -InterpolationPartsWatcher.prototype.cancelWatch = function cancelWatch() { - this.expressionFnsWatcher(); -}; - -// NOTE: ADVANCED_OPTIMIZATIONS mode. -// -// This file is compiled with Closure compiler's ADVANCED_OPTIMIZATIONS flag! Be wary of using -// constructs incompatible with that mode. - -/* global $interpolateMinErr: false */ -/* global indexToLineAndColumn: false */ -/* global InterpolationParts: false */ -/* global PluralMessage: false */ -/* global SelectMessage: false */ -/* global subtractOffset: false */ - -// The params src and dst are exactly one of two types: NestedParserState or MessageFormatParser. -// This function is fully optimized by V8. (inspect via IRHydra or --trace-deopt.) -// The idea behind writing it this way is to avoid repeating oneself. This is the ONE place where -// the parser state that is saved/restored when parsing nested mustaches is specified. -function copyNestedParserState(src, dst) { - dst.expressionFn = src.expressionFn; - dst.expressionMinusOffsetFn = src.expressionMinusOffsetFn; - dst.pluralOffset = src.pluralOffset; - dst.choices = src.choices; - dst.choiceKey = src.choiceKey; - dst.interpolationParts = src.interpolationParts; - dst.ruleChoiceKeyword = src.ruleChoiceKeyword; - dst.msgStartIndex = src.msgStartIndex; - dst.expressionStartIndex = src.expressionStartIndex; -} - -function NestedParserState(parser) { - copyNestedParserState(parser, this); -} - -/** - * @constructor - * @private - */ -function MessageFormatParser(text, startIndex, $parse, pluralCat, stringifier, - mustHaveExpression, trustedContext, allOrNothing) { - this.text = text; - this.index = startIndex || 0; - this.$parse = $parse; - this.pluralCat = pluralCat; - this.stringifier = stringifier; - this.mustHaveExpression = !!mustHaveExpression; - this.trustedContext = trustedContext; - this.allOrNothing = !!allOrNothing; - this.expressionFn = null; - this.expressionMinusOffsetFn = null; - this.pluralOffset = null; - this.choices = null; - this.choiceKey = null; - this.interpolationParts = null; - this.msgStartIndex = null; - this.nestedStateStack = []; - this.parsedFn = null; - this.rule = null; - this.ruleStack = null; - this.ruleChoiceKeyword = null; - this.interpNestLevel = null; - this.expressionStartIndex = null; - this.stringStartIndex = null; - this.stringQuote = null; - this.stringInterestsRe = null; - this.angularOperatorStack = null; - this.textPart = null; -} - -// preserve v8 optimization. -var EMPTY_STATE = new NestedParserState(new MessageFormatParser( - /* text= */ '', /* startIndex= */ 0, /* $parse= */ null, /* pluralCat= */ null, /* stringifier= */ null, - /* mustHaveExpression= */ false, /* trustedContext= */ null, /* allOrNothing */ false)); - -MessageFormatParser.prototype.pushState = function pushState() { - this.nestedStateStack.push(new NestedParserState(this)); - copyNestedParserState(EMPTY_STATE, this); -}; - -MessageFormatParser.prototype.popState = function popState() { - if (this.nestedStateStack.length === 0) { - this.errorInParseLogic(); - } - var previousState = this.nestedStateStack.pop(); - copyNestedParserState(previousState, this); -}; - -// Oh my JavaScript! Who knew you couldn't match a regex at a specific -// location in a string but will always search forward?! -// Apparently you'll be growing this ability via the sticky flag (y) in -// ES6. I'll just to work around you for now. -MessageFormatParser.prototype.matchRe = function matchRe(re, search) { - re.lastIndex = this.index; - var match = re.exec(this.text); - if (match != null && (search === true || (match.index == this.index))) { - this.index = re.lastIndex; - return match; - } - return null; -}; - -MessageFormatParser.prototype.searchRe = function searchRe(re) { - return this.matchRe(re, true); -}; - - -MessageFormatParser.prototype.consumeRe = function consumeRe(re) { - // Without the sticky flag, we can't use the .test() method to consume a - // match at the current index. Instead, we'll use the slower .exec() method - // and verify match.index. - return !!this.matchRe(re); -}; - -// Run through our grammar avoiding deeply nested function call chains. -MessageFormatParser.prototype.run = function run(initialRule) { - this.ruleStack = [initialRule]; - do { - this.rule = this.ruleStack.pop(); - while (this.rule) { - this.rule(); - } - this.assertRuleOrNull(this.rule); - } while (this.ruleStack.length > 0); -}; - -MessageFormatParser.prototype.errorInParseLogic = function errorInParseLogic() { - throw $interpolateMinErr('logicbug', - 'The messageformat parser has encountered an internal error. Please file a github issue against the AngularJS project and provide this message text that triggers the bug. Text: “{0}”', - this.text); -}; - -MessageFormatParser.prototype.assertRuleOrNull = function assertRuleOrNull(rule) { - if (rule === void 0) { - this.errorInParseLogic(); - } -}; - -var NEXT_WORD_RE = /\s*(\w+)\s*/g; -MessageFormatParser.prototype.errorExpecting = function errorExpecting() { - // What was wrong with the syntax? Unsupported type, missing comma, or something else? - var match = this.matchRe(NEXT_WORD_RE), position; - if (match == null) { - position = indexToLineAndColumn(this.text, this.index); - throw $interpolateMinErr('reqarg', - 'Expected one of “plural” or “select” at line {0}, column {1} of text “{2}”', - position.line, position.column, this.text); - } - var word = match[1]; - if (word == "select" || word == "plural") { - position = indexToLineAndColumn(this.text, this.index); - throw $interpolateMinErr('reqcomma', - 'Expected a comma after the keyword “{0}” at line {1}, column {2} of text “{3}”', - word, position.line, position.column, this.text); - } else { - position = indexToLineAndColumn(this.text, this.index); - throw $interpolateMinErr('unknarg', - 'Unsupported keyword “{0}” at line {0}, column {1}. Only “plural” and “select” are currently supported. Text: “{3}”', - word, position.line, position.column, this.text); - } -}; - -var STRING_START_RE = /['"]/g; -MessageFormatParser.prototype.ruleString = function ruleString() { - var match = this.matchRe(STRING_START_RE); - if (match == null) { - var position = indexToLineAndColumn(this.text, this.index); - throw $interpolateMinErr('wantstring', - 'Expected the beginning of a string at line {0}, column {1} in text “{2}”', - position.line, position.column, this.text); - } - this.startStringAtMatch(match); -}; - -MessageFormatParser.prototype.startStringAtMatch = function startStringAtMatch(match) { - this.stringStartIndex = match.index; - this.stringQuote = match[0]; - this.stringInterestsRe = this.stringQuote == "'" ? SQUOTED_STRING_INTEREST_RE : DQUOTED_STRING_INTEREST_RE; - this.rule = this.ruleInsideString; -}; - -var SQUOTED_STRING_INTEREST_RE = /\\(?:\\|'|u[0-9A-Fa-f]{4}|x[0-9A-Fa-f]{2}|[0-7]{3}|\r\n|\n|[\s\S])|'/g; -var DQUOTED_STRING_INTEREST_RE = /\\(?:\\|"|u[0-9A-Fa-f]{4}|x[0-9A-Fa-f]{2}|[0-7]{3}|\r\n|\n|[\s\S])|"/g; -MessageFormatParser.prototype.ruleInsideString = function ruleInsideString() { - var match = this.searchRe(this.stringInterestsRe); - if (match == null) { - var position = indexToLineAndColumn(this.text, this.stringStartIndex); - throw $interpolateMinErr('untermstr', - 'The string beginning at line {0}, column {1} is unterminated in text “{2}”', - position.line, position.column, this.text); - } - var chars = match[0]; - if (match == this.stringQuote) { - this.rule = null; - } -}; - -var PLURAL_OR_SELECT_ARG_TYPE_RE = /\s*(plural|select)\s*,\s*/g; -MessageFormatParser.prototype.rulePluralOrSelect = function rulePluralOrSelect() { - var match = this.searchRe(PLURAL_OR_SELECT_ARG_TYPE_RE); - if (match == null) { - this.errorExpecting(); - } - var argType = match[1]; - switch (argType) { - case "plural": this.rule = this.rulePluralStyle; break; - case "select": this.rule = this.ruleSelectStyle; break; - default: this.errorInParseLogic(); - } -}; - -MessageFormatParser.prototype.rulePluralStyle = function rulePluralStyle() { - this.choices = Object.create(null); - this.ruleChoiceKeyword = this.rulePluralValueOrKeyword; - this.rule = this.rulePluralOffset; -}; - -MessageFormatParser.prototype.ruleSelectStyle = function ruleSelectStyle() { - this.choices = Object.create(null); - this.ruleChoiceKeyword = this.ruleSelectKeyword; - this.rule = this.ruleSelectKeyword; -}; - -var NUMBER_RE = /[0]|(?:[1-9][0-9]*)/g; -var PLURAL_OFFSET_RE = new RegExp("\\s*offset\\s*:\\s*(" + NUMBER_RE.source + ")", "g"); - -MessageFormatParser.prototype.rulePluralOffset = function rulePluralOffset() { - var match = this.matchRe(PLURAL_OFFSET_RE); - this.pluralOffset = (match == null) ? 0 : parseInt(match[1], 10); - this.expressionMinusOffsetFn = subtractOffset(this.expressionFn, this.pluralOffset); - this.rule = this.rulePluralValueOrKeyword; -}; - -MessageFormatParser.prototype.assertChoiceKeyIsNew = function assertChoiceKeyIsNew(choiceKey, index) { - if (this.choices[choiceKey] !== void 0) { - var position = indexToLineAndColumn(this.text, index); - throw $interpolateMinErr('dupvalue', - 'The choice “{0}” is specified more than once. Duplicate key is at line {1}, column {2} in text “{3}”', - choiceKey, position.line, position.column, this.text); - } -}; - -var SELECT_KEYWORD = /\s*(\w+)/g; -MessageFormatParser.prototype.ruleSelectKeyword = function ruleSelectKeyword() { - var match = this.matchRe(SELECT_KEYWORD); - if (match == null) { - this.parsedFn = new SelectMessage(this.expressionFn, this.choices).parsedFn; - this.rule = null; - return; - } - this.choiceKey = match[1]; - this.assertChoiceKeyIsNew(this.choiceKey, match.index); - this.rule = this.ruleMessageText; -}; - -var EXPLICIT_VALUE_OR_KEYWORD_RE = new RegExp("\\s*(?:(?:=(" + NUMBER_RE.source + "))|(\\w+))", "g"); -MessageFormatParser.prototype.rulePluralValueOrKeyword = function rulePluralValueOrKeyword() { - var match = this.matchRe(EXPLICIT_VALUE_OR_KEYWORD_RE); - if (match == null) { - this.parsedFn = new PluralMessage(this.expressionFn, this.choices, this.pluralOffset, this.pluralCat).parsedFn; - this.rule = null; - return; - } - if (match[1] != null) { - this.choiceKey = parseInt(match[1], 10); - } else { - this.choiceKey = match[2]; - } - this.assertChoiceKeyIsNew(this.choiceKey, match.index); - this.rule = this.ruleMessageText; -}; - -var BRACE_OPEN_RE = /\s*{/g; -var BRACE_CLOSE_RE = /}/g; -MessageFormatParser.prototype.ruleMessageText = function ruleMessageText() { - if (!this.consumeRe(BRACE_OPEN_RE)) { - var position = indexToLineAndColumn(this.text, this.index); - throw $interpolateMinErr('reqopenbrace', - 'The plural choice “{0}” must be followed by a message in braces at line {1}, column {2} in text “{3}”', - this.choiceKey, position.line, position.column, this.text); - } - this.msgStartIndex = this.index; - this.interpolationParts = new InterpolationParts(this.trustedContext, this.allOrNothing); - this.rule = this.ruleInInterpolationOrMessageText; -}; - -// Note: Since "\" is used as an escape character, don't allow it to be part of the -// startSymbol/endSymbol when I add the feature to allow them to be redefined. -var INTERP_OR_END_MESSAGE_RE = /\\.|{{|}/g; -var INTERP_OR_PLURALVALUE_OR_END_MESSAGE_RE = /\\.|{{|#|}/g; -var ESCAPE_OR_MUSTACHE_BEGIN_RE = /\\.|{{/g; -MessageFormatParser.prototype.advanceInInterpolationOrMessageText = function advanceInInterpolationOrMessageText() { - var currentIndex = this.index, match, re; - if (this.ruleChoiceKeyword == null) { // interpolation - match = this.searchRe(ESCAPE_OR_MUSTACHE_BEGIN_RE); - if (match == null) { // End of interpolation text. Nothing more to process. - this.textPart = this.text.substring(currentIndex); - this.index = this.text.length; - return null; - } - } else { - match = this.searchRe(this.ruleChoiceKeyword == this.rulePluralValueOrKeyword ? - INTERP_OR_PLURALVALUE_OR_END_MESSAGE_RE : INTERP_OR_END_MESSAGE_RE); - if (match == null) { - var position = indexToLineAndColumn(this.text, this.msgStartIndex); - throw $interpolateMinErr('reqendbrace', - 'The plural/select choice “{0}” message starting at line {1}, column {2} does not have an ending closing brace. Text “{3}”', - this.choiceKey, position.line, position.column, this.text); - } - } - // match is non-null. - var token = match[0]; - this.textPart = this.text.substring(currentIndex, match.index); - return token; -}; - -MessageFormatParser.prototype.ruleInInterpolationOrMessageText = function ruleInInterpolationOrMessageText() { - var currentIndex = this.index; - var token = this.advanceInInterpolationOrMessageText(); - if (token == null) { - // End of interpolation text. Nothing more to process. - this.index = this.text.length; - this.interpolationParts.addText(this.text.substring(currentIndex)); - this.rule = null; - return; - } - if (token[0] == "\\") { - // unescape next character and continue - this.interpolationParts.addText(this.textPart + token[1]); - return; - } - this.interpolationParts.addText(this.textPart); - if (token == "{{") { - this.pushState(); - this.ruleStack.push(this.ruleEndMustacheInInterpolationOrMessage); - this.rule = this.ruleEnteredMustache; - } else if (token == "}") { - this.choices[this.choiceKey] = this.interpolationParts.toParsedFn(/*mustHaveExpression=*/false, this.text); - this.rule = this.ruleChoiceKeyword; - } else if (token == "#") { - this.interpolationParts.addExpressionFn(this.expressionMinusOffsetFn); - } else { - this.errorInParseLogic(); - } -}; - -MessageFormatParser.prototype.ruleInterpolate = function ruleInterpolate() { - this.interpolationParts = new InterpolationParts(this.trustedContext, this.allOrNothing); - this.rule = this.ruleInInterpolation; -}; - -MessageFormatParser.prototype.ruleInInterpolation = function ruleInInterpolation() { - var currentIndex = this.index; - var match = this.searchRe(ESCAPE_OR_MUSTACHE_BEGIN_RE); - if (match == null) { - // End of interpolation text. Nothing more to process. - this.index = this.text.length; - this.interpolationParts.addText(this.text.substring(currentIndex)); - this.parsedFn = this.interpolationParts.toParsedFn(this.mustHaveExpression, this.text); - this.rule = null; - return; - } - var token = match[0]; - if (token[0] == "\\") { - // unescape next character and continue - this.interpolationParts.addText(this.text.substring(currentIndex, match.index) + token[1]); - return; - } - this.interpolationParts.addText(this.text.substring(currentIndex, match.index)); - this.pushState(); - this.ruleStack.push(this.ruleInterpolationEndMustache); - this.rule = this.ruleEnteredMustache; -}; - -MessageFormatParser.prototype.ruleInterpolationEndMustache = function ruleInterpolationEndMustache() { - var expressionFn = this.parsedFn; - this.popState(); - this.interpolationParts.addExpressionFn(expressionFn); - this.rule = this.ruleInInterpolation; -}; - -MessageFormatParser.prototype.ruleEnteredMustache = function ruleEnteredMustache() { - this.parsedFn = null; - this.ruleStack.push(this.ruleEndMustache); - this.rule = this.ruleAngularExpression; -}; - -MessageFormatParser.prototype.ruleEndMustacheInInterpolationOrMessage = function ruleEndMustacheInInterpolationOrMessage() { - var expressionFn = this.parsedFn; - this.popState(); - this.interpolationParts.addExpressionFn(expressionFn); - this.rule = this.ruleInInterpolationOrMessageText; -}; - - - -var INTERP_END_RE = /\s*}}/g; -MessageFormatParser.prototype.ruleEndMustache = function ruleEndMustache() { - var match = this.matchRe(INTERP_END_RE); - if (match == null) { - var position = indexToLineAndColumn(this.text, this.index); - throw $interpolateMinErr('reqendinterp', - 'Expecting end of interpolation symbol, “{0}”, at line {1}, column {2} in text “{3}”', - '}}', position.line, position.column, this.text); - } - if (this.parsedFn == null) { - // If we parsed a MessageFormat extension, (e.g. select/plural today, maybe more some other - // day), then the result *has* to be a string and those rules would have already set - // this.parsedFn. If there was no MessageFormat extension, then there is no requirement to - // stringify the result and parsedFn isn't set. We set it here. While we could have set it - // unconditionally when exiting the Angular expression, I intend for us to not just replace - // $interpolate, but also to replace $parse in a future version (so ng-bind can work), and in - // such a case we do not want to unnecessarily stringify something if it's not going to be used - // in a string context. - this.parsedFn = this.$parse(this.expressionFn, this.stringifier); - this.parsedFn['exp'] = this.expressionFn['exp']; // Needed to pretend to be $interpolate for tests copied from interpolateSpec.js - this.parsedFn['expressions'] = this.expressionFn['expressions']; // Require this to call $compile.$$addBindingInfo() which allows Protractor to find elements by binding. - } - this.rule = null; -}; - -MessageFormatParser.prototype.ruleAngularExpression = function ruleAngularExpression() { - this.angularOperatorStack = []; - this.expressionStartIndex = this.index; - this.rule = this.ruleInAngularExpression; -}; - -function getEndOperator(opBegin) { - switch (opBegin) { - case "{": return "}"; - case "[": return "]"; - case "(": return ")"; - default: return null; - } -} - -function getBeginOperator(opEnd) { - switch (opEnd) { - case "}": return "{"; - case "]": return "["; - case ")": return "("; - default: return null; - } -} - -// TODO(chirayu): The interpolation endSymbol must also be accounted for. It -// just so happens that "}" is an operator so it's in the list below. But we -// should support any other type of start/end interpolation symbol. -var INTERESTING_OPERATORS_RE = /[[\]{}()'",]/g; -MessageFormatParser.prototype.ruleInAngularExpression = function ruleInAngularExpression() { - var startIndex = this.index; - var match = this.searchRe(INTERESTING_OPERATORS_RE); - var position; - if (match == null) { - if (this.angularOperatorStack.length === 0) { - // This is the end of the Angular expression so this is actually a - // success. Note that when inside an interpolation, this means we even - // consumed the closing interpolation symbols if they were curlies. This - // is NOT an error at this point but will become an error further up the - // stack when the part that saw the opening curlies is unable to find the - // closing ones. - this.index = this.text.length; - this.expressionFn = this.$parse(this.text.substring(this.expressionStartIndex, this.index)); - // Needed to pretend to be $interpolate for tests copied from interpolateSpec.js - this.expressionFn['exp'] = this.text.substring(this.expressionStartIndex, this.index); - this.expressionFn['expressions'] = this.expressionFn['expressions']; - this.rule = null; - return; - } - var innermostOperator = this.angularOperatorStack[0]; - throw $interpolateMinErr('badexpr', - 'Unexpected end of Angular expression. Expecting operator “{0}” at the end of the text “{1}”', - this.getEndOperator(innermostOperator), this.text); - } - var operator = match[0]; - if (operator == "'" || operator == '"') { - this.ruleStack.push(this.ruleInAngularExpression); - this.startStringAtMatch(match); - return; - } - if (operator == ",") { - if (this.trustedContext) { - position = indexToLineAndColumn(this.text, this.index); - throw $interpolateMinErr('unsafe', - 'Use of select/plural MessageFormat syntax is currently disallowed in a secure context ({0}). At line {1}, column {2} of text “{3}”', - this.trustedContext, position.line, position.column, this.text); - } - // only the top level comma has relevance. - if (this.angularOperatorStack.length === 0) { - // todo: does this need to be trimmed? - this.expressionFn = this.$parse(this.text.substring(this.expressionStartIndex, match.index)); - // Needed to pretend to be $interpolate for tests copied from interpolateSpec.js - this.expressionFn['exp'] = this.text.substring(this.expressionStartIndex, match.index); - this.expressionFn['expressions'] = this.expressionFn['expressions']; - this.rule = null; - this.rule = this.rulePluralOrSelect; - } - return; - } - if (getEndOperator(operator) != null) { - this.angularOperatorStack.unshift(operator); - return; - } - var beginOperator = getBeginOperator(operator); - if (beginOperator == null) { - this.errorInParseLogic(); - } - if (this.angularOperatorStack.length > 0) { - if (beginOperator == this.angularOperatorStack[0]) { - this.angularOperatorStack.shift(); - return; - } - position = indexToLineAndColumn(this.text, this.index); - throw $interpolateMinErr('badexpr', - 'Unexpected operator “{0}” at line {1}, column {2} in text. Was expecting “{3}”. Text: “{4}”', - operator, position.line, position.column, getEndOperator(this.angularOperatorStack[0]), this.text); - } - // We are trying to pop off the operator stack but there really isn't anything to pop off. - this.index = match.index; - this.expressionFn = this.$parse(this.text.substring(this.expressionStartIndex, this.index)); - // Needed to pretend to be $interpolate for tests copied from interpolateSpec.js - this.expressionFn['exp'] = this.text.substring(this.expressionStartIndex, this.index); - this.expressionFn['expressions'] = this.expressionFn['expressions']; - this.rule = null; -}; - -// NOTE: ADVANCED_OPTIMIZATIONS mode. -// -// This file is compiled with Closure compiler's ADVANCED_OPTIMIZATIONS flag! Be wary of using -// constructs incompatible with that mode. - -/* global $interpolateMinErr: false */ -/* global MessageFormatParser: false */ -/* global stringify: false */ - -/** - * @ngdoc service - * @name $$messageFormat - * - * @description - * Angular internal service to recognize MessageFormat extensions in interpolation expressions. - * For more information, see: - * https://docs.google.com/a/google.com/document/d/1pbtW2yvtmFBikfRrJd8VAsabiFkKezmYZ_PbgdjQOVU/edit - * - * ## Example - * - * - * - *
- *
- * {{recipients.length, plural, offset:1 - * =0 {{{sender.name}} gave no gifts (\#=#)} - * =1 {{{sender.name}} gave one gift to {{recipients[0].name}} (\#=#)} - * one {{{sender.name}} gave {{recipients[0].name}} and one other person a gift (\#=#)} - * other {{{sender.name}} gave {{recipients[0].name}} and # other people a gift (\#=#)} - * }} - *
- *
- * - * - * function Person(name, gender) { - * this.name = name; - * this.gender = gender; - * } - * - * var alice = new Person("Alice", "female"), - * bob = new Person("Bob", "male"), - * charlie = new Person("Charlie", "male"), - * harry = new Person("Harry Potter", "male"); - * - * angular.module('msgFmtExample', ['ngMessageFormat']) - * .controller('AppController', ['$scope', function($scope) { - * $scope.recipients = [alice, bob, charlie]; - * $scope.sender = harry; - * $scope.decreaseRecipients = function() { - * --$scope.recipients.length; - * }; - * }]); - * - * - * - * describe('MessageFormat plural', function() { - * it('should pluralize initial values', function() { - * var messageElem = element(by.binding('recipients.length')), decreaseRecipientsBtn = element(by.id('decreaseRecipients')); - * expect(messageElem.getText()).toEqual('Harry Potter gave Alice and 2 other people a gift (#=2)'); - * decreaseRecipientsBtn.click(); - * expect(messageElem.getText()).toEqual('Harry Potter gave Alice and one other person a gift (#=1)'); - * decreaseRecipientsBtn.click(); - * expect(messageElem.getText()).toEqual('Harry Potter gave one gift to Alice (#=0)'); - * decreaseRecipientsBtn.click(); - * expect(messageElem.getText()).toEqual('Harry Potter gave no gifts (#=-1)'); - * }); - * }); - * - *
- */ -var $$MessageFormatFactory = ['$parse', '$locale', '$sce', '$exceptionHandler', function $$messageFormat( - $parse, $locale, $sce, $exceptionHandler) { - - function getStringifier(trustedContext, allOrNothing, text) { - return function stringifier(value) { - try { - value = trustedContext ? $sce['getTrusted'](trustedContext, value) : $sce['valueOf'](value); - return allOrNothing && (value === void 0) ? value : stringify(value); - } catch (err) { - $exceptionHandler($interpolateMinErr['interr'](text, err)); - } - }; - } - - function interpolate(text, mustHaveExpression, trustedContext, allOrNothing) { - var stringifier = getStringifier(trustedContext, allOrNothing, text); - var parser = new MessageFormatParser(text, 0, $parse, $locale['pluralCat'], stringifier, - mustHaveExpression, trustedContext, allOrNothing); - parser.run(parser.ruleInterpolate); - return parser.parsedFn; - } - - return { - 'interpolate': interpolate - }; -}]; - -var $$interpolateDecorator = ['$$messageFormat', '$delegate', function $$interpolateDecorator($$messageFormat, $interpolate) { - if ($interpolate['startSymbol']() != "{{" || $interpolate['endSymbol']() != "}}") { - throw $interpolateMinErr('nochgmustache', 'angular-message-format.js currently does not allow you to use custom start and end symbols for interpolation.'); - } - var interpolate = $$messageFormat['interpolate']; - interpolate['startSymbol'] = $interpolate['startSymbol']; - interpolate['endSymbol'] = $interpolate['endSymbol']; - return interpolate; -}]; - - -/** - * @ngdoc module - * @name ngMessageFormat - * @packageName angular-message-format - * @description - */ -var module = window['angular']['module']('ngMessageFormat', ['ng']); -module['factory']('$$messageFormat', $$MessageFormatFactory); -module['config'](['$provide', function($provide) { - $provide['decorator']('$interpolate', $$interpolateDecorator); -}]); - - -})(window, window.angular); diff --git a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-message-format.min.js b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-message-format.min.js deleted file mode 100644 index f85a5876..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-message-format.min.js +++ /dev/null @@ -1,26 +0,0 @@ -/* - AngularJS v1.5.0 - (c) 2010-2016 Google, Inc. http://angularjs.org - License: MIT -*/ -(function(h){'use strict';function C(a){if(null==a)return"";switch(typeof a){case "string":return a;case "number":return""+a;default:return D(a)}}function f(a,b){for(var d=a.split(/\n/g),k=0;k=c.length)b-=c.length;else return{h:k+1,f:b+1}}}function t(a){function b(){return a}var d=u[a];if(null!=d)return d;b.$$watchDelegate=function(b,d,c){var e=b.$watch(v,function(){m(d)&&d.call(null,a,a,b);e()},c);return e};u[a]=b;b.exp=a;b.expressions=[];return b}function F(a,b){function d(a){return void 0== -a?a:a-b}function c(b){return d(a(b))}if(0===b)return a;var e;c.$$watchDelegate=function(b,c,k){return e=b.$watch(a,function(a,k){m(c)&&c.call(null,d(a),d(k),b)},k)};return c}function l(a,b){var d=this;this.b=a;this.e=b;if(void 0===b.other)throw e("reqother");this.d=function(a){return d.D(a)};this.d.$$watchDelegate=function(a,b,c){return d.P(a,b,c)};this.d.exp=a.exp;this.d.expressions=a.expressions}function n(a,b,d,c){var e=this;this.scope=b;this.oa=a;this.v=d;this.qa=c;this.U=void 0;this.K=v;this.ka= -b.$watch(a.b,function(a){return e.ja(a)},c)}function p(a,b){l.call(this,a,b)}function w(){}function q(a,b,d,c){l.call(this,a,b);this.offset=d;this.M=c}function x(){}function g(a,b){this.u=a;this.B=b;this.i=[];this.g=[];this.J=[];this.s="";this.q=null}function r(a,b,d){this.c=a;this.scope=b;this.W=void 0;this.v=d;var c=this;this.la=b.$watchGroup(a.g,function(a,b){c.Ea(a,b)})}function s(a,b){b.b=a.b;b.C=a.C;b.w=a.w;b.e=a.e;b.k=a.k;b.c=a.c;b.n=a.n;b.F=a.F;b.l=a.l}function y(a){s(a,this)}function c(a, -b,d,c,e,E,f,g){this.text=a;this.index=b||0;this.A=d;this.M=c;this.Da=e;this.pa=!!E;this.u=f;this.B=!!g;this.F=this.c=this.k=this.e=this.w=this.C=this.b=null;this.L=[];this.G=this.j=this.ca=this.O=this.da=this.l=this.n=this.o=this.a=this.d=null}function z(a){switch(a){case "{":return"}";case "[":return"]";case "(":return")";default:return null}}function G(a){switch(a){case "}":return"{";case "]":return"[";case ")":return"(";default:return null}}var e=h.angular.$interpolateMinErr,v=h.angular.noop,m= -h.angular.isFunction,D=h.angular.toJson,u=Object.create(null);l.prototype.T=function(a){return this.e[this.R(a)]};l.prototype.D=function(a){return this.T(this.b(a))(a)};l.prototype.P=function(a,b,d){var c=new n(this,a,b,d);return function(){c.I()}};n.prototype.ja=function(a){var b=this;this.K();a=this.oa.T(a);this.K=this.scope.$watch(a,function(a,c){return b.na(a,c)},this.qa)};n.prototype.na=function(a,b){m(this.v)&&this.v.call(null,a,a===b?a:this.U,this.scope);this.U=a};n.prototype.I=function(){this.ka(); -this.K()};w.prototype=l.prototype;p.prototype=new w;p.prototype.R=function(a){return void 0!==this.e[a]?a:"other"};x.prototype=l.prototype;q.prototype=new x;q.prototype.R=function(a){if(isNaN(a))return"other";if(void 0!==this.e[a])return a;a=this.M(a-this.offset);return void 0!==this.e[a]?a:"other"};g.prototype.S=function(){this.s&&(null==this.q?this.i.push(this.s):(this.i.push(this.q.join("")),this.q=null),this.s="")};g.prototype.p=function(a){a.length&&(this.s?this.q?this.q.push(a):this.q=[this.s, -a]:this.s=a)};g.prototype.H=function(a){this.S();this.J.push(this.i.length);this.g.push(a);this.i.push("")};g.prototype.ma=function(a){for(var b=Array(this.g.length),d=0;d - * - *
- *
You did not enter a field
- *
- * Your email must be between 5 and 100 characters long - *
- *
- * - * ``` - * - * Now whatever key/value entries are present within the provided object (in this case `$error`) then - * the ngMessages directive will render the inner first ngMessage directive (depending if the key values - * match the attribute value present on each ngMessage directive). In other words, if your errors - * object contains the following data: - * - * ```javascript - * - * myField.$error = { minlength : true, required : true }; - * ``` - * - * Then the `required` message will be displayed first. When required is false then the `minlength` message - * will be displayed right after (since these messages are ordered this way in the template HTML code). - * The prioritization of each message is determined by what order they're present in the DOM. - * Therefore, instead of having custom JavaScript code determine the priority of what errors are - * present before others, the presentation of the errors are handled within the template. - * - * By default, ngMessages will only display one error at a time. However, if you wish to display all - * messages then the `ng-messages-multiple` attribute flag can be used on the element containing the - * ngMessages directive to make this happen. - * - * ```html - * - *
...
- * - * - * ... - * ``` - * - * ## Reusing and Overriding Messages - * In addition to prioritization, ngMessages also allows for including messages from a remote or an inline - * template. This allows for generic collection of messages to be reused across multiple parts of an - * application. - * - * ```html - * - * - *
- *
- *
- * ``` - * - * However, including generic messages may not be useful enough to match all input fields, therefore, - * `ngMessages` provides the ability to override messages defined in the remote template by redefining - * them within the directive container. - * - * ```html - * - * - * - *
- * - * - *
- * - *
You did not enter your email address
- * - * - *
Your email address is invalid
- * - * - *
- *
- *
- * ``` - * - * In the example HTML code above the message that is set on required will override the corresponding - * required message defined within the remote template. Therefore, with particular input fields (such - * email addresses, date fields, autocomplete inputs, etc...), specialized error messages can be applied - * while more generic messages can be used to handle other, more general input errors. - * - * ## Dynamic Messaging - * ngMessages also supports using expressions to dynamically change key values. Using arrays and - * repeaters to list messages is also supported. This means that the code below will be able to - * fully adapt itself and display the appropriate message when any of the expression data changes: - * - * ```html - *
- * - *
- *
You did not enter your email address
- *
- * - *
{{ errorMessage.text }}
- *
- *
- *
- * ``` - * - * The `errorMessage.type` expression can be a string value or it can be an array so - * that multiple errors can be associated with a single error message: - * - * ```html - * - *
- *
You did not enter your email address
- *
- * Your email must be between 5 and 100 characters long - *
- *
- * ``` - * - * Feel free to use other structural directives such as ng-if and ng-switch to further control - * what messages are active and when. Be careful, if you place ng-message on the same element - * as these structural directives, Angular may not be able to determine if a message is active - * or not. Therefore it is best to place the ng-message on a child element of the structural - * directive. - * - * ```html - *
- *
- *
Please enter something
- *
- *
- * ``` - * - * ## Animations - * If the `ngAnimate` module is active within the application then the `ngMessages`, `ngMessage` and - * `ngMessageExp` directives will trigger animations whenever any messages are added and removed from - * the DOM by the `ngMessages` directive. - * - * Whenever the `ngMessages` directive contains one or more visible messages then the `.ng-active` CSS - * class will be added to the element. The `.ng-inactive` CSS class will be applied when there are no - * messages present. Therefore, CSS transitions and keyframes as well as JavaScript animations can - * hook into the animations whenever these classes are added/removed. - * - * Let's say that our HTML code for our messages container looks like so: - * - * ```html - * - * ``` - * - * Then the CSS animation code for the message container looks like so: - * - * ```css - * .my-messages { - * transition:1s linear all; - * } - * .my-messages.ng-active { - * // messages are visible - * } - * .my-messages.ng-inactive { - * // messages are hidden - * } - * ``` - * - * Whenever an inner message is attached (becomes visible) or removed (becomes hidden) then the enter - * and leave animation is triggered for each particular element bound to the `ngMessage` directive. - * - * Therefore, the CSS code for the inner messages looks like so: - * - * ```css - * .some-message { - * transition:1s linear all; - * } - * - * .some-message.ng-enter {} - * .some-message.ng-enter.ng-enter-active {} - * - * .some-message.ng-leave {} - * .some-message.ng-leave.ng-leave-active {} - * ``` - * - * {@link ngAnimate Click here} to learn how to use JavaScript animations or to learn more about ngAnimate. - */ -angular.module('ngMessages', []) - - /** - * @ngdoc directive - * @module ngMessages - * @name ngMessages - * @restrict AE - * - * @description - * `ngMessages` is a directive that is designed to show and hide messages based on the state - * of a key/value object that it listens on. The directive itself complements error message - * reporting with the `ngModel` $error object (which stores a key/value state of validation errors). - * - * `ngMessages` manages the state of internal messages within its container element. The internal - * messages use the `ngMessage` directive and will be inserted/removed from the page depending - * on if they're present within the key/value object. By default, only one message will be displayed - * at a time and this depends on the prioritization of the messages within the template. (This can - * be changed by using the `ng-messages-multiple` or `multiple` attribute on the directive container.) - * - * A remote template can also be used to promote message reusability and messages can also be - * overridden. - * - * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. - * - * @usage - * ```html - * - * - * ... - * ... - * ... - * - * - * - * - * ... - * ... - * ... - * - * ``` - * - * @param {string} ngMessages an angular expression evaluating to a key/value object - * (this is typically the $error object on an ngModel instance). - * @param {string=} ngMessagesMultiple|multiple when set, all messages will be displayed with true - * - * @example - * - * - *
- * - *
myForm.myName.$error = {{ myForm.myName.$error | json }}
- * - *
- *
You did not enter a field
- *
Your field is too short
- *
Your field is too long
- *
- *
- *
- * - * angular.module('ngMessagesExample', ['ngMessages']); - * - *
- */ - .directive('ngMessages', ['$animate', function($animate) { - var ACTIVE_CLASS = 'ng-active'; - var INACTIVE_CLASS = 'ng-inactive'; - - return { - require: 'ngMessages', - restrict: 'AE', - controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { - var ctrl = this; - var latestKey = 0; - var nextAttachId = 0; - - this.getAttachId = function getAttachId() { return nextAttachId++; }; - - var messages = this.messages = {}; - var renderLater, cachedCollection; - - this.render = function(collection) { - collection = collection || {}; - - renderLater = false; - cachedCollection = collection; - - // this is true if the attribute is empty or if the attribute value is truthy - var multiple = isAttrTruthy($scope, $attrs.ngMessagesMultiple) || - isAttrTruthy($scope, $attrs.multiple); - - var unmatchedMessages = []; - var matchedKeys = {}; - var messageItem = ctrl.head; - var messageFound = false; - var totalMessages = 0; - - // we use != instead of !== to allow for both undefined and null values - while (messageItem != null) { - totalMessages++; - var messageCtrl = messageItem.message; - - var messageUsed = false; - if (!messageFound) { - forEach(collection, function(value, key) { - if (!messageUsed && truthy(value) && messageCtrl.test(key)) { - // this is to prevent the same error name from showing up twice - if (matchedKeys[key]) return; - matchedKeys[key] = true; - - messageUsed = true; - messageCtrl.attach(); - } - }); - } - - if (messageUsed) { - // unless we want to display multiple messages then we should - // set a flag here to avoid displaying the next message in the list - messageFound = !multiple; - } else { - unmatchedMessages.push(messageCtrl); - } - - messageItem = messageItem.next; - } - - forEach(unmatchedMessages, function(messageCtrl) { - messageCtrl.detach(); - }); - - unmatchedMessages.length !== totalMessages - ? $animate.setClass($element, ACTIVE_CLASS, INACTIVE_CLASS) - : $animate.setClass($element, INACTIVE_CLASS, ACTIVE_CLASS); - }; - - $scope.$watchCollection($attrs.ngMessages || $attrs['for'], ctrl.render); - - this.reRender = function() { - if (!renderLater) { - renderLater = true; - $scope.$evalAsync(function() { - if (renderLater) { - cachedCollection && ctrl.render(cachedCollection); - } - }); - } - }; - - this.register = function(comment, messageCtrl) { - var nextKey = latestKey.toString(); - messages[nextKey] = { - message: messageCtrl - }; - insertMessageNode($element[0], comment, nextKey); - comment.$$ngMessageNode = nextKey; - latestKey++; - - ctrl.reRender(); - }; - - this.deregister = function(comment) { - var key = comment.$$ngMessageNode; - delete comment.$$ngMessageNode; - removeMessageNode($element[0], comment, key); - delete messages[key]; - ctrl.reRender(); - }; - - function findPreviousMessage(parent, comment) { - var prevNode = comment; - var parentLookup = []; - while (prevNode && prevNode !== parent) { - var prevKey = prevNode.$$ngMessageNode; - if (prevKey && prevKey.length) { - return messages[prevKey]; - } - - // dive deeper into the DOM and examine its children for any ngMessage - // comments that may be in an element that appears deeper in the list - if (prevNode.childNodes.length && parentLookup.indexOf(prevNode) == -1) { - parentLookup.push(prevNode); - prevNode = prevNode.childNodes[prevNode.childNodes.length - 1]; - } else { - prevNode = prevNode.previousSibling || prevNode.parentNode; - } - } - } - - function insertMessageNode(parent, comment, key) { - var messageNode = messages[key]; - if (!ctrl.head) { - ctrl.head = messageNode; - } else { - var match = findPreviousMessage(parent, comment); - if (match) { - messageNode.next = match.next; - match.next = messageNode; - } else { - messageNode.next = ctrl.head; - ctrl.head = messageNode; - } - } - } - - function removeMessageNode(parent, comment, key) { - var messageNode = messages[key]; - - var match = findPreviousMessage(parent, comment); - if (match) { - match.next = messageNode.next; - } else { - ctrl.head = messageNode.next; - } - } - }] - }; - - function isAttrTruthy(scope, attr) { - return (isString(attr) && attr.length === 0) || //empty attribute - truthy(scope.$eval(attr)); - } - - function truthy(val) { - return isString(val) ? val.length : !!val; - } - }]) - - /** - * @ngdoc directive - * @name ngMessagesInclude - * @restrict AE - * @scope - * - * @description - * `ngMessagesInclude` is a directive with the purpose to import existing ngMessage template - * code from a remote template and place the downloaded template code into the exact spot - * that the ngMessagesInclude directive is placed within the ngMessages container. This allows - * for a series of pre-defined messages to be reused and also allows for the developer to - * determine what messages are overridden due to the placement of the ngMessagesInclude directive. - * - * @usage - * ```html - * - * - * ... - * - * - * - * - * ... - * - * ``` - * - * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. - * - * @param {string} ngMessagesInclude|src a string value corresponding to the remote template. - */ - .directive('ngMessagesInclude', - ['$templateRequest', '$document', '$compile', function($templateRequest, $document, $compile) { - - return { - restrict: 'AE', - require: '^^ngMessages', // we only require this for validation sake - link: function($scope, element, attrs) { - var src = attrs.ngMessagesInclude || attrs.src; - $templateRequest(src).then(function(html) { - $compile(html)($scope, function(contents) { - element.after(contents); - - // the anchor is placed for debugging purposes - var anchor = jqLite($document[0].createComment(' ngMessagesInclude: ' + src + ' ')); - element.after(anchor); - - // we don't want to pollute the DOM anymore by keeping an empty directive element - element.remove(); - }); - }); - } - }; - }]) - - /** - * @ngdoc directive - * @name ngMessage - * @restrict AE - * @scope - * - * @description - * `ngMessage` is a directive with the purpose to show and hide a particular message. - * For `ngMessage` to operate, a parent `ngMessages` directive on a parent DOM element - * must be situated since it determines which messages are visible based on the state - * of the provided key/value map that `ngMessages` listens on. - * - * More information about using `ngMessage` can be found in the - * {@link module:ngMessages `ngMessages` module documentation}. - * - * @usage - * ```html - * - * - * ... - * ... - * - * - * - * - * ... - * ... - * - * ``` - * - * @param {expression} ngMessage|when a string value corresponding to the message key. - */ - .directive('ngMessage', ngMessageDirectiveFactory()) - - - /** - * @ngdoc directive - * @name ngMessageExp - * @restrict AE - * @priority 1 - * @scope - * - * @description - * `ngMessageExp` is a directive with the purpose to show and hide a particular message. - * For `ngMessageExp` to operate, a parent `ngMessages` directive on a parent DOM element - * must be situated since it determines which messages are visible based on the state - * of the provided key/value map that `ngMessages` listens on. - * - * @usage - * ```html - * - * - * ... - * - * - * - * - * ... - * - * ``` - * - * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. - * - * @param {expression} ngMessageExp|whenExp an expression value corresponding to the message key. - */ - .directive('ngMessageExp', ngMessageDirectiveFactory()); - -function ngMessageDirectiveFactory() { - return ['$animate', function($animate) { - return { - restrict: 'AE', - transclude: 'element', - priority: 1, // must run before ngBind, otherwise the text is set on the comment - terminal: true, - require: '^^ngMessages', - link: function(scope, element, attrs, ngMessagesCtrl, $transclude) { - var commentNode = element[0]; - - var records; - var staticExp = attrs.ngMessage || attrs.when; - var dynamicExp = attrs.ngMessageExp || attrs.whenExp; - var assignRecords = function(items) { - records = items - ? (isArray(items) - ? items - : items.split(/[\s,]+/)) - : null; - ngMessagesCtrl.reRender(); - }; - - if (dynamicExp) { - assignRecords(scope.$eval(dynamicExp)); - scope.$watchCollection(dynamicExp, assignRecords); - } else { - assignRecords(staticExp); - } - - var currentElement, messageCtrl; - ngMessagesCtrl.register(commentNode, messageCtrl = { - test: function(name) { - return contains(records, name); - }, - attach: function() { - if (!currentElement) { - $transclude(scope, function(elm) { - $animate.enter(elm, null, element); - currentElement = elm; - - // Each time we attach this node to a message we get a new id that we can match - // when we are destroying the node later. - var $$attachId = currentElement.$$attachId = ngMessagesCtrl.getAttachId(); - - // in the event that the parent element is destroyed - // by any other structural directive then it's time - // to deregister the message from the controller - currentElement.on('$destroy', function() { - if (currentElement && currentElement.$$attachId === $$attachId) { - ngMessagesCtrl.deregister(commentNode); - messageCtrl.detach(); - } - }); - }); - } - }, - detach: function() { - if (currentElement) { - var elm = currentElement; - currentElement = null; - $animate.leave(elm); - } - } - }); - } - }; - }]; - - function contains(collection, key) { - if (collection) { - return isArray(collection) - ? collection.indexOf(key) >= 0 - : collection.hasOwnProperty(key); - } - } -} - - -})(window, window.angular); diff --git a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-messages.min.js b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-messages.min.js deleted file mode 100644 index 19f59cc8..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-messages.min.js +++ /dev/null @@ -1,12 +0,0 @@ -/* - AngularJS v1.5.0 - (c) 2010-2016 Google, Inc. http://angularjs.org - License: MIT -*/ -(function(A,d,B){'use strict';function l(){return["$animate",function(v){return{restrict:"AE",transclude:"element",priority:1,terminal:!0,require:"^^ngMessages",link:function(n,r,a,b,m){var k=r[0],f,p=a.ngMessage||a.when;a=a.ngMessageExp||a.whenExp;var d=function(a){f=a?w(a)?a:a.split(/[\s,]+/):null;b.reRender()};a?(d(n.$eval(a)),n.$watchCollection(a,d)):d(p);var e,q;b.register(k,q={test:function(a){var g=f;a=g?w(g)?0<=g.indexOf(a):g.hasOwnProperty(a):void 0;return a},attach:function(){e||m(n,function(a){v.enter(a, -null,r);e=a;var g=e.$$attachId=b.getAttachId();e.on("$destroy",function(){e&&e.$$attachId===g&&(b.deregister(k),q.detach())})})},detach:function(){if(e){var a=e;e=null;v.leave(a)}}})}}}]}var w=d.isArray,x=d.forEach,y=d.isString,z=d.element;d.module("ngMessages",[]).directive("ngMessages",["$animate",function(d){function n(a,b){return y(b)&&0===b.length||r(a.$eval(b))}function r(a){return y(a)?a.length:!!a}return{require:"ngMessages",restrict:"AE",controller:["$element","$scope","$attrs",function(a, -b,m){function k(a,b){for(var c=b,f=[];c&&c!==a;){var h=c.$$ngMessageNode;if(h&&h.length)return e[h];c.childNodes.length&&-1==f.indexOf(c)?(f.push(c),c=c.childNodes[c.childNodes.length-1]):c=c.previousSibling||c.parentNode}}var f=this,p=0,l=0;this.getAttachId=function(){return l++};var e=this.messages={},q,s;this.render=function(g){g=g||{};q=!1;s=g;for(var e=n(b,m.ngMessagesMultiple)||n(b,m.multiple),c=[],k={},h=f.head,p=!1,l=0;null!=h;){l++;var t=h.message,u=!1;p||x(g,function(a,c){!u&&r(a)&&t.test(c)&& -!k[c]&&(u=k[c]=!0,t.attach())});u?p=!e:c.push(t);h=h.next}x(c,function(a){a.detach()});c.length!==l?d.setClass(a,"ng-active","ng-inactive"):d.setClass(a,"ng-inactive","ng-active")};b.$watchCollection(m.ngMessages||m["for"],f.render);this.reRender=function(){q||(q=!0,b.$evalAsync(function(){q&&s&&f.render(s)}))};this.register=function(g,b){var c=p.toString();e[c]={message:b};var d=a[0],h=e[c];f.head?(d=k(d,g))?(h.next=d.next,d.next=h):(h.next=f.head,f.head=h):f.head=h;g.$$ngMessageNode=c;p++;f.reRender()}; -this.deregister=function(b){var d=b.$$ngMessageNode;delete b.$$ngMessageNode;var c=e[d];(b=k(a[0],b))?b.next=c.next:f.head=c.next;delete e[d];f.reRender()}}]}}]).directive("ngMessagesInclude",["$templateRequest","$document","$compile",function(d,n,l){return{restrict:"AE",require:"^^ngMessages",link:function(a,b,m){var k=m.ngMessagesInclude||m.src;d(k).then(function(d){l(d)(a,function(a){b.after(a);a=z(n[0].createComment(" ngMessagesInclude: "+k+" "));b.after(a);b.remove()})})}}}]).directive("ngMessage", -l()).directive("ngMessageExp",l())})(window,window.angular); -//# sourceMappingURL=angular-messages.min.js.map diff --git a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-mocks.js b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-mocks.js deleted file mode 100644 index 34d36087..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-mocks.js +++ /dev/null @@ -1,2842 +0,0 @@ -/** - * @license AngularJS v1.5.0 - * (c) 2010-2016 Google, Inc. http://angularjs.org - * License: MIT - */ -(function(window, angular, undefined) { - -'use strict'; - -/** - * @ngdoc object - * @name angular.mock - * @description - * - * Namespace from 'angular-mocks.js' which contains testing related code. - */ -angular.mock = {}; - -/** - * ! This is a private undocumented service ! - * - * @name $browser - * - * @description - * This service is a mock implementation of {@link ng.$browser}. It provides fake - * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr, - * cookies, etc... - * - * The api of this service is the same as that of the real {@link ng.$browser $browser}, except - * that there are several helper methods available which can be used in tests. - */ -angular.mock.$BrowserProvider = function() { - this.$get = function() { - return new angular.mock.$Browser(); - }; -}; - -angular.mock.$Browser = function() { - var self = this; - - this.isMock = true; - self.$$url = "http://server/"; - self.$$lastUrl = self.$$url; // used by url polling fn - self.pollFns = []; - - // TODO(vojta): remove this temporary api - self.$$completeOutstandingRequest = angular.noop; - self.$$incOutstandingRequestCount = angular.noop; - - - // register url polling fn - - self.onUrlChange = function(listener) { - self.pollFns.push( - function() { - if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) { - self.$$lastUrl = self.$$url; - self.$$lastState = self.$$state; - listener(self.$$url, self.$$state); - } - } - ); - - return listener; - }; - - self.$$applicationDestroyed = angular.noop; - self.$$checkUrlChange = angular.noop; - - self.deferredFns = []; - self.deferredNextId = 0; - - self.defer = function(fn, delay) { - delay = delay || 0; - self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId}); - self.deferredFns.sort(function(a, b) { return a.time - b.time;}); - return self.deferredNextId++; - }; - - - /** - * @name $browser#defer.now - * - * @description - * Current milliseconds mock time. - */ - self.defer.now = 0; - - - self.defer.cancel = function(deferId) { - var fnIndex; - - angular.forEach(self.deferredFns, function(fn, index) { - if (fn.id === deferId) fnIndex = index; - }); - - if (angular.isDefined(fnIndex)) { - self.deferredFns.splice(fnIndex, 1); - return true; - } - - return false; - }; - - - /** - * @name $browser#defer.flush - * - * @description - * Flushes all pending requests and executes the defer callbacks. - * - * @param {number=} number of milliseconds to flush. See {@link #defer.now} - */ - self.defer.flush = function(delay) { - if (angular.isDefined(delay)) { - self.defer.now += delay; - } else { - if (self.deferredFns.length) { - self.defer.now = self.deferredFns[self.deferredFns.length - 1].time; - } else { - throw new Error('No deferred tasks to be flushed'); - } - } - - while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) { - self.deferredFns.shift().fn(); - } - }; - - self.$$baseHref = '/'; - self.baseHref = function() { - return this.$$baseHref; - }; -}; -angular.mock.$Browser.prototype = { - -/** - * @name $browser#poll - * - * @description - * run all fns in pollFns - */ - poll: function poll() { - angular.forEach(this.pollFns, function(pollFn) { - pollFn(); - }); - }, - - url: function(url, replace, state) { - if (angular.isUndefined(state)) { - state = null; - } - if (url) { - this.$$url = url; - // Native pushState serializes & copies the object; simulate it. - this.$$state = angular.copy(state); - return this; - } - - return this.$$url; - }, - - state: function() { - return this.$$state; - }, - - notifyWhenNoOutstandingRequests: function(fn) { - fn(); - } -}; - - -/** - * @ngdoc provider - * @name $exceptionHandlerProvider - * - * @description - * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors - * passed to the `$exceptionHandler`. - */ - -/** - * @ngdoc service - * @name $exceptionHandler - * - * @description - * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed - * to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration - * information. - * - * - * ```js - * describe('$exceptionHandlerProvider', function() { - * - * it('should capture log messages and exceptions', function() { - * - * module(function($exceptionHandlerProvider) { - * $exceptionHandlerProvider.mode('log'); - * }); - * - * inject(function($log, $exceptionHandler, $timeout) { - * $timeout(function() { $log.log(1); }); - * $timeout(function() { $log.log(2); throw 'banana peel'; }); - * $timeout(function() { $log.log(3); }); - * expect($exceptionHandler.errors).toEqual([]); - * expect($log.assertEmpty()); - * $timeout.flush(); - * expect($exceptionHandler.errors).toEqual(['banana peel']); - * expect($log.log.logs).toEqual([[1], [2], [3]]); - * }); - * }); - * }); - * ``` - */ - -angular.mock.$ExceptionHandlerProvider = function() { - var handler; - - /** - * @ngdoc method - * @name $exceptionHandlerProvider#mode - * - * @description - * Sets the logging mode. - * - * @param {string} mode Mode of operation, defaults to `rethrow`. - * - * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log` - * mode stores an array of errors in `$exceptionHandler.errors`, to allow later - * assertion of them. See {@link ngMock.$log#assertEmpty assertEmpty()} and - * {@link ngMock.$log#reset reset()} - * - `rethrow`: If any errors are passed to the handler in tests, it typically means that there - * is a bug in the application or test, so this mock will make these tests fail. - * For any implementations that expect exceptions to be thrown, the `rethrow` mode - * will also maintain a log of thrown errors. - */ - this.mode = function(mode) { - - switch (mode) { - case 'log': - case 'rethrow': - var errors = []; - handler = function(e) { - if (arguments.length == 1) { - errors.push(e); - } else { - errors.push([].slice.call(arguments, 0)); - } - if (mode === "rethrow") { - throw e; - } - }; - handler.errors = errors; - break; - default: - throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!"); - } - }; - - this.$get = function() { - return handler; - }; - - this.mode('rethrow'); -}; - - -/** - * @ngdoc service - * @name $log - * - * @description - * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays - * (one array per logging level). These arrays are exposed as `logs` property of each of the - * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`. - * - */ -angular.mock.$LogProvider = function() { - var debug = true; - - function concat(array1, array2, index) { - return array1.concat(Array.prototype.slice.call(array2, index)); - } - - this.debugEnabled = function(flag) { - if (angular.isDefined(flag)) { - debug = flag; - return this; - } else { - return debug; - } - }; - - this.$get = function() { - var $log = { - log: function() { $log.log.logs.push(concat([], arguments, 0)); }, - warn: function() { $log.warn.logs.push(concat([], arguments, 0)); }, - info: function() { $log.info.logs.push(concat([], arguments, 0)); }, - error: function() { $log.error.logs.push(concat([], arguments, 0)); }, - debug: function() { - if (debug) { - $log.debug.logs.push(concat([], arguments, 0)); - } - } - }; - - /** - * @ngdoc method - * @name $log#reset - * - * @description - * Reset all of the logging arrays to empty. - */ - $log.reset = function() { - /** - * @ngdoc property - * @name $log#log.logs - * - * @description - * Array of messages logged using {@link ng.$log#log `log()`}. - * - * @example - * ```js - * $log.log('Some Log'); - * var first = $log.log.logs.unshift(); - * ``` - */ - $log.log.logs = []; - /** - * @ngdoc property - * @name $log#info.logs - * - * @description - * Array of messages logged using {@link ng.$log#info `info()`}. - * - * @example - * ```js - * $log.info('Some Info'); - * var first = $log.info.logs.unshift(); - * ``` - */ - $log.info.logs = []; - /** - * @ngdoc property - * @name $log#warn.logs - * - * @description - * Array of messages logged using {@link ng.$log#warn `warn()`}. - * - * @example - * ```js - * $log.warn('Some Warning'); - * var first = $log.warn.logs.unshift(); - * ``` - */ - $log.warn.logs = []; - /** - * @ngdoc property - * @name $log#error.logs - * - * @description - * Array of messages logged using {@link ng.$log#error `error()`}. - * - * @example - * ```js - * $log.error('Some Error'); - * var first = $log.error.logs.unshift(); - * ``` - */ - $log.error.logs = []; - /** - * @ngdoc property - * @name $log#debug.logs - * - * @description - * Array of messages logged using {@link ng.$log#debug `debug()`}. - * - * @example - * ```js - * $log.debug('Some Error'); - * var first = $log.debug.logs.unshift(); - * ``` - */ - $log.debug.logs = []; - }; - - /** - * @ngdoc method - * @name $log#assertEmpty - * - * @description - * Assert that all of the logging methods have no logged messages. If any messages are present, - * an exception is thrown. - */ - $log.assertEmpty = function() { - var errors = []; - angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) { - angular.forEach($log[logLevel].logs, function(log) { - angular.forEach(log, function(logItem) { - errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + - (logItem.stack || '')); - }); - }); - }); - if (errors.length) { - errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or " + - "an expected log message was not checked and removed:"); - errors.push(''); - throw new Error(errors.join('\n---------\n')); - } - }; - - $log.reset(); - return $log; - }; -}; - - -/** - * @ngdoc service - * @name $interval - * - * @description - * Mock implementation of the $interval service. - * - * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to - * move forward by `millis` milliseconds and trigger any functions scheduled to run in that - * time. - * - * @param {function()} fn A function that should be called repeatedly. - * @param {number} delay Number of milliseconds between each function call. - * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat - * indefinitely. - * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise - * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. - * @param {...*=} Pass additional parameters to the executed function. - * @returns {promise} A promise which will be notified on each iteration. - */ -angular.mock.$IntervalProvider = function() { - this.$get = ['$browser', '$rootScope', '$q', '$$q', - function($browser, $rootScope, $q, $$q) { - var repeatFns = [], - nextRepeatId = 0, - now = 0; - - var $interval = function(fn, delay, count, invokeApply) { - var hasParams = arguments.length > 4, - args = hasParams ? Array.prototype.slice.call(arguments, 4) : [], - iteration = 0, - skipApply = (angular.isDefined(invokeApply) && !invokeApply), - deferred = (skipApply ? $$q : $q).defer(), - promise = deferred.promise; - - count = (angular.isDefined(count)) ? count : 0; - promise.then(null, null, (!hasParams) ? fn : function() { - fn.apply(null, args); - }); - - promise.$$intervalId = nextRepeatId; - - function tick() { - deferred.notify(iteration++); - - if (count > 0 && iteration >= count) { - var fnIndex; - deferred.resolve(iteration); - - angular.forEach(repeatFns, function(fn, index) { - if (fn.id === promise.$$intervalId) fnIndex = index; - }); - - if (angular.isDefined(fnIndex)) { - repeatFns.splice(fnIndex, 1); - } - } - - if (skipApply) { - $browser.defer.flush(); - } else { - $rootScope.$apply(); - } - } - - repeatFns.push({ - nextTime:(now + delay), - delay: delay, - fn: tick, - id: nextRepeatId, - deferred: deferred - }); - repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;}); - - nextRepeatId++; - return promise; - }; - /** - * @ngdoc method - * @name $interval#cancel - * - * @description - * Cancels a task associated with the `promise`. - * - * @param {promise} promise A promise from calling the `$interval` function. - * @returns {boolean} Returns `true` if the task was successfully cancelled. - */ - $interval.cancel = function(promise) { - if (!promise) return false; - var fnIndex; - - angular.forEach(repeatFns, function(fn, index) { - if (fn.id === promise.$$intervalId) fnIndex = index; - }); - - if (angular.isDefined(fnIndex)) { - repeatFns[fnIndex].deferred.reject('canceled'); - repeatFns.splice(fnIndex, 1); - return true; - } - - return false; - }; - - /** - * @ngdoc method - * @name $interval#flush - * @description - * - * Runs interval tasks scheduled to be run in the next `millis` milliseconds. - * - * @param {number=} millis maximum timeout amount to flush up until. - * - * @return {number} The amount of time moved forward. - */ - $interval.flush = function(millis) { - now += millis; - while (repeatFns.length && repeatFns[0].nextTime <= now) { - var task = repeatFns[0]; - task.fn(); - task.nextTime += task.delay; - repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;}); - } - return millis; - }; - - return $interval; - }]; -}; - - -/* jshint -W101 */ -/* The R_ISO8061_STR regex is never going to fit into the 100 char limit! - * This directive should go inside the anonymous function but a bug in JSHint means that it would - * not be enacted early enough to prevent the warning. - */ -var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; - -function jsonStringToDate(string) { - var match; - if (match = string.match(R_ISO8061_STR)) { - var date = new Date(0), - tzHour = 0, - tzMin = 0; - if (match[9]) { - tzHour = toInt(match[9] + match[10]); - tzMin = toInt(match[9] + match[11]); - } - date.setUTCFullYear(toInt(match[1]), toInt(match[2]) - 1, toInt(match[3])); - date.setUTCHours(toInt(match[4] || 0) - tzHour, - toInt(match[5] || 0) - tzMin, - toInt(match[6] || 0), - toInt(match[7] || 0)); - return date; - } - return string; -} - -function toInt(str) { - return parseInt(str, 10); -} - -function padNumber(num, digits, trim) { - var neg = ''; - if (num < 0) { - neg = '-'; - num = -num; - } - num = '' + num; - while (num.length < digits) num = '0' + num; - if (trim) { - num = num.substr(num.length - digits); - } - return neg + num; -} - - -/** - * @ngdoc type - * @name angular.mock.TzDate - * @description - * - * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`. - * - * Mock of the Date type which has its timezone specified via constructor arg. - * - * The main purpose is to create Date-like instances with timezone fixed to the specified timezone - * offset, so that we can test code that depends on local timezone settings without dependency on - * the time zone settings of the machine where the code is running. - * - * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored) - * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC* - * - * @example - * !!!! WARNING !!!!! - * This is not a complete Date object so only methods that were implemented can be called safely. - * To make matters worse, TzDate instances inherit stuff from Date via a prototype. - * - * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is - * incomplete we might be missing some non-standard methods. This can result in errors like: - * "Date.prototype.foo called on incompatible Object". - * - * ```js - * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z'); - * newYearInBratislava.getTimezoneOffset() => -60; - * newYearInBratislava.getFullYear() => 2010; - * newYearInBratislava.getMonth() => 0; - * newYearInBratislava.getDate() => 1; - * newYearInBratislava.getHours() => 0; - * newYearInBratislava.getMinutes() => 0; - * newYearInBratislava.getSeconds() => 0; - * ``` - * - */ -angular.mock.TzDate = function(offset, timestamp) { - var self = new Date(0); - if (angular.isString(timestamp)) { - var tsStr = timestamp; - - self.origDate = jsonStringToDate(timestamp); - - timestamp = self.origDate.getTime(); - if (isNaN(timestamp)) { - throw { - name: "Illegal Argument", - message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string" - }; - } - } else { - self.origDate = new Date(timestamp); - } - - var localOffset = new Date(timestamp).getTimezoneOffset(); - self.offsetDiff = localOffset * 60 * 1000 - offset * 1000 * 60 * 60; - self.date = new Date(timestamp + self.offsetDiff); - - self.getTime = function() { - return self.date.getTime() - self.offsetDiff; - }; - - self.toLocaleDateString = function() { - return self.date.toLocaleDateString(); - }; - - self.getFullYear = function() { - return self.date.getFullYear(); - }; - - self.getMonth = function() { - return self.date.getMonth(); - }; - - self.getDate = function() { - return self.date.getDate(); - }; - - self.getHours = function() { - return self.date.getHours(); - }; - - self.getMinutes = function() { - return self.date.getMinutes(); - }; - - self.getSeconds = function() { - return self.date.getSeconds(); - }; - - self.getMilliseconds = function() { - return self.date.getMilliseconds(); - }; - - self.getTimezoneOffset = function() { - return offset * 60; - }; - - self.getUTCFullYear = function() { - return self.origDate.getUTCFullYear(); - }; - - self.getUTCMonth = function() { - return self.origDate.getUTCMonth(); - }; - - self.getUTCDate = function() { - return self.origDate.getUTCDate(); - }; - - self.getUTCHours = function() { - return self.origDate.getUTCHours(); - }; - - self.getUTCMinutes = function() { - return self.origDate.getUTCMinutes(); - }; - - self.getUTCSeconds = function() { - return self.origDate.getUTCSeconds(); - }; - - self.getUTCMilliseconds = function() { - return self.origDate.getUTCMilliseconds(); - }; - - self.getDay = function() { - return self.date.getDay(); - }; - - // provide this method only on browsers that already have it - if (self.toISOString) { - self.toISOString = function() { - return padNumber(self.origDate.getUTCFullYear(), 4) + '-' + - padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' + - padNumber(self.origDate.getUTCDate(), 2) + 'T' + - padNumber(self.origDate.getUTCHours(), 2) + ':' + - padNumber(self.origDate.getUTCMinutes(), 2) + ':' + - padNumber(self.origDate.getUTCSeconds(), 2) + '.' + - padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z'; - }; - } - - //hide all methods not implemented in this mock that the Date prototype exposes - var unimplementedMethods = ['getUTCDay', - 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', - 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', - 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', - 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString', - 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf']; - - angular.forEach(unimplementedMethods, function(methodName) { - self[methodName] = function() { - throw new Error("Method '" + methodName + "' is not implemented in the TzDate mock"); - }; - }); - - return self; -}; - -//make "tzDateInstance instanceof Date" return true -angular.mock.TzDate.prototype = Date.prototype; -/* jshint +W101 */ - - -/** - * @ngdoc service - * @name $animate - * - * @description - * Mock implementation of the {@link ng.$animate `$animate`} service. Exposes two additional methods - * for testing animations. - */ -angular.mock.animate = angular.module('ngAnimateMock', ['ng']) - - .config(['$provide', function($provide) { - - $provide.factory('$$forceReflow', function() { - function reflowFn() { - reflowFn.totalReflows++; - } - reflowFn.totalReflows = 0; - return reflowFn; - }); - - $provide.factory('$$animateAsyncRun', function() { - var queue = []; - var queueFn = function() { - return function(fn) { - queue.push(fn); - }; - }; - queueFn.flush = function() { - if (queue.length === 0) return false; - - for (var i = 0; i < queue.length; i++) { - queue[i](); - } - queue = []; - - return true; - }; - return queueFn; - }); - - $provide.decorator('$$animateJs', ['$delegate', function($delegate) { - var runners = []; - - var animateJsConstructor = function() { - var animator = $delegate.apply($delegate, arguments); - // If no javascript animation is found, animator is undefined - if (animator) { - runners.push(animator); - } - return animator; - }; - - animateJsConstructor.$closeAndFlush = function() { - runners.forEach(function(runner) { - runner.end(); - }); - runners = []; - }; - - return animateJsConstructor; - }]); - - $provide.decorator('$animateCss', ['$delegate', function($delegate) { - var runners = []; - - var animateCssConstructor = function(element, options) { - var animator = $delegate(element, options); - runners.push(animator); - return animator; - }; - - animateCssConstructor.$closeAndFlush = function() { - runners.forEach(function(runner) { - runner.end(); - }); - runners = []; - }; - - return animateCssConstructor; - }]); - - $provide.decorator('$animate', ['$delegate', '$timeout', '$browser', '$$rAF', '$animateCss', '$$animateJs', - '$$forceReflow', '$$animateAsyncRun', '$rootScope', - function($delegate, $timeout, $browser, $$rAF, $animateCss, $$animateJs, - $$forceReflow, $$animateAsyncRun, $rootScope) { - var animate = { - queue: [], - cancel: $delegate.cancel, - on: $delegate.on, - off: $delegate.off, - pin: $delegate.pin, - get reflows() { - return $$forceReflow.totalReflows; - }, - enabled: $delegate.enabled, - /** - * @ngdoc method - * @name $animate#closeAndFlush - * @description - * - * This method will close all pending animations (both {@link ngAnimate#javascript-based-animations Javascript} - * and {@link ngAnimate.$animateCss CSS}) and it will also flush any remaining animation frames and/or callbacks. - */ - closeAndFlush: function() { - // we allow the flush command to swallow the errors - // because depending on whether CSS or JS animations are - // used, there may not be a RAF flush. The primary flush - // at the end of this function must throw an exception - // because it will track if there were pending animations - this.flush(true); - $animateCss.$closeAndFlush(); - $$animateJs.$closeAndFlush(); - this.flush(); - }, - /** - * @ngdoc method - * @name $animate#flush - * @description - * - * This method is used to flush the pending callbacks and animation frames to either start - * an animation or conclude an animation. Note that this will not actually close an - * actively running animation (see {@link ngMock.$animate#closeAndFlush `closeAndFlush()`} for that). - */ - flush: function(hideErrors) { - $rootScope.$digest(); - - var doNextRun, somethingFlushed = false; - do { - doNextRun = false; - - if ($$rAF.queue.length) { - $$rAF.flush(); - doNextRun = somethingFlushed = true; - } - - if ($$animateAsyncRun.flush()) { - doNextRun = somethingFlushed = true; - } - } while (doNextRun); - - if (!somethingFlushed && !hideErrors) { - throw new Error('No pending animations ready to be closed or flushed'); - } - - $rootScope.$digest(); - } - }; - - angular.forEach( - ['animate','enter','leave','move','addClass','removeClass','setClass'], function(method) { - animate[method] = function() { - animate.queue.push({ - event: method, - element: arguments[0], - options: arguments[arguments.length - 1], - args: arguments - }); - return $delegate[method].apply($delegate, arguments); - }; - }); - - return animate; - }]); - - }]); - - -/** - * @ngdoc function - * @name angular.mock.dump - * @description - * - * *NOTE*: this is not an injectable instance, just a globally available function. - * - * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for - * debugging. - * - * This method is also available on window, where it can be used to display objects on debug - * console. - * - * @param {*} object - any object to turn into string. - * @return {string} a serialized string of the argument - */ -angular.mock.dump = function(object) { - return serialize(object); - - function serialize(object) { - var out; - - if (angular.isElement(object)) { - object = angular.element(object); - out = angular.element('
'); - angular.forEach(object, function(element) { - out.append(angular.element(element).clone()); - }); - out = out.html(); - } else if (angular.isArray(object)) { - out = []; - angular.forEach(object, function(o) { - out.push(serialize(o)); - }); - out = '[ ' + out.join(', ') + ' ]'; - } else if (angular.isObject(object)) { - if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) { - out = serializeScope(object); - } else if (object instanceof Error) { - out = object.stack || ('' + object.name + ': ' + object.message); - } else { - // TODO(i): this prevents methods being logged, - // we should have a better way to serialize objects - out = angular.toJson(object, true); - } - } else { - out = String(object); - } - - return out; - } - - function serializeScope(scope, offset) { - offset = offset || ' '; - var log = [offset + 'Scope(' + scope.$id + '): {']; - for (var key in scope) { - if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) { - log.push(' ' + key + ': ' + angular.toJson(scope[key])); - } - } - var child = scope.$$childHead; - while (child) { - log.push(serializeScope(child, offset + ' ')); - child = child.$$nextSibling; - } - log.push('}'); - return log.join('\n' + offset); - } -}; - -/** - * @ngdoc service - * @name $httpBackend - * @description - * Fake HTTP backend implementation suitable for unit testing applications that use the - * {@link ng.$http $http service}. - * - * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less - * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}. - * - * During unit testing, we want our unit tests to run quickly and have no external dependencies so - * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or - * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is - * to verify whether a certain request has been sent or not, or alternatively just let the - * application make requests, respond with pre-trained responses and assert that the end result is - * what we expect it to be. - * - * This mock implementation can be used to respond with static or dynamic responses via the - * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc). - * - * When an Angular application needs some data from a server, it calls the $http service, which - * sends the request to a real server using $httpBackend service. With dependency injection, it is - * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify - * the requests and respond with some testing data without sending a request to a real server. - * - * There are two ways to specify what test data should be returned as http responses by the mock - * backend when the code under test makes http requests: - * - * - `$httpBackend.expect` - specifies a request expectation - * - `$httpBackend.when` - specifies a backend definition - * - * - * ## Request Expectations vs Backend Definitions - * - * Request expectations provide a way to make assertions about requests made by the application and - * to define responses for those requests. The test will fail if the expected requests are not made - * or they are made in the wrong order. - * - * Backend definitions allow you to define a fake backend for your application which doesn't assert - * if a particular request was made or not, it just returns a trained response if a request is made. - * The test will pass whether or not the request gets made during testing. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Request expectationsBackend definitions
Syntax.expect(...).respond(...).when(...).respond(...)
Typical usagestrict unit testsloose (black-box) unit testing
Fulfills multiple requestsNOYES
Order of requests mattersYESNO
Request requiredYESNO
Response requiredoptional (see below)YES
- * - * In cases where both backend definitions and request expectations are specified during unit - * testing, the request expectations are evaluated first. - * - * If a request expectation has no response specified, the algorithm will search your backend - * definitions for an appropriate response. - * - * If a request didn't match any expectation or if the expectation doesn't have the response - * defined, the backend definitions are evaluated in sequential order to see if any of them match - * the request. The response from the first matched definition is returned. - * - * - * ## Flushing HTTP requests - * - * The $httpBackend used in production always responds to requests asynchronously. If we preserved - * this behavior in unit testing, we'd have to create async unit tests, which are hard to write, - * to follow and to maintain. But neither can the testing mock respond synchronously; that would - * change the execution of the code under test. For this reason, the mock $httpBackend has a - * `flush()` method, which allows the test to explicitly flush pending requests. This preserves - * the async api of the backend, while allowing the test to execute synchronously. - * - * - * ## Unit testing with mock $httpBackend - * The following code shows how to setup and use the mock backend when unit testing a controller. - * First we create the controller under test: - * - ```js - // The module code - angular - .module('MyApp', []) - .controller('MyController', MyController); - - // The controller code - function MyController($scope, $http) { - var authToken; - - $http.get('/auth.py').then(function(response) { - authToken = response.headers('A-Token'); - $scope.user = response.data; - }); - - $scope.saveMessage = function(message) { - var headers = { 'Authorization': authToken }; - $scope.status = 'Saving...'; - - $http.post('/add-msg.py', message, { headers: headers } ).then(function(response) { - $scope.status = ''; - }).catch(function() { - $scope.status = 'Failed...'; - }); - }; - } - ``` - * - * Now we setup the mock backend and create the test specs: - * - ```js - // testing controller - describe('MyController', function() { - var $httpBackend, $rootScope, createController, authRequestHandler; - - // Set up the module - beforeEach(module('MyApp')); - - beforeEach(inject(function($injector) { - // Set up the mock http service responses - $httpBackend = $injector.get('$httpBackend'); - // backend definition common for all tests - authRequestHandler = $httpBackend.when('GET', '/auth.py') - .respond({userId: 'userX'}, {'A-Token': 'xxx'}); - - // Get hold of a scope (i.e. the root scope) - $rootScope = $injector.get('$rootScope'); - // The $controller service is used to create instances of controllers - var $controller = $injector.get('$controller'); - - createController = function() { - return $controller('MyController', {'$scope' : $rootScope }); - }; - })); - - - afterEach(function() { - $httpBackend.verifyNoOutstandingExpectation(); - $httpBackend.verifyNoOutstandingRequest(); - }); - - - it('should fetch authentication token', function() { - $httpBackend.expectGET('/auth.py'); - var controller = createController(); - $httpBackend.flush(); - }); - - - it('should fail authentication', function() { - - // Notice how you can change the response even after it was set - authRequestHandler.respond(401, ''); - - $httpBackend.expectGET('/auth.py'); - var controller = createController(); - $httpBackend.flush(); - expect($rootScope.status).toBe('Failed...'); - }); - - - it('should send msg to server', function() { - var controller = createController(); - $httpBackend.flush(); - - // now you don’t care about the authentication, but - // the controller will still send the request and - // $httpBackend will respond without you having to - // specify the expectation and response for this request - - $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, ''); - $rootScope.saveMessage('message content'); - expect($rootScope.status).toBe('Saving...'); - $httpBackend.flush(); - expect($rootScope.status).toBe(''); - }); - - - it('should send auth header', function() { - var controller = createController(); - $httpBackend.flush(); - - $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) { - // check if the header was sent, if it wasn't the expectation won't - // match the request and the test will fail - return headers['Authorization'] == 'xxx'; - }).respond(201, ''); - - $rootScope.saveMessage('whatever'); - $httpBackend.flush(); - }); - }); - ``` - * - * ## Dynamic responses - * - * You define a response to a request by chaining a call to `respond()` onto a definition or expectation. - * If you provide a **callback** as the first parameter to `respond(callback)` then you can dynamically generate - * a response based on the properties of the request. - * - * The `callback` function should be of the form `function(method, url, data, headers, params)`. - * - * ### Query parameters - * - * By default, query parameters on request URLs are parsed into the `params` object. So a request URL - * of `/list?q=searchstr&orderby=-name` would set `params` to be `{q: 'searchstr', orderby: '-name'}`. - * - * ### Regex parameter matching - * - * If an expectation or definition uses a **regex** to match the URL, you can provide an array of **keys** via a - * `params` argument. The index of each **key** in the array will match the index of a **group** in the - * **regex**. - * - * The `params` object in the **callback** will now have properties with these keys, which hold the value of the - * corresponding **group** in the **regex**. - * - * This also applies to the `when` and `expect` shortcut methods. - * - * - * ```js - * $httpBackend.expect('GET', /\/user\/(.+)/, undefined, undefined, ['id']) - * .respond(function(method, url, data, headers, params) { - * // for requested url of '/user/1234' params is {id: '1234'} - * }); - * - * $httpBackend.whenPATCH(/\/user\/(.+)\/article\/(.+)/, undefined, undefined, ['user', 'article']) - * .respond(function(method, url, data, headers, params) { - * // for url of '/user/1234/article/567' params is {user: '1234', article: '567'} - * }); - * ``` - * - * ## Matching route requests - * - * For extra convenience, `whenRoute` and `expectRoute` shortcuts are available. These methods offer colon - * delimited matching of the url path, ignoring the query string. This allows declarations - * similar to how application routes are configured with `$routeProvider`. Because these methods convert - * the definition url to regex, declaration order is important. Combined with query parameter parsing, - * the following is possible: - * - ```js - $httpBackend.whenRoute('GET', '/users/:id') - .respond(function(method, url, data, headers, params) { - return [200, MockUserList[Number(params.id)]]; - }); - - $httpBackend.whenRoute('GET', '/users') - .respond(function(method, url, data, headers, params) { - var userList = angular.copy(MockUserList), - defaultSort = 'lastName', - count, pages, isPrevious, isNext; - - // paged api response '/v1/users?page=2' - params.page = Number(params.page) || 1; - - // query for last names '/v1/users?q=Archer' - if (params.q) { - userList = $filter('filter')({lastName: params.q}); - } - - pages = Math.ceil(userList.length / pagingLength); - isPrevious = params.page > 1; - isNext = params.page < pages; - - return [200, { - count: userList.length, - previous: isPrevious, - next: isNext, - // sort field -> '/v1/users?sortBy=firstName' - results: $filter('orderBy')(userList, params.sortBy || defaultSort) - .splice((params.page - 1) * pagingLength, pagingLength) - }]; - }); - ``` - */ -angular.mock.$HttpBackendProvider = function() { - this.$get = ['$rootScope', '$timeout', createHttpBackendMock]; -}; - -/** - * General factory function for $httpBackend mock. - * Returns instance for unit testing (when no arguments specified): - * - passing through is disabled - * - auto flushing is disabled - * - * Returns instance for e2e testing (when `$delegate` and `$browser` specified): - * - passing through (delegating request to real backend) is enabled - * - auto flushing is enabled - * - * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified) - * @param {Object=} $browser Auto-flushing enabled if specified - * @return {Object} Instance of $httpBackend mock - */ -function createHttpBackendMock($rootScope, $timeout, $delegate, $browser) { - var definitions = [], - expectations = [], - responses = [], - responsesPush = angular.bind(responses, responses.push), - copy = angular.copy; - - function createResponse(status, data, headers, statusText) { - if (angular.isFunction(status)) return status; - - return function() { - return angular.isNumber(status) - ? [status, data, headers, statusText] - : [200, status, data, headers]; - }; - } - - // TODO(vojta): change params to: method, url, data, headers, callback - function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) { - var xhr = new MockXhr(), - expectation = expectations[0], - wasExpected = false; - - function prettyPrint(data) { - return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp) - ? data - : angular.toJson(data); - } - - function wrapResponse(wrapped) { - if (!$browser && timeout) { - timeout.then ? timeout.then(handleTimeout) : $timeout(handleTimeout, timeout); - } - - return handleResponse; - - function handleResponse() { - var response = wrapped.response(method, url, data, headers, wrapped.params(url)); - xhr.$$respHeaders = response[2]; - callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(), - copy(response[3] || '')); - } - - function handleTimeout() { - for (var i = 0, ii = responses.length; i < ii; i++) { - if (responses[i] === handleResponse) { - responses.splice(i, 1); - callback(-1, undefined, ''); - break; - } - } - } - } - - if (expectation && expectation.match(method, url)) { - if (!expectation.matchData(data)) { - throw new Error('Expected ' + expectation + ' with different data\n' + - 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data); - } - - if (!expectation.matchHeaders(headers)) { - throw new Error('Expected ' + expectation + ' with different headers\n' + - 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' + - prettyPrint(headers)); - } - - expectations.shift(); - - if (expectation.response) { - responses.push(wrapResponse(expectation)); - return; - } - wasExpected = true; - } - - var i = -1, definition; - while ((definition = definitions[++i])) { - if (definition.match(method, url, data, headers || {})) { - if (definition.response) { - // if $browser specified, we do auto flush all requests - ($browser ? $browser.defer : responsesPush)(wrapResponse(definition)); - } else if (definition.passThrough) { - $delegate(method, url, data, callback, headers, timeout, withCredentials); - } else throw new Error('No response defined !'); - return; - } - } - throw wasExpected ? - new Error('No response defined !') : - new Error('Unexpected request: ' + method + ' ' + url + '\n' + - (expectation ? 'Expected ' + expectation : 'No more request expected')); - } - - /** - * @ngdoc method - * @name $httpBackend#when - * @description - * Creates a new backend definition. - * - * @param {string} method HTTP method. - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives - * data string and returns true if the data is as expected. - * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header - * object and returns true if the headers match the current definition. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. - * - * - respond – - * `{function([status,] data[, headers, statusText]) - * | function(function(method, url, data, headers, params)}` - * – The respond method takes a set of static data to be returned or a function that can - * return an array containing response status (number), response data (string), response - * headers (Object), and the text for the status (string). The respond method returns the - * `requestHandler` object for possible overrides. - */ - $httpBackend.when = function(method, url, data, headers, keys) { - var definition = new MockHttpExpectation(method, url, data, headers, keys), - chain = { - respond: function(status, data, headers, statusText) { - definition.passThrough = undefined; - definition.response = createResponse(status, data, headers, statusText); - return chain; - } - }; - - if ($browser) { - chain.passThrough = function() { - definition.response = undefined; - definition.passThrough = true; - return chain; - }; - } - - definitions.push(definition); - return chain; - }; - - /** - * @ngdoc method - * @name $httpBackend#whenGET - * @description - * Creates a new backend definition for GET requests. For more info see `when()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(Object|function(Object))=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. - */ - - /** - * @ngdoc method - * @name $httpBackend#whenHEAD - * @description - * Creates a new backend definition for HEAD requests. For more info see `when()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(Object|function(Object))=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. - */ - - /** - * @ngdoc method - * @name $httpBackend#whenDELETE - * @description - * Creates a new backend definition for DELETE requests. For more info see `when()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(Object|function(Object))=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. - */ - - /** - * @ngdoc method - * @name $httpBackend#whenPOST - * @description - * Creates a new backend definition for POST requests. For more info see `when()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives - * data string and returns true if the data is as expected. - * @param {(Object|function(Object))=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. - */ - - /** - * @ngdoc method - * @name $httpBackend#whenPUT - * @description - * Creates a new backend definition for PUT requests. For more info see `when()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives - * data string and returns true if the data is as expected. - * @param {(Object|function(Object))=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. - */ - - /** - * @ngdoc method - * @name $httpBackend#whenJSONP - * @description - * Creates a new backend definition for JSONP requests. For more info see `when()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. - */ - createShortMethods('when'); - - /** - * @ngdoc method - * @name $httpBackend#whenRoute - * @description - * Creates a new backend definition that compares only with the requested route. - * - * @param {string} method HTTP method. - * @param {string} url HTTP url string that supports colon param matching. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. See #when for more info. - */ - $httpBackend.whenRoute = function(method, url) { - var pathObj = parseRoute(url); - return $httpBackend.when(method, pathObj.regexp, undefined, undefined, pathObj.keys); - }; - - function parseRoute(url) { - var ret = { - regexp: url - }, - keys = ret.keys = []; - - if (!url || !angular.isString(url)) return ret; - - url = url - .replace(/([().])/g, '\\$1') - .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option) { - var optional = option === '?' ? option : null; - var star = option === '*' ? option : null; - keys.push({ name: key, optional: !!optional }); - slash = slash || ''; - return '' - + (optional ? '' : slash) - + '(?:' - + (optional ? slash : '') - + (star && '(.+?)' || '([^/]+)') - + (optional || '') - + ')' - + (optional || ''); - }) - .replace(/([\/$\*])/g, '\\$1'); - - ret.regexp = new RegExp('^' + url, 'i'); - return ret; - } - - /** - * @ngdoc method - * @name $httpBackend#expect - * @description - * Creates a new request expectation. - * - * @param {string} method HTTP method. - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that - * receives data string and returns true if the data is as expected, or Object if request body - * is in JSON format. - * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header - * object and returns true if the headers match the current expectation. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. - * - * - respond – - * `{function([status,] data[, headers, statusText]) - * | function(function(method, url, data, headers, params)}` - * – The respond method takes a set of static data to be returned or a function that can - * return an array containing response status (number), response data (string), response - * headers (Object), and the text for the status (string). The respond method returns the - * `requestHandler` object for possible overrides. - */ - $httpBackend.expect = function(method, url, data, headers, keys) { - var expectation = new MockHttpExpectation(method, url, data, headers, keys), - chain = { - respond: function(status, data, headers, statusText) { - expectation.response = createResponse(status, data, headers, statusText); - return chain; - } - }; - - expectations.push(expectation); - return chain; - }; - - /** - * @ngdoc method - * @name $httpBackend#expectGET - * @description - * Creates a new request expectation for GET requests. For more info see `expect()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {Object=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. See #expect for more info. - */ - - /** - * @ngdoc method - * @name $httpBackend#expectHEAD - * @description - * Creates a new request expectation for HEAD requests. For more info see `expect()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {Object=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. - */ - - /** - * @ngdoc method - * @name $httpBackend#expectDELETE - * @description - * Creates a new request expectation for DELETE requests. For more info see `expect()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {Object=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. - */ - - /** - * @ngdoc method - * @name $httpBackend#expectPOST - * @description - * Creates a new request expectation for POST requests. For more info see `expect()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that - * receives data string and returns true if the data is as expected, or Object if request body - * is in JSON format. - * @param {Object=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. - */ - - /** - * @ngdoc method - * @name $httpBackend#expectPUT - * @description - * Creates a new request expectation for PUT requests. For more info see `expect()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that - * receives data string and returns true if the data is as expected, or Object if request body - * is in JSON format. - * @param {Object=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. - */ - - /** - * @ngdoc method - * @name $httpBackend#expectPATCH - * @description - * Creates a new request expectation for PATCH requests. For more info see `expect()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that - * receives data string and returns true if the data is as expected, or Object if request body - * is in JSON format. - * @param {Object=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. - */ - - /** - * @ngdoc method - * @name $httpBackend#expectJSONP - * @description - * Creates a new request expectation for JSONP requests. For more info see `expect()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives an url - * and returns true if the url matches the current definition. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. - */ - createShortMethods('expect'); - - /** - * @ngdoc method - * @name $httpBackend#expectRoute - * @description - * Creates a new request expectation that compares only with the requested route. - * - * @param {string} method HTTP method. - * @param {string} url HTTP url string that supports colon param matching. - * @returns {requestHandler} Returns an object with `respond` method that controls how a matched - * request is handled. You can save this object for later use and invoke `respond` again in - * order to change how a matched request is handled. See #expect for more info. - */ - $httpBackend.expectRoute = function(method, url) { - var pathObj = parseRoute(url); - return $httpBackend.expect(method, pathObj.regexp, undefined, undefined, pathObj.keys); - }; - - - /** - * @ngdoc method - * @name $httpBackend#flush - * @description - * Flushes all pending requests using the trained responses. - * - * @param {number=} count Number of responses to flush (in the order they arrived). If undefined, - * all pending requests will be flushed. If there are no pending requests when the flush method - * is called an exception is thrown (as this typically a sign of programming error). - */ - $httpBackend.flush = function(count, digest) { - if (digest !== false) $rootScope.$digest(); - if (!responses.length) throw new Error('No pending request to flush !'); - - if (angular.isDefined(count) && count !== null) { - while (count--) { - if (!responses.length) throw new Error('No more pending request to flush !'); - responses.shift()(); - } - } else { - while (responses.length) { - responses.shift()(); - } - } - $httpBackend.verifyNoOutstandingExpectation(digest); - }; - - - /** - * @ngdoc method - * @name $httpBackend#verifyNoOutstandingExpectation - * @description - * Verifies that all of the requests defined via the `expect` api were made. If any of the - * requests were not made, verifyNoOutstandingExpectation throws an exception. - * - * Typically, you would call this method following each test case that asserts requests using an - * "afterEach" clause. - * - * ```js - * afterEach($httpBackend.verifyNoOutstandingExpectation); - * ``` - */ - $httpBackend.verifyNoOutstandingExpectation = function(digest) { - if (digest !== false) $rootScope.$digest(); - if (expectations.length) { - throw new Error('Unsatisfied requests: ' + expectations.join(', ')); - } - }; - - - /** - * @ngdoc method - * @name $httpBackend#verifyNoOutstandingRequest - * @description - * Verifies that there are no outstanding requests that need to be flushed. - * - * Typically, you would call this method following each test case that asserts requests using an - * "afterEach" clause. - * - * ```js - * afterEach($httpBackend.verifyNoOutstandingRequest); - * ``` - */ - $httpBackend.verifyNoOutstandingRequest = function() { - if (responses.length) { - throw new Error('Unflushed requests: ' + responses.length); - } - }; - - - /** - * @ngdoc method - * @name $httpBackend#resetExpectations - * @description - * Resets all request expectations, but preserves all backend definitions. Typically, you would - * call resetExpectations during a multiple-phase test when you want to reuse the same instance of - * $httpBackend mock. - */ - $httpBackend.resetExpectations = function() { - expectations.length = 0; - responses.length = 0; - }; - - return $httpBackend; - - - function createShortMethods(prefix) { - angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) { - $httpBackend[prefix + method] = function(url, headers, keys) { - return $httpBackend[prefix](method, url, undefined, headers, keys); - }; - }); - - angular.forEach(['PUT', 'POST', 'PATCH'], function(method) { - $httpBackend[prefix + method] = function(url, data, headers, keys) { - return $httpBackend[prefix](method, url, data, headers, keys); - }; - }); - } -} - -function MockHttpExpectation(method, url, data, headers, keys) { - - this.data = data; - this.headers = headers; - - this.match = function(m, u, d, h) { - if (method != m) return false; - if (!this.matchUrl(u)) return false; - if (angular.isDefined(d) && !this.matchData(d)) return false; - if (angular.isDefined(h) && !this.matchHeaders(h)) return false; - return true; - }; - - this.matchUrl = function(u) { - if (!url) return true; - if (angular.isFunction(url.test)) return url.test(u); - if (angular.isFunction(url)) return url(u); - return url == u; - }; - - this.matchHeaders = function(h) { - if (angular.isUndefined(headers)) return true; - if (angular.isFunction(headers)) return headers(h); - return angular.equals(headers, h); - }; - - this.matchData = function(d) { - if (angular.isUndefined(data)) return true; - if (data && angular.isFunction(data.test)) return data.test(d); - if (data && angular.isFunction(data)) return data(d); - if (data && !angular.isString(data)) { - return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d)); - } - return data == d; - }; - - this.toString = function() { - return method + ' ' + url; - }; - - this.params = function(u) { - return angular.extend(parseQuery(), pathParams()); - - function pathParams() { - var keyObj = {}; - if (!url || !angular.isFunction(url.test) || !keys || keys.length === 0) return keyObj; - - var m = url.exec(u); - if (!m) return keyObj; - for (var i = 1, len = m.length; i < len; ++i) { - var key = keys[i - 1]; - var val = m[i]; - if (key && val) { - keyObj[key.name || key] = val; - } - } - - return keyObj; - } - - function parseQuery() { - var obj = {}, key_value, key, - queryStr = u.indexOf('?') > -1 - ? u.substring(u.indexOf('?') + 1) - : ""; - - angular.forEach(queryStr.split('&'), function(keyValue) { - if (keyValue) { - key_value = keyValue.replace(/\+/g,'%20').split('='); - key = tryDecodeURIComponent(key_value[0]); - if (angular.isDefined(key)) { - var val = angular.isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; - if (!hasOwnProperty.call(obj, key)) { - obj[key] = val; - } else if (angular.isArray(obj[key])) { - obj[key].push(val); - } else { - obj[key] = [obj[key],val]; - } - } - } - }); - return obj; - } - function tryDecodeURIComponent(value) { - try { - return decodeURIComponent(value); - } catch (e) { - // Ignore any invalid uri component - } - } - }; -} - -function createMockXhr() { - return new MockXhr(); -} - -function MockXhr() { - - // hack for testing $http, $httpBackend - MockXhr.$$lastInstance = this; - - this.open = function(method, url, async) { - this.$$method = method; - this.$$url = url; - this.$$async = async; - this.$$reqHeaders = {}; - this.$$respHeaders = {}; - }; - - this.send = function(data) { - this.$$data = data; - }; - - this.setRequestHeader = function(key, value) { - this.$$reqHeaders[key] = value; - }; - - this.getResponseHeader = function(name) { - // the lookup must be case insensitive, - // that's why we try two quick lookups first and full scan last - var header = this.$$respHeaders[name]; - if (header) return header; - - name = angular.lowercase(name); - header = this.$$respHeaders[name]; - if (header) return header; - - header = undefined; - angular.forEach(this.$$respHeaders, function(headerVal, headerName) { - if (!header && angular.lowercase(headerName) == name) header = headerVal; - }); - return header; - }; - - this.getAllResponseHeaders = function() { - var lines = []; - - angular.forEach(this.$$respHeaders, function(value, key) { - lines.push(key + ': ' + value); - }); - return lines.join('\n'); - }; - - this.abort = angular.noop; -} - - -/** - * @ngdoc service - * @name $timeout - * @description - * - * This service is just a simple decorator for {@link ng.$timeout $timeout} service - * that adds a "flush" and "verifyNoPendingTasks" methods. - */ - -angular.mock.$TimeoutDecorator = ['$delegate', '$browser', function($delegate, $browser) { - - /** - * @ngdoc method - * @name $timeout#flush - * @description - * - * Flushes the queue of pending tasks. - * - * @param {number=} delay maximum timeout amount to flush up until - */ - $delegate.flush = function(delay) { - $browser.defer.flush(delay); - }; - - /** - * @ngdoc method - * @name $timeout#verifyNoPendingTasks - * @description - * - * Verifies that there are no pending tasks that need to be flushed. - */ - $delegate.verifyNoPendingTasks = function() { - if ($browser.deferredFns.length) { - throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' + - formatPendingTasksAsString($browser.deferredFns)); - } - }; - - function formatPendingTasksAsString(tasks) { - var result = []; - angular.forEach(tasks, function(task) { - result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}'); - }); - - return result.join(', '); - } - - return $delegate; -}]; - -angular.mock.$RAFDecorator = ['$delegate', function($delegate) { - var rafFn = function(fn) { - var index = rafFn.queue.length; - rafFn.queue.push(fn); - return function() { - rafFn.queue.splice(index, 1); - }; - }; - - rafFn.queue = []; - rafFn.supported = $delegate.supported; - - rafFn.flush = function() { - if (rafFn.queue.length === 0) { - throw new Error('No rAF callbacks present'); - } - - var length = rafFn.queue.length; - for (var i = 0; i < length; i++) { - rafFn.queue[i](); - } - - rafFn.queue = rafFn.queue.slice(i); - }; - - return rafFn; -}]; - -/** - * - */ -angular.mock.$RootElementProvider = function() { - this.$get = function() { - return angular.element('
'); - }; -}; - -/** - * @ngdoc service - * @name $controller - * @description - * A decorator for {@link ng.$controller} with additional `bindings` parameter, useful when testing - * controllers of directives that use {@link $compile#-bindtocontroller- `bindToController`}. - * - * - * ## Example - * - * ```js - * - * // Directive definition ... - * - * myMod.directive('myDirective', { - * controller: 'MyDirectiveController', - * bindToController: { - * name: '@' - * } - * }); - * - * - * // Controller definition ... - * - * myMod.controller('MyDirectiveController', ['$log', function($log) { - * $log.info(this.name); - * })]; - * - * - * // In a test ... - * - * describe('myDirectiveController', function() { - * it('should write the bound name to the log', inject(function($controller, $log) { - * var ctrl = $controller('MyDirectiveController', { /* no locals */ }, { name: 'Clark Kent' }); - * expect(ctrl.name).toEqual('Clark Kent'); - * expect($log.info.logs).toEqual(['Clark Kent']); - * }); - * }); - * - * ``` - * - * @param {Function|string} constructor If called with a function then it's considered to be the - * controller constructor function. Otherwise it's considered to be a string which is used - * to retrieve the controller constructor using the following steps: - * - * * check if a controller with given name is registered via `$controllerProvider` - * * check if evaluating the string on the current scope returns a constructor - * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global - * `window` object (not recommended) - * - * The string can use the `controller as property` syntax, where the controller instance is published - * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this - * to work correctly. - * - * @param {Object} locals Injection locals for Controller. - * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used - * to simulate the `bindToController` feature and simplify certain kinds of tests. - * @return {Object} Instance of given controller. - */ -angular.mock.$ControllerDecorator = ['$delegate', function($delegate) { - return function(expression, locals, later, ident) { - if (later && typeof later === 'object') { - var create = $delegate(expression, locals, true, ident); - angular.extend(create.instance, later); - return create(); - } - return $delegate(expression, locals, later, ident); - }; -}]; - -/** - * @ngdoc service - * @name $componentController - * @description - * A service that can be used to create instances of component controllers. - *
- * Be aware that the controller will be instantiated and attached to the scope as specified in - * the component definition object. That means that you must always provide a `$scope` object - * in the `locals` param. - *
- * @param {string} componentName the name of the component whose controller we want to instantiate - * @param {Object} locals Injection locals for Controller. - * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used - * to simulate the `bindToController` feature and simplify certain kinds of tests. - * @param {string=} ident Override the property name to use when attaching the controller to the scope. - * @return {Object} Instance of requested controller. - */ -angular.mock.$ComponentControllerProvider = ['$compileProvider', function($compileProvider) { - return { - $get: ['$controller','$injector', function($controller,$injector) { - return function $componentController(componentName, locals, bindings, ident) { - // get all directives associated to the component name - var directives = $injector.get(componentName + 'Directive'); - // look for those directives that are components - var candidateDirectives = directives.filter(function(directiveInfo) { - // components have controller, controllerAs and restrict:'E' - return directiveInfo.controller && directiveInfo.controllerAs && directiveInfo.restrict === 'E'; - }); - // check if valid directives found - if (candidateDirectives.length === 0) { - throw new Error('No component found'); - } - if (candidateDirectives.length > 1) { - throw new Error('Too many components found'); - } - // get the info of the component - var directiveInfo = candidateDirectives[0]; - return $controller(directiveInfo.controller, locals, bindings, ident || directiveInfo.controllerAs); - }; - }] - }; -}]; - - -/** - * @ngdoc module - * @name ngMock - * @packageName angular-mocks - * @description - * - * # ngMock - * - * The `ngMock` module provides support to inject and mock Angular services into unit tests. - * In addition, ngMock also extends various core ng services such that they can be - * inspected and controlled in a synchronous manner within test code. - * - * - *
- * - */ -angular.module('ngMock', ['ng']).provider({ - $browser: angular.mock.$BrowserProvider, - $exceptionHandler: angular.mock.$ExceptionHandlerProvider, - $log: angular.mock.$LogProvider, - $interval: angular.mock.$IntervalProvider, - $httpBackend: angular.mock.$HttpBackendProvider, - $rootElement: angular.mock.$RootElementProvider, - $componentController: angular.mock.$ComponentControllerProvider -}).config(['$provide', function($provide) { - $provide.decorator('$timeout', angular.mock.$TimeoutDecorator); - $provide.decorator('$$rAF', angular.mock.$RAFDecorator); - $provide.decorator('$rootScope', angular.mock.$RootScopeDecorator); - $provide.decorator('$controller', angular.mock.$ControllerDecorator); -}]); - -/** - * @ngdoc module - * @name ngMockE2E - * @module ngMockE2E - * @packageName angular-mocks - * @description - * - * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing. - * Currently there is only one mock present in this module - - * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock. - */ -angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) { - $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator); -}]); - -/** - * @ngdoc service - * @name $httpBackend - * @module ngMockE2E - * @description - * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of - * applications that use the {@link ng.$http $http service}. - * - * *Note*: For fake http backend implementation suitable for unit testing please see - * {@link ngMock.$httpBackend unit-testing $httpBackend mock}. - * - * This implementation can be used to respond with static or dynamic responses via the `when` api - * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the - * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch - * templates from a webserver). - * - * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application - * is being developed with the real backend api replaced with a mock, it is often desirable for - * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch - * templates or static files from the webserver). To configure the backend with this behavior - * use the `passThrough` request handler of `when` instead of `respond`. - * - * Additionally, we don't want to manually have to flush mocked out requests like we do during unit - * testing. For this reason the e2e $httpBackend flushes mocked out requests - * automatically, closely simulating the behavior of the XMLHttpRequest object. - * - * To setup the application to run with this http backend, you have to create a module that depends - * on the `ngMockE2E` and your application modules and defines the fake backend: - * - * ```js - * myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']); - * myAppDev.run(function($httpBackend) { - * phones = [{name: 'phone1'}, {name: 'phone2'}]; - * - * // returns the current list of phones - * $httpBackend.whenGET('/phones').respond(phones); - * - * // adds a new phone to the phones array - * $httpBackend.whenPOST('/phones').respond(function(method, url, data) { - * var phone = angular.fromJson(data); - * phones.push(phone); - * return [200, phone, {}]; - * }); - * $httpBackend.whenGET(/^\/templates\//).passThrough(); - * //... - * }); - * ``` - * - * Afterwards, bootstrap your app with this new module. - */ - -/** - * @ngdoc method - * @name $httpBackend#when - * @module ngMockE2E - * @description - * Creates a new backend definition. - * - * @param {string} method HTTP method. - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(string|RegExp)=} data HTTP request body. - * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header - * object and returns true if the headers match the current definition. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on - * {@link ngMock.$httpBackend $httpBackend mock}. - * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that - * control how a matched request is handled. You can save this object for later use and invoke - * `respond` or `passThrough` again in order to change how a matched request is handled. - * - * - respond – - * `{function([status,] data[, headers, statusText]) - * | function(function(method, url, data, headers, params)}` - * – The respond method takes a set of static data to be returned or a function that can return - * an array containing response status (number), response data (string), response headers - * (Object), and the text for the status (string). - * - passThrough – `{function()}` – Any request matching a backend definition with - * `passThrough` handler will be passed through to the real backend (an XHR request will be made - * to the server.) - * - Both methods return the `requestHandler` object for possible overrides. - */ - -/** - * @ngdoc method - * @name $httpBackend#whenGET - * @module ngMockE2E - * @description - * Creates a new backend definition for GET requests. For more info see `when()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(Object|function(Object))=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on - * {@link ngMock.$httpBackend $httpBackend mock}. - * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that - * control how a matched request is handled. You can save this object for later use and invoke - * `respond` or `passThrough` again in order to change how a matched request is handled. - */ - -/** - * @ngdoc method - * @name $httpBackend#whenHEAD - * @module ngMockE2E - * @description - * Creates a new backend definition for HEAD requests. For more info see `when()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(Object|function(Object))=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on - * {@link ngMock.$httpBackend $httpBackend mock}. - * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that - * control how a matched request is handled. You can save this object for later use and invoke - * `respond` or `passThrough` again in order to change how a matched request is handled. - */ - -/** - * @ngdoc method - * @name $httpBackend#whenDELETE - * @module ngMockE2E - * @description - * Creates a new backend definition for DELETE requests. For more info see `when()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(Object|function(Object))=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on - * {@link ngMock.$httpBackend $httpBackend mock}. - * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that - * control how a matched request is handled. You can save this object for later use and invoke - * `respond` or `passThrough` again in order to change how a matched request is handled. - */ - -/** - * @ngdoc method - * @name $httpBackend#whenPOST - * @module ngMockE2E - * @description - * Creates a new backend definition for POST requests. For more info see `when()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(string|RegExp)=} data HTTP request body. - * @param {(Object|function(Object))=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on - * {@link ngMock.$httpBackend $httpBackend mock}. - * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that - * control how a matched request is handled. You can save this object for later use and invoke - * `respond` or `passThrough` again in order to change how a matched request is handled. - */ - -/** - * @ngdoc method - * @name $httpBackend#whenPUT - * @module ngMockE2E - * @description - * Creates a new backend definition for PUT requests. For more info see `when()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(string|RegExp)=} data HTTP request body. - * @param {(Object|function(Object))=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on - * {@link ngMock.$httpBackend $httpBackend mock}. - * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that - * control how a matched request is handled. You can save this object for later use and invoke - * `respond` or `passThrough` again in order to change how a matched request is handled. - */ - -/** - * @ngdoc method - * @name $httpBackend#whenPATCH - * @module ngMockE2E - * @description - * Creates a new backend definition for PATCH requests. For more info see `when()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(string|RegExp)=} data HTTP request body. - * @param {(Object|function(Object))=} headers HTTP headers. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on - * {@link ngMock.$httpBackend $httpBackend mock}. - * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that - * control how a matched request is handled. You can save this object for later use and invoke - * `respond` or `passThrough` again in order to change how a matched request is handled. - */ - -/** - * @ngdoc method - * @name $httpBackend#whenJSONP - * @module ngMockE2E - * @description - * Creates a new backend definition for JSONP requests. For more info see `when()`. - * - * @param {string|RegExp|function(string)} url HTTP url or function that receives a url - * and returns true if the url matches the current definition. - * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on - * {@link ngMock.$httpBackend $httpBackend mock}. - * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that - * control how a matched request is handled. You can save this object for later use and invoke - * `respond` or `passThrough` again in order to change how a matched request is handled. - */ -/** - * @ngdoc method - * @name $httpBackend#whenRoute - * @module ngMockE2E - * @description - * Creates a new backend definition that compares only with the requested route. - * - * @param {string} method HTTP method. - * @param {string} url HTTP url string that supports colon param matching. - * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that - * control how a matched request is handled. You can save this object for later use and invoke - * `respond` or `passThrough` again in order to change how a matched request is handled. - */ -angular.mock.e2e = {}; -angular.mock.e2e.$httpBackendDecorator = - ['$rootScope', '$timeout', '$delegate', '$browser', createHttpBackendMock]; - - -/** - * @ngdoc type - * @name $rootScope.Scope - * @module ngMock - * @description - * {@link ng.$rootScope.Scope Scope} type decorated with helper methods useful for testing. These - * methods are automatically available on any {@link ng.$rootScope.Scope Scope} instance when - * `ngMock` module is loaded. - * - * In addition to all the regular `Scope` methods, the following helper methods are available: - */ -angular.mock.$RootScopeDecorator = ['$delegate', function($delegate) { - - var $rootScopePrototype = Object.getPrototypeOf($delegate); - - $rootScopePrototype.$countChildScopes = countChildScopes; - $rootScopePrototype.$countWatchers = countWatchers; - - return $delegate; - - // ------------------------------------------------------------------------------------------ // - - /** - * @ngdoc method - * @name $rootScope.Scope#$countChildScopes - * @module ngMock - * @description - * Counts all the direct and indirect child scopes of the current scope. - * - * The current scope is excluded from the count. The count includes all isolate child scopes. - * - * @returns {number} Total number of child scopes. - */ - function countChildScopes() { - // jshint validthis: true - var count = 0; // exclude the current scope - var pendingChildHeads = [this.$$childHead]; - var currentScope; - - while (pendingChildHeads.length) { - currentScope = pendingChildHeads.shift(); - - while (currentScope) { - count += 1; - pendingChildHeads.push(currentScope.$$childHead); - currentScope = currentScope.$$nextSibling; - } - } - - return count; - } - - - /** - * @ngdoc method - * @name $rootScope.Scope#$countWatchers - * @module ngMock - * @description - * Counts all the watchers of direct and indirect child scopes of the current scope. - * - * The watchers of the current scope are included in the count and so are all the watchers of - * isolate child scopes. - * - * @returns {number} Total number of watchers. - */ - function countWatchers() { - // jshint validthis: true - var count = this.$$watchers ? this.$$watchers.length : 0; // include the current scope - var pendingChildHeads = [this.$$childHead]; - var currentScope; - - while (pendingChildHeads.length) { - currentScope = pendingChildHeads.shift(); - - while (currentScope) { - count += currentScope.$$watchers ? currentScope.$$watchers.length : 0; - pendingChildHeads.push(currentScope.$$childHead); - currentScope = currentScope.$$nextSibling; - } - } - - return count; - } -}]; - - -if (window.jasmine || window.mocha) { - - var currentSpec = null, - annotatedFunctions = [], - isSpecRunning = function() { - return !!currentSpec; - }; - - angular.mock.$$annotate = angular.injector.$$annotate; - angular.injector.$$annotate = function(fn) { - if (typeof fn === 'function' && !fn.$inject) { - annotatedFunctions.push(fn); - } - return angular.mock.$$annotate.apply(this, arguments); - }; - - - (window.beforeEach || window.setup)(function() { - annotatedFunctions = []; - currentSpec = this; - }); - - (window.afterEach || window.teardown)(function() { - var injector = currentSpec.$injector; - - annotatedFunctions.forEach(function(fn) { - delete fn.$inject; - }); - - angular.forEach(currentSpec.$modules, function(module) { - if (module && module.$$hashKey) { - module.$$hashKey = undefined; - } - }); - - currentSpec.$injector = null; - currentSpec.$modules = null; - currentSpec.$providerInjector = null; - currentSpec = null; - - if (injector) { - injector.get('$rootElement').off(); - injector.get('$rootScope').$destroy(); - } - - // clean up jquery's fragment cache - angular.forEach(angular.element.fragments, function(val, key) { - delete angular.element.fragments[key]; - }); - - MockXhr.$$lastInstance = null; - - angular.forEach(angular.callbacks, function(val, key) { - delete angular.callbacks[key]; - }); - angular.callbacks.counter = 0; - }); - - /** - * @ngdoc function - * @name angular.mock.module - * @description - * - * *NOTE*: This function is also published on window for easy access.
- * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha - * - * This function registers a module configuration code. It collects the configuration information - * which will be used when the injector is created by {@link angular.mock.inject inject}. - * - * See {@link angular.mock.inject inject} for usage example - * - * @param {...(string|Function|Object)} fns any number of modules which are represented as string - * aliases or as anonymous module initialization functions. The modules are used to - * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an - * object literal is passed each key-value pair will be registered on the module via - * {@link auto.$provide $provide}.value, the key being the string name (or token) to associate - * with the value on the injector. - */ - window.module = angular.mock.module = function() { - var moduleFns = Array.prototype.slice.call(arguments, 0); - return isSpecRunning() ? workFn() : workFn; - ///////////////////// - function workFn() { - if (currentSpec.$injector) { - throw new Error('Injector already created, can not register a module!'); - } else { - var fn, modules = currentSpec.$modules || (currentSpec.$modules = []); - angular.forEach(moduleFns, function(module) { - if (angular.isObject(module) && !angular.isArray(module)) { - fn = function($provide) { - angular.forEach(module, function(value, key) { - $provide.value(key, value); - }); - }; - } else { - fn = module; - } - if (currentSpec.$providerInjector) { - currentSpec.$providerInjector.invoke(fn); - } else { - modules.push(fn); - } - }); - } - } - }; - - /** - * @ngdoc function - * @name angular.mock.inject - * @description - * - * *NOTE*: This function is also published on window for easy access.
- * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha - * - * The inject function wraps a function into an injectable function. The inject() creates new - * instance of {@link auto.$injector $injector} per test, which is then used for - * resolving references. - * - * - * ## Resolving References (Underscore Wrapping) - * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this - * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable - * that is declared in the scope of the `describe()` block. Since we would, most likely, want - * the variable to have the same name of the reference we have a problem, since the parameter - * to the `inject()` function would hide the outer variable. - * - * To help with this, the injected parameters can, optionally, be enclosed with underscores. - * These are ignored by the injector when the reference name is resolved. - * - * For example, the parameter `_myService_` would be resolved as the reference `myService`. - * Since it is available in the function body as _myService_, we can then assign it to a variable - * defined in an outer scope. - * - * ``` - * // Defined out reference variable outside - * var myService; - * - * // Wrap the parameter in underscores - * beforeEach( inject( function(_myService_){ - * myService = _myService_; - * })); - * - * // Use myService in a series of tests. - * it('makes use of myService', function() { - * myService.doStuff(); - * }); - * - * ``` - * - * See also {@link angular.mock.module angular.mock.module} - * - * ## Example - * Example of what a typical jasmine tests looks like with the inject method. - * ```js - * - * angular.module('myApplicationModule', []) - * .value('mode', 'app') - * .value('version', 'v1.0.1'); - * - * - * describe('MyApp', function() { - * - * // You need to load modules that you want to test, - * // it loads only the "ng" module by default. - * beforeEach(module('myApplicationModule')); - * - * - * // inject() is used to inject arguments of all given functions - * it('should provide a version', inject(function(mode, version) { - * expect(version).toEqual('v1.0.1'); - * expect(mode).toEqual('app'); - * })); - * - * - * // The inject and module method can also be used inside of the it or beforeEach - * it('should override a version and test the new version is injected', function() { - * // module() takes functions or strings (module aliases) - * module(function($provide) { - * $provide.value('version', 'overridden'); // override version here - * }); - * - * inject(function(version) { - * expect(version).toEqual('overridden'); - * }); - * }); - * }); - * - * ``` - * - * @param {...Function} fns any number of functions which will be injected using the injector. - */ - - - - var ErrorAddingDeclarationLocationStack = function(e, errorForStack) { - this.message = e.message; - this.name = e.name; - if (e.line) this.line = e.line; - if (e.sourceId) this.sourceId = e.sourceId; - if (e.stack && errorForStack) - this.stack = e.stack + '\n' + errorForStack.stack; - if (e.stackArray) this.stackArray = e.stackArray; - }; - ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString; - - window.inject = angular.mock.inject = function() { - var blockFns = Array.prototype.slice.call(arguments, 0); - var errorForStack = new Error('Declaration Location'); - return isSpecRunning() ? workFn.call(currentSpec) : workFn; - ///////////////////// - function workFn() { - var modules = currentSpec.$modules || []; - var strictDi = !!currentSpec.$injectorStrict; - modules.unshift(function($injector) { - currentSpec.$providerInjector = $injector; - }); - modules.unshift('ngMock'); - modules.unshift('ng'); - var injector = currentSpec.$injector; - if (!injector) { - if (strictDi) { - // If strictDi is enabled, annotate the providerInjector blocks - angular.forEach(modules, function(moduleFn) { - if (typeof moduleFn === "function") { - angular.injector.$$annotate(moduleFn); - } - }); - } - injector = currentSpec.$injector = angular.injector(modules, strictDi); - currentSpec.$injectorStrict = strictDi; - } - for (var i = 0, ii = blockFns.length; i < ii; i++) { - if (currentSpec.$injectorStrict) { - // If the injector is strict / strictDi, and the spec wants to inject using automatic - // annotation, then annotate the function here. - injector.annotate(blockFns[i]); - } - try { - /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */ - injector.invoke(blockFns[i] || angular.noop, this); - /* jshint +W040 */ - } catch (e) { - if (e.stack && errorForStack) { - throw new ErrorAddingDeclarationLocationStack(e, errorForStack); - } - throw e; - } finally { - errorForStack = null; - } - } - } - }; - - - angular.mock.inject.strictDi = function(value) { - value = arguments.length ? !!value : true; - return isSpecRunning() ? workFn() : workFn; - - function workFn() { - if (value !== currentSpec.$injectorStrict) { - if (currentSpec.$injector) { - throw new Error('Injector already created, can not modify strict annotations'); - } else { - currentSpec.$injectorStrict = value; - } - } - } - }; -} - - -})(window, window.angular); diff --git a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-resource.js b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-resource.js deleted file mode 100644 index 444be83c..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-resource.js +++ /dev/null @@ -1,768 +0,0 @@ -/** - * @license AngularJS v1.5.0 - * (c) 2010-2016 Google, Inc. http://angularjs.org - * License: MIT - */ -(function(window, angular, undefined) {'use strict'; - -var $resourceMinErr = angular.$$minErr('$resource'); - -// Helper functions and regex to lookup a dotted path on an object -// stopping at undefined/null. The path must be composed of ASCII -// identifiers (just like $parse) -var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/; - -function isValidDottedPath(path) { - return (path != null && path !== '' && path !== 'hasOwnProperty' && - MEMBER_NAME_REGEX.test('.' + path)); -} - -function lookupDottedPath(obj, path) { - if (!isValidDottedPath(path)) { - throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path); - } - var keys = path.split('.'); - for (var i = 0, ii = keys.length; i < ii && angular.isDefined(obj); i++) { - var key = keys[i]; - obj = (obj !== null) ? obj[key] : undefined; - } - return obj; -} - -/** - * Create a shallow copy of an object and clear other fields from the destination - */ -function shallowClearAndCopy(src, dst) { - dst = dst || {}; - - angular.forEach(dst, function(value, key) { - delete dst[key]; - }); - - for (var key in src) { - if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) { - dst[key] = src[key]; - } - } - - return dst; -} - -/** - * @ngdoc module - * @name ngResource - * @description - * - * # ngResource - * - * The `ngResource` module provides interaction support with RESTful services - * via the $resource service. - * - * - *
- * - * See {@link ngResource.$resource `$resource`} for usage. - */ - -/** - * @ngdoc service - * @name $resource - * @requires $http - * @requires ng.$log - * @requires $q - * @requires ng.$timeout - * - * @description - * A factory which creates a resource object that lets you interact with - * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources. - * - * The returned resource object has action methods which provide high-level behaviors without - * the need to interact with the low level {@link ng.$http $http} service. - * - * Requires the {@link ngResource `ngResource`} module to be installed. - * - * By default, trailing slashes will be stripped from the calculated URLs, - * which can pose problems with server backends that do not expect that - * behavior. This can be disabled by configuring the `$resourceProvider` like - * this: - * - * ```js - app.config(['$resourceProvider', function($resourceProvider) { - // Don't strip trailing slashes from calculated URLs - $resourceProvider.defaults.stripTrailingSlashes = false; - }]); - * ``` - * - * @param {string} url A parameterized URL template with parameters prefixed by `:` as in - * `/user/:username`. If you are using a URL with a port number (e.g. - * `http://example.com:8080/api`), it will be respected. - * - * If you are using a url with a suffix, just add the suffix, like this: - * `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')` - * or even `$resource('http://example.com/resource/:resource_id.:format')` - * If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be - * collapsed down to a single `.`. If you need this sequence to appear and not collapse then you - * can escape it with `/\.`. - * - * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in - * `actions` methods. If a parameter value is a function, it will be executed every time - * when a param value needs to be obtained for a request (unless the param was overridden). - * - * Each key value in the parameter object is first bound to url template if present and then any - * excess keys are appended to the url search query after the `?`. - * - * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in - * URL `/path/greet?salutation=Hello`. - * - * If the parameter value is prefixed with `@` then the value for that parameter will be extracted - * from the corresponding property on the `data` object (provided when calling an action method). - * For example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of - * `someParam` will be `data.someProp`. - * - * @param {Object.=} actions Hash with declaration of custom actions that should extend - * the default set of resource actions. The declaration should be created in the format of {@link - * ng.$http#usage $http.config}: - * - * {action1: {method:?, params:?, isArray:?, headers:?, ...}, - * action2: {method:?, params:?, isArray:?, headers:?, ...}, - * ...} - * - * Where: - * - * - **`action`** – {string} – The name of action. This name becomes the name of the method on - * your resource object. - * - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`, - * `DELETE`, `JSONP`, etc). - * - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of - * the parameter value is a function, it will be executed every time when a param value needs to - * be obtained for a request (unless the param was overridden). - * - **`url`** – {string} – action specific `url` override. The url templating is supported just - * like for the resource-level urls. - * - **`isArray`** – {boolean=} – If true then the returned object for this action is an array, - * see `returns` section. - * - **`transformRequest`** – - * `{function(data, headersGetter)|Array.}` – - * transform function or an array of such functions. The transform function takes the http - * request body and headers and returns its transformed (typically serialized) version. - * By default, transformRequest will contain one function that checks if the request data is - * an object and serializes to using `angular.toJson`. To prevent this behavior, set - * `transformRequest` to an empty array: `transformRequest: []` - * - **`transformResponse`** – - * `{function(data, headersGetter)|Array.}` – - * transform function or an array of such functions. The transform function takes the http - * response body and headers and returns its transformed (typically deserialized) version. - * By default, transformResponse will contain one function that checks if the response looks - * like a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior, - * set `transformResponse` to an empty array: `transformResponse: []` - * - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the - * GET request, otherwise if a cache instance built with - * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for - * caching. - * - **`timeout`** – `{number}` – timeout in milliseconds.
- * **Note:** In contrast to {@link ng.$http#usage $http.config}, {@link ng.$q promises} are - * **not** supported in $resource, because the same value would be used for multiple requests. - * If you are looking for a way to cancel requests, you should use the `cancellable` option. - * - **`cancellable`** – `{boolean}` – if set to true, the request made by a "non-instance" call - * will be cancelled (if not already completed) by calling `$cancelRequest()` on the call's - * return value. Calling `$cancelRequest()` for a non-cancellable or an already - * completed/cancelled request will have no effect.
- * - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the - * XHR object. See - * [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5) - * for more information. - * - **`responseType`** - `{string}` - see - * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType). - * - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods - - * `response` and `responseError`. Both `response` and `responseError` interceptors get called - * with `http response` object. See {@link ng.$http $http interceptors}. - * - * @param {Object} options Hash with custom settings that should extend the - * default `$resourceProvider` behavior. The supported options are: - * - * - **`stripTrailingSlashes`** – {boolean} – If true then the trailing - * slashes from any calculated URL will be stripped. (Defaults to true.) - * - **`cancellable`** – {boolean} – If true, the request made by a "non-instance" call will be - * cancelled (if not already completed) by calling `$cancelRequest()` on the call's return value. - * This can be overwritten per action. (Defaults to false.) - * - * @returns {Object} A resource "class" object with methods for the default set of resource actions - * optionally extended with custom `actions`. The default set contains these actions: - * ```js - * { 'get': {method:'GET'}, - * 'save': {method:'POST'}, - * 'query': {method:'GET', isArray:true}, - * 'remove': {method:'DELETE'}, - * 'delete': {method:'DELETE'} }; - * ``` - * - * Calling these methods invoke an {@link ng.$http} with the specified http method, - * destination and parameters. When the data is returned from the server then the object is an - * instance of the resource class. The actions `save`, `remove` and `delete` are available on it - * as methods with the `$` prefix. This allows you to easily perform CRUD operations (create, - * read, update, delete) on server-side data like this: - * ```js - * var User = $resource('/user/:userId', {userId:'@id'}); - * var user = User.get({userId:123}, function() { - * user.abc = true; - * user.$save(); - * }); - * ``` - * - * It is important to realize that invoking a $resource object method immediately returns an - * empty reference (object or array depending on `isArray`). Once the data is returned from the - * server the existing reference is populated with the actual data. This is a useful trick since - * usually the resource is assigned to a model which is then rendered by the view. Having an empty - * object results in no rendering, once the data arrives from the server then the object is - * populated with the data and the view automatically re-renders itself showing the new data. This - * means that in most cases one never has to write a callback function for the action methods. - * - * The action methods on the class object or instance object can be invoked with the following - * parameters: - * - * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])` - * - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])` - * - non-GET instance actions: `instance.$action([parameters], [success], [error])` - * - * - * Success callback is called with (value, responseHeaders) arguments, where the value is - * the populated resource instance or collection object. The error callback is called - * with (httpResponse) argument. - * - * Class actions return empty instance (with additional properties below). - * Instance actions return promise of the action. - * - * The Resource instances and collections have these additional properties: - * - * - `$promise`: the {@link ng.$q promise} of the original server interaction that created this - * instance or collection. - * - * On success, the promise is resolved with the same resource instance or collection object, - * updated with data from server. This makes it easy to use in - * {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view - * rendering until the resource(s) are loaded. - * - * On failure, the promise is rejected with the {@link ng.$http http response} object, without - * the `resource` property. - * - * If an interceptor object was provided, the promise will instead be resolved with the value - * returned by the interceptor. - * - * - `$resolved`: `true` after first server interaction is completed (either with success or - * rejection), `false` before that. Knowing if the Resource has been resolved is useful in - * data-binding. - * - * The Resource instances and collections have these additional methods: - * - * - `$cancelRequest`: If there is a cancellable, pending request related to the instance or - * collection, calling this method will abort the request. - * - * @example - * - * # Credit card resource - * - * ```js - // Define CreditCard class - var CreditCard = $resource('/user/:userId/card/:cardId', - {userId:123, cardId:'@id'}, { - charge: {method:'POST', params:{charge:true}} - }); - - // We can retrieve a collection from the server - var cards = CreditCard.query(function() { - // GET: /user/123/card - // server returns: [ {id:456, number:'1234', name:'Smith'} ]; - - var card = cards[0]; - // each item is an instance of CreditCard - expect(card instanceof CreditCard).toEqual(true); - card.name = "J. Smith"; - // non GET methods are mapped onto the instances - card.$save(); - // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} - // server returns: {id:456, number:'1234', name: 'J. Smith'}; - - // our custom method is mapped as well. - card.$charge({amount:9.99}); - // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'} - }); - - // we can create an instance as well - var newCard = new CreditCard({number:'0123'}); - newCard.name = "Mike Smith"; - newCard.$save(); - // POST: /user/123/card {number:'0123', name:'Mike Smith'} - // server returns: {id:789, number:'0123', name: 'Mike Smith'}; - expect(newCard.id).toEqual(789); - * ``` - * - * The object returned from this function execution is a resource "class" which has "static" method - * for each action in the definition. - * - * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and - * `headers`. - * - * @example - * - * # User resource - * - * When the data is returned from the server then the object is an instance of the resource type and - * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD - * operations (create, read, update, delete) on server-side data. - - ```js - var User = $resource('/user/:userId', {userId:'@id'}); - User.get({userId:123}, function(user) { - user.abc = true; - user.$save(); - }); - ``` - * - * It's worth noting that the success callback for `get`, `query` and other methods gets passed - * in the response that came from the server as well as $http header getter function, so one - * could rewrite the above example and get access to http headers as: - * - ```js - var User = $resource('/user/:userId', {userId:'@id'}); - User.get({userId:123}, function(user, getResponseHeaders){ - user.abc = true; - user.$save(function(user, putResponseHeaders) { - //user => saved user object - //putResponseHeaders => $http header getter - }); - }); - ``` - * - * You can also access the raw `$http` promise via the `$promise` property on the object returned - * - ``` - var User = $resource('/user/:userId', {userId:'@id'}); - User.get({userId:123}) - .$promise.then(function(user) { - $scope.user = user; - }); - ``` - * - * @example - * - * # Creating a custom 'PUT' request - * - * In this example we create a custom method on our resource to make a PUT request - * ```js - * var app = angular.module('app', ['ngResource', 'ngRoute']); - * - * // Some APIs expect a PUT request in the format URL/object/ID - * // Here we are creating an 'update' method - * app.factory('Notes', ['$resource', function($resource) { - * return $resource('/notes/:id', null, - * { - * 'update': { method:'PUT' } - * }); - * }]); - * - * // In our controller we get the ID from the URL using ngRoute and $routeParams - * // We pass in $routeParams and our Notes factory along with $scope - * app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes', - function($scope, $routeParams, Notes) { - * // First get a note object from the factory - * var note = Notes.get({ id:$routeParams.id }); - * $id = note.id; - * - * // Now call update passing in the ID first then the object you are updating - * Notes.update({ id:$id }, note); - * - * // This will PUT /notes/ID with the note object in the request payload - * }]); - * ``` - * - * @example - * - * # Cancelling requests - * - * If an action's configuration specifies that it is cancellable, you can cancel the request related - * to an instance or collection (as long as it is a result of a "non-instance" call): - * - ```js - // ...defining the `Hotel` resource... - var Hotel = $resource('/api/hotel/:id', {id: '@id'}, { - // Let's make the `query()` method cancellable - query: {method: 'get', isArray: true, cancellable: true} - }); - - // ...somewhere in the PlanVacationController... - ... - this.onDestinationChanged = function onDestinationChanged(destination) { - // We don't care about any pending request for hotels - // in a different destination any more - this.availableHotels.$cancelRequest(); - - // Let's query for hotels in '' - // (calls: /api/hotel?location=) - this.availableHotels = Hotel.query({location: destination}); - }; - ``` - * - */ -angular.module('ngResource', ['ng']). - provider('$resource', function() { - var PROTOCOL_AND_DOMAIN_REGEX = /^https?:\/\/[^\/]*/; - var provider = this; - - this.defaults = { - // Strip slashes by default - stripTrailingSlashes: true, - - // Default actions configuration - actions: { - 'get': {method: 'GET'}, - 'save': {method: 'POST'}, - 'query': {method: 'GET', isArray: true}, - 'remove': {method: 'DELETE'}, - 'delete': {method: 'DELETE'} - } - }; - - this.$get = ['$http', '$log', '$q', '$timeout', function($http, $log, $q, $timeout) { - - var noop = angular.noop, - forEach = angular.forEach, - extend = angular.extend, - copy = angular.copy, - isFunction = angular.isFunction; - - /** - * We need our custom method because encodeURIComponent is too aggressive and doesn't follow - * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set - * (pchar) allowed in path segments: - * segment = *pchar - * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - * pct-encoded = "%" HEXDIG HEXDIG - * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" - * / "*" / "+" / "," / ";" / "=" - */ - function encodeUriSegment(val) { - return encodeUriQuery(val, true). - replace(/%26/gi, '&'). - replace(/%3D/gi, '='). - replace(/%2B/gi, '+'); - } - - - /** - * This method is intended for encoding *key* or *value* parts of query component. We need a - * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't - * have to be encoded per http://tools.ietf.org/html/rfc3986: - * query = *( pchar / "/" / "?" ) - * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * pct-encoded = "%" HEXDIG HEXDIG - * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" - * / "*" / "+" / "," / ";" / "=" - */ - function encodeUriQuery(val, pctEncodeSpaces) { - return encodeURIComponent(val). - replace(/%40/gi, '@'). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); - } - - function Route(template, defaults) { - this.template = template; - this.defaults = extend({}, provider.defaults, defaults); - this.urlParams = {}; - } - - Route.prototype = { - setUrlParams: function(config, params, actionUrl) { - var self = this, - url = actionUrl || self.template, - val, - encodedVal, - protocolAndDomain = ''; - - var urlParams = self.urlParams = {}; - forEach(url.split(/\W/), function(param) { - if (param === 'hasOwnProperty') { - throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name."); - } - if (!(new RegExp("^\\d+$").test(param)) && param && - (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) { - urlParams[param] = { - isQueryParamValue: (new RegExp("\\?.*=:" + param + "(?:\\W|$)")).test(url) - }; - } - }); - url = url.replace(/\\:/g, ':'); - url = url.replace(PROTOCOL_AND_DOMAIN_REGEX, function(match) { - protocolAndDomain = match; - return ''; - }); - - params = params || {}; - forEach(self.urlParams, function(paramInfo, urlParam) { - val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam]; - if (angular.isDefined(val) && val !== null) { - if (paramInfo.isQueryParamValue) { - encodedVal = encodeUriQuery(val, true); - } else { - encodedVal = encodeUriSegment(val); - } - url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) { - return encodedVal + p1; - }); - } else { - url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match, - leadingSlashes, tail) { - if (tail.charAt(0) == '/') { - return tail; - } else { - return leadingSlashes + tail; - } - }); - } - }); - - // strip trailing slashes and set the url (unless this behavior is specifically disabled) - if (self.defaults.stripTrailingSlashes) { - url = url.replace(/\/+$/, '') || '/'; - } - - // then replace collapse `/.` if found in the last URL path segment before the query - // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x` - url = url.replace(/\/\.(?=\w+($|\?))/, '.'); - // replace escaped `/\.` with `/.` - config.url = protocolAndDomain + url.replace(/\/\\\./, '/.'); - - - // set params - delegate param encoding to $http - forEach(params, function(value, key) { - if (!self.urlParams[key]) { - config.params = config.params || {}; - config.params[key] = value; - } - }); - } - }; - - - function resourceFactory(url, paramDefaults, actions, options) { - var route = new Route(url, options); - - actions = extend({}, provider.defaults.actions, actions); - - function extractParams(data, actionParams) { - var ids = {}; - actionParams = extend({}, paramDefaults, actionParams); - forEach(actionParams, function(value, key) { - if (isFunction(value)) { value = value(); } - ids[key] = value && value.charAt && value.charAt(0) == '@' ? - lookupDottedPath(data, value.substr(1)) : value; - }); - return ids; - } - - function defaultResponseInterceptor(response) { - return response.resource; - } - - function Resource(value) { - shallowClearAndCopy(value || {}, this); - } - - Resource.prototype.toJSON = function() { - var data = extend({}, this); - delete data.$promise; - delete data.$resolved; - return data; - }; - - forEach(actions, function(action, name) { - var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method); - var numericTimeout = action.timeout; - var cancellable = angular.isDefined(action.cancellable) ? action.cancellable : - (options && angular.isDefined(options.cancellable)) ? options.cancellable : - provider.defaults.cancellable; - - if (numericTimeout && !angular.isNumber(numericTimeout)) { - $log.debug('ngResource:\n' + - ' Only numeric values are allowed as `timeout`.\n' + - ' Promises are not supported in $resource, because the same value would ' + - 'be used for multiple requests. If you are looking for a way to cancel ' + - 'requests, you should use the `cancellable` option.'); - delete action.timeout; - numericTimeout = null; - } - - Resource[name] = function(a1, a2, a3, a4) { - var params = {}, data, success, error; - - /* jshint -W086 */ /* (purposefully fall through case statements) */ - switch (arguments.length) { - case 4: - error = a4; - success = a3; - //fallthrough - case 3: - case 2: - if (isFunction(a2)) { - if (isFunction(a1)) { - success = a1; - error = a2; - break; - } - - success = a2; - error = a3; - //fallthrough - } else { - params = a1; - data = a2; - success = a3; - break; - } - case 1: - if (isFunction(a1)) success = a1; - else if (hasBody) data = a1; - else params = a1; - break; - case 0: break; - default: - throw $resourceMinErr('badargs', - "Expected up to 4 arguments [params, data, success, error], got {0} arguments", - arguments.length); - } - /* jshint +W086 */ /* (purposefully fall through case statements) */ - - var isInstanceCall = this instanceof Resource; - var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data)); - var httpConfig = {}; - var responseInterceptor = action.interceptor && action.interceptor.response || - defaultResponseInterceptor; - var responseErrorInterceptor = action.interceptor && action.interceptor.responseError || - undefined; - var timeoutDeferred; - var numericTimeoutPromise; - - forEach(action, function(value, key) { - switch (key) { - default: - httpConfig[key] = copy(value); - break; - case 'params': - case 'isArray': - case 'interceptor': - case 'cancellable': - break; - } - }); - - if (!isInstanceCall && cancellable) { - timeoutDeferred = $q.defer(); - httpConfig.timeout = timeoutDeferred.promise; - - if (numericTimeout) { - numericTimeoutPromise = $timeout(timeoutDeferred.resolve, numericTimeout); - } - } - - if (hasBody) httpConfig.data = data; - route.setUrlParams(httpConfig, - extend({}, extractParams(data, action.params || {}), params), - action.url); - - var promise = $http(httpConfig).then(function(response) { - var data = response.data; - - if (data) { - // Need to convert action.isArray to boolean in case it is undefined - // jshint -W018 - if (angular.isArray(data) !== (!!action.isArray)) { - throw $resourceMinErr('badcfg', - 'Error in resource configuration for action `{0}`. Expected response to ' + - 'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object', - angular.isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url); - } - // jshint +W018 - if (action.isArray) { - value.length = 0; - forEach(data, function(item) { - if (typeof item === "object") { - value.push(new Resource(item)); - } else { - // Valid JSON values may be string literals, and these should not be converted - // into objects. These items will not have access to the Resource prototype - // methods, but unfortunately there - value.push(item); - } - }); - } else { - var promise = value.$promise; // Save the promise - shallowClearAndCopy(data, value); - value.$promise = promise; // Restore the promise - } - } - response.resource = value; - - return response; - }, function(response) { - (error || noop)(response); - return $q.reject(response); - }); - - promise.finally(function() { - value.$resolved = true; - if (!isInstanceCall && cancellable) { - value.$cancelRequest = angular.noop; - $timeout.cancel(numericTimeoutPromise); - timeoutDeferred = numericTimeoutPromise = httpConfig.timeout = null; - } - }); - - promise = promise.then( - function(response) { - var value = responseInterceptor(response); - (success || noop)(value, response.headers); - return value; - }, - responseErrorInterceptor); - - if (!isInstanceCall) { - // we are creating instance / collection - // - set the initial promise - // - return the instance / collection - value.$promise = promise; - value.$resolved = false; - if (cancellable) value.$cancelRequest = timeoutDeferred.resolve; - - return value; - } - - // instance call - return promise; - }; - - - Resource.prototype['$' + name] = function(params, success, error) { - if (isFunction(params)) { - error = success; success = params; params = {}; - } - var result = Resource[name].call(this, params, this, success, error); - return result.$promise || result; - }; - }); - - Resource.bind = function(additionalParamDefaults) { - return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); - }; - - return Resource; - } - - return resourceFactory; - }]; - }); - - -})(window, window.angular); diff --git a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-resource.min.js b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-resource.min.js deleted file mode 100644 index 306657dc..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-resource.min.js +++ /dev/null @@ -1,15 +0,0 @@ -/* - AngularJS v1.5.0 - (c) 2010-2016 Google, Inc. http://angularjs.org - License: MIT -*/ -(function(Q,d,G){'use strict';function H(t,g){g=g||{};d.forEach(g,function(d,q){delete g[q]});for(var q in t)!t.hasOwnProperty(q)||"$"===q.charAt(0)&&"$"===q.charAt(1)||(g[q]=t[q]);return g}var z=d.$$minErr("$resource"),N=/^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/;d.module("ngResource",["ng"]).provider("$resource",function(){var t=/^https?:\/\/[^\/]*/,g=this;this.defaults={stripTrailingSlashes:!0,actions:{get:{method:"GET"},save:{method:"POST"},query:{method:"GET",isArray:!0},remove:{method:"DELETE"},"delete":{method:"DELETE"}}}; -this.$get=["$http","$log","$q","$timeout",function(q,M,I,J){function A(d,h){return encodeURIComponent(d).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,h?"%20":"+")}function B(d,h){this.template=d;this.defaults=v({},g.defaults,h);this.urlParams={}}function K(e,h,n,k){function c(a,b){var c={};b=v({},h,b);u(b,function(b,h){x(b)&&(b=b());var f;if(b&&b.charAt&&"@"==b.charAt(0)){f=a;var l=b.substr(1);if(null==l||""===l||"hasOwnProperty"===l||!N.test("."+ -l))throw z("badmember",l);for(var l=l.split("."),m=0,k=l.length;m - */ - /* global -ngRouteModule */ -var ngRouteModule = angular.module('ngRoute', ['ng']). - provider('$route', $RouteProvider), - $routeMinErr = angular.$$minErr('ngRoute'); - -/** - * @ngdoc provider - * @name $routeProvider - * - * @description - * - * Used for configuring routes. - * - * ## Example - * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. - * - * ## Dependencies - * Requires the {@link ngRoute `ngRoute`} module to be installed. - */ -function $RouteProvider() { - function inherit(parent, extra) { - return angular.extend(Object.create(parent), extra); - } - - var routes = {}; - - /** - * @ngdoc method - * @name $routeProvider#when - * - * @param {string} path Route path (matched against `$location.path`). If `$location.path` - * contains redundant trailing slash or is missing one, the route will still match and the - * `$location.path` will be updated to add or drop the trailing slash to exactly match the - * route definition. - * - * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up - * to the next slash are matched and stored in `$routeParams` under the given `name` - * when the route matches. - * * `path` can contain named groups starting with a colon and ending with a star: - * e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name` - * when the route matches. - * * `path` can contain optional named groups with a question mark: e.g.`:name?`. - * - * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match - * `/color/brown/largecode/code/with/slashes/edit` and extract: - * - * * `color: brown` - * * `largecode: code/with/slashes`. - * - * - * @param {Object} route Mapping information to be assigned to `$route.current` on route - * match. - * - * Object properties: - * - * - `controller` – `{(string|function()=}` – Controller fn that should be associated with - * newly created scope or the name of a {@link angular.Module#controller registered - * controller} if passed as a string. - * - `controllerAs` – `{string=}` – An identifier name for a reference to the controller. - * If present, the controller will be published to scope under the `controllerAs` name. - * - `template` – `{string=|function()=}` – html template as a string or a function that - * returns an html template as a string which should be used by {@link - * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives. - * This property takes precedence over `templateUrl`. - * - * If `template` is a function, it will be called with the following parameters: - * - * - `{Array.}` - route parameters extracted from the current - * `$location.path()` by applying the current route - * - * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html - * template that should be used by {@link ngRoute.directive:ngView ngView}. - * - * If `templateUrl` is a function, it will be called with the following parameters: - * - * - `{Array.}` - route parameters extracted from the current - * `$location.path()` by applying the current route - * - * - `resolve` - `{Object.=}` - An optional map of dependencies which should - * be injected into the controller. If any of these dependencies are promises, the router - * will wait for them all to be resolved or one to be rejected before the controller is - * instantiated. - * If all the promises are resolved successfully, the values of the resolved promises are - * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is - * fired. If any of the promises are rejected the - * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. - * For easier access to the resolved dependencies from the template, the `resolve` map will - * be available on the scope of the route, under `$resolve` (by default) or a custom name - * specified by the `resolveAs` property (see below). This can be particularly useful, when - * working with {@link angular.Module#component components} as route templates.
- *
- * **Note:** If your scope already contains a property with this name, it will be hidden - * or overwritten. Make sure, you specify an appropriate name for this property, that - * does not collide with other properties on the scope. - *
- * The map object is: - * - * - `key` – `{string}`: a name of a dependency to be injected into the controller. - * - `factory` - `{string|function}`: If `string` then it is an alias for a service. - * Otherwise if function, then it is {@link auto.$injector#invoke injected} - * and the return value is treated as the dependency. If the result is a promise, it is - * resolved before its value is injected into the controller. Be aware that - * `ngRoute.$routeParams` will still refer to the previous route within these resolve - * functions. Use `$route.current.params` to access the new route parameters, instead. - * - * - `resolveAs` - `{string=}` - The name under which the `resolve` map will be available on - * the scope of the route. If omitted, defaults to `$resolve`. - * - * - `redirectTo` – `{(string|function())=}` – value to update - * {@link ng.$location $location} path with and trigger route redirection. - * - * If `redirectTo` is a function, it will be called with the following parameters: - * - * - `{Object.}` - route parameters extracted from the current - * `$location.path()` by applying the current route templateUrl. - * - `{string}` - current `$location.path()` - * - `{Object}` - current `$location.search()` - * - * The custom `redirectTo` function is expected to return a string which will be used - * to update `$location.path()` and `$location.search()`. - * - * - `[reloadOnSearch=true]` - `{boolean=}` - reload route when only `$location.search()` - * or `$location.hash()` changes. - * - * If the option is set to `false` and url in the browser changes, then - * `$routeUpdate` event is broadcasted on the root scope. - * - * - `[caseInsensitiveMatch=false]` - `{boolean=}` - match routes without being case sensitive - * - * If the option is set to `true`, then the particular route can be matched without being - * case sensitive - * - * @returns {Object} self - * - * @description - * Adds a new route definition to the `$route` service. - */ - this.when = function(path, route) { - //copy original route object to preserve params inherited from proto chain - var routeCopy = angular.copy(route); - if (angular.isUndefined(routeCopy.reloadOnSearch)) { - routeCopy.reloadOnSearch = true; - } - if (angular.isUndefined(routeCopy.caseInsensitiveMatch)) { - routeCopy.caseInsensitiveMatch = this.caseInsensitiveMatch; - } - routes[path] = angular.extend( - routeCopy, - path && pathRegExp(path, routeCopy) - ); - - // create redirection for trailing slashes - if (path) { - var redirectPath = (path[path.length - 1] == '/') - ? path.substr(0, path.length - 1) - : path + '/'; - - routes[redirectPath] = angular.extend( - {redirectTo: path}, - pathRegExp(redirectPath, routeCopy) - ); - } - - return this; - }; - - /** - * @ngdoc property - * @name $routeProvider#caseInsensitiveMatch - * @description - * - * A boolean property indicating if routes defined - * using this provider should be matched using a case insensitive - * algorithm. Defaults to `false`. - */ - this.caseInsensitiveMatch = false; - - /** - * @param path {string} path - * @param opts {Object} options - * @return {?Object} - * - * @description - * Normalizes the given path, returning a regular expression - * and the original path. - * - * Inspired by pathRexp in visionmedia/express/lib/utils.js. - */ - function pathRegExp(path, opts) { - var insensitive = opts.caseInsensitiveMatch, - ret = { - originalPath: path, - regexp: path - }, - keys = ret.keys = []; - - path = path - .replace(/([().])/g, '\\$1') - .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option) { - var optional = option === '?' ? option : null; - var star = option === '*' ? option : null; - keys.push({ name: key, optional: !!optional }); - slash = slash || ''; - return '' - + (optional ? '' : slash) - + '(?:' - + (optional ? slash : '') - + (star && '(.+?)' || '([^/]+)') - + (optional || '') - + ')' - + (optional || ''); - }) - .replace(/([\/$\*])/g, '\\$1'); - - ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : ''); - return ret; - } - - /** - * @ngdoc method - * @name $routeProvider#otherwise - * - * @description - * Sets route definition that will be used on route change when no other route definition - * is matched. - * - * @param {Object|string} params Mapping information to be assigned to `$route.current`. - * If called with a string, the value maps to `redirectTo`. - * @returns {Object} self - */ - this.otherwise = function(params) { - if (typeof params === 'string') { - params = {redirectTo: params}; - } - this.when(null, params); - return this; - }; - - - this.$get = ['$rootScope', - '$location', - '$routeParams', - '$q', - '$injector', - '$templateRequest', - '$sce', - function($rootScope, $location, $routeParams, $q, $injector, $templateRequest, $sce) { - - /** - * @ngdoc service - * @name $route - * @requires $location - * @requires $routeParams - * - * @property {Object} current Reference to the current route definition. - * The route definition contains: - * - * - `controller`: The controller constructor as defined in the route definition. - * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for - * controller instantiation. The `locals` contain - * the resolved values of the `resolve` map. Additionally the `locals` also contain: - * - * - `$scope` - The current route scope. - * - `$template` - The current route template HTML. - * - * The `locals` will be assigned to the route scope's `$resolve` property. You can override - * the property name, using `resolveAs` in the route definition. See - * {@link ngRoute.$routeProvider $routeProvider} for more info. - * - * @property {Object} routes Object with all route configuration Objects as its properties. - * - * @description - * `$route` is used for deep-linking URLs to controllers and views (HTML partials). - * It watches `$location.url()` and tries to map the path to an existing route definition. - * - * Requires the {@link ngRoute `ngRoute`} module to be installed. - * - * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API. - * - * The `$route` service is typically used in conjunction with the - * {@link ngRoute.directive:ngView `ngView`} directive and the - * {@link ngRoute.$routeParams `$routeParams`} service. - * - * @example - * This example shows how changing the URL hash causes the `$route` to match a route against the - * URL, and the `ngView` pulls in the partial. - * - * - * - *
- * Choose: - * Moby | - * Moby: Ch1 | - * Gatsby | - * Gatsby: Ch4 | - * Scarlet Letter
- * - *
- * - *
- * - *
$location.path() = {{$location.path()}}
- *
$route.current.templateUrl = {{$route.current.templateUrl}}
- *
$route.current.params = {{$route.current.params}}
- *
$route.current.scope.name = {{$route.current.scope.name}}
- *
$routeParams = {{$routeParams}}
- *
- *
- * - * - * controller: {{name}}
- * Book Id: {{params.bookId}}
- *
- * - * - * controller: {{name}}
- * Book Id: {{params.bookId}}
- * Chapter Id: {{params.chapterId}} - *
- * - * - * angular.module('ngRouteExample', ['ngRoute']) - * - * .controller('MainController', function($scope, $route, $routeParams, $location) { - * $scope.$route = $route; - * $scope.$location = $location; - * $scope.$routeParams = $routeParams; - * }) - * - * .controller('BookController', function($scope, $routeParams) { - * $scope.name = "BookController"; - * $scope.params = $routeParams; - * }) - * - * .controller('ChapterController', function($scope, $routeParams) { - * $scope.name = "ChapterController"; - * $scope.params = $routeParams; - * }) - * - * .config(function($routeProvider, $locationProvider) { - * $routeProvider - * .when('/Book/:bookId', { - * templateUrl: 'book.html', - * controller: 'BookController', - * resolve: { - * // I will cause a 1 second delay - * delay: function($q, $timeout) { - * var delay = $q.defer(); - * $timeout(delay.resolve, 1000); - * return delay.promise; - * } - * } - * }) - * .when('/Book/:bookId/ch/:chapterId', { - * templateUrl: 'chapter.html', - * controller: 'ChapterController' - * }); - * - * // configure html5 to get links working on jsfiddle - * $locationProvider.html5Mode(true); - * }); - * - * - * - * - * it('should load and compile correct template', function() { - * element(by.linkText('Moby: Ch1')).click(); - * var content = element(by.css('[ng-view]')).getText(); - * expect(content).toMatch(/controller\: ChapterController/); - * expect(content).toMatch(/Book Id\: Moby/); - * expect(content).toMatch(/Chapter Id\: 1/); - * - * element(by.partialLinkText('Scarlet')).click(); - * - * content = element(by.css('[ng-view]')).getText(); - * expect(content).toMatch(/controller\: BookController/); - * expect(content).toMatch(/Book Id\: Scarlet/); - * }); - * - *
- */ - - /** - * @ngdoc event - * @name $route#$routeChangeStart - * @eventType broadcast on root scope - * @description - * Broadcasted before a route change. At this point the route services starts - * resolving all of the dependencies needed for the route change to occur. - * Typically this involves fetching the view template as well as any dependencies - * defined in `resolve` route property. Once all of the dependencies are resolved - * `$routeChangeSuccess` is fired. - * - * The route change (and the `$location` change that triggered it) can be prevented - * by calling `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} - * for more details about event object. - * - * @param {Object} angularEvent Synthetic event object. - * @param {Route} next Future route information. - * @param {Route} current Current route information. - */ - - /** - * @ngdoc event - * @name $route#$routeChangeSuccess - * @eventType broadcast on root scope - * @description - * Broadcasted after a route change has happened successfully. - * The `resolve` dependencies are now available in the `current.locals` property. - * - * {@link ngRoute.directive:ngView ngView} listens for the directive - * to instantiate the controller and render the view. - * - * @param {Object} angularEvent Synthetic event object. - * @param {Route} current Current route information. - * @param {Route|Undefined} previous Previous route information, or undefined if current is - * first route entered. - */ - - /** - * @ngdoc event - * @name $route#$routeChangeError - * @eventType broadcast on root scope - * @description - * Broadcasted if any of the resolve promises are rejected. - * - * @param {Object} angularEvent Synthetic event object - * @param {Route} current Current route information. - * @param {Route} previous Previous route information. - * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. - */ - - /** - * @ngdoc event - * @name $route#$routeUpdate - * @eventType broadcast on root scope - * @description - * The `reloadOnSearch` property has been set to false, and we are reusing the same - * instance of the Controller. - * - * @param {Object} angularEvent Synthetic event object - * @param {Route} current Current/previous route information. - */ - - var forceReload = false, - preparedRoute, - preparedRouteIsUpdateOnly, - $route = { - routes: routes, - - /** - * @ngdoc method - * @name $route#reload - * - * @description - * Causes `$route` service to reload the current route even if - * {@link ng.$location $location} hasn't changed. - * - * As a result of that, {@link ngRoute.directive:ngView ngView} - * creates new scope and reinstantiates the controller. - */ - reload: function() { - forceReload = true; - - var fakeLocationEvent = { - defaultPrevented: false, - preventDefault: function fakePreventDefault() { - this.defaultPrevented = true; - forceReload = false; - } - }; - - $rootScope.$evalAsync(function() { - prepareRoute(fakeLocationEvent); - if (!fakeLocationEvent.defaultPrevented) commitRoute(); - }); - }, - - /** - * @ngdoc method - * @name $route#updateParams - * - * @description - * Causes `$route` service to update the current URL, replacing - * current route parameters with those specified in `newParams`. - * Provided property names that match the route's path segment - * definitions will be interpolated into the location's path, while - * remaining properties will be treated as query params. - * - * @param {!Object} newParams mapping of URL parameter names to values - */ - updateParams: function(newParams) { - if (this.current && this.current.$$route) { - newParams = angular.extend({}, this.current.params, newParams); - $location.path(interpolate(this.current.$$route.originalPath, newParams)); - // interpolate modifies newParams, only query params are left - $location.search(newParams); - } else { - throw $routeMinErr('norout', 'Tried updating route when with no current route'); - } - } - }; - - $rootScope.$on('$locationChangeStart', prepareRoute); - $rootScope.$on('$locationChangeSuccess', commitRoute); - - return $route; - - ///////////////////////////////////////////////////// - - /** - * @param on {string} current url - * @param route {Object} route regexp to match the url against - * @return {?Object} - * - * @description - * Check if the route matches the current url. - * - * Inspired by match in - * visionmedia/express/lib/router/router.js. - */ - function switchRouteMatcher(on, route) { - var keys = route.keys, - params = {}; - - if (!route.regexp) return null; - - var m = route.regexp.exec(on); - if (!m) return null; - - for (var i = 1, len = m.length; i < len; ++i) { - var key = keys[i - 1]; - - var val = m[i]; - - if (key && val) { - params[key.name] = val; - } - } - return params; - } - - function prepareRoute($locationEvent) { - var lastRoute = $route.current; - - preparedRoute = parseRoute(); - preparedRouteIsUpdateOnly = preparedRoute && lastRoute && preparedRoute.$$route === lastRoute.$$route - && angular.equals(preparedRoute.pathParams, lastRoute.pathParams) - && !preparedRoute.reloadOnSearch && !forceReload; - - if (!preparedRouteIsUpdateOnly && (lastRoute || preparedRoute)) { - if ($rootScope.$broadcast('$routeChangeStart', preparedRoute, lastRoute).defaultPrevented) { - if ($locationEvent) { - $locationEvent.preventDefault(); - } - } - } - } - - function commitRoute() { - var lastRoute = $route.current; - var nextRoute = preparedRoute; - - if (preparedRouteIsUpdateOnly) { - lastRoute.params = nextRoute.params; - angular.copy(lastRoute.params, $routeParams); - $rootScope.$broadcast('$routeUpdate', lastRoute); - } else if (nextRoute || lastRoute) { - forceReload = false; - $route.current = nextRoute; - if (nextRoute) { - if (nextRoute.redirectTo) { - if (angular.isString(nextRoute.redirectTo)) { - $location.path(interpolate(nextRoute.redirectTo, nextRoute.params)).search(nextRoute.params) - .replace(); - } else { - $location.url(nextRoute.redirectTo(nextRoute.pathParams, $location.path(), $location.search())) - .replace(); - } - } - } - - $q.when(nextRoute). - then(function() { - if (nextRoute) { - var locals = angular.extend({}, nextRoute.resolve), - template, templateUrl; - - angular.forEach(locals, function(value, key) { - locals[key] = angular.isString(value) ? - $injector.get(value) : $injector.invoke(value, null, null, key); - }); - - if (angular.isDefined(template = nextRoute.template)) { - if (angular.isFunction(template)) { - template = template(nextRoute.params); - } - } else if (angular.isDefined(templateUrl = nextRoute.templateUrl)) { - if (angular.isFunction(templateUrl)) { - templateUrl = templateUrl(nextRoute.params); - } - if (angular.isDefined(templateUrl)) { - nextRoute.loadedTemplateUrl = $sce.valueOf(templateUrl); - template = $templateRequest(templateUrl); - } - } - if (angular.isDefined(template)) { - locals['$template'] = template; - } - return $q.all(locals); - } - }). - then(function(locals) { - // after route change - if (nextRoute == $route.current) { - if (nextRoute) { - nextRoute.locals = locals; - angular.copy(nextRoute.params, $routeParams); - } - $rootScope.$broadcast('$routeChangeSuccess', nextRoute, lastRoute); - } - }, function(error) { - if (nextRoute == $route.current) { - $rootScope.$broadcast('$routeChangeError', nextRoute, lastRoute, error); - } - }); - } - } - - - /** - * @returns {Object} the current active route, by matching it against the URL - */ - function parseRoute() { - // Match a route - var params, match; - angular.forEach(routes, function(route, path) { - if (!match && (params = switchRouteMatcher($location.path(), route))) { - match = inherit(route, { - params: angular.extend({}, $location.search(), params), - pathParams: params}); - match.$$route = route; - } - }); - // No route matched; fallback to "otherwise" route - return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); - } - - /** - * @returns {string} interpolation of the redirect path with the parameters - */ - function interpolate(string, params) { - var result = []; - angular.forEach((string || '').split(':'), function(segment, i) { - if (i === 0) { - result.push(segment); - } else { - var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/); - var key = segmentMatch[1]; - result.push(params[key]); - result.push(segmentMatch[2] || ''); - delete params[key]; - } - }); - return result.join(''); - } - }]; -} - -ngRouteModule.provider('$routeParams', $RouteParamsProvider); - - -/** - * @ngdoc service - * @name $routeParams - * @requires $route - * - * @description - * The `$routeParams` service allows you to retrieve the current set of route parameters. - * - * Requires the {@link ngRoute `ngRoute`} module to be installed. - * - * The route parameters are a combination of {@link ng.$location `$location`}'s - * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}. - * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched. - * - * In case of parameter name collision, `path` params take precedence over `search` params. - * - * The service guarantees that the identity of the `$routeParams` object will remain unchanged - * (but its properties will likely change) even when a route change occurs. - * - * Note that the `$routeParams` are only updated *after* a route change completes successfully. - * This means that you cannot rely on `$routeParams` being correct in route resolve functions. - * Instead you can use `$route.current.params` to access the new route's parameters. - * - * @example - * ```js - * // Given: - * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby - * // Route: /Chapter/:chapterId/Section/:sectionId - * // - * // Then - * $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'} - * ``` - */ -function $RouteParamsProvider() { - this.$get = function() { return {}; }; -} - -ngRouteModule.directive('ngView', ngViewFactory); -ngRouteModule.directive('ngView', ngViewFillContentFactory); - - -/** - * @ngdoc directive - * @name ngView - * @restrict ECA - * - * @description - * # Overview - * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by - * including the rendered template of the current route into the main layout (`index.html`) file. - * Every time the current route changes, the included view changes with it according to the - * configuration of the `$route` service. - * - * Requires the {@link ngRoute `ngRoute`} module to be installed. - * - * @animations - * enter - animation is used to bring new content into the browser. - * leave - animation is used to animate existing content away. - * - * The enter and leave animation occur concurrently. - * - * @scope - * @priority 400 - * @param {string=} onload Expression to evaluate whenever the view updates. - * - * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll - * $anchorScroll} to scroll the viewport after the view is updated. - * - * - If the attribute is not set, disable scrolling. - * - If the attribute is set without value, enable scrolling. - * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated - * as an expression yields a truthy value. - * @example - - -
- Choose: - Moby | - Moby: Ch1 | - Gatsby | - Gatsby: Ch4 | - Scarlet Letter
- -
-
-
-
- -
$location.path() = {{main.$location.path()}}
-
$route.current.templateUrl = {{main.$route.current.templateUrl}}
-
$route.current.params = {{main.$route.current.params}}
-
$routeParams = {{main.$routeParams}}
-
-
- - -
- controller: {{book.name}}
- Book Id: {{book.params.bookId}}
-
-
- - -
- controller: {{chapter.name}}
- Book Id: {{chapter.params.bookId}}
- Chapter Id: {{chapter.params.chapterId}} -
-
- - - .view-animate-container { - position:relative; - height:100px!important; - background:white; - border:1px solid black; - height:40px; - overflow:hidden; - } - - .view-animate { - padding:10px; - } - - .view-animate.ng-enter, .view-animate.ng-leave { - transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; - - display:block; - width:100%; - border-left:1px solid black; - - position:absolute; - top:0; - left:0; - right:0; - bottom:0; - padding:10px; - } - - .view-animate.ng-enter { - left:100%; - } - .view-animate.ng-enter.ng-enter-active { - left:0; - } - .view-animate.ng-leave.ng-leave-active { - left:-100%; - } - - - - angular.module('ngViewExample', ['ngRoute', 'ngAnimate']) - .config(['$routeProvider', '$locationProvider', - function($routeProvider, $locationProvider) { - $routeProvider - .when('/Book/:bookId', { - templateUrl: 'book.html', - controller: 'BookCtrl', - controllerAs: 'book' - }) - .when('/Book/:bookId/ch/:chapterId', { - templateUrl: 'chapter.html', - controller: 'ChapterCtrl', - controllerAs: 'chapter' - }); - - $locationProvider.html5Mode(true); - }]) - .controller('MainCtrl', ['$route', '$routeParams', '$location', - function($route, $routeParams, $location) { - this.$route = $route; - this.$location = $location; - this.$routeParams = $routeParams; - }]) - .controller('BookCtrl', ['$routeParams', function($routeParams) { - this.name = "BookCtrl"; - this.params = $routeParams; - }]) - .controller('ChapterCtrl', ['$routeParams', function($routeParams) { - this.name = "ChapterCtrl"; - this.params = $routeParams; - }]); - - - - - it('should load and compile correct template', function() { - element(by.linkText('Moby: Ch1')).click(); - var content = element(by.css('[ng-view]')).getText(); - expect(content).toMatch(/controller\: ChapterCtrl/); - expect(content).toMatch(/Book Id\: Moby/); - expect(content).toMatch(/Chapter Id\: 1/); - - element(by.partialLinkText('Scarlet')).click(); - - content = element(by.css('[ng-view]')).getText(); - expect(content).toMatch(/controller\: BookCtrl/); - expect(content).toMatch(/Book Id\: Scarlet/); - }); - -
- */ - - -/** - * @ngdoc event - * @name ngView#$viewContentLoaded - * @eventType emit on the current ngView scope - * @description - * Emitted every time the ngView content is reloaded. - */ -ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate']; -function ngViewFactory($route, $anchorScroll, $animate) { - return { - restrict: 'ECA', - terminal: true, - priority: 400, - transclude: 'element', - link: function(scope, $element, attr, ctrl, $transclude) { - var currentScope, - currentElement, - previousLeaveAnimation, - autoScrollExp = attr.autoscroll, - onloadExp = attr.onload || ''; - - scope.$on('$routeChangeSuccess', update); - update(); - - function cleanupLastView() { - if (previousLeaveAnimation) { - $animate.cancel(previousLeaveAnimation); - previousLeaveAnimation = null; - } - - if (currentScope) { - currentScope.$destroy(); - currentScope = null; - } - if (currentElement) { - previousLeaveAnimation = $animate.leave(currentElement); - previousLeaveAnimation.then(function() { - previousLeaveAnimation = null; - }); - currentElement = null; - } - } - - function update() { - var locals = $route.current && $route.current.locals, - template = locals && locals.$template; - - if (angular.isDefined(template)) { - var newScope = scope.$new(); - var current = $route.current; - - // Note: This will also link all children of ng-view that were contained in the original - // html. If that content contains controllers, ... they could pollute/change the scope. - // However, using ng-view on an element with additional content does not make sense... - // Note: We can't remove them in the cloneAttchFn of $transclude as that - // function is called before linking the content, which would apply child - // directives to non existing elements. - var clone = $transclude(newScope, function(clone) { - $animate.enter(clone, null, currentElement || $element).then(function onNgViewEnter() { - if (angular.isDefined(autoScrollExp) - && (!autoScrollExp || scope.$eval(autoScrollExp))) { - $anchorScroll(); - } - }); - cleanupLastView(); - }); - - currentElement = clone; - currentScope = current.scope = newScope; - currentScope.$emit('$viewContentLoaded'); - currentScope.$eval(onloadExp); - } else { - cleanupLastView(); - } - } - } - }; -} - -// This directive is called during the $transclude call of the first `ngView` directive. -// It will replace and compile the content of the element with the loaded template. -// We need this directive so that the element content is already filled when -// the link function of another directive on the same element as ngView -// is called. -ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route']; -function ngViewFillContentFactory($compile, $controller, $route) { - return { - restrict: 'ECA', - priority: -400, - link: function(scope, $element) { - var current = $route.current, - locals = current.locals; - - $element.html(locals.$template); - - var link = $compile($element.contents()); - - if (current.controller) { - locals.$scope = scope; - var controller = $controller(current.controller, locals); - if (current.controllerAs) { - scope[current.controllerAs] = controller; - } - $element.data('$ngControllerController', controller); - $element.children().data('$ngControllerController', controller); - } - scope[current.resolveAs || '$resolve'] = locals; - - link(scope); - } - }; -} - - -})(window, window.angular); diff --git a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-route.min.js b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-route.min.js deleted file mode 100644 index 4d0d0187..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-route.min.js +++ /dev/null @@ -1,15 +0,0 @@ -/* - AngularJS v1.5.0 - (c) 2010-2016 Google, Inc. http://angularjs.org - License: MIT -*/ -(function(r,d,C){'use strict';function x(s,h,g){return{restrict:"ECA",terminal:!0,priority:400,transclude:"element",link:function(a,c,b,f,y){function k(){n&&(g.cancel(n),n=null);l&&(l.$destroy(),l=null);m&&(n=g.leave(m),n.then(function(){n=null}),m=null)}function z(){var b=s.current&&s.current.locals;if(d.isDefined(b&&b.$template)){var b=a.$new(),f=s.current;m=y(b,function(b){g.enter(b,null,m||c).then(function(){!d.isDefined(u)||u&&!a.$eval(u)||h()});k()});l=f.scope=b;l.$emit("$viewContentLoaded"); -l.$eval(v)}else k()}var l,m,n,u=b.autoscroll,v=b.onload||"";a.$on("$routeChangeSuccess",z);z()}}}function A(d,h,g){return{restrict:"ECA",priority:-400,link:function(a,c){var b=g.current,f=b.locals;c.html(f.$template);var y=d(c.contents());if(b.controller){f.$scope=a;var k=h(b.controller,f);b.controllerAs&&(a[b.controllerAs]=k);c.data("$ngControllerController",k);c.children().data("$ngControllerController",k)}a[b.resolveAs||"$resolve"]=f;y(a)}}}r=d.module("ngRoute",["ng"]).provider("$route",function(){function s(a, -c){return d.extend(Object.create(a),c)}function h(a,d){var b=d.caseInsensitiveMatch,f={originalPath:a,regexp:a},g=f.keys=[];a=a.replace(/([().])/g,"\\$1").replace(/(\/)?:(\w+)([\?\*])?/g,function(a,d,b,c){a="?"===c?c:null;c="*"===c?c:null;g.push({name:b,optional:!!a});d=d||"";return""+(a?"":d)+"(?:"+(a?d:"")+(c&&"(.+?)"||"([^/]+)")+(a||"")+")"+(a||"")}).replace(/([\/$\*])/g,"\\$1");f.regexp=new RegExp("^"+a+"$",b?"i":"");return f}var g={};this.when=function(a,c){var b=d.copy(c);d.isUndefined(b.reloadOnSearch)&& -(b.reloadOnSearch=!0);d.isUndefined(b.caseInsensitiveMatch)&&(b.caseInsensitiveMatch=this.caseInsensitiveMatch);g[a]=d.extend(b,a&&h(a,b));if(a){var f="/"==a[a.length-1]?a.substr(0,a.length-1):a+"/";g[f]=d.extend({redirectTo:a},h(f,b))}return this};this.caseInsensitiveMatch=!1;this.otherwise=function(a){"string"===typeof a&&(a={redirectTo:a});this.when(null,a);return this};this.$get=["$rootScope","$location","$routeParams","$q","$injector","$templateRequest","$sce",function(a,c,b,f,h,k,r){function l(b){var e= -t.current;(x=(p=n())&&e&&p.$$route===e.$$route&&d.equals(p.pathParams,e.pathParams)&&!p.reloadOnSearch&&!v)||!e&&!p||a.$broadcast("$routeChangeStart",p,e).defaultPrevented&&b&&b.preventDefault()}function m(){var w=t.current,e=p;if(x)w.params=e.params,d.copy(w.params,b),a.$broadcast("$routeUpdate",w);else if(e||w)v=!1,(t.current=e)&&e.redirectTo&&(d.isString(e.redirectTo)?c.path(u(e.redirectTo,e.params)).search(e.params).replace():c.url(e.redirectTo(e.pathParams,c.path(),c.search())).replace()),f.when(e).then(function(){if(e){var a= -d.extend({},e.resolve),b,c;d.forEach(a,function(b,e){a[e]=d.isString(b)?h.get(b):h.invoke(b,null,null,e)});d.isDefined(b=e.template)?d.isFunction(b)&&(b=b(e.params)):d.isDefined(c=e.templateUrl)&&(d.isFunction(c)&&(c=c(e.params)),d.isDefined(c)&&(e.loadedTemplateUrl=r.valueOf(c),b=k(c)));d.isDefined(b)&&(a.$template=b);return f.all(a)}}).then(function(c){e==t.current&&(e&&(e.locals=c,d.copy(e.params,b)),a.$broadcast("$routeChangeSuccess",e,w))},function(b){e==t.current&&a.$broadcast("$routeChangeError", -e,w,b)})}function n(){var a,b;d.forEach(g,function(f,g){var q;if(q=!b){var h=c.path();q=f.keys;var l={};if(f.regexp)if(h=f.regexp.exec(h)){for(var k=1,n=h.length;k - * - * See {@link ngSanitize.$sanitize `$sanitize`} for usage. - */ - -/** - * @ngdoc service - * @name $sanitize - * @kind function - * - * @description - * Sanitizes an html string by stripping all potentially dangerous tokens. - * - * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are - * then serialized back to properly escaped html string. This means that no unsafe input can make - * it into the returned string. - * - * The whitelist for URL sanitization of attribute values is configured using the functions - * `aHrefSanitizationWhitelist` and `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider - * `$compileProvider`}. - * - * The input may also contain SVG markup if this is enabled via {@link $sanitizeProvider}. - * - * @param {string} html HTML input. - * @returns {string} Sanitized HTML. - * - * @example - - - -
- Snippet: - - - - - - - - - - - - - - - - - - - - - - - - - -
DirectiveHowSourceRendered
ng-bind-htmlAutomatically uses $sanitize
<div ng-bind-html="snippet">
</div>
ng-bind-htmlBypass $sanitize by explicitly trusting the dangerous value -
<div ng-bind-html="deliberatelyTrustDangerousSnippet()">
-</div>
-
ng-bindAutomatically escapes
<div ng-bind="snippet">
</div>
-
-
- - it('should sanitize the html snippet by default', function() { - expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). - toBe('

an html\nclick here\nsnippet

'); - }); - - it('should inline raw snippet if bound to a trusted value', function() { - expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()). - toBe("

an html\n" + - "click here\n" + - "snippet

"); - }); - - it('should escape snippet without any filter', function() { - expect(element(by.css('#bind-default div')).getInnerHtml()). - toBe("<p style=\"color:blue\">an html\n" + - "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + - "snippet</p>"); - }); - - it('should update', function() { - element(by.model('snippet')).clear(); - element(by.model('snippet')).sendKeys('new text'); - expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). - toBe('new text'); - expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe( - 'new text'); - expect(element(by.css('#bind-default div')).getInnerHtml()).toBe( - "new <b onclick=\"alert(1)\">text</b>"); - }); -
-
- */ - - -/** - * @ngdoc provider - * @name $sanitizeProvider - * - * @description - * Creates and configures {@link $sanitize} instance. - */ -function $SanitizeProvider() { - var svgEnabled = false; - - this.$get = ['$$sanitizeUri', function($$sanitizeUri) { - if (svgEnabled) { - angular.extend(validElements, svgElements); - } - return function(html) { - var buf = []; - htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { - return !/^unsafe:/.test($$sanitizeUri(uri, isImage)); - })); - return buf.join(''); - }; - }]; - - - /** - * @ngdoc method - * @name $sanitizeProvider#enableSvg - * @kind function - * - * @description - * Enables a subset of svg to be supported by the sanitizer. - * - *
- *

By enabling this setting without taking other precautions, you might expose your - * application to click-hijacking attacks. In these attacks, sanitized svg elements could be positioned - * outside of the containing element and be rendered over other elements on the page (e.g. a login - * link). Such behavior can then result in phishing incidents.

- * - *

To protect against these, explicitly setup `overflow: hidden` css rule for all potential svg - * tags within the sanitized content:

- * - *
- * - *

-   *   .rootOfTheIncludedContent svg {
-   *     overflow: hidden !important;
-   *   }
-   *   
- *
- * - * @param {boolean=} regexp New regexp to whitelist urls with. - * @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called - * without an argument or self for chaining otherwise. - */ - this.enableSvg = function(enableSvg) { - if (angular.isDefined(enableSvg)) { - svgEnabled = enableSvg; - return this; - } else { - return svgEnabled; - } - }; -} - -function sanitizeText(chars) { - var buf = []; - var writer = htmlSanitizeWriter(buf, angular.noop); - writer.chars(chars); - return buf.join(''); -} - - -// Regular Expressions for parsing tags and attributes -var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, - // Match everything outside of normal chars and " (quote character) - NON_ALPHANUMERIC_REGEXP = /([^\#-~ |!])/g; - - -// Good source of info about elements and attributes -// http://dev.w3.org/html5/spec/Overview.html#semantics -// http://simon.html5.org/html-elements - -// Safe Void Elements - HTML5 -// http://dev.w3.org/html5/spec/Overview.html#void-elements -var voidElements = toMap("area,br,col,hr,img,wbr"); - -// Elements that you can, intentionally, leave open (and which close themselves) -// http://dev.w3.org/html5/spec/Overview.html#optional-tags -var optionalEndTagBlockElements = toMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), - optionalEndTagInlineElements = toMap("rp,rt"), - optionalEndTagElements = angular.extend({}, - optionalEndTagInlineElements, - optionalEndTagBlockElements); - -// Safe Block Elements - HTML5 -var blockElements = angular.extend({}, optionalEndTagBlockElements, toMap("address,article," + - "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," + - "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul")); - -// Inline Elements - HTML5 -var inlineElements = angular.extend({}, optionalEndTagInlineElements, toMap("a,abbr,acronym,b," + - "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," + - "samp,small,span,strike,strong,sub,sup,time,tt,u,var")); - -// SVG Elements -// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements -// Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted. -// They can potentially allow for arbitrary javascript to be executed. See #11290 -var svgElements = toMap("circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph," + - "hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline," + - "radialGradient,rect,stop,svg,switch,text,title,tspan"); - -// Blocked Elements (will be stripped) -var blockedElements = toMap("script,style"); - -var validElements = angular.extend({}, - voidElements, - blockElements, - inlineElements, - optionalEndTagElements); - -//Attributes that have href and hence need to be sanitized -var uriAttrs = toMap("background,cite,href,longdesc,src,xlink:href"); - -var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' + - 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' + - 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' + - 'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' + - 'valign,value,vspace,width'); - -// SVG attributes (without "id" and "name" attributes) -// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes -var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' + - 'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' + - 'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' + - 'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' + - 'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' + - 'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' + - 'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' + - 'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' + - 'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' + - 'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' + - 'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' + - 'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' + - 'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' + - 'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' + - 'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true); - -var validAttrs = angular.extend({}, - uriAttrs, - svgAttrs, - htmlAttrs); - -function toMap(str, lowercaseKeys) { - var obj = {}, items = str.split(','), i; - for (i = 0; i < items.length; i++) { - obj[lowercaseKeys ? angular.lowercase(items[i]) : items[i]] = true; - } - return obj; -} - -var inertBodyElement; -(function(window) { - var doc; - if (window.document && window.document.implementation) { - doc = window.document.implementation.createHTMLDocument("inert"); - } else { - throw $sanitizeMinErr('noinert', "Can't create an inert html document"); - } - var docElement = doc.documentElement || doc.getDocumentElement(); - var bodyElements = docElement.getElementsByTagName('body'); - - // usually there should be only one body element in the document, but IE doesn't have any, so we need to create one - if (bodyElements.length === 1) { - inertBodyElement = bodyElements[0]; - } else { - var html = doc.createElement('html'); - inertBodyElement = doc.createElement('body'); - html.appendChild(inertBodyElement); - doc.appendChild(html); - } -})(window); - -/** - * @example - * htmlParser(htmlString, { - * start: function(tag, attrs) {}, - * end: function(tag) {}, - * chars: function(text) {}, - * comment: function(text) {} - * }); - * - * @param {string} html string - * @param {object} handler - */ -function htmlParser(html, handler) { - if (html === null || html === undefined) { - html = ''; - } else if (typeof html !== 'string') { - html = '' + html; - } - inertBodyElement.innerHTML = html; - - //mXSS protection - var mXSSAttempts = 5; - do { - if (mXSSAttempts === 0) { - throw $sanitizeMinErr('uinput', "Failed to sanitize html because the input is unstable"); - } - mXSSAttempts--; - - // strip custom-namespaced attributes on IE<=11 - if (document.documentMode <= 11) { - stripCustomNsAttrs(inertBodyElement); - } - html = inertBodyElement.innerHTML; //trigger mXSS - inertBodyElement.innerHTML = html; - } while (html !== inertBodyElement.innerHTML); - - var node = inertBodyElement.firstChild; - while (node) { - switch (node.nodeType) { - case 1: // ELEMENT_NODE - handler.start(node.nodeName.toLowerCase(), attrToMap(node.attributes)); - break; - case 3: // TEXT NODE - handler.chars(node.textContent); - break; - } - - var nextNode; - if (!(nextNode = node.firstChild)) { - if (node.nodeType == 1) { - handler.end(node.nodeName.toLowerCase()); - } - nextNode = node.nextSibling; - if (!nextNode) { - while (nextNode == null) { - node = node.parentNode; - if (node === inertBodyElement) break; - nextNode = node.nextSibling; - if (node.nodeType == 1) { - handler.end(node.nodeName.toLowerCase()); - } - } - } - } - node = nextNode; - } - - while (node = inertBodyElement.firstChild) { - inertBodyElement.removeChild(node); - } -} - -function attrToMap(attrs) { - var map = {}; - for (var i = 0, ii = attrs.length; i < ii; i++) { - var attr = attrs[i]; - map[attr.name] = attr.value; - } - return map; -} - - -/** - * Escapes all potentially dangerous characters, so that the - * resulting string can be safely inserted into attribute or - * element text. - * @param value - * @returns {string} escaped text - */ -function encodeEntities(value) { - return value. - replace(/&/g, '&'). - replace(SURROGATE_PAIR_REGEXP, function(value) { - var hi = value.charCodeAt(0); - var low = value.charCodeAt(1); - return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'; - }). - replace(NON_ALPHANUMERIC_REGEXP, function(value) { - return '&#' + value.charCodeAt(0) + ';'; - }). - replace(//g, '>'); -} - -/** - * create an HTML/XML writer which writes to buffer - * @param {Array} buf use buf.join('') to get out sanitized html string - * @returns {object} in the form of { - * start: function(tag, attrs) {}, - * end: function(tag) {}, - * chars: function(text) {}, - * comment: function(text) {} - * } - */ -function htmlSanitizeWriter(buf, uriValidator) { - var ignoreCurrentElement = false; - var out = angular.bind(buf, buf.push); - return { - start: function(tag, attrs) { - tag = angular.lowercase(tag); - if (!ignoreCurrentElement && blockedElements[tag]) { - ignoreCurrentElement = tag; - } - if (!ignoreCurrentElement && validElements[tag] === true) { - out('<'); - out(tag); - angular.forEach(attrs, function(value, key) { - var lkey=angular.lowercase(key); - var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background'); - if (validAttrs[lkey] === true && - (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { - out(' '); - out(key); - out('="'); - out(encodeEntities(value)); - out('"'); - } - }); - out('>'); - } - }, - end: function(tag) { - tag = angular.lowercase(tag); - if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) { - out(''); - } - if (tag == ignoreCurrentElement) { - ignoreCurrentElement = false; - } - }, - chars: function(chars) { - if (!ignoreCurrentElement) { - out(encodeEntities(chars)); - } - } - }; -} - - -/** - * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' attribute to declare - * ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). This is undesirable since we don't want - * to allow any of these custom attributes. This method strips them all. - * - * @param node Root element to process - */ -function stripCustomNsAttrs(node) { - if (node.nodeType === Node.ELEMENT_NODE) { - var attrs = node.attributes; - for (var i = 0, l = attrs.length; i < l; i++) { - var attrNode = attrs[i]; - var attrName = attrNode.name.toLowerCase(); - if (attrName === 'xmlns:ns1' || attrName.indexOf('ns1:') === 0) { - node.removeAttributeNode(attrNode); - i--; - l--; - } - } - } - - var nextNode = node.firstChild; - if (nextNode) { - stripCustomNsAttrs(nextNode); - } - - nextNode = node.nextSibling; - if (nextNode) { - stripCustomNsAttrs(nextNode); - } -} - - - -// define ngSanitize module and register $sanitize service -angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); - -/* global sanitizeText: false */ - -/** - * @ngdoc filter - * @name linky - * @kind function - * - * @description - * Finds links in text input and turns them into html links. Supports `http/https/ftp/mailto` and - * plain email address links. - * - * Requires the {@link ngSanitize `ngSanitize`} module to be installed. - * - * @param {string} text Input text. - * @param {string} target Window (`_blank|_self|_parent|_top`) or named frame to open links in. - * @param {object|function(url)} [attributes] Add custom attributes to the link element. - * - * Can be one of: - * - * - `object`: A map of attributes - * - `function`: Takes the url as a parameter and returns a map of attributes - * - * If the map of attributes contains a value for `target`, it overrides the value of - * the target parameter. - * - * - * @returns {string} Html-linkified and {@link $sanitize sanitized} text. - * - * @usage - - * - * @example - - -
- Snippet: - - - - - - - - - - - - - - - - - - - - - - - - - - -
FilterSourceRendered
linky filter -
<div ng-bind-html="snippet | linky">
</div>
-
-
-
linky target -
<div ng-bind-html="snippetWithSingleURL | linky:'_blank'">
</div>
-
-
-
linky custom attributes -
<div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}">
</div>
-
-
-
no filter
<div ng-bind="snippet">
</div>
- - - angular.module('linkyExample', ['ngSanitize']) - .controller('ExampleController', ['$scope', function($scope) { - $scope.snippet = - 'Pretty text with some links:\n'+ - 'http://angularjs.org/,\n'+ - 'mailto:us@somewhere.org,\n'+ - 'another@somewhere.org,\n'+ - 'and one more: ftp://127.0.0.1/.'; - $scope.snippetWithSingleURL = 'http://angularjs.org/'; - }]); - - - it('should linkify the snippet with urls', function() { - expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). - toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' + - 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); - expect(element.all(by.css('#linky-filter a')).count()).toEqual(4); - }); - - it('should not linkify snippet without the linky filter', function() { - expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()). - toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' + - 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); - expect(element.all(by.css('#escaped-html a')).count()).toEqual(0); - }); - - it('should update', function() { - element(by.model('snippet')).clear(); - element(by.model('snippet')).sendKeys('new http://link.'); - expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). - toBe('new http://link.'); - expect(element.all(by.css('#linky-filter a')).count()).toEqual(1); - expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()) - .toBe('new http://link.'); - }); - - it('should work with the target property', function() { - expect(element(by.id('linky-target')). - element(by.binding("snippetWithSingleURL | linky:'_blank'")).getText()). - toBe('http://angularjs.org/'); - expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank'); - }); - - it('should optionally add custom attributes', function() { - expect(element(by.id('linky-custom-attributes')). - element(by.binding("snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}")).getText()). - toBe('http://angularjs.org/'); - expect(element(by.css('#linky-custom-attributes a')).getAttribute('rel')).toEqual('nofollow'); - }); - - - */ -angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { - var LINKY_URL_REGEXP = - /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i, - MAILTO_REGEXP = /^mailto:/i; - - var linkyMinErr = angular.$$minErr('linky'); - var isString = angular.isString; - - return function(text, target, attributes) { - if (text == null || text === '') return text; - if (!isString(text)) throw linkyMinErr('notstring', 'Expected string but received: {0}', text); - - var match; - var raw = text; - var html = []; - var url; - var i; - while ((match = raw.match(LINKY_URL_REGEXP))) { - // We can not end in these as they are sometimes found at the end of the sentence - url = match[0]; - // if we did not match ftp/http/www/mailto then assume mailto - if (!match[2] && !match[4]) { - url = (match[3] ? 'http://' : 'mailto:') + url; - } - i = match.index; - addText(raw.substr(0, i)); - addLink(url, match[0].replace(MAILTO_REGEXP, '')); - raw = raw.substring(i + match[0].length); - } - addText(raw); - return $sanitize(html.join('')); - - function addText(text) { - if (!text) { - return; - } - html.push(sanitizeText(text)); - } - - function addLink(url, text) { - var key; - html.push(''); - addText(text); - html.push(''); - } - }; -}]); - - -})(window, window.angular); diff --git a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-sanitize.min.js b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-sanitize.min.js deleted file mode 100644 index 135d5a0e..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-sanitize.min.js +++ /dev/null @@ -1,15 +0,0 @@ -/* - AngularJS v1.5.0 - (c) 2010-2016 Google, Inc. http://angularjs.org - License: MIT -*/ -(function(A,e,B){'use strict';function C(a){var c=[];v(c,e.noop).chars(a);return c.join("")}function h(a,c){var b={},d=a.split(","),l;for(l=0;l=document.documentMode&&n(g);a=g.innerHTML;g.innerHTML=a}while(a!==g.innerHTML);for(b=g.firstChild;b;){switch(b.nodeType){case 1:c.start(b.nodeName.toLowerCase(),E(b.attributes)); -break;case 3:c.chars(b.textContent)}var d;if(!(d=b.firstChild)&&(1==b.nodeType&&c.end(b.nodeName.toLowerCase()),d=b.nextSibling,!d))for(;null==d;){b=b.parentNode;if(b===g)break;d=b.nextSibling;1==b.nodeType&&c.end(b.nodeName.toLowerCase())}b=d}for(;b=g.firstChild;)g.removeChild(b)}function E(a){for(var c={},b=0,d=a.length;b/g,">")}function v(a,c){var b=!1,d=e.bind(a,a.push);return{start:function(a,f){a=e.lowercase(a);!b&&H[a]&&(b=a);b||!0!==t[a]||(d("<"),d(a),e.forEach(f,function(b,f){var g=e.lowercase(f),h="img"===a&&"src"===g||"background"===g;!0!==I[g]||!0===y[g]&&!c(b,h)||(d(" "),d(f),d('="'),d(x(b)),d('"'))}),d(">"))},end:function(a){a=e.lowercase(a);b||!0!==t[a]||!0===z[a]||(d(""));a== -b&&(b=!1)},chars:function(a){b||d(x(a))}}}function n(a){if(a.nodeType===Node.ELEMENT_NODE)for(var c=a.attributes,b=0,d=c.length;b"\u201d\u2019]/i,b=/^mailto:/i,d=e.$$minErr("linky"),g=e.isString;return function(f,h,m){function k(a){a&&p.push(C(a))}function q(a,b){var c;p.push("');k(b);p.push("")}if(null==f||""===f)return f;if(!g(f))throw d("notstring",f);for(var r=f,p=[],s,n;f=r.match(c);)s=f[0],f[2]||f[4]||(s=(f[3]?"http://":"mailto:")+s),n=f.index,k(r.substr(0,n)),q(s,f[0].replace(b,"")),r=r.substring(n+f[0].length);k(r);return a(p.join(""))}}])})(window,window.angular); -//# sourceMappingURL=angular-sanitize.min.js.map diff --git a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-scenario.js b/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-scenario.js deleted file mode 100644 index 20af805f..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/app/fusion/external/angular-1.5/angular-scenario.js +++ /dev/null @@ -1,41849 +0,0 @@ -/*! - * jQuery JavaScript Library v2.1.1 - * http://jquery.com/ - * - * Includes Sizzle.js - * http://sizzlejs.com/ - * - * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors - * Released under the MIT license - * http://jquery.org/license - * - * Date: 2014-05-01T17:11Z - */ - -(function( global, factory ) {'use strict'; - - if ( typeof module === "object" && typeof module.exports === "object" ) { - // For CommonJS and CommonJS-like environments where a proper window is present, - // execute the factory and get jQuery - // For environments that do not inherently posses a window with a document - // (such as Node.js), expose a jQuery-making factory as module.exports - // This accentuates the need for the creation of a real window - // e.g. var jQuery = require("jquery")(window); - // See ticket #14549 for more info - module.exports = global.document ? - factory( global, true ) : - function( w ) { - if ( !w.document ) { - throw new Error( "jQuery requires a window with a document" ); - } - return factory( w ); - }; - } else { - factory( global ); - } - -// Pass this if window is not defined yet -}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { - -// Can't do this because several apps including ASP.NET trace -// the stack via arguments.caller.callee and Firefox dies if -// you try to trace through "use strict" call chains. (#13335) -// Support: Firefox 18+ -// - -var arr = []; - -var slice = arr.slice; - -var concat = arr.concat; - -var push = arr.push; - -var indexOf = arr.indexOf; - -var class2type = {}; - -var toString = class2type.toString; - -var hasOwn = class2type.hasOwnProperty; - -var support = {}; - - - -var - // Use the correct document accordingly with window argument (sandbox) - document = window.document, - - version = "2.1.1", - - // Define a local copy of jQuery - jQuery = function( selector, context ) { - // The jQuery object is actually just the init constructor 'enhanced' - // Need init if jQuery is called (just allow error to be thrown if not included) - return new jQuery.fn.init( selector, context ); - }, - - // Support: Android<4.1 - // Make sure we trim BOM and NBSP - rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, - - // Matches dashed string for camelizing - rmsPrefix = /^-ms-/, - rdashAlpha = /-([\da-z])/gi, - - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function( all, letter ) { - return letter.toUpperCase(); - }; - -jQuery.fn = jQuery.prototype = { - // The current version of jQuery being used - jquery: version, - - constructor: jQuery, - - // Start with an empty selector - selector: "", - - // The default length of a jQuery object is 0 - length: 0, - - toArray: function() { - return slice.call( this ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - return num != null ? - - // Return just the one element from the set - ( num < 0 ? this[ num + this.length ] : this[ num ] ) : - - // Return all the elements in a clean array - slice.call( this ); - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems ) { - - // Build a new jQuery matched element set - var ret = jQuery.merge( this.constructor(), elems ); - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - ret.context = this.context; - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - return jQuery.each( this, callback, args ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map(this, function( elem, i ) { - return callback.call( elem, i, elem ); - })); - }, - - slice: function() { - return this.pushStack( slice.apply( this, arguments ) ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - eq: function( i ) { - var len = this.length, - j = +i + ( i < 0 ? len : 0 ); - return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); - }, - - end: function() { - return this.prevObject || this.constructor(null); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: arr.sort, - splice: arr.splice -}; - -jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - - // skip the boolean and the target - target = arguments[ i ] || {}; - i++; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if ( i === length ) { - target = this; - i--; - } - - for ( ; i < length; i++ ) { - // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { - if ( copyIsArray ) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; - - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend({ - // Unique for each copy of jQuery on the page - expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), - - // Assume jQuery is ready without the ready module - isReady: true, - - error: function( msg ) { - throw new Error( msg ); - }, - - noop: function() {}, - - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). - isFunction: function( obj ) { - return jQuery.type(obj) === "function"; - }, - - isArray: Array.isArray, - - isWindow: function( obj ) { - return obj != null && obj === obj.window; - }, - - isNumeric: function( obj ) { - // parseFloat NaNs numeric-cast false positives (null|true|false|"") - // ...but misinterprets leading-number strings, particularly hex literals ("0x...") - // subtraction forces infinities to NaN - return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; - }, - - isPlainObject: function( obj ) { - // Not plain objects: - // - Any object or value whose internal [[Class]] property is not "[object Object]" - // - DOM nodes - // - window - if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { - return false; - } - - if ( obj.constructor && - !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { - return false; - } - - // If the function hasn't returned already, we're confident that - // |obj| is a plain object, created by {} or constructed with new Object - return true; - }, - - isEmptyObject: function( obj ) { - var name; - for ( name in obj ) { - return false; - } - return true; - }, - - type: function( obj ) { - if ( obj == null ) { - return obj + ""; - } - // Support: Android < 4.0, iOS < 6 (functionish RegExp) - return typeof obj === "object" || typeof obj === "function" ? - class2type[ toString.call(obj) ] || "object" : - typeof obj; - }, - - // Evaluates a script in a global context - globalEval: function( code ) { - var script, - indirect = eval; - - code = jQuery.trim( code ); - - if ( code ) { - // If the code includes a valid, prologue position - // strict mode pragma, execute code by injecting a - // script tag into the document. - if ( code.indexOf("use strict") === 1 ) { - script = document.createElement("script"); - script.text = code; - document.head.appendChild( script ).parentNode.removeChild( script ); - } else { - // Otherwise, avoid the DOM node creation, insertion - // and removal by using an indirect global eval - indirect( code ); - } - } - }, - - // Convert dashed to camelCase; used by the css and data modules - // Microsoft forgot to hump their vendor prefix (#9572) - camelCase: function( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); - }, - - nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); - }, - - // args is for internal usage only - each: function( obj, callback, args ) { - var value, - i = 0, - length = obj.length, - isArray = isArraylike( obj ); - - if ( args ) { - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback.apply( obj[ i ], args ); - - if ( value === false ) { - break; - } - } - } else { - for ( i in obj ) { - value = callback.apply( obj[ i ], args ); - - if ( value === false ) { - break; - } - } - } - - // A special, fast, case for the most common use of each - } else { - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback.call( obj[ i ], i, obj[ i ] ); - - if ( value === false ) { - break; - } - } - } else { - for ( i in obj ) { - value = callback.call( obj[ i ], i, obj[ i ] ); - - if ( value === false ) { - break; - } - } - } - } - - return obj; - }, - - // Support: Android<4.1 - trim: function( text ) { - return text == null ? - "" : - ( text + "" ).replace( rtrim, "" ); - }, - - // results is for internal usage only - makeArray: function( arr, results ) { - var ret = results || []; - - if ( arr != null ) { - if ( isArraylike( Object(arr) ) ) { - jQuery.merge( ret, - typeof arr === "string" ? - [ arr ] : arr - ); - } else { - push.call( ret, arr ); - } - } - - return ret; - }, - - inArray: function( elem, arr, i ) { - return arr == null ? -1 : indexOf.call( arr, elem, i ); - }, - - merge: function( first, second ) { - var len = +second.length, - j = 0, - i = first.length; - - for ( ; j < len; j++ ) { - first[ i++ ] = second[ j ]; - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, invert ) { - var callbackInverse, - matches = [], - i = 0, - length = elems.length, - callbackExpect = !invert; - - // Go through the array, only saving the items - // that pass the validator function - for ( ; i < length; i++ ) { - callbackInverse = !callback( elems[ i ], i ); - if ( callbackInverse !== callbackExpect ) { - matches.push( elems[ i ] ); - } - } - - return matches; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var value, - i = 0, - length = elems.length, - isArray = isArraylike( elems ), - ret = []; - - // Go through the array, translating each of the items to their new values - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret.push( value ); - } - } - - // Go through every key on the object, - } else { - for ( i in elems ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret.push( value ); - } - } - } - - // Flatten any nested arrays - return concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function( fn, context ) { - var tmp, args, proxy; - - if ( typeof context === "string" ) { - tmp = fn[ context ]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if ( !jQuery.isFunction( fn ) ) { - return undefined; - } - - // Simulated bind - args = slice.call( arguments, 2 ); - proxy = function() { - return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || jQuery.guid++; - - return proxy; - }, - - now: Date.now, - - // jQuery.support is not used in Core but other projects attach their - // properties to it so it needs to exist. - support: support -}); - -// Populate the class2type map -jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -}); - -function isArraylike( obj ) { - var length = obj.length, - type = jQuery.type( obj ); - - if ( type === "function" || jQuery.isWindow( obj ) ) { - return false; - } - - if ( obj.nodeType === 1 && length ) { - return true; - } - - return type === "array" || length === 0 || - typeof length === "number" && length > 0 && ( length - 1 ) in obj; -} -var Sizzle = -/*! - * Sizzle CSS Selector Engine v1.10.19 - * http://sizzlejs.com/ - * - * Copyright 2013 jQuery Foundation, Inc. and other contributors - * Released under the MIT license - * http://jquery.org/license - * - * Date: 2014-04-18 - */ -(function( window ) { - -var i, - support, - Expr, - getText, - isXML, - tokenize, - compile, - select, - outermostContext, - sortInput, - hasDuplicate, - - // Local document vars - setDocument, - document, - docElem, - documentIsHTML, - rbuggyQSA, - rbuggyMatches, - matches, - contains, - - // Instance-specific data - expando = "sizzle" + -(new Date()), - preferredDoc = window.document, - dirruns = 0, - done = 0, - classCache = createCache(), - tokenCache = createCache(), - compilerCache = createCache(), - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - } - return 0; - }, - - // General-purpose constants - strundefined = typeof undefined, - MAX_NEGATIVE = 1 << 31, - - // Instance methods - hasOwn = ({}).hasOwnProperty, - arr = [], - pop = arr.pop, - push_native = arr.push, - push = arr.push, - slice = arr.slice, - // Use a stripped-down indexOf if we can't use a native one - indexOf = arr.indexOf || function( elem ) { - var i = 0, - len = this.length; - for ( ; i < len; i++ ) { - if ( this[i] === elem ) { - return i; - } - } - return -1; - }, - - booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", - - // Regular expressions - - // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace - whitespace = "[\\x20\\t\\r\\n\\f]", - // http://www.w3.org/TR/css3-syntax/#characters - characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", - - // Loosely modeled on CSS identifier characters - // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors - // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier - identifier = characterEncoding.replace( "w", "w#" ), - - // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors - attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + - // Operator (capture 2) - "*([*^$|!~]?=)" + whitespace + - // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" - "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + - "*\\]", - - pseudos = ":(" + characterEncoding + ")(?:\\((" + - // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: - // 1. quoted (capture 3; capture 4 or capture 5) - "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + - // 2. simple (capture 6) - "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + - // 3. anything else (capture 2) - ".*" + - ")\\)|)", - - // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter - rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), - - rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), - rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), - - rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), - - rpseudo = new RegExp( pseudos ), - ridentifier = new RegExp( "^" + identifier + "$" ), - - matchExpr = { - "ID": new RegExp( "^#(" + characterEncoding + ")" ), - "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), - "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), - "ATTR": new RegExp( "^" + attributes ), - "PSEUDO": new RegExp( "^" + pseudos ), - "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + - "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + - "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), - "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), - // For use in libraries implementing .is() - // We use this for POS matching in `select` - "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + - whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) - }, - - rinputs = /^(?:input|select|textarea|button)$/i, - rheader = /^h\d$/i, - - rnative = /^[^{]+\{\s*\[native \w/, - - // Easily-parseable/retrievable ID or TAG or CLASS selectors - rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, - - rsibling = /[+~]/, - rescape = /'|\\/g, - - // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters - runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), - funescape = function( _, escaped, escapedWhitespace ) { - var high = "0x" + escaped - 0x10000; - // NaN means non-codepoint - // Support: Firefox<24 - // Workaround erroneous numeric interpretation of +"0x" - return high !== high || escapedWhitespace ? - escaped : - high < 0 ? - // BMP codepoint - String.fromCharCode( high + 0x10000 ) : - // Supplemental Plane codepoint (surrogate pair) - String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); - }; - -// Optimize for push.apply( _, NodeList ) -try { - push.apply( - (arr = slice.call( preferredDoc.childNodes )), - preferredDoc.childNodes - ); - // Support: Android<4.0 - // Detect silently failing push.apply - arr[ preferredDoc.childNodes.length ].nodeType; -} catch ( e ) { - push = { apply: arr.length ? - - // Leverage slice if possible - function( target, els ) { - push_native.apply( target, slice.call(els) ); - } : - - // Support: IE<9 - // Otherwise append directly - function( target, els ) { - var j = target.length, - i = 0; - // Can't trust NodeList.length - while ( (target[j++] = els[i++]) ) {} - target.length = j - 1; - } - }; -} - -function Sizzle( selector, context, results, seed ) { - var match, elem, m, nodeType, - // QSA vars - i, groups, old, nid, newContext, newSelector; - - if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { - setDocument( context ); - } - - context = context || document; - results = results || []; - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { - return []; - } - - if ( documentIsHTML && !seed ) { - - // Shortcuts - if ( (match = rquickExpr.exec( selector )) ) { - // Speed-up: Sizzle("#ID") - if ( (m = match[1]) ) { - if ( nodeType === 9 ) { - elem = context.getElementById( m ); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document (jQuery #6963) - if ( elem && elem.parentNode ) { - // Handle the case where IE, Opera, and Webkit return items - // by name instead of ID - if ( elem.id === m ) { - results.push( elem ); - return results; - } - } else { - return results; - } - } else { - // Context is not a document - if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && - contains( context, elem ) && elem.id === m ) { - results.push( elem ); - return results; - } - } - - // Speed-up: Sizzle("TAG") - } else if ( match[2] ) { - push.apply( results, context.getElementsByTagName( selector ) ); - return results; - - // Speed-up: Sizzle(".CLASS") - } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { - push.apply( results, context.getElementsByClassName( m ) ); - return results; - } - } - - // QSA path - if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { - nid = old = expando; - newContext = context; - newSelector = nodeType === 9 && selector; - - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - groups = tokenize( selector ); - - if ( (old = context.getAttribute("id")) ) { - nid = old.replace( rescape, "\\$&" ); - } else { - context.setAttribute( "id", nid ); - } - nid = "[id='" + nid + "'] "; - - i = groups.length; - while ( i-- ) { - groups[i] = nid + toSelector( groups[i] ); - } - newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; - newSelector = groups.join(","); - } - - if ( newSelector ) { - try { - push.apply( results, - newContext.querySelectorAll( newSelector ) - ); - return results; - } catch(qsaError) { - } finally { - if ( !old ) { - context.removeAttribute("id"); - } - } - } - } - } - - // All others - return select( selector.replace( rtrim, "$1" ), context, results, seed ); -} - -/** - * Create key-value caches of limited size - * @returns {Function(string, Object)} Returns the Object data after storing it on itself with - * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) - * deleting the oldest entry - */ -function createCache() { - var keys = []; - - function cache( key, value ) { - // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) - if ( keys.push( key + " " ) > Expr.cacheLength ) { - // Only keep the most recent entries - delete cache[ keys.shift() ]; - } - return (cache[ key + " " ] = value); - } - return cache; -} - -/** - * Mark a function for special use by Sizzle - * @param {Function} fn The function to mark - */ -function markFunction( fn ) { - fn[ expando ] = true; - return fn; -} - -/** - * Support testing using an element - * @param {Function} fn Passed the created div and expects a boolean result - */ -function assert( fn ) { - var div = document.createElement("div"); - - try { - return !!fn( div ); - } catch (e) { - return false; - } finally { - // Remove from its parent by default - if ( div.parentNode ) { - div.parentNode.removeChild( div ); - } - // release memory in IE - div = null; - } -} - -/** - * Adds the same handler for all of the specified attrs - * @param {String} attrs Pipe-separated list of attributes - * @param {Function} handler The method that will be applied - */ -function addHandle( attrs, handler ) { - var arr = attrs.split("|"), - i = attrs.length; - - while ( i-- ) { - Expr.attrHandle[ arr[i] ] = handler; - } -} - -/** - * Checks document order of two siblings - * @param {Element} a - * @param {Element} b - * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b - */ -function siblingCheck( a, b ) { - var cur = b && a, - diff = cur && a.nodeType === 1 && b.nodeType === 1 && - ( ~b.sourceIndex || MAX_NEGATIVE ) - - ( ~a.sourceIndex || MAX_NEGATIVE ); - - // Use IE sourceIndex if available on both nodes - if ( diff ) { - return diff; - } - - // Check if b follows a - if ( cur ) { - while ( (cur = cur.nextSibling) ) { - if ( cur === b ) { - return -1; - } - } - } - - return a ? 1 : -1; -} - -/** - * Returns a function to use in pseudos for input types - * @param {String} type - */ -function createInputPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === type; - }; -} - -/** - * Returns a function to use in pseudos for buttons - * @param {String} type - */ -function createButtonPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && elem.type === type; - }; -} - -/** - * Returns a function to use in pseudos for positionals - * @param {Function} fn - */ -function createPositionalPseudo( fn ) { - return markFunction(function( argument ) { - argument = +argument; - return markFunction(function( seed, matches ) { - var j, - matchIndexes = fn( [], seed.length, argument ), - i = matchIndexes.length; - - // Match elements found at the specified indexes - while ( i-- ) { - if ( seed[ (j = matchIndexes[i]) ] ) { - seed[j] = !(matches[j] = seed[j]); - } - } - }); - }); -} - -/** - * Checks a node for validity as a Sizzle context - * @param {Element|Object=} context - * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value - */ -function testContext( context ) { - return context && typeof context.getElementsByTagName !== strundefined && context; -} - -// Expose support vars for convenience -support = Sizzle.support = {}; - -/** - * Detects XML nodes - * @param {Element|Object} elem An element or a document - * @returns {Boolean} True iff elem is a non-HTML XML node - */ -isXML = Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = elem && (elem.ownerDocument || elem).documentElement; - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -/** - * Sets document-related variables once based on the current document - * @param {Element|Object} [doc] An element or document object to use to set the document - * @returns {Object} Returns the current document - */ -setDocument = Sizzle.setDocument = function( node ) { - var hasCompare, - doc = node ? node.ownerDocument || node : preferredDoc, - parent = doc.defaultView; - - // If no document and documentElement is available, return - if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { - return document; - } - - // Set our document - document = doc; - docElem = doc.documentElement; - - // Support tests - documentIsHTML = !isXML( doc ); - - // Support: IE>8 - // If iframe document is assigned to "document" variable and if iframe has been reloaded, - // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 - // IE6-8 do not support the defaultView property so parent will be undefined - if ( parent && parent !== parent.top ) { - // IE11 does not have attachEvent, so all must suffer - if ( parent.addEventListener ) { - parent.addEventListener( "unload", function() { - setDocument(); - }, false ); - } else if ( parent.attachEvent ) { - parent.attachEvent( "onunload", function() { - setDocument(); - }); - } - } - - /* Attributes - ---------------------------------------------------------------------- */ - - // Support: IE<8 - // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) - support.attributes = assert(function( div ) { - div.className = "i"; - return !div.getAttribute("className"); - }); - - /* getElement(s)By* - ---------------------------------------------------------------------- */ - - // Check if getElementsByTagName("*") returns only elements - support.getElementsByTagName = assert(function( div ) { - div.appendChild( doc.createComment("") ); - return !div.getElementsByTagName("*").length; - }); - - // Check if getElementsByClassName can be trusted - support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { - div.innerHTML = "
"; - - // Support: Safari<4 - // Catch class over-caching - div.firstChild.className = "i"; - // Support: Opera<10 - // Catch gEBCN failure to find non-leading classes - return div.getElementsByClassName("i").length === 2; - }); - - // Support: IE<10 - // Check if getElementById returns elements by name - // The broken getElementById methods don't pick up programatically-set names, - // so use a roundabout getElementsByName test - support.getById = assert(function( div ) { - docElem.appendChild( div ).id = expando; - return !doc.getElementsByName || !doc.getElementsByName( expando ).length; - }); - - // ID find and filter - if ( support.getById ) { - Expr.find["ID"] = function( id, context ) { - if ( typeof context.getElementById !== strundefined && documentIsHTML ) { - var m = context.getElementById( id ); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [ m ] : []; - } - }; - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - return elem.getAttribute("id") === attrId; - }; - }; - } else { - // Support: IE6/7 - // getElementById is not reliable as a find shortcut - delete Expr.find["ID"]; - - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); - return node && node.value === attrId; - }; - }; - } - - // Tag - Expr.find["TAG"] = support.getElementsByTagName ? - function( tag, context ) { - if ( typeof context.getElementsByTagName !== strundefined ) { - return context.getElementsByTagName( tag ); - } - } : - function( tag, context ) { - var elem, - tmp = [], - i = 0, - results = context.getElementsByTagName( tag ); - - // Filter out possible comments - if ( tag === "*" ) { - while ( (elem = results[i++]) ) { - if ( elem.nodeType === 1 ) { - tmp.push( elem ); - } - } - - return tmp; - } - return results; - }; - - // Class - Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { - if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { - return context.getElementsByClassName( className ); - } - }; - - /* QSA/matchesSelector - ---------------------------------------------------------------------- */ - - // QSA and matchesSelector support - - // matchesSelector(:active) reports false when true (IE9/Opera 11.5) - rbuggyMatches = []; - - // qSa(:focus) reports false when true (Chrome 21) - // We allow this because of a bug in IE8/9 that throws an error - // whenever `document.activeElement` is accessed on an iframe - // So, we allow :focus to pass through QSA all the time to avoid the IE error - // See http://bugs.jquery.com/ticket/13378 - rbuggyQSA = []; - - if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { - // Build QSA regex - // Regex strategy adopted from Diego Perini - assert(function( div ) { - // Select is set to empty string on purpose - // This is to test IE's treatment of not explicitly - // setting a boolean content attribute, - // since its presence should be enough - // http://bugs.jquery.com/ticket/12359 - div.innerHTML = ""; - - // Support: IE8, Opera 11-12.16 - // Nothing should be selected when empty strings follow ^= or $= or *= - // The test attribute must be unknown in Opera but "safe" for WinRT - // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section - if ( div.querySelectorAll("[msallowclip^='']").length ) { - rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); - } - - // Support: IE8 - // Boolean attributes and "value" are not treated correctly - if ( !div.querySelectorAll("[selected]").length ) { - rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); - } - - // Webkit/Opera - :checked should return selected option elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - // IE8 throws error here and will not see later tests - if ( !div.querySelectorAll(":checked").length ) { - rbuggyQSA.push(":checked"); - } - }); - - assert(function( div ) { - // Support: Windows 8 Native Apps - // The type and name attributes are restricted during .innerHTML assignment - var input = doc.createElement("input"); - input.setAttribute( "type", "hidden" ); - div.appendChild( input ).setAttribute( "name", "D" ); - - // Support: IE8 - // Enforce case-sensitivity of name attribute - if ( div.querySelectorAll("[name=d]").length ) { - rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); - } - - // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) - // IE8 throws error here and will not see later tests - if ( !div.querySelectorAll(":enabled").length ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } - - // Opera 10-11 does not throw on post-comma invalid pseudos - div.querySelectorAll("*,:x"); - rbuggyQSA.push(",.*:"); - }); - } - - if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || - docElem.webkitMatchesSelector || - docElem.mozMatchesSelector || - docElem.oMatchesSelector || - docElem.msMatchesSelector) )) ) { - - assert(function( div ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9) - support.disconnectedMatch = matches.call( div, "div" ); - - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( div, "[s!='']:x" ); - rbuggyMatches.push( "!=", pseudos ); - }); - } - - rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); - rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); - - /* Contains - ---------------------------------------------------------------------- */ - hasCompare = rnative.test( docElem.compareDocumentPosition ); - - // Element contains another - // Purposefully does not implement inclusive descendent - // As in, an element does not contain itself - contains = hasCompare || rnative.test( docElem.contains ) ? - function( a, b ) { - var adown = a.nodeType === 9 ? a.documentElement : a, - bup = b && b.parentNode; - return a === bup || !!( bup && bup.nodeType === 1 && ( - adown.contains ? - adown.contains( bup ) : - a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 - )); - } : - function( a, b ) { - if ( b ) { - while ( (b = b.parentNode) ) { - if ( b === a ) { - return true; - } - } - } - return false; - }; - - /* Sorting - ---------------------------------------------------------------------- */ - - // Document order sorting - sortOrder = hasCompare ? - function( a, b ) { - - // Flag for duplicate removal - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - // Sort on method existence if only one input has compareDocumentPosition - var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; - if ( compare ) { - return compare; - } - - // Calculate position if both inputs belong to the same document - compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? - a.compareDocumentPosition( b ) : - - // Otherwise we know they are disconnected - 1; - - // Disconnected nodes - if ( compare & 1 || - (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { - - // Choose the first element that is related to our preferred document - if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { - return -1; - } - if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { - return 1; - } - - // Maintain original order - return sortInput ? - ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : - 0; - } - - return compare & 4 ? -1 : 1; - } : - function( a, b ) { - // Exit early if the nodes are identical - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - var cur, - i = 0, - aup = a.parentNode, - bup = b.parentNode, - ap = [ a ], - bp = [ b ]; - - // Parentless nodes are either documents or disconnected - if ( !aup || !bup ) { - return a === doc ? -1 : - b === doc ? 1 : - aup ? -1 : - bup ? 1 : - sortInput ? - ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : - 0; - - // If the nodes are siblings, we can do a quick check - } else if ( aup === bup ) { - return siblingCheck( a, b ); - } - - // Otherwise we need full lists of their ancestors for comparison - cur = a; - while ( (cur = cur.parentNode) ) { - ap.unshift( cur ); - } - cur = b; - while ( (cur = cur.parentNode) ) { - bp.unshift( cur ); - } - - // Walk down the tree looking for a discrepancy - while ( ap[i] === bp[i] ) { - i++; - } - - return i ? - // Do a sibling check if the nodes have a common ancestor - siblingCheck( ap[i], bp[i] ) : - - // Otherwise nodes in our document sort first - ap[i] === preferredDoc ? -1 : - bp[i] === preferredDoc ? 1 : - 0; - }; - - return doc; -}; - -Sizzle.matches = function( expr, elements ) { - return Sizzle( expr, null, null, elements ); -}; - -Sizzle.matchesSelector = function( elem, expr ) { - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } - - // Make sure that attribute selectors are quoted - expr = expr.replace( rattributeQuotes, "='$1']" ); - - if ( support.matchesSelector && documentIsHTML && - ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && - ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { - - try { - var ret = matches.call( elem, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || support.disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9 - elem.document && elem.document.nodeType !== 11 ) { - return ret; - } - } catch(e) {} - } - - return Sizzle( expr, document, null, [ elem ] ).length > 0; -}; - -Sizzle.contains = function( context, elem ) { - // Set document vars if needed - if ( ( context.ownerDocument || context ) !== document ) { - setDocument( context ); - } - return contains( context, elem ); -}; - -Sizzle.attr = function( elem, name ) { - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } - - var fn = Expr.attrHandle[ name.toLowerCase() ], - // Don't get fooled by Object.prototype properties (jQuery #13807) - val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? - fn( elem, name, !documentIsHTML ) : - undefined; - - return val !== undefined ? - val : - support.attributes || !documentIsHTML ? - elem.getAttribute( name ) : - (val = elem.getAttributeNode(name)) && val.specified ? - val.value : - null; -}; - -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; - -/** - * Document sorting and removing duplicates - * @param {ArrayLike} results - */ -Sizzle.uniqueSort = function( results ) { - var elem, - duplicates = [], - j = 0, - i = 0; - - // Unless we *know* we can detect duplicates, assume their presence - hasDuplicate = !support.detectDuplicates; - sortInput = !support.sortStable && results.slice( 0 ); - results.sort( sortOrder ); - - if ( hasDuplicate ) { - while ( (elem = results[i++]) ) { - if ( elem === results[ i ] ) { - j = duplicates.push( i ); - } - } - while ( j-- ) { - results.splice( duplicates[ j ], 1 ); - } - } - - // Clear input after sorting to release objects - // See https://github.com/jquery/sizzle/pull/225 - sortInput = null; - - return results; -}; - -/** - * Utility function for retrieving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -getText = Sizzle.getText = function( elem ) { - var node, - ret = "", - i = 0, - nodeType = elem.nodeType; - - if ( !nodeType ) { - // If no nodeType, this is expected to be an array - while ( (node = elem[i++]) ) { - // Do not traverse comment nodes - ret += getText( node ); - } - } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - // Use textContent for elements - // innerText usage removed for consistency of new lines (jQuery #11153) - if ( typeof elem.textContent === "string" ) { - return elem.textContent; - } else { - // Traverse its children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - // Do not include comment or processing instruction nodes - - return ret; -}; - -Expr = Sizzle.selectors = { - - // Can be adjusted by the user - cacheLength: 50, - - createPseudo: markFunction, - - match: matchExpr, - - attrHandle: {}, - - find: {}, - - relative: { - ">": { dir: "parentNode", first: true }, - " ": { dir: "parentNode" }, - "+": { dir: "previousSibling", first: true }, - "~": { dir: "previousSibling" } - }, - - preFilter: { - "ATTR": function( match ) { - match[1] = match[1].replace( runescape, funescape ); - - // Move the given value to match[3] whether quoted or unquoted - match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); - - if ( match[2] === "~=" ) { - match[3] = " " + match[3] + " "; - } - - return match.slice( 0, 4 ); - }, - - "CHILD": function( match ) { - /* matches from matchExpr["CHILD"] - 1 type (only|nth|...) - 2 what (child|of-type) - 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) - 4 xn-component of xn+y argument ([+-]?\d*n|) - 5 sign of xn-component - 6 x of xn-component - 7 sign of y-component - 8 y of y-component - */ - match[1] = match[1].toLowerCase(); - - if ( match[1].slice( 0, 3 ) === "nth" ) { - // nth-* requires argument - if ( !match[3] ) { - Sizzle.error( match[0] ); - } - - // numeric x and y parameters for Expr.filter.CHILD - // remember that false/true cast respectively to 0/1 - match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); - match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); - - // other types prohibit arguments - } else if ( match[3] ) { - Sizzle.error( match[0] ); - } - - return match; - }, - - "PSEUDO": function( match ) { - var excess, - unquoted = !match[6] && match[2]; - - if ( matchExpr["CHILD"].test( match[0] ) ) { - return null; - } - - // Accept quoted arguments as-is - if ( match[3] ) { - match[2] = match[4] || match[5] || ""; - - // Strip excess characters from unquoted arguments - } else if ( unquoted && rpseudo.test( unquoted ) && - // Get excess from tokenize (recursively) - (excess = tokenize( unquoted, true )) && - // advance to the next closing parenthesis - (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { - - // excess is a negative index - match[0] = match[0].slice( 0, excess ); - match[2] = unquoted.slice( 0, excess ); - } - - // Return only captures needed by the pseudo filter method (type and argument) - return match.slice( 0, 3 ); - } - }, - - filter: { - - "TAG": function( nodeNameSelector ) { - var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); - return nodeNameSelector === "*" ? - function() { return true; } : - function( elem ) { - return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; - }; - }, - - "CLASS": function( className ) { - var pattern = classCache[ className + " " ]; - - return pattern || - (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && - classCache( className, function( elem ) { - return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); - }); - }, - - "ATTR": function( name, operator, check ) { - return function( elem ) { - var result = Sizzle.attr( elem, name ); - - if ( result == null ) { - return operator === "!="; - } - if ( !operator ) { - return true; - } - - result += ""; - - return operator === "=" ? result === check : - operator === "!=" ? result !== check : - operator === "^=" ? check && result.indexOf( check ) === 0 : - operator === "*=" ? check && result.indexOf( check ) > -1 : - operator === "$=" ? check && result.slice( -check.length ) === check : - operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : - operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : - false; - }; - }, - - "CHILD": function( type, what, argument, first, last ) { - var simple = type.slice( 0, 3 ) !== "nth", - forward = type.slice( -4 ) !== "last", - ofType = what === "of-type"; - - return first === 1 && last === 0 ? - - // Shortcut for :nth-*(n) - function( elem ) { - return !!elem.parentNode; - } : - - function( elem, context, xml ) { - var cache, outerCache, node, diff, nodeIndex, start, - dir = simple !== forward ? "nextSibling" : "previousSibling", - parent = elem.parentNode, - name = ofType && elem.nodeName.toLowerCase(), - useCache = !xml && !ofType; - - if ( parent ) { - - // :(first|last|only)-(child|of-type) - if ( simple ) { - while ( dir ) { - node = elem; - while ( (node = node[ dir ]) ) { - if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { - return false; - } - } - // Reverse direction for :only-* (if we haven't yet done so) - start = dir = type === "only" && !start && "nextSibling"; - } - return true; - } - - start = [ forward ? parent.firstChild : parent.lastChild ]; - - // non-xml :nth-child(...) stores cache data on `parent` - if ( forward && useCache ) { - // Seek `elem` from a previously-cached index - outerCache = parent[ expando ] || (parent[ expando ] = {}); - cache = outerCache[ type ] || []; - nodeIndex = cache[0] === dirruns && cache[1]; - diff = cache[0] === dirruns && cache[2]; - node = nodeIndex && parent.childNodes[ nodeIndex ]; - - while ( (node = ++nodeIndex && node && node[ dir ] || - - // Fallback to seeking `elem` from the start - (diff = nodeIndex = 0) || start.pop()) ) { - - // When found, cache indexes on `parent` and break - if ( node.nodeType === 1 && ++diff && node === elem ) { - outerCache[ type ] = [ dirruns, nodeIndex, diff ]; - break; - } - } - - // Use previously-cached element index if available - } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { - diff = cache[1]; - - // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) - } else { - // Use the same loop as above to seek `elem` from the start - while ( (node = ++nodeIndex && node && node[ dir ] || - (diff = nodeIndex = 0) || start.pop()) ) { - - if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { - // Cache the index of each encountered element - if ( useCache ) { - (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; - } - - if ( node === elem ) { - break; - } - } - } - } - - // Incorporate the offset, then check against cycle size - diff -= last; - return diff === first || ( diff % first === 0 && diff / first >= 0 ); - } - }; - }, - - "PSEUDO": function( pseudo, argument ) { - // pseudo-class names are case-insensitive - // http://www.w3.org/TR/selectors/#pseudo-classes - // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters - // Remember that setFilters inherits from pseudos - var args, - fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || - Sizzle.error( "unsupported pseudo: " + pseudo ); - - // The user may use createPseudo to indicate that - // arguments are needed to create the filter function - // just as Sizzle does - if ( fn[ expando ] ) { - return fn( argument ); - } - - // But maintain support for old signatures - if ( fn.length > 1 ) { - args = [ pseudo, pseudo, "", argument ]; - return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? - markFunction(function( seed, matches ) { - var idx, - matched = fn( seed, argument ), - i = matched.length; - while ( i-- ) { - idx = indexOf.call( seed, matched[i] ); - seed[ idx ] = !( matches[ idx ] = matched[i] ); - } - }) : - function( elem ) { - return fn( elem, 0, args ); - }; - } - - return fn; - } - }, - - pseudos: { - // Potentially complex pseudos - "not": markFunction(function( selector ) { - // Trim the selector passed to compile - // to avoid treating leading and trailing - // spaces as combinators - var input = [], - results = [], - matcher = compile( selector.replace( rtrim, "$1" ) ); - - return matcher[ expando ] ? - markFunction(function( seed, matches, context, xml ) { - var elem, - unmatched = matcher( seed, null, xml, [] ), - i = seed.length; - - // Match elements unmatched by `matcher` - while ( i-- ) { - if ( (elem = unmatched[i]) ) { - seed[i] = !(matches[i] = elem); - } - } - }) : - function( elem, context, xml ) { - input[0] = elem; - matcher( input, null, xml, results ); - return !results.pop(); - }; - }), - - "has": markFunction(function( selector ) { - return function( elem ) { - return Sizzle( selector, elem ).length > 0; - }; - }), - - "contains": markFunction(function( text ) { - return function( elem ) { - return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; - }; - }), - - // "Whether an element is represented by a :lang() selector - // is based solely on the element's language value - // being equal to the identifier C, - // or beginning with the identifier C immediately followed by "-". - // The matching of C against the element's language value is performed case-insensitively. - // The identifier C does not have to be a valid language name." - // http://www.w3.org/TR/selectors/#lang-pseudo - "lang": markFunction( function( lang ) { - // lang value must be a valid identifier - if ( !ridentifier.test(lang || "") ) { - Sizzle.error( "unsupported lang: " + lang ); - } - lang = lang.replace( runescape, funescape ).toLowerCase(); - return function( elem ) { - var elemLang; - do { - if ( (elemLang = documentIsHTML ? - elem.lang : - elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { - - elemLang = elemLang.toLowerCase(); - return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; - } - } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); - return false; - }; - }), - - // Miscellaneous - "target": function( elem ) { - var hash = window.location && window.location.hash; - return hash && hash.slice( 1 ) === elem.id; - }, - - "root": function( elem ) { - return elem === docElem; - }, - - "focus": function( elem ) { - return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); - }, - - // Boolean properties - "enabled": function( elem ) { - return elem.disabled === false; - }, - - "disabled": function( elem ) { - return elem.disabled === true; - }, - - "checked": function( elem ) { - // In CSS3, :checked should return both checked and selected elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - var nodeName = elem.nodeName.toLowerCase(); - return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); - }, - - "selected": function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - // Contents - "empty": function( elem ) { - // http://www.w3.org/TR/selectors/#empty-pseudo - // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), - // but not by others (comment: 8; processing instruction: 7; etc.) - // nodeType < 6 works because attributes (2) do not appear as children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - if ( elem.nodeType < 6 ) { - return false; - } - } - return true; - }, - - "parent": function( elem ) { - return !Expr.pseudos["empty"]( elem ); - }, - - // Element/input types - "header": function( elem ) { - return rheader.test( elem.nodeName ); - }, - - "input": function( elem ) { - return rinputs.test( elem.nodeName ); - }, - - "button": function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === "button" || name === "button"; - }, - - "text": function( elem ) { - var attr; - return elem.nodeName.toLowerCase() === "input" && - elem.type === "text" && - - // Support: IE<8 - // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" - ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); - }, - - // Position-in-collection - "first": createPositionalPseudo(function() { - return [ 0 ]; - }), - - "last": createPositionalPseudo(function( matchIndexes, length ) { - return [ length - 1 ]; - }), - - "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { - return [ argument < 0 ? argument + length : argument ]; - }), - - "even": createPositionalPseudo(function( matchIndexes, length ) { - var i = 0; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "odd": createPositionalPseudo(function( matchIndexes, length ) { - var i = 1; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; --i >= 0; ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; ++i < length; ) { - matchIndexes.push( i ); - } - return matchIndexes; - }) - } -}; - -Expr.pseudos["nth"] = Expr.pseudos["eq"]; - -// Add button/input type pseudos -for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { - Expr.pseudos[ i ] = createInputPseudo( i ); -} -for ( i in { submit: true, reset: true } ) { - Expr.pseudos[ i ] = createButtonPseudo( i ); -} - -// Easy API for creating new setFilters -function setFilters() {} -setFilters.prototype = Expr.filters = Expr.pseudos; -Expr.setFilters = new setFilters(); - -tokenize = Sizzle.tokenize = function( selector, parseOnly ) { - var matched, match, tokens, type, - soFar, groups, preFilters, - cached = tokenCache[ selector + " " ]; - - if ( cached ) { - return parseOnly ? 0 : cached.slice( 0 ); - } - - soFar = selector; - groups = []; - preFilters = Expr.preFilter; - - while ( soFar ) { - - // Comma and first run - if ( !matched || (match = rcomma.exec( soFar )) ) { - if ( match ) { - // Don't consume trailing commas as valid - soFar = soFar.slice( match[0].length ) || soFar; - } - groups.push( (tokens = []) ); - } - - matched = false; - - // Combinators - if ( (match = rcombinators.exec( soFar )) ) { - matched = match.shift(); - tokens.push({ - value: matched, - // Cast descendant combinators to space - type: match[0].replace( rtrim, " " ) - }); - soFar = soFar.slice( matched.length ); - } - - // Filters - for ( type in Expr.filter ) { - if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || - (match = preFilters[ type ]( match ))) ) { - matched = match.shift(); - tokens.push({ - value: matched, - type: type, - matches: match - }); - soFar = soFar.slice( matched.length ); - } - } - - if ( !matched ) { - break; - } - } - - // Return the length of the invalid excess - // if we're just parsing - // Otherwise, throw an error or return tokens - return parseOnly ? - soFar.length : - soFar ? - Sizzle.error( selector ) : - // Cache the tokens - tokenCache( selector, groups ).slice( 0 ); -}; - -function toSelector( tokens ) { - var i = 0, - len = tokens.length, - selector = ""; - for ( ; i < len; i++ ) { - selector += tokens[i].value; - } - return selector; -} - -function addCombinator( matcher, combinator, base ) { - var dir = combinator.dir, - checkNonElements = base && dir === "parentNode", - doneName = done++; - - return combinator.first ? - // Check against closest ancestor/preceding element - function( elem, context, xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - return matcher( elem, context, xml ); - } - } - } : - - // Check against all ancestor/preceding elements - function( elem, context, xml ) { - var oldCache, outerCache, - newCache = [ dirruns, doneName ]; - - // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching - if ( xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - if ( matcher( elem, context, xml ) ) { - return true; - } - } - } - } else { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - outerCache = elem[ expando ] || (elem[ expando ] = {}); - if ( (oldCache = outerCache[ dir ]) && - oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { - - // Assign to newCache so results back-propagate to previous elements - return (newCache[ 2 ] = oldCache[ 2 ]); - } else { - // Reuse newcache so results back-propagate to previous elements - outerCache[ dir ] = newCache; - - // A match means we're done; a fail means we have to keep checking - if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { - return true; - } - } - } - } - } - }; -} - -function elementMatcher( matchers ) { - return matchers.length > 1 ? - function( elem, context, xml ) { - var i = matchers.length; - while ( i-- ) { - if ( !matchers[i]( elem, context, xml ) ) { - return false; - } - } - return true; - } : - matchers[0]; -} - -function multipleContexts( selector, contexts, results ) { - var i = 0, - len = contexts.length; - for ( ; i < len; i++ ) { - Sizzle( selector, contexts[i], results ); - } - return results; -} - -function condense( unmatched, map, filter, context, xml ) { - var elem, - newUnmatched = [], - i = 0, - len = unmatched.length, - mapped = map != null; - - for ( ; i < len; i++ ) { - if ( (elem = unmatched[i]) ) { - if ( !filter || filter( elem, context, xml ) ) { - newUnmatched.push( elem ); - if ( mapped ) { - map.push( i ); - } - } - } - } - - return newUnmatched; -} - -function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { - if ( postFilter && !postFilter[ expando ] ) { - postFilter = setMatcher( postFilter ); - } - if ( postFinder && !postFinder[ expando ] ) { - postFinder = setMatcher( postFinder, postSelector ); - } - return markFunction(function( seed, results, context, xml ) { - var temp, i, elem, - preMap = [], - postMap = [], - preexisting = results.length, - - // Get initial elements from seed or context - elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), - - // Prefilter to get matcher input, preserving a map for seed-results synchronization - matcherIn = preFilter && ( seed || !selector ) ? - condense( elems, preMap, preFilter, context, xml ) : - elems, - - matcherOut = matcher ? - // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, - postFinder || ( seed ? preFilter : preexisting || postFilter ) ? - - // ...intermediate processing is necessary - [] : - - // ...otherwise use results directly - results : - matcherIn; - - // Find primary matches - if ( matcher ) { - matcher( matcherIn, matcherOut, context, xml ); - } - - // Apply postFilter - if ( postFilter ) { - temp = condense( matcherOut, postMap ); - postFilter( temp, [], context, xml ); - - // Un-match failing elements by moving them back to matcherIn - i = temp.length; - while ( i-- ) { - if ( (elem = temp[i]) ) { - matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); - } - } - } - - if ( seed ) { - if ( postFinder || preFilter ) { - if ( postFinder ) { - // Get the final matcherOut by condensing this intermediate into postFinder contexts - temp = []; - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) ) { - // Restore matcherIn since elem is not yet a final match - temp.push( (matcherIn[i] = elem) ); - } - } - postFinder( null, (matcherOut = []), temp, xml ); - } - - // Move matched elements from seed to results to keep them synchronized - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) && - (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { - - seed[temp] = !(results[temp] = elem); - } - } - } - - // Add elements to results, through postFinder if defined - } else { - matcherOut = condense( - matcherOut === results ? - matcherOut.splice( preexisting, matcherOut.length ) : - matcherOut - ); - if ( postFinder ) { - postFinder( null, results, matcherOut, xml ); - } else { - push.apply( results, matcherOut ); - } - } - }); -} - -function matcherFromTokens( tokens ) { - var checkContext, matcher, j, - len = tokens.length, - leadingRelative = Expr.relative[ tokens[0].type ], - implicitRelative = leadingRelative || Expr.relative[" "], - i = leadingRelative ? 1 : 0, - - // The foundational matcher ensures that elements are reachable from top-level context(s) - matchContext = addCombinator( function( elem ) { - return elem === checkContext; - }, implicitRelative, true ), - matchAnyContext = addCombinator( function( elem ) { - return indexOf.call( checkContext, elem ) > -1; - }, implicitRelative, true ), - matchers = [ function( elem, context, xml ) { - return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( - (checkContext = context).nodeType ? - matchContext( elem, context, xml ) : - matchAnyContext( elem, context, xml ) ); - } ]; - - for ( ; i < len; i++ ) { - if ( (matcher = Expr.relative[ tokens[i].type ]) ) { - matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; - } else { - matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); - - // Return special upon seeing a positional matcher - if ( matcher[ expando ] ) { - // Find the next relative operator (if any) for proper handling - j = ++i; - for ( ; j < len; j++ ) { - if ( Expr.relative[ tokens[j].type ] ) { - break; - } - } - return setMatcher( - i > 1 && elementMatcher( matchers ), - i > 1 && toSelector( - // If the preceding token was a descendant combinator, insert an implicit any-element `*` - tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) - ).replace( rtrim, "$1" ), - matcher, - i < j && matcherFromTokens( tokens.slice( i, j ) ), - j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), - j < len && toSelector( tokens ) - ); - } - matchers.push( matcher ); - } - } - - return elementMatcher( matchers ); -} - -function matcherFromGroupMatchers( elementMatchers, setMatchers ) { - var bySet = setMatchers.length > 0, - byElement = elementMatchers.length > 0, - superMatcher = function( seed, context, xml, results, outermost ) { - var elem, j, matcher, - matchedCount = 0, - i = "0", - unmatched = seed && [], - setMatched = [], - contextBackup = outermostContext, - // We must always have either seed elements or outermost context - elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), - // Use integer dirruns iff this is the outermost matcher - dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), - len = elems.length; - - if ( outermost ) { - outermostContext = context !== document && context; - } - - // Add elements passing elementMatchers directly to results - // Keep `i` a string if there are no elements so `matchedCount` will be "00" below - // Support: IE<9, Safari - // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id - for ( ; i !== len && (elem = elems[i]) != null; i++ ) { - if ( byElement && elem ) { - j = 0; - while ( (matcher = elementMatchers[j++]) ) { - if ( matcher( elem, context, xml ) ) { - results.push( elem ); - break; - } - } - if ( outermost ) { - dirruns = dirrunsUnique; - } - } - - // Track unmatched elements for set filters - if ( bySet ) { - // They will have gone through all possible matchers - if ( (elem = !matcher && elem) ) { - matchedCount--; - } - - // Lengthen the array for every element, matched or not - if ( seed ) { - unmatched.push( elem ); - } - } - } - - // Apply set filters to unmatched elements - matchedCount += i; - if ( bySet && i !== matchedCount ) { - j = 0; - while ( (matcher = setMatchers[j++]) ) { - matcher( unmatched, setMatched, context, xml ); - } - - if ( seed ) { - // Reintegrate element matches to eliminate the need for sorting - if ( matchedCount > 0 ) { - while ( i-- ) { - if ( !(unmatched[i] || setMatched[i]) ) { - setMatched[i] = pop.call( results ); - } - } - } - - // Discard index placeholder values to get only actual matches - setMatched = condense( setMatched ); - } - - // Add matches to results - push.apply( results, setMatched ); - - // Seedless set matches succeeding multiple successful matchers stipulate sorting - if ( outermost && !seed && setMatched.length > 0 && - ( matchedCount + setMatchers.length ) > 1 ) { - - Sizzle.uniqueSort( results ); - } - } - - // Override manipulation of globals by nested matchers - if ( outermost ) { - dirruns = dirrunsUnique; - outermostContext = contextBackup; - } - - return unmatched; - }; - - return bySet ? - markFunction( superMatcher ) : - superMatcher; -} - -compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { - var i, - setMatchers = [], - elementMatchers = [], - cached = compilerCache[ selector + " " ]; - - if ( !cached ) { - // Generate a function of recursive functions that can be used to check each element - if ( !match ) { - match = tokenize( selector ); - } - i = match.length; - while ( i-- ) { - cached = matcherFromTokens( match[i] ); - if ( cached[ expando ] ) { - setMatchers.push( cached ); - } else { - elementMatchers.push( cached ); - } - } - - // Cache the compiled function - cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); - - // Save selector and tokenization - cached.selector = selector; - } - return cached; -}; - -/** - * A low-level selection function that works with Sizzle's compiled - * selector functions - * @param {String|Function} selector A selector or a pre-compiled - * selector function built with Sizzle.compile - * @param {Element} context - * @param {Array} [results] - * @param {Array} [seed] A set of elements to match against - */ -select = Sizzle.select = function( selector, context, results, seed ) { - var i, tokens, token, type, find, - compiled = typeof selector === "function" && selector, - match = !seed && tokenize( (selector = compiled.selector || selector) ); - - results = results || []; - - // Try to minimize operations if there is no seed and only one group - if ( match.length === 1 ) { - - // Take a shortcut and set the context if the root selector is an ID - tokens = match[0] = match[0].slice( 0 ); - if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && - support.getById && context.nodeType === 9 && documentIsHTML && - Expr.relative[ tokens[1].type ] ) { - - context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; - if ( !context ) { - return results; - - // Precompiled matchers will still verify ancestry, so step up a level - } else if ( compiled ) { - context = context.parentNode; - } - - selector = selector.slice( tokens.shift().value.length ); - } - - // Fetch a seed set for right-to-left matching - i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; - while ( i-- ) { - token = tokens[i]; - - // Abort if we hit a combinator - if ( Expr.relative[ (type = token.type) ] ) { - break; - } - if ( (find = Expr.find[ type ]) ) { - // Search, expanding context for leading sibling combinators - if ( (seed = find( - token.matches[0].replace( runescape, funescape ), - rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context - )) ) { - - // If seed is empty or no tokens remain, we can return early - tokens.splice( i, 1 ); - selector = seed.length && toSelector( tokens ); - if ( !selector ) { - push.apply( results, seed ); - return results; - } - - break; - } - } - } - } - - // Compile and execute a filtering function if one is not provided - // Provide `match` to avoid retokenization if we modified the selector above - ( compiled || compile( selector, match ) )( - seed, - context, - !documentIsHTML, - results, - rsibling.test( selector ) && testContext( context.parentNode ) || context - ); - return results; -}; - -// One-time assignments - -// Sort stability -support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; - -// Support: Chrome<14 -// Always assume duplicates if they aren't passed to the comparison function -support.detectDuplicates = !!hasDuplicate; - -// Initialize against the default document -setDocument(); - -// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) -// Detached nodes confoundingly follow *each other* -support.sortDetached = assert(function( div1 ) { - // Should return 1, but returns 4 (following) - return div1.compareDocumentPosition( document.createElement("div") ) & 1; -}); - -// Support: IE<8 -// Prevent attribute/property "interpolation" -// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx -if ( !assert(function( div ) { - div.innerHTML = ""; - return div.firstChild.getAttribute("href") === "#" ; -}) ) { - addHandle( "type|href|height|width", function( elem, name, isXML ) { - if ( !isXML ) { - return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); - } - }); -} - -// Support: IE<9 -// Use defaultValue in place of getAttribute("value") -if ( !support.attributes || !assert(function( div ) { - div.innerHTML = ""; - div.firstChild.setAttribute( "value", "" ); - return div.firstChild.getAttribute( "value" ) === ""; -}) ) { - addHandle( "value", function( elem, name, isXML ) { - if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { - return elem.defaultValue; - } - }); -} - -// Support: IE<9 -// Use getAttributeNode to fetch booleans when getAttribute lies -if ( !assert(function( div ) { - return div.getAttribute("disabled") == null; -}) ) { - addHandle( booleans, function( elem, name, isXML ) { - var val; - if ( !isXML ) { - return elem[ name ] === true ? name.toLowerCase() : - (val = elem.getAttributeNode( name )) && val.specified ? - val.value : - null; - } - }); -} - -return Sizzle; - -})( window ); - - - -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.pseudos; -jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; - - - -var rneedsContext = jQuery.expr.match.needsContext; - -var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); - - - -var risSimple = /^.[^:#\[\.,]*$/; - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, not ) { - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep( elements, function( elem, i ) { - /* jshint -W018 */ - return !!qualifier.call( elem, i, elem ) !== not; - }); - - } - - if ( qualifier.nodeType ) { - return jQuery.grep( elements, function( elem ) { - return ( elem === qualifier ) !== not; - }); - - } - - if ( typeof qualifier === "string" ) { - if ( risSimple.test( qualifier ) ) { - return jQuery.filter( qualifier, elements, not ); - } - - qualifier = jQuery.filter( qualifier, elements ); - } - - return jQuery.grep( elements, function( elem ) { - return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; - }); -} - -jQuery.filter = function( expr, elems, not ) { - var elem = elems[ 0 ]; - - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 && elem.nodeType === 1 ? - jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : - jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { - return elem.nodeType === 1; - })); -}; - -jQuery.fn.extend({ - find: function( selector ) { - var i, - len = this.length, - ret = [], - self = this; - - if ( typeof selector !== "string" ) { - return this.pushStack( jQuery( selector ).filter(function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - }) ); - } - - for ( i = 0; i < len; i++ ) { - jQuery.find( selector, self[ i ], ret ); - } - - // Needed because $( selector, context ) becomes $( context ).find( selector ) - ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); - ret.selector = this.selector ? this.selector + " " + selector : selector; - return ret; - }, - filter: function( selector ) { - return this.pushStack( winnow(this, selector || [], false) ); - }, - not: function( selector ) { - return this.pushStack( winnow(this, selector || [], true) ); - }, - is: function( selector ) { - return !!winnow( - this, - - // If this is a positional/relative selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - typeof selector === "string" && rneedsContext.test( selector ) ? - jQuery( selector ) : - selector || [], - false - ).length; - } -}); - - -// Initialize a jQuery object - - -// A central reference to the root jQuery(document) -var rootjQuery, - - // A simple way to check for HTML strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - // Strict HTML recognition (#11290: must start with <) - rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, - - init = jQuery.fn.init = function( selector, context ) { - var match, elem; - - // HANDLE: $(""), $(null), $(undefined), $(false) - if ( !selector ) { - return this; - } - - // Handle HTML strings - if ( typeof selector === "string" ) { - if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = rquickExpr.exec( selector ); - } - - // Match html or make sure no context is specified for #id - if ( match && (match[1] || !context) ) { - - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - context = context instanceof jQuery ? context[0] : context; - - // scripts is true for back-compat - // Intentionally let the error be thrown if parseHTML is not present - jQuery.merge( this, jQuery.parseHTML( - match[1], - context && context.nodeType ? context.ownerDocument || context : document, - true - ) ); - - // HANDLE: $(html, props) - if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { - for ( match in context ) { - // Properties of context are called as methods if possible - if ( jQuery.isFunction( this[ match ] ) ) { - this[ match ]( context[ match ] ); - - // ...and otherwise set as attributes - } else { - this.attr( match, context[ match ] ); - } - } - } - - return this; - - // HANDLE: $(#id) - } else { - elem = document.getElementById( match[2] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || rootjQuery ).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(DOMElement) - } else if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return typeof rootjQuery.ready !== "undefined" ? - rootjQuery.ready( selector ) : - // Execute immediately if ready is not present - selector( jQuery ); - } - - if ( selector.selector !== undefined ) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray( selector, this ); - }; - -// Give the init function the jQuery prototype for later instantiation -init.prototype = jQuery.fn; - -// Initialize central reference -rootjQuery = jQuery( document ); - - -var rparentsprev = /^(?:parents|prev(?:Until|All))/, - // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.extend({ - dir: function( elem, dir, until ) { - var matched = [], - truncate = until !== undefined; - - while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { - if ( elem.nodeType === 1 ) { - if ( truncate && jQuery( elem ).is( until ) ) { - break; - } - matched.push( elem ); - } - } - return matched; - }, - - sibling: function( n, elem ) { - var matched = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - matched.push( n ); - } - } - - return matched; - } -}); - -jQuery.fn.extend({ - has: function( target ) { - var targets = jQuery( target, this ), - l = targets.length; - - return this.filter(function() { - var i = 0; - for ( ; i < l; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); - }, - - closest: function( selectors, context ) { - var cur, - i = 0, - l = this.length, - matched = [], - pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; - - for ( ; i < l; i++ ) { - for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { - // Always skip document fragments - if ( cur.nodeType < 11 && (pos ? - pos.index(cur) > -1 : - - // Don't pass non-elements to Sizzle - cur.nodeType === 1 && - jQuery.find.matchesSelector(cur, selectors)) ) { - - matched.push( cur ); - break; - } - } - } - - return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); - }, - - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; - } - - // index in selector - if ( typeof elem === "string" ) { - return indexOf.call( jQuery( elem ), this[ 0 ] ); - } - - // Locate the position of the desired element - return indexOf.call( this, - - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[ 0 ] : elem - ); - }, - - add: function( selector, context ) { - return this.pushStack( - jQuery.unique( - jQuery.merge( this.get(), jQuery( selector, context ) ) - ) - ); - }, - - addBack: function( selector ) { - return this.add( selector == null ? - this.prevObject : this.prevObject.filter(selector) - ); - } -}); - -function sibling( cur, dir ) { - while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} - return cur; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return sibling( elem, "nextSibling" ); - }, - prev: function( elem ) { - return sibling( elem, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return elem.contentDocument || jQuery.merge( [], elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var matched = jQuery.map( this, fn, until ); - - if ( name.slice( -5 ) !== "Until" ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - matched = jQuery.filter( selector, matched ); - } - - if ( this.length > 1 ) { - // Remove duplicates - if ( !guaranteedUnique[ name ] ) { - jQuery.unique( matched ); - } - - // Reverse order for parents* and prev-derivatives - if ( rparentsprev.test( name ) ) { - matched.reverse(); - } - } - - return this.pushStack( matched ); - }; -}); -var rnotwhite = (/\S+/g); - - - -// String to Object options format cache -var optionsCache = {}; - -// Convert String-formatted options into Object-formatted ones and store in cache -function createOptions( options ) { - var object = optionsCache[ options ] = {}; - jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { - object[ flag ] = true; - }); - return object; -} - -/* - * Create a callback list using the following parameters: - * - * options: an optional list of space-separated options that will change how - * the callback list behaves or a more traditional option object - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible options: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ -jQuery.Callbacks = function( options ) { - - // Convert options from String-formatted to Object-formatted if needed - // (we check in cache first) - options = typeof options === "string" ? - ( optionsCache[ options ] || createOptions( options ) ) : - jQuery.extend( {}, options ); - - var // Last fire value (for non-forgettable lists) - memory, - // Flag to know if list was already fired - fired, - // Flag to know if list is currently firing - firing, - // First callback to fire (used internally by add and fireWith) - firingStart, - // End of the loop when firing - firingLength, - // Index of currently firing callback (modified by remove if needed) - firingIndex, - // Actual callback list - list = [], - // Stack of fire calls for repeatable lists - stack = !options.once && [], - // Fire callbacks - fire = function( data ) { - memory = options.memory && data; - fired = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - firing = true; - for ( ; list && firingIndex < firingLength; firingIndex++ ) { - if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { - memory = false; // To prevent further calls using add - break; - } - } - firing = false; - if ( list ) { - if ( stack ) { - if ( stack.length ) { - fire( stack.shift() ); - } - } else if ( memory ) { - list = []; - } else { - self.disable(); - } - } - }, - // Actual Callbacks object - self = { - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - // First, we save the current length - var start = list.length; - (function add( args ) { - jQuery.each( args, function( _, arg ) { - var type = jQuery.type( arg ); - if ( type === "function" ) { - if ( !options.unique || !self.has( arg ) ) { - list.push( arg ); - } - } else if ( arg && arg.length && type !== "string" ) { - // Inspect recursively - add( arg ); - } - }); - })( arguments ); - // Do we need to add the callbacks to the - // current firing batch? - if ( firing ) { - firingLength = list.length; - // With memory, if we're not firing then - // we should call right away - } else if ( memory ) { - firingStart = start; - fire( memory ); - } - } - return this; - }, - // Remove a callback from the list - remove: function() { - if ( list ) { - jQuery.each( arguments, function( _, arg ) { - var index; - while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { - list.splice( index, 1 ); - // Handle firing indexes - if ( firing ) { - if ( index <= firingLength ) { - firingLength--; - } - if ( index <= firingIndex ) { - firingIndex--; - } - } - } - }); - } - return this; - }, - // Check if a given callback is in the list. - // If no argument is given, return whether or not list has callbacks attached. - has: function( fn ) { - return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); - }, - // Remove all callbacks from the list - empty: function() { - list = []; - firingLength = 0; - return this; - }, - // Have the list do nothing anymore - disable: function() { - list = stack = memory = undefined; - return this; - }, - // Is it disabled? - disabled: function() { - return !list; - }, - // Lock the list in its current state - lock: function() { - stack = undefined; - if ( !memory ) { - self.disable(); - } - return this; - }, - // Is it locked? - locked: function() { - return !stack; - }, - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - if ( list && ( !fired || stack ) ) { - args = args || []; - args = [ context, args.slice ? args.slice() : args ]; - if ( firing ) { - stack.push( args ); - } else { - fire( args ); - } - } - return this; - }, - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; - } - }; - - return self; -}; - - -jQuery.extend({ - - Deferred: function( func ) { - var tuples = [ - // action, add listener, listener list, final state - [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], - [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], - [ "notify", "progress", jQuery.Callbacks("memory") ] - ], - state = "pending", - promise = { - state: function() { - return state; - }, - always: function() { - deferred.done( arguments ).fail( arguments ); - return this; - }, - then: function( /* fnDone, fnFail, fnProgress */ ) { - var fns = arguments; - return jQuery.Deferred(function( newDefer ) { - jQuery.each( tuples, function( i, tuple ) { - var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; - // deferred[ done | fail | progress ] for forwarding actions to newDefer - deferred[ tuple[1] ](function() { - var returned = fn && fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise() - .done( newDefer.resolve ) - .fail( newDefer.reject ) - .progress( newDefer.notify ); - } else { - newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); - } - }); - }); - fns = null; - }).promise(); - }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - return obj != null ? jQuery.extend( obj, promise ) : promise; - } - }, - deferred = {}; - - // Keep pipe for back-compat - promise.pipe = promise.then; - - // Add list-specific methods - jQuery.each( tuples, function( i, tuple ) { - var list = tuple[ 2 ], - stateString = tuple[ 3 ]; - - // promise[ done | fail | progress ] = list.add - promise[ tuple[1] ] = list.add; - - // Handle state - if ( stateString ) { - list.add(function() { - // state = [ resolved | rejected ] - state = stateString; - - // [ reject_list | resolve_list ].disable; progress_list.lock - }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); - } - - // deferred[ resolve | reject | notify ] - deferred[ tuple[0] ] = function() { - deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); - return this; - }; - deferred[ tuple[0] + "With" ] = list.fireWith; - }); - - // Make the deferred a promise - promise.promise( deferred ); - - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function( subordinate /* , ..., subordinateN */ ) { - var i = 0, - resolveValues = slice.call( arguments ), - length = resolveValues.length, - - // the count of uncompleted subordinates - remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, - - // the master Deferred. If resolveValues consist of only a single Deferred, just use that. - deferred = remaining === 1 ? subordinate : jQuery.Deferred(), - - // Update function for both resolve and progress values - updateFunc = function( i, contexts, values ) { - return function( value ) { - contexts[ i ] = this; - values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; - if ( values === progressValues ) { - deferred.notifyWith( contexts, values ); - } else if ( !( --remaining ) ) { - deferred.resolveWith( contexts, values ); - } - }; - }, - - progressValues, progressContexts, resolveContexts; - - // add listeners to Deferred subordinates; treat others as resolved - if ( length > 1 ) { - progressValues = new Array( length ); - progressContexts = new Array( length ); - resolveContexts = new Array( length ); - for ( ; i < length; i++ ) { - if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { - resolveValues[ i ].promise() - .done( updateFunc( i, resolveContexts, resolveValues ) ) - .fail( deferred.reject ) - .progress( updateFunc( i, progressContexts, progressValues ) ); - } else { - --remaining; - } - } - } - - // if we're not waiting on anything, resolve the master - if ( !remaining ) { - deferred.resolveWith( resolveContexts, resolveValues ); - } - - return deferred.promise(); - } -}); - - -// The deferred used on DOM ready -var readyList; - -jQuery.fn.ready = function( fn ) { - // Add the callback - jQuery.ready.promise().done( fn ); - - return this; -}; - -jQuery.extend({ - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Hold (or release) the ready event - holdReady: function( hold ) { - if ( hold ) { - jQuery.readyWait++; - } else { - jQuery.ready( true ); - } - }, - - // Handle when the DOM is ready - ready: function( wait ) { - - // Abort if there are pending holds or we're already ready - if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { - return; - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.triggerHandler ) { - jQuery( document ).triggerHandler( "ready" ); - jQuery( document ).off( "ready" ); - } - } -}); - -/** - * The ready event handler and self cleanup method - */ -function completed() { - document.removeEventListener( "DOMContentLoaded", completed, false ); - window.removeEventListener( "load", completed, false ); - jQuery.ready(); -} - -jQuery.ready.promise = function( obj ) { - if ( !readyList ) { - - readyList = jQuery.Deferred(); - - // Catch cases where $(document).ready() is called after the browser event has already occurred. - // we once tried to use readyState "interactive" here, but it caused issues like the one - // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 - if ( document.readyState === "complete" ) { - // Handle it asynchronously to allow scripts the opportunity to delay ready - setTimeout( jQuery.ready ); - - } else { - - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", completed, false ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", completed, false ); - } - } - return readyList.promise( obj ); -}; - -// Kick off the DOM ready check even if the user does not -jQuery.ready.promise(); - - - - -// Multifunctional method to get and set values of a collection -// The value/s can optionally be executed if it's a function -var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { - var i = 0, - len = elems.length, - bulk = key == null; - - // Sets many values - if ( jQuery.type( key ) === "object" ) { - chainable = true; - for ( i in key ) { - jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); - } - - // Sets one value - } else if ( value !== undefined ) { - chainable = true; - - if ( !jQuery.isFunction( value ) ) { - raw = true; - } - - if ( bulk ) { - // Bulk operations run against the entire set - if ( raw ) { - fn.call( elems, value ); - fn = null; - - // ...except when executing function values - } else { - bulk = fn; - fn = function( elem, key, value ) { - return bulk.call( jQuery( elem ), value ); - }; - } - } - - if ( fn ) { - for ( ; i < len; i++ ) { - fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); - } - } - } - - return chainable ? - elems : - - // Gets - bulk ? - fn.call( elems ) : - len ? fn( elems[0], key ) : emptyGet; -}; - - -/** - * Determines whether an object can have data - */ -jQuery.acceptData = function( owner ) { - // Accepts only: - // - Node - // - Node.ELEMENT_NODE - // - Node.DOCUMENT_NODE - // - Object - // - Any - /* jshint -W018 */ - return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); -}; - - -function Data() { - // Support: Android < 4, - // Old WebKit does not have Object.preventExtensions/freeze method, - // return new empty object instead with no [[set]] accessor - Object.defineProperty( this.cache = {}, 0, { - get: function() { - return {}; - } - }); - - this.expando = jQuery.expando + Math.random(); -} - -Data.uid = 1; -Data.accepts = jQuery.acceptData; - -Data.prototype = { - key: function( owner ) { - // We can accept data for non-element nodes in modern browsers, - // but we should not, see #8335. - // Always return the key for a frozen object. - if ( !Data.accepts( owner ) ) { - return 0; - } - - var descriptor = {}, - // Check if the owner object already has a cache key - unlock = owner[ this.expando ]; - - // If not, create one - if ( !unlock ) { - unlock = Data.uid++; - - // Secure it in a non-enumerable, non-writable property - try { - descriptor[ this.expando ] = { value: unlock }; - Object.defineProperties( owner, descriptor ); - - // Support: Android < 4 - // Fallback to a less secure definition - } catch ( e ) { - descriptor[ this.expando ] = unlock; - jQuery.extend( owner, descriptor ); - } - } - - // Ensure the cache object - if ( !this.cache[ unlock ] ) { - this.cache[ unlock ] = {}; - } - - return unlock; - }, - set: function( owner, data, value ) { - var prop, - // There may be an unlock assigned to this node, - // if there is no entry for this "owner", create one inline - // and set the unlock as though an owner entry had always existed - unlock = this.key( owner ), - cache = this.cache[ unlock ]; - - // Handle: [ owner, key, value ] args - if ( typeof data === "string" ) { - cache[ data ] = value; - - // Handle: [ owner, { properties } ] args - } else { - // Fresh assignments by object are shallow copied - if ( jQuery.isEmptyObject( cache ) ) { - jQuery.extend( this.cache[ unlock ], data ); - // Otherwise, copy the properties one-by-one to the cache object - } else { - for ( prop in data ) { - cache[ prop ] = data[ prop ]; - } - } - } - return cache; - }, - get: function( owner, key ) { - // Either a valid cache is found, or will be created. - // New caches will be created and the unlock returned, - // allowing direct access to the newly created - // empty data object. A valid owner object must be provided. - var cache = this.cache[ this.key( owner ) ]; - - return key === undefined ? - cache : cache[ key ]; - }, - access: function( owner, key, value ) { - var stored; - // In cases where either: - // - // 1. No key was specified - // 2. A string key was specified, but no value provided - // - // Take the "read" path and allow the get method to determine - // which value to return, respectively either: - // - // 1. The entire cache object - // 2. The data stored at the key - // - if ( key === undefined || - ((key && typeof key === "string") && value === undefined) ) { - - stored = this.get( owner, key ); - - return stored !== undefined ? - stored : this.get( owner, jQuery.camelCase(key) ); - } - - // [*]When the key is not a string, or both a key and value - // are specified, set or extend (existing objects) with either: - // - // 1. An object of properties - // 2. A key and value - // - this.set( owner, key, value ); - - // Since the "set" path can have two possible entry points - // return the expected data based on which path was taken[*] - return value !== undefined ? value : key; - }, - remove: function( owner, key ) { - var i, name, camel, - unlock = this.key( owner ), - cache = this.cache[ unlock ]; - - if ( key === undefined ) { - this.cache[ unlock ] = {}; - - } else { - // Support array or space separated string of keys - if ( jQuery.isArray( key ) ) { - // If "name" is an array of keys... - // When data is initially created, via ("key", "val") signature, - // keys will be converted to camelCase. - // Since there is no way to tell _how_ a key was added, remove - // both plain key and camelCase key. #12786 - // This will only penalize the array argument path. - name = key.concat( key.map( jQuery.camelCase ) ); - } else { - camel = jQuery.camelCase( key ); - // Try the string as a key before any manipulation - if ( key in cache ) { - name = [ key, camel ]; - } else { - // If a key with the spaces exists, use it. - // Otherwise, create an array by matching non-whitespace - name = camel; - name = name in cache ? - [ name ] : ( name.match( rnotwhite ) || [] ); - } - } - - i = name.length; - while ( i-- ) { - delete cache[ name[ i ] ]; - } - } - }, - hasData: function( owner ) { - return !jQuery.isEmptyObject( - this.cache[ owner[ this.expando ] ] || {} - ); - }, - discard: function( owner ) { - if ( owner[ this.expando ] ) { - delete this.cache[ owner[ this.expando ] ]; - } - } -}; -var data_priv = new Data(); - -var data_user = new Data(); - - - -/* - Implementation Summary - - 1. Enforce API surface and semantic compatibility with 1.9.x branch - 2. Improve the module's maintainability by reducing the storage - paths to a single mechanism. - 3. Use the same single mechanism to support "private" and "user" data. - 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) - 5. Avoid exposing implementation details on user objects (eg. expando properties) - 6. Provide a clear path for implementation upgrade to WeakMap in 2014 -*/ -var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, - rmultiDash = /([A-Z])/g; - -function dataAttr( elem, key, data ) { - var name; - - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - // Only convert to a number if it doesn't change the string - +data + "" === data ? +data : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} - - // Make sure we set the data so it isn't changed later - data_user.set( elem, key, data ); - } else { - data = undefined; - } - } - return data; -} - -jQuery.extend({ - hasData: function( elem ) { - return data_user.hasData( elem ) || data_priv.hasData( elem ); - }, - - data: function( elem, name, data ) { - return data_user.access( elem, name, data ); - }, - - removeData: function( elem, name ) { - data_user.remove( elem, name ); - }, - - // TODO: Now that all calls to _data and _removeData have been replaced - // with direct calls to data_priv methods, these can be deprecated. - _data: function( elem, name, data ) { - return data_priv.access( elem, name, data ); - }, - - _removeData: function( elem, name ) { - data_priv.remove( elem, name ); - } -}); - -jQuery.fn.extend({ - data: function( key, value ) { - var i, name, data, - elem = this[ 0 ], - attrs = elem && elem.attributes; - - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = data_user.get( elem ); - - if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { - i = attrs.length; - while ( i-- ) { - - // Support: IE11+ - // The attrs elements can be null (#14894) - if ( attrs[ i ] ) { - name = attrs[ i ].name; - if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.slice(5) ); - dataAttr( elem, name, data[ name ] ); - } - } - } - data_priv.set( elem, "hasDataAttrs", true ); - } - } - - return data; - } - - // Sets multiple values - if ( typeof key === "object" ) { - return this.each(function() { - data_user.set( this, key ); - }); - } - - return access( this, function( value ) { - var data, - camelKey = jQuery.camelCase( key ); - - // The calling jQuery object (element matches) is not empty - // (and therefore has an element appears at this[ 0 ]) and the - // `value` parameter was not undefined. An empty jQuery object - // will result in `undefined` for elem = this[ 0 ] which will - // throw an exception if an attempt to read a data cache is made. - if ( elem && value === undefined ) { - // Attempt to get data from the cache - // with the key as-is - data = data_user.get( elem, key ); - if ( data !== undefined ) { - return data; - } - - // Attempt to get data from the cache - // with the key camelized - data = data_user.get( elem, camelKey ); - if ( data !== undefined ) { - return data; - } - - // Attempt to "discover" the data in - // HTML5 custom data-* attrs - data = dataAttr( elem, camelKey, undefined ); - if ( data !== undefined ) { - return data; - } - - // We tried really hard, but the data doesn't exist. - return; - } - - // Set the data... - this.each(function() { - // First, attempt to store a copy or reference of any - // data that might've been store with a camelCased key. - var data = data_user.get( this, camelKey ); - - // For HTML5 data-* attribute interop, we have to - // store property names with dashes in a camelCase form. - // This might not apply to all properties...* - data_user.set( this, camelKey, value ); - - // *... In the case of properties that might _actually_ - // have dashes, we need to also store a copy of that - // unchanged property. - if ( key.indexOf("-") !== -1 && data !== undefined ) { - data_user.set( this, key, value ); - } - }); - }, null, value, arguments.length > 1, null, true ); - }, - - removeData: function( key ) { - return this.each(function() { - data_user.remove( this, key ); - }); - } -}); - - -jQuery.extend({ - queue: function( elem, type, data ) { - var queue; - - if ( elem ) { - type = ( type || "fx" ) + "queue"; - queue = data_priv.get( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !queue || jQuery.isArray( data ) ) { - queue = data_priv.access( elem, type, jQuery.makeArray(data) ); - } else { - queue.push( data ); - } - } - return queue || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - startLength = queue.length, - fn = queue.shift(), - hooks = jQuery._queueHooks( elem, type ), - next = function() { - jQuery.dequeue( elem, type ); - }; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - startLength--; - } - - if ( fn ) { - - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - // clear up the last queue stop function - delete hooks.stop; - fn.call( elem, next, hooks ); - } - - if ( !startLength && hooks ) { - hooks.empty.fire(); - } - }, - - // not intended for public consumption - generates a queueHooks object, or returns the current one - _queueHooks: function( elem, type ) { - var key = type + "queueHooks"; - return data_priv.get( elem, key ) || data_priv.access( elem, key, { - empty: jQuery.Callbacks("once memory").add(function() { - data_priv.remove( elem, [ type + "queue", key ] ); - }) - }); - } -}); - -jQuery.fn.extend({ - queue: function( type, data ) { - var setter = 2; - - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } - - if ( arguments.length < setter ) { - return jQuery.queue( this[0], type ); - } - - return data === undefined ? - this : - this.each(function() { - var queue = jQuery.queue( this, type, data ); - - // ensure a hooks for this queue - jQuery._queueHooks( this, type ); - - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, obj ) { - var tmp, - count = 1, - defer = jQuery.Deferred(), - elements = this, - i = this.length, - resolve = function() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - }; - - if ( typeof type !== "string" ) { - obj = type; - type = undefined; - } - type = type || "fx"; - - while ( i-- ) { - tmp = data_priv.get( elements[ i ], type + "queueHooks" ); - if ( tmp && tmp.empty ) { - count++; - tmp.empty.add( resolve ); - } - } - resolve(); - return defer.promise( obj ); - } -}); -var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; - -var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; - -var isHidden = function( elem, el ) { - // isHidden might be called from jQuery#filter function; - // in that case, element will be second argument - elem = el || elem; - return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); - }; - -var rcheckableType = (/^(?:checkbox|radio)$/i); - - - -(function() { - var fragment = document.createDocumentFragment(), - div = fragment.appendChild( document.createElement( "div" ) ), - input = document.createElement( "input" ); - - // #11217 - WebKit loses check when the name is after the checked attribute - // Support: Windows Web Apps (WWA) - // `name` and `type` need .setAttribute for WWA - input.setAttribute( "type", "radio" ); - input.setAttribute( "checked", "checked" ); - input.setAttribute( "name", "t" ); - - div.appendChild( input ); - - // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 - // old WebKit doesn't clone checked state correctly in fragments - support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Make sure textarea (and checkbox) defaultValue is properly cloned - // Support: IE9-IE11+ - div.innerHTML = ""; - support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; -})(); -var strundefined = typeof undefined; - - - -support.focusinBubbles = "onfocusin" in window; - - -var - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, - rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; - -function returnTrue() { - return true; -} - -function returnFalse() { - return false; -} - -function safeActiveElement() { - try { - return document.activeElement; - } catch ( err ) { } -} - -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { - - global: {}, - - add: function( elem, types, handler, data, selector ) { - - var handleObjIn, eventHandle, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = data_priv.get( elem ); - - // Don't attach events to noData or text/comment nodes (but allow plain objects) - if ( !elemData ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - if ( !(events = elemData.events) ) { - events = elemData.events = {}; - } - if ( !(eventHandle = elemData.handle) ) { - eventHandle = elemData.handle = function( e ) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ? - jQuery.event.dispatch.apply( elem, arguments ) : undefined; - }; - } - - // Handle multiple events separated by a space - types = ( types || "" ).match( rnotwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[t] ) || []; - type = origType = tmp[1]; - namespaces = ( tmp[2] || "" ).split( "." ).sort(); - - // There *must* be a type, no attaching namespace-only handlers - if ( !type ) { - continue; - } - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend({ - type: type, - origType: origType, - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - needsContext: selector && jQuery.expr.match.needsContext.test( selector ), - namespace: namespaces.join(".") - }, handleObjIn ); - - // Init the event handler queue if we're the first - if ( !(handlers = events[ type ]) ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener if the special events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - }, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - - var j, origCount, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = data_priv.hasData( elem ) && data_priv.get( elem ); - - if ( !elemData || !(events = elemData.events) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = ( types || "" ).match( rnotwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[t] ) || []; - type = origType = tmp[1]; - namespaces = ( tmp[2] || "" ).split( "." ).sort(); - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector ? special.delegateType : special.bindType ) || type; - handlers = events[ type ] || []; - tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); - - // Remove matching events - origCount = j = handlers.length; - while ( j-- ) { - handleObj = handlers[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !tmp || tmp.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { - handlers.splice( j, 1 ); - - if ( handleObj.selector ) { - handlers.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( origCount && !handlers.length ) { - if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - delete elemData.handle; - data_priv.remove( elem, "events" ); - } - }, - - trigger: function( event, data, elem, onlyHandlers ) { - - var i, cur, tmp, bubbleType, ontype, handle, special, - eventPath = [ elem || document ], - type = hasOwn.call( event, "type" ) ? event.type : event, - namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; - - cur = tmp = elem = elem || document; - - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf(".") >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - ontype = type.indexOf(":") < 0 && "on" + type; - - // Caller can pass in a jQuery.Event object, Object, or just an event type string - event = event[ jQuery.expando ] ? - event : - new jQuery.Event( type, typeof event === "object" && event ); - - // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) - event.isTrigger = onlyHandlers ? 2 : 3; - event.namespace = namespaces.join("."); - event.namespace_re = event.namespace ? - new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : - null; - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data == null ? - [ event ] : - jQuery.makeArray( data, [ event ] ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - if ( !rfocusMorph.test( bubbleType + type ) ) { - cur = cur.parentNode; - } - for ( ; cur; cur = cur.parentNode ) { - eventPath.push( cur ); - tmp = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( tmp === (elem.ownerDocument || document) ) { - eventPath.push( tmp.defaultView || tmp.parentWindow || window ); - } - } - - // Fire handlers on the event path - i = 0; - while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { - - event.type = i > 1 ? - bubbleType : - special.bindType || type; - - // jQuery handler - handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - - // Native handler - handle = ontype && cur[ ontype ]; - if ( handle && handle.apply && jQuery.acceptData( cur ) ) { - event.result = handle.apply( cur, data ); - if ( event.result === false ) { - event.preventDefault(); - } - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && - jQuery.acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name name as the event. - // Don't do default actions on window, that's where global variables be (#6170) - if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - tmp = elem[ ontype ]; - - if ( tmp ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - elem[ type ](); - jQuery.event.triggered = undefined; - - if ( tmp ) { - elem[ ontype ] = tmp; - } - } - } - } - - return event.result; - }, - - dispatch: function( event ) { - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( event ); - - var i, j, ret, matched, handleObj, - handlerQueue = [], - args = slice.call( arguments ), - handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], - special = jQuery.event.special[ event.type ] || {}; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[0] = event; - event.delegateTarget = this; - - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; - } - - // Determine handlers - handlerQueue = jQuery.event.handlers.call( this, event, handlers ); - - // Run delegates first; they may want to stop propagation beneath us - i = 0; - while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { - event.currentTarget = matched.elem; - - j = 0; - while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { - - // Triggered event must either 1) have no namespace, or - // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). - if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { - - event.handleObj = handleObj; - event.data = handleObj.data; - - ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) - .apply( matched.elem, args ); - - if ( ret !== undefined ) { - if ( (event.result = ret) === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } - - return event.result; - }, - - handlers: function( event, handlers ) { - var i, matches, sel, handleObj, - handlerQueue = [], - delegateCount = handlers.delegateCount, - cur = event.target; - - // Find delegate handlers - // Black-hole SVG instance trees (#13180) - // Avoid non-left-click bubbling in Firefox (#3861) - if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { - - for ( ; cur !== this; cur = cur.parentNode || this ) { - - // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) - if ( cur.disabled !== true || event.type !== "click" ) { - matches = []; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - - // Don't conflict with Object.prototype properties (#13203) - sel = handleObj.selector + " "; - - if ( matches[ sel ] === undefined ) { - matches[ sel ] = handleObj.needsContext ? - jQuery( sel, this ).index( cur ) >= 0 : - jQuery.find( sel, this, null, [ cur ] ).length; - } - if ( matches[ sel ] ) { - matches.push( handleObj ); - } - } - if ( matches.length ) { - handlerQueue.push({ elem: cur, handlers: matches }); - } - } - } - } - - // Add the remaining (directly-bound) handlers - if ( delegateCount < handlers.length ) { - handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); - } - - return handlerQueue; - }, - - // Includes some event props shared by KeyEvent and MouseEvent - props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), - - fixHooks: {}, - - keyHooks: { - props: "char charCode key keyCode".split(" "), - filter: function( event, original ) { - - // Add which for key events - if ( event.which == null ) { - event.which = original.charCode != null ? original.charCode : original.keyCode; - } - - return event; - } - }, - - mouseHooks: { - props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), - filter: function( event, original ) { - var eventDoc, doc, body, - button = original.button; - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && original.clientX != null ) { - eventDoc = event.target.ownerDocument || document; - doc = eventDoc.documentElement; - body = eventDoc.body; - - event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); - event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && button !== undefined ) { - event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); - } - - return event; - } - }, - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } - - // Create a writable copy of the event object and normalize some properties - var i, prop, copy, - type = event.type, - originalEvent = event, - fixHook = this.fixHooks[ type ]; - - if ( !fixHook ) { - this.fixHooks[ type ] = fixHook = - rmouseEvent.test( type ) ? this.mouseHooks : - rkeyEvent.test( type ) ? this.keyHooks : - {}; - } - copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; - - event = new jQuery.Event( originalEvent ); - - i = copy.length; - while ( i-- ) { - prop = copy[ i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Support: Cordova 2.5 (WebKit) (#13255) - // All events should have a target; Cordova deviceready doesn't - if ( !event.target ) { - event.target = document; - } - - // Support: Safari 6.0+, Chrome < 28 - // Target should not be a text node (#504, #13143) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; - }, - - special: { - load: { - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - focus: { - // Fire native event if possible so blur/focus sequence is correct - trigger: function() { - if ( this !== safeActiveElement() && this.focus ) { - this.focus(); - return false; - } - }, - delegateType: "focusin" - }, - blur: { - trigger: function() { - if ( this === safeActiveElement() && this.blur ) { - this.blur(); - return false; - } - }, - delegateType: "focusout" - }, - click: { - // For checkbox, fire native event so checked state will be right - trigger: function() { - if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { - this.click(); - return false; - } - }, - - // For cross-browser consistency, don't fire native .click() on links - _default: function( event ) { - return jQuery.nodeName( event.target, "a" ); - } - }, - - beforeunload: { - postDispatch: function( event ) { - - // Support: Firefox 20+ - // Firefox doesn't alert if the returnValue field is not set. - if ( event.result !== undefined && event.originalEvent ) { - event.originalEvent.returnValue = event.result; - } - } - } - }, - - simulate: function( type, elem, event, bubble ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - var e = jQuery.extend( - new jQuery.Event(), - event, - { - type: type, - isSimulated: true, - originalEvent: {} - } - ); - if ( bubble ) { - jQuery.event.trigger( e, null, elem ); - } else { - jQuery.event.dispatch.call( elem, e ); - } - if ( e.isDefaultPrevented() ) { - event.preventDefault(); - } - } -}; - -jQuery.removeEvent = function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); - } -}; - -jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !(this instanceof jQuery.Event) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = src.defaultPrevented || - src.defaultPrevented === undefined && - // Support: Android < 4.0 - src.returnValue === false ? - returnTrue : - returnFalse; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse, - - preventDefault: function() { - var e = this.originalEvent; - - this.isDefaultPrevented = returnTrue; - - if ( e && e.preventDefault ) { - e.preventDefault(); - } - }, - stopPropagation: function() { - var e = this.originalEvent; - - this.isPropagationStopped = returnTrue; - - if ( e && e.stopPropagation ) { - e.stopPropagation(); - } - }, - stopImmediatePropagation: function() { - var e = this.originalEvent; - - this.isImmediatePropagationStopped = returnTrue; - - if ( e && e.stopImmediatePropagation ) { - e.stopImmediatePropagation(); - } - - this.stopPropagation(); - } -}; - -// Create mouseenter/leave events using mouseover/out and event-time checks -// Support: Chrome 15+ -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout", - pointerenter: "pointerover", - pointerleave: "pointerout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var ret, - target = this, - related = event.relatedTarget, - handleObj = event.handleObj; - - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !jQuery.contains( target, related )) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -}); - -// Create "bubbling" focus and blur events -// Support: Firefox, Chrome, Safari -if ( !support.focusinBubbles ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler on the document while someone wants focusin/focusout - var handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - var doc = this.ownerDocument || this, - attaches = data_priv.access( doc, fix ); - - if ( !attaches ) { - doc.addEventListener( orig, handler, true ); - } - data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); - }, - teardown: function() { - var doc = this.ownerDocument || this, - attaches = data_priv.access( doc, fix ) - 1; - - if ( !attaches ) { - doc.removeEventListener( orig, handler, true ); - data_priv.remove( doc, fix ); - - } else { - data_priv.access( doc, fix, attaches ); - } - } - }; - }); -} - -jQuery.fn.extend({ - - on: function( types, selector, data, fn, /*INTERNAL*/ one ) { - var origFn, type; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - this.on( type, selector, data, types[ type ], one ); - } - return this; - } - - if ( data == null && fn == null ) { - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return this; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return this.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - }); - }, - one: function( types, selector, data, fn ) { - return this.on( types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - var handleObj, type; - if ( types && types.preventDefault && types.handleObj ) { - // ( event ) dispatched jQuery.Event - handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - // ( types-object [, selector] ) - for ( type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each(function() { - jQuery.event.remove( this, types, fn, selector ); - }); - }, - - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - triggerHandler: function( type, data ) { - var elem = this[0]; - if ( elem ) { - return jQuery.event.trigger( type, data, elem, true ); - } - } -}); - - -var - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, - rtagName = /<([\w:]+)/, - rhtml = /<|&#?\w+;/, - rnoInnerhtml = /<(?:script|style|link)/i, - // checked="checked" or checked - rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, - rscriptType = /^$|\/(?:java|ecma)script/i, - rscriptTypeMasked = /^true\/(.*)/, - rcleanScript = /^\s*\s*$/g, - - // We have to close these tags to support XHTML (#13200) - wrapMap = { - - // Support: IE 9 - option: [ 1, "" ], - - thead: [ 1, "", "
" ], - col: [ 2, "", "
" ], - tr: [ 2, "", "
" ], - td: [ 3, "", "
" ], - - _default: [ 0, "", "" ] - }; - -// Support: IE 9 -wrapMap.optgroup = wrapMap.option; - -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -// Support: 1.x compatibility -// Manipulating tables requires a tbody -function manipulationTarget( elem, content ) { - return jQuery.nodeName( elem, "table" ) && - jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? - - elem.getElementsByTagName("tbody")[0] || - elem.appendChild( elem.ownerDocument.createElement("tbody") ) : - elem; -} - -// Replace/restore the type attribute of script elements for safe DOM manipulation -function disableScript( elem ) { - elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; - return elem; -} -function restoreScript( elem ) { - var match = rscriptTypeMasked.exec( elem.type ); - - if ( match ) { - elem.type = match[ 1 ]; - } else { - elem.removeAttribute("type"); - } - - return elem; -} - -// Mark scripts as having already been evaluated -function setGlobalEval( elems, refElements ) { - var i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - data_priv.set( - elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) - ); - } -} - -function cloneCopyEvent( src, dest ) { - var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; - - if ( dest.nodeType !== 1 ) { - return; - } - - // 1. Copy private data: events, handlers, etc. - if ( data_priv.hasData( src ) ) { - pdataOld = data_priv.access( src ); - pdataCur = data_priv.set( dest, pdataOld ); - events = pdataOld.events; - - if ( events ) { - delete pdataCur.handle; - pdataCur.events = {}; - - for ( type in events ) { - for ( i = 0, l = events[ type ].length; i < l; i++ ) { - jQuery.event.add( dest, type, events[ type ][ i ] ); - } - } - } - } - - // 2. Copy user data - if ( data_user.hasData( src ) ) { - udataOld = data_user.access( src ); - udataCur = jQuery.extend( {}, udataOld ); - - data_user.set( dest, udataCur ); - } -} - -function getAll( context, tag ) { - var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : - context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : - []; - - return tag === undefined || tag && jQuery.nodeName( context, tag ) ? - jQuery.merge( [ context ], ret ) : - ret; -} - -// Support: IE >= 9 -function fixInput( src, dest ) { - var nodeName = dest.nodeName.toLowerCase(); - - // Fails to persist the checked state of a cloned checkbox or radio button. - if ( nodeName === "input" && rcheckableType.test( src.type ) ) { - dest.checked = src.checked; - - // Fails to return the selected option to the default selected state when cloning options - } else if ( nodeName === "input" || nodeName === "textarea" ) { - dest.defaultValue = src.defaultValue; - } -} - -jQuery.extend({ - clone: function( elem, dataAndEvents, deepDataAndEvents ) { - var i, l, srcElements, destElements, - clone = elem.cloneNode( true ), - inPage = jQuery.contains( elem.ownerDocument, elem ); - - // Support: IE >= 9 - // Fix Cloning issues - if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && - !jQuery.isXMLDoc( elem ) ) { - - // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 - destElements = getAll( clone ); - srcElements = getAll( elem ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - fixInput( srcElements[ i ], destElements[ i ] ); - } - } - - // Copy the events from the original to the clone - if ( dataAndEvents ) { - if ( deepDataAndEvents ) { - srcElements = srcElements || getAll( elem ); - destElements = destElements || getAll( clone ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - cloneCopyEvent( srcElements[ i ], destElements[ i ] ); - } - } else { - cloneCopyEvent( elem, clone ); - } - } - - // Preserve script evaluation history - destElements = getAll( clone, "script" ); - if ( destElements.length > 0 ) { - setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); - } - - // Return the cloned set - return clone; - }, - - buildFragment: function( elems, context, scripts, selection ) { - var elem, tmp, tag, wrap, contains, j, - fragment = context.createDocumentFragment(), - nodes = [], - i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - elem = elems[ i ]; - - if ( elem || elem === 0 ) { - - // Add nodes directly - if ( jQuery.type( elem ) === "object" ) { - // Support: QtWebKit - // jQuery.merge because push.apply(_, arraylike) throws - jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); - - // Convert non-html into a text node - } else if ( !rhtml.test( elem ) ) { - nodes.push( context.createTextNode( elem ) ); - - // Convert html into DOM nodes - } else { - tmp = tmp || fragment.appendChild( context.createElement("div") ); - - // Deserialize a standard representation - tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); - wrap = wrapMap[ tag ] || wrapMap._default; - tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[ 2 ]; - - // Descend through wrappers to the right content - j = wrap[ 0 ]; - while ( j-- ) { - tmp = tmp.lastChild; - } - - // Support: QtWebKit - // jQuery.merge because push.apply(_, arraylike) throws - jQuery.merge( nodes, tmp.childNodes ); - - // Remember the top-level container - tmp = fragment.firstChild; - - // Fixes #12346 - // Support: Webkit, IE - tmp.textContent = ""; - } - } - } - - // Remove wrapper from fragment - fragment.textContent = ""; - - i = 0; - while ( (elem = nodes[ i++ ]) ) { - - // #4087 - If origin and destination elements are the same, and this is - // that element, do not do anything - if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { - continue; - } - - contains = jQuery.contains( elem.ownerDocument, elem ); - - // Append to fragment - tmp = getAll( fragment.appendChild( elem ), "script" ); - - // Preserve script evaluation history - if ( contains ) { - setGlobalEval( tmp ); - } - - // Capture executables - if ( scripts ) { - j = 0; - while ( (elem = tmp[ j++ ]) ) { - if ( rscriptType.test( elem.type || "" ) ) { - scripts.push( elem ); - } - } - } - } - - return fragment; - }, - - cleanData: function( elems ) { - var data, elem, type, key, - special = jQuery.event.special, - i = 0; - - for ( ; (elem = elems[ i ]) !== undefined; i++ ) { - if ( jQuery.acceptData( elem ) ) { - key = elem[ data_priv.expando ]; - - if ( key && (data = data_priv.cache[ key ]) ) { - if ( data.events ) { - for ( type in data.events ) { - if ( special[ type ] ) { - jQuery.event.remove( elem, type ); - - // This is a shortcut to avoid jQuery.event.remove's overhead - } else { - jQuery.removeEvent( elem, type, data.handle ); - } - } - } - if ( data_priv.cache[ key ] ) { - // Discard any remaining `private` data - delete data_priv.cache[ key ]; - } - } - } - // Discard any remaining `user` data - delete data_user.cache[ elem[ data_user.expando ] ]; - } - } -}); - -jQuery.fn.extend({ - text: function( value ) { - return access( this, function( value ) { - return value === undefined ? - jQuery.text( this ) : - this.empty().each(function() { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - this.textContent = value; - } - }); - }, null, value, arguments.length ); - }, - - append: function() { - return this.domManip( arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.appendChild( elem ); - } - }); - }, - - prepend: function() { - return this.domManip( arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.insertBefore( elem, target.firstChild ); - } - }); - }, - - before: function() { - return this.domManip( arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this ); - } - }); - }, - - after: function() { - return this.domManip( arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this.nextSibling ); - } - }); - }, - - remove: function( selector, keepData /* Internal Use Only */ ) { - var elem, - elems = selector ? jQuery.filter( selector, this ) : this, - i = 0; - - for ( ; (elem = elems[i]) != null; i++ ) { - if ( !keepData && elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem ) ); - } - - if ( elem.parentNode ) { - if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { - setGlobalEval( getAll( elem, "script" ) ); - } - elem.parentNode.removeChild( elem ); - } - } - - return this; - }, - - empty: function() { - var elem, - i = 0; - - for ( ; (elem = this[i]) != null; i++ ) { - if ( elem.nodeType === 1 ) { - - // Prevent memory leaks - jQuery.cleanData( getAll( elem, false ) ); - - // Remove any remaining nodes - elem.textContent = ""; - } - } - - return this; - }, - - clone: function( dataAndEvents, deepDataAndEvents ) { - dataAndEvents = dataAndEvents == null ? false : dataAndEvents; - deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; - - return this.map(function() { - return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); - }); - }, - - html: function( value ) { - return access( this, function( value ) { - var elem = this[ 0 ] || {}, - i = 0, - l = this.length; - - if ( value === undefined && elem.nodeType === 1 ) { - return elem.innerHTML; - } - - // See if we can take a shortcut and just use innerHTML - if ( typeof value === "string" && !rnoInnerhtml.test( value ) && - !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { - - value = value.replace( rxhtmlTag, "<$1>" ); - - try { - for ( ; i < l; i++ ) { - elem = this[ i ] || {}; - - // Remove element nodes and prevent memory leaks - if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - elem.innerHTML = value; - } - } - - elem = 0; - - // If using innerHTML throws an exception, use the fallback method - } catch( e ) {} - } - - if ( elem ) { - this.empty().append( value ); - } - }, null, value, arguments.length ); - }, - - replaceWith: function() { - var arg = arguments[ 0 ]; - - // Make the changes, replacing each context element with the new content - this.domManip( arguments, function( elem ) { - arg = this.parentNode; - - jQuery.cleanData( getAll( this ) ); - - if ( arg ) { - arg.replaceChild( elem, this ); - } - }); - - // Force removal if there was no new content (e.g., from empty arguments) - return arg && (arg.length || arg.nodeType) ? this : this.remove(); - }, - - detach: function( selector ) { - return this.remove( selector, true ); - }, - - domManip: function( args, callback ) { - - // Flatten any nested arrays - args = concat.apply( [], args ); - - var fragment, first, scripts, hasScripts, node, doc, - i = 0, - l = this.length, - set = this, - iNoClone = l - 1, - value = args[ 0 ], - isFunction = jQuery.isFunction( value ); - - // We can't cloneNode fragments that contain checked, in WebKit - if ( isFunction || - ( l > 1 && typeof value === "string" && - !support.checkClone && rchecked.test( value ) ) ) { - return this.each(function( index ) { - var self = set.eq( index ); - if ( isFunction ) { - args[ 0 ] = value.call( this, index, self.html() ); - } - self.domManip( args, callback ); - }); - } - - if ( l ) { - fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); - first = fragment.firstChild; - - if ( fragment.childNodes.length === 1 ) { - fragment = first; - } - - if ( first ) { - scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); - hasScripts = scripts.length; - - // Use the original fragment for the last item instead of the first because it can end up - // being emptied incorrectly in certain situations (#8070). - for ( ; i < l; i++ ) { - node = fragment; - - if ( i !== iNoClone ) { - node = jQuery.clone( node, true, true ); - - // Keep references to cloned scripts for later restoration - if ( hasScripts ) { - // Support: QtWebKit - // jQuery.merge because push.apply(_, arraylike) throws - jQuery.merge( scripts, getAll( node, "script" ) ); - } - } - - callback.call( this[ i ], node, i ); - } - - if ( hasScripts ) { - doc = scripts[ scripts.length - 1 ].ownerDocument; - - // Reenable scripts - jQuery.map( scripts, restoreScript ); - - // Evaluate executable scripts on first document insertion - for ( i = 0; i < hasScripts; i++ ) { - node = scripts[ i ]; - if ( rscriptType.test( node.type || "" ) && - !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { - - if ( node.src ) { - // Optional AJAX dependency, but won't run scripts if not present - if ( jQuery._evalUrl ) { - jQuery._evalUrl( node.src ); - } - } else { - jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); - } - } - } - } - } - } - - return this; - } -}); - -jQuery.each({ - appendTo: "append", - prependTo: "prepend", - insertBefore: "before", - insertAfter: "after", - replaceAll: "replaceWith" -}, function( name, original ) { - jQuery.fn[ name ] = function( selector ) { - var elems, - ret = [], - insert = jQuery( selector ), - last = insert.length - 1, - i = 0; - - for ( ; i <= last; i++ ) { - elems = i === last ? this : this.clone( true ); - jQuery( insert[ i ] )[ original ]( elems ); - - // Support: QtWebKit - // .get() because push.apply(_, arraylike) throws - push.apply( ret, elems.get() ); - } - - return this.pushStack( ret ); - }; -}); - - -var iframe, - elemdisplay = {}; - -/** - * Retrieve the actual display of a element - * @param {String} name nodeName of the element - * @param {Object} doc Document object - */ -// Called only from within defaultDisplay -function actualDisplay( name, doc ) { - var style, - elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), - - // getDefaultComputedStyle might be reliably used only on attached element - display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? - - // Use of this method is a temporary fix (more like optmization) until something better comes along, - // since it was removed from specification and supported only in FF - style.display : jQuery.css( elem[ 0 ], "display" ); - - // We don't have any data stored on the element, - // so use "detach" method as fast way to get rid of the element - elem.detach(); - - return display; -} - -/** - * Try to determine the default display value of an element - * @param {String} nodeName - */ -function defaultDisplay( nodeName ) { - var doc = document, - display = elemdisplay[ nodeName ]; - - if ( !display ) { - display = actualDisplay( nodeName, doc ); - - // If the simple way fails, read from inside an iframe - if ( display === "none" || !display ) { - - // Use the already-created iframe if possible - iframe = (iframe || jQuery( "