From ce1cd9f31a2057a95c2c3e90775b190df1c803dc Mon Sep 17 00:00:00 2001 From: AuthyApps Date: Mon, 3 Jan 2022 15:12:08 +0000 Subject: [PATCH] Version bump to 0.6.0 [skip ci] --- CHANGELOG.md | 16 + docs/0.6.0/-search.html | 34 + docs/0.6.0/images/arrow_down.svg | 3 + docs/0.6.0/images/docs_logo.svg | 7 + docs/0.6.0/images/logo-icon.svg | 3 + docs/0.6.0/images/logo-text.svg | 6 + docs/0.6.0/index.html | 13 + docs/0.6.0/navigation.html | 181 +++ docs/0.6.0/scripts/clipboard.js | 52 + docs/0.6.0/scripts/main.js | 366 ++++++ docs/0.6.0/scripts/main.js.map | 1 + docs/0.6.0/scripts/navigationLoader.js | 54 + docs/0.6.0/scripts/pages.js | 124 ++ docs/0.6.0/scripts/platformContentHandler.js | 226 ++++ docs/0.6.0/scripts/scripts.js | 11 + docs/0.6.0/scripts/search.js | 7 + docs/0.6.0/scripts/sourceset_dependencies.js | 1 + docs/0.6.0/styles/jetbrains-mono.css | 13 + docs/0.6.0/styles/style.css | 1056 +++++++++++++++++ .../com.twilio.verify.data/-entry/-init-.html | 50 + .../-entry/component1.html | 50 + .../-entry/component2.html | 50 + .../com.twilio.verify.data/-entry/copy.html | 50 + .../com.twilio.verify.data/-entry/index.html | 251 ++++ .../-migration/index.html | 199 ++++ .../-migration/migrate.html | 50 + .../verify/com.twilio.verify.data/index.html | 98 ++ .../-log-level/-all/index.html | 298 +++++ .../-log-level/-debug/index.html | 298 +++++ .../-log-level/-error/index.html | 298 +++++ .../-log-level/-info/index.html | 298 +++++ .../-log-level/-networking/index.html | 298 +++++ .../-log-level/index.html | 358 ++++++ .../-logger-service/index.html | 178 +++ .../-logger-service/log.html | 50 + .../com.twilio.verify.logger/index.html | 98 ++ .../-challenge-details/-init-.html | 50 + .../-challenge-details/component1.html | 50 + .../-challenge-details/component2.html | 50 + .../-challenge-details/component3.html | 50 + .../-challenge-details/copy.html | 50 + .../-challenge-details/index.html | 321 +++++ .../-challenge-list-order/-asc/index.html | 277 +++++ .../-challenge-list-order/-desc/index.html | 277 +++++ .../-challenge-list-order/index.html | 295 +++++ .../-challenge-list-payload/-init-.html | 50 + .../-challenge-list-payload/index.html | 259 ++++ .../-challenge-list/index.html | 173 +++ .../-challenge-status/-approved/index.html | 298 +++++ .../-challenge-status/-denied/index.html | 298 +++++ .../-challenge-status/-expired/index.html | 298 +++++ .../-challenge-status/-pending/index.html | 298 +++++ .../-challenge-status/index.html | 358 ++++++ .../-challenge/index.html | 299 +++++ .../-detail/-init-.html | 50 + .../-detail/component1.html | 50 + .../-detail/component2.html | 50 + .../-detail/copy.html | 50 + .../-detail/index.html | 274 +++++ .../-factor-payload/index.html | 237 ++++ .../-factor-status/-unverified/index.html | 298 +++++ .../-factor-status/-verified/index.html | 298 +++++ .../-factor-status/index.html | 316 +++++ .../-factor-type/-p-u-s-h/index.html | 298 +++++ .../-factor-type/index.html | 295 +++++ .../-factor/index.html | 299 +++++ .../-metadata/index.html | 215 ++++ .../-push-factor-payload/-init-.html | 50 + .../-push-factor-payload/index.html | 289 +++++ .../-update-challenge-payload/index.html | 186 +++ .../-update-factor-payload/index.html | 165 +++ .../-init-.html | 50 + .../-update-push-challenge-payload/index.html | 217 ++++ .../-update-push-factor-payload/-init-.html | 50 + .../component1.html | 50 + .../component2.html | 50 + .../-update-push-factor-payload/copy.html | 50 + .../-update-push-factor-payload/index.html | 274 +++++ .../-verify-factor-payload/index.html | 165 +++ .../-verify-push-factor-payload/-init-.html | 50 + .../-verify-push-factor-payload/index.html | 175 +++ .../com.twilio.verify.models/index.html | 540 +++++++++ .../-failure-response/-init-.html | 50 + .../-failure-response/index.html | 194 +++ .../-http-method/-delete/index.html | 298 +++++ .../-http-method/-get/index.html | 298 +++++ .../-http-method/-post/index.html | 298 +++++ .../-http-method/-put/index.html | 298 +++++ .../-http-method/index.html | 358 ++++++ .../-media-type-header/-accept/index.html | 298 +++++ .../-content-type/index.html | 298 +++++ .../-media-type-header/index.html | 316 +++++ .../-network-adapter/-init-.html | 50 + .../-network-adapter/execute.html | 50 + .../-network-adapter/index.html | 155 +++ .../-network-exception/-init-.html | 58 + .../-network-exception/index.html | 454 +++++++ .../-network-provider/execute.html | 50 + .../-network-provider/index.html | 168 +++ .../-request-helper/common-headers.html | 50 + .../-request-helper/index.html | 155 +++ .../-request/-builder/-init-.html | 50 + .../-request/-builder/body.html | 50 + .../-request/-builder/build.html | 50 + .../-request/-builder/copy.html | 50 + .../-request/-builder/headers.html | 50 + .../-request/-builder/http-method.html | 50 + .../-request/-builder/index.html | 311 +++++ .../-request/-builder/query.html | 50 + .../-request/-builder/tag.html | 50 + .../-request/get-params.html | 50 + .../-request/index.html | 290 +++++ .../-response/-init-.html | 50 + .../-response/index.html | 173 +++ .../com.twilio.verify.networking/index.html | 280 +++++ .../-authentication-token-error/index.html | 298 +++++ .../-initialization-error/index.html | 298 +++++ .../-error-code/-input-error/index.html | 298 +++++ .../-error-code/-key-storage-error/index.html | 298 +++++ .../-error-code/-mapper-error/index.html | 298 +++++ .../-error-code/-network-error/index.html | 298 +++++ .../-error-code/-storage-error/index.html | 298 +++++ .../-error-code/index.html | 421 +++++++ .../-twilio-verify-exception/-init-.html | 50 + .../-twilio-verify-exception/index.html | 444 +++++++ .../-twilio-verify/-builder/-init-.html | 50 + .../-builder/add-logging-service.html | 50 + .../-twilio-verify/-builder/build.html | 50 + .../enable-default-logging-service.html | 50 + .../-twilio-verify/-builder/index.html | 256 ++++ .../-builder/network-provider.html | 50 + .../-twilio-verify/clear-local-storage.html | 50 + .../-twilio-verify/create-factor.html | 50 + .../-twilio-verify/delete-factor.html | 50 + .../-twilio-verify/get-all-challenges.html | 50 + .../-twilio-verify/get-all-factors.html | 50 + .../-twilio-verify/get-challenge.html | 50 + .../-twilio-verify/index.html | 391 ++++++ .../-twilio-verify/update-challenge.html | 50 + .../-twilio-verify/update-factor.html | 50 + .../-twilio-verify/verify-factor.html | 50 + .../0.6.0/verify/com.twilio.verify/index.html | 98 ++ docs/0.6.0/verify/index.html | 96 ++ docs/0.6.0/verify/package-list | 9 + docs/latest | 2 +- verify/gradle.properties | 6 +- 146 files changed, 23993 insertions(+), 4 deletions(-) create mode 100644 docs/0.6.0/-search.html create mode 100644 docs/0.6.0/images/arrow_down.svg create mode 100644 docs/0.6.0/images/docs_logo.svg create mode 100644 docs/0.6.0/images/logo-icon.svg create mode 100644 docs/0.6.0/images/logo-text.svg create mode 100644 docs/0.6.0/index.html create mode 100644 docs/0.6.0/navigation.html create mode 100644 docs/0.6.0/scripts/clipboard.js create mode 100644 docs/0.6.0/scripts/main.js create mode 100644 docs/0.6.0/scripts/main.js.map create mode 100644 docs/0.6.0/scripts/navigationLoader.js create mode 100644 docs/0.6.0/scripts/pages.js create mode 100644 docs/0.6.0/scripts/platformContentHandler.js create mode 100644 docs/0.6.0/scripts/scripts.js create mode 100644 docs/0.6.0/scripts/search.js create mode 100644 docs/0.6.0/scripts/sourceset_dependencies.js create mode 100644 docs/0.6.0/styles/jetbrains-mono.css create mode 100644 docs/0.6.0/styles/style.css create mode 100644 docs/0.6.0/verify/com.twilio.verify.data/-entry/-init-.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.data/-entry/component1.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.data/-entry/component2.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.data/-entry/copy.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.data/-entry/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.data/-migration/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.data/-migration/migrate.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.data/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.logger/-log-level/-all/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.logger/-log-level/-debug/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.logger/-log-level/-error/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.logger/-log-level/-info/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.logger/-log-level/-networking/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.logger/-log-level/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.logger/-logger-service/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.logger/-logger-service/log.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.logger/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-details/-init-.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-details/component1.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-details/component2.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-details/component3.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-details/copy.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-details/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-list-order/-asc/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-list-order/-desc/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-list-order/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-list-payload/-init-.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-list-payload/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-list/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-status/-approved/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-status/-denied/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-status/-expired/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-status/-pending/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge-status/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-challenge/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-detail/-init-.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-detail/component1.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-detail/component2.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-detail/copy.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-detail/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-factor-payload/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-factor-status/-unverified/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-factor-status/-verified/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-factor-status/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-factor-type/-p-u-s-h/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-factor-type/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-factor/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-metadata/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-push-factor-payload/-init-.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-push-factor-payload/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-update-challenge-payload/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-update-factor-payload/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-update-push-challenge-payload/-init-.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-update-push-challenge-payload/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-update-push-factor-payload/-init-.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-update-push-factor-payload/component1.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-update-push-factor-payload/component2.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-update-push-factor-payload/copy.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-update-push-factor-payload/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-verify-factor-payload/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-verify-push-factor-payload/-init-.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/-verify-push-factor-payload/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.models/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-failure-response/-init-.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-failure-response/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-http-method/-delete/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-http-method/-get/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-http-method/-post/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-http-method/-put/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-http-method/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-media-type-header/-accept/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-media-type-header/-content-type/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-media-type-header/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-network-adapter/-init-.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-network-adapter/execute.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-network-adapter/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-network-exception/-init-.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-network-exception/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-network-provider/execute.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-network-provider/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-request-helper/common-headers.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-request-helper/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-request/-builder/-init-.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-request/-builder/body.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-request/-builder/build.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-request/-builder/copy.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-request/-builder/headers.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-request/-builder/http-method.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-request/-builder/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-request/-builder/query.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-request/-builder/tag.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-request/get-params.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-request/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-response/-init-.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/-response/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify.networking/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify-exception/-error-code/-authentication-token-error/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify-exception/-error-code/-initialization-error/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify-exception/-error-code/-input-error/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify-exception/-error-code/-key-storage-error/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify-exception/-error-code/-mapper-error/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify-exception/-error-code/-network-error/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify-exception/-error-code/-storage-error/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify-exception/-error-code/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify-exception/-init-.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify-exception/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/-builder/-init-.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/-builder/add-logging-service.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/-builder/build.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/-builder/enable-default-logging-service.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/-builder/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/-builder/network-provider.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/clear-local-storage.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/create-factor.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/delete-factor.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/get-all-challenges.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/get-all-factors.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/get-challenge.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/index.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/update-challenge.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/update-factor.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/-twilio-verify/verify-factor.html create mode 100644 docs/0.6.0/verify/com.twilio.verify/index.html create mode 100644 docs/0.6.0/verify/index.html create mode 100644 docs/0.6.0/verify/package-list diff --git a/CHANGELOG.md b/CHANGELOG.md index b567b1e2..61382345 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,19 @@ +# 0.6.0 (2022-01-03) + +### Features +- Validate challenge status before trying to update it. Add validations for empty factor sid or challenge sid. Get decrypt information correctly when the provider is not valid. ([5a68181](https://github.com/twilio/twilio-verify-android/commit/5a681814ef97131fff2578acaa988b2e48d186bc)) + +### Size impact + +| ABI | APK Size Impact | +| --------------- | --------------- | +| x86 | 74.3KB | +| x86_64 | 74.3KB | +| armeabi-v7a | 74.3KB | +| arm64-v8a | 74.3KB | +| universal | 74.3KB | + + # 0.5.0 (2021-11-26) ### Features diff --git a/docs/0.6.0/-search.html b/docs/0.6.0/-search.html new file mode 100644 index 00000000..0c4f4d78 --- /dev/null +++ b/docs/0.6.0/-search.html @@ -0,0 +1,34 @@ + + + + Search + + + + + + +
+
+ +
+
+
+ + + +

Search results for

+ + +
+ +
+
+ + + diff --git a/docs/0.6.0/images/arrow_down.svg b/docs/0.6.0/images/arrow_down.svg new file mode 100644 index 00000000..89e7df47 --- /dev/null +++ b/docs/0.6.0/images/arrow_down.svg @@ -0,0 +1,3 @@ + + + diff --git a/docs/0.6.0/images/docs_logo.svg b/docs/0.6.0/images/docs_logo.svg new file mode 100644 index 00000000..7c1e3ae8 --- /dev/null +++ b/docs/0.6.0/images/docs_logo.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/docs/0.6.0/images/logo-icon.svg b/docs/0.6.0/images/logo-icon.svg new file mode 100644 index 00000000..1b3b3670 --- /dev/null +++ b/docs/0.6.0/images/logo-icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/docs/0.6.0/images/logo-text.svg b/docs/0.6.0/images/logo-text.svg new file mode 100644 index 00000000..7bf3e6c5 --- /dev/null +++ b/docs/0.6.0/images/logo-text.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/docs/0.6.0/index.html b/docs/0.6.0/index.html new file mode 100644 index 00000000..e82cebd2 --- /dev/null +++ b/docs/0.6.0/index.html @@ -0,0 +1,13 @@ + + + + + + Document + + + + + \ No newline at end of file diff --git a/docs/0.6.0/navigation.html b/docs/0.6.0/navigation.html new file mode 100644 index 00000000..84a5d717 --- /dev/null +++ b/docs/0.6.0/navigation.html @@ -0,0 +1,181 @@ + + diff --git a/docs/0.6.0/scripts/clipboard.js b/docs/0.6.0/scripts/clipboard.js new file mode 100644 index 00000000..b00ce246 --- /dev/null +++ b/docs/0.6.0/scripts/clipboard.js @@ -0,0 +1,52 @@ +window.addEventListener('load', () => { + document.querySelectorAll('span.copy-icon').forEach(element => { + element.addEventListener('click', (el) => copyElementsContentToClipboard(element)); + }) + + document.querySelectorAll('span.anchor-icon').forEach(element => { + element.addEventListener('click', (el) => { + if(element.hasAttribute('pointing-to')){ + const location = hrefWithoutCurrentlyUsedAnchor() + '#' + element.getAttribute('pointing-to') + copyTextToClipboard(element, location) + } + }); + }) +}) + +const copyElementsContentToClipboard = (element) => { + const selection = window.getSelection(); + const range = document.createRange(); + range.selectNodeContents(element.parentNode.parentNode); + selection.removeAllRanges(); + selection.addRange(range); + + copyAndShowPopup(element, () => selection.removeAllRanges()) +} + +const copyTextToClipboard = (element, text) => { + var textarea = document.createElement("textarea"); + textarea.textContent = text; + textarea.style.position = "fixed"; + document.body.appendChild(textarea); + textarea.select(); + + copyAndShowPopup(element, () => document.body.removeChild(textarea)) +} + +const copyAndShowPopup = (element, after) => { + try { + document.execCommand('copy'); + element.nextElementSibling.classList.add('active-popup'); + setTimeout(() => { + element.nextElementSibling.classList.remove('active-popup'); + }, 1200); + } catch (e) { + console.error('Failed to write to clipboard:', e) + } + finally { + if(after) after() + } +} + +const hrefWithoutCurrentlyUsedAnchor = () => window.location.href.split('#')[0] + diff --git a/docs/0.6.0/scripts/main.js b/docs/0.6.0/scripts/main.js new file mode 100644 index 00000000..d257cb95 --- /dev/null +++ b/docs/0.6.0/scripts/main.js @@ -0,0 +1,366 @@ +!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=1111)}([function(e,t,n){e.exports=n(768)()},function(e,t,n){"use strict";e.exports=n(763)},function(e,t,n){var r; +/*! + Copyright (c) 2017 Jed Watson. + Licensed under the MIT License (MIT), see + http://jedwatson.github.io/classnames +*/!function(){"use strict";var n={}.hasOwnProperty;function o(){for(var e=[],t=0;t>>0;for(t=0;t0)for(n=0;n=0?n?"+":"":"-")+Math.pow(10,Math.max(0,o)).toString().substr(1)+r}o.suppressDeprecationWarnings=!1,o.deprecationHandler=null,S=Object.keys?Object.keys:function(e){var t,n=[];for(t in e)s(e,t)&&n.push(t);return n};var P=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,j=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Y={},A={};function I(e,t,n,r){var o=r;"string"==typeof r&&(o=function(){return this[r]()}),e&&(A[e]=o),t&&(A[t[0]]=function(){return C(o.apply(this,arguments),t[1],t[2])}),n&&(A[n]=function(){return this.localeData().ordinal(o.apply(this,arguments),e)})}function R(e,t){return e.isValid()?(t=$(t,e.localeData()),Y[t]=Y[t]||function(e){var t,n,r,o=e.match(P);for(t=0,n=o.length;t=0&&j.test(e);)e=e.replace(j,r),j.lastIndex=0,n-=1;return e}var H={};function N(e,t){var n=e.toLowerCase();H[n]=H[n+"s"]=H[t]=e}function z(e){return"string"==typeof e?H[e]||H[e.toLowerCase()]:void 0}function F(e){var t,n,r={};for(n in e)s(e,n)&&(t=z(n))&&(r[t]=e[n]);return r}var B={};function U(e,t){B[e]=t}function W(e){return e%4==0&&e%100!=0||e%400==0}function V(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function q(e){var t=+e,n=0;return 0!==t&&isFinite(t)&&(n=V(t)),n}function G(e,t){return function(n){return null!=n?(J(this,e,n),o.updateOffset(this,t),this):K(this,e)}}function K(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function J(e,t,n){e.isValid()&&!isNaN(n)&&("FullYear"===t&&W(e.year())&&1===e.month()&&29===e.date()?(n=q(n),e._d["set"+(e._isUTC?"UTC":"")+t](n,e.month(),xe(n,e.month()))):e._d["set"+(e._isUTC?"UTC":"")+t](n))}var Q,Z=/\d/,X=/\d\d/,ee=/\d{3}/,te=/\d{4}/,ne=/[+-]?\d{6}/,re=/\d\d?/,oe=/\d\d\d\d?/,ie=/\d\d\d\d\d\d?/,ae=/\d{1,3}/,se=/\d{1,4}/,le=/[+-]?\d{1,6}/,ce=/\d+/,ue=/[+-]?\d+/,fe=/Z|[+-]\d\d:?\d\d/gi,de=/Z|[+-]\d\d(?::?\d\d)?/gi,pe=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;function he(e,t,n){Q[e]=T(t)?t:function(e,r){return e&&n?n:t}}function me(e,t){return s(Q,e)?Q[e](t._strict,t._locale):new RegExp(ge(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,(function(e,t,n,r,o){return t||n||r||o}))))}function ge(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}Q={};var ve,ye={};function be(e,t){var n,r=t;for("string"==typeof e&&(e=[e]),u(t)&&(r=function(e,n){n[t]=q(e)}),n=0;n68?1900:2e3)};var je=G("FullYear",!0);function Ye(e,t,n,r,o,i,a){var s;return e<100&&e>=0?(s=new Date(e+400,t,n,r,o,i,a),isFinite(s.getFullYear())&&s.setFullYear(e)):s=new Date(e,t,n,r,o,i,a),s}function Ae(e){var t,n;return e<100&&e>=0?((n=Array.prototype.slice.call(arguments))[0]=e+400,t=new Date(Date.UTC.apply(null,n)),isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e)):t=new Date(Date.UTC.apply(null,arguments)),t}function Ie(e,t,n){var r=7+t-n;return-(7+Ae(e,0,r).getUTCDay()-t)%7+r-1}function Re(e,t,n,r,o){var i,a,s=1+7*(t-1)+(7+n-r)%7+Ie(e,r,o);return s<=0?a=Pe(i=e-1)+s:s>Pe(e)?(i=e+1,a=s-Pe(e)):(i=e,a=s),{year:i,dayOfYear:a}}function $e(e,t,n){var r,o,i=Ie(e.year(),t,n),a=Math.floor((e.dayOfYear()-i-1)/7)+1;return a<1?r=a+He(o=e.year()-1,t,n):a>He(e.year(),t,n)?(r=a-He(e.year(),t,n),o=e.year()+1):(o=e.year(),r=a),{week:r,year:o}}function He(e,t,n){var r=Ie(e,t,n),o=Ie(e+1,t,n);return(Pe(e)-r+o)/7}function Ne(e,t){return e.slice(t,7).concat(e.slice(0,t))}I("w",["ww",2],"wo","week"),I("W",["WW",2],"Wo","isoWeek"),N("week","w"),N("isoWeek","W"),U("week",5),U("isoWeek",5),he("w",re),he("ww",re,X),he("W",re),he("WW",re,X),_e(["w","ww","W","WW"],(function(e,t,n,r){t[r.substr(0,1)]=q(e)})),I("d",0,"do","day"),I("dd",0,0,(function(e){return this.localeData().weekdaysMin(this,e)})),I("ddd",0,0,(function(e){return this.localeData().weekdaysShort(this,e)})),I("dddd",0,0,(function(e){return this.localeData().weekdays(this,e)})),I("e",0,0,"weekday"),I("E",0,0,"isoWeekday"),N("day","d"),N("weekday","e"),N("isoWeekday","E"),U("day",11),U("weekday",11),U("isoWeekday",11),he("d",re),he("e",re),he("E",re),he("dd",(function(e,t){return t.weekdaysMinRegex(e)})),he("ddd",(function(e,t){return t.weekdaysShortRegex(e)})),he("dddd",(function(e,t){return t.weekdaysRegex(e)})),_e(["dd","ddd","dddd"],(function(e,t,n,r){var o=n._locale.weekdaysParse(e,r,n._strict);null!=o?t.d=o:m(n).invalidWeekday=e})),_e(["d","e","E"],(function(e,t,n,r){t[r]=q(e)}));var ze="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Fe="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Be="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),Ue=pe,We=pe,Ve=pe;function qe(e,t,n){var r,o,i,a=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],r=0;r<7;++r)i=h([2e3,1]).day(r),this._minWeekdaysParse[r]=this.weekdaysMin(i,"").toLocaleLowerCase(),this._shortWeekdaysParse[r]=this.weekdaysShort(i,"").toLocaleLowerCase(),this._weekdaysParse[r]=this.weekdays(i,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(o=ve.call(this._weekdaysParse,a))?o:null:"ddd"===t?-1!==(o=ve.call(this._shortWeekdaysParse,a))?o:null:-1!==(o=ve.call(this._minWeekdaysParse,a))?o:null:"dddd"===t?-1!==(o=ve.call(this._weekdaysParse,a))||-1!==(o=ve.call(this._shortWeekdaysParse,a))||-1!==(o=ve.call(this._minWeekdaysParse,a))?o:null:"ddd"===t?-1!==(o=ve.call(this._shortWeekdaysParse,a))||-1!==(o=ve.call(this._weekdaysParse,a))||-1!==(o=ve.call(this._minWeekdaysParse,a))?o:null:-1!==(o=ve.call(this._minWeekdaysParse,a))||-1!==(o=ve.call(this._weekdaysParse,a))||-1!==(o=ve.call(this._shortWeekdaysParse,a))?o:null}function Ge(){function e(e,t){return t.length-e.length}var t,n,r,o,i,a=[],s=[],l=[],c=[];for(t=0;t<7;t++)n=h([2e3,1]).day(t),r=ge(this.weekdaysMin(n,"")),o=ge(this.weekdaysShort(n,"")),i=ge(this.weekdays(n,"")),a.push(r),s.push(o),l.push(i),c.push(r),c.push(o),c.push(i);a.sort(e),s.sort(e),l.sort(e),c.sort(e),this._weekdaysRegex=new RegExp("^("+c.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+l.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+s.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+a.join("|")+")","i")}function Ke(){return this.hours()%12||12}function Je(e,t){I(e,0,0,(function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)}))}function Qe(e,t){return t._meridiemParse}I("H",["HH",2],0,"hour"),I("h",["hh",2],0,Ke),I("k",["kk",2],0,(function(){return this.hours()||24})),I("hmm",0,0,(function(){return""+Ke.apply(this)+C(this.minutes(),2)})),I("hmmss",0,0,(function(){return""+Ke.apply(this)+C(this.minutes(),2)+C(this.seconds(),2)})),I("Hmm",0,0,(function(){return""+this.hours()+C(this.minutes(),2)})),I("Hmmss",0,0,(function(){return""+this.hours()+C(this.minutes(),2)+C(this.seconds(),2)})),Je("a",!0),Je("A",!1),N("hour","h"),U("hour",13),he("a",Qe),he("A",Qe),he("H",re),he("h",re),he("k",re),he("HH",re,X),he("hh",re,X),he("kk",re,X),he("hmm",oe),he("hmmss",ie),he("Hmm",oe),he("Hmmss",ie),be(["H","HH"],3),be(["k","kk"],(function(e,t,n){var r=q(e);t[3]=24===r?0:r})),be(["a","A"],(function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e})),be(["h","hh"],(function(e,t,n){t[3]=q(e),m(n).bigHour=!0})),be("hmm",(function(e,t,n){var r=e.length-2;t[3]=q(e.substr(0,r)),t[4]=q(e.substr(r)),m(n).bigHour=!0})),be("hmmss",(function(e,t,n){var r=e.length-4,o=e.length-2;t[3]=q(e.substr(0,r)),t[4]=q(e.substr(r,2)),t[5]=q(e.substr(o)),m(n).bigHour=!0})),be("Hmm",(function(e,t,n){var r=e.length-2;t[3]=q(e.substr(0,r)),t[4]=q(e.substr(r))})),be("Hmmss",(function(e,t,n){var r=e.length-4,o=e.length-2;t[3]=q(e.substr(0,r)),t[4]=q(e.substr(r,2)),t[5]=q(e.substr(o))}));var Ze,Xe=G("Hours",!0),et={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:ke,monthsShort:Me,week:{dow:0,doy:6},weekdays:ze,weekdaysMin:Be,weekdaysShort:Fe,meridiemParse:/[ap]\.?m?\.?/i},tt={},nt={};function rt(e,t){var n,r=Math.min(e.length,t.length);for(n=0;n0;){if(r=it(o.slice(0,t).join("-")))return r;if(n&&n.length>=t&&rt(o,n)>=t-1)break;t--}i++}return Ze}(e)}function ct(e){var t,n=e._a;return n&&-2===m(e).overflow&&(t=n[1]<0||n[1]>11?1:n[2]<1||n[2]>xe(n[0],n[1])?2:n[3]<0||n[3]>24||24===n[3]&&(0!==n[4]||0!==n[5]||0!==n[6])?3:n[4]<0||n[4]>59?4:n[5]<0||n[5]>59?5:n[6]<0||n[6]>999?6:-1,m(e)._overflowDayOfYear&&(t<0||t>2)&&(t=2),m(e)._overflowWeeks&&-1===t&&(t=7),m(e)._overflowWeekday&&-1===t&&(t=8),m(e).overflow=t),e}var ut=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,ft=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,dt=/Z|[+-]\d\d(?::?\d\d)?/,pt=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/],["YYYYMM",/\d{6}/,!1],["YYYY",/\d{4}/,!1]],ht=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],mt=/^\/?Date\((-?\d+)/i,gt=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,vt={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function yt(e){var t,n,r,o,i,a,s=e._i,l=ut.exec(s)||ft.exec(s);if(l){for(m(e).iso=!0,t=0,n=pt.length;t7)&&(l=!0)):(i=e._locale._week.dow,a=e._locale._week.doy,c=$e(Ot(),i,a),n=wt(t.gg,e._a[0],c.year),r=wt(t.w,c.week),null!=t.d?((o=t.d)<0||o>6)&&(l=!0):null!=t.e?(o=t.e+i,(t.e<0||t.e>6)&&(l=!0)):o=i),r<1||r>He(n,i,a)?m(e)._overflowWeeks=!0:null!=l?m(e)._overflowWeekday=!0:(s=Re(n,r,o,i,a),e._a[0]=s.year,e._dayOfYear=s.dayOfYear)}(e),null!=e._dayOfYear&&(a=wt(e._a[0],r[0]),(e._dayOfYear>Pe(a)||0===e._dayOfYear)&&(m(e)._overflowDayOfYear=!0),n=Ae(a,0,e._dayOfYear),e._a[1]=n.getUTCMonth(),e._a[2]=n.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=s[t]=r[t];for(;t<7;t++)e._a[t]=s[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[3]&&0===e._a[4]&&0===e._a[5]&&0===e._a[6]&&(e._nextDay=!0,e._a[3]=0),e._d=(e._useUTC?Ae:Ye).apply(null,s),i=e._useUTC?e._d.getUTCDay():e._d.getDay(),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[3]=24),e._w&&void 0!==e._w.d&&e._w.d!==i&&(m(e).weekdayMismatch=!0)}}function kt(e){if(e._f!==o.ISO_8601)if(e._f!==o.RFC_2822){e._a=[],m(e).empty=!0;var t,n,r,i,a,s,l=""+e._i,c=l.length,u=0;for(r=$(e._f,e._locale).match(P)||[],t=0;t0&&m(e).unusedInput.push(a),l=l.slice(l.indexOf(n)+n.length),u+=n.length),A[i]?(n?m(e).empty=!1:m(e).unusedTokens.push(i),we(i,n,e)):e._strict&&!n&&m(e).unusedTokens.push(i);m(e).charsLeftOver=c-u,l.length>0&&m(e).unusedInput.push(l),e._a[3]<=12&&!0===m(e).bigHour&&e._a[3]>0&&(m(e).bigHour=void 0),m(e).parsedDateParts=e._a.slice(0),m(e).meridiem=e._meridiem,e._a[3]=function(e,t,n){var r;return null==n?t:null!=e.meridiemHour?e.meridiemHour(t,n):null!=e.isPM?((r=e.isPM(n))&&t<12&&(t+=12),r||12!==t||(t=0),t):t}(e._locale,e._a[3],e._meridiem),null!==(s=m(e).era)&&(e._a[0]=e._locale.erasConvertYear(s,e._a[0])),xt(e),ct(e)}else _t(e);else yt(e)}function Mt(e){var t=e._i,n=e._f;return e._locale=e._locale||lt(e._l),null===t||void 0===n&&""===t?v({nullInput:!0}):("string"==typeof t&&(e._i=t=e._locale.preparse(t)),x(t)?new w(ct(t)):(f(t)?e._d=t:i(n)?function(e){var t,n,r,o,i,a,s=!1;if(0===e._f.length)return m(e).invalidFormat=!0,void(e._d=new Date(NaN));for(o=0;othis?this:e:v()}));function Lt(e,t){var n,r;if(1===t.length&&i(t[0])&&(t=t[0]),!t.length)return Ot();for(n=t[0],r=1;r=0?new Date(e+400,t,n)-126227808e5:new Date(e,t,n).valueOf()}function on(e,t,n){return e<100&&e>=0?Date.UTC(e+400,t,n)-126227808e5:Date.UTC(e,t,n)}function an(e,t){return t.erasAbbrRegex(e)}function sn(){var e,t,n=[],r=[],o=[],i=[],a=this.eras();for(e=0,t=a.length;e(i=He(e,r,o))&&(t=i),un.call(this,e,t,n,r,o))}function un(e,t,n,r,o){var i=Re(e,t,n,r,o),a=Ae(i.year,0,i.dayOfYear);return this.year(a.getUTCFullYear()),this.month(a.getUTCMonth()),this.date(a.getUTCDate()),this}I("N",0,0,"eraAbbr"),I("NN",0,0,"eraAbbr"),I("NNN",0,0,"eraAbbr"),I("NNNN",0,0,"eraName"),I("NNNNN",0,0,"eraNarrow"),I("y",["y",1],"yo","eraYear"),I("y",["yy",2],0,"eraYear"),I("y",["yyy",3],0,"eraYear"),I("y",["yyyy",4],0,"eraYear"),he("N",an),he("NN",an),he("NNN",an),he("NNNN",(function(e,t){return t.erasNameRegex(e)})),he("NNNNN",(function(e,t){return t.erasNarrowRegex(e)})),be(["N","NN","NNN","NNNN","NNNNN"],(function(e,t,n,r){var o=n._locale.erasParse(e,r,n._strict);o?m(n).era=o:m(n).invalidEra=e})),he("y",ce),he("yy",ce),he("yyy",ce),he("yyyy",ce),he("yo",(function(e,t){return t._eraYearOrdinalRegex||ce})),be(["y","yy","yyy","yyyy"],0),be(["yo"],(function(e,t,n,r){var o;n._locale._eraYearOrdinalRegex&&(o=e.match(n._locale._eraYearOrdinalRegex)),n._locale.eraYearOrdinalParse?t[0]=n._locale.eraYearOrdinalParse(e,o):t[0]=parseInt(e,10)})),I(0,["gg",2],0,(function(){return this.weekYear()%100})),I(0,["GG",2],0,(function(){return this.isoWeekYear()%100})),ln("gggg","weekYear"),ln("ggggg","weekYear"),ln("GGGG","isoWeekYear"),ln("GGGGG","isoWeekYear"),N("weekYear","gg"),N("isoWeekYear","GG"),U("weekYear",1),U("isoWeekYear",1),he("G",ue),he("g",ue),he("GG",re,X),he("gg",re,X),he("GGGG",se,te),he("gggg",se,te),he("GGGGG",le,ne),he("ggggg",le,ne),_e(["gggg","ggggg","GGGG","GGGGG"],(function(e,t,n,r){t[r.substr(0,2)]=q(e)})),_e(["gg","GG"],(function(e,t,n,r){t[r]=o.parseTwoDigitYear(e)})),I("Q",0,"Qo","quarter"),N("quarter","Q"),U("quarter",7),he("Q",Z),be("Q",(function(e,t){t[1]=3*(q(e)-1)})),I("D",["DD",2],"Do","date"),N("date","D"),U("date",9),he("D",re),he("DD",re,X),he("Do",(function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient})),be(["D","DD"],2),be("Do",(function(e,t){t[2]=q(e.match(re)[0])}));var fn=G("Date",!0);I("DDD",["DDDD",3],"DDDo","dayOfYear"),N("dayOfYear","DDD"),U("dayOfYear",4),he("DDD",ae),he("DDDD",ee),be(["DDD","DDDD"],(function(e,t,n){n._dayOfYear=q(e)})),I("m",["mm",2],0,"minute"),N("minute","m"),U("minute",14),he("m",re),he("mm",re,X),be(["m","mm"],4);var dn=G("Minutes",!1);I("s",["ss",2],0,"second"),N("second","s"),U("second",15),he("s",re),he("ss",re,X),be(["s","ss"],5);var pn,hn,mn=G("Seconds",!1);for(I("S",0,0,(function(){return~~(this.millisecond()/100)})),I(0,["SS",2],0,(function(){return~~(this.millisecond()/10)})),I(0,["SSS",3],0,"millisecond"),I(0,["SSSS",4],0,(function(){return 10*this.millisecond()})),I(0,["SSSSS",5],0,(function(){return 100*this.millisecond()})),I(0,["SSSSSS",6],0,(function(){return 1e3*this.millisecond()})),I(0,["SSSSSSS",7],0,(function(){return 1e4*this.millisecond()})),I(0,["SSSSSSSS",8],0,(function(){return 1e5*this.millisecond()})),I(0,["SSSSSSSSS",9],0,(function(){return 1e6*this.millisecond()})),N("millisecond","ms"),U("millisecond",16),he("S",ae,Z),he("SS",ae,X),he("SSS",ae,ee),pn="SSSS";pn.length<=9;pn+="S")he(pn,ce);function gn(e,t){t[6]=q(1e3*("0."+e))}for(pn="S";pn.length<=9;pn+="S")be(pn,gn);hn=G("Milliseconds",!1),I("z",0,0,"zoneAbbr"),I("zz",0,0,"zoneName");var vn=w.prototype;function yn(e){return e}vn.add=qt,vn.calendar=function(e,t){1===arguments.length&&(Jt(arguments[0])?(e=arguments[0],t=void 0):Qt(arguments[0])&&(t=arguments[0],e=void 0));var n=e||Ot(),r=Rt(n,this).startOf("day"),i=o.calendarFormat(this,r)||"sameElse",a=t&&(T(t[i])?t[i].call(this,n):t[i]);return this.format(a||this.localeData().calendar(i,this,Ot(n)))},vn.clone=function(){return new w(this)},vn.diff=function(e,t,n){var r,o,i;if(!this.isValid())return NaN;if(!(r=Rt(e,this)).isValid())return NaN;switch(o=6e4*(r.utcOffset()-this.utcOffset()),t=z(t)){case"year":i=Zt(this,r)/12;break;case"month":i=Zt(this,r);break;case"quarter":i=Zt(this,r)/3;break;case"second":i=(this-r)/1e3;break;case"minute":i=(this-r)/6e4;break;case"hour":i=(this-r)/36e5;break;case"day":i=(this-r-o)/864e5;break;case"week":i=(this-r-o)/6048e5;break;default:i=this-r}return n?i:V(i)},vn.endOf=function(e){var t,n;if(void 0===(e=z(e))||"millisecond"===e||!this.isValid())return this;switch(n=this._isUTC?on:rn,e){case"year":t=n(this.year()+1,0,1)-1;break;case"quarter":t=n(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":t=n(this.year(),this.month()+1,1)-1;break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":t=n(this.year(),this.month(),this.date()+1)-1;break;case"hour":t=this._d.valueOf(),t+=36e5-nn(t+(this._isUTC?0:6e4*this.utcOffset()),36e5)-1;break;case"minute":t=this._d.valueOf(),t+=6e4-nn(t,6e4)-1;break;case"second":t=this._d.valueOf(),t+=1e3-nn(t,1e3)-1}return this._d.setTime(t),o.updateOffset(this,!0),this},vn.format=function(e){e||(e=this.isUtc()?o.defaultFormatUtc:o.defaultFormat);var t=R(this,e);return this.localeData().postformat(t)},vn.from=function(e,t){return this.isValid()&&(x(e)&&e.isValid()||Ot(e).isValid())?Ft({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},vn.fromNow=function(e){return this.from(Ot(),e)},vn.to=function(e,t){return this.isValid()&&(x(e)&&e.isValid()||Ot(e).isValid())?Ft({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},vn.toNow=function(e){return this.to(Ot(),e)},vn.get=function(e){return T(this[e=z(e)])?this[e]():this},vn.invalidAt=function(){return m(this).overflow},vn.isAfter=function(e,t){var n=x(e)?e:Ot(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=z(t)||"millisecond")?this.valueOf()>n.valueOf():n.valueOf()9999?R(n,t?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):T(Date.prototype.toISOString)?t?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",R(n,"Z")):R(n,t?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")},vn.inspect=function(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e,t,n,r="moment",o="";return this.isLocal()||(r=0===this.utcOffset()?"moment.utc":"moment.parseZone",o="Z"),e="["+r+'("]',t=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",n=o+'[")]',this.format(e+t+"-MM-DD[T]HH:mm:ss.SSS"+n)},"undefined"!=typeof Symbol&&null!=Symbol.for&&(vn[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),vn.toJSON=function(){return this.isValid()?this.toISOString():null},vn.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},vn.unix=function(){return Math.floor(this.valueOf()/1e3)},vn.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},vn.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},vn.eraName=function(){var e,t,n,r=this.localeData().eras();for(e=0,t=r.length;ethis.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},vn.isLocal=function(){return!!this.isValid()&&!this._isUTC},vn.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},vn.isUtc=Ht,vn.isUTC=Ht,vn.zoneAbbr=function(){return this._isUTC?"UTC":""},vn.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},vn.dates=M("dates accessor is deprecated. Use date instead.",fn),vn.months=M("months accessor is deprecated. Use month instead",De),vn.years=M("years accessor is deprecated. Use year instead",je),vn.zone=M("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",(function(e,t){return null!=e?("string"!=typeof e&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()})),vn.isDSTShifted=M("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",(function(){if(!c(this._isDSTShifted))return this._isDSTShifted;var e,t={};return _(t,this),(t=Mt(t))._a?(e=t._isUTC?h(t._a):Ot(t._a),this._isDSTShifted=this.isValid()&&function(e,t,n){var r,o=Math.min(e.length,t.length),i=Math.abs(e.length-t.length),a=0;for(r=0;r0):this._isDSTShifted=!1,this._isDSTShifted}));var bn=D.prototype;function _n(e,t,n,r){var o=lt(),i=h().set(r,t);return o[n](i,e)}function wn(e,t,n){if(u(e)&&(t=e,e=void 0),e=e||"",null!=t)return _n(e,t,n,"month");var r,o=[];for(r=0;r<12;r++)o[r]=_n(e,r,n,"month");return o}function xn(e,t,n,r){"boolean"==typeof e?(u(t)&&(n=t,t=void 0),t=t||""):(n=t=e,e=!1,u(t)&&(n=t,t=void 0),t=t||"");var o,i=lt(),a=e?i._week.dow:0,s=[];if(null!=n)return _n(t,(n+a)%7,r,"day");for(o=0;o<7;o++)s[o]=_n(t,(o+a)%7,r,"day");return s}bn.calendar=function(e,t,n){var r=this._calendar[e]||this._calendar.sameElse;return T(r)?r.call(t,n):r},bn.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.match(P).map((function(e){return"MMMM"===e||"MM"===e||"DD"===e||"dddd"===e?e.slice(1):e})).join(""),this._longDateFormat[e])},bn.invalidDate=function(){return this._invalidDate},bn.ordinal=function(e){return this._ordinal.replace("%d",e)},bn.preparse=yn,bn.postformat=yn,bn.relativeTime=function(e,t,n,r){var o=this._relativeTime[n];return T(o)?o(e,t,n,r):o.replace(/%d/i,e)},bn.pastFuture=function(e,t){var n=this._relativeTime[e>0?"future":"past"];return T(n)?n(t):n.replace(/%s/i,t)},bn.set=function(e){var t,n;for(n in e)s(e,n)&&(T(t=e[n])?this[n]=t:this["_"+n]=t);this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},bn.eras=function(e,t){var n,r,i,a=this._eras||lt("en")._eras;for(n=0,r=a.length;n=0)return l[r]},bn.erasConvertYear=function(e,t){var n=e.since<=e.until?1:-1;return void 0===t?o(e.since).year():o(e.since).year()+(t-e.offset)*n},bn.erasAbbrRegex=function(e){return s(this,"_erasAbbrRegex")||sn.call(this),e?this._erasAbbrRegex:this._erasRegex},bn.erasNameRegex=function(e){return s(this,"_erasNameRegex")||sn.call(this),e?this._erasNameRegex:this._erasRegex},bn.erasNarrowRegex=function(e){return s(this,"_erasNarrowRegex")||sn.call(this),e?this._erasNarrowRegex:this._erasRegex},bn.months=function(e,t){return e?i(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||Se).test(t)?"format":"standalone"][e.month()]:i(this._months)?this._months:this._months.standalone},bn.monthsShort=function(e,t){return e?i(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[Se.test(t)?"format":"standalone"][e.month()]:i(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},bn.monthsParse=function(e,t,n){var r,o,i;if(this._monthsParseExact)return Te.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),r=0;r<12;r++){if(o=h([2e3,r]),n&&!this._longMonthsParse[r]&&(this._longMonthsParse[r]=new RegExp("^"+this.months(o,"").replace(".","")+"$","i"),this._shortMonthsParse[r]=new RegExp("^"+this.monthsShort(o,"").replace(".","")+"$","i")),n||this._monthsParse[r]||(i="^"+this.months(o,"")+"|^"+this.monthsShort(o,""),this._monthsParse[r]=new RegExp(i.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[r].test(e))return r;if(n&&"MMM"===t&&this._shortMonthsParse[r].test(e))return r;if(!n&&this._monthsParse[r].test(e))return r}},bn.monthsRegex=function(e){return this._monthsParseExact?(s(this,"_monthsRegex")||Ce.call(this),e?this._monthsStrictRegex:this._monthsRegex):(s(this,"_monthsRegex")||(this._monthsRegex=Ee),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},bn.monthsShortRegex=function(e){return this._monthsParseExact?(s(this,"_monthsRegex")||Ce.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(s(this,"_monthsShortRegex")||(this._monthsShortRegex=Oe),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},bn.week=function(e){return $e(e,this._week.dow,this._week.doy).week},bn.firstDayOfYear=function(){return this._week.doy},bn.firstDayOfWeek=function(){return this._week.dow},bn.weekdays=function(e,t){var n=i(this._weekdays)?this._weekdays:this._weekdays[e&&!0!==e&&this._weekdays.isFormat.test(t)?"format":"standalone"];return!0===e?Ne(n,this._week.dow):e?n[e.day()]:n},bn.weekdaysMin=function(e){return!0===e?Ne(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin},bn.weekdaysShort=function(e){return!0===e?Ne(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort},bn.weekdaysParse=function(e,t,n){var r,o,i;if(this._weekdaysParseExact)return qe.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),r=0;r<7;r++){if(o=h([2e3,1]).day(r),n&&!this._fullWeekdaysParse[r]&&(this._fullWeekdaysParse[r]=new RegExp("^"+this.weekdays(o,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[r]=new RegExp("^"+this.weekdaysShort(o,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[r]=new RegExp("^"+this.weekdaysMin(o,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[r]||(i="^"+this.weekdays(o,"")+"|^"+this.weekdaysShort(o,"")+"|^"+this.weekdaysMin(o,""),this._weekdaysParse[r]=new RegExp(i.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[r].test(e))return r;if(n&&"ddd"===t&&this._shortWeekdaysParse[r].test(e))return r;if(n&&"dd"===t&&this._minWeekdaysParse[r].test(e))return r;if(!n&&this._weekdaysParse[r].test(e))return r}},bn.weekdaysRegex=function(e){return this._weekdaysParseExact?(s(this,"_weekdaysRegex")||Ge.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(s(this,"_weekdaysRegex")||(this._weekdaysRegex=Ue),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},bn.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(s(this,"_weekdaysRegex")||Ge.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(s(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=We),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},bn.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(s(this,"_weekdaysRegex")||Ge.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(s(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=Ve),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},bn.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},bn.meridiem=function(e,t,n){return e>11?n?"pm":"PM":n?"am":"AM"},at("en",{eras:[{since:"0001-01-01",until:1/0,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-1/0,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===q(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th")}}),o.lang=M("moment.lang is deprecated. Use moment.locale instead.",at),o.langData=M("moment.langData is deprecated. Use moment.localeData instead.",lt);var kn=Math.abs;function Mn(e,t,n,r){var o=Ft(t,n);return e._milliseconds+=r*o._milliseconds,e._days+=r*o._days,e._months+=r*o._months,e._bubble()}function Sn(e){return e<0?Math.floor(e):Math.ceil(e)}function On(e){return 4800*e/146097}function En(e){return 146097*e/4800}function Tn(e){return function(){return this.as(e)}}var Ln=Tn("ms"),Dn=Tn("s"),Cn=Tn("m"),Pn=Tn("h"),jn=Tn("d"),Yn=Tn("w"),An=Tn("M"),In=Tn("Q"),Rn=Tn("y");function $n(e){return function(){return this.isValid()?this._data[e]:NaN}}var Hn=$n("milliseconds"),Nn=$n("seconds"),zn=$n("minutes"),Fn=$n("hours"),Bn=$n("days"),Un=$n("months"),Wn=$n("years"),Vn=Math.round,qn={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function Gn(e,t,n,r,o){return o.relativeTime(t||1,!!n,e,r)}var Kn=Math.abs;function Jn(e){return(e>0)-(e<0)||+e}function Qn(){if(!this.isValid())return this.localeData().invalidDate();var e,t,n,r,o,i,a,s,l=Kn(this._milliseconds)/1e3,c=Kn(this._days),u=Kn(this._months),f=this.asSeconds();return f?(e=V(l/60),t=V(e/60),l%=60,e%=60,n=V(u/12),u%=12,r=l?l.toFixed(3).replace(/\.?0+$/,""):"",o=f<0?"-":"",i=Jn(this._months)!==Jn(f)?"-":"",a=Jn(this._days)!==Jn(f)?"-":"",s=Jn(this._milliseconds)!==Jn(f)?"-":"",o+"P"+(n?i+n+"Y":"")+(u?i+u+"M":"")+(c?a+c+"D":"")+(t||e||l?"T":"")+(t?s+t+"H":"")+(e?s+e+"M":"")+(l?s+r+"S":"")):"P0D"}var Zn=Ct.prototype;return Zn.isValid=function(){return this._isValid},Zn.abs=function(){var e=this._data;return this._milliseconds=kn(this._milliseconds),this._days=kn(this._days),this._months=kn(this._months),e.milliseconds=kn(e.milliseconds),e.seconds=kn(e.seconds),e.minutes=kn(e.minutes),e.hours=kn(e.hours),e.months=kn(e.months),e.years=kn(e.years),this},Zn.add=function(e,t){return Mn(this,e,t,1)},Zn.subtract=function(e,t){return Mn(this,e,t,-1)},Zn.as=function(e){if(!this.isValid())return NaN;var t,n,r=this._milliseconds;if("month"===(e=z(e))||"quarter"===e||"year"===e)switch(t=this._days+r/864e5,n=this._months+On(t),e){case"month":return n;case"quarter":return n/3;case"year":return n/12}else switch(t=this._days+Math.round(En(this._months)),e){case"week":return t/7+r/6048e5;case"day":return t+r/864e5;case"hour":return 24*t+r/36e5;case"minute":return 1440*t+r/6e4;case"second":return 86400*t+r/1e3;case"millisecond":return Math.floor(864e5*t)+r;default:throw new Error("Unknown unit "+e)}},Zn.asMilliseconds=Ln,Zn.asSeconds=Dn,Zn.asMinutes=Cn,Zn.asHours=Pn,Zn.asDays=jn,Zn.asWeeks=Yn,Zn.asMonths=An,Zn.asQuarters=In,Zn.asYears=Rn,Zn.valueOf=function(){return this.isValid()?this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*q(this._months/12):NaN},Zn._bubble=function(){var e,t,n,r,o,i=this._milliseconds,a=this._days,s=this._months,l=this._data;return i>=0&&a>=0&&s>=0||i<=0&&a<=0&&s<=0||(i+=864e5*Sn(En(s)+a),a=0,s=0),l.milliseconds=i%1e3,e=V(i/1e3),l.seconds=e%60,t=V(e/60),l.minutes=t%60,n=V(t/60),l.hours=n%24,a+=V(n/24),o=V(On(a)),s+=o,a-=Sn(En(o)),r=V(s/12),s%=12,l.days=a,l.months=s,l.years=r,this},Zn.clone=function(){return Ft(this)},Zn.get=function(e){return e=z(e),this.isValid()?this[e+"s"]():NaN},Zn.milliseconds=Hn,Zn.seconds=Nn,Zn.minutes=zn,Zn.hours=Fn,Zn.days=Bn,Zn.weeks=function(){return V(this.days()/7)},Zn.months=Un,Zn.years=Wn,Zn.humanize=function(e,t){if(!this.isValid())return this.localeData().invalidDate();var n,r,o=!1,i=qn;return"object"==typeof e&&(t=e,e=!1),"boolean"==typeof e&&(o=e),"object"==typeof t&&(i=Object.assign({},qn,t),null!=t.s&&null==t.ss&&(i.ss=t.s-1)),n=this.localeData(),r=function(e,t,n,r){var o=Ft(e).abs(),i=Vn(o.as("s")),a=Vn(o.as("m")),s=Vn(o.as("h")),l=Vn(o.as("d")),c=Vn(o.as("M")),u=Vn(o.as("w")),f=Vn(o.as("y")),d=i<=n.ss&&["s",i]||i0,d[4]=r,Gn.apply(null,d)}(this,!o,i,n),o&&(r=n.pastFuture(+this,r)),n.postformat(r)},Zn.toISOString=Qn,Zn.toString=Qn,Zn.toJSON=Qn,Zn.locale=Xt,Zn.localeData=tn,Zn.toIsoString=M("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Qn),Zn.lang=en,I("X",0,0,"unix"),I("x",0,0,"valueOf"),he("x",ue),he("X",/[+-]?\d+(\.\d{1,3})?/),be("X",(function(e,t,n){n._d=new Date(1e3*parseFloat(e))})),be("x",(function(e,t,n){n._d=new Date(q(e))})), +//! moment.js +o.version="2.26.0",t=Ot,o.fn=vn,o.min=function(){var e=[].slice.call(arguments,0);return Lt("isBefore",e)},o.max=function(){var e=[].slice.call(arguments,0);return Lt("isAfter",e)},o.now=function(){return Date.now?Date.now():+new Date},o.utc=h,o.unix=function(e){return Ot(1e3*e)},o.months=function(e,t){return wn(e,t,"months")},o.isDate=f,o.locale=at,o.invalid=v,o.duration=Ft,o.isMoment=x,o.weekdays=function(e,t,n){return xn(e,t,n,"weekdays")},o.parseZone=function(){return Ot.apply(null,arguments).parseZone()},o.localeData=lt,o.isDuration=Pt,o.monthsShort=function(e,t){return wn(e,t,"monthsShort")},o.weekdaysMin=function(e,t,n){return xn(e,t,n,"weekdaysMin")},o.defineLocale=st,o.updateLocale=function(e,t){if(null!=t){var n,r,o=et;null!=tt[e]&&null!=tt[e].parentLocale?tt[e].set(L(tt[e]._config,t)):(null!=(r=it(e))&&(o=r._config),t=L(o,t),null==r&&(t.abbr=e),(n=new D(t)).parentLocale=tt[e],tt[e]=n),at(e)}else null!=tt[e]&&(null!=tt[e].parentLocale?(tt[e]=tt[e].parentLocale,e===at()&&at(e)):null!=tt[e]&&delete tt[e]);return tt[e]},o.locales=function(){return S(tt)},o.weekdaysShort=function(e,t,n){return xn(e,t,n,"weekdaysShort")},o.normalizeUnits=z,o.relativeTimeRounding=function(e){return void 0===e?Vn:"function"==typeof e&&(Vn=e,!0)},o.relativeTimeThreshold=function(e,t){return void 0!==qn[e]&&(void 0===t?qn[e]:(qn[e]=t,"s"===e&&(qn.ss=t-1),!0))},o.calendarFormat=function(e,t){var n=e.diff(t,"days",!0);return n<-6?"sameElse":n<-1?"lastWeek":n<0?"lastDay":n<1?"sameDay":n<2?"nextDay":n<7?"nextWeek":"sameElse"},o.prototype=vn,o.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},o}()}).call(this,n(900)(e))},function(e,t,n){"use strict";var r=n(171),o={};o[n(48)("toStringTag")]="z",o+""!="[object z]"&&n(63)(Object.prototype,"toString",(function(){return"[object "+r(this)+"]"}),!0)},function(e,t,n){n(793),e.exports=angular},function(e,t,n){var r=n(31);r(r.S+r.F*!n(53),"Object",{defineProperty:n(58).f})},function(e,t,n){"use strict";var r=n(40),o=n(80),i=n(53),a=n(31),s=n(63),l=n(145).KEY,c=n(54),u=n(164),f=n(143),d=n(140),p=n(48),h=n(275),m=n(274),g=n(777),v=n(213),y=n(49),b=n(51),_=n(82),w=n(94),x=n(165),k=n(141),M=n(124),S=n(778),O=n(125),E=n(169),T=n(58),L=n(114),D=O.f,C=T.f,P=S.f,j=r.Symbol,Y=r.JSON,A=Y&&Y.stringify,I=p("_hidden"),R=p("toPrimitive"),$={}.propertyIsEnumerable,H=u("symbol-registry"),N=u("symbols"),z=u("op-symbols"),F=Object.prototype,B="function"==typeof j&&!!E.f,U=r.QObject,W=!U||!U.prototype||!U.prototype.findChild,V=i&&c((function(){return 7!=M(C({},"a",{get:function(){return C(this,"a",{value:7}).a}})).a}))?function(e,t,n){var r=D(F,t);r&&delete F[t],C(e,t,n),r&&e!==F&&C(F,t,r)}:C,q=function(e){var t=N[e]=M(j.prototype);return t._k=e,t},G=B&&"symbol"==typeof j.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof j},K=function(e,t,n){return e===F&&K(z,t,n),y(e),t=x(t,!0),y(n),o(N,t)?(n.enumerable?(o(e,I)&&e[I][t]&&(e[I][t]=!1),n=M(n,{enumerable:k(0,!1)})):(o(e,I)||C(e,I,k(1,{})),e[I][t]=!0),V(e,t,n)):C(e,t,n)},J=function(e,t){y(e);for(var n,r=g(t=w(t)),o=0,i=r.length;i>o;)K(e,n=r[o++],t[n]);return e},Q=function(e){var t=$.call(this,e=x(e,!0));return!(this===F&&o(N,e)&&!o(z,e))&&(!(t||!o(this,e)||!o(N,e)||o(this,I)&&this[I][e])||t)},Z=function(e,t){if(e=w(e),t=x(t,!0),e!==F||!o(N,t)||o(z,t)){var n=D(e,t);return!n||!o(N,t)||o(e,I)&&e[I][t]||(n.enumerable=!0),n}},X=function(e){for(var t,n=P(w(e)),r=[],i=0;n.length>i;)o(N,t=n[i++])||t==I||t==l||r.push(t);return r},ee=function(e){for(var t,n=e===F,r=P(n?z:w(e)),i=[],a=0;r.length>a;)!o(N,t=r[a++])||n&&!o(F,t)||i.push(N[t]);return i};B||(s((j=function(){if(this instanceof j)throw TypeError("Symbol is not a constructor!");var e=d(arguments.length>0?arguments[0]:void 0),t=function(n){this===F&&t.call(z,n),o(this,I)&&o(this[I],e)&&(this[I][e]=!1),V(this,e,k(1,n))};return i&&W&&V(F,e,{configurable:!0,set:t}),q(e)}).prototype,"toString",(function(){return this._k})),O.f=Z,T.f=K,n(146).f=S.f=X,n(144).f=Q,E.f=ee,i&&!n(139)&&s(F,"propertyIsEnumerable",Q,!0),h.f=function(e){return q(p(e))}),a(a.G+a.W+a.F*!B,{Symbol:j});for(var te="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),ne=0;te.length>ne;)p(te[ne++]);for(var re=L(p.store),oe=0;re.length>oe;)m(re[oe++]);a(a.S+a.F*!B,"Symbol",{for:function(e){return o(H,e+="")?H[e]:H[e]=j(e)},keyFor:function(e){if(!G(e))throw TypeError(e+" is not a symbol!");for(var t in H)if(H[t]===e)return t},useSetter:function(){W=!0},useSimple:function(){W=!1}}),a(a.S+a.F*!B,"Object",{create:function(e,t){return void 0===t?M(e):J(M(e),t)},defineProperty:K,defineProperties:J,getOwnPropertyDescriptor:Z,getOwnPropertyNames:X,getOwnPropertySymbols:ee});var ie=c((function(){E.f(1)}));a(a.S+a.F*ie,"Object",{getOwnPropertySymbols:function(e){return E.f(_(e))}}),Y&&a(a.S+a.F*(!B||c((function(){var e=j();return"[null]"!=A([e])||"{}"!=A({a:e})||"{}"!=A(Object(e))}))),"JSON",{stringify:function(e){for(var t,n,r=[e],o=1;arguments.length>o;)r.push(arguments[o++]);if(n=t=r[1],(b(t)||void 0!==e)&&!G(e))return v(t)||(t=function(e,t){if("function"==typeof n&&(t=n.call(this,e,t)),!G(t))return t}),r[1]=t,A.apply(Y,r)}}),j.prototype[R]||n(93)(j.prototype,R,j.prototype.valueOf),f(j,"Symbol"),f(Math,"Math",!0),f(r.JSON,"JSON",!0)},function(e,t,n){n(274)("asyncIterator")},function(e,t,n){"use strict";n(779);var r=n(49),o=n(170),i=n(53),a=/./.toString,s=function(e){n(63)(RegExp.prototype,"toString",e,!0)};n(54)((function(){return"/a/b"!=a.call({source:"a",flags:"b"})}))?s((function(){var e=r(this);return"/".concat(e.source,"/","flags"in e?e.flags:!i&&e instanceof RegExp?o.call(e):void 0)})):"toString"!=a.name&&s((function(){return a.call(this)}))},function(e,t,n){var r=Date.prototype,o=r.toString,i=r.getTime;new Date(NaN)+""!="Invalid Date"&&n(63)(r,"toString",(function(){var e=i.call(this);return e==e?o.call(this):"Invalid Date"}))},function(e,t,n){var r=n(31);r(r.S,"Object",{create:n(124)})},function(e,t,n){var r=n(31),o=n(124),i=n(96),a=n(49),s=n(51),l=n(54),c=n(276),u=(n(40).Reflect||{}).construct,f=l((function(){function e(){}return!(u((function(){}),[],e)instanceof e)})),d=!l((function(){u((function(){}))}));r(r.S+r.F*(f||d),"Reflect",{construct:function(e,t){i(e),a(t);var n=arguments.length<3?e:i(arguments[2]);if(d&&!f)return u(e,t,n);if(e==n){switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3])}var r=[null];return r.push.apply(r,t),new(c.apply(e,r))}var l=n.prototype,p=o(s(l)?l:Object.prototype),h=Function.apply.call(e,p,t);return s(h)?h:p}})},function(e,t,n){var r=n(31);r(r.S,"Object",{setPrototypeOf:n(278).set})},function(e,t,n){for(var r=n(15),o=n(114),i=n(63),a=n(40),s=n(93),l=n(142),c=n(48),u=c("iterator"),f=c("toStringTag"),d=l.Array,p={CSSRuleList:!0,CSSStyleDeclaration:!1,CSSValueList:!1,ClientRectList:!1,DOMRectList:!1,DOMStringList:!1,DOMTokenList:!0,DataTransferItemList:!1,FileList:!1,HTMLAllCollection:!1,HTMLCollection:!1,HTMLFormElement:!1,HTMLSelectElement:!1,MediaList:!0,MimeTypeArray:!1,NamedNodeMap:!1,NodeList:!0,PaintRequestList:!1,Plugin:!1,PluginArray:!1,SVGLengthList:!1,SVGNumberList:!1,SVGPathSegList:!1,SVGPointList:!1,SVGStringList:!1,SVGTransformList:!1,SourceBufferList:!1,StyleSheetList:!0,TextTrackCueList:!1,TextTrackList:!1,TouchList:!1},h=o(p),m=0;m=e.length?(this._t=void 0,o(1)):o(0,"keys"==t?n:"values"==t?e[n]:[n,e[n]])}),"values"),i.Arguments=i.Array,r("keys"),r("values"),r("entries")},function(e,t,n){var r=n(58).f,o=Function.prototype,i=/^\s*function ([^ (]*)/;"name"in o||n(53)&&r(o,"name",{configurable:!0,get:function(){try{return(""+this).match(i)[1]}catch(e){return""}}})},function(e,t,n){"use strict";var r=n(31),o=n(210)(!1),i=[].indexOf,a=!!i&&1/[1].indexOf(1,-0)<0;r(r.P+r.F*(a||!n(115)(i)),"Array",{indexOf:function(e){return a?i.apply(this,arguments)||0:o(this,e,arguments[1])}})},function(e,t,n){var r=n(31);r(r.S+r.F,"Object",{assign:n(279)})},function(e,t,n){var r=n(82),o=n(114);n(780)("keys",(function(){return function(e){return o(r(e))}}))},function(e,t,n){"use strict";e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var n=function(e,t){var n=e[1]||"",r=e[3];if(!r)return n;if(t&&"function"==typeof btoa){var o=(a=r,s=btoa(unescape(encodeURIComponent(JSON.stringify(a)))),l="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(s),"/*# ".concat(l," */")),i=r.sources.map((function(e){return"/*# sourceURL=".concat(r.sourceRoot||"").concat(e," */")}));return[n].concat(i).concat([o]).join("\n")}var a,s,l;return[n].join("\n")}(t,e);return t[2]?"@media ".concat(t[2]," {").concat(n,"}"):n})).join("")},t.i=function(e,n,r){"string"==typeof e&&(e=[[null,e,""]]);var o={};if(r)for(var i=0;i]+>|\t|)+|(?:\n)))/gm,c="Could not find the language '{}', did you forget to load/include a language module?",u={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0},f="of and for in not or if then".split(" ");function d(e){return e.replace(/&/g,"&").replace(//g,">")}function p(e){return e.nodeName.toLowerCase()}function h(e){return a.test(e)}function m(e){var t,n={},r=Array.prototype.slice.call(arguments,1);for(t in e)n[t]=e[t];return r.forEach((function(e){for(t in e)n[t]=e[t]})),n}function g(e){var t=[];return function e(n,r){for(var o=n.firstChild;o;o=o.nextSibling)3===o.nodeType?r+=o.nodeValue.length:1===o.nodeType&&(t.push({event:"start",offset:r,node:o}),r=e(o,r),p(o).match(/br|hr|img|input/)||t.push({event:"stop",offset:r,node:o}));return r}(e,0),t}function v(e){return e.variants&&!e.cached_variants&&(e.cached_variants=e.variants.map((function(t){return m(e,{variants:null},t)}))),e.cached_variants?e.cached_variants:function e(t){return!!t&&(t.endsWithParent||e(t.starts))}(e)?[m(e,{starts:e.starts?m(e.starts):null})]:Object.isFrozen(e)?[m(e)]:[e]}function y(e,t){return t?Number(t):(n=e,-1!=f.indexOf(n.toLowerCase())?0:1);var n}function b(e){function t(e){return e&&e.source||e}function r(n,r){return new RegExp(t(n),"m"+(e.case_insensitive?"i":"")+(r?"g":""))}function o(e){var n,o,i={},a=[],s={},l=1;function c(e,t){i[l]=e,a.push([e,t]),l+=function(e){return new RegExp(e.toString()+"|").exec("").length-1}(t)+1}for(var u=0;u0&&(i+=n),i+="(";l.length>0;){var c=r.exec(l);if(null==c){i+=l;break}i+=l.substring(0,c.index),l=l.substring(c.index+c[0].length),"\\"==c[0][0]&&c[1]?i+="\\"+String(Number(c[1])+s):(i+=c[0],"("==c[0]&&o++)}i+=")"}return i}(f,"|"),!0),s.lastIndex=0,s.exec=function(t){var r;if(0===a.length)return null;n.lastIndex=s.lastIndex;var o=n.exec(t);if(!o)return null;for(var l=0;l')+t+(n?"":"")}function f(){S+=null!=k.subLanguage?function(){var e="string"==typeof k.subLanguage;if(e&&!r[k.subLanguage])return d(E);var t=e?_(k.subLanguage,E,!0,M[k.subLanguage]):w(E,k.subLanguage.length?k.subLanguage:void 0);return k.relevance>0&&(T+=t.relevance),e&&(M[k.subLanguage]=t.top),l(t.language,t.value,!1,!0)}():function(){var e,t,n,r;if(!k.keywords)return d(E);for(r="",t=0,k.lexemesRe.lastIndex=0,n=k.lexemesRe.exec(E);n;)r+=d(E.substring(t,n.index)),(e=s(k,n))?(T+=e[1],r+=l(e[0],d(n[0]))):r+=d(n[0]),t=k.lexemesRe.lastIndex,n=k.lexemesRe.exec(E);return r+d(E.substr(t))}(),E=""}function p(e){S+=e.className?l(e.className,"",!0):"",k=Object.create(e,{parent:{value:k}})}function h(e){var t=e[0],n=e.rule;return n&&n.endSameAsBegin&&(n.endRe=function(e){return new RegExp(e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),"m")}(t)),n.skip?E+=t:(n.excludeBegin&&(E+=t),f(),n.returnBegin||n.excludeBegin||(E=t)),p(n),n.returnBegin?0:t.length}function m(e){var t=e[0],n=a.substr(e.index),r=function e(t,n){if(function(e,t){var n=e&&e.exec(t);return n&&0===n.index}(t.endRe,n)){for(;t.endsParent&&t.parent;)t=t.parent;return t}if(t.endsWithParent)return e(t.parent,n)}(k,n);if(r){var o=k;o.skip?E+=t:(o.returnEnd||o.excludeEnd||(E+=t),f(),o.excludeEnd&&(E=t));do{k.className&&(S+=""),k.skip||k.subLanguage||(T+=k.relevance),k=k.parent}while(k!==r.parent);return r.starts&&(r.endSameAsBegin&&(r.starts.endRe=r.endRe),p(r.starts)),o.returnEnd?0:t.length}}var g={};function v(e,t){var r=t&&t[0];if(E+=e,null==r)return f(),0;if("begin"==g.type&&"end"==t.type&&g.index==t.index&&""===r)return E+=a.slice(t.index,t.index+1),1;if(g=t,"begin"===t.type)return h(t);if("illegal"===t.type&&!n)throw new Error('Illegal lexeme "'+r+'" for mode "'+(k.className||"")+'"');if("end"===t.type){var o=m(t);if(null!=o)return o}return E+=r,r.length}var y=O(e);if(!y)throw console.error(c.replace("{}",e)),new Error('Unknown language: "'+e+'"');b(y);var x,k=o||y,M={},S="";for(x=k;x!==y;x=x.parent)x.className&&(S=l(x.className,"",!0)+S);var E="",T=0;try{for(var L,D,C=0;k.terminators.lastIndex=C,L=k.terminators.exec(a);)D=v(a.substring(C,L.index),L),C=L.index+D;for(v(a.substr(C)),x=k;x.parent;x=x.parent)x.className&&(S+="");return{relevance:T,value:S,illegal:!1,language:e,top:k}}catch(t){if(t.message&&-1!==t.message.indexOf("Illegal"))return{illegal:!0,relevance:0,value:d(a)};if(i)return{relevance:0,value:d(a),language:e,top:k,errorRaised:t};throw t}}function w(e,t){t=t||u.languages||n(r);var o={relevance:0,value:d(e)},i=o;return t.filter(O).filter(E).forEach((function(t){var n=_(t,e,!1);n.language=t,n.relevance>i.relevance&&(i=n),n.relevance>o.relevance&&(i=o,o=n)})),i.language&&(o.second_best=i),o}function x(e){return u.tabReplace||u.useBR?e.replace(l,(function(e,t){return u.useBR&&"\n"===e?"
":u.tabReplace?t.replace(/\t/g,u.tabReplace):""})):e}function k(e){var n,r,i,a,l,f=function(e){var t,n,r,o,i=e.className+" ";if(i+=e.parentNode?e.parentNode.className:"",n=s.exec(i)){var a=O(n[1]);return a||(console.warn(c.replace("{}",n[1])),console.warn("Falling back to no-highlight mode for this block.",e)),a?n[1]:"no-highlight"}for(t=0,r=(i=i.split(/\s+/)).length;t/g,"\n"):n=e,l=n.textContent,i=f?_(f,l,!0):w(l),(r=g(n)).length&&((a=document.createElement("div")).innerHTML=i.value,i.value=function(e,n,r){var o=0,i="",a=[];function s(){return e.length&&n.length?e[0].offset!==n[0].offset?e[0].offset"}function c(e){i+=""}function u(e){("start"===e.event?l:c)(e.node)}for(;e.length||n.length;){var f=s();if(i+=d(r.substring(o,f[0].offset)),o=f[0].offset,f===e){a.reverse().forEach(c);do{u(f.splice(0,1)[0]),f=s()}while(f===e&&f.length&&f[0].offset===o);a.reverse().forEach(l)}else"start"===f[0].event?a.push(f[0].node):a.pop(),u(f.splice(0,1)[0])}return i+d(r.substr(o))}(r,g(a),l)),i.value=x(i.value),e.innerHTML=i.value,e.className=function(e,t,n){var r=t?o[t]:n,i=[e.trim()];return e.match(/\bhljs\b/)||i.push("hljs"),-1===e.indexOf(r)&&i.push(r),i.join(" ").trim()}(e.className,f,i.language),e.result={language:i.language,re:i.relevance},i.second_best&&(e.second_best={language:i.second_best.language,re:i.second_best.relevance}))}function M(){if(!M.called){M.called=!0;var e=document.querySelectorAll("pre code");t.forEach.call(e,k)}}var S={disableAutodetect:!0};function O(e){return e=(e||"").toLowerCase(),r[e]||r[o[e]]}function E(e){var t=O(e);return t&&!t.disableAutodetect}return e.highlight=_,e.highlightAuto=w,e.fixMarkup=x,e.highlightBlock=k,e.configure=function(e){u=m(u,e)},e.initHighlighting=M,e.initHighlightingOnLoad=function(){window.addEventListener("DOMContentLoaded",M,!1),window.addEventListener("load",M,!1)},e.registerLanguage=function(t,n){var a;try{a=n(e)}catch(e){if(console.error("Language definition for '{}' could not be registered.".replace("{}",t)),!i)throw e;console.error(e),a=S}r[t]=a,a.rawDefinition=n.bind(null,e),a.aliases&&a.aliases.forEach((function(e){o[e]=t}))},e.listLanguages=function(){return n(r)},e.getLanguage=O,e.requireLanguage=function(e){var t=O(e);if(t)return t;throw new Error("The '{}' language is required, but not loaded.".replace("{}",e))},e.autoDetection=E,e.inherit=m,e.debugMode=function(){i=!1},e.IDENT_RE="[a-zA-Z]\\w*",e.UNDERSCORE_IDENT_RE="[a-zA-Z_]\\w*",e.NUMBER_RE="\\b\\d+(\\.\\d+)?",e.C_NUMBER_RE="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BINARY_NUMBER_RE="\\b(0b[01]+)",e.RE_STARTERS_RE="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BACKSLASH_ESCAPE={begin:"\\\\[\\s\\S]",relevance:0},e.APOS_STRING_MODE={className:"string",begin:"'",end:"'",illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},e.QUOTE_STRING_MODE={className:"string",begin:'"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},e.PHRASAL_WORDS_MODE={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},e.COMMENT=function(t,n,r){var o=e.inherit({className:"comment",begin:t,end:n,contains:[]},r||{});return o.contains.push(e.PHRASAL_WORDS_MODE),o.contains.push({className:"doctag",begin:"(?:TODO|FIXME|NOTE|BUG|XXX):",relevance:0}),o},e.C_LINE_COMMENT_MODE=e.COMMENT("//","$"),e.C_BLOCK_COMMENT_MODE=e.COMMENT("/\\*","\\*/"),e.HASH_COMMENT_MODE=e.COMMENT("#","$"),e.NUMBER_MODE={className:"number",begin:e.NUMBER_RE,relevance:0},e.C_NUMBER_MODE={className:"number",begin:e.C_NUMBER_RE,relevance:0},e.BINARY_NUMBER_MODE={className:"number",begin:e.BINARY_NUMBER_RE,relevance:0},e.CSS_NUMBER_MODE={className:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},e.REGEXP_MODE={className:"regexp",begin:/\//,end:/\/[gimuy]*/,illegal:/\n/,contains:[e.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[e.BACKSLASH_ESCAPE]}]},e.TITLE_MODE={className:"title",begin:e.IDENT_RE,relevance:0},e.UNDERSCORE_TITLE_MODE={className:"title",begin:e.UNDERSCORE_IDENT_RE,relevance:0},e.METHOD_GUARD={begin:"\\.\\s*"+e.UNDERSCORE_IDENT_RE,relevance:0},[e.BACKSLASH_ESCAPE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.PHRASAL_WORDS_MODE,e.COMMENT,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.HASH_COMMENT_MODE,e.NUMBER_MODE,e.C_NUMBER_MODE,e.BINARY_NUMBER_MODE,e.CSS_NUMBER_MODE,e.REGEXP_MODE,e.TITLE_MODE,e.UNDERSCORE_TITLE_MODE,e.METHOD_GUARD].forEach((function(e){!function e(t){Object.freeze(t);var n="function"==typeof t;return Object.getOwnPropertyNames(t).forEach((function(r){!t.hasOwnProperty(r)||null===t[r]||"object"!=typeof t[r]&&"function"!=typeof t[r]||n&&("caller"===r||"callee"===r||"arguments"===r)||Object.isFrozen(t[r])||e(t[r])})),t}(e)})),e},i="object"==typeof window&&window||"object"==typeof self&&self,t.nodeType?i&&(i.hljs=o({}),void 0===(r=function(){return i.hljs}.apply(t,[]))||(e.exports=r)):o(t)},function(e,t,n){"use strict";var r=n(31),o=n(98)(0),i=n(115)([].forEach,!0);r(r.P+r.F*!i,"Array",{forEach:function(e){return o(this,e,arguments[1])}})},function(e,t,n){"use strict";var r=n(31),o=n(98)(1);r(r.P+r.F*!n(115)([].map,!0),"Array",{map:function(e){return o(this,e,arguments[1])}})},function(e,t,n){var r=n(40),o=n(92),i=n(93),a=n(63),s=n(95),l=function(e,t,n){var c,u,f,d,p=e&l.F,h=e&l.G,m=e&l.S,g=e&l.P,v=e&l.B,y=h?r:m?r[t]||(r[t]={}):(r[t]||{}).prototype,b=h?o:o[t]||(o[t]={}),_=b.prototype||(b.prototype={});for(c in h&&(n=t),n)f=((u=!p&&y&&void 0!==y[c])?y:n)[c],d=v&&u?s(f,r):g&&"function"==typeof f?s(Function.call,f):f,y&&a(y,c,f,e&l.U),b[c]!=f&&i(b,c,d),g&&_[c]!=f&&(_[c]=f)};r.core=o,l.F=1,l.G=2,l.S=4,l.P=8,l.B=16,l.W=32,l.U=64,l.R=128,e.exports=l},function(e,t,n){"use strict";!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE){0;try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}}}(),e.exports=n(764)},function(e,t,n){var r=n(318);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(902);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t,n){"use strict";var r=n(280)(!0);n(209)(String,"String",(function(e){this._t=String(e),this._i=0}),(function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1})}))},function(e,t,n){var r=n(828);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(31);r(r.S,"Array",{isArray:n(213)})},function(e,t,n){var r=n(1075);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t,n){"use strict";var r=n(95),o=n(31),i=n(82),a=n(281),s=n(282),l=n(81),c=n(283),u=n(284);o(o.S+o.F*!n(214)((function(e){Array.from(e)})),"Array",{from:function(e){var t,n,o,f,d=i(e),p="function"==typeof this?this:Array,h=arguments.length,m=h>1?arguments[1]:void 0,g=void 0!==m,v=0,y=u(d);if(g&&(m=r(m,h>2?arguments[2]:void 0,2)),null==y||p==Array&&s(y))for(n=new p(t=l(d.length));t>v;v++)c(n,v,g?m(d[v],v):d[v]);else for(f=y.call(d),n=new p;!(o=f.next()).done;v++)c(n,v,g?a(f,m,[o.value,v],!0):o.value);return n.length=v,n}})},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){var r=n(930);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t){e.exports=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}},function(e,t){ +/*! +Copyright (C) 2013-2015 by Andrea Giammarchi - @WebReflection + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ +!function(e){"use strict";function t(){return f.createDocumentFragment()}function n(e){return f.createElement(e)}function r(e,t){if(!e)throw new Error("Failed to construct "+t+": 1 argument required, but only 0 present.")}function o(e){if(1===e.length)return i(e[0]);for(var n=t(),r=R.call(e),o=0;o3?s(a):null,b=String(a.key),_=String(a.char),w=a.location,x=a.keyCode||(a.keyCode=b)&&b.charCodeAt(0)||0,k=a.charCode||(a.charCode=_)&&_.charCodeAt(0)||0,M=a.bubbles,S=a.cancelable,O=a.repeat,E=a.locale,T=a.view||e;if(a.which||(a.which=a.keyCode),"initKeyEvent"in d)d.initKeyEvent(t,M,S,T,p,m,h,g,x,k);else if(0f;)void 0!==(n=l(r,t=c[f++]))&&s(u,t,n);return u}})},function(e,t,n){"use strict";var r,o,i,a,s=n(139),l=n(40),c=n(95),u=n(171),f=n(31),d=n(51),p=n(96),h=n(175),m=n(176),g=n(222),v=n(289).set,y=n(795)(),b=n(290),_=n(796),w=n(797),x=n(291),k=l.TypeError,M=l.process,S=M&&M.versions,O=S&&S.v8||"",E=l.Promise,T="process"==u(M),L=function(){},D=o=b.f,C=!!function(){try{var e=E.resolve(1),t=(e.constructor={})[n(48)("species")]=function(e){e(L,L)};return(T||"function"==typeof PromiseRejectionEvent)&&e.then(L)instanceof t&&0!==O.indexOf("6.6")&&-1===w.indexOf("Chrome/66")}catch(e){}}(),P=function(e){var t;return!(!d(e)||"function"!=typeof(t=e.then))&&t},j=function(e,t){if(!e._n){e._n=!0;var n=e._c;y((function(){for(var r=e._v,o=1==e._s,i=0,a=function(t){var n,i,a,s=o?t.ok:t.fail,l=t.resolve,c=t.reject,u=t.domain;try{s?(o||(2==e._h&&I(e),e._h=1),!0===s?n=r:(u&&u.enter(),n=s(r),u&&(u.exit(),a=!0)),n===t.promise?c(k("Promise-chain cycle")):(i=P(n))?i.call(n,l,c):l(n)):c(r)}catch(e){u&&!a&&u.exit(),c(e)}};n.length>i;)a(n[i++]);e._c=[],e._n=!1,t&&!e._h&&Y(e)}))}},Y=function(e){v.call(l,(function(){var t,n,r,o=e._v,i=A(e);if(i&&(t=_((function(){T?M.emit("unhandledRejection",o,e):(n=l.onunhandledrejection)?n({promise:e,reason:o}):(r=l.console)&&r.error&&r.error("Unhandled promise rejection",o)})),e._h=T||A(e)?2:1),e._a=void 0,i&&t.e)throw t.v}))},A=function(e){return 1!==e._h&&0===(e._a||e._c).length},I=function(e){v.call(l,(function(){var t;T?M.emit("rejectionHandled",e):(t=l.onrejectionhandled)&&t({promise:e,reason:e._v})}))},R=function(e){var t=this;t._d||(t._d=!0,(t=t._w||t)._v=e,t._s=2,t._a||(t._a=t._c.slice()),j(t,!0))},$=function(e){var t,n=this;if(!n._d){n._d=!0,n=n._w||n;try{if(n===e)throw k("Promise can't be resolved itself");(t=P(e))?y((function(){var r={_w:n,_d:!1};try{t.call(e,c($,r,1),c(R,r,1))}catch(e){R.call(r,e)}})):(n._v=e,n._s=1,j(n,!1))}catch(e){R.call({_w:n,_d:!1},e)}}};C||(E=function(e){h(this,E,"Promise","_h"),p(e),r.call(this);try{e(c($,this,1),c(R,this,1))}catch(e){R.call(this,e)}},(r=function(e){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1}).prototype=n(174)(E.prototype,{then:function(e,t){var n=D(g(this,E));return n.ok="function"!=typeof e||e,n.fail="function"==typeof t&&t,n.domain=T?M.domain:void 0,this._c.push(n),this._a&&this._a.push(n),this._s&&j(this,!1),n.promise},catch:function(e){return this.then(void 0,e)}}),i=function(){var e=new r;this.promise=e,this.resolve=c($,e,1),this.reject=c(R,e,1)},b.f=D=function(e){return e===E||e===a?new i(e):o(e)}),f(f.G+f.W+f.F*!C,{Promise:E}),n(143)(E,"Promise"),n(221)("Promise"),a=n(92).Promise,f(f.S+f.F*!C,"Promise",{reject:function(e){var t=D(this);return(0,t.reject)(e),t.promise}}),f(f.S+f.F*(s||!C),"Promise",{resolve:function(e){return x(s&&this===a?E:this,e)}}),f(f.S+f.F*!(C&&n(214)((function(e){E.all(e).catch(L)}))),"Promise",{all:function(e){var t=this,n=D(t),r=n.resolve,o=n.reject,i=_((function(){var n=[],i=0,a=1;m(e,!1,(function(e){var s=i++,l=!1;n.push(void 0),a++,t.resolve(e).then((function(e){l||(l=!0,n[s]=e,--a||r(n))}),o)})),--a||r(n)}));return i.e&&o(i.v),n.promise},race:function(e){var t=this,n=D(t),r=n.reject,o=_((function(){m(e,!1,(function(e){t.resolve(e).then(n.resolve,r)}))}));return o.e&&r(o.v),n.promise}})},function(e,t,n){var r=n(1071);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(164)("wks"),o=n(140),i=n(40).Symbol,a="function"==typeof i;(e.exports=function(e){return r[e]||(r[e]=a&&i[e]||(a?i:o)("Symbol."+e))}).store=r},function(e,t,n){var r=n(51);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t,n){var r=n(897);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t,n){"use strict";var r=n(49),o=n(82),i=n(81),a=n(167),s=n(216),l=n(172),c=Math.max,u=Math.min,f=Math.floor,d=/\$([$&`']|\d\d?|<[^>]*>)/g,p=/\$([$&`']|\d\d?)/g;n(173)("replace",2,(function(e,t,n,h){return[function(r,o){var i=e(this),a=null==r?void 0:r[t];return void 0!==a?a.call(r,i,o):n.call(String(i),r,o)},function(e,t){var o=h(n,e,this,t);if(o.done)return o.value;var f=r(e),d=String(this),p="function"==typeof t;p||(t=String(t));var g=f.global;if(g){var v=f.unicode;f.lastIndex=0}for(var y=[];;){var b=l(f,d);if(null===b)break;if(y.push(b),!g)break;""===String(b[0])&&(f.lastIndex=s(d,i(f.lastIndex),v))}for(var _,w="",x=0,k=0;k=x&&(w+=d.slice(x,S)+D,x=S+M.length)}return w+d.slice(x)}];function m(e,t,r,i,a,s){var l=r+e.length,c=i.length,u=p;return void 0!==a&&(a=o(a),u=d),n.call(s,u,(function(n,o){var s;switch(o.charAt(0)){case"$":return"$";case"&":return e;case"`":return t.slice(0,r);case"'":return t.slice(l);case"<":s=a[o.slice(1,-1)];break;default:var u=+o;if(0===u)return n;if(u>c){var d=f(u/10);return 0===d?n:d<=c?void 0===i[d-1]?o.charAt(1):i[d-1]+o.charAt(1):n}s=i[u-1]}return void 0===s?"":s}))}}))},function(e,t,n){e.exports=!n(54)((function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}))},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t){var n=e.exports={version:"2.6.11"};"number"==typeof __e&&(__e=n)},function(e,t){e.exports=''},function(e,t,n){"use strict";t.__esModule=!0;var r,o=n(199),i=(r=o)&&r.__esModule?r:{default:r};t.default=i.default||function(e){for(var t=1;t1||"".split(/.?/)[p]?function(e,t){var o=String(this);if(void 0===e&&0===t)return[];if(!r(e))return n.call(o,e,t);for(var i,a,s,l=[],u=(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.unicode?"u":"")+(e.sticky?"y":""),f=0,h=void 0===t?4294967295:t>>>0,m=new RegExp(e.source,u+"g");(i=c.call(m,o))&&!((a=m.lastIndex)>f&&(l.push(o.slice(f,i.index)),i[p]>1&&i.index=h));)m.lastIndex===i.index&&m.lastIndex++;return f===o[p]?!s&&m.test("")||l.push(""):l.push(o.slice(f)),l[p]>h?l.slice(0,h):l}:"0".split(void 0,0)[p]?function(e,t){return void 0===e&&0===t?[]:n.call(this,e,t)}:n,[function(n,r){var o=e(this),i=null==n?void 0:n[t];return void 0!==i?i.call(n,o,r):m.call(String(o),n,r)},function(e,t){var r=u(m,e,this,t,m!==n);if(r.done)return r.value;var c=o(e),d=String(this),p=i(c,RegExp),g=c.unicode,v=(c.ignoreCase?"i":"")+(c.multiline?"m":"")+(c.unicode?"u":"")+(h?"y":"g"),y=new p(h?c:"^(?:"+c.source+")",v),b=void 0===t?4294967295:t>>>0;if(0===b)return[];if(0===d.length)return null===l(y,d)?[d]:[];for(var _=0,w=0,x=[];w=0;--o){var i=this.tryEntries[o],a=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),w(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var o=r.arg;w(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:k(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}(e.exports);try{regeneratorRuntime=r}catch(e){Function("r","regeneratorRuntime = r")(r)}},function(e,t,n){var r=n(240)("wks"),o=n(186),i=n(60).Symbol,a="function"==typeof i;(e.exports=function(e){return r[e]||(r[e]=a&&i[e]||(a?i:o)("Symbol."+e))}).store=r},function(e,t,n){var r=n(316);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(798);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t,n){"use strict";e.exports=function(e){return o.test("number"==typeof e?r(e):e.charAt(0))};var r=String.fromCharCode,o=/\s/},function(e,t){e.exports=''},function(e,t,n){"use strict";t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t,n){"use strict";t.__esModule=!0;var r,o=n(940),i=(r=o)&&r.__esModule?r:{default:r};t.default=function(){function e(e,t){for(var n=0;n0?o(r(e),9007199254740991):0}},function(e,t,n){var r=n(113);e.exports=function(e){return Object(r(e))}},function(e,t){e.exports=function(){for(var e={},t=0;t'},function(e,t,n){var r=n(928);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(1101);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(1102);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(103);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t,n){e.exports=!n(130)((function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}))},function(e,t,n){var r=n(987);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t){var n=e.exports={version:"2.6.11"};"number"==typeof __e&&(__e=n)},function(e,t,n){var r=n(58),o=n(141);e.exports=n(53)?function(e,t,n){return r.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){var r=n(166),o=n(113);e.exports=function(e){return r(o(e))}},function(e,t,n){var r=n(96);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){var r=n(95),o=n(166),i=n(82),a=n(81),s=n(782);e.exports=function(e,t){var n=1==e,l=2==e,c=3==e,u=4==e,f=6==e,d=5==e||f,p=t||s;return function(t,s,h){for(var m,g,v=i(t),y=o(v),b=r(s,h,3),_=a(y.length),w=0,x=n?p(t,_):l?p(t,0):void 0;_>w;w++)if((d||w in y)&&(g=b(m=y[w],w,v),e))if(n)x[w]=g;else if(g)switch(e){case 3:return!0;case 5:return m;case 6:return w;case 2:x.push(m)}else if(u)return!1;return f?-1:c||u?u:x}}},function(e,t,n){"use strict";var r=n(31),o=n(788);r(r.P+r.F*!n(115)([].reduce,!0),"Array",{reduce:function(e){return o(this,e,arguments.length,arguments[1],!1)}})},function(e,t,n){var r=n(31);r(r.P,"Function",{bind:n(276)})},function(e,t,n){"use strict";var r=n(31),o=n(210)(!0);r(r.P,"Array",{includes:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0)}}),n(138)("includes")},function(e,t,n){var r=n(89),o=n(454),i=n(236),a=Object.defineProperty;t.f=n(90)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),o)try{return a(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t){e.exports=''},function(e,t,n){(function(t){function n(e){try{if(!t.localStorage)return!1}catch(e){return!1}var n=t.localStorage[e];return null!=n&&"true"===String(n).toLowerCase()}e.exports=function(e,t){if(n("noDeprecation"))return e;var r=!1;return function(){if(!r){if(n("throwDeprecation"))throw new Error(t);n("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}}}).call(this,n(97))},function(e,t){e.exports=''},function(e,t,n){e.exports={default:n(938),__esModule:!0}},function(e,t,n){"use strict";t.__esModule=!0;var r=a(n(960)),o=a(n(964)),i=a(n(459));function a(e){return e&&e.__esModule?e:{default:e}}t.default=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":(0,i.default)(t)));e.prototype=(0,o.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(r.default?(0,r.default)(e,t):e.__proto__=t)}},function(e,t){e.exports=function(e,t,n){var r;return function(){if(!t)return e.apply(this,arguments);var o=this,i=arguments,a=n&&!r;return clearTimeout(r),r=setTimeout((function(){if(r=null,!a)return e.apply(o,i)}),t),a?e.apply(this,arguments):void 0}}},function(e,t,n){var r=n(871);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t,n){"use strict";e.exports=function(e,t,n,r,o,i,a,s){if(!e){var l;if(void 0===t)l=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,o,i,a,s],u=0;(l=new Error(t.replace(/%s/g,(function(){return c[u++]})))).name="Invariant Violation"}throw l.framesToPop=1,l}}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t){e.exports=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e}},function(e,t,n){var r=n(269),o=n(212);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t,n){"use strict";var r=n(54);e.exports=function(e,t){return!!e&&r((function(){t?e.call(null,(function(){}),1):e.call(null)}))}},function(e,t,n){"use strict";var r=n(31),o=n(285);r(r.P+r.F*n(286)("includes"),"String",{includes:function(e){return!!~o(this,e,"includes").indexOf(e,arguments.length>1?arguments[1]:void 0)}})},function(e,t,n){"use strict";var r=n(227),o="function"==typeof Symbol&&"symbol"==typeof Symbol("foo"),i=Object.prototype.toString,a=Array.prototype.concat,s=Object.defineProperty,l=s&&function(){var e={};try{for(var t in s(e,"x",{enumerable:!1,value:e}),e)return!1;return e.x===e}catch(e){return!1}}(),c=function(e,t,n,r){var o;(!(t in e)||"function"==typeof(o=r)&&"[object Function]"===i.call(o)&&r())&&(l?s(e,t,{configurable:!0,enumerable:!1,value:n,writable:!0}):e[t]=n)},u=function(e,t){var n=arguments.length>2?arguments[2]:{},i=r(t);o&&(i=a.call(i,Object.getOwnPropertySymbols(t)));for(var s=0;sdocument.F=Object<\/script>"),e.close(),l=e.F;r--;)delete l.prototype[i[r]];return l()};e.exports=Object.create||function(e,t){var n;return null!==e?(s.prototype=r(e),n=new s,s.prototype=null,n[a]=e):n=l(),void 0===t?n:o(n,t)}},function(e,t,n){var r=n(144),o=n(141),i=n(94),a=n(165),s=n(80),l=n(266),c=Object.getOwnPropertyDescriptor;t.f=n(53)?c:function(e,t){if(e=i(e),t=a(t,!0),l)try{return c(e,t)}catch(e){}if(s(e,t))return o(!r.f.call(e,t),e[t])}},function(e,t,n){var r=n(51);e.exports=function(e,t){if(!r(e)||e._t!==t)throw TypeError("Incompatible receiver, "+t+" required!");return e}},function(e,t,n){"use strict";var r=TypeError,o=Object.getOwnPropertyDescriptor;if(o)try{o({},"")}catch(e){o=null}var i=function(){throw new r},a=o?function(){try{return i}catch(e){try{return o(arguments,"callee").get}catch(e){return i}}}():i,s=n(128)(),l=Object.getPrototypeOf||function(e){return e.__proto__},c=void 0,u="undefined"==typeof Uint8Array?void 0:l(Uint8Array),f={"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?void 0:ArrayBuffer,"%ArrayBufferPrototype%":"undefined"==typeof ArrayBuffer?void 0:ArrayBuffer.prototype,"%ArrayIteratorPrototype%":s?l([][Symbol.iterator]()):void 0,"%ArrayPrototype%":Array.prototype,"%ArrayProto_entries%":Array.prototype.entries,"%ArrayProto_forEach%":Array.prototype.forEach,"%ArrayProto_keys%":Array.prototype.keys,"%ArrayProto_values%":Array.prototype.values,"%AsyncFromSyncIteratorPrototype%":void 0,"%AsyncFunction%":void 0,"%AsyncFunctionPrototype%":void 0,"%AsyncGenerator%":void 0,"%AsyncGeneratorFunction%":void 0,"%AsyncGeneratorPrototype%":void 0,"%AsyncIteratorPrototype%":c&&s&&Symbol.asyncIterator?c[Symbol.asyncIterator]():void 0,"%Atomics%":"undefined"==typeof Atomics?void 0:Atomics,"%Boolean%":Boolean,"%BooleanPrototype%":Boolean.prototype,"%DataView%":"undefined"==typeof DataView?void 0:DataView,"%DataViewPrototype%":"undefined"==typeof DataView?void 0:DataView.prototype,"%Date%":Date,"%DatePrototype%":Date.prototype,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%ErrorPrototype%":Error.prototype,"%eval%":eval,"%EvalError%":EvalError,"%EvalErrorPrototype%":EvalError.prototype,"%Float32Array%":"undefined"==typeof Float32Array?void 0:Float32Array,"%Float32ArrayPrototype%":"undefined"==typeof Float32Array?void 0:Float32Array.prototype,"%Float64Array%":"undefined"==typeof Float64Array?void 0:Float64Array,"%Float64ArrayPrototype%":"undefined"==typeof Float64Array?void 0:Float64Array.prototype,"%Function%":Function,"%FunctionPrototype%":Function.prototype,"%Generator%":void 0,"%GeneratorFunction%":void 0,"%GeneratorPrototype%":void 0,"%Int8Array%":"undefined"==typeof Int8Array?void 0:Int8Array,"%Int8ArrayPrototype%":"undefined"==typeof Int8Array?void 0:Int8Array.prototype,"%Int16Array%":"undefined"==typeof Int16Array?void 0:Int16Array,"%Int16ArrayPrototype%":"undefined"==typeof Int16Array?void 0:Int8Array.prototype,"%Int32Array%":"undefined"==typeof Int32Array?void 0:Int32Array,"%Int32ArrayPrototype%":"undefined"==typeof Int32Array?void 0:Int32Array.prototype,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":s?l(l([][Symbol.iterator]())):void 0,"%JSON%":"object"==typeof JSON?JSON:void 0,"%JSONParse%":"object"==typeof JSON?JSON.parse:void 0,"%Map%":"undefined"==typeof Map?void 0:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&s?l((new Map)[Symbol.iterator]()):void 0,"%MapPrototype%":"undefined"==typeof Map?void 0:Map.prototype,"%Math%":Math,"%Number%":Number,"%NumberPrototype%":Number.prototype,"%Object%":Object,"%ObjectPrototype%":Object.prototype,"%ObjProto_toString%":Object.prototype.toString,"%ObjProto_valueOf%":Object.prototype.valueOf,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?void 0:Promise,"%PromisePrototype%":"undefined"==typeof Promise?void 0:Promise.prototype,"%PromiseProto_then%":"undefined"==typeof Promise?void 0:Promise.prototype.then,"%Promise_all%":"undefined"==typeof Promise?void 0:Promise.all,"%Promise_reject%":"undefined"==typeof Promise?void 0:Promise.reject,"%Promise_resolve%":"undefined"==typeof Promise?void 0:Promise.resolve,"%Proxy%":"undefined"==typeof Proxy?void 0:Proxy,"%RangeError%":RangeError,"%RangeErrorPrototype%":RangeError.prototype,"%ReferenceError%":ReferenceError,"%ReferenceErrorPrototype%":ReferenceError.prototype,"%Reflect%":"undefined"==typeof Reflect?void 0:Reflect,"%RegExp%":RegExp,"%RegExpPrototype%":RegExp.prototype,"%Set%":"undefined"==typeof Set?void 0:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&s?l((new Set)[Symbol.iterator]()):void 0,"%SetPrototype%":"undefined"==typeof Set?void 0:Set.prototype,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?void 0:SharedArrayBuffer,"%SharedArrayBufferPrototype%":"undefined"==typeof SharedArrayBuffer?void 0:SharedArrayBuffer.prototype,"%String%":String,"%StringIteratorPrototype%":s?l(""[Symbol.iterator]()):void 0,"%StringPrototype%":String.prototype,"%Symbol%":s?Symbol:void 0,"%SymbolPrototype%":s?Symbol.prototype:void 0,"%SyntaxError%":SyntaxError,"%SyntaxErrorPrototype%":SyntaxError.prototype,"%ThrowTypeError%":a,"%TypedArray%":u,"%TypedArrayPrototype%":u?u.prototype:void 0,"%TypeError%":r,"%TypeErrorPrototype%":r.prototype,"%Uint8Array%":"undefined"==typeof Uint8Array?void 0:Uint8Array,"%Uint8ArrayPrototype%":"undefined"==typeof Uint8Array?void 0:Uint8Array.prototype,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?void 0:Uint8ClampedArray,"%Uint8ClampedArrayPrototype%":"undefined"==typeof Uint8ClampedArray?void 0:Uint8ClampedArray.prototype,"%Uint16Array%":"undefined"==typeof Uint16Array?void 0:Uint16Array,"%Uint16ArrayPrototype%":"undefined"==typeof Uint16Array?void 0:Uint16Array.prototype,"%Uint32Array%":"undefined"==typeof Uint32Array?void 0:Uint32Array,"%Uint32ArrayPrototype%":"undefined"==typeof Uint32Array?void 0:Uint32Array.prototype,"%URIError%":URIError,"%URIErrorPrototype%":URIError.prototype,"%WeakMap%":"undefined"==typeof WeakMap?void 0:WeakMap,"%WeakMapPrototype%":"undefined"==typeof WeakMap?void 0:WeakMap.prototype,"%WeakSet%":"undefined"==typeof WeakSet?void 0:WeakSet,"%WeakSetPrototype%":"undefined"==typeof WeakSet?void 0:WeakSet.prototype},d=n(229).call(Function.call,String.prototype.replace),p=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,h=/\\(\\)?/g,m=function(e){var t=[];return d(e,p,(function(e,n,r,o){t[t.length]=r?d(o,h,"$1"):n||e})),t},g=function(e,t){if(!(e in f))throw new SyntaxError("intrinsic "+e+" does not exist!");if(void 0===f[e]&&!t)throw new r("intrinsic "+e+" exists, but is not available. Please file an issue!");return f[e]};e.exports=function(e,t){if("string"!=typeof e||0===e.length)throw new TypeError("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new TypeError('"allowMissing" argument must be a boolean');for(var n=m(e),i=g("%"+(n.length>0?n[0]:"")+"%",t),a=1;a=n.length){var s=o(i,n[a]);if(!t&&!(n[a]in i))throw new r("base intrinsic for "+e+" exists, but the property is not available.");i=s?s.get||s.value:i[n[a]]}else i=i[n[a]];return i}},function(e,t,n){"use strict";(function(t){var r=t.Symbol,o=n(230);e.exports=function(){return"function"==typeof r&&("function"==typeof Symbol&&("symbol"==typeof r("foo")&&("symbol"==typeof Symbol("bar")&&o())))}}).call(this,n(97))},function(e,t,n){"use strict";var r=n(31),o=n(98)(5),i=!0;"find"in[]&&Array(1).find((function(){i=!1})),r(r.P+r.F*i,"Array",{find:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0)}}),n(138)("find")},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t){(t=e.exports=function(e){return e.replace(/^\s*|\s*$/g,"")}).left=function(e){return e.replace(/^\s*/,"")},t.right=function(e){return e.replace(/\s*$/,"")}},function(e,t){e.exports=''},function(e,t){e.exports=''},function(e,t,n){"use strict";var r=n(227),o=n(294),i=n(803),a=n(806),s=n(807),l=n(299),c=n(809),u=n(810),f=n(127),d=n(147),p=n(815),h=n(818),m=n(819),g=n(822),v=n(825),y=d("Date.prototype.getTime"),b=Object.getPrototypeOf,_=d("Object.prototype.toString"),w=f("%Set%",!0),x=d("Map.prototype.has",!0),k=d("Map.prototype.get",!0),M=d("Map.prototype.size",!0),S=d("Set.prototype.add",!0),O=d("Set.prototype.delete",!0),E=d("Set.prototype.has",!0),T=d("Set.prototype.size",!0);function L(e,t,n,r){for(var o,i=h(e);(o=i.next())&&!o.done;)if(Y(t,o.value,n,r))return O(e,o.value),!0;return!1}function D(e){return void 0===e?null:"object"!=typeof e?"symbol"!=typeof e&&("string"!=typeof e&&"number"!=typeof e||+e==+e):void 0}function C(e,t,n,r,o,i){var a=D(n);if(null!=a)return a;var s=k(t,a),l=v({},o,{strict:!1});return!(void 0===s&&!x(t,a)||!Y(r,s,l,i))&&(!x(e,a)&&Y(r,s,l,i))}function P(e,t,n){var r=D(n);return null!=r?r:E(t,r)&&!E(e,r)}function j(e,t,n,r,o,i){for(var a,s,l=h(e);(a=l.next())&&!a.done;)if(Y(n,s=a.value,o,i)&&Y(r,k(t,s),o,i))return O(e,s),!0;return!1}function Y(e,t,n,f){var d=n||{};if(d.strict?i(e,t):e===t)return!0;if(u(e)!==u(t))return!1;if(!e||!t||"object"!=typeof e&&"object"!=typeof t)return d.strict?i(e,t):e==t;var m,O=f.has(e),D=f.has(t);if(O&&D){if(f.get(e)===f.get(t))return!0}else m={};return O||f.set(e,m),D||f.set(t,m),function(e,t,n,i){var u,f;if(typeof e!=typeof t)return!1;if(null==e||null==t)return!1;if(_(e)!==_(t))return!1;if(o(e)!==o(t))return!1;var d=l(e),m=l(t);if(d!==m)return!1;var O=e instanceof Error,D=t instanceof Error;if(O!==D)return!1;if((O||D)&&(e.name!==t.name||e.message!==t.message))return!1;var I=a(e),R=a(t);if(I!==R)return!1;if((I||R)&&(e.source!==t.source||s(e)!==s(t)))return!1;var $=c(e),H=c(t);if($!==H)return!1;if(($||H)&&y(e)!==y(t))return!1;if(n.strict&&b&&b(e)!==b(t))return!1;if(g(e)!==g(t))return!1;var N=A(e),z=A(t);if(N!==z)return!1;if(N||z){if(e.length!==t.length)return!1;for(u=0;u=0;u--)if(F[u]!=B[u])return!1;for(u=F.length-1;u>=0;u--)if(f=F[u],!Y(e[f],t[f],n,i))return!1;var U=p(e),W=p(t);if(U!==W)return!1;if("Set"===U||"Set"===W)return function(e,t,n,r){if(T(e)!==T(t))return!1;var o,i,a,s=h(e),l=h(t);for(;(o=s.next())&&!o.done;)if(o.value&&"object"==typeof o.value)a||(a=new w),S(a,o.value);else if(!E(t,o.value)){if(n.strict)return!1;if(!P(e,t,o.value))return!1;a||(a=new w),S(a,o.value)}if(a){for(;(i=l.next())&&!i.done;)if(i.value&&"object"==typeof i.value){if(!L(a,i.value,n.strict,r))return!1}else if(!n.strict&&!E(e,i.value)&&!L(a,i.value,n.strict,r))return!1;return 0===T(a)}return!0}(e,t,n,i);if("Map"===U)return function(e,t,n,r){if(M(e)!==M(t))return!1;var o,i,a,s,l,c,u=h(e),f=h(t);for(;(o=u.next())&&!o.done;)if(s=o.value[0],l=o.value[1],s&&"object"==typeof s)a||(a=new w),S(a,s);else if(void 0===(c=k(t,s))&&!x(t,s)||!Y(l,c,n,r)){if(n.strict)return!1;if(!C(e,t,s,l,n,r))return!1;a||(a=new w),S(a,s)}if(a){for(;(i=f.next())&&!i.done;)if(s=i.value[0],c=i.value[1],s&&"object"==typeof s){if(!j(a,e,s,c,n,r))return!1}else if(!(n.strict||e.has(s)&&Y(k(e,s),c,n,r)||j(a,e,s,c,v({},n,{strict:!1}),r)))return!1;return 0===T(a)}return!0}(e,t,n,i);return!0}(e,t,d,f)}function A(e){return!(!e||"object"!=typeof e||"number"!=typeof e.length)&&("function"==typeof e.copy&&"function"==typeof e.slice&&(!(e.length>0&&"number"!=typeof e[0])&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))))}e.exports=function(e,t,n){return Y(e,t,n,m())}},function(e,t,n){var r=n(872);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(876);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(1073);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(48)("unscopables"),o=Array.prototype;null==o[r]&&n(93)(o,r,{}),e.exports=function(e){o[r][e]=!0}},function(e,t){e.exports=!1},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t){e.exports={}},function(e,t,n){var r=n(58).f,o=n(80),i=n(48)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t})}},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){var r=n(140)("meta"),o=n(51),i=n(80),a=n(58).f,s=0,l=Object.isExtensible||function(){return!0},c=!n(54)((function(){return l(Object.preventExtensions({}))})),u=function(e){a(e,r,{value:{i:"O"+ ++s,w:{}}})},f=e.exports={KEY:r,NEED:!1,fastKey:function(e,t){if(!o(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!i(e,r)){if(!l(e))return"F";if(!t)return"E";u(e)}return e[r].i},getWeak:function(e,t){if(!i(e,r)){if(!l(e))return!0;if(!t)return!1;u(e)}return e[r].w},onFreeze:function(e){return c&&f.NEED&&l(e)&&!i(e,r)&&u(e),e}}},function(e,t,n){var r=n(269),o=n(212).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return r(e,o)}},function(e,t,n){"use strict";var r=n(127),o=n(228),i=o(r("String.prototype.indexOf"));e.exports=function(e,t){var n=r(e,!!t);return"function"==typeof n&&i(e,".prototype.")?o(n):n}},function(e,t,n){"use strict";n(317)("trim",(function(e){return function(){return e(this,3)}}))},function(e,t,n){var r=n(184);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t,n){var r=n(455),o=n(241);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t){e.exports=!0},function(e,t,n){var r=n(237);e.exports=function(e){return Object(r(e))}},function(e,t){e.exports={}},function(e,t,n){"use strict";var r=Object.prototype.hasOwnProperty;function o(e,t){return e===t?0!==e||0!==t||1/e==1/t:e!=e&&t!=t}e.exports=function(e,t){if(o(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(var a=0;a'},function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return v}));var r=n(260),o=(n(0),n(1)),i=n.n(o),a=n(255);function s(e,t){for(var n=0;n needs a DOM element to compute boundaries. The child you passed is neither a DOM element (e.g.
) nor does it use the innerRef prop.\n\nSee https://goo.gl/LrBNgw for more info.")}(n,e._ref),e._handleScroll=e._handleScroll.bind(e),e.scrollableAncestor=e._findScrollableAncestor(),e.scrollEventListenerUnsubscribe=Object(r.a)(e.scrollableAncestor,"scroll",e._handleScroll,{passive:!0}),e.resizeEventListenerUnsubscribe=Object(r.a)(window,"resize",e._handleScroll,{passive:!0}),e._handleScroll(null)})))}},{key:"componentDidUpdate",value:function(){var e=this;n.getWindow()&&this.scrollableAncestor&&(this.cancelOnNextTick||(this.cancelOnNextTick=m((function(){e.cancelOnNextTick=null,e._handleScroll(null)}))))}},{key:"componentWillUnmount",value:function(){n.getWindow()&&(this.scrollEventListenerUnsubscribe&&this.scrollEventListenerUnsubscribe(),this.resizeEventListenerUnsubscribe&&this.resizeEventListenerUnsubscribe(),this.cancelOnNextTick&&this.cancelOnNextTick())}},{key:"_findScrollableAncestor",value:function(){var t=this.props,n=t.horizontal,r=t.scrollableAncestor;if(r)return function(t){return"window"===t?e.window:t}(r);for(var o=this._ref;o.parentNode;){if((o=o.parentNode)===document.body)return window;var i=window.getComputedStyle(o),a=(n?i.getPropertyValue("overflow-x"):i.getPropertyValue("overflow-y"))||i.getPropertyValue("overflow");if("auto"===a||"scroll"===a)return o}return window}},{key:"_handleScroll",value:function(e){if(this._ref){var t=this._getBounds(),n=function(e){return e.viewportBottom-e.viewportTop==0?"invisible":e.viewportTop<=e.waypointTop&&e.waypointTop<=e.viewportBottom||e.viewportTop<=e.waypointBottom&&e.waypointBottom<=e.viewportBottom||e.waypointTop<=e.viewportTop&&e.viewportBottom<=e.waypointBottom?"inside":e.viewportBottom0?r:n)(e)}},function(e,t,n){var r=n(31),o=n(273)(!1);r(r.S,"Object",{values:function(e){return o(e)}})},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){"use strict";var r=n(49);e.exports=function(){var e=r(this),t="";return e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.unicode&&(t+="u"),e.sticky&&(t+="y"),t}},function(e,t,n){var r=n(112),o=n(48)("toStringTag"),i="Arguments"==r(function(){return arguments}());e.exports=function(e){var t,n,a;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),o))?n:i?r(t):"Object"==(a=r(t))&&"function"==typeof t.callee?"Arguments":a}},function(e,t,n){"use strict";var r=n(171),o=RegExp.prototype.exec;e.exports=function(e,t){var n=e.exec;if("function"==typeof n){var i=n.call(e,t);if("object"!=typeof i)throw new TypeError("RegExp exec method returned something other than an Object or null");return i}if("RegExp"!==r(e))throw new TypeError("RegExp#exec called on incompatible receiver");return o.call(e,t)}},function(e,t,n){"use strict";n(785);var r=n(63),o=n(93),i=n(54),a=n(113),s=n(48),l=n(217),c=s("species"),u=!i((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$")})),f=function(){var e=/(?:)/,t=e.exec;e.exec=function(){return t.apply(this,arguments)};var n="ab".split(e);return 2===n.length&&"a"===n[0]&&"b"===n[1]}();e.exports=function(e,t,n){var d=s(e),p=!i((function(){var t={};return t[d]=function(){return 7},7!=""[e](t)})),h=p?!i((function(){var t=!1,n=/a/;return n.exec=function(){return t=!0,null},"split"===e&&(n.constructor={},n.constructor[c]=function(){return n}),n[d](""),!t})):void 0;if(!p||!h||"replace"===e&&!u||"split"===e&&!f){var m=/./[d],g=n(a,d,""[e],(function(e,t,n,r,o){return t.exec===l?p&&!o?{done:!0,value:m.call(t,n,r)}:{done:!0,value:e.call(n,t,r)}:{done:!1}})),v=g[0],y=g[1];r(String.prototype,e,v),o(RegExp.prototype,d,2==t?function(e,t){return y.call(e,this,t)}:function(e){return y.call(e,this)})}}},function(e,t,n){var r=n(63);e.exports=function(e,t,n){for(var o in t)r(e,o,t[o],n);return e}},function(e,t){e.exports=function(e,t,n,r){if(!(e instanceof t)||void 0!==r&&r in e)throw TypeError(n+": incorrect invocation!");return e}},function(e,t,n){var r=n(95),o=n(281),i=n(282),a=n(49),s=n(81),l=n(284),c={},u={};(t=e.exports=function(e,t,n,f,d){var p,h,m,g,v=d?function(){return e}:l(e),y=r(n,f,t?2:1),b=0;if("function"!=typeof v)throw TypeError(e+" is not iterable!");if(i(v)){for(p=s(e.length);p>b;b++)if((g=t?y(a(h=e[b])[0],h[1]):y(e[b]))===c||g===u)return g}else for(m=v.call(e);!(h=m.next()).done;)if((g=o(m,y,h.value,t))===c||g===u)return g}).BREAK=c,t.RETURN=u},function(e,t,n){var r=n(31),o=n(273)(!0);r(r.S,"Object",{entries:function(e){return o(e)}})},function(e,t,n){"use strict";var r=n(288),o=n(126);e.exports=n(218)("Set",(function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}}),{add:function(e){return r.def(o(this,"Set"),e=0===e?0:e,e)}},r)},function(e,t,n){"use strict";var r=n(49),o=n(81),i=n(216),a=n(172);n(173)("match",1,(function(e,t,n,s){return[function(n){var r=e(this),o=null==n?void 0:n[t];return void 0!==o?o.call(n,r):new RegExp(n)[t](String(r))},function(e){var t=s(n,e,this);if(t.done)return t.value;var l=r(e),c=String(this);if(!l.global)return a(l,c);var u=l.unicode;l.lastIndex=0;for(var f,d=[],p=0;null!==(f=a(l,c));){var h=String(f[0]);d[p]=h,""===h&&(l.lastIndex=i(c,o(l.lastIndex),u)),p++}return 0===p?null:d}]}))},function(e,t,n){"use strict";n(224)("link",(function(e){return function(t){return e(this,"a","href",t)}}))},function(e,t,n){"use strict";var r=n(31),o=n(96),i=n(82),a=n(54),s=[].sort,l=[1,2,3];r(r.P+r.F*(a((function(){l.sort(void 0)}))||!a((function(){l.sort(null)}))||!n(115)(s)),"Array",{sort:function(e){return void 0===e?s.call(i(this)):s.call(i(this),o(e))}})},function(e,t,n){"use strict";var r=n(31),o=n(98)(3);r(r.P+r.F*!n(115)([].some,!0),"Array",{some:function(e){return o(this,e,arguments[1])}})},function(e,t,n){"use strict";var r=n(40),o=n(80),i=n(112),a=n(219),s=n(165),l=n(54),c=n(146).f,u=n(125).f,f=n(58).f,d=n(317).trim,p=r.Number,h=p,m=p.prototype,g="Number"==i(n(124)(m)),v="trim"in String.prototype,y=function(e){var t=s(e,!1);if("string"==typeof t&&t.length>2){var n,r,o,i=(t=v?t.trim():d(t,3)).charCodeAt(0);if(43===i||45===i){if(88===(n=t.charCodeAt(2))||120===n)return NaN}else if(48===i){switch(t.charCodeAt(1)){case 66:case 98:r=2,o=49;break;case 79:case 111:r=8,o=55;break;default:return+t}for(var a,l=t.slice(2),c=0,u=l.length;co)return NaN;return parseInt(l,r)}}return+t};if(!p(" 0o1")||!p("0b1")||p("+0x1")){p=function(e){var t=arguments.length<1?0:e,n=this;return n instanceof p&&(g?l((function(){m.valueOf.call(n)})):"Number"!=i(n))?a(new h(y(t)),n,p):y(t)};for(var b,_=n(53)?c(h):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger".split(","),w=0;_.length>w;w++)o(h,b=_[w])&&!o(p,b)&&f(p,b,u(h,b));p.prototype=m,m.constructor=p,n(63)(r,"Number",p)}},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){var r=n(102).f,o=n(119),i=n(65)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t})}},function(e,t,n){"use strict";e.exports=function(e){var t="string"==typeof e?e.charCodeAt(0):e;return t>=48&&t<=57}},function(e,t,n){"use strict";e.exports=s;var r=n(1022),o=r.CONTINUE,i=r.SKIP,a=r.EXIT;function s(e,t,n,o){"function"==typeof t&&"function"!=typeof n&&(o=n,n=t,t=null),r(e,t,(function(e,t){var r=t[t.length-1],o=r?r.children.indexOf(e):null;return n(e,o,r)}),o)}s.CONTINUE=o,s.SKIP=i,s.EXIT=a},function(e,t){e.exports=''},function(e,t){e.exports=''},function(e,t){e.exports=''},function(e,t){e.exports=''},function(e,t){e.exports=''},function(e,t){e.exports=''},function(e,t,n){var r=n(799);"string"==typeof(r=r.__esModule?r.default:r)&&(r=[[e.i,r,""]]);var o={insert:"head",singleton:!1};n(21)(r,o);r.locals&&(e.exports=r.locals)},function(e,t,n){"use strict";var r=n(308).forEach,o=n(829),i=n(830),a=n(831),s=n(832),l=n(833),c=n(309),u=n(834),f=n(836),d=n(837),p=n(838);function h(e){return Array.isArray(e)||void 0!==e.length}function m(e){if(Array.isArray(e))return e;var t=[];return r(e,(function(e){t.push(e)})),t}function g(e){return e&&1===e.nodeType}function v(e,t,n){var r=e[t];return null==r&&void 0!==n?n:r}e.exports=function(e){var t;if((e=e||{}).idHandler)t={get:function(t){return e.idHandler.get(t,!0)},set:e.idHandler.set};else{var n=a(),y=s({idGenerator:n,stateHandler:f});t=y}var b=e.reporter;b||(b=l(!1===b));var _=v(e,"batchProcessor",u({reporter:b})),w={};w.callOnAdd=!!v(e,"callOnAdd",!0),w.debug=!!v(e,"debug",!1);var x,k=i(t),M=o({stateHandler:f}),S=v(e,"strategy","object"),O=v(e,"important",!1),E={reporter:b,batchProcessor:_,stateHandler:f,idHandler:t,important:O};if("scroll"===S&&(c.isLegacyOpera()?(b.warn("Scroll strategy is not supported on legacy Opera. Changing to object strategy."),S="object"):c.isIE(9)&&(b.warn("Scroll strategy is not supported on IE9. Changing to object strategy."),S="object")),"scroll"===S)x=p(E);else{if("object"!==S)throw new Error("Invalid strategy name: "+S);x=d(E)}var T={};return{listenTo:function(e,n,o){function i(e){var t=k.get(e);r(t,(function(t){t(e)}))}function a(e,t,n){k.add(t,n),e&&n(t)}if(o||(o=n,n=e,e={}),!n)throw new Error("At least one element required.");if(!o)throw new Error("Listener required.");if(g(n))n=[n];else{if(!h(n))return b.error("Invalid arguments. Must be a DOM element or a collection of DOM elements.");n=m(n)}var s=0,l=v(e,"callOnAdd",w.callOnAdd),c=v(e,"onReady",(function(){})),u=v(e,"debug",w.debug);r(n,(function(e){f.getState(e)||(f.initState(e),t.set(e));var d=t.get(e);if(u&&b.log("Attaching listener to element",d,e),!M.isDetectable(e))return u&&b.log(d,"Not detectable."),M.isBusy(e)?(u&&b.log(d,"System busy making it detectable"),a(l,e,o),T[d]=T[d]||[],void T[d].push((function(){++s===n.length&&c()}))):(u&&b.log(d,"Making detectable..."),M.markBusy(e,!0),x.makeDetectable({debug:u,important:O},e,(function(e){if(u&&b.log(d,"onElementDetectable"),f.getState(e)){M.markAsDetectable(e),M.markBusy(e,!1),x.addListener(e,i),a(l,e,o);var t=f.getState(e);if(t&&t.startSize){var p=e.offsetWidth,h=e.offsetHeight;t.startSize.width===p&&t.startSize.height===h||i(e)}T[d]&&r(T[d],(function(e){e()}))}else u&&b.log(d,"Element uninstalled before being detectable.");delete T[d],++s===n.length&&c()})));u&&b.log(d,"Already detecable, adding listener."),a(l,e,o),s++})),s===n.length&&c()},removeListener:k.removeListener,removeAllListeners:k.removeAllListeners,uninstall:function(e){if(!e)return b.error("At least one element is required.");if(g(e))e=[e];else{if(!h(e))return b.error("Invalid arguments. Must be a DOM element or a collection of DOM elements.");e=m(e)}r(e,(function(e){k.removeAllListeners(e),x.uninstall(e),f.cleanState(e)}))},initDocument:function(e){x.initDocument&&x.initDocument(e)}}}},function(e,t,n){e.exports={default:n(931),__esModule:!0}},function(e,t,n){"use strict";(function(e){function r(t,n){var r,o,i,a=void 0!==(r=void 0!==n?n:"undefined"!=typeof window?window:"undefined"!=typeof self?self:e).document&&r.document.attachEvent;if(!a){var s=(i=r.requestAnimationFrame||r.mozRequestAnimationFrame||r.webkitRequestAnimationFrame||function(e){return r.setTimeout(e,20)},function(e){return i(e)}),l=(o=r.cancelAnimationFrame||r.mozCancelAnimationFrame||r.webkitCancelAnimationFrame||r.clearTimeout,function(e){return o(e)}),c=function(e){var t=e.__resizeTriggers__,n=t.firstElementChild,r=t.lastElementChild,o=n.firstElementChild;r.scrollLeft=r.scrollWidth,r.scrollTop=r.scrollHeight,o.style.width=n.offsetWidth+1+"px",o.style.height=n.offsetHeight+1+"px",n.scrollLeft=n.scrollWidth,n.scrollTop=n.scrollHeight},u=function(e){if(!(e.target.className&&"function"==typeof e.target.className.indexOf&&e.target.className.indexOf("contract-trigger")<0&&e.target.className.indexOf("expand-trigger")<0)){var t=this;c(this),this.__resizeRAF__&&l(this.__resizeRAF__),this.__resizeRAF__=s((function(){(function(e){return e.offsetWidth!=e.__resizeLast__.width||e.offsetHeight!=e.__resizeLast__.height})(t)&&(t.__resizeLast__.width=t.offsetWidth,t.__resizeLast__.height=t.offsetHeight,t.__resizeListeners__.forEach((function(n){n.call(t,e)})))}))}},f=!1,d="",p="animationstart",h="Webkit Moz O ms".split(" "),m="webkitAnimationStart animationstart oAnimationStart MSAnimationStart".split(" "),g=r.document.createElement("fakeelement");if(void 0!==g.style.animationName&&(f=!0),!1===f)for(var v=0;v div, .contract-trigger:before { content: " "; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; z-index: -1; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }',r=e.head||e.getElementsByTagName("head")[0],o=e.createElement("style");o.id="detectElementResize",o.type="text/css",null!=t&&o.setAttribute("nonce",t),o.styleSheet?o.styleSheet.cssText=n:o.appendChild(e.createTextNode(n)),r.appendChild(o)}}(o),e.__resizeLast__={},e.__resizeListeners__=[],(e.__resizeTriggers__=o.createElement("div")).className="resize-triggers",e.__resizeTriggers__.innerHTML='
',e.appendChild(e.__resizeTriggers__),c(e),e.addEventListener("scroll",u,!0),p&&(e.__resizeTriggers__.__animationListener__=function(t){t.animationName==y&&c(e)},e.__resizeTriggers__.addEventListener(p,e.__resizeTriggers__.__animationListener__))}e.__resizeListeners__.push(n)}},removeResizeListener:function(e,t){if(a)e.detachEvent("onresize",t);else if(e.__resizeListeners__.splice(e.__resizeListeners__.indexOf(t),1),!e.__resizeListeners__.length){e.removeEventListener("scroll",u,!0),e.__resizeTriggers__.__animationListener__&&(e.__resizeTriggers__.removeEventListener(p,e.__resizeTriggers__.__animationListener__),e.__resizeTriggers__.__animationListener__=null);try{e.__resizeTriggers__=!e.removeChild(e.__resizeTriggers__)}catch(e){}}}}}n.d(t,"a",(function(){return r}))}).call(this,n(97))},function(e,t){e.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t){function n(e,t){for(var n=0;nu;)if((s=l[u++])!=s)return!0}else for(;c>u;u++)if((e||u in l)&&l[u]===n)return e||u||0;return!e&&-1}}},function(e,t,n){var r=n(164)("keys"),o=n(140);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t,n){var r=n(112);e.exports=Array.isArray||function(e){return"Array"==r(e)}},function(e,t,n){var r=n(48)("iterator"),o=!1;try{var i=[7][r]();i.return=function(){o=!0},Array.from(i,(function(){throw 2}))}catch(e){}e.exports=function(e,t){if(!t&&!o)return!1;var n=!1;try{var i=[7],a=i[r]();a.next=function(){return{done:n=!0}},i[r]=function(){return a},e(i)}catch(e){}return n}},function(e,t,n){var r=n(51),o=n(112),i=n(48)("match");e.exports=function(e){var t;return r(e)&&(void 0!==(t=e[i])?!!t:"RegExp"==o(e))}},function(e,t,n){"use strict";var r=n(280)(!0);e.exports=function(e,t,n){return t+(n?r(e,t).length:1)}},function(e,t,n){"use strict";var r,o,i=n(170),a=RegExp.prototype.exec,s=String.prototype.replace,l=a,c=(r=/a/,o=/b*/g,a.call(r,"a"),a.call(o,"a"),0!==r.lastIndex||0!==o.lastIndex),u=void 0!==/()??/.exec("")[1];(c||u)&&(l=function(e){var t,n,r,o,l=this;return u&&(n=new RegExp("^"+l.source+"$(?!\\s)",i.call(l))),c&&(t=l.lastIndex),r=a.call(l,e),c&&r&&(l.lastIndex=l.global?r.index+r[0].length:t),u&&r&&r.length>1&&s.call(r[0],n,(function(){for(o=1;o0?arguments[0]:void 0)}}),{get:function(e){var t=r.getEntry(o(this,"Map"),e);return t&&t.v},set:function(e,t){return r.def(o(this,"Map"),0===e?0:e,t)}},r,!0)},function(e,t,n){"use strict";var r=n(40),o=n(58),i=n(53),a=n(48)("species");e.exports=function(e){var t=r[e];i&&t&&!t[a]&&o.f(t,a,{configurable:!0,get:function(){return this}})}},function(e,t,n){var r=n(49),o=n(96),i=n(48)("species");e.exports=function(e,t){var n,a=r(e).constructor;return void 0===a||null==(n=r(a)[i])?t:o(n)}},function(e,t,n){var r=n(20),o=n(27),i=n(22);(t=r(!1)).i(o,"",!0),t.i(i),t.push([e.i,"@media (hover: hover), (-moz-touch-enabled: 0), (-ms-high-contrast: none), (-ms-high-contrast: active) {.close_ab8:hover {\n color: #ff008c;\n color: var(--ring-link-hover-color);\n }}\n\n.alert_84a {\n position: relative;\n\n display: flex;\n align-items: baseline;\n\n box-sizing: border-box;\n min-height: 40px;\n margin: 8px auto;\n padding: 0 16px;\n\n transition:\n transform 300ms ease-out,\n margin-bottom 300ms ease-out,\n opacity 300ms ease-out;\n white-space: nowrap;\n pointer-events: auto;\n\n border-radius: 3px;\n\n border-radius: var(--ring-border-radius);\n background-color: #111314;\n background-color: var(--ring-message-background-color);\n box-shadow: 0 2px 16px rgba(0, 42, 76, 0.15);\n box-shadow: 0 2px 16px var(--ring-popup-shadow-color);\n\n font-size: 13px;\n\n font-size: var(--ring-font-size);\n line-height: 40px;\n}\n\n.alertInline_b5a {\n margin: 8px;\n}\n\n.error_4c9 {\n word-wrap: break-word;\n\n color: #c22731;\n\n color: var(--ring-error-color);\n}\n\n.icon_1a3 {\n margin-right: 8px;\n}\n\n.caption_b0a {\n overflow: hidden;\n\n max-width: calc(100% - 40px);\n\n margin: 12px 40px 12px 0;\n\n white-space: normal;\n\n color: #fff;\n\n color: var(--ring-dark-text-color);\n\n line-height: 20px\n}\n\n.caption_b0a .ring-link,\n \n .caption_b0a .link_66c {\n color: #008eff;\n color: var(--ring-main-color);\n }\n\n.badge_2a3 {\n margin-left: 8px;\n\n vertical-align: baseline;\n}\n\n.loader_a6d {\n top: 2px;\n\n margin-right: 8px;\n}\n\n.close_ab8 {\n position: absolute;\n top: 2px;\n right: 0;\n\n margin: 4px;\n padding: 8px;\n\n cursor: pointer;\n\n color: #888;\n\n color: var(--ring-dark-secondary-color);\n border: none;\n background: transparent;\n\n font-size: 0;\n line-height: 0\n}\n\n.close_ab8:focus {\n color: #ff008c;\n color: var(--ring-link-hover-color);\n }\n\n@-webkit-keyframes show_a16 {\n from {\n transform: translateY(100%);\n\n opacity: 0;\n }\n\n to {\n transform: translateY(0);\n\n opacity: 1;\n }\n}\n\n@keyframes show_a16 {\n from {\n transform: translateY(100%);\n\n opacity: 0;\n }\n\n to {\n transform: translateY(0);\n\n opacity: 1;\n }\n}\n\n@-webkit-keyframes shaking_5d8 {\n 10%,\n 90% {\n transform: translateX(-1px);\n }\n\n 20%,\n 80% {\n transform: translateX(2px);\n }\n\n 30%,\n 50%,\n 70% {\n transform: translateX(-4px);\n }\n\n 40%,\n 60% {\n transform: translateX(4px);\n }\n}\n\n@keyframes shaking_5d8 {\n 10%,\n 90% {\n transform: translateX(-1px);\n }\n\n 20%,\n 80% {\n transform: translateX(2px);\n }\n\n 30%,\n 50%,\n 70% {\n transform: translateX(-4px);\n }\n\n 40%,\n 60% {\n transform: translateX(4px);\n }\n}\n\n.animationOpen_93d {\n -webkit-animation-name: show_a16;\n animation-name: show_a16;\n -webkit-animation-duration: 300ms;\n animation-duration: 300ms;\n}\n\n.animationClosing_fdb {\n z-index: -1;\n z-index: var(--ring-invisible-element-z-index);\n\n opacity: 0;\n}\n\n.animationShaking_6b8 {\n -webkit-animation-name: shaking_5d8;\n animation-name: shaking_5d8;\n -webkit-animation-duration: 500ms;\n animation-duration: 500ms;\n}\n",""]),t.locals={unit:""+o.locals.unit,"animation-duration":"300ms","animation-easing":"ease-out",close:"close_ab8",alert:"alert_84a",alertInline:"alertInline_b5a",error:"error_4c9",icon:"icon_1a3",caption:"caption_b0a",link:"link_66c",badge:"badge_2a3",loader:"loader_a6d",animationOpen:"animationOpen_93d",show:"show_a16",animationClosing:"animationClosing_fdb",animationShaking:"animationShaking_6b8",shaking:"shaking_5d8"},e.exports=t},function(e,t,n){var r=n(31),o=n(54),i=n(113),a=/"/g,s=function(e,t,n,r){var o=String(i(e)),s="<"+t;return""!==n&&(s+=" "+n+'="'+String(r).replace(a,""")+'"'),s+">"+o+""};e.exports=function(e,t){var n={};n[e]=t(s),r(r.P+r.F*o((function(){var t=""[e]('"');return t!==t.toLowerCase()||t.split('"').length>3})),"String",n)}},function(e,t,n){var r=n(31);r(r.S,"Date",{now:function(){return(new Date).getTime()}})},function(e,t,n){var r=n(31),o=n(125).f,i=n(49);r(r.S,"Reflect",{deleteProperty:function(e,t){var n=o(i(e),t);return!(n&&!n.configurable)&&delete e[t]}})},function(e,t,n){"use strict";var r=Array.prototype.slice,o=n(293),i=Object.keys,a=i?function(e){return i(e)}:n(802),s=Object.keys;a.shim=function(){Object.keys?function(){var e=Object.keys(arguments);return e&&e.length===arguments.length}(1,2)||(Object.keys=function(e){return o(e)?s(r.call(e)):s(e)}):Object.keys=a;return Object.keys||a},e.exports=a},function(e,t,n){"use strict";var r=n(229),o=n(127)("%Function%"),i=o.apply,a=o.call;e.exports=function(){return r.apply(a,arguments)},e.exports.apply=function(){return r.apply(i,arguments)}},function(e,t,n){"use strict";var r=n(804);e.exports=Function.prototype.bind||r},function(e,t,n){"use strict";e.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),n=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(n))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var r=Object.getOwnPropertySymbols(e);if(1!==r.length||r[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var o=Object.getOwnPropertyDescriptor(e,t);if(42!==o.value||!0!==o.enumerable)return!1}return!0}},function(e,t){var n,r,o=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function s(e){if(n===setTimeout)return setTimeout(e,0);if((n===i||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:i}catch(e){n=i}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(e){r=a}}();var l,c=[],u=!1,f=-1;function d(){u&&l&&(u=!1,l.length?c=l.concat(c):f=-1,c.length&&p())}function p(){if(!u){var e=s(d);u=!0;for(var t=c.length;t;){for(l=c,c=[];++f1)for(var n=1;n button,\n.buttonToolbar_956 > .ring-button-group,\n.buttonToolbar_956 > .button_850,\n.buttonToolbar_956 > .buttonGroup_506,\n.buttonToolbar_956 > .buttonToolbar_956 {\n margin-right: 8px;\n}\n\n.buttonToolbar_956 > :last-child {\n margin-right: 0;\n}\n",""]),t.locals={unit:""+o.locals.unit,buttonToolbar:"buttonToolbar_956",button:"button_850",buttonGroup:"buttonGroup_506"},e.exports=t},function(e,t,n){"use strict";n(224)("anchor",(function(e){return function(t){return e(this,"a","name",t)}}))},function(e,t,n){var r=n(103),o=n(60).document,i=r(o)&&r(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t,n){var r=n(103);e.exports=function(e,t){if(!r(e))return e;var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t){e.exports=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){var r=n(240)("keys"),o=n(186);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t,n){var r=n(55),o=n(60),i=o["__core-js_shared__"]||(o["__core-js_shared__"]={});(e.exports=function(e,t){return i[e]||(i[e]=void 0!==t?t:{})})("versions",[]).push({version:r.version,mode:n(152)?"pure":"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){var r=n(187),o=n(185),i=n(120),a=n(236),s=n(119),l=n(454),c=Object.getOwnPropertyDescriptor;t.f=n(90)?c:function(e,t){if(e=i(e),t=a(t,!0),l)try{return c(e,t)}catch(e){}if(s(e,t))return o(!r.f.call(e,t),e[t])}},function(e,t,n){var r=n(84),o=n(55),i=n(130);e.exports=function(e,t){var n=(o.Object||{})[e]||Object[e],a={};a[e]=t(n),r(r.S+r.F*i((function(){n(1)})),"Object",a)}},function(e,t,n){var r=n(89),o=n(947),i=n(241),a=n(239)("IE_PROTO"),s=function(){},l=function(){var e,t=n(235)("iframe"),r=i.length;for(t.style.display="none",n(463).appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("\n * \n * \n * \n * ```\n *\n * @param {DOMElement} element DOM element which is the root of AngularJS application.\n * @param {Array=} modules an array of modules to load into the application.\n * Each item in the array should be the name of a predefined module or a (DI annotated)\n * function that will be invoked by the injector as a `config` block.\n * See: {@link angular.module modules}\n * @param {Object=} config an object for defining configuration options for the application. The\n * following keys are supported:\n *\n * * `strictDi` - disable automatic function annotation for the application. This is meant to\n * assist in finding bugs which break minified code. Defaults to `false`.\n *\n * @returns {auto.$injector} Returns the newly created injector for this app.\n */\nfunction bootstrap(element, modules, config) {\n if (!isObject(config)) config = {};\n var defaultConfig = {\n strictDi: false\n };\n config = extend(defaultConfig, config);\n var doBootstrap = function() {\n element = jqLite(element);\n\n if (element.injector()) {\n var tag = (element[0] === window.document) ? 'document' : startingTag(element);\n // Encode angle brackets to prevent input from being sanitized to empty string #8683.\n throw ngMinErr(\n 'btstrpd',\n 'App already bootstrapped with this element \\'{0}\\'',\n tag.replace(//,'>'));\n }\n\n modules = modules || [];\n modules.unshift(['$provide', function($provide) {\n $provide.value('$rootElement', element);\n }]);\n\n if (config.debugInfoEnabled) {\n // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.\n modules.push(['$compileProvider', function($compileProvider) {\n $compileProvider.debugInfoEnabled(true);\n }]);\n }\n\n modules.unshift('ng');\n var injector = createInjector(modules, config.strictDi);\n injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',\n function bootstrapApply(scope, element, compile, injector) {\n scope.$apply(function() {\n element.data('$injector', injector);\n compile(element)(scope);\n });\n }]\n );\n return injector;\n };\n\n var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;\n var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;\n\n if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {\n config.debugInfoEnabled = true;\n window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');\n }\n\n if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {\n return doBootstrap();\n }\n\n window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');\n angular.resumeBootstrap = function(extraModules) {\n forEach(extraModules, function(module) {\n modules.push(module);\n });\n return doBootstrap();\n };\n\n if (isFunction(angular.resumeDeferredBootstrap)) {\n angular.resumeDeferredBootstrap();\n }\n}\n\n/**\n * @ngdoc function\n * @name angular.reloadWithDebugInfo\n * @module ng\n * @description\n * Use this function to reload the current application with debug information turned on.\n * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.\n *\n * See {@link ng.$compileProvider#debugInfoEnabled} for more.\n */\nfunction reloadWithDebugInfo() {\n window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;\n window.location.reload();\n}\n\n/**\n * @name angular.getTestability\n * @module ng\n * @description\n * Get the testability service for the instance of AngularJS on the given\n * element.\n * @param {DOMElement} element DOM element which is the root of AngularJS application.\n */\nfunction getTestability(rootElement) {\n var injector = angular.element(rootElement).injector();\n if (!injector) {\n throw ngMinErr('test',\n 'no injector found for element argument to getTestability');\n }\n return injector.get('$$testability');\n}\n\nvar SNAKE_CASE_REGEXP = /[A-Z]/g;\nfunction snake_case(name, separator) {\n separator = separator || '_';\n return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {\n return (pos ? separator : '') + letter.toLowerCase();\n });\n}\n\nvar bindJQueryFired = false;\nfunction bindJQuery() {\n var originalCleanData;\n\n if (bindJQueryFired) {\n return;\n }\n\n // bind to jQuery if present;\n var jqName = jq();\n jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)\n !jqName ? undefined : // use jqLite\n window[jqName]; // use jQuery specified by `ngJq`\n\n // Use jQuery if it exists with proper functionality, otherwise default to us.\n // AngularJS 1.2+ requires jQuery 1.7+ for on()/off() support.\n // AngularJS 1.3+ technically requires at least jQuery 2.1+ but it may work with older\n // versions. It will not work for sure with jQuery <1.7, though.\n if (jQuery && jQuery.fn.on) {\n jqLite = jQuery;\n extend(jQuery.fn, {\n scope: JQLitePrototype.scope,\n isolateScope: JQLitePrototype.isolateScope,\n controller: /** @type {?} */ (JQLitePrototype).controller,\n injector: JQLitePrototype.injector,\n inheritedData: JQLitePrototype.inheritedData\n });\n } else {\n jqLite = JQLite;\n }\n\n // All nodes removed from the DOM via various jqLite/jQuery APIs like .remove()\n // are passed through jqLite/jQuery.cleanData. Monkey-patch this method to fire\n // the $destroy event on all removed nodes.\n originalCleanData = jqLite.cleanData;\n jqLite.cleanData = function(elems) {\n var events;\n for (var i = 0, elem; (elem = elems[i]) != null; i++) {\n events = (jqLite._data(elem) || {}).events;\n if (events && events.$destroy) {\n jqLite(elem).triggerHandler('$destroy');\n }\n }\n originalCleanData(elems);\n };\n\n angular.element = jqLite;\n\n // Prevent double-proxying.\n bindJQueryFired = true;\n}\n\n/**\n * @ngdoc function\n * @name angular.UNSAFE_restoreLegacyJqLiteXHTMLReplacement\n * @module ng\n * @kind function\n *\n * @description\n * Restores the pre-1.8 behavior of jqLite that turns XHTML-like strings like\n * `
` to `
` instead of `
`.\n * The new behavior is a security fix. Thus, if you need to call this function, please try to adjust\n * your code for this change and remove your use of this function as soon as possible.\n\n * Note that this only patches jqLite. If you use jQuery 3.5.0 or newer, please read the\n * [jQuery 3.5 upgrade guide](https://jquery.com/upgrade-guide/3.5/) for more details\n * about the workarounds.\n */\nfunction UNSAFE_restoreLegacyJqLiteXHTMLReplacement() {\n JQLite.legacyXHTMLReplacement = true;\n}\n\n/**\n * throw error if the argument is falsy.\n */\nfunction assertArg(arg, name, reason) {\n if (!arg) {\n throw ngMinErr('areq', 'Argument \\'{0}\\' is {1}', (name || '?'), (reason || 'required'));\n }\n return arg;\n}\n\nfunction assertArgFn(arg, name, acceptArrayAnnotation) {\n if (acceptArrayAnnotation && isArray(arg)) {\n arg = arg[arg.length - 1];\n }\n\n assertArg(isFunction(arg), name, 'not a function, got ' +\n (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));\n return arg;\n}\n\n/**\n * throw error if the name given is hasOwnProperty\n * @param {String} name the name to test\n * @param {String} context the context in which the name is used, such as module or directive\n */\nfunction assertNotHasOwnProperty(name, context) {\n if (name === 'hasOwnProperty') {\n throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);\n }\n}\n\n/**\n * Return the value accessible from the object by path. Any undefined traversals are ignored\n * @param {Object} obj starting object\n * @param {String} path path to traverse\n * @param {boolean} [bindFnToScope=true]\n * @returns {Object} value as accessible by path\n */\n//TODO(misko): this function needs to be removed\nfunction getter(obj, path, bindFnToScope) {\n if (!path) return obj;\n var keys = path.split('.');\n var key;\n var lastInstance = obj;\n var len = keys.length;\n\n for (var i = 0; i < len; i++) {\n key = keys[i];\n if (obj) {\n obj = (lastInstance = obj)[key];\n }\n }\n if (!bindFnToScope && isFunction(obj)) {\n return bind(lastInstance, obj);\n }\n return obj;\n}\n\n/**\n * Return the DOM siblings between the first and last node in the given array.\n * @param {Array} array like object\n * @returns {Array} the inputted object or a jqLite collection containing the nodes\n */\nfunction getBlockNodes(nodes) {\n // TODO(perf): update `nodes` instead of creating a new object?\n var node = nodes[0];\n var endNode = nodes[nodes.length - 1];\n var blockNodes;\n\n for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {\n if (blockNodes || nodes[i] !== node) {\n if (!blockNodes) {\n blockNodes = jqLite(slice.call(nodes, 0, i));\n }\n blockNodes.push(node);\n }\n }\n\n return blockNodes || nodes;\n}\n\n\n/**\n * Creates a new object without a prototype. This object is useful for lookup without having to\n * guard against prototypically inherited properties via hasOwnProperty.\n *\n * Related micro-benchmarks:\n * - http://jsperf.com/object-create2\n * - http://jsperf.com/proto-map-lookup/2\n * - http://jsperf.com/for-in-vs-object-keys2\n *\n * @returns {Object}\n */\nfunction createMap() {\n return Object.create(null);\n}\n\nfunction stringify(value) {\n if (value == null) { // null || undefined\n return '';\n }\n switch (typeof value) {\n case 'string':\n break;\n case 'number':\n value = '' + value;\n break;\n default:\n if (hasCustomToString(value) && !isArray(value) && !isDate(value)) {\n value = value.toString();\n } else {\n value = toJson(value);\n }\n }\n\n return value;\n}\n\nvar NODE_TYPE_ELEMENT = 1;\nvar NODE_TYPE_ATTRIBUTE = 2;\nvar NODE_TYPE_TEXT = 3;\nvar NODE_TYPE_COMMENT = 8;\nvar NODE_TYPE_DOCUMENT = 9;\nvar NODE_TYPE_DOCUMENT_FRAGMENT = 11;\n\n/**\n * @ngdoc type\n * @name angular.Module\n * @module ng\n * @description\n *\n * Interface for configuring AngularJS {@link angular.module modules}.\n */\n\nfunction setupModuleLoader(window) {\n\n var $injectorMinErr = minErr('$injector');\n var ngMinErr = minErr('ng');\n\n function ensure(obj, name, factory) {\n return obj[name] || (obj[name] = factory());\n }\n\n var angular = ensure(window, 'angular', Object);\n\n // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap\n angular.$$minErr = angular.$$minErr || minErr;\n\n return ensure(angular, 'module', function() {\n /** @type {Object.} */\n var modules = {};\n\n /**\n * @ngdoc function\n * @name angular.module\n * @module ng\n * @description\n *\n * The `angular.module` is a global place for creating, registering and retrieving AngularJS\n * modules.\n * All modules (AngularJS core or 3rd party) that should be available to an application must be\n * registered using this mechanism.\n *\n * Passing one argument retrieves an existing {@link angular.Module},\n * whereas passing more than one argument creates a new {@link angular.Module}\n *\n *\n * # Module\n *\n * A module is a collection of services, directives, controllers, filters, and configuration information.\n * `angular.module` is used to configure the {@link auto.$injector $injector}.\n *\n * ```js\n * // Create a new module\n * var myModule = angular.module('myModule', []);\n *\n * // register a new service\n * myModule.value('appName', 'MyCoolApp');\n *\n * // configure existing services inside initialization blocks.\n * myModule.config(['$locationProvider', function($locationProvider) {\n * // Configure existing providers\n * $locationProvider.hashPrefix('!');\n * }]);\n * ```\n *\n * Then you can create an injector and load your modules like this:\n *\n * ```js\n * var injector = angular.injector(['ng', 'myModule'])\n * ```\n *\n * However it's more likely that you'll just use\n * {@link ng.directive:ngApp ngApp} or\n * {@link angular.bootstrap} to simplify this process for you.\n *\n * @param {!string} name The name of the module to create or retrieve.\n * @param {!Array.=} requires If specified then new module is being created. If\n * unspecified then the module is being retrieved for further configuration.\n * @param {Function=} configFn Optional configuration function for the module. Same as\n * {@link angular.Module#config Module#config()}.\n * @returns {angular.Module} new module with the {@link angular.Module} api.\n */\n return function module(name, requires, configFn) {\n\n var info = {};\n\n var assertNotHasOwnProperty = function(name, context) {\n if (name === 'hasOwnProperty') {\n throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);\n }\n };\n\n assertNotHasOwnProperty(name, 'module');\n if (requires && modules.hasOwnProperty(name)) {\n modules[name] = null;\n }\n return ensure(modules, name, function() {\n if (!requires) {\n throw $injectorMinErr('nomod', 'Module \\'{0}\\' is not available! You either misspelled ' +\n 'the module name or forgot to load it. If registering a module ensure that you ' +\n 'specify the dependencies as the second argument.', name);\n }\n\n /** @type {!Array.>} */\n var invokeQueue = [];\n\n /** @type {!Array.} */\n var configBlocks = [];\n\n /** @type {!Array.} */\n var runBlocks = [];\n\n var config = invokeLater('$injector', 'invoke', 'push', configBlocks);\n\n /** @type {angular.Module} */\n var moduleInstance = {\n // Private state\n _invokeQueue: invokeQueue,\n _configBlocks: configBlocks,\n _runBlocks: runBlocks,\n\n /**\n * @ngdoc method\n * @name angular.Module#info\n * @module ng\n *\n * @param {Object=} info Information about the module\n * @returns {Object|Module} The current info object for this module if called as a getter,\n * or `this` if called as a setter.\n *\n * @description\n * Read and write custom information about this module.\n * For example you could put the version of the module in here.\n *\n * ```js\n * angular.module('myModule', []).info({ version: '1.0.0' });\n * ```\n *\n * The version could then be read back out by accessing the module elsewhere:\n *\n * ```\n * var version = angular.module('myModule').info().version;\n * ```\n *\n * You can also retrieve this information during runtime via the\n * {@link $injector#modules `$injector.modules`} property:\n *\n * ```js\n * var version = $injector.modules['myModule'].info().version;\n * ```\n */\n info: function(value) {\n if (isDefined(value)) {\n if (!isObject(value)) throw ngMinErr('aobj', 'Argument \\'{0}\\' must be an object', 'value');\n info = value;\n return this;\n }\n return info;\n },\n\n /**\n * @ngdoc property\n * @name angular.Module#requires\n * @module ng\n *\n * @description\n * Holds the list of modules which the injector will load before the current module is\n * loaded.\n */\n requires: requires,\n\n /**\n * @ngdoc property\n * @name angular.Module#name\n * @module ng\n *\n * @description\n * Name of the module.\n */\n name: name,\n\n\n /**\n * @ngdoc method\n * @name angular.Module#provider\n * @module ng\n * @param {string} name service name\n * @param {Function} providerType Construction function for creating new instance of the\n * service.\n * @description\n * See {@link auto.$provide#provider $provide.provider()}.\n */\n provider: invokeLaterAndSetModuleName('$provide', 'provider'),\n\n /**\n * @ngdoc method\n * @name angular.Module#factory\n * @module ng\n * @param {string} name service name\n * @param {Function} providerFunction Function for creating new instance of the service.\n * @description\n * See {@link auto.$provide#factory $provide.factory()}.\n */\n factory: invokeLaterAndSetModuleName('$provide', 'factory'),\n\n /**\n * @ngdoc method\n * @name angular.Module#service\n * @module ng\n * @param {string} name service name\n * @param {Function} constructor A constructor function that will be instantiated.\n * @description\n * See {@link auto.$provide#service $provide.service()}.\n */\n service: invokeLaterAndSetModuleName('$provide', 'service'),\n\n /**\n * @ngdoc method\n * @name angular.Module#value\n * @module ng\n * @param {string} name service name\n * @param {*} object Service instance object.\n * @description\n * See {@link auto.$provide#value $provide.value()}.\n */\n value: invokeLater('$provide', 'value'),\n\n /**\n * @ngdoc method\n * @name angular.Module#constant\n * @module ng\n * @param {string} name constant name\n * @param {*} object Constant value.\n * @description\n * Because the constants are fixed, they get applied before other provide methods.\n * See {@link auto.$provide#constant $provide.constant()}.\n */\n constant: invokeLater('$provide', 'constant', 'unshift'),\n\n /**\n * @ngdoc method\n * @name angular.Module#decorator\n * @module ng\n * @param {string} name The name of the service to decorate.\n * @param {Function} decorFn This function will be invoked when the service needs to be\n * instantiated and should return the decorated service instance.\n * @description\n * See {@link auto.$provide#decorator $provide.decorator()}.\n */\n decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks),\n\n /**\n * @ngdoc method\n * @name angular.Module#animation\n * @module ng\n * @param {string} name animation name\n * @param {Function} animationFactory Factory function for creating new instance of an\n * animation.\n * @description\n *\n * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.\n *\n *\n * Defines an animation hook that can be later used with\n * {@link $animate $animate} service and directives that use this service.\n *\n * ```js\n * module.animation('.animation-name', function($inject1, $inject2) {\n * return {\n * eventName : function(element, done) {\n * //code to run the animation\n * //once complete, then run done()\n * return function cancellationFunction(element) {\n * //code to cancel the animation\n * }\n * }\n * }\n * })\n * ```\n *\n * See {@link ng.$animateProvider#register $animateProvider.register()} and\n * {@link ngAnimate ngAnimate module} for more information.\n */\n animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),\n\n /**\n * @ngdoc method\n * @name angular.Module#filter\n * @module ng\n * @param {string} name Filter name - this must be a valid AngularJS expression identifier\n * @param {Function} filterFactory Factory function for creating new instance of filter.\n * @description\n * See {@link ng.$filterProvider#register $filterProvider.register()}.\n *\n *
\n * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`.\n * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace\n * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores\n * (`myapp_subsection_filterx`).\n *
\n */\n filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),\n\n /**\n * @ngdoc method\n * @name angular.Module#controller\n * @module ng\n * @param {string|Object} name Controller name, or an object map of controllers where the\n * keys are the names and the values are the constructors.\n * @param {Function} constructor Controller constructor function.\n * @description\n * See {@link ng.$controllerProvider#register $controllerProvider.register()}.\n */\n controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),\n\n /**\n * @ngdoc method\n * @name angular.Module#directive\n * @module ng\n * @param {string|Object} name Directive name, or an object map of directives where the\n * keys are the names and the values are the factories.\n * @param {Function} directiveFactory Factory function for creating new instance of\n * directives.\n * @description\n * See {@link ng.$compileProvider#directive $compileProvider.directive()}.\n */\n directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),\n\n /**\n * @ngdoc method\n * @name angular.Module#component\n * @module ng\n * @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match ``),\n * or an object map of components where the keys are the names and the values are the component definition objects.\n * @param {Object} options Component definition object (a simplified\n * {@link ng.$compile#directive-definition-object directive definition object})\n *\n * @description\n * See {@link ng.$compileProvider#component $compileProvider.component()}.\n */\n component: invokeLaterAndSetModuleName('$compileProvider', 'component'),\n\n /**\n * @ngdoc method\n * @name angular.Module#config\n * @module ng\n * @param {Function} configFn Execute this function on module load. Useful for service\n * configuration.\n * @description\n * Use this method to configure services by injecting their\n * {@link angular.Module#provider `providers`}, e.g. for adding routes to the\n * {@link ngRoute.$routeProvider $routeProvider}.\n *\n * Note that you can only inject {@link angular.Module#provider `providers`} and\n * {@link angular.Module#constant `constants`} into this function.\n *\n * For more about how to configure services, see\n * {@link providers#provider-recipe Provider Recipe}.\n */\n config: config,\n\n /**\n * @ngdoc method\n * @name angular.Module#run\n * @module ng\n * @param {Function} initializationFn Execute this function after injector creation.\n * Useful for application initialization.\n * @description\n * Use this method to register work which should be performed when the injector is done\n * loading all modules.\n */\n run: function(block) {\n runBlocks.push(block);\n return this;\n }\n };\n\n if (configFn) {\n config(configFn);\n }\n\n return moduleInstance;\n\n /**\n * @param {string} provider\n * @param {string} method\n * @param {String=} insertMethod\n * @returns {angular.Module}\n */\n function invokeLater(provider, method, insertMethod, queue) {\n if (!queue) queue = invokeQueue;\n return function() {\n queue[insertMethod || 'push']([provider, method, arguments]);\n return moduleInstance;\n };\n }\n\n /**\n * @param {string} provider\n * @param {string} method\n * @returns {angular.Module}\n */\n function invokeLaterAndSetModuleName(provider, method, queue) {\n if (!queue) queue = invokeQueue;\n return function(recipeName, factoryFunction) {\n if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;\n queue.push([provider, method, arguments]);\n return moduleInstance;\n };\n }\n });\n };\n });\n\n}\n\n/* global shallowCopy: true */\n\n/**\n * Creates a shallow copy of an object, an array or a primitive.\n *\n * Assumes that there are no proto properties for objects.\n */\nfunction shallowCopy(src, dst) {\n if (isArray(src)) {\n dst = dst || [];\n\n for (var i = 0, ii = src.length; i < ii; i++) {\n dst[i] = src[i];\n }\n } else if (isObject(src)) {\n dst = dst || {};\n\n for (var key in src) {\n if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {\n dst[key] = src[key];\n }\n }\n }\n\n return dst || src;\n}\n\n/* exported toDebugString */\n\nfunction serializeObject(obj, maxDepth) {\n var seen = [];\n\n // There is no direct way to stringify object until reaching a specific depth\n // and a very deep object can cause a performance issue, so we copy the object\n // based on this specific depth and then stringify it.\n if (isValidObjectMaxDepth(maxDepth)) {\n // This file is also included in `angular-loader`, so `copy()` might not always be available in\n // the closure. Therefore, it is lazily retrieved as `angular.copy()` when needed.\n obj = angular.copy(obj, null, maxDepth);\n }\n return JSON.stringify(obj, function(key, val) {\n val = toJsonReplacer(key, val);\n if (isObject(val)) {\n\n if (seen.indexOf(val) >= 0) return '...';\n\n seen.push(val);\n }\n return val;\n });\n}\n\nfunction toDebugString(obj, maxDepth) {\n if (typeof obj === 'function') {\n return obj.toString().replace(/ \\{[\\s\\S]*$/, '');\n } else if (isUndefined(obj)) {\n return 'undefined';\n } else if (typeof obj !== 'string') {\n return serializeObject(obj, maxDepth);\n }\n return obj;\n}\n\n/* global angularModule: true,\n version: true,\n\n $CompileProvider,\n\n htmlAnchorDirective,\n inputDirective,\n hiddenInputBrowserCacheDirective,\n formDirective,\n scriptDirective,\n selectDirective,\n optionDirective,\n ngBindDirective,\n ngBindHtmlDirective,\n ngBindTemplateDirective,\n ngClassDirective,\n ngClassEvenDirective,\n ngClassOddDirective,\n ngCloakDirective,\n ngControllerDirective,\n ngFormDirective,\n ngHideDirective,\n ngIfDirective,\n ngIncludeDirective,\n ngIncludeFillContentDirective,\n ngInitDirective,\n ngNonBindableDirective,\n ngPluralizeDirective,\n ngRefDirective,\n ngRepeatDirective,\n ngShowDirective,\n ngStyleDirective,\n ngSwitchDirective,\n ngSwitchWhenDirective,\n ngSwitchDefaultDirective,\n ngOptionsDirective,\n ngTranscludeDirective,\n ngModelDirective,\n ngListDirective,\n ngChangeDirective,\n patternDirective,\n patternDirective,\n requiredDirective,\n requiredDirective,\n minlengthDirective,\n minlengthDirective,\n maxlengthDirective,\n maxlengthDirective,\n ngValueDirective,\n ngModelOptionsDirective,\n ngAttributeAliasDirectives,\n ngEventDirectives,\n\n $AnchorScrollProvider,\n $AnimateProvider,\n $CoreAnimateCssProvider,\n $$CoreAnimateJsProvider,\n $$CoreAnimateQueueProvider,\n $$AnimateRunnerFactoryProvider,\n $$AnimateAsyncRunFactoryProvider,\n $BrowserProvider,\n $CacheFactoryProvider,\n $ControllerProvider,\n $DateProvider,\n $DocumentProvider,\n $$IsDocumentHiddenProvider,\n $ExceptionHandlerProvider,\n $FilterProvider,\n $$ForceReflowProvider,\n $InterpolateProvider,\n $$IntervalFactoryProvider,\n $IntervalProvider,\n $HttpProvider,\n $HttpParamSerializerProvider,\n $HttpParamSerializerJQLikeProvider,\n $HttpBackendProvider,\n $xhrFactoryProvider,\n $jsonpCallbacksProvider,\n $LocationProvider,\n $LogProvider,\n $$MapProvider,\n $ParseProvider,\n $RootScopeProvider,\n $QProvider,\n $$QProvider,\n $$SanitizeUriProvider,\n $SceProvider,\n $SceDelegateProvider,\n $SnifferProvider,\n $$TaskTrackerFactoryProvider,\n $TemplateCacheProvider,\n $TemplateRequestProvider,\n $$TestabilityProvider,\n $TimeoutProvider,\n $$RAFProvider,\n $WindowProvider,\n $$jqLiteProvider,\n $$CookieReaderProvider\n*/\n\n\n/**\n * @ngdoc object\n * @name angular.version\n * @module ng\n * @description\n * An object that contains information about the current AngularJS version.\n *\n * This object has the following properties:\n *\n * - `full` – `{string}` – Full version string, such as \"0.9.18\".\n * - `major` – `{number}` – Major version number, such as \"0\".\n * - `minor` – `{number}` – Minor version number, such as \"9\".\n * - `dot` – `{number}` – Dot version number, such as \"18\".\n * - `codeName` – `{string}` – Code name of the release, such as \"jiggling-armfat\".\n */\nvar version = {\n // These placeholder strings will be replaced by grunt's `build` task.\n // They need to be double- or single-quoted.\n full: '1.8.0',\n major: 1,\n minor: 8,\n dot: 0,\n codeName: 'nested-vaccination'\n};\n\n\nfunction publishExternalAPI(angular) {\n extend(angular, {\n 'errorHandlingConfig': errorHandlingConfig,\n 'bootstrap': bootstrap,\n 'copy': copy,\n 'extend': extend,\n 'merge': merge,\n 'equals': equals,\n 'element': jqLite,\n 'forEach': forEach,\n 'injector': createInjector,\n 'noop': noop,\n 'bind': bind,\n 'toJson': toJson,\n 'fromJson': fromJson,\n 'identity': identity,\n 'isUndefined': isUndefined,\n 'isDefined': isDefined,\n 'isString': isString,\n 'isFunction': isFunction,\n 'isObject': isObject,\n 'isNumber': isNumber,\n 'isElement': isElement,\n 'isArray': isArray,\n 'version': version,\n 'isDate': isDate,\n 'callbacks': {$$counter: 0},\n 'getTestability': getTestability,\n 'reloadWithDebugInfo': reloadWithDebugInfo,\n 'UNSAFE_restoreLegacyJqLiteXHTMLReplacement': UNSAFE_restoreLegacyJqLiteXHTMLReplacement,\n '$$minErr': minErr,\n '$$csp': csp,\n '$$encodeUriSegment': encodeUriSegment,\n '$$encodeUriQuery': encodeUriQuery,\n '$$lowercase': lowercase,\n '$$stringify': stringify,\n '$$uppercase': uppercase\n });\n\n angularModule = setupModuleLoader(window);\n\n angularModule('ng', ['ngLocale'], ['$provide',\n function ngModule($provide) {\n // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.\n $provide.provider({\n $$sanitizeUri: $$SanitizeUriProvider\n });\n $provide.provider('$compile', $CompileProvider).\n directive({\n a: htmlAnchorDirective,\n input: inputDirective,\n textarea: inputDirective,\n form: formDirective,\n script: scriptDirective,\n select: selectDirective,\n option: optionDirective,\n ngBind: ngBindDirective,\n ngBindHtml: ngBindHtmlDirective,\n ngBindTemplate: ngBindTemplateDirective,\n ngClass: ngClassDirective,\n ngClassEven: ngClassEvenDirective,\n ngClassOdd: ngClassOddDirective,\n ngCloak: ngCloakDirective,\n ngController: ngControllerDirective,\n ngForm: ngFormDirective,\n ngHide: ngHideDirective,\n ngIf: ngIfDirective,\n ngInclude: ngIncludeDirective,\n ngInit: ngInitDirective,\n ngNonBindable: ngNonBindableDirective,\n ngPluralize: ngPluralizeDirective,\n ngRef: ngRefDirective,\n ngRepeat: ngRepeatDirective,\n ngShow: ngShowDirective,\n ngStyle: ngStyleDirective,\n ngSwitch: ngSwitchDirective,\n ngSwitchWhen: ngSwitchWhenDirective,\n ngSwitchDefault: ngSwitchDefaultDirective,\n ngOptions: ngOptionsDirective,\n ngTransclude: ngTranscludeDirective,\n ngModel: ngModelDirective,\n ngList: ngListDirective,\n ngChange: ngChangeDirective,\n pattern: patternDirective,\n ngPattern: patternDirective,\n required: requiredDirective,\n ngRequired: requiredDirective,\n minlength: minlengthDirective,\n ngMinlength: minlengthDirective,\n maxlength: maxlengthDirective,\n ngMaxlength: maxlengthDirective,\n ngValue: ngValueDirective,\n ngModelOptions: ngModelOptionsDirective\n }).\n directive({\n ngInclude: ngIncludeFillContentDirective,\n input: hiddenInputBrowserCacheDirective\n }).\n directive(ngAttributeAliasDirectives).\n directive(ngEventDirectives);\n $provide.provider({\n $anchorScroll: $AnchorScrollProvider,\n $animate: $AnimateProvider,\n $animateCss: $CoreAnimateCssProvider,\n $$animateJs: $$CoreAnimateJsProvider,\n $$animateQueue: $$CoreAnimateQueueProvider,\n $$AnimateRunner: $$AnimateRunnerFactoryProvider,\n $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,\n $browser: $BrowserProvider,\n $cacheFactory: $CacheFactoryProvider,\n $controller: $ControllerProvider,\n $document: $DocumentProvider,\n $$isDocumentHidden: $$IsDocumentHiddenProvider,\n $exceptionHandler: $ExceptionHandlerProvider,\n $filter: $FilterProvider,\n $$forceReflow: $$ForceReflowProvider,\n $interpolate: $InterpolateProvider,\n $interval: $IntervalProvider,\n $$intervalFactory: $$IntervalFactoryProvider,\n $http: $HttpProvider,\n $httpParamSerializer: $HttpParamSerializerProvider,\n $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,\n $httpBackend: $HttpBackendProvider,\n $xhrFactory: $xhrFactoryProvider,\n $jsonpCallbacks: $jsonpCallbacksProvider,\n $location: $LocationProvider,\n $log: $LogProvider,\n $parse: $ParseProvider,\n $rootScope: $RootScopeProvider,\n $q: $QProvider,\n $$q: $$QProvider,\n $sce: $SceProvider,\n $sceDelegate: $SceDelegateProvider,\n $sniffer: $SnifferProvider,\n $$taskTrackerFactory: $$TaskTrackerFactoryProvider,\n $templateCache: $TemplateCacheProvider,\n $templateRequest: $TemplateRequestProvider,\n $$testability: $$TestabilityProvider,\n $timeout: $TimeoutProvider,\n $window: $WindowProvider,\n $$rAF: $$RAFProvider,\n $$jqLite: $$jqLiteProvider,\n $$Map: $$MapProvider,\n $$cookieReader: $$CookieReaderProvider\n });\n }\n ])\n .info({ angularVersion: '1.8.0' });\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Any commits to this file should be reviewed with security in mind. *\n * Changes to this file can potentially create security vulnerabilities. *\n * An approval from 2 Core members with history of modifying *\n * this file is required. *\n * *\n * Does the change somehow allow for arbitrary javascript to be executed? *\n * Or allows for someone to change the prototype of built-in objects? *\n * Or gives undesired access to variables likes document or window? *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/* global\n JQLitePrototype: true,\n BOOLEAN_ATTR: true,\n ALIASED_ATTR: true\n*/\n\n//////////////////////////////////\n//JQLite\n//////////////////////////////////\n\n/**\n * @ngdoc function\n * @name angular.element\n * @module ng\n * @kind function\n *\n * @description\n * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.\n *\n * If jQuery is available, `angular.element` is an alias for the\n * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`\n * delegates to AngularJS's built-in subset of jQuery, called \"jQuery lite\" or **jqLite**.\n *\n * jqLite is a tiny, API-compatible subset of jQuery that allows\n * AngularJS to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most\n * commonly needed functionality with the goal of having a very small footprint.\n *\n * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the\n * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a\n * specific version of jQuery if multiple versions exist on the page.\n *\n *
**Note:** All element references in AngularJS are always wrapped with jQuery or\n * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.
\n *\n *
**Note:** Keep in mind that this function will not find elements\n * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`\n * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.
\n *\n * ## AngularJS's jqLite\n * jqLite provides only the following jQuery methods:\n *\n * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument\n * - [`after()`](http://api.jquery.com/after/)\n * - [`append()`](http://api.jquery.com/append/) - Contrary to jQuery, this doesn't clone elements\n * so will not work correctly when invoked on a jqLite object containing more than one DOM node\n * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters\n * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData\n * - [`children()`](http://api.jquery.com/children/) - Does not support selectors\n * - [`clone()`](http://api.jquery.com/clone/)\n * - [`contents()`](http://api.jquery.com/contents/)\n * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.\n * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.\n * - [`data()`](http://api.jquery.com/data/)\n * - [`detach()`](http://api.jquery.com/detach/)\n * - [`empty()`](http://api.jquery.com/empty/)\n * - [`eq()`](http://api.jquery.com/eq/)\n * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name\n * - [`hasClass()`](http://api.jquery.com/hasClass/)\n * - [`html()`](http://api.jquery.com/html/)\n * - [`next()`](http://api.jquery.com/next/) - Does not support selectors\n * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData\n * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter\n * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors\n * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors\n * - [`prepend()`](http://api.jquery.com/prepend/)\n * - [`prop()`](http://api.jquery.com/prop/)\n * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`)\n * - [`remove()`](http://api.jquery.com/remove/)\n * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes\n * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument\n * - [`removeData()`](http://api.jquery.com/removeData/)\n * - [`replaceWith()`](http://api.jquery.com/replaceWith/)\n * - [`text()`](http://api.jquery.com/text/)\n * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument\n * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers\n * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter\n * - [`val()`](http://api.jquery.com/val/)\n * - [`wrap()`](http://api.jquery.com/wrap/)\n *\n * jqLite also provides a method restoring pre-1.8 insecure treatment of XHTML-like tags.\n * This legacy behavior turns input like `
` to `
`\n * instead of `
` like version 1.8 & newer do. To restore it, invoke:\n * ```js\n * angular.UNSAFE_restoreLegacyJqLiteXHTMLReplacement();\n * ```\n * Note that this only patches jqLite. If you use jQuery 3.5.0 or newer, please read the\n * [jQuery 3.5 upgrade guide](https://jquery.com/upgrade-guide/3.5/) for more details\n * about the workarounds.\n *\n * ## jQuery/jqLite Extras\n * AngularJS also provides the following additional methods and events to both jQuery and jqLite:\n *\n * ### Events\n * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event\n * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM\n * element before it is removed.\n *\n * ### Methods\n * - `controller(name)` - retrieves the controller of the current element or its parent. By default\n * retrieves controller associated with the `ngController` directive. If `name` is provided as\n * camelCase directive name, then the controller for this directive will be retrieved (e.g.\n * `'ngModel'`).\n * - `injector()` - retrieves the injector of the current element or its parent.\n * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current\n * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to\n * be enabled.\n * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the\n * current element. This getter should be used only on elements that contain a directive which starts a new isolate\n * scope. Calling `scope()` on this element always returns the original non-isolate scope.\n * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.\n * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top\n * parent element is reached.\n *\n * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See\n * https://github.com/angular/angular.js/issues/14251 for more information.\n *\n * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.\n * @returns {Object} jQuery object.\n */\n\nJQLite.expando = 'ng339';\n\nvar jqCache = JQLite.cache = {},\n jqId = 1;\n\n/*\n * !!! This is an undocumented \"private\" function !!!\n */\nJQLite._data = function(node) {\n //jQuery always returns an object on cache miss\n return this.cache[node[this.expando]] || {};\n};\n\nfunction jqNextId() { return ++jqId; }\n\n\nvar DASH_LOWERCASE_REGEXP = /-([a-z])/g;\nvar MS_HACK_REGEXP = /^-ms-/;\nvar MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };\nvar jqLiteMinErr = minErr('jqLite');\n\n/**\n * Converts kebab-case to camelCase.\n * There is also a special case for the ms prefix starting with a lowercase letter.\n * @param name Name to normalize\n */\nfunction cssKebabToCamel(name) {\n return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-'));\n}\n\nfunction fnCamelCaseReplace(all, letter) {\n return letter.toUpperCase();\n}\n\n/**\n * Converts kebab-case to camelCase.\n * @param name Name to normalize\n */\nfunction kebabToCamel(name) {\n return name\n .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace);\n}\n\nvar SINGLE_TAG_REGEXP = /^<([\\w-]+)\\s*\\/?>(?:<\\/\\1>|)$/;\nvar HTML_REGEXP = /<|&#?\\w+;/;\nvar TAG_NAME_REGEXP = /<([\\w:-]+)/;\nvar XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\\w:-]+)[^>]*)\\/>/gi;\n\n// Table parts need to be wrapped with `` or they're\n// stripped to their contents when put in a div.\n// XHTML parsers do not magically insert elements in the\n// same way that tag soup parsers do, so we cannot shorten\n// this by omitting or other required elements.\nvar wrapMap = {\n thead: ['table'],\n col: ['colgroup', 'table'],\n tr: ['tbody', 'table'],\n td: ['tr', 'tbody', 'table']\n};\n\nwrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;\nwrapMap.th = wrapMap.td;\n\n// Support: IE <10 only\n// IE 9 requires an option wrapper & it needs to have the whole table structure\n// set up in advance; assigning `\"\"` to `tr.innerHTML` doesn't work, etc.\nvar wrapMapIE9 = {\n option: [1, ''],\n _default: [0, '', '']\n};\n\nfor (var key in wrapMap) {\n var wrapMapValueClosing = wrapMap[key];\n var wrapMapValue = wrapMapValueClosing.slice().reverse();\n wrapMapIE9[key] = [wrapMapValue.length, '<' + wrapMapValue.join('><') + '>', ''];\n}\n\nwrapMapIE9.optgroup = wrapMapIE9.option;\n\nfunction jqLiteIsTextNode(html) {\n return !HTML_REGEXP.test(html);\n}\n\nfunction jqLiteAcceptsData(node) {\n // The window object can accept data but has no nodeType\n // Otherwise we are only interested in elements (1) and documents (9)\n var nodeType = node.nodeType;\n return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;\n}\n\nfunction jqLiteHasData(node) {\n for (var key in jqCache[node.ng339]) {\n return true;\n }\n return false;\n}\n\nfunction jqLiteBuildFragment(html, context) {\n var tmp, tag, wrap, finalHtml,\n fragment = context.createDocumentFragment(),\n nodes = [], i;\n\n if (jqLiteIsTextNode(html)) {\n // Convert non-html into a text node\n nodes.push(context.createTextNode(html));\n } else {\n // Convert html into DOM nodes\n tmp = fragment.appendChild(context.createElement('div'));\n tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();\n finalHtml = JQLite.legacyXHTMLReplacement ?\n html.replace(XHTML_TAG_REGEXP, '<$1>') :\n html;\n\n if (msie < 10) {\n wrap = wrapMapIE9[tag] || wrapMapIE9._default;\n tmp.innerHTML = wrap[1] + finalHtml + wrap[2];\n\n // Descend through wrappers to the right content\n i = wrap[0];\n while (i--) {\n tmp = tmp.firstChild;\n }\n } else {\n wrap = wrapMap[tag] || [];\n\n // Create wrappers & descend into them\n i = wrap.length;\n while (--i > -1) {\n tmp.appendChild(window.document.createElement(wrap[i]));\n tmp = tmp.firstChild;\n }\n\n tmp.innerHTML = finalHtml;\n }\n\n nodes = concat(nodes, tmp.childNodes);\n\n tmp = fragment.firstChild;\n tmp.textContent = '';\n }\n\n // Remove wrapper from fragment\n fragment.textContent = '';\n fragment.innerHTML = ''; // Clear inner HTML\n forEach(nodes, function(node) {\n fragment.appendChild(node);\n });\n\n return fragment;\n}\n\nfunction jqLiteParseHTML(html, context) {\n context = context || window.document;\n var parsed;\n\n if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {\n return [context.createElement(parsed[1])];\n }\n\n if ((parsed = jqLiteBuildFragment(html, context))) {\n return parsed.childNodes;\n }\n\n return [];\n}\n\nfunction jqLiteWrapNode(node, wrapper) {\n var parent = node.parentNode;\n\n if (parent) {\n parent.replaceChild(wrapper, node);\n }\n\n wrapper.appendChild(node);\n}\n\n\n// IE9-11 has no method \"contains\" in SVG element and in Node.prototype. Bug #10259.\nvar jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {\n // eslint-disable-next-line no-bitwise\n return !!(this.compareDocumentPosition(arg) & 16);\n};\n\n/////////////////////////////////////////////\nfunction JQLite(element) {\n if (element instanceof JQLite) {\n return element;\n }\n\n var argIsString;\n\n if (isString(element)) {\n element = trim(element);\n argIsString = true;\n }\n if (!(this instanceof JQLite)) {\n if (argIsString && element.charAt(0) !== '<') {\n throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');\n }\n return new JQLite(element);\n }\n\n if (argIsString) {\n jqLiteAddNodes(this, jqLiteParseHTML(element));\n } else if (isFunction(element)) {\n jqLiteReady(element);\n } else {\n jqLiteAddNodes(this, element);\n }\n}\n\nfunction jqLiteClone(element) {\n return element.cloneNode(true);\n}\n\nfunction jqLiteDealoc(element, onlyDescendants) {\n if (!onlyDescendants && jqLiteAcceptsData(element)) jqLite.cleanData([element]);\n\n if (element.querySelectorAll) {\n jqLite.cleanData(element.querySelectorAll('*'));\n }\n}\n\nfunction isEmptyObject(obj) {\n var name;\n\n for (name in obj) {\n return false;\n }\n return true;\n}\n\nfunction removeIfEmptyData(element) {\n var expandoId = element.ng339;\n var expandoStore = expandoId && jqCache[expandoId];\n\n var events = expandoStore && expandoStore.events;\n var data = expandoStore && expandoStore.data;\n\n if ((!data || isEmptyObject(data)) && (!events || isEmptyObject(events))) {\n delete jqCache[expandoId];\n element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it\n }\n}\n\nfunction jqLiteOff(element, type, fn, unsupported) {\n if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');\n\n var expandoStore = jqLiteExpandoStore(element);\n var events = expandoStore && expandoStore.events;\n var handle = expandoStore && expandoStore.handle;\n\n if (!handle) return; //no listeners registered\n\n if (!type) {\n for (type in events) {\n if (type !== '$destroy') {\n element.removeEventListener(type, handle);\n }\n delete events[type];\n }\n } else {\n\n var removeHandler = function(type) {\n var listenerFns = events[type];\n if (isDefined(fn)) {\n arrayRemove(listenerFns || [], fn);\n }\n if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {\n element.removeEventListener(type, handle);\n delete events[type];\n }\n };\n\n forEach(type.split(' '), function(type) {\n removeHandler(type);\n if (MOUSE_EVENT_MAP[type]) {\n removeHandler(MOUSE_EVENT_MAP[type]);\n }\n });\n }\n\n removeIfEmptyData(element);\n}\n\nfunction jqLiteRemoveData(element, name) {\n var expandoId = element.ng339;\n var expandoStore = expandoId && jqCache[expandoId];\n\n if (expandoStore) {\n if (name) {\n delete expandoStore.data[name];\n } else {\n expandoStore.data = {};\n }\n\n removeIfEmptyData(element);\n }\n}\n\n\nfunction jqLiteExpandoStore(element, createIfNecessary) {\n var expandoId = element.ng339,\n expandoStore = expandoId && jqCache[expandoId];\n\n if (createIfNecessary && !expandoStore) {\n element.ng339 = expandoId = jqNextId();\n expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};\n }\n\n return expandoStore;\n}\n\n\nfunction jqLiteData(element, key, value) {\n if (jqLiteAcceptsData(element)) {\n var prop;\n\n var isSimpleSetter = isDefined(value);\n var isSimpleGetter = !isSimpleSetter && key && !isObject(key);\n var massGetter = !key;\n var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);\n var data = expandoStore && expandoStore.data;\n\n if (isSimpleSetter) { // data('key', value)\n data[kebabToCamel(key)] = value;\n } else {\n if (massGetter) { // data()\n return data;\n } else {\n if (isSimpleGetter) { // data('key')\n // don't force creation of expandoStore if it doesn't exist yet\n return data && data[kebabToCamel(key)];\n } else { // mass-setter: data({key1: val1, key2: val2})\n for (prop in key) {\n data[kebabToCamel(prop)] = key[prop];\n }\n }\n }\n }\n }\n}\n\nfunction jqLiteHasClass(element, selector) {\n if (!element.getAttribute) return false;\n return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\\n\\t]/g, ' ').\n indexOf(' ' + selector + ' ') > -1);\n}\n\nfunction jqLiteRemoveClass(element, cssClasses) {\n if (cssClasses && element.setAttribute) {\n var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')\n .replace(/[\\n\\t]/g, ' ');\n var newClasses = existingClasses;\n\n forEach(cssClasses.split(' '), function(cssClass) {\n cssClass = trim(cssClass);\n newClasses = newClasses.replace(' ' + cssClass + ' ', ' ');\n });\n\n if (newClasses !== existingClasses) {\n element.setAttribute('class', trim(newClasses));\n }\n }\n}\n\nfunction jqLiteAddClass(element, cssClasses) {\n if (cssClasses && element.setAttribute) {\n var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')\n .replace(/[\\n\\t]/g, ' ');\n var newClasses = existingClasses;\n\n forEach(cssClasses.split(' '), function(cssClass) {\n cssClass = trim(cssClass);\n if (newClasses.indexOf(' ' + cssClass + ' ') === -1) {\n newClasses += cssClass + ' ';\n }\n });\n\n if (newClasses !== existingClasses) {\n element.setAttribute('class', trim(newClasses));\n }\n }\n}\n\n\nfunction jqLiteAddNodes(root, elements) {\n // THIS CODE IS VERY HOT. Don't make changes without benchmarking.\n\n if (elements) {\n\n // if a Node (the most common case)\n if (elements.nodeType) {\n root[root.length++] = elements;\n } else {\n var length = elements.length;\n\n // if an Array or NodeList and not a Window\n if (typeof length === 'number' && elements.window !== elements) {\n if (length) {\n for (var i = 0; i < length; i++) {\n root[root.length++] = elements[i];\n }\n }\n } else {\n root[root.length++] = elements;\n }\n }\n }\n}\n\n\nfunction jqLiteController(element, name) {\n return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');\n}\n\nfunction jqLiteInheritedData(element, name, value) {\n // if element is the document object work with the html element instead\n // this makes $(document).scope() possible\n if (element.nodeType === NODE_TYPE_DOCUMENT) {\n element = element.documentElement;\n }\n var names = isArray(name) ? name : [name];\n\n while (element) {\n for (var i = 0, ii = names.length; i < ii; i++) {\n if (isDefined(value = jqLite.data(element, names[i]))) return value;\n }\n\n // If dealing with a document fragment node with a host element, and no parent, use the host\n // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM\n // to lookup parent controllers.\n element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);\n }\n}\n\nfunction jqLiteEmpty(element) {\n jqLiteDealoc(element, true);\n while (element.firstChild) {\n element.removeChild(element.firstChild);\n }\n}\n\nfunction jqLiteRemove(element, keepData) {\n if (!keepData) jqLiteDealoc(element);\n var parent = element.parentNode;\n if (parent) parent.removeChild(element);\n}\n\n\nfunction jqLiteDocumentLoaded(action, win) {\n win = win || window;\n if (win.document.readyState === 'complete') {\n // Force the action to be run async for consistent behavior\n // from the action's point of view\n // i.e. it will definitely not be in a $apply\n win.setTimeout(action);\n } else {\n // No need to unbind this handler as load is only ever called once\n jqLite(win).on('load', action);\n }\n}\n\nfunction jqLiteReady(fn) {\n function trigger() {\n window.document.removeEventListener('DOMContentLoaded', trigger);\n window.removeEventListener('load', trigger);\n fn();\n }\n\n // check if document is already loaded\n if (window.document.readyState === 'complete') {\n window.setTimeout(fn);\n } else {\n // We can not use jqLite since we are not done loading and jQuery could be loaded later.\n\n // Works for modern browsers and IE9\n window.document.addEventListener('DOMContentLoaded', trigger);\n\n // Fallback to window.onload for others\n window.addEventListener('load', trigger);\n }\n}\n\n//////////////////////////////////////////\n// Functions which are declared directly.\n//////////////////////////////////////////\nvar JQLitePrototype = JQLite.prototype = {\n ready: jqLiteReady,\n toString: function() {\n var value = [];\n forEach(this, function(e) { value.push('' + e);});\n return '[' + value.join(', ') + ']';\n },\n\n eq: function(index) {\n return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);\n },\n\n length: 0,\n push: push,\n sort: [].sort,\n splice: [].splice\n};\n\n//////////////////////////////////////////\n// Functions iterating getter/setters.\n// these functions return self on setter and\n// value on get.\n//////////////////////////////////////////\nvar BOOLEAN_ATTR = {};\nforEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {\n BOOLEAN_ATTR[lowercase(value)] = value;\n});\nvar BOOLEAN_ELEMENTS = {};\nforEach('input,select,option,textarea,button,form,details'.split(','), function(value) {\n BOOLEAN_ELEMENTS[value] = true;\n});\nvar ALIASED_ATTR = {\n 'ngMinlength': 'minlength',\n 'ngMaxlength': 'maxlength',\n 'ngMin': 'min',\n 'ngMax': 'max',\n 'ngPattern': 'pattern',\n 'ngStep': 'step'\n};\n\nfunction getBooleanAttrName(element, name) {\n // check dom last since we will most likely fail on name\n var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];\n\n // booleanAttr is here twice to minimize DOM access\n return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;\n}\n\nfunction getAliasedAttrName(name) {\n return ALIASED_ATTR[name];\n}\n\nforEach({\n data: jqLiteData,\n removeData: jqLiteRemoveData,\n hasData: jqLiteHasData,\n cleanData: function jqLiteCleanData(nodes) {\n for (var i = 0, ii = nodes.length; i < ii; i++) {\n jqLiteRemoveData(nodes[i]);\n jqLiteOff(nodes[i]);\n }\n }\n}, function(fn, name) {\n JQLite[name] = fn;\n});\n\nforEach({\n data: jqLiteData,\n inheritedData: jqLiteInheritedData,\n\n scope: function(element) {\n // Can't use jqLiteData here directly so we stay compatible with jQuery!\n return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);\n },\n\n isolateScope: function(element) {\n // Can't use jqLiteData here directly so we stay compatible with jQuery!\n return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');\n },\n\n controller: jqLiteController,\n\n injector: function(element) {\n return jqLiteInheritedData(element, '$injector');\n },\n\n removeAttr: function(element, name) {\n element.removeAttribute(name);\n },\n\n hasClass: jqLiteHasClass,\n\n css: function(element, name, value) {\n name = cssKebabToCamel(name);\n\n if (isDefined(value)) {\n element.style[name] = value;\n } else {\n return element.style[name];\n }\n },\n\n attr: function(element, name, value) {\n var ret;\n var nodeType = element.nodeType;\n if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT ||\n !element.getAttribute) {\n return;\n }\n\n var lowercasedName = lowercase(name);\n var isBooleanAttr = BOOLEAN_ATTR[lowercasedName];\n\n if (isDefined(value)) {\n // setter\n\n if (value === null || (value === false && isBooleanAttr)) {\n element.removeAttribute(name);\n } else {\n element.setAttribute(name, isBooleanAttr ? lowercasedName : value);\n }\n } else {\n // getter\n\n ret = element.getAttribute(name);\n\n if (isBooleanAttr && ret !== null) {\n ret = lowercasedName;\n }\n // Normalize non-existing attributes to undefined (as jQuery).\n return ret === null ? undefined : ret;\n }\n },\n\n prop: function(element, name, value) {\n if (isDefined(value)) {\n element[name] = value;\n } else {\n return element[name];\n }\n },\n\n text: (function() {\n getText.$dv = '';\n return getText;\n\n function getText(element, value) {\n if (isUndefined(value)) {\n var nodeType = element.nodeType;\n return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';\n }\n element.textContent = value;\n }\n })(),\n\n val: function(element, value) {\n if (isUndefined(value)) {\n if (element.multiple && nodeName_(element) === 'select') {\n var result = [];\n forEach(element.options, function(option) {\n if (option.selected) {\n result.push(option.value || option.text);\n }\n });\n return result;\n }\n return element.value;\n }\n element.value = value;\n },\n\n html: function(element, value) {\n if (isUndefined(value)) {\n return element.innerHTML;\n }\n jqLiteDealoc(element, true);\n element.innerHTML = value;\n },\n\n empty: jqLiteEmpty\n}, function(fn, name) {\n /**\n * Properties: writes return selection, reads return first value\n */\n JQLite.prototype[name] = function(arg1, arg2) {\n var i, key;\n var nodeCount = this.length;\n\n // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it\n // in a way that survives minification.\n // jqLiteEmpty takes no arguments but is a setter.\n if (fn !== jqLiteEmpty &&\n (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {\n if (isObject(arg1)) {\n\n // we are a write, but the object properties are the key/values\n for (i = 0; i < nodeCount; i++) {\n if (fn === jqLiteData) {\n // data() takes the whole object in jQuery\n fn(this[i], arg1);\n } else {\n for (key in arg1) {\n fn(this[i], key, arg1[key]);\n }\n }\n }\n // return self for chaining\n return this;\n } else {\n // we are a read, so read the first child.\n // TODO: do we still need this?\n var value = fn.$dv;\n // Only if we have $dv do we iterate over all, otherwise it is just the first element.\n var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;\n for (var j = 0; j < jj; j++) {\n var nodeValue = fn(this[j], arg1, arg2);\n value = value ? value + nodeValue : nodeValue;\n }\n return value;\n }\n } else {\n // we are a write, so apply to all children\n for (i = 0; i < nodeCount; i++) {\n fn(this[i], arg1, arg2);\n }\n // return self for chaining\n return this;\n }\n };\n});\n\nfunction createEventHandler(element, events) {\n var eventHandler = function(event, type) {\n // jQuery specific api\n event.isDefaultPrevented = function() {\n return event.defaultPrevented;\n };\n\n var eventFns = events[type || event.type];\n var eventFnsLength = eventFns ? eventFns.length : 0;\n\n if (!eventFnsLength) return;\n\n if (isUndefined(event.immediatePropagationStopped)) {\n var originalStopImmediatePropagation = event.stopImmediatePropagation;\n event.stopImmediatePropagation = function() {\n event.immediatePropagationStopped = true;\n\n if (event.stopPropagation) {\n event.stopPropagation();\n }\n\n if (originalStopImmediatePropagation) {\n originalStopImmediatePropagation.call(event);\n }\n };\n }\n\n event.isImmediatePropagationStopped = function() {\n return event.immediatePropagationStopped === true;\n };\n\n // Some events have special handlers that wrap the real handler\n var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;\n\n // Copy event handlers in case event handlers array is modified during execution.\n if ((eventFnsLength > 1)) {\n eventFns = shallowCopy(eventFns);\n }\n\n for (var i = 0; i < eventFnsLength; i++) {\n if (!event.isImmediatePropagationStopped()) {\n handlerWrapper(element, event, eventFns[i]);\n }\n }\n };\n\n // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all\n // events on `element`\n eventHandler.elem = element;\n return eventHandler;\n}\n\nfunction defaultHandlerWrapper(element, event, handler) {\n handler.call(element, event);\n}\n\nfunction specialMouseHandlerWrapper(target, event, handler) {\n // Refer to jQuery's implementation of mouseenter & mouseleave\n // Read about mouseenter and mouseleave:\n // http://www.quirksmode.org/js/events_mouse.html#link8\n var related = event.relatedTarget;\n // For mousenter/leave call the handler if related is outside the target.\n // NB: No relatedTarget if the mouse left/entered the browser window\n if (!related || (related !== target && !jqLiteContains.call(target, related))) {\n handler.call(target, event);\n }\n}\n\n//////////////////////////////////////////\n// Functions iterating traversal.\n// These functions chain results into a single\n// selector.\n//////////////////////////////////////////\nforEach({\n removeData: jqLiteRemoveData,\n\n on: function jqLiteOn(element, type, fn, unsupported) {\n if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');\n\n // Do not add event handlers to non-elements because they will not be cleaned up.\n if (!jqLiteAcceptsData(element)) {\n return;\n }\n\n var expandoStore = jqLiteExpandoStore(element, true);\n var events = expandoStore.events;\n var handle = expandoStore.handle;\n\n if (!handle) {\n handle = expandoStore.handle = createEventHandler(element, events);\n }\n\n // http://jsperf.com/string-indexof-vs-split\n var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];\n var i = types.length;\n\n var addHandler = function(type, specialHandlerWrapper, noEventListener) {\n var eventFns = events[type];\n\n if (!eventFns) {\n eventFns = events[type] = [];\n eventFns.specialHandlerWrapper = specialHandlerWrapper;\n if (type !== '$destroy' && !noEventListener) {\n element.addEventListener(type, handle);\n }\n }\n\n eventFns.push(fn);\n };\n\n while (i--) {\n type = types[i];\n if (MOUSE_EVENT_MAP[type]) {\n addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);\n addHandler(type, undefined, true);\n } else {\n addHandler(type);\n }\n }\n },\n\n off: jqLiteOff,\n\n one: function(element, type, fn) {\n element = jqLite(element);\n\n //add the listener twice so that when it is called\n //you can remove the original function and still be\n //able to call element.off(ev, fn) normally\n element.on(type, function onFn() {\n element.off(type, fn);\n element.off(type, onFn);\n });\n element.on(type, fn);\n },\n\n replaceWith: function(element, replaceNode) {\n var index, parent = element.parentNode;\n jqLiteDealoc(element);\n forEach(new JQLite(replaceNode), function(node) {\n if (index) {\n parent.insertBefore(node, index.nextSibling);\n } else {\n parent.replaceChild(node, element);\n }\n index = node;\n });\n },\n\n children: function(element) {\n var children = [];\n forEach(element.childNodes, function(element) {\n if (element.nodeType === NODE_TYPE_ELEMENT) {\n children.push(element);\n }\n });\n return children;\n },\n\n contents: function(element) {\n return element.contentDocument || element.childNodes || [];\n },\n\n append: function(element, node) {\n var nodeType = element.nodeType;\n if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;\n\n node = new JQLite(node);\n\n for (var i = 0, ii = node.length; i < ii; i++) {\n var child = node[i];\n element.appendChild(child);\n }\n },\n\n prepend: function(element, node) {\n if (element.nodeType === NODE_TYPE_ELEMENT) {\n var index = element.firstChild;\n forEach(new JQLite(node), function(child) {\n element.insertBefore(child, index);\n });\n }\n },\n\n wrap: function(element, wrapNode) {\n jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);\n },\n\n remove: jqLiteRemove,\n\n detach: function(element) {\n jqLiteRemove(element, true);\n },\n\n after: function(element, newElement) {\n var index = element, parent = element.parentNode;\n\n if (parent) {\n newElement = new JQLite(newElement);\n\n for (var i = 0, ii = newElement.length; i < ii; i++) {\n var node = newElement[i];\n parent.insertBefore(node, index.nextSibling);\n index = node;\n }\n }\n },\n\n addClass: jqLiteAddClass,\n removeClass: jqLiteRemoveClass,\n\n toggleClass: function(element, selector, condition) {\n if (selector) {\n forEach(selector.split(' '), function(className) {\n var classCondition = condition;\n if (isUndefined(classCondition)) {\n classCondition = !jqLiteHasClass(element, className);\n }\n (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);\n });\n }\n },\n\n parent: function(element) {\n var parent = element.parentNode;\n return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;\n },\n\n next: function(element) {\n return element.nextElementSibling;\n },\n\n find: function(element, selector) {\n if (element.getElementsByTagName) {\n return element.getElementsByTagName(selector);\n } else {\n return [];\n }\n },\n\n clone: jqLiteClone,\n\n triggerHandler: function(element, event, extraParameters) {\n\n var dummyEvent, eventFnsCopy, handlerArgs;\n var eventName = event.type || event;\n var expandoStore = jqLiteExpandoStore(element);\n var events = expandoStore && expandoStore.events;\n var eventFns = events && events[eventName];\n\n if (eventFns) {\n // Create a dummy event to pass to the handlers\n dummyEvent = {\n preventDefault: function() { this.defaultPrevented = true; },\n isDefaultPrevented: function() { return this.defaultPrevented === true; },\n stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },\n isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },\n stopPropagation: noop,\n type: eventName,\n target: element\n };\n\n // If a custom event was provided then extend our dummy event with it\n if (event.type) {\n dummyEvent = extend(dummyEvent, event);\n }\n\n // Copy event handlers in case event handlers array is modified during execution.\n eventFnsCopy = shallowCopy(eventFns);\n handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];\n\n forEach(eventFnsCopy, function(fn) {\n if (!dummyEvent.isImmediatePropagationStopped()) {\n fn.apply(element, handlerArgs);\n }\n });\n }\n }\n}, function(fn, name) {\n /**\n * chaining functions\n */\n JQLite.prototype[name] = function(arg1, arg2, arg3) {\n var value;\n\n for (var i = 0, ii = this.length; i < ii; i++) {\n if (isUndefined(value)) {\n value = fn(this[i], arg1, arg2, arg3);\n if (isDefined(value)) {\n // any function which returns a value needs to be wrapped\n value = jqLite(value);\n }\n } else {\n jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));\n }\n }\n return isDefined(value) ? value : this;\n };\n});\n\n// bind legacy bind/unbind to on/off\nJQLite.prototype.bind = JQLite.prototype.on;\nJQLite.prototype.unbind = JQLite.prototype.off;\n\n\n// Provider for private $$jqLite service\n/** @this */\nfunction $$jqLiteProvider() {\n this.$get = function $$jqLite() {\n return extend(JQLite, {\n hasClass: function(node, classes) {\n if (node.attr) node = node[0];\n return jqLiteHasClass(node, classes);\n },\n addClass: function(node, classes) {\n if (node.attr) node = node[0];\n return jqLiteAddClass(node, classes);\n },\n removeClass: function(node, classes) {\n if (node.attr) node = node[0];\n return jqLiteRemoveClass(node, classes);\n }\n });\n };\n}\n\n/**\n * Computes a hash of an 'obj'.\n * Hash of a:\n * string is string\n * number is number as string\n * object is either result of calling $$hashKey function on the object or uniquely generated id,\n * that is also assigned to the $$hashKey property of the object.\n *\n * @param obj\n * @returns {string} hash string such that the same input will have the same hash string.\n * The resulting string key is in 'type:hashKey' format.\n */\nfunction hashKey(obj, nextUidFn) {\n var key = obj && obj.$$hashKey;\n\n if (key) {\n if (typeof key === 'function') {\n key = obj.$$hashKey();\n }\n return key;\n }\n\n var objType = typeof obj;\n if (objType === 'function' || (objType === 'object' && obj !== null)) {\n key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();\n } else {\n key = objType + ':' + obj;\n }\n\n return key;\n}\n\n// A minimal ES2015 Map implementation.\n// Should be bug/feature equivalent to the native implementations of supported browsers\n// (for the features required in Angular).\n// See https://kangax.github.io/compat-table/es6/#test-Map\nvar nanKey = Object.create(null);\nfunction NgMapShim() {\n this._keys = [];\n this._values = [];\n this._lastKey = NaN;\n this._lastIndex = -1;\n}\nNgMapShim.prototype = {\n _idx: function(key) {\n if (key !== this._lastKey) {\n this._lastKey = key;\n this._lastIndex = this._keys.indexOf(key);\n }\n return this._lastIndex;\n },\n _transformKey: function(key) {\n return isNumberNaN(key) ? nanKey : key;\n },\n get: function(key) {\n key = this._transformKey(key);\n var idx = this._idx(key);\n if (idx !== -1) {\n return this._values[idx];\n }\n },\n has: function(key) {\n key = this._transformKey(key);\n var idx = this._idx(key);\n return idx !== -1;\n },\n set: function(key, value) {\n key = this._transformKey(key);\n var idx = this._idx(key);\n if (idx === -1) {\n idx = this._lastIndex = this._keys.length;\n }\n this._keys[idx] = key;\n this._values[idx] = value;\n\n // Support: IE11\n // Do not `return this` to simulate the partial IE11 implementation\n },\n delete: function(key) {\n key = this._transformKey(key);\n var idx = this._idx(key);\n if (idx === -1) {\n return false;\n }\n this._keys.splice(idx, 1);\n this._values.splice(idx, 1);\n this._lastKey = NaN;\n this._lastIndex = -1;\n return true;\n }\n};\n\n// For now, always use `NgMapShim`, even if `window.Map` is available. Some native implementations\n// are still buggy (often in subtle ways) and can cause hard-to-debug failures. When native `Map`\n// implementations get more stable, we can reconsider switching to `window.Map` (when available).\nvar NgMap = NgMapShim;\n\nvar $$MapProvider = [/** @this */function() {\n this.$get = [function() {\n return NgMap;\n }];\n}];\n\n/**\n * @ngdoc function\n * @module ng\n * @name angular.injector\n * @kind function\n *\n * @description\n * Creates an injector object that can be used for retrieving services as well as for\n * dependency injection (see {@link guide/di dependency injection}).\n *\n * @param {Array.} modules A list of module functions or their aliases. See\n * {@link angular.module}. The `ng` module must be explicitly added.\n * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which\n * disallows argument name annotation inference.\n * @returns {injector} Injector object. See {@link auto.$injector $injector}.\n *\n * @example\n * Typical usage\n * ```js\n * // create an injector\n * var $injector = angular.injector(['ng']);\n *\n * // use the injector to kick off your application\n * // use the type inference to auto inject arguments, or use implicit injection\n * $injector.invoke(function($rootScope, $compile, $document) {\n * $compile($document)($rootScope);\n * $rootScope.$digest();\n * });\n * ```\n *\n * Sometimes you want to get access to the injector of a currently running AngularJS app\n * from outside AngularJS. Perhaps, you want to inject and compile some markup after the\n * application has been bootstrapped. You can do this using the extra `injector()` added\n * to JQuery/jqLite elements. See {@link angular.element}.\n *\n * *This is fairly rare but could be the case if a third party library is injecting the\n * markup.*\n *\n * In the following example a new block of HTML containing a `ng-controller`\n * directive is added to the end of the document body by JQuery. We then compile and link\n * it into the current AngularJS scope.\n *\n * ```js\n * var $div = $('
{{content.label}}
');\n * $(document.body).append($div);\n *\n * angular.element(document).injector().invoke(function($compile) {\n * var scope = angular.element($div).scope();\n * $compile($div)(scope);\n * });\n * ```\n */\n\n\n/**\n * @ngdoc module\n * @name auto\n * @installation\n * @description\n *\n * Implicit module which gets automatically added to each {@link auto.$injector $injector}.\n */\n\nvar ARROW_ARG = /^([^(]+?)=>/;\nvar FN_ARGS = /^[^(]*\\(\\s*([^)]*)\\)/m;\nvar FN_ARG_SPLIT = /,/;\nvar FN_ARG = /^\\s*(_?)(\\S+?)\\1\\s*$/;\nvar STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/mg;\nvar $injectorMinErr = minErr('$injector');\n\nfunction stringifyFn(fn) {\n return Function.prototype.toString.call(fn);\n}\n\nfunction extractArgs(fn) {\n var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),\n args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);\n return args;\n}\n\nfunction anonFn(fn) {\n // For anonymous functions, showing at the very least the function signature can help in\n // debugging.\n var args = extractArgs(fn);\n if (args) {\n return 'function(' + (args[1] || '').replace(/[\\s\\r\\n]+/, ' ') + ')';\n }\n return 'fn';\n}\n\nfunction annotate(fn, strictDi, name) {\n var $inject,\n argDecl,\n last;\n\n if (typeof fn === 'function') {\n if (!($inject = fn.$inject)) {\n $inject = [];\n if (fn.length) {\n if (strictDi) {\n if (!isString(name) || !name) {\n name = fn.name || anonFn(fn);\n }\n throw $injectorMinErr('strictdi',\n '{0} is not using explicit annotation and cannot be invoked in strict mode', name);\n }\n argDecl = extractArgs(fn);\n forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {\n arg.replace(FN_ARG, function(all, underscore, name) {\n $inject.push(name);\n });\n });\n }\n fn.$inject = $inject;\n }\n } else if (isArray(fn)) {\n last = fn.length - 1;\n assertArgFn(fn[last], 'fn');\n $inject = fn.slice(0, last);\n } else {\n assertArgFn(fn, 'fn', true);\n }\n return $inject;\n}\n\n///////////////////////////////////////\n\n/**\n * @ngdoc service\n * @name $injector\n *\n * @description\n *\n * `$injector` is used to retrieve object instances as defined by\n * {@link auto.$provide provider}, instantiate types, invoke methods,\n * and load modules.\n *\n * The following always holds true:\n *\n * ```js\n * var $injector = angular.injector();\n * expect($injector.get('$injector')).toBe($injector);\n * expect($injector.invoke(function($injector) {\n * return $injector;\n * })).toBe($injector);\n * ```\n *\n * ## Injection Function Annotation\n *\n * JavaScript does not have annotations, and annotations are needed for dependency injection. The\n * following are all valid ways of annotating function with injection arguments and are equivalent.\n *\n * ```js\n * // inferred (only works if code not minified/obfuscated)\n * $injector.invoke(function(serviceA){});\n *\n * // annotated\n * function explicit(serviceA) {};\n * explicit.$inject = ['serviceA'];\n * $injector.invoke(explicit);\n *\n * // inline\n * $injector.invoke(['serviceA', function(serviceA){}]);\n * ```\n *\n * ### Inference\n *\n * In JavaScript calling `toString()` on a function returns the function definition. The definition\n * can then be parsed and the function arguments can be extracted. This method of discovering\n * annotations is disallowed when the injector is in strict mode.\n * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the\n * argument names.\n *\n * ### `$inject` Annotation\n * By adding an `$inject` property onto a function the injection parameters can be specified.\n *\n * ### Inline\n * As an array of injection names, where the last item in the array is the function to call.\n */\n\n/**\n * @ngdoc property\n * @name $injector#modules\n * @type {Object}\n * @description\n * A hash containing all the modules that have been loaded into the\n * $injector.\n *\n * You can use this property to find out information about a module via the\n * {@link angular.Module#info `myModule.info(...)`} method.\n *\n * For example:\n *\n * ```\n * var info = $injector.modules['ngAnimate'].info();\n * ```\n *\n * **Do not use this property to attempt to modify the modules after the application\n * has been bootstrapped.**\n */\n\n\n/**\n * @ngdoc method\n * @name $injector#get\n *\n * @description\n * Return an instance of the service.\n *\n * @param {string} name The name of the instance to retrieve.\n * @param {string=} caller An optional string to provide the origin of the function call for error messages.\n * @return {*} The instance.\n */\n\n/**\n * @ngdoc method\n * @name $injector#invoke\n *\n * @description\n * Invoke the method and supply the method arguments from the `$injector`.\n *\n * @param {Function|Array.} fn The injectable function to invoke. Function parameters are\n * injected according to the {@link guide/di $inject Annotation} rules.\n * @param {Object=} self The `this` for the invoked method.\n * @param {Object=} locals Optional object. If preset then any argument names are read from this\n * object first, before the `$injector` is consulted.\n * @returns {*} the value returned by the invoked `fn` function.\n */\n\n/**\n * @ngdoc method\n * @name $injector#has\n *\n * @description\n * Allows the user to query if the particular service exists.\n *\n * @param {string} name Name of the service to query.\n * @returns {boolean} `true` if injector has given service.\n */\n\n/**\n * @ngdoc method\n * @name $injector#instantiate\n * @description\n * Create a new instance of JS type. The method takes a constructor function, invokes the new\n * operator, and supplies all of the arguments to the constructor function as specified by the\n * constructor annotation.\n *\n * @param {Function} Type Annotated constructor function.\n * @param {Object=} locals Optional object. If preset then any argument names are read from this\n * object first, before the `$injector` is consulted.\n * @returns {Object} new instance of `Type`.\n */\n\n/**\n * @ngdoc method\n * @name $injector#annotate\n *\n * @description\n * Returns an array of service names which the function is requesting for injection. This API is\n * used by the injector to determine which services need to be injected into the function when the\n * function is invoked. There are three ways in which the function can be annotated with the needed\n * dependencies.\n *\n * #### Argument names\n *\n * The simplest form is to extract the dependencies from the arguments of the function. This is done\n * by converting the function into a string using `toString()` method and extracting the argument\n * names.\n * ```js\n * // Given\n * function MyController($scope, $route) {\n * // ...\n * }\n *\n * // Then\n * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);\n * ```\n *\n * You can disallow this method by using strict injection mode.\n *\n * This method does not work with code minification / obfuscation. For this reason the following\n * annotation strategies are supported.\n *\n * #### The `$inject` property\n *\n * If a function has an `$inject` property and its value is an array of strings, then the strings\n * represent names of services to be injected into the function.\n * ```js\n * // Given\n * var MyController = function(obfuscatedScope, obfuscatedRoute) {\n * // ...\n * }\n * // Define function dependencies\n * MyController['$inject'] = ['$scope', '$route'];\n *\n * // Then\n * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);\n * ```\n *\n * #### The array notation\n *\n * It is often desirable to inline Injected functions and that's when setting the `$inject` property\n * is very inconvenient. In these situations using the array notation to specify the dependencies in\n * a way that survives minification is a better choice:\n *\n * ```js\n * // We wish to write this (not minification / obfuscation safe)\n * injector.invoke(function($compile, $rootScope) {\n * // ...\n * });\n *\n * // We are forced to write break inlining\n * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {\n * // ...\n * };\n * tmpFn.$inject = ['$compile', '$rootScope'];\n * injector.invoke(tmpFn);\n *\n * // To better support inline function the inline annotation is supported\n * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {\n * // ...\n * }]);\n *\n * // Therefore\n * expect(injector.annotate(\n * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])\n * ).toEqual(['$compile', '$rootScope']);\n * ```\n *\n * @param {Function|Array.} fn Function for which dependent service names need to\n * be retrieved as described above.\n *\n * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.\n *\n * @returns {Array.} The names of the services which the function requires.\n */\n/**\n * @ngdoc method\n * @name $injector#loadNewModules\n *\n * @description\n *\n * **This is a dangerous API, which you use at your own risk!**\n *\n * Add the specified modules to the current injector.\n *\n * This method will add each of the injectables to the injector and execute all of the config and run\n * blocks for each module passed to the method.\n *\n * If a module has already been loaded into the injector then it will not be loaded again.\n *\n * * The application developer is responsible for loading the code containing the modules; and for\n * ensuring that lazy scripts are not downloaded and executed more often that desired.\n * * Previously compiled HTML will not be affected by newly loaded directives, filters and components.\n * * Modules cannot be unloaded.\n *\n * You can use {@link $injector#modules `$injector.modules`} to check whether a module has been loaded\n * into the injector, which may indicate whether the script has been executed already.\n *\n * @example\n * Here is an example of loading a bundle of modules, with a utility method called `getScript`:\n *\n * ```javascript\n * app.factory('loadModule', function($injector) {\n * return function loadModule(moduleName, bundleUrl) {\n * return getScript(bundleUrl).then(function() { $injector.loadNewModules([moduleName]); });\n * };\n * })\n * ```\n *\n * @param {Array=} mods an array of modules to load into the application.\n * Each item in the array should be the name of a predefined module or a (DI annotated)\n * function that will be invoked by the injector as a `config` block.\n * See: {@link angular.module modules}\n */\n\n\n/**\n * @ngdoc service\n * @name $provide\n *\n * @description\n *\n * The {@link auto.$provide $provide} service has a number of methods for registering components\n * with the {@link auto.$injector $injector}. Many of these functions are also exposed on\n * {@link angular.Module}.\n *\n * An AngularJS **service** is a singleton object created by a **service factory**. These **service\n * factories** are functions which, in turn, are created by a **service provider**.\n * The **service providers** are constructor functions. When instantiated they must contain a\n * property called `$get`, which holds the **service factory** function.\n *\n * When you request a service, the {@link auto.$injector $injector} is responsible for finding the\n * correct **service provider**, instantiating it and then calling its `$get` **service factory**\n * function to get the instance of the **service**.\n *\n * Often services have no configuration options and there is no need to add methods to the service\n * provider. The provider will be no more than a constructor function with a `$get` property. For\n * these cases the {@link auto.$provide $provide} service has additional helper methods to register\n * services without specifying a provider.\n *\n * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the\n * {@link auto.$injector $injector}\n * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by\n * providers and services.\n * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by\n * services, not providers.\n * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**\n * that will be wrapped in a **service provider** object, whose `$get` property will contain the\n * given factory function.\n * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**\n * that will be wrapped in a **service provider** object, whose `$get` property will instantiate\n * a new object using the given constructor function.\n * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that\n * will be able to modify or replace the implementation of another service.\n *\n * See the individual methods for more information and examples.\n */\n\n/**\n * @ngdoc method\n * @name $provide#provider\n * @description\n *\n * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions\n * are constructor functions, whose instances are responsible for \"providing\" a factory for a\n * service.\n *\n * Service provider names start with the name of the service they provide followed by `Provider`.\n * For example, the {@link ng.$log $log} service has a provider called\n * {@link ng.$logProvider $logProvider}.\n *\n * Service provider objects can have additional methods which allow configuration of the provider\n * and its service. Importantly, you can configure what kind of service is created by the `$get`\n * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a\n * method {@link ng.$logProvider#debugEnabled debugEnabled}\n * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the\n * console or not.\n *\n * It is possible to inject other providers into the provider function,\n * but the injected provider must have been defined before the one that requires it.\n *\n * @param {string} name The name of the instance. NOTE: the provider will be available under `name +\n 'Provider'` key.\n * @param {(Object|function())} provider If the provider is:\n *\n * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using\n * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.\n * - `Constructor`: a new instance of the provider will be created using\n * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.\n *\n * @returns {Object} registered provider instance\n\n * @example\n *\n * The following example shows how to create a simple event tracking service and register it using\n * {@link auto.$provide#provider $provide.provider()}.\n *\n * ```js\n * // Define the eventTracker provider\n * function EventTrackerProvider() {\n * var trackingUrl = '/track';\n *\n * // A provider method for configuring where the tracked events should been saved\n * this.setTrackingUrl = function(url) {\n * trackingUrl = url;\n * };\n *\n * // The service factory function\n * this.$get = ['$http', function($http) {\n * var trackedEvents = {};\n * return {\n * // Call this to track an event\n * event: function(event) {\n * var count = trackedEvents[event] || 0;\n * count += 1;\n * trackedEvents[event] = count;\n * return count;\n * },\n * // Call this to save the tracked events to the trackingUrl\n * save: function() {\n * $http.post(trackingUrl, trackedEvents);\n * }\n * };\n * }];\n * }\n *\n * describe('eventTracker', function() {\n * var postSpy;\n *\n * beforeEach(module(function($provide) {\n * // Register the eventTracker provider\n * $provide.provider('eventTracker', EventTrackerProvider);\n * }));\n *\n * beforeEach(module(function(eventTrackerProvider) {\n * // Configure eventTracker provider\n * eventTrackerProvider.setTrackingUrl('/custom-track');\n * }));\n *\n * it('tracks events', inject(function(eventTracker) {\n * expect(eventTracker.event('login')).toEqual(1);\n * expect(eventTracker.event('login')).toEqual(2);\n * }));\n *\n * it('saves to the tracking url', inject(function(eventTracker, $http) {\n * postSpy = spyOn($http, 'post');\n * eventTracker.event('login');\n * eventTracker.save();\n * expect(postSpy).toHaveBeenCalled();\n * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');\n * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');\n * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });\n * }));\n * });\n * ```\n */\n\n/**\n * @ngdoc method\n * @name $provide#factory\n * @description\n *\n * Register a **service factory**, which will be called to return the service instance.\n * This is short for registering a service where its provider consists of only a `$get` property,\n * which is the given service factory function.\n * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to\n * configure your service in a provider.\n *\n * @param {string} name The name of the instance.\n * @param {Function|Array.} $getFn The injectable $getFn for the instance creation.\n * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here is an example of registering a service\n * ```js\n * $provide.factory('ping', ['$http', function($http) {\n * return function ping() {\n * return $http.send('/ping');\n * };\n * }]);\n * ```\n * You would then inject and use this service like this:\n * ```js\n * someModule.controller('Ctrl', ['ping', function(ping) {\n * ping();\n * }]);\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#service\n * @description\n *\n * Register a **service constructor**, which will be invoked with `new` to create the service\n * instance.\n * This is short for registering a service where its provider's `$get` property is a factory\n * function that returns an instance instantiated by the injector from the service constructor\n * function.\n *\n * Internally it looks a bit like this:\n *\n * ```\n * {\n * $get: function() {\n * return $injector.instantiate(constructor);\n * }\n * }\n * ```\n *\n *\n * You should use {@link auto.$provide#service $provide.service(class)} if you define your service\n * as a type/class.\n *\n * @param {string} name The name of the instance.\n * @param {Function|Array.} constructor An injectable class (constructor function)\n * that will be instantiated.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here is an example of registering a service using\n * {@link auto.$provide#service $provide.service(class)}.\n * ```js\n * var Ping = function($http) {\n * this.$http = $http;\n * };\n *\n * Ping.$inject = ['$http'];\n *\n * Ping.prototype.send = function() {\n * return this.$http.get('/ping');\n * };\n * $provide.service('ping', Ping);\n * ```\n * You would then inject and use this service like this:\n * ```js\n * someModule.controller('Ctrl', ['ping', function(ping) {\n * ping.send();\n * }]);\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#value\n * @description\n *\n * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a\n * number, an array, an object or a function. This is short for registering a service where its\n * provider's `$get` property is a factory function that takes no arguments and returns the **value\n * service**. That also means it is not possible to inject other services into a value service.\n *\n * Value services are similar to constant services, except that they cannot be injected into a\n * module configuration function (see {@link angular.Module#config}) but they can be overridden by\n * an AngularJS {@link auto.$provide#decorator decorator}.\n *\n * @param {string} name The name of the instance.\n * @param {*} value The value.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here are some examples of creating value services.\n * ```js\n * $provide.value('ADMIN_USER', 'admin');\n *\n * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });\n *\n * $provide.value('halfOf', function(value) {\n * return value / 2;\n * });\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#constant\n * @description\n *\n * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,\n * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not\n * possible to inject other services into a constant.\n *\n * But unlike {@link auto.$provide#value value}, a constant can be\n * injected into a module configuration function (see {@link angular.Module#config}) and it cannot\n * be overridden by an AngularJS {@link auto.$provide#decorator decorator}.\n *\n * @param {string} name The name of the constant.\n * @param {*} value The constant value.\n * @returns {Object} registered instance\n *\n * @example\n * Here a some examples of creating constants:\n * ```js\n * $provide.constant('SHARD_HEIGHT', 306);\n *\n * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);\n *\n * $provide.constant('double', function(value) {\n * return value * 2;\n * });\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#decorator\n * @description\n *\n * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function\n * intercepts the creation of a service, allowing it to override or modify the behavior of the\n * service. The return value of the decorator function may be the original service, or a new service\n * that replaces (or wraps and delegates to) the original service.\n *\n * You can find out more about using decorators in the {@link guide/decorators} guide.\n *\n * @param {string} name The name of the service to decorate.\n * @param {Function|Array.} decorator This function will be invoked when the service needs to be\n * provided and should return the decorated service instance. The function is called using\n * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.\n * Local injection arguments:\n *\n * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,\n * decorated or delegated to.\n *\n * @example\n * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting\n * calls to {@link ng.$log#error $log.warn()}.\n * ```js\n * $provide.decorator('$log', ['$delegate', function($delegate) {\n * $delegate.warn = $delegate.error;\n * return $delegate;\n * }]);\n * ```\n */\n\n\nfunction createInjector(modulesToLoad, strictDi) {\n strictDi = (strictDi === true);\n var INSTANTIATING = {},\n providerSuffix = 'Provider',\n path = [],\n loadedModules = new NgMap(),\n providerCache = {\n $provide: {\n provider: supportObject(provider),\n factory: supportObject(factory),\n service: supportObject(service),\n value: supportObject(value),\n constant: supportObject(constant),\n decorator: decorator\n }\n },\n providerInjector = (providerCache.$injector =\n createInternalInjector(providerCache, function(serviceName, caller) {\n if (angular.isString(caller)) {\n path.push(caller);\n }\n throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));\n })),\n instanceCache = {},\n protoInstanceInjector =\n createInternalInjector(instanceCache, function(serviceName, caller) {\n var provider = providerInjector.get(serviceName + providerSuffix, caller);\n return instanceInjector.invoke(\n provider.$get, provider, undefined, serviceName);\n }),\n instanceInjector = protoInstanceInjector;\n\n providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };\n instanceInjector.modules = providerInjector.modules = createMap();\n var runBlocks = loadModules(modulesToLoad);\n instanceInjector = protoInstanceInjector.get('$injector');\n instanceInjector.strictDi = strictDi;\n forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });\n\n instanceInjector.loadNewModules = function(mods) {\n forEach(loadModules(mods), function(fn) { if (fn) instanceInjector.invoke(fn); });\n };\n\n\n return instanceInjector;\n\n ////////////////////////////////////\n // $provider\n ////////////////////////////////////\n\n function supportObject(delegate) {\n return function(key, value) {\n if (isObject(key)) {\n forEach(key, reverseParams(delegate));\n } else {\n return delegate(key, value);\n }\n };\n }\n\n function provider(name, provider_) {\n assertNotHasOwnProperty(name, 'service');\n if (isFunction(provider_) || isArray(provider_)) {\n provider_ = providerInjector.instantiate(provider_);\n }\n if (!provider_.$get) {\n throw $injectorMinErr('pget', 'Provider \\'{0}\\' must define $get factory method.', name);\n }\n return (providerCache[name + providerSuffix] = provider_);\n }\n\n function enforceReturnValue(name, factory) {\n return /** @this */ function enforcedReturnValue() {\n var result = instanceInjector.invoke(factory, this);\n if (isUndefined(result)) {\n throw $injectorMinErr('undef', 'Provider \\'{0}\\' must return a value from $get factory method.', name);\n }\n return result;\n };\n }\n\n function factory(name, factoryFn, enforce) {\n return provider(name, {\n $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn\n });\n }\n\n function service(name, constructor) {\n return factory(name, ['$injector', function($injector) {\n return $injector.instantiate(constructor);\n }]);\n }\n\n function value(name, val) { return factory(name, valueFn(val), false); }\n\n function constant(name, value) {\n assertNotHasOwnProperty(name, 'constant');\n providerCache[name] = value;\n instanceCache[name] = value;\n }\n\n function decorator(serviceName, decorFn) {\n var origProvider = providerInjector.get(serviceName + providerSuffix),\n orig$get = origProvider.$get;\n\n origProvider.$get = function() {\n var origInstance = instanceInjector.invoke(orig$get, origProvider);\n return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});\n };\n }\n\n ////////////////////////////////////\n // Module Loading\n ////////////////////////////////////\n function loadModules(modulesToLoad) {\n assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');\n var runBlocks = [], moduleFn;\n forEach(modulesToLoad, function(module) {\n if (loadedModules.get(module)) return;\n loadedModules.set(module, true);\n\n function runInvokeQueue(queue) {\n var i, ii;\n for (i = 0, ii = queue.length; i < ii; i++) {\n var invokeArgs = queue[i],\n provider = providerInjector.get(invokeArgs[0]);\n\n provider[invokeArgs[1]].apply(provider, invokeArgs[2]);\n }\n }\n\n try {\n if (isString(module)) {\n moduleFn = angularModule(module);\n instanceInjector.modules[module] = moduleFn;\n runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);\n runInvokeQueue(moduleFn._invokeQueue);\n runInvokeQueue(moduleFn._configBlocks);\n } else if (isFunction(module)) {\n runBlocks.push(providerInjector.invoke(module));\n } else if (isArray(module)) {\n runBlocks.push(providerInjector.invoke(module));\n } else {\n assertArgFn(module, 'module');\n }\n } catch (e) {\n if (isArray(module)) {\n module = module[module.length - 1];\n }\n if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {\n // Safari & FF's stack traces don't contain error.message content\n // unlike those of Chrome and IE\n // So if stack doesn't contain message, we create a new string that contains both.\n // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.\n // eslint-disable-next-line no-ex-assign\n e = e.message + '\\n' + e.stack;\n }\n throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\\n{1}',\n module, e.stack || e.message || e);\n }\n });\n return runBlocks;\n }\n\n ////////////////////////////////////\n // internal Injector\n ////////////////////////////////////\n\n function createInternalInjector(cache, factory) {\n\n function getService(serviceName, caller) {\n if (cache.hasOwnProperty(serviceName)) {\n if (cache[serviceName] === INSTANTIATING) {\n throw $injectorMinErr('cdep', 'Circular dependency found: {0}',\n serviceName + ' <- ' + path.join(' <- '));\n }\n return cache[serviceName];\n } else {\n try {\n path.unshift(serviceName);\n cache[serviceName] = INSTANTIATING;\n cache[serviceName] = factory(serviceName, caller);\n return cache[serviceName];\n } catch (err) {\n if (cache[serviceName] === INSTANTIATING) {\n delete cache[serviceName];\n }\n throw err;\n } finally {\n path.shift();\n }\n }\n }\n\n\n function injectionArgs(fn, locals, serviceName) {\n var args = [],\n $inject = createInjector.$$annotate(fn, strictDi, serviceName);\n\n for (var i = 0, length = $inject.length; i < length; i++) {\n var key = $inject[i];\n if (typeof key !== 'string') {\n throw $injectorMinErr('itkn',\n 'Incorrect injection token! Expected service name as string, got {0}', key);\n }\n args.push(locals && locals.hasOwnProperty(key) ? locals[key] :\n getService(key, serviceName));\n }\n return args;\n }\n\n function isClass(func) {\n // Support: IE 9-11 only\n // IE 9-11 do not support classes and IE9 leaks with the code below.\n if (msie || typeof func !== 'function') {\n return false;\n }\n var result = func.$$ngIsClass;\n if (!isBoolean(result)) {\n result = func.$$ngIsClass = /^class\\b/.test(stringifyFn(func));\n }\n return result;\n }\n\n function invoke(fn, self, locals, serviceName) {\n if (typeof locals === 'string') {\n serviceName = locals;\n locals = null;\n }\n\n var args = injectionArgs(fn, locals, serviceName);\n if (isArray(fn)) {\n fn = fn[fn.length - 1];\n }\n\n if (!isClass(fn)) {\n // http://jsperf.com/angularjs-invoke-apply-vs-switch\n // #5388\n return fn.apply(self, args);\n } else {\n args.unshift(null);\n return new (Function.prototype.bind.apply(fn, args))();\n }\n }\n\n\n function instantiate(Type, locals, serviceName) {\n // Check if Type is annotated and use just the given function at n-1 as parameter\n // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);\n var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);\n var args = injectionArgs(Type, locals, serviceName);\n // Empty object at position 0 is ignored for invocation with `new`, but required.\n args.unshift(null);\n return new (Function.prototype.bind.apply(ctor, args))();\n }\n\n\n return {\n invoke: invoke,\n instantiate: instantiate,\n get: getService,\n annotate: createInjector.$$annotate,\n has: function(name) {\n return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);\n }\n };\n }\n}\n\ncreateInjector.$$annotate = annotate;\n\n/**\n * @ngdoc provider\n * @name $anchorScrollProvider\n * @this\n *\n * @description\n * Use `$anchorScrollProvider` to disable automatic scrolling whenever\n * {@link ng.$location#hash $location.hash()} changes.\n */\nfunction $AnchorScrollProvider() {\n\n var autoScrollingEnabled = true;\n\n /**\n * @ngdoc method\n * @name $anchorScrollProvider#disableAutoScrolling\n *\n * @description\n * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to\n * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.
\n * Use this method to disable automatic scrolling.\n *\n * If automatic scrolling is disabled, one must explicitly call\n * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the\n * current hash.\n */\n this.disableAutoScrolling = function() {\n autoScrollingEnabled = false;\n };\n\n /**\n * @ngdoc service\n * @name $anchorScroll\n * @kind function\n * @requires $window\n * @requires $location\n * @requires $rootScope\n *\n * @description\n * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the\n * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified\n * in the\n * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).\n *\n * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to\n * match any anchor whenever it changes. This can be disabled by calling\n * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.\n *\n * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a\n * vertical scroll-offset (either fixed or dynamic).\n *\n * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of\n * {@link ng.$location#hash $location.hash()} will be used.\n *\n * @property {(number|function|jqLite)} yOffset\n * If set, specifies a vertical scroll-offset. This is often useful when there are fixed\n * positioned elements at the top of the page, such as navbars, headers etc.\n *\n * `yOffset` can be specified in various ways:\n * - **number**: A fixed number of pixels to be used as offset.

\n * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return\n * a number representing the offset (in pixels).

\n * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from\n * the top of the page to the element's bottom will be used as offset.
\n * **Note**: The element will be taken into account only as long as its `position` is set to\n * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust\n * their height and/or positioning according to the viewport's size.\n *\n *
\n *
\n * In order for `yOffset` to work properly, scrolling should take place on the document's root and\n * not some child element.\n *
\n *\n * @example\n \n \n
\n Go to bottom\n You're at the bottom!\n
\n
\n \n angular.module('anchorScrollExample', [])\n .controller('ScrollController', ['$scope', '$location', '$anchorScroll',\n function($scope, $location, $anchorScroll) {\n $scope.gotoBottom = function() {\n // set the location.hash to the id of\n // the element you wish to scroll to.\n $location.hash('bottom');\n\n // call $anchorScroll()\n $anchorScroll();\n };\n }]);\n \n \n #scrollArea {\n height: 280px;\n overflow: auto;\n }\n\n #bottom {\n display: block;\n margin-top: 2000px;\n }\n \n
\n *\n *
\n * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).\n * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.\n *\n * @example\n \n \n \n
\n Anchor {{x}} of 5\n
\n
\n \n angular.module('anchorScrollOffsetExample', [])\n .run(['$anchorScroll', function($anchorScroll) {\n $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels\n }])\n .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',\n function($anchorScroll, $location, $scope) {\n $scope.gotoAnchor = function(x) {\n var newHash = 'anchor' + x;\n if ($location.hash() !== newHash) {\n // set the $location.hash to `newHash` and\n // $anchorScroll will automatically scroll to it\n $location.hash('anchor' + x);\n } else {\n // call $anchorScroll() explicitly,\n // since $location.hash hasn't changed\n $anchorScroll();\n }\n };\n }\n ]);\n \n \n body {\n padding-top: 50px;\n }\n\n .anchor {\n border: 2px dashed DarkOrchid;\n padding: 10px 10px 200px 10px;\n }\n\n .fixed-header {\n background-color: rgba(0, 0, 0, 0.2);\n height: 50px;\n position: fixed;\n top: 0; left: 0; right: 0;\n }\n\n .fixed-header > a {\n display: inline-block;\n margin: 5px 15px;\n }\n \n
\n */\n this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {\n var document = $window.document;\n\n // Helper function to get first anchor from a NodeList\n // (using `Array#some()` instead of `angular#forEach()` since it's more performant\n // and working in all supported browsers.)\n function getFirstAnchor(list) {\n var result = null;\n Array.prototype.some.call(list, function(element) {\n if (nodeName_(element) === 'a') {\n result = element;\n return true;\n }\n });\n return result;\n }\n\n function getYOffset() {\n\n var offset = scroll.yOffset;\n\n if (isFunction(offset)) {\n offset = offset();\n } else if (isElement(offset)) {\n var elem = offset[0];\n var style = $window.getComputedStyle(elem);\n if (style.position !== 'fixed') {\n offset = 0;\n } else {\n offset = elem.getBoundingClientRect().bottom;\n }\n } else if (!isNumber(offset)) {\n offset = 0;\n }\n\n return offset;\n }\n\n function scrollTo(elem) {\n if (elem) {\n elem.scrollIntoView();\n\n var offset = getYOffset();\n\n if (offset) {\n // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.\n // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the\n // top of the viewport.\n //\n // IF the number of pixels from the top of `elem` to the end of the page's content is less\n // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some\n // way down the page.\n //\n // This is often the case for elements near the bottom of the page.\n //\n // In such cases we do not need to scroll the whole `offset` up, just the difference between\n // the top of the element and the offset, which is enough to align the top of `elem` at the\n // desired position.\n var elemTop = elem.getBoundingClientRect().top;\n $window.scrollBy(0, elemTop - offset);\n }\n } else {\n $window.scrollTo(0, 0);\n }\n }\n\n function scroll(hash) {\n // Allow numeric hashes\n hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();\n var elm;\n\n // empty hash, scroll to the top of the page\n if (!hash) scrollTo(null);\n\n // element with given id\n else if ((elm = document.getElementById(hash))) scrollTo(elm);\n\n // first anchor with given name :-D\n else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);\n\n // no element and hash === 'top', scroll to the top of the page\n else if (hash === 'top') scrollTo(null);\n }\n\n // does not scroll when user clicks on anchor link that is currently on\n // (no url change, no $location.hash() change), browser native does scroll\n if (autoScrollingEnabled) {\n $rootScope.$watch(function autoScrollWatch() {return $location.hash();},\n function autoScrollWatchAction(newVal, oldVal) {\n // skip the initial scroll if $location.hash is empty\n if (newVal === oldVal && newVal === '') return;\n\n jqLiteDocumentLoaded(function() {\n $rootScope.$evalAsync(scroll);\n });\n });\n }\n\n return scroll;\n }];\n}\n\nvar $animateMinErr = minErr('$animate');\nvar ELEMENT_NODE = 1;\nvar NG_ANIMATE_CLASSNAME = 'ng-animate';\n\nfunction mergeClasses(a,b) {\n if (!a && !b) return '';\n if (!a) return b;\n if (!b) return a;\n if (isArray(a)) a = a.join(' ');\n if (isArray(b)) b = b.join(' ');\n return a + ' ' + b;\n}\n\nfunction extractElementNode(element) {\n for (var i = 0; i < element.length; i++) {\n var elm = element[i];\n if (elm.nodeType === ELEMENT_NODE) {\n return elm;\n }\n }\n}\n\nfunction splitClasses(classes) {\n if (isString(classes)) {\n classes = classes.split(' ');\n }\n\n // Use createMap() to prevent class assumptions involving property names in\n // Object.prototype\n var obj = createMap();\n forEach(classes, function(klass) {\n // sometimes the split leaves empty string values\n // incase extra spaces were applied to the options\n if (klass.length) {\n obj[klass] = true;\n }\n });\n return obj;\n}\n\n// if any other type of options value besides an Object value is\n// passed into the $animate.method() animation then this helper code\n// will be run which will ignore it. While this patch is not the\n// greatest solution to this, a lot of existing plugins depend on\n// $animate to either call the callback (< 1.2) or return a promise\n// that can be changed. This helper function ensures that the options\n// are wiped clean incase a callback function is provided.\nfunction prepareAnimateOptions(options) {\n return isObject(options)\n ? options\n : {};\n}\n\nvar $$CoreAnimateJsProvider = /** @this */ function() {\n this.$get = noop;\n};\n\n// this is prefixed with Core since it conflicts with\n// the animateQueueProvider defined in ngAnimate/animateQueue.js\nvar $$CoreAnimateQueueProvider = /** @this */ function() {\n var postDigestQueue = new NgMap();\n var postDigestElements = [];\n\n this.$get = ['$$AnimateRunner', '$rootScope',\n function($$AnimateRunner, $rootScope) {\n return {\n enabled: noop,\n on: noop,\n off: noop,\n pin: noop,\n\n push: function(element, event, options, domOperation) {\n if (domOperation) {\n domOperation();\n }\n\n options = options || {};\n if (options.from) {\n element.css(options.from);\n }\n if (options.to) {\n element.css(options.to);\n }\n\n if (options.addClass || options.removeClass) {\n addRemoveClassesPostDigest(element, options.addClass, options.removeClass);\n }\n\n var runner = new $$AnimateRunner();\n\n // since there are no animations to run the runner needs to be\n // notified that the animation call is complete.\n runner.complete();\n return runner;\n }\n };\n\n\n function updateData(data, classes, value) {\n var changed = false;\n if (classes) {\n classes = isString(classes) ? classes.split(' ') :\n isArray(classes) ? classes : [];\n forEach(classes, function(className) {\n if (className) {\n changed = true;\n data[className] = value;\n }\n });\n }\n return changed;\n }\n\n function handleCSSClassChanges() {\n forEach(postDigestElements, function(element) {\n var data = postDigestQueue.get(element);\n if (data) {\n var existing = splitClasses(element.attr('class'));\n var toAdd = '';\n var toRemove = '';\n forEach(data, function(status, className) {\n var hasClass = !!existing[className];\n if (status !== hasClass) {\n if (status) {\n toAdd += (toAdd.length ? ' ' : '') + className;\n } else {\n toRemove += (toRemove.length ? ' ' : '') + className;\n }\n }\n });\n\n forEach(element, function(elm) {\n if (toAdd) {\n jqLiteAddClass(elm, toAdd);\n }\n if (toRemove) {\n jqLiteRemoveClass(elm, toRemove);\n }\n });\n postDigestQueue.delete(element);\n }\n });\n postDigestElements.length = 0;\n }\n\n\n function addRemoveClassesPostDigest(element, add, remove) {\n var data = postDigestQueue.get(element) || {};\n\n var classesAdded = updateData(data, add, true);\n var classesRemoved = updateData(data, remove, false);\n\n if (classesAdded || classesRemoved) {\n\n postDigestQueue.set(element, data);\n postDigestElements.push(element);\n\n if (postDigestElements.length === 1) {\n $rootScope.$$postDigest(handleCSSClassChanges);\n }\n }\n }\n }];\n};\n\n/**\n * @ngdoc provider\n * @name $animateProvider\n *\n * @description\n * Default implementation of $animate that doesn't perform any animations, instead just\n * synchronously performs DOM updates and resolves the returned runner promise.\n *\n * In order to enable animations the `ngAnimate` module has to be loaded.\n *\n * To see the functional implementation check out `src/ngAnimate/animate.js`.\n */\nvar $AnimateProvider = ['$provide', /** @this */ function($provide) {\n var provider = this;\n var classNameFilter = null;\n var customFilter = null;\n\n this.$$registeredAnimations = Object.create(null);\n\n /**\n * @ngdoc method\n * @name $animateProvider#register\n *\n * @description\n * Registers a new injectable animation factory function. The factory function produces the\n * animation object which contains callback functions for each event that is expected to be\n * animated.\n *\n * * `eventFn`: `function(element, ... , doneFunction, options)`\n * The element to animate, the `doneFunction` and the options fed into the animation. Depending\n * on the type of animation additional arguments will be injected into the animation function. The\n * list below explains the function signatures for the different animation methods:\n *\n * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)\n * - addClass: function(element, addedClasses, doneFunction, options)\n * - removeClass: function(element, removedClasses, doneFunction, options)\n * - enter, leave, move: function(element, doneFunction, options)\n * - animate: function(element, fromStyles, toStyles, doneFunction, options)\n *\n * Make sure to trigger the `doneFunction` once the animation is fully complete.\n *\n * ```js\n * return {\n * //enter, leave, move signature\n * eventFn : function(element, done, options) {\n * //code to run the animation\n * //once complete, then run done()\n * return function endFunction(wasCancelled) {\n * //code to cancel the animation\n * }\n * }\n * }\n * ```\n *\n * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).\n * @param {Function} factory The factory function that will be executed to return the animation\n * object.\n */\n this.register = function(name, factory) {\n if (name && name.charAt(0) !== '.') {\n throw $animateMinErr('notcsel', 'Expecting class selector starting with \\'.\\' got \\'{0}\\'.', name);\n }\n\n var key = name + '-animation';\n provider.$$registeredAnimations[name.substr(1)] = key;\n $provide.factory(key, factory);\n };\n\n /**\n * @ngdoc method\n * @name $animateProvider#customFilter\n *\n * @description\n * Sets and/or returns the custom filter function that is used to \"filter\" animations, i.e.\n * determine if an animation is allowed or not. When no filter is specified (the default), no\n * animation will be blocked. Setting the `customFilter` value will only allow animations for\n * which the filter function's return value is truthy.\n *\n * This allows to easily create arbitrarily complex rules for filtering animations, such as\n * allowing specific events only, or enabling animations on specific subtrees of the DOM, etc.\n * Filtering animations can also boost performance for low-powered devices, as well as\n * applications containing a lot of structural operations.\n *\n *
\n * **Best Practice:**\n * Keep the filtering function as lean as possible, because it will be called for each DOM\n * action (e.g. insertion, removal, class change) performed by \"animation-aware\" directives.\n * See {@link guide/animations#which-directives-support-animations- here} for a list of built-in\n * directives that support animations.\n * Performing computationally expensive or time-consuming operations on each call of the\n * filtering function can make your animations sluggish.\n *
\n *\n * **Note:** If present, `customFilter` will be checked before\n * {@link $animateProvider#classNameFilter classNameFilter}.\n *\n * @param {Function=} filterFn - The filter function which will be used to filter all animations.\n * If a falsy value is returned, no animation will be performed. The function will be called\n * with the following arguments:\n * - **node** `{DOMElement}` - The DOM element to be animated.\n * - **event** `{String}` - The name of the animation event (e.g. `enter`, `leave`, `addClass`\n * etc).\n * - **options** `{Object}` - A collection of options/styles used for the animation.\n * @return {Function} The current filter function or `null` if there is none set.\n */\n this.customFilter = function(filterFn) {\n if (arguments.length === 1) {\n customFilter = isFunction(filterFn) ? filterFn : null;\n }\n\n return customFilter;\n };\n\n /**\n * @ngdoc method\n * @name $animateProvider#classNameFilter\n *\n * @description\n * Sets and/or returns the CSS class regular expression that is checked when performing\n * an animation. Upon bootstrap the classNameFilter value is not set at all and will\n * therefore enable $animate to attempt to perform an animation on any element that is triggered.\n * When setting the `classNameFilter` value, animations will only be performed on elements\n * that successfully match the filter expression. This in turn can boost performance\n * for low-powered devices as well as applications containing a lot of structural operations.\n *\n * **Note:** If present, `classNameFilter` will be checked after\n * {@link $animateProvider#customFilter customFilter}. If `customFilter` is present and returns\n * false, `classNameFilter` will not be checked.\n *\n * @param {RegExp=} expression The className expression which will be checked against all animations\n * @return {RegExp} The current CSS className expression value. If null then there is no expression value\n */\n this.classNameFilter = function(expression) {\n if (arguments.length === 1) {\n classNameFilter = (expression instanceof RegExp) ? expression : null;\n if (classNameFilter) {\n var reservedRegex = new RegExp('[(\\\\s|\\\\/)]' + NG_ANIMATE_CLASSNAME + '[(\\\\s|\\\\/)]');\n if (reservedRegex.test(classNameFilter.toString())) {\n classNameFilter = null;\n throw $animateMinErr('nongcls', '$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the \"{0}\" CSS class.', NG_ANIMATE_CLASSNAME);\n }\n }\n }\n return classNameFilter;\n };\n\n this.$get = ['$$animateQueue', function($$animateQueue) {\n function domInsert(element, parentElement, afterElement) {\n // if for some reason the previous element was removed\n // from the dom sometime before this code runs then let's\n // just stick to using the parent element as the anchor\n if (afterElement) {\n var afterNode = extractElementNode(afterElement);\n if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {\n afterElement = null;\n }\n }\n if (afterElement) {\n afterElement.after(element);\n } else {\n parentElement.prepend(element);\n }\n }\n\n /**\n * @ngdoc service\n * @name $animate\n * @description The $animate service exposes a series of DOM utility methods that provide support\n * for animation hooks. The default behavior is the application of DOM operations, however,\n * when an animation is detected (and animations are enabled), $animate will do the heavy lifting\n * to ensure that animation runs with the triggered DOM operation.\n *\n * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't\n * included and only when it is active then the animation hooks that `$animate` triggers will be\n * functional. Once active then all structural `ng-` directives will trigger animations as they perform\n * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,\n * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.\n *\n * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.\n *\n * To learn more about enabling animation support, click here to visit the\n * {@link ngAnimate ngAnimate module page}.\n */\n return {\n // we don't call it directly since non-existant arguments may\n // be interpreted as null within the sub enabled function\n\n /**\n *\n * @ngdoc method\n * @name $animate#on\n * @kind function\n * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)\n * has fired on the given element or among any of its children. Once the listener is fired, the provided callback\n * is fired with the following params:\n *\n * ```js\n * $animate.on('enter', container,\n * function callback(element, phase) {\n * // cool we detected an enter animation within the container\n * }\n * );\n * ```\n *\n *
\n * **Note**: Generally, the events that are fired correspond 1:1 to `$animate` method names,\n * e.g. {@link ng.$animate#addClass addClass()} will fire `addClass`, and {@link ng.ngClass}\n * will fire `addClass` if classes are added, and `removeClass` if classes are removed.\n * However, there are two exceptions:\n *\n *
    \n *
  • if both an {@link ng.$animate#addClass addClass()} and a\n * {@link ng.$animate#removeClass removeClass()} action are performed during the same\n * animation, the event fired will be `setClass`. This is true even for `ngClass`.
  • \n *
  • an {@link ng.$animate#animate animate()} call that adds and removes classes will fire\n * the `setClass` event, but if it either removes or adds classes,\n * it will fire `animate` instead.
  • \n *
\n *\n *
\n *\n * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)\n * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself\n * as well as among its children\n * @param {Function} callback the callback function that will be fired when the listener is triggered.\n *\n * The arguments present in the callback function are:\n * * `element` - The captured DOM element that the animation was fired on.\n * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).\n * * `data` - an object with these properties:\n * * addClass - `{string|null}` - space-separated CSS classes to add to the element\n * * removeClass - `{string|null}` - space-separated CSS classes to remove from the element\n * * from - `{Object|null}` - CSS properties & values at the beginning of the animation\n * * to - `{Object|null}` - CSS properties & values at the end of the animation\n *\n * Note that the callback does not trigger a scope digest. Wrap your call into a\n * {@link $rootScope.Scope#$apply scope.$apply} to propagate changes to the scope.\n */\n on: $$animateQueue.on,\n\n /**\n *\n * @ngdoc method\n * @name $animate#off\n * @kind function\n * @description Deregisters an event listener based on the event which has been associated with the provided element. This method\n * can be used in three different ways depending on the arguments:\n *\n * ```js\n * // remove all the animation event listeners listening for `enter`\n * $animate.off('enter');\n *\n * // remove listeners for all animation events from the container element\n * $animate.off(container);\n *\n * // remove all the animation event listeners listening for `enter` on the given element and its children\n * $animate.off('enter', container);\n *\n * // remove the event listener function provided by `callback` that is set\n * // to listen for `enter` on the given `container` as well as its children\n * $animate.off('enter', container, callback);\n * ```\n *\n * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,\n * addClass, removeClass, etc...), or the container element. If it is the element, all other\n * arguments are ignored.\n * @param {DOMElement=} container the container element the event listener was placed on\n * @param {Function=} callback the callback function that was registered as the listener\n */\n off: $$animateQueue.off,\n\n /**\n * @ngdoc method\n * @name $animate#pin\n * @kind function\n * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists\n * outside of the DOM structure of the AngularJS application. By doing so, any animation triggered via `$animate` can be issued on the\n * element despite being outside the realm of the application or within another application. Say for example if the application\n * was bootstrapped on an element that is somewhere inside of the `` tag, but we wanted to allow for an element to be situated\n * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind\n * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.\n *\n * Note that this feature is only active when the `ngAnimate` module is used.\n *\n * @param {DOMElement} element the external element that will be pinned\n * @param {DOMElement} parentElement the host parent element that will be associated with the external element\n */\n pin: $$animateQueue.pin,\n\n /**\n *\n * @ngdoc method\n * @name $animate#enabled\n * @kind function\n * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This\n * function can be called in four ways:\n *\n * ```js\n * // returns true or false\n * $animate.enabled();\n *\n * // changes the enabled state for all animations\n * $animate.enabled(false);\n * $animate.enabled(true);\n *\n * // returns true or false if animations are enabled for an element\n * $animate.enabled(element);\n *\n * // changes the enabled state for an element and its children\n * $animate.enabled(element, true);\n * $animate.enabled(element, false);\n * ```\n *\n * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state\n * @param {boolean=} enabled whether or not the animations will be enabled for the element\n *\n * @return {boolean} whether or not animations are enabled\n */\n enabled: $$animateQueue.enabled,\n\n /**\n * @ngdoc method\n * @name $animate#cancel\n * @kind function\n * @description Cancels the provided animation and applies the end state of the animation.\n * Note that this does not cancel the underlying operation, e.g. the setting of classes or\n * adding the element to the DOM.\n *\n * @param {animationRunner} animationRunner An animation runner returned by an $animate function.\n *\n * @example\n \n \n angular.module('animationExample', ['ngAnimate']).component('cancelExample', {\n templateUrl: 'template.html',\n controller: function($element, $animate) {\n this.runner = null;\n\n this.addClass = function() {\n this.runner = $animate.addClass($element.find('div'), 'red');\n var ctrl = this;\n this.runner.finally(function() {\n ctrl.runner = null;\n });\n };\n\n this.removeClass = function() {\n this.runner = $animate.removeClass($element.find('div'), 'red');\n var ctrl = this;\n this.runner.finally(function() {\n ctrl.runner = null;\n });\n };\n\n this.cancel = function() {\n $animate.cancel(this.runner);\n };\n }\n });\n \n \n

\n \n \n
\n \n
\n

CSS-Animated Text
\n

\n
\n \n \n \n \n .red-add, .red-remove {\n transition: all 4s cubic-bezier(0.250, 0.460, 0.450, 0.940);\n }\n\n .red,\n .red-add.red-add-active {\n color: #FF0000;\n font-size: 40px;\n }\n\n .red-remove.red-remove-active {\n font-size: 10px;\n color: black;\n }\n\n \n
\n */\n cancel: function(runner) {\n if (runner.cancel) {\n runner.cancel();\n }\n },\n\n /**\n *\n * @ngdoc method\n * @name $animate#enter\n * @kind function\n * @description Inserts the element into the DOM either after the `after` element (if provided) or\n * as the first child within the `parent` element and then triggers an animation.\n * A promise is returned that will be resolved during the next digest once the animation\n * has completed.\n *\n * @param {DOMElement} element the element which will be inserted into the DOM\n * @param {DOMElement} parent the parent element which will append the element as\n * a child (so long as the after element is not present)\n * @param {DOMElement=} after the sibling element after which the element will be appended\n * @param {object=} options an optional collection of options/styles that will be applied to the element.\n * The object can have the following properties:\n *\n * - **addClass** - `{string}` - space-separated CSS classes to add to element\n * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`\n * - **removeClass** - `{string}` - space-separated CSS classes to remove from element\n * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`\n *\n * @return {Runner} the animation runner\n */\n enter: function(element, parent, after, options) {\n parent = parent && jqLite(parent);\n after = after && jqLite(after);\n parent = parent || after.parent();\n domInsert(element, parent, after);\n return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));\n },\n\n /**\n *\n * @ngdoc method\n * @name $animate#move\n * @kind function\n * @description Inserts (moves) the element into its new position in the DOM either after\n * the `after` element (if provided) or as the first child within the `parent` element\n * and then triggers an animation. A promise is returned that will be resolved\n * during the next digest once the animation has completed.\n *\n * @param {DOMElement} element the element which will be moved into the new DOM position\n * @param {DOMElement} parent the parent element which will append the element as\n * a child (so long as the after element is not present)\n * @param {DOMElement=} after the sibling element after which the element will be appended\n * @param {object=} options an optional collection of options/styles that will be applied to the element.\n * The object can have the following properties:\n *\n * - **addClass** - `{string}` - space-separated CSS classes to add to element\n * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`\n * - **removeClass** - `{string}` - space-separated CSS classes to remove from element\n * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`\n *\n * @return {Runner} the animation runner\n */\n move: function(element, parent, after, options) {\n parent = parent && jqLite(parent);\n after = after && jqLite(after);\n parent = parent || after.parent();\n domInsert(element, parent, after);\n return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));\n },\n\n /**\n * @ngdoc method\n * @name $animate#leave\n * @kind function\n * @description Triggers an animation and then removes the element from the DOM.\n * When the function is called a promise is returned that will be resolved during the next\n * digest once the animation has completed.\n *\n * @param {DOMElement} element the element which will be removed from the DOM\n * @param {object=} options an optional collection of options/styles that will be applied to the element.\n * The object can have the following properties:\n *\n * - **addClass** - `{string}` - space-separated CSS classes to add to element\n * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`\n * - **removeClass** - `{string}` - space-separated CSS classes to remove from element\n * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`\n *\n * @return {Runner} the animation runner\n */\n leave: function(element, options) {\n return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {\n element.remove();\n });\n },\n\n /**\n * @ngdoc method\n * @name $animate#addClass\n * @kind function\n *\n * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon\n * execution, the addClass operation will only be handled after the next digest and it will not trigger an\n * animation if element already contains the CSS class or if the class is removed at a later step.\n * Note that class-based animations are treated differently compared to structural animations\n * (like enter, move and leave) since the CSS classes may be added/removed at different points\n * depending if CSS or JavaScript animations are used.\n *\n * @param {DOMElement} element the element which the CSS classes will be applied to\n * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)\n * @param {object=} options an optional collection of options/styles that will be applied to the element.\n * The object can have the following properties:\n *\n * - **removeClass** - `{string}` - space-separated CSS classes to remove from element\n * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`\n * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`\n *\n * @return {Runner} animationRunner the animation runner\n */\n addClass: function(element, className, options) {\n options = prepareAnimateOptions(options);\n options.addClass = mergeClasses(options.addclass, className);\n return $$animateQueue.push(element, 'addClass', options);\n },\n\n /**\n * @ngdoc method\n * @name $animate#removeClass\n * @kind function\n *\n * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon\n * execution, the removeClass operation will only be handled after the next digest and it will not trigger an\n * animation if element does not contain the CSS class or if the class is added at a later step.\n * Note that class-based animations are treated differently compared to structural animations\n * (like enter, move and leave) since the CSS classes may be added/removed at different points\n * depending if CSS or JavaScript animations are used.\n *\n * @param {DOMElement} element the element which the CSS classes will be applied to\n * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)\n * @param {object=} options an optional collection of options/styles that will be applied to the element.\n * The object can have the following properties:\n *\n * - **addClass** - `{string}` - space-separated CSS classes to add to element\n * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`\n * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`\n *\n * @return {Runner} the animation runner\n */\n removeClass: function(element, className, options) {\n options = prepareAnimateOptions(options);\n options.removeClass = mergeClasses(options.removeClass, className);\n return $$animateQueue.push(element, 'removeClass', options);\n },\n\n /**\n * @ngdoc method\n * @name $animate#setClass\n * @kind function\n *\n * @description Performs both the addition and removal of a CSS classes on an element and (during the process)\n * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and\n * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has\n * passed. Note that class-based animations are treated differently compared to structural animations\n * (like enter, move and leave) since the CSS classes may be added/removed at different points\n * depending if CSS or JavaScript animations are used.\n *\n * @param {DOMElement} element the element which the CSS classes will be applied to\n * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)\n * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)\n * @param {object=} options an optional collection of options/styles that will be applied to the element.\n * The object can have the following properties:\n *\n * - **addClass** - `{string}` - space-separated CSS classes to add to element\n * - **removeClass** - `{string}` - space-separated CSS classes to remove from element\n * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`\n * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`\n *\n * @return {Runner} the animation runner\n */\n setClass: function(element, add, remove, options) {\n options = prepareAnimateOptions(options);\n options.addClass = mergeClasses(options.addClass, add);\n options.removeClass = mergeClasses(options.removeClass, remove);\n return $$animateQueue.push(element, 'setClass', options);\n },\n\n /**\n * @ngdoc method\n * @name $animate#animate\n * @kind function\n *\n * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.\n * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take\n * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and\n * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding\n * style in `to`, the style in `from` is applied immediately, and no animation is run.\n * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`\n * method (or as part of the `options` parameter):\n *\n * ```js\n * ngModule.animation('.my-inline-animation', function() {\n * return {\n * animate : function(element, from, to, done, options) {\n * //animation\n * done();\n * }\n * }\n * });\n * ```\n *\n * @param {DOMElement} element the element which the CSS styles will be applied to\n * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.\n * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.\n * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If\n * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.\n * (Note that if no animation is detected then this value will not be applied to the element.)\n * @param {object=} options an optional collection of options/styles that will be applied to the element.\n * The object can have the following properties:\n *\n * - **addClass** - `{string}` - space-separated CSS classes to add to element\n * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`\n * - **removeClass** - `{string}` - space-separated CSS classes to remove from element\n * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`\n *\n * @return {Runner} the animation runner\n */\n animate: function(element, from, to, className, options) {\n options = prepareAnimateOptions(options);\n options.from = options.from ? extend(options.from, from) : from;\n options.to = options.to ? extend(options.to, to) : to;\n\n className = className || 'ng-inline-animate';\n options.tempClasses = mergeClasses(options.tempClasses, className);\n return $$animateQueue.push(element, 'animate', options);\n }\n };\n }];\n}];\n\nvar $$AnimateAsyncRunFactoryProvider = /** @this */ function() {\n this.$get = ['$$rAF', function($$rAF) {\n var waitQueue = [];\n\n function waitForTick(fn) {\n waitQueue.push(fn);\n if (waitQueue.length > 1) return;\n $$rAF(function() {\n for (var i = 0; i < waitQueue.length; i++) {\n waitQueue[i]();\n }\n waitQueue = [];\n });\n }\n\n return function() {\n var passed = false;\n waitForTick(function() {\n passed = true;\n });\n return function(callback) {\n if (passed) {\n callback();\n } else {\n waitForTick(callback);\n }\n };\n };\n }];\n};\n\nvar $$AnimateRunnerFactoryProvider = /** @this */ function() {\n this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',\n function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {\n\n var INITIAL_STATE = 0;\n var DONE_PENDING_STATE = 1;\n var DONE_COMPLETE_STATE = 2;\n\n AnimateRunner.chain = function(chain, callback) {\n var index = 0;\n\n next();\n function next() {\n if (index === chain.length) {\n callback(true);\n return;\n }\n\n chain[index](function(response) {\n if (response === false) {\n callback(false);\n return;\n }\n index++;\n next();\n });\n }\n };\n\n AnimateRunner.all = function(runners, callback) {\n var count = 0;\n var status = true;\n forEach(runners, function(runner) {\n runner.done(onProgress);\n });\n\n function onProgress(response) {\n status = status && response;\n if (++count === runners.length) {\n callback(status);\n }\n }\n };\n\n function AnimateRunner(host) {\n this.setHost(host);\n\n var rafTick = $$animateAsyncRun();\n var timeoutTick = function(fn) {\n $timeout(fn, 0, false);\n };\n\n this._doneCallbacks = [];\n this._tick = function(fn) {\n if ($$isDocumentHidden()) {\n timeoutTick(fn);\n } else {\n rafTick(fn);\n }\n };\n this._state = 0;\n }\n\n AnimateRunner.prototype = {\n setHost: function(host) {\n this.host = host || {};\n },\n\n done: function(fn) {\n if (this._state === DONE_COMPLETE_STATE) {\n fn();\n } else {\n this._doneCallbacks.push(fn);\n }\n },\n\n progress: noop,\n\n getPromise: function() {\n if (!this.promise) {\n var self = this;\n this.promise = $q(function(resolve, reject) {\n self.done(function(status) {\n if (status === false) {\n reject();\n } else {\n resolve();\n }\n });\n });\n }\n return this.promise;\n },\n\n then: function(resolveHandler, rejectHandler) {\n return this.getPromise().then(resolveHandler, rejectHandler);\n },\n\n 'catch': function(handler) {\n return this.getPromise()['catch'](handler);\n },\n\n 'finally': function(handler) {\n return this.getPromise()['finally'](handler);\n },\n\n pause: function() {\n if (this.host.pause) {\n this.host.pause();\n }\n },\n\n resume: function() {\n if (this.host.resume) {\n this.host.resume();\n }\n },\n\n end: function() {\n if (this.host.end) {\n this.host.end();\n }\n this._resolve(true);\n },\n\n cancel: function() {\n if (this.host.cancel) {\n this.host.cancel();\n }\n this._resolve(false);\n },\n\n complete: function(response) {\n var self = this;\n if (self._state === INITIAL_STATE) {\n self._state = DONE_PENDING_STATE;\n self._tick(function() {\n self._resolve(response);\n });\n }\n },\n\n _resolve: function(response) {\n if (this._state !== DONE_COMPLETE_STATE) {\n forEach(this._doneCallbacks, function(fn) {\n fn(response);\n });\n this._doneCallbacks.length = 0;\n this._state = DONE_COMPLETE_STATE;\n }\n }\n };\n\n return AnimateRunner;\n }];\n};\n\n/* exported $CoreAnimateCssProvider */\n\n/**\n * @ngdoc service\n * @name $animateCss\n * @kind object\n * @this\n *\n * @description\n * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,\n * then the `$animateCss` service will actually perform animations.\n *\n * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.\n */\nvar $CoreAnimateCssProvider = function() {\n this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {\n\n return function(element, initialOptions) {\n // all of the animation functions should create\n // a copy of the options data, however, if a\n // parent service has already created a copy then\n // we should stick to using that\n var options = initialOptions || {};\n if (!options.$$prepared) {\n options = copy(options);\n }\n\n // there is no point in applying the styles since\n // there is no animation that goes on at all in\n // this version of $animateCss.\n if (options.cleanupStyles) {\n options.from = options.to = null;\n }\n\n if (options.from) {\n element.css(options.from);\n options.from = null;\n }\n\n var closed, runner = new $$AnimateRunner();\n return {\n start: run,\n end: run\n };\n\n function run() {\n $$rAF(function() {\n applyAnimationContents();\n if (!closed) {\n runner.complete();\n }\n closed = true;\n });\n return runner;\n }\n\n function applyAnimationContents() {\n if (options.addClass) {\n element.addClass(options.addClass);\n options.addClass = null;\n }\n if (options.removeClass) {\n element.removeClass(options.removeClass);\n options.removeClass = null;\n }\n if (options.to) {\n element.css(options.to);\n options.to = null;\n }\n }\n };\n }];\n};\n\n/* global getHash: true, stripHash: false */\n\nfunction getHash(url) {\n var index = url.indexOf('#');\n return index === -1 ? '' : url.substr(index);\n}\n\nfunction trimEmptyHash(url) {\n return url.replace(/#$/, '');\n}\n\n/**\n * ! This is a private undocumented service !\n *\n * @name $browser\n * @requires $log\n * @description\n * This object has two goals:\n *\n * - hide all the global state in the browser caused by the window object\n * - abstract away all the browser specific features and inconsistencies\n *\n * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`\n * service, which can be used for convenient testing of the application without the interaction with\n * the real browser apis.\n */\n/**\n * @param {object} window The global window object.\n * @param {object} document jQuery wrapped document.\n * @param {object} $log window.console or an object with the same interface.\n * @param {object} $sniffer $sniffer service\n */\nfunction Browser(window, document, $log, $sniffer, $$taskTrackerFactory) {\n var self = this,\n location = window.location,\n history = window.history,\n setTimeout = window.setTimeout,\n clearTimeout = window.clearTimeout,\n pendingDeferIds = {},\n taskTracker = $$taskTrackerFactory($log);\n\n self.isMock = false;\n\n //////////////////////////////////////////////////////////////\n // Task-tracking API\n //////////////////////////////////////////////////////////////\n\n // TODO(vojta): remove this temporary api\n self.$$completeOutstandingRequest = taskTracker.completeTask;\n self.$$incOutstandingRequestCount = taskTracker.incTaskCount;\n\n // TODO(vojta): prefix this method with $$ ?\n self.notifyWhenNoOutstandingRequests = taskTracker.notifyWhenNoPendingTasks;\n\n //////////////////////////////////////////////////////////////\n // URL API\n //////////////////////////////////////////////////////////////\n\n var cachedState, lastHistoryState,\n lastBrowserUrl = location.href,\n baseElement = document.find('base'),\n pendingLocation = null,\n getCurrentState = !$sniffer.history ? noop : function getCurrentState() {\n try {\n return history.state;\n } catch (e) {\n // MSIE can reportedly throw when there is no state (UNCONFIRMED).\n }\n };\n\n cacheState();\n\n /**\n * @name $browser#url\n *\n * @description\n * GETTER:\n * Without any argument, this method just returns current value of `location.href` (with a\n * trailing `#` stripped of if the hash is empty).\n *\n * SETTER:\n * With at least one argument, this method sets url to new value.\n * If html5 history api supported, `pushState`/`replaceState` is used, otherwise\n * `location.href`/`location.replace` is used.\n * Returns its own instance to allow chaining.\n *\n * NOTE: this api is intended for use only by the `$location` service. Please use the\n * {@link ng.$location $location service} to change url.\n *\n * @param {string} url New url (when used as setter)\n * @param {boolean=} replace Should new url replace current history record?\n * @param {object=} state State object to use with `pushState`/`replaceState`\n */\n self.url = function(url, replace, state) {\n // In modern browsers `history.state` is `null` by default; treating it separately\n // from `undefined` would cause `$browser.url('/foo')` to change `history.state`\n // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.\n if (isUndefined(state)) {\n state = null;\n }\n\n // Android Browser BFCache causes location, history reference to become stale.\n if (location !== window.location) location = window.location;\n if (history !== window.history) history = window.history;\n\n // setter\n if (url) {\n var sameState = lastHistoryState === state;\n\n // Normalize the inputted URL\n url = urlResolve(url).href;\n\n // Don't change anything if previous and current URLs and states match. This also prevents\n // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.\n // See https://github.com/angular/angular.js/commit/ffb2701\n if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {\n return self;\n }\n var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);\n lastBrowserUrl = url;\n lastHistoryState = state;\n // Don't use history API if only the hash changed\n // due to a bug in IE10/IE11 which leads\n // to not firing a `hashchange` nor `popstate` event\n // in some cases (see #9143).\n if ($sniffer.history && (!sameBase || !sameState)) {\n history[replace ? 'replaceState' : 'pushState'](state, '', url);\n cacheState();\n } else {\n if (!sameBase) {\n pendingLocation = url;\n }\n if (replace) {\n location.replace(url);\n } else if (!sameBase) {\n location.href = url;\n } else {\n location.hash = getHash(url);\n }\n if (location.href !== url) {\n pendingLocation = url;\n }\n }\n if (pendingLocation) {\n pendingLocation = url;\n }\n return self;\n // getter\n } else {\n // - pendingLocation is needed as browsers don't allow to read out\n // the new location.href if a reload happened or if there is a bug like in iOS 9 (see\n // https://openradar.appspot.com/22186109).\n return trimEmptyHash(pendingLocation || location.href);\n }\n };\n\n /**\n * @name $browser#state\n *\n * @description\n * This method is a getter.\n *\n * Return history.state or null if history.state is undefined.\n *\n * @returns {object} state\n */\n self.state = function() {\n return cachedState;\n };\n\n var urlChangeListeners = [],\n urlChangeInit = false;\n\n function cacheStateAndFireUrlChange() {\n pendingLocation = null;\n fireStateOrUrlChange();\n }\n\n // This variable should be used *only* inside the cacheState function.\n var lastCachedState = null;\n function cacheState() {\n // This should be the only place in $browser where `history.state` is read.\n cachedState = getCurrentState();\n cachedState = isUndefined(cachedState) ? null : cachedState;\n\n // Prevent callbacks fo fire twice if both hashchange & popstate were fired.\n if (equals(cachedState, lastCachedState)) {\n cachedState = lastCachedState;\n }\n\n lastCachedState = cachedState;\n lastHistoryState = cachedState;\n }\n\n function fireStateOrUrlChange() {\n var prevLastHistoryState = lastHistoryState;\n cacheState();\n\n if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) {\n return;\n }\n\n lastBrowserUrl = self.url();\n lastHistoryState = cachedState;\n forEach(urlChangeListeners, function(listener) {\n listener(self.url(), cachedState);\n });\n }\n\n /**\n * @name $browser#onUrlChange\n *\n * @description\n * Register callback function that will be called, when url changes.\n *\n * It's only called when the url is changed from outside of AngularJS:\n * - user types different url into address bar\n * - user clicks on history (forward/back) button\n * - user clicks on a link\n *\n * It's not called when url is changed by $browser.url() method\n *\n * The listener gets called with new url as parameter.\n *\n * NOTE: this api is intended for use only by the $location service. Please use the\n * {@link ng.$location $location service} to monitor url changes in AngularJS apps.\n *\n * @param {function(string)} listener Listener function to be called when url changes.\n * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.\n */\n self.onUrlChange = function(callback) {\n // TODO(vojta): refactor to use node's syntax for events\n if (!urlChangeInit) {\n // We listen on both (hashchange/popstate) when available, as some browsers don't\n // fire popstate when user changes the address bar and don't fire hashchange when url\n // changed by push/replaceState\n\n // html5 history api - popstate event\n if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);\n // hashchange event\n jqLite(window).on('hashchange', cacheStateAndFireUrlChange);\n\n urlChangeInit = true;\n }\n\n urlChangeListeners.push(callback);\n return callback;\n };\n\n /**\n * @private\n * Remove popstate and hashchange handler from window.\n *\n * NOTE: this api is intended for use only by $rootScope.\n */\n self.$$applicationDestroyed = function() {\n jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);\n };\n\n /**\n * Checks whether the url has changed outside of AngularJS.\n * Needs to be exported to be able to check for changes that have been done in sync,\n * as hashchange/popstate events fire in async.\n */\n self.$$checkUrlChange = fireStateOrUrlChange;\n\n //////////////////////////////////////////////////////////////\n // Misc API\n //////////////////////////////////////////////////////////////\n\n /**\n * @name $browser#baseHref\n *\n * @description\n * Returns current \n * (always relative - without domain)\n *\n * @returns {string} The current base href\n */\n self.baseHref = function() {\n var href = baseElement.attr('href');\n return href ? href.replace(/^(https?:)?\\/\\/[^/]*/, '') : '';\n };\n\n /**\n * @name $browser#defer\n * @param {function()} fn A function, who's execution should be deferred.\n * @param {number=} [delay=0] Number of milliseconds to defer the function execution.\n * @param {string=} [taskType=DEFAULT_TASK_TYPE] The type of task that is deferred.\n * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.\n *\n * @description\n * Executes a fn asynchronously via `setTimeout(fn, delay)`.\n *\n * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using\n * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed\n * via `$browser.defer.flush()`.\n *\n */\n self.defer = function(fn, delay, taskType) {\n var timeoutId;\n\n delay = delay || 0;\n taskType = taskType || taskTracker.DEFAULT_TASK_TYPE;\n\n taskTracker.incTaskCount(taskType);\n timeoutId = setTimeout(function() {\n delete pendingDeferIds[timeoutId];\n taskTracker.completeTask(fn, taskType);\n }, delay);\n pendingDeferIds[timeoutId] = taskType;\n\n return timeoutId;\n };\n\n\n /**\n * @name $browser#defer.cancel\n *\n * @description\n * Cancels a deferred task identified with `deferId`.\n *\n * @param {*} deferId Token returned by the `$browser.defer` function.\n * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully\n * canceled.\n */\n self.defer.cancel = function(deferId) {\n if (pendingDeferIds.hasOwnProperty(deferId)) {\n var taskType = pendingDeferIds[deferId];\n delete pendingDeferIds[deferId];\n clearTimeout(deferId);\n taskTracker.completeTask(noop, taskType);\n return true;\n }\n return false;\n };\n\n}\n\n/** @this */\nfunction $BrowserProvider() {\n this.$get = ['$window', '$log', '$sniffer', '$document', '$$taskTrackerFactory',\n function($window, $log, $sniffer, $document, $$taskTrackerFactory) {\n return new Browser($window, $document, $log, $sniffer, $$taskTrackerFactory);\n }];\n}\n\n/**\n * @ngdoc service\n * @name $cacheFactory\n * @this\n *\n * @description\n * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to\n * them.\n *\n * ```js\n *\n * var cache = $cacheFactory('cacheId');\n * expect($cacheFactory.get('cacheId')).toBe(cache);\n * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();\n *\n * cache.put(\"key\", \"value\");\n * cache.put(\"another key\", \"another value\");\n *\n * // We've specified no options on creation\n * expect(cache.info()).toEqual({id: 'cacheId', size: 2});\n *\n * ```\n *\n *\n * @param {string} cacheId Name or id of the newly created cache.\n * @param {object=} options Options object that specifies the cache behavior. Properties:\n *\n * - `{number=}` `capacity` — turns the cache into LRU cache.\n *\n * @returns {object} Newly created cache object with the following set of methods:\n *\n * - `{object}` `info()` — Returns id, size, and options of cache.\n * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns\n * it.\n * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.\n * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.\n * - `{void}` `removeAll()` — Removes all cached values.\n * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.\n *\n * @example\n \n \n
\n \n \n \n\n

Cached Values

\n
\n \n : \n \n
\n\n

Cache Info

\n
\n \n : \n \n
\n
\n
\n \n angular.module('cacheExampleApp', []).\n controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {\n $scope.keys = [];\n $scope.cache = $cacheFactory('cacheId');\n $scope.put = function(key, value) {\n if (angular.isUndefined($scope.cache.get(key))) {\n $scope.keys.push(key);\n }\n $scope.cache.put(key, angular.isUndefined(value) ? null : value);\n };\n }]);\n \n \n p {\n margin: 10px 0 3px;\n }\n \n
\n */\nfunction $CacheFactoryProvider() {\n\n this.$get = function() {\n var caches = {};\n\n function cacheFactory(cacheId, options) {\n if (cacheId in caches) {\n throw minErr('$cacheFactory')('iid', 'CacheId \\'{0}\\' is already taken!', cacheId);\n }\n\n var size = 0,\n stats = extend({}, options, {id: cacheId}),\n data = createMap(),\n capacity = (options && options.capacity) || Number.MAX_VALUE,\n lruHash = createMap(),\n freshEnd = null,\n staleEnd = null;\n\n /**\n * @ngdoc type\n * @name $cacheFactory.Cache\n *\n * @description\n * A cache object used to store and retrieve data, primarily used by\n * {@link $templateRequest $templateRequest} and the {@link ng.directive:script script}\n * directive to cache templates and other data.\n *\n * ```js\n * angular.module('superCache')\n * .factory('superCache', ['$cacheFactory', function($cacheFactory) {\n * return $cacheFactory('super-cache');\n * }]);\n * ```\n *\n * Example test:\n *\n * ```js\n * it('should behave like a cache', inject(function(superCache) {\n * superCache.put('key', 'value');\n * superCache.put('another key', 'another value');\n *\n * expect(superCache.info()).toEqual({\n * id: 'super-cache',\n * size: 2\n * });\n *\n * superCache.remove('another key');\n * expect(superCache.get('another key')).toBeUndefined();\n *\n * superCache.removeAll();\n * expect(superCache.info()).toEqual({\n * id: 'super-cache',\n * size: 0\n * });\n * }));\n * ```\n */\n return (caches[cacheId] = {\n\n /**\n * @ngdoc method\n * @name $cacheFactory.Cache#put\n * @kind function\n *\n * @description\n * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be\n * retrieved later, and incrementing the size of the cache if the key was not already\n * present in the cache. If behaving like an LRU cache, it will also remove stale\n * entries from the set.\n *\n * It will not insert undefined values into the cache.\n *\n * @param {string} key the key under which the cached data is stored.\n * @param {*} value the value to store alongside the key. If it is undefined, the key\n * will not be stored.\n * @returns {*} the value stored.\n */\n put: function(key, value) {\n if (isUndefined(value)) return;\n if (capacity < Number.MAX_VALUE) {\n var lruEntry = lruHash[key] || (lruHash[key] = {key: key});\n\n refresh(lruEntry);\n }\n\n if (!(key in data)) size++;\n data[key] = value;\n\n if (size > capacity) {\n this.remove(staleEnd.key);\n }\n\n return value;\n },\n\n /**\n * @ngdoc method\n * @name $cacheFactory.Cache#get\n * @kind function\n *\n * @description\n * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.\n *\n * @param {string} key the key of the data to be retrieved\n * @returns {*} the value stored.\n */\n get: function(key) {\n if (capacity < Number.MAX_VALUE) {\n var lruEntry = lruHash[key];\n\n if (!lruEntry) return;\n\n refresh(lruEntry);\n }\n\n return data[key];\n },\n\n\n /**\n * @ngdoc method\n * @name $cacheFactory.Cache#remove\n * @kind function\n *\n * @description\n * Removes an entry from the {@link $cacheFactory.Cache Cache} object.\n *\n * @param {string} key the key of the entry to be removed\n */\n remove: function(key) {\n if (capacity < Number.MAX_VALUE) {\n var lruEntry = lruHash[key];\n\n if (!lruEntry) return;\n\n if (lruEntry === freshEnd) freshEnd = lruEntry.p;\n if (lruEntry === staleEnd) staleEnd = lruEntry.n;\n link(lruEntry.n,lruEntry.p);\n\n delete lruHash[key];\n }\n\n if (!(key in data)) return;\n\n delete data[key];\n size--;\n },\n\n\n /**\n * @ngdoc method\n * @name $cacheFactory.Cache#removeAll\n * @kind function\n *\n * @description\n * Clears the cache object of any entries.\n */\n removeAll: function() {\n data = createMap();\n size = 0;\n lruHash = createMap();\n freshEnd = staleEnd = null;\n },\n\n\n /**\n * @ngdoc method\n * @name $cacheFactory.Cache#destroy\n * @kind function\n *\n * @description\n * Destroys the {@link $cacheFactory.Cache Cache} object entirely,\n * removing it from the {@link $cacheFactory $cacheFactory} set.\n */\n destroy: function() {\n data = null;\n stats = null;\n lruHash = null;\n delete caches[cacheId];\n },\n\n\n /**\n * @ngdoc method\n * @name $cacheFactory.Cache#info\n * @kind function\n *\n * @description\n * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.\n *\n * @returns {object} an object with the following properties:\n *
    \n *
  • **id**: the id of the cache instance
  • \n *
  • **size**: the number of entries kept in the cache instance
  • \n *
  • **...**: any additional properties from the options object when creating the\n * cache.
  • \n *
\n */\n info: function() {\n return extend({}, stats, {size: size});\n }\n });\n\n\n /**\n * makes the `entry` the freshEnd of the LRU linked list\n */\n function refresh(entry) {\n if (entry !== freshEnd) {\n if (!staleEnd) {\n staleEnd = entry;\n } else if (staleEnd === entry) {\n staleEnd = entry.n;\n }\n\n link(entry.n, entry.p);\n link(entry, freshEnd);\n freshEnd = entry;\n freshEnd.n = null;\n }\n }\n\n\n /**\n * bidirectionally links two entries of the LRU linked list\n */\n function link(nextEntry, prevEntry) {\n if (nextEntry !== prevEntry) {\n if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify\n if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify\n }\n }\n }\n\n\n /**\n * @ngdoc method\n * @name $cacheFactory#info\n *\n * @description\n * Get information about all the caches that have been created\n *\n * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`\n */\n cacheFactory.info = function() {\n var info = {};\n forEach(caches, function(cache, cacheId) {\n info[cacheId] = cache.info();\n });\n return info;\n };\n\n\n /**\n * @ngdoc method\n * @name $cacheFactory#get\n *\n * @description\n * Get access to a cache object by the `cacheId` used when it was created.\n *\n * @param {string} cacheId Name or id of a cache to access.\n * @returns {object} Cache object identified by the cacheId or undefined if no such cache.\n */\n cacheFactory.get = function(cacheId) {\n return caches[cacheId];\n };\n\n\n return cacheFactory;\n };\n}\n\n/**\n * @ngdoc service\n * @name $templateCache\n * @this\n *\n * @description\n * `$templateCache` is a {@link $cacheFactory.Cache Cache object} created by the\n * {@link ng.$cacheFactory $cacheFactory}.\n *\n * The first time a template is used, it is loaded in the template cache for quick retrieval. You\n * can load templates directly into the cache in a `script` tag, by using {@link $templateRequest},\n * or by consuming the `$templateCache` service directly.\n *\n * Adding via the `script` tag:\n *\n * ```html\n * \n * ```\n *\n * **Note:** the `script` tag containing the template does not need to be included in the `head` of\n * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (e.g.\n * element with {@link ngApp} attribute), otherwise the template will be ignored.\n *\n * Adding via the `$templateCache` service:\n *\n * ```js\n * var myApp = angular.module('myApp', []);\n * myApp.run(function($templateCache) {\n * $templateCache.put('templateId.html', 'This is the content of the template');\n * });\n * ```\n *\n * To retrieve the template later, simply use it in your component:\n * ```js\n * myApp.component('myComponent', {\n * templateUrl: 'templateId.html'\n * });\n * ```\n *\n * or get it via the `$templateCache` service:\n * ```js\n * $templateCache.get('templateId.html')\n * ```\n *\n */\nfunction $TemplateCacheProvider() {\n this.$get = ['$cacheFactory', function($cacheFactory) {\n return $cacheFactory('templates');\n }];\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Any commits to this file should be reviewed with security in mind. *\n * Changes to this file can potentially create security vulnerabilities. *\n * An approval from 2 Core members with history of modifying *\n * this file is required. *\n * *\n * Does the change somehow allow for arbitrary javascript to be executed? *\n * Or allows for someone to change the prototype of built-in objects? *\n * Or gives undesired access to variables like document or window? *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!\n *\n * DOM-related variables:\n *\n * - \"node\" - DOM Node\n * - \"element\" - DOM Element or Node\n * - \"$node\" or \"$element\" - jqLite-wrapped node or element\n *\n *\n * Compiler related stuff:\n *\n * - \"linkFn\" - linking fn of a single directive\n * - \"nodeLinkFn\" - function that aggregates all linking fns for a particular node\n * - \"childLinkFn\" - function that aggregates all linking fns for child nodes of a particular node\n * - \"compositeLinkFn\" - function that aggregates all linking fns for a compilation root (nodeList)\n */\n\n\n/**\n * @ngdoc service\n * @name $compile\n * @kind function\n *\n * @description\n * Compiles an HTML string or DOM into a template and produces a template function, which\n * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.\n *\n * The compilation is a process of walking the DOM tree and matching DOM elements to\n * {@link ng.$compileProvider#directive directives}.\n *\n *
\n * **Note:** This document is an in-depth reference of all directive options.\n * For a gentle introduction to directives with examples of common use cases,\n * see the {@link guide/directive directive guide}.\n *
\n *\n * ## Comprehensive Directive API\n *\n * There are many different options for a directive.\n *\n * The difference resides in the return value of the factory function.\n * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}\n * that defines the directive properties, or just the `postLink` function (all other properties will have\n * the default values).\n *\n *
\n * **Best Practice:** It's recommended to use the \"directive definition object\" form.\n *
\n *\n * Here's an example directive declared with a Directive Definition Object:\n *\n * ```js\n * var myModule = angular.module(...);\n *\n * myModule.directive('directiveName', function factory(injectables) {\n * var directiveDefinitionObject = {\n * {@link $compile#-priority- priority}: 0,\n * {@link $compile#-template- template}: '
', // or // function(tElement, tAttrs) { ... },\n * // or\n * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... },\n * {@link $compile#-transclude- transclude}: false,\n * {@link $compile#-restrict- restrict}: 'A',\n * {@link $compile#-templatenamespace- templateNamespace}: 'html',\n * {@link $compile#-scope- scope}: false,\n * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },\n * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier',\n * {@link $compile#-bindtocontroller- bindToController}: false,\n * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],\n * {@link $compile#-multielement- multiElement}: false,\n * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) {\n * return {\n * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },\n * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }\n * }\n * // or\n * // return function postLink( ... ) { ... }\n * },\n * // or\n * // {@link $compile#-link- link}: {\n * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },\n * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }\n * // }\n * // or\n * // {@link $compile#-link- link}: function postLink( ... ) { ... }\n * };\n * return directiveDefinitionObject;\n * });\n * ```\n *\n *
\n * **Note:** Any unspecified options will use the default value. You can see the default values below.\n *
\n *\n * Therefore the above can be simplified as:\n *\n * ```js\n * var myModule = angular.module(...);\n *\n * myModule.directive('directiveName', function factory(injectables) {\n * var directiveDefinitionObject = {\n * link: function postLink(scope, iElement, iAttrs) { ... }\n * };\n * return directiveDefinitionObject;\n * // or\n * // return function postLink(scope, iElement, iAttrs) { ... }\n * });\n * ```\n *\n * ### Life-cycle hooks\n * Directive controllers can provide the following methods that are called by AngularJS at points in the life-cycle of the\n * directive:\n * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and\n * had their bindings initialized (and before the pre & post linking functions for the directives on\n * this element). This is a good place to put initialization code for your controller.\n * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The\n * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an\n * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a\n * component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will\n * also be called when your bindings are initialized.\n * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on\n * changes. Any actions that you wish to take in response to the changes that you detect must be\n * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook\n * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not\n * be detected by AngularJS's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;\n * if detecting changes, you must store the previous value(s) for comparison to the current values.\n * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing\n * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in\n * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent\n * components will have their `$onDestroy()` hook called before child components.\n * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link\n * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.\n * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since\n * they are waiting for their template to load asynchronously and their own compilation and linking has been\n * suspended until that occurs.\n *\n * #### Comparison with life-cycle hooks in the new Angular\n * The new Angular also uses life-cycle hooks for its components. While the AngularJS life-cycle hooks are similar there are\n * some differences that you should be aware of, especially when it comes to moving your code from AngularJS to Angular:\n *\n * * AngularJS hooks are prefixed with `$`, such as `$onInit`. Angular hooks are prefixed with `ng`, such as `ngOnInit`.\n * * AngularJS hooks can be defined on the controller prototype or added to the controller inside its constructor.\n * In Angular you can only define hooks on the prototype of the Component class.\n * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in AngularJS than you would to\n * `ngDoCheck` in Angular.\n * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be\n * propagated throughout the application.\n * Angular does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an\n * error or do nothing depending upon the state of `enableProdMode()`.\n *\n * #### Life-cycle hook examples\n *\n * This example shows how you can check for mutations to a Date object even though the identity of the object\n * has not changed.\n *\n * \n * \n * angular.module('do-check-module', [])\n * .component('app', {\n * template:\n * 'Month: ' +\n * 'Date: {{ $ctrl.date }}' +\n * '',\n * controller: function() {\n * this.date = new Date();\n * this.month = this.date.getMonth();\n * this.updateDate = function() {\n * this.date.setMonth(this.month);\n * };\n * }\n * })\n * .component('test', {\n * bindings: { date: '<' },\n * template:\n * '
{{ $ctrl.log | json }}
',\n * controller: function() {\n * var previousValue;\n * this.log = [];\n * this.$doCheck = function() {\n * var currentValue = this.date && this.date.valueOf();\n * if (previousValue !== currentValue) {\n * this.log.push('doCheck: date mutated: ' + this.date);\n * previousValue = currentValue;\n * }\n * };\n * }\n * });\n *
\n * \n * \n * \n *
\n *\n * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the\n * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large\n * arrays or objects can have a negative impact on your application performance.)\n *\n * \n * \n *
\n * \n * \n *
{{ items }}
\n * \n *
\n *
\n * \n * angular.module('do-check-module', [])\n * .component('test', {\n * bindings: { items: '<' },\n * template:\n * '
{{ $ctrl.log | json }}
',\n * controller: function() {\n * this.log = [];\n *\n * this.$doCheck = function() {\n * if (this.items_ref !== this.items) {\n * this.log.push('doCheck: items changed');\n * this.items_ref = this.items;\n * }\n * if (!angular.equals(this.items_clone, this.items)) {\n * this.log.push('doCheck: items mutated');\n * this.items_clone = angular.copy(this.items);\n * }\n * };\n * }\n * });\n *
\n *
\n *\n *\n * ### Directive Definition Object\n *\n * The directive definition object provides instructions to the {@link ng.$compile\n * compiler}. The attributes are:\n *\n * #### `multiElement`\n * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between\n * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them\n * together as the directive elements. It is recommended that this feature be used on directives\n * which are not strictly behavioral (such as {@link ngClick}), and which\n * do not manipulate or replace child nodes (such as {@link ngInclude}).\n *\n * #### `priority`\n * When there are multiple directives defined on a single DOM element, sometimes it\n * is necessary to specify the order in which the directives are applied. The `priority` is used\n * to sort the directives before their `compile` functions get called. Priority is defined as a\n * number. Directives with greater numerical `priority` are compiled first. Pre-link functions\n * are also run in priority order, but post-link functions are run in reverse order. The order\n * of directives with the same priority is undefined. The default priority is `0`.\n *\n * #### `terminal`\n * If set to true then the current `priority` will be the last set of directives\n * which will execute (any directives at the current priority will still execute\n * as the order of execution on same `priority` is undefined). Note that expressions\n * and other directives used in the directive's template will also be excluded from execution.\n *\n * #### `scope`\n * The scope property can be `false`, `true`, or an object:\n *\n * * **`false` (default):** No scope will be created for the directive. The directive will use its\n * parent's scope.\n *\n * * **`true`:** A new child scope that prototypically inherits from its parent will be created for\n * the directive's element. If multiple directives on the same element request a new scope,\n * only one new scope is created.\n *\n * * **`{...}` (an object hash):** A new \"isolate\" scope is created for the directive's template.\n * The 'isolate' scope differs from normal scope in that it does not prototypically\n * inherit from its parent scope. This is useful when creating reusable components, which should not\n * accidentally read or modify data in the parent scope. Note that an isolate scope\n * directive without a `template` or `templateUrl` will not apply the isolate scope\n * to its children elements.\n *\n * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the\n * directive's element. These local properties are useful for aliasing values for templates. The keys in\n * the object hash map to the name of the property on the isolate scope; the values define how the property\n * is bound to the parent scope, via matching attributes on the directive's element:\n *\n * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is\n * always a string since DOM attributes are strings. If no `attr` name is specified then the\n * attribute name is assumed to be the same as the local name. Given `` and the isolate scope definition `scope: { localName:'@myAttr' }`,\n * the directive's scope property `localName` will reflect the interpolated value of `hello\n * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's\n * scope. The `name` is read from the parent scope (not the directive's scope).\n *\n * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression\n * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.\n * If no `attr` name is specified then the attribute name is assumed to be the same as the local\n * name. Given `` and the isolate scope definition `scope: {\n * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the\n * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in\n * `localModel` and vice versa. If the binding expression is non-assignable, or if the attribute\n * isn't optional and doesn't exist, an exception\n * ({@link error/$compile/nonassign `$compile:nonassign`}) will be thrown upon discovering changes\n * to the local value, since it will be impossible to sync them back to the parent scope.\n *\n * By default, the {@link ng.$rootScope.Scope#$watch `$watch`}\n * method is used for tracking changes, and the equality check is based on object identity.\n * However, if an object literal or an array literal is passed as the binding expression, the\n * equality check is done by value (using the {@link angular.equals} function). It's also possible\n * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection\n * `$watchCollection`}: use `=*` or `=*attr`\n *\n * * `<` or `` and directive definition of\n * `scope: { localModel:'` and the isolate scope definition `scope: {\n * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for\n * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope\n * via an expression to the parent scope. This can be done by passing a map of local variable names\n * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`\n * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.\n *\n * All 4 kinds of bindings (`@`, `=`, `<`, and `&`) can be made optional by adding `?` to the expression.\n * The marker must come after the mode and before the attribute name.\n * See the {@link error/$compile/iscp Invalid Isolate Scope Definition error} for definition examples.\n * This is useful to refine the interface directives provide.\n * One subtle difference between optional and non-optional happens **when the binding attribute is not\n * set**:\n * - the binding is optional: the property will not be defined\n * - the binding is not optional: the property is defined\n *\n * ```js\n *app.directive('testDir', function() {\n return {\n scope: {\n notoptional: '=',\n optional: '=?',\n },\n bindToController: true,\n controller: function() {\n this.$onInit = function() {\n console.log(this.hasOwnProperty('notoptional')) // true\n console.log(this.hasOwnProperty('optional')) // false\n }\n }\n }\n })\n *```\n *\n *\n * ##### Combining directives with different scope defintions\n *\n * In general it's possible to apply more than one directive to one element, but there might be limitations\n * depending on the type of scope required by the directives. The following points will help explain these limitations.\n * For simplicity only two directives are taken into account, but it is also applicable for several directives:\n *\n * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope\n * * **child scope** + **no scope** => Both directives will share one single child scope\n * * **child scope** + **child scope** => Both directives will share one single child scope\n * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use\n * its parent's scope\n * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot\n * be applied to the same element.\n * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives\n * cannot be applied to the same element.\n *\n *\n * #### `bindToController`\n * This property is used to bind scope properties directly to the controller. It can be either\n * `true` or an object hash with the same format as the `scope` property.\n *\n * When an isolate scope is used for a directive (see above), `bindToController: true` will\n * allow a component to have its properties bound to the controller, rather than to scope.\n *\n * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller\n * properties. You can access these bindings once they have been initialized by providing a controller method called\n * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings\n * initialized.\n *\n * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.\n * This will set up the scope bindings to the controller directly. Note that `scope` can still be used\n * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate\n * scope (useful for component directives).\n *\n * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.\n *\n *\n * #### `controller`\n * Controller constructor function. The controller is instantiated before the\n * pre-linking phase and can be accessed by other directives (see\n * `require` attribute). This allows the directives to communicate with each other and augment\n * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:\n *\n * * `$scope` - Current scope associated with the element\n * * `$element` - Current element\n * * `$attrs` - Current attributes object for the element\n * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:\n * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:\n * * `scope`: (optional) override the scope.\n * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.\n * * `futureParentElement` (optional):\n * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.\n * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.\n * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)\n * and when the `cloneLinkingFn` is passed,\n * as those elements need to created and cloned in a special way when they are defined outside their\n * usual containers (e.g. like ``).\n * * See also the `directive.templateNamespace` property.\n * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)\n * then the default transclusion is provided.\n * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns\n * `true` if the specified slot contains content (i.e. one or more DOM nodes).\n *\n * #### `require`\n * Require another directive and inject its controller as the fourth argument to the linking function. The\n * `require` property can be a string, an array or an object:\n * * a **string** containing the name of the directive to pass to the linking function\n * * an **array** containing the names of directives to pass to the linking function. The argument passed to the\n * linking function will be an array of controllers in the same order as the names in the `require` property\n * * an **object** whose property values are the names of the directives to pass to the linking function. The argument\n * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding\n * controllers.\n *\n * If the `require` property is an object and `bindToController` is truthy, then the required controllers are\n * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers\n * have been constructed but before `$onInit` is called.\n * If the name of the required controller is the same as the local name (the key), the name can be\n * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.\n * See the {@link $compileProvider#component} helper for an example of how this can be used.\n * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is\n * raised (unless no link function is specified and the required controllers are not being bound to the directive\n * controller, in which case error checking is skipped). The name can be prefixed with:\n *\n * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.\n * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.\n * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.\n * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.\n * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass\n * `null` to the `link` fn if not found.\n * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass\n * `null` to the `link` fn if not found.\n *\n *\n * #### `controllerAs`\n * Identifier name for a reference to the controller in the directive's scope.\n * This allows the controller to be referenced from the directive template. This is especially\n * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible\n * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the\n * `controllerAs` reference might overwrite a property that already exists on the parent scope.\n *\n *\n * #### `restrict`\n * String of subset of `EACM` which restricts the directive to a specific directive\n * declaration style. If omitted, the defaults (elements and attributes) are used.\n *\n * * `E` - Element name (default): ``\n * * `A` - Attribute (default): `
`\n * * `C` - Class: `
`\n * * `M` - Comment: ``\n *\n *\n * #### `templateNamespace`\n * String representing the document type used by the markup in the template.\n * AngularJS needs this information as those elements need to be created and cloned\n * in a special way when they are defined outside their usual containers like `` and ``.\n *\n * * `html` - All root nodes in the template are HTML. Root nodes may also be\n * top-level elements such as `` or ``.\n * * `svg` - The root nodes in the template are SVG elements (excluding ``).\n * * `math` - The root nodes in the template are MathML elements (excluding ``).\n *\n * If no `templateNamespace` is specified, then the namespace is considered to be `html`.\n *\n * #### `template`\n * HTML markup that may:\n * * Replace the contents of the directive's element (default).\n * * Replace the directive's element itself (if `replace` is true - DEPRECATED).\n * * Wrap the contents of the directive's element (if `transclude` is true).\n *\n * Value may be:\n *\n * * A string. For example `
{{delete_str}}
`.\n * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`\n * function api below) and returns a string value.\n *\n *\n * #### `templateUrl`\n * This is similar to `template` but the template is loaded from the specified URL, asynchronously.\n *\n * Because template loading is asynchronous the compiler will suspend compilation of directives on that element\n * for later when the template has been resolved. In the meantime it will continue to compile and link\n * sibling and parent elements as though this element had not contained any directives.\n *\n * The compiler does not suspend the entire compilation to wait for templates to be loaded because this\n * would result in the whole app \"stalling\" until all templates are loaded asynchronously - even in the\n * case when only one deeply nested directive has `templateUrl`.\n *\n * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}.\n *\n * You can specify `templateUrl` as a string representing the URL or as a function which takes two\n * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns\n * a string value representing the url. In either case, the template URL is passed through {@link\n * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.\n *\n *\n * #### `replace`\n *
\n * **Note:** `replace` is deprecated in AngularJS and has been removed in the new Angular (v2+).\n *
\n *\n * Specifies what the template should replace. Defaults to `false`.\n *\n * * `true` - the template will replace the directive's element.\n * * `false` - the template will replace the contents of the directive's element.\n *\n * The replacement process migrates all of the attributes / classes from the old element to the new\n * one. See the {@link guide/directive#template-expanding-directive\n * Directives Guide} for an example.\n *\n * There are very few scenarios where element replacement is required for the application function,\n * the main one being reusable custom components that are used within SVG contexts\n * (because SVG doesn't work with custom elements in the DOM tree).\n *\n * #### `transclude`\n * Extract the contents of the element where the directive appears and make it available to the directive.\n * The contents are compiled and provided to the directive as a **transclusion function**. See the\n * {@link $compile#transclusion Transclusion} section below.\n *\n *\n * #### `compile`\n *\n * ```js\n * function compile(tElement, tAttrs, transclude) { ... }\n * ```\n *\n * The compile function deals with transforming the template DOM. Since most directives do not do\n * template transformation, it is not used often. The compile function takes the following arguments:\n *\n * * `tElement` - template element - The element where the directive has been declared. It is\n * safe to do template transformation on the element and child elements only.\n *\n * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared\n * between all directive compile functions.\n *\n * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`\n *\n *
\n * **Note:** The template instance and the link instance may be different objects if the template has\n * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that\n * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration\n * should be done in a linking function rather than in a compile function.\n *
\n\n *
\n * **Note:** The compile function cannot handle directives that recursively use themselves in their\n * own templates or compile functions. Compiling these directives results in an infinite loop and\n * stack overflow errors.\n *\n * This can be avoided by manually using `$compile` in the postLink function to imperatively compile\n * a directive's template instead of relying on automatic template compilation via `template` or\n * `templateUrl` declaration or manual compilation inside the compile function.\n *
\n *\n *
\n * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it\n * e.g. does not know about the right outer scope. Please use the transclude function that is passed\n * to the link function instead.\n *
\n\n * A compile function can have a return value which can be either a function or an object.\n *\n * * returning a (post-link) function - is equivalent to registering the linking function via the\n * `link` property of the config object when the compile function is empty.\n *\n * * returning an object with function(s) registered via `pre` and `post` properties - allows you to\n * control when a linking function should be called during the linking phase. See info about\n * pre-linking and post-linking functions below.\n *\n *\n * #### `link`\n * This property is used only if the `compile` property is not defined.\n *\n * ```js\n * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }\n * ```\n *\n * The link function is responsible for registering DOM listeners as well as updating the DOM. It is\n * executed after the template has been cloned. This is where most of the directive logic will be\n * put.\n *\n * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the\n * directive for registering {@link ng.$rootScope.Scope#$watch watches}.\n *\n * * `iElement` - instance element - The element where the directive is to be used. It is safe to\n * manipulate the children of the element only in `postLink` function since the children have\n * already been linked.\n *\n * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared\n * between all directive linking functions.\n *\n * * `controller` - the directive's required controller instance(s) - Instances are shared\n * among all directives, which allows the directives to use the controllers as a communication\n * channel. The exact value depends on the directive's `require` property:\n * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one\n * * `string`: the controller instance\n * * `array`: array of controller instances\n *\n * If a required controller cannot be found, and it is optional, the instance is `null`,\n * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.\n *\n * Note that you can also require the directive's own controller - it will be made available like\n * any other controller.\n *\n * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.\n * This is the same as the `$transclude` parameter of directive controllers,\n * see {@link ng.$compile#-controller- the controller section for details}.\n * `function([scope], cloneLinkingFn, futureParentElement)`.\n *\n * #### Pre-linking function\n *\n * Executed before the child elements are linked. Not safe to do DOM transformation since the\n * compiler linking function will fail to locate the correct elements for linking.\n *\n * #### Post-linking function\n *\n * Executed after the child elements are linked.\n *\n * Note that child elements that contain `templateUrl` directives will not have been compiled\n * and linked since they are waiting for their template to load asynchronously and their own\n * compilation and linking has been suspended until that occurs.\n *\n * It is safe to do DOM transformation in the post-linking function on elements that are not waiting\n * for their async templates to be resolved.\n *\n *\n * ### Transclusion\n *\n * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and\n * copying them to another part of the DOM, while maintaining their connection to the original AngularJS\n * scope from where they were taken.\n *\n * Transclusion is used (often with {@link ngTransclude}) to insert the\n * original contents of a directive's element into a specified place in the template of the directive.\n * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded\n * content has access to the properties on the scope from which it was taken, even if the directive\n * has isolated scope.\n * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.\n *\n * This makes it possible for the widget to have private state for its template, while the transcluded\n * content has access to its originating scope.\n *\n *
\n * **Note:** When testing an element transclude directive you must not place the directive at the root of the\n * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives\n * Testing Transclusion Directives}.\n *
\n *\n * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the\n * directive's element, the entire element or multiple parts of the element contents:\n *\n * * `true` - transclude the content (i.e. the child nodes) of the directive's element.\n * * `'element'` - transclude the whole of the directive's element including any directives on this\n * element that are defined at a lower priority than this directive. When used, the `template`\n * property is ignored.\n * * **`{...}` (an object hash):** - map elements of the content onto transclusion \"slots\" in the template.\n *\n * **Multi-slot transclusion** is declared by providing an object for the `transclude` property.\n *\n * This object is a map where the keys are the name of the slot to fill and the value is an element selector\n * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)\n * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).\n *\n * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}.\n *\n * If the element selector is prefixed with a `?` then that slot is optional.\n *\n * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `` elements to\n * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.\n *\n * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements\n * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call\n * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and\n * injectable into the directive's controller.\n *\n *\n * #### Transclusion Functions\n *\n * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion\n * function** to the directive's `link` function and `controller`. This transclusion function is a special\n * **linking function** that will return the compiled contents linked to a new transclusion scope.\n *\n *
\n * If you are just using {@link ngTransclude} then you don't need to worry about this function, since\n * ngTransclude will deal with it for us.\n *
\n *\n * If you want to manually control the insertion and removal of the transcluded content in your directive\n * then you must use this transclude function. When you call a transclude function it returns a jqLite/JQuery\n * object that contains the compiled DOM, which is linked to the correct transclusion scope.\n *\n * When you call a transclusion function you can pass in a **clone attach function**. This function accepts\n * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded\n * content and the `scope` is the newly created transclusion scope, which the clone will be linked to.\n *\n *
\n * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function\n * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.\n *
\n *\n * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone\n * attach function**:\n *\n * ```js\n * var transcludedContent, transclusionScope;\n *\n * $transclude(function(clone, scope) {\n * element.append(clone);\n * transcludedContent = clone;\n * transclusionScope = scope;\n * });\n * ```\n *\n * Later, if you want to remove the transcluded content from your DOM then you should also destroy the\n * associated transclusion scope:\n *\n * ```js\n * transcludedContent.remove();\n * transclusionScope.$destroy();\n * ```\n *\n *
\n * **Best Practice**: if you intend to add and remove transcluded content manually in your directive\n * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),\n * then you are also responsible for calling `$destroy` on the transclusion scope.\n *
\n *\n * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}\n * automatically destroy their transcluded clones as necessary so you do not need to worry about this if\n * you are simply using {@link ngTransclude} to inject the transclusion into your directive.\n *\n *\n * #### Transclusion Scopes\n *\n * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion\n * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed\n * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it\n * was taken.\n *\n * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look\n * like this:\n *\n * ```html\n *
\n *
\n *
\n *
\n *
\n *
\n * ```\n *\n * The `$parent` scope hierarchy will look like this:\n *\n ```\n - $rootScope\n - isolate\n - transclusion\n ```\n *\n * but the scopes will inherit prototypically from different scopes to their `$parent`.\n *\n ```\n - $rootScope\n - transclusion\n - isolate\n ```\n *\n *\n * ### Attributes\n *\n * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the\n * `link()` or `compile()` functions. It has a variety of uses.\n *\n * * *Accessing normalized attribute names:* Directives like `ngBind` can be expressed in many ways:\n * `ng:bind`, `data-ng-bind`, or `x-ng-bind`. The attributes object allows for normalized access\n * to the attributes.\n *\n * * *Directive inter-communication:* All directives share the same instance of the attributes\n * object which allows the directives to use the attributes object as inter directive\n * communication.\n *\n * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object\n * allowing other directives to read the interpolated value.\n *\n * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes\n * that contain interpolation (e.g. `src=\"{{bar}}\"`). Not only is this very efficient but it's also\n * the only way to easily get the actual value because during the linking phase the interpolation\n * hasn't been evaluated yet and so the value is at this time set to `undefined`.\n *\n * ```js\n * function linkingFn(scope, elm, attrs, ctrl) {\n * // get the attribute value\n * console.log(attrs.ngModel);\n *\n * // change the attribute\n * attrs.$set('ngModel', 'new value');\n *\n * // observe changes to interpolated attribute\n * attrs.$observe('ngModel', function(value) {\n * console.log('ngModel has changed value to ' + value);\n * });\n * }\n * ```\n *\n * ## Example\n *\n *
\n * **Note**: Typically directives are registered with `module.directive`. The example below is\n * to illustrate how `$compile` works.\n *
\n *\n \n \n \n
\n
\n
\n
\n
\n
\n \n it('should auto compile', function() {\n var textarea = $('textarea');\n var output = $('div[compile]');\n // The initial state reads 'Hello AngularJS'.\n expect(output.getText()).toBe('Hello AngularJS');\n textarea.clear();\n textarea.sendKeys('{{name}}!');\n expect(output.getText()).toBe('AngularJS!');\n });\n \n
\n\n *\n *\n * @param {string|DOMElement} element Element or HTML string to compile into a template function.\n * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.\n *\n *
\n * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it\n * e.g. will not use the right outer scope. Please pass the transclude function as a\n * `parentBoundTranscludeFn` to the link function instead.\n *
\n *\n * @param {number} maxPriority only apply directives lower than given priority (Only effects the\n * root element(s), not their children)\n * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template\n * (a DOM element/tree) to a scope. Where:\n *\n * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.\n * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the\n * `template` and call the `cloneAttachFn` function allowing the caller to attach the\n * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is\n * called as:
`cloneAttachFn(clonedElement, scope)` where:\n *\n * * `clonedElement` - is a clone of the original `element` passed into the compiler.\n * * `scope` - is the current scope with which the linking function is working with.\n *\n * * `options` - An optional object hash with linking options. If `options` is provided, then the following\n * keys may be used to control linking behavior:\n *\n * * `parentBoundTranscludeFn` - the transclude function made available to\n * directives; if given, it will be passed through to the link functions of\n * directives found in `element` during compilation.\n * * `transcludeControllers` - an object hash with keys that map controller names\n * to a hash with the key `instance`, which maps to the controller instance;\n * if given, it will make the controllers available to directives on the compileNode:\n * ```\n * {\n * parent: {\n * instance: parentControllerInstance\n * }\n * }\n * ```\n * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add\n * the cloned elements; only needed for transcludes that are allowed to contain non HTML\n * elements (e.g. SVG elements). See also the `directive.controller` property.\n *\n * Calling the linking function returns the element of the template. It is either the original\n * element passed in, or the clone of the element if the `cloneAttachFn` is provided.\n *\n * After linking the view is not updated until after a call to `$digest`, which typically is done by\n * AngularJS automatically.\n *\n * If you need access to the bound view, there are two ways to do it:\n *\n * - If you are not asking the linking function to clone the template, create the DOM element(s)\n * before you send them to the compiler and keep this reference around.\n * ```js\n * var element = angular.element('

{{total}}

');\n * $compile(element)(scope);\n * ```\n *\n * - if on the other hand, you need the element to be cloned, the view reference from the original\n * example would not point to the clone, but rather to the original template that was cloned. In\n * this case, you can access the clone either via the `cloneAttachFn` or the value returned by the\n * linking function:\n * ```js\n * var templateElement = angular.element('

{{total}}

');\n * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {\n * // Attach the clone to DOM document at the right place.\n * });\n *\n * // Now we have reference to the cloned DOM via `clonedElement`.\n * // NOTE: The `clonedElement` returned by the linking function is the same as the\n * // `clonedElement` passed to `cloneAttachFn`.\n * ```\n *\n *\n * For information on how the compiler works, see the\n * {@link guide/compiler AngularJS HTML Compiler} section of the Developer Guide.\n *\n * @knownIssue\n *\n * ### Double Compilation\n *\n Double compilation occurs when an already compiled part of the DOM gets\n compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues,\n and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it\n section on double compilation} for an in-depth explanation and ways to avoid it.\n\n * @knownIssue\n\n ### Issues with `replace: true`\n *\n *
\n * **Note**: {@link $compile#-replace- `replace: true`} is deprecated and not recommended to use,\n * mainly due to the issues listed here. It has been completely removed in the new Angular.\n *
\n *\n * #### Attribute values are not merged\n *\n * When a `replace` directive encounters the same attribute on the original and the replace node,\n * it will simply deduplicate the attribute and join the values with a space or with a `;` in case of\n * the `style` attribute.\n * ```html\n * Original Node: \n * Replace Template: \n * Result: \n * ```\n *\n * That means attributes that contain AngularJS expressions will not be merged correctly, e.g.\n * {@link ngShow} or {@link ngClass} will cause a {@link $parse} error:\n *\n * ```html\n * Original Node: \n * Replace Template: \n * Result: \n * ```\n *\n * See issue [#5695](https://github.com/angular/angular.js/issues/5695).\n *\n * #### Directives are not deduplicated before compilation\n *\n * When the original node and the replace template declare the same directive(s), they will be\n * {@link guide/compiler#double-compilation-and-how-to-avoid-it compiled twice} because the compiler\n * does not deduplicate them. In many cases, this is not noticeable, but e.g. {@link ngModel} will\n * attach `$formatters` and `$parsers` twice.\n *\n * See issue [#2573](https://github.com/angular/angular.js/issues/2573).\n *\n * #### `transclude: element` in the replace template root can have unexpected effects\n *\n * When the replace template has a directive at the root node that uses\n * {@link $compile#-transclude- `transclude: element`}, e.g.\n * {@link ngIf} or {@link ngRepeat}, the DOM structure or scope inheritance can be incorrect.\n * See the following issues:\n *\n * - Incorrect scope on replaced element:\n * [#9837](https://github.com/angular/angular.js/issues/9837)\n * - Different DOM between `template` and `templateUrl`:\n * [#10612](https://github.com/angular/angular.js/issues/14326)\n *\n */\n\n/**\n * @ngdoc directive\n * @name ngProp\n * @restrict A\n * @element ANY\n *\n * @usage\n *\n * ```html\n * \n * \n * ```\n *\n * or with uppercase letters in property (e.g. \"propName\"):\n *\n *\n * ```html\n * \n * \n * ```\n *\n *\n * @description\n * The `ngProp` directive binds an expression to a DOM element property.\n * `ngProp` allows writing to arbitrary properties by including\n * the property name in the attribute, e.g. `ng-prop-value=\"'my value'\"` binds 'my value' to\n * the `value` property.\n *\n * Usually, it's not necessary to write to properties in AngularJS, as the built-in directives\n * handle the most common use cases (instead of the above example, you would use {@link ngValue}).\n *\n * However, [custom elements](https://developer.mozilla.org/docs/Web/Web_Components/Using_custom_elements)\n * often use custom properties to hold data, and `ngProp` can be used to provide input to these\n * custom elements.\n *\n * ## Binding to camelCase properties\n *\n * Since HTML attributes are case-insensitive, camelCase properties like `innerHTML` must be escaped.\n * AngularJS uses the underscore (_) in front of a character to indicate that it is uppercase, so\n * `innerHTML` must be written as `ng-prop-inner_h_t_m_l=\"expression\"` (Note that this is just an\n * example, and for binding HTML {@link ngBindHtml} should be used.\n *\n * ## Security\n *\n * Binding expressions to arbitrary properties poses a security risk, as properties like `innerHTML`\n * can insert potentially dangerous HTML into the application, e.g. script tags that execute\n * malicious code.\n * For this reason, `ngProp` applies Strict Contextual Escaping with the {@link ng.$sce $sce service}.\n * This means vulnerable properties require their content to be \"trusted\", based on the\n * context of the property. For example, the `innerHTML` is in the `HTML` context, and the\n * `iframe.src` property is in the `RESOURCE_URL` context, which requires that values written to\n * this property are trusted as a `RESOURCE_URL`.\n *\n * This can be set explicitly by calling $sce.trustAs(type, value) on the value that is\n * trusted before passing it to the `ng-prop-*` directive. There are exist shorthand methods for\n * each context type in the form of {@link ng.$sce#trustAsResourceUrl $sce.trustAsResourceUrl()} et al.\n *\n * In some cases you can also rely upon automatic sanitization of untrusted values - see below.\n *\n * Based on the context, other options may exist to mark a value as trusted / configure the behavior\n * of {@link ng.$sce}. For example, to restrict the `RESOURCE_URL` context to specific origins, use\n * the {@link $sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist()}\n * and {@link $sceDelegateProvider#resourceUrlBlacklist resourceUrlBlacklist()}.\n *\n * {@link ng.$sce#what-trusted-context-types-are-supported- Find out more about the different context types}.\n *\n * ### HTML Sanitization\n *\n * By default, `$sce` will throw an error if it detects untrusted HTML content, and will not bind the\n * content.\n * However, if you include the {@link ngSanitize ngSanitize module}, it will try to sanitize the\n * potentially dangerous HTML, e.g. strip non-whitelisted tags and attributes when binding to\n * `innerHTML`.\n *\n * @example\n * ### Binding to different contexts\n *\n * \n * \n * angular.module('exampleNgProp', [])\n * .component('main', {\n * templateUrl: 'main.html',\n * controller: function($sce) {\n * this.safeContent = 'Safe content';\n * this.unsafeContent = '';\n * this.trustedUnsafeContent = $sce.trustAsHtml(this.unsafeContent);\n * }\n * });\n * \n * \n *
\n *
\n * Binding to a property without security context:\n *
\n * innerText (safeContent)\n *
\n *\n *
\n * \"Safe\" content that requires a security context will throw because the contents could potentially be dangerous ...\n *
\n * innerHTML (safeContent)\n *
\n *\n *
\n * ... so that actually dangerous content cannot be executed:\n *
\n * innerHTML (unsafeContent)\n *
\n *\n *
\n * ... but unsafe Content that has been trusted explicitly works - only do this if you are 100% sure!\n *
\n * innerHTML (trustedUnsafeContent)\n *
\n *
\n *
\n * \n *
\n *
\n * \n * .prop-unit {\n * margin-bottom: 10px;\n * }\n *\n * .prop-binding {\n * min-height: 30px;\n * border: 1px solid blue;\n * }\n *\n * .prop-note {\n * font-family: Monospace;\n * }\n * \n *
\n *\n *\n * @example\n * ### Binding to innerHTML with ngSanitize\n *\n * \n * \n * angular.module('exampleNgProp', ['ngSanitize'])\n * .component('main', {\n * templateUrl: 'main.html',\n * controller: function($sce) {\n * this.safeContent = 'Safe content';\n * this.unsafeContent = '';\n * this.trustedUnsafeContent = $sce.trustAsHtml(this.unsafeContent);\n * }\n * });\n * \n * \n *
\n *
\n * \"Safe\" content will be sanitized ...\n *
\n * innerHTML (safeContent)\n *
\n *\n *
\n * ... as will dangerous content:\n *
\n * innerHTML (unsafeContent)\n *
\n *\n *
\n * ... and content that has been trusted explicitly works the same as without ngSanitize:\n *
\n * innerHTML (trustedUnsafeContent)\n *
\n *
\n *
\n * \n *
\n *
\n * \n * .prop-unit {\n * margin-bottom: 10px;\n * }\n *\n * .prop-binding {\n * min-height: 30px;\n * border: 1px solid blue;\n * }\n *\n * .prop-note {\n * font-family: Monospace;\n * }\n * \n *
\n *\n */\n\n/** @ngdoc directive\n * @name ngOn\n * @restrict A\n * @element ANY\n *\n * @usage\n *\n * ```html\n * \n * \n * ```\n *\n * or with uppercase letters in property (e.g. \"eventName\"):\n *\n *\n * ```html\n * \n * \n * ```\n *\n * @description\n * The `ngOn` directive adds an event listener to a DOM element via\n * {@link angular.element angular.element().on()}, and evaluates an expression when the event is\n * fired.\n * `ngOn` allows adding listeners for arbitrary events by including\n * the event name in the attribute, e.g. `ng-on-drop=\"onDrop()\"` executes the 'onDrop()' expression\n * when the `drop` event is fired.\n *\n * AngularJS provides specific directives for many events, such as {@link ngClick}, so in most\n * cases it is not necessary to use `ngOn`. However, AngularJS does not support all events\n * (e.g. the `drop` event in the example above), and new events might be introduced in later DOM\n * standards.\n *\n * Another use-case for `ngOn` is listening to\n * [custom events](https://developer.mozilla.org/docs/Web/Guide/Events/Creating_and_triggering_events)\n * fired by\n * [custom elements](https://developer.mozilla.org/docs/Web/Web_Components/Using_custom_elements).\n *\n * ## Binding to camelCase properties\n *\n * Since HTML attributes are case-insensitive, camelCase properties like `myEvent` must be escaped.\n * AngularJS uses the underscore (_) in front of a character to indicate that it is uppercase, so\n * `myEvent` must be written as `ng-on-my_event=\"expression\"`.\n *\n * @example\n * ### Bind to built-in DOM events\n *\n * \n * \n * angular.module('exampleNgOn', [])\n * .component('main', {\n * templateUrl: 'main.html',\n * controller: function() {\n * this.clickCount = 0;\n * this.mouseoverCount = 0;\n *\n * this.loadingState = 0;\n * }\n * });\n * \n * \n *
\n * This is equivalent to `ngClick` and `ngMouseover`:
\n * Click or mouseover
\n * clickCount: {{$ctrl.clickCount}}
\n * mouseover: {{$ctrl.mouseoverCount}}\n *\n *
\n *\n * For the `error` and `load` event on images no built-in AngularJS directives exist:
\n *
\n *
\n * Image is loading\n * Image load error\n * Image loaded successfully\n *
\n *
\n *
\n * \n *
\n *
\n *
\n *\n *\n * @example\n * ### Bind to custom DOM events\n *\n * \n * \n * angular.module('exampleNgOn', [])\n * .component('main', {\n * templateUrl: 'main.html',\n * controller: function() {\n * this.eventLog = '';\n *\n * this.listener = function($event) {\n * this.eventLog = 'Event with type \"' + $event.type + '\" fired at ' + $event.detail;\n * };\n * }\n * })\n * .component('childComponent', {\n * templateUrl: 'child.html',\n * controller: function($element) {\n * this.fireEvent = function() {\n * var event = new CustomEvent('customtype', { detail: new Date()});\n *\n * $element[0].dispatchEvent(event);\n * };\n * }\n * });\n * \n * \n *
\n * Event log: {{$ctrl.eventLog}}\n *
\n * \n \n * \n * \n *
\n *
\n *
\n */\n\nvar $compileMinErr = minErr('$compile');\n\nfunction UNINITIALIZED_VALUE() {}\nvar _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();\n\n/**\n * @ngdoc provider\n * @name $compileProvider\n *\n * @description\n */\n$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];\n/** @this */\nfunction $CompileProvider($provide, $$sanitizeUriProvider) {\n var hasDirectives = {},\n Suffix = 'Directive',\n COMMENT_DIRECTIVE_REGEXP = /^\\s*directive:\\s*([\\w-]+)\\s+(.*)$/,\n CLASS_DIRECTIVE_REGEXP = /(([\\w-]+)(?::([^;]+))?;?)/,\n ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),\n REQUIRE_PREFIX_REGEXP = /^(?:(\\^\\^?)?(\\?)?(\\^\\^?)?)?/;\n\n // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes\n // The assumption is that future DOM event attribute names will begin with\n // 'on' and be composed of only English letters.\n var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;\n var bindingCache = createMap();\n\n function parseIsolateBindings(scope, directiveName, isController) {\n var LOCAL_REGEXP = /^([@&]|[=<](\\*?))(\\??)\\s*([\\w$]*)$/;\n\n var bindings = createMap();\n\n forEach(scope, function(definition, scopeName) {\n definition = definition.trim();\n\n if (definition in bindingCache) {\n bindings[scopeName] = bindingCache[definition];\n return;\n }\n var match = definition.match(LOCAL_REGEXP);\n\n if (!match) {\n throw $compileMinErr('iscp',\n 'Invalid {3} for directive \\'{0}\\'.' +\n ' Definition: {... {1}: \\'{2}\\' ...}',\n directiveName, scopeName, definition,\n (isController ? 'controller bindings definition' :\n 'isolate scope definition'));\n }\n\n bindings[scopeName] = {\n mode: match[1][0],\n collection: match[2] === '*',\n optional: match[3] === '?',\n attrName: match[4] || scopeName\n };\n if (match[4]) {\n bindingCache[definition] = bindings[scopeName];\n }\n });\n\n return bindings;\n }\n\n function parseDirectiveBindings(directive, directiveName) {\n var bindings = {\n isolateScope: null,\n bindToController: null\n };\n if (isObject(directive.scope)) {\n if (directive.bindToController === true) {\n bindings.bindToController = parseIsolateBindings(directive.scope,\n directiveName, true);\n bindings.isolateScope = {};\n } else {\n bindings.isolateScope = parseIsolateBindings(directive.scope,\n directiveName, false);\n }\n }\n if (isObject(directive.bindToController)) {\n bindings.bindToController =\n parseIsolateBindings(directive.bindToController, directiveName, true);\n }\n if (bindings.bindToController && !directive.controller) {\n // There is no controller\n throw $compileMinErr('noctrl',\n 'Cannot bind to controller without directive \\'{0}\\'s controller.',\n directiveName);\n }\n return bindings;\n }\n\n function assertValidDirectiveName(name) {\n var letter = name.charAt(0);\n if (!letter || letter !== lowercase(letter)) {\n throw $compileMinErr('baddir', 'Directive/Component name \\'{0}\\' is invalid. The first character must be a lowercase letter', name);\n }\n if (name !== name.trim()) {\n throw $compileMinErr('baddir',\n 'Directive/Component name \\'{0}\\' is invalid. The name should not contain leading or trailing whitespaces',\n name);\n }\n }\n\n function getDirectiveRequire(directive) {\n var require = directive.require || (directive.controller && directive.name);\n\n if (!isArray(require) && isObject(require)) {\n forEach(require, function(value, key) {\n var match = value.match(REQUIRE_PREFIX_REGEXP);\n var name = value.substring(match[0].length);\n if (!name) require[key] = match[0] + key;\n });\n }\n\n return require;\n }\n\n function getDirectiveRestrict(restrict, name) {\n if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) {\n throw $compileMinErr('badrestrict',\n 'Restrict property \\'{0}\\' of directive \\'{1}\\' is invalid',\n restrict,\n name);\n }\n\n return restrict || 'EA';\n }\n\n /**\n * @ngdoc method\n * @name $compileProvider#directive\n * @kind function\n *\n * @description\n * Register a new directive with the compiler.\n *\n * @param {string|Object} name Name of the directive in camel-case (i.e. `ngBind` which will match\n * as `ng-bind`), or an object map of directives where the keys are the names and the values\n * are the factories.\n * @param {Function|Array} directiveFactory An injectable directive factory function. See the\n * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.\n * @returns {ng.$compileProvider} Self for chaining.\n */\n this.directive = function registerDirective(name, directiveFactory) {\n assertArg(name, 'name');\n assertNotHasOwnProperty(name, 'directive');\n if (isString(name)) {\n assertValidDirectiveName(name);\n assertArg(directiveFactory, 'directiveFactory');\n if (!hasDirectives.hasOwnProperty(name)) {\n hasDirectives[name] = [];\n $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',\n function($injector, $exceptionHandler) {\n var directives = [];\n forEach(hasDirectives[name], function(directiveFactory, index) {\n try {\n var directive = $injector.invoke(directiveFactory);\n if (isFunction(directive)) {\n directive = { compile: valueFn(directive) };\n } else if (!directive.compile && directive.link) {\n directive.compile = valueFn(directive.link);\n }\n directive.priority = directive.priority || 0;\n directive.index = index;\n directive.name = directive.name || name;\n directive.require = getDirectiveRequire(directive);\n directive.restrict = getDirectiveRestrict(directive.restrict, name);\n directive.$$moduleName = directiveFactory.$$moduleName;\n directives.push(directive);\n } catch (e) {\n $exceptionHandler(e);\n }\n });\n return directives;\n }]);\n }\n hasDirectives[name].push(directiveFactory);\n } else {\n forEach(name, reverseParams(registerDirective));\n }\n return this;\n };\n\n /**\n * @ngdoc method\n * @name $compileProvider#component\n * @module ng\n * @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match ``),\n * or an object map of components where the keys are the names and the values are the component definition objects.\n * @param {Object} options Component definition object (a simplified\n * {@link ng.$compile#directive-definition-object directive definition object}),\n * with the following properties (all optional):\n *\n * - `controller` – `{(string|function()=}` – controller constructor function that should be\n * associated with newly created scope or the name of a {@link ng.$compile#-controller-\n * registered controller} if passed as a string. An empty `noop` function by default.\n * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.\n * If present, the controller will be published to scope under the `controllerAs` name.\n * If not present, this will default to be `$ctrl`.\n * - `template` – `{string=|function()=}` – html template as a string or a function that\n * returns an html template as a string which should be used as the contents of this component.\n * Empty string by default.\n *\n * If `template` is a function, then it is {@link auto.$injector#invoke injected} with\n * the following locals:\n *\n * - `$element` - Current element\n * - `$attrs` - Current attributes object for the element\n *\n * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html\n * template that should be used as the contents of this component.\n *\n * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with\n * the following locals:\n *\n * - `$element` - Current element\n * - `$attrs` - Current attributes object for the element\n *\n * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.\n * Component properties are always bound to the component controller and not to the scope.\n * See {@link ng.$compile#-bindtocontroller- `bindToController`}.\n * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.\n * Disabled by default.\n * - `require` - `{Object=}` - requires the controllers of other directives and binds them to\n * this component's controller. The object keys specify the property names under which the required\n * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.\n * - `$...` – additional properties to attach to the directive factory function and the controller\n * constructor function. (This is used by the component router to annotate)\n *\n * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.\n * @description\n * Register a **component definition** with the compiler. This is a shorthand for registering a special\n * type of directive, which represents a self-contained UI component in your application. Such components\n * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).\n *\n * Component definitions are very simple and do not require as much configuration as defining general\n * directives. Component definitions usually consist only of a template and a controller backing it.\n *\n * In order to make the definition easier, components enforce best practices like use of `controllerAs`,\n * `bindToController`. They always have **isolate scope** and are restricted to elements.\n *\n * Here are a few examples of how you would usually define components:\n *\n * ```js\n * var myMod = angular.module(...);\n * myMod.component('myComp', {\n * template: '
My name is {{$ctrl.name}}
',\n * controller: function() {\n * this.name = 'shahar';\n * }\n * });\n *\n * myMod.component('myComp', {\n * template: '
My name is {{$ctrl.name}}
',\n * bindings: {name: '@'}\n * });\n *\n * myMod.component('myComp', {\n * templateUrl: 'views/my-comp.html',\n * controller: 'MyCtrl',\n * controllerAs: 'ctrl',\n * bindings: {name: '@'}\n * });\n *\n * ```\n * For more examples, and an in-depth guide, see the {@link guide/component component guide}.\n *\n *
\n * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.\n */\n this.component = function registerComponent(name, options) {\n if (!isString(name)) {\n forEach(name, reverseParams(bind(this, registerComponent)));\n return this;\n }\n\n var controller = options.controller || function() {};\n\n function factory($injector) {\n function makeInjectable(fn) {\n if (isFunction(fn) || isArray(fn)) {\n return /** @this */ function(tElement, tAttrs) {\n return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});\n };\n } else {\n return fn;\n }\n }\n\n var template = (!options.template && !options.templateUrl ? '' : options.template);\n var ddo = {\n controller: controller,\n controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',\n template: makeInjectable(template),\n templateUrl: makeInjectable(options.templateUrl),\n transclude: options.transclude,\n scope: {},\n bindToController: options.bindings || {},\n restrict: 'E',\n require: options.require\n };\n\n // Copy annotations (starting with $) over to the DDO\n forEach(options, function(val, key) {\n if (key.charAt(0) === '$') ddo[key] = val;\n });\n\n return ddo;\n }\n\n // TODO(pete) remove the following `forEach` before we release 1.6.0\n // The component-router@0.2.0 looks for the annotations on the controller constructor\n // Nothing in AngularJS looks for annotations on the factory function but we can't remove\n // it from 1.5.x yet.\n\n // Copy any annotation properties (starting with $) over to the factory and controller constructor functions\n // These could be used by libraries such as the new component router\n forEach(options, function(val, key) {\n if (key.charAt(0) === '$') {\n factory[key] = val;\n // Don't try to copy over annotations to named controller\n if (isFunction(controller)) controller[key] = val;\n }\n });\n\n factory.$inject = ['$injector'];\n\n return this.directive(name, factory);\n };\n\n\n /**\n * @ngdoc method\n * @name $compileProvider#aHrefSanitizationWhitelist\n * @kind function\n *\n * @description\n * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n * urls during a[href] sanitization.\n *\n * The sanitization is a security measure aimed at preventing XSS attacks via html links.\n *\n * Any url about to be assigned to a[href] via data-binding is first normalized and turned into\n * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`\n * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n *\n * @param {RegExp=} regexp New regexp to whitelist urls with.\n * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n * chaining otherwise.\n */\n this.aHrefSanitizationWhitelist = function(regexp) {\n if (isDefined(regexp)) {\n $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);\n return this;\n } else {\n return $$sanitizeUriProvider.aHrefSanitizationWhitelist();\n }\n };\n\n\n /**\n * @ngdoc method\n * @name $compileProvider#imgSrcSanitizationWhitelist\n * @kind function\n *\n * @description\n * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n * urls during img[src] sanitization.\n *\n * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n *\n * Any url about to be assigned to img[src] via data-binding is first normalized and turned into\n * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`\n * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n *\n * @param {RegExp=} regexp New regexp to whitelist urls with.\n * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n * chaining otherwise.\n */\n this.imgSrcSanitizationWhitelist = function(regexp) {\n if (isDefined(regexp)) {\n $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);\n return this;\n } else {\n return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();\n }\n };\n\n /**\n * @ngdoc method\n * @name $compileProvider#debugInfoEnabled\n *\n * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the\n * current debugInfoEnabled state\n * @returns {*} current value if used as getter or itself (chaining) if used as setter\n *\n * @kind function\n *\n * @description\n * Call this method to enable/disable various debug runtime information in the compiler such as adding\n * binding information and a reference to the current scope on to DOM elements.\n * If enabled, the compiler will add the following to DOM elements that have been bound to the scope\n * * `ng-binding` CSS class\n * * `ng-scope` and `ng-isolated-scope` CSS classes\n * * `$binding` data property containing an array of the binding expressions\n * * Data properties used by the {@link angular.element#methods `scope()`/`isolateScope()` methods} to return\n * the element's scope.\n * * Placeholder comments will contain information about what directive and binding caused the placeholder.\n * E.g. ``.\n *\n * You may want to disable this in production for a significant performance boost. See\n * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.\n *\n * The default value is true.\n */\n var debugInfoEnabled = true;\n this.debugInfoEnabled = function(enabled) {\n if (isDefined(enabled)) {\n debugInfoEnabled = enabled;\n return this;\n }\n return debugInfoEnabled;\n };\n\n /**\n * @ngdoc method\n * @name $compileProvider#strictComponentBindingsEnabled\n *\n * @param {boolean=} enabled update the strictComponentBindingsEnabled state if provided,\n * otherwise return the current strictComponentBindingsEnabled state.\n * @returns {*} current value if used as getter or itself (chaining) if used as setter\n *\n * @kind function\n *\n * @description\n * Call this method to enable / disable the strict component bindings check. If enabled, the\n * compiler will enforce that all scope / controller bindings of a\n * {@link $compileProvider#directive directive} / {@link $compileProvider#component component}\n * that are not set as optional with `?`, must be provided when the directive is instantiated.\n * If not provided, the compiler will throw the\n * {@link error/$compile/missingattr $compile:missingattr error}.\n *\n * The default value is false.\n */\n var strictComponentBindingsEnabled = false;\n this.strictComponentBindingsEnabled = function(enabled) {\n if (isDefined(enabled)) {\n strictComponentBindingsEnabled = enabled;\n return this;\n }\n return strictComponentBindingsEnabled;\n };\n\n var TTL = 10;\n /**\n * @ngdoc method\n * @name $compileProvider#onChangesTtl\n * @description\n *\n * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and\n * assuming that the model is unstable.\n *\n * The current default is 10 iterations.\n *\n * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result\n * in several iterations of calls to these hooks. However if an application needs more than the default 10\n * iterations to stabilize then you should investigate what is causing the model to continuously change during\n * the `$onChanges` hook execution.\n *\n * Increasing the TTL could have performance implications, so you should not change it without proper justification.\n *\n * @param {number} limit The number of `$onChanges` hook iterations.\n * @returns {number|object} the current limit (or `this` if called as a setter for chaining)\n */\n this.onChangesTtl = function(value) {\n if (arguments.length) {\n TTL = value;\n return this;\n }\n return TTL;\n };\n\n var commentDirectivesEnabledConfig = true;\n /**\n * @ngdoc method\n * @name $compileProvider#commentDirectivesEnabled\n * @description\n *\n * It indicates to the compiler\n * whether or not directives on comments should be compiled.\n * Defaults to `true`.\n *\n * Calling this function with false disables the compilation of directives\n * on comments for the whole application.\n * This results in a compilation performance gain,\n * as the compiler doesn't have to check comments when looking for directives.\n * This should however only be used if you are sure that no comment directives are used in\n * the application (including any 3rd party directives).\n *\n * @param {boolean} enabled `false` if the compiler may ignore directives on comments\n * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)\n */\n this.commentDirectivesEnabled = function(value) {\n if (arguments.length) {\n commentDirectivesEnabledConfig = value;\n return this;\n }\n return commentDirectivesEnabledConfig;\n };\n\n\n var cssClassDirectivesEnabledConfig = true;\n /**\n * @ngdoc method\n * @name $compileProvider#cssClassDirectivesEnabled\n * @description\n *\n * It indicates to the compiler\n * whether or not directives on element classes should be compiled.\n * Defaults to `true`.\n *\n * Calling this function with false disables the compilation of directives\n * on element classes for the whole application.\n * This results in a compilation performance gain,\n * as the compiler doesn't have to check element classes when looking for directives.\n * This should however only be used if you are sure that no class directives are used in\n * the application (including any 3rd party directives).\n *\n * @param {boolean} enabled `false` if the compiler may ignore directives on element classes\n * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)\n */\n this.cssClassDirectivesEnabled = function(value) {\n if (arguments.length) {\n cssClassDirectivesEnabledConfig = value;\n return this;\n }\n return cssClassDirectivesEnabledConfig;\n };\n\n\n /**\n * The security context of DOM Properties.\n * @private\n */\n var PROP_CONTEXTS = createMap();\n\n /**\n * @ngdoc method\n * @name $compileProvider#addPropertySecurityContext\n * @description\n *\n * Defines the security context for DOM properties bound by ng-prop-*.\n *\n * @param {string} elementName The element name or '*' to match any element.\n * @param {string} propertyName The DOM property name.\n * @param {string} ctx The {@link $sce} security context in which this value is safe for use, e.g. `$sce.URL`\n * @returns {object} `this` for chaining\n */\n this.addPropertySecurityContext = function(elementName, propertyName, ctx) {\n var key = (elementName.toLowerCase() + '|' + propertyName.toLowerCase());\n\n if (key in PROP_CONTEXTS && PROP_CONTEXTS[key] !== ctx) {\n throw $compileMinErr('ctxoverride', 'Property context \\'{0}.{1}\\' already set to \\'{2}\\', cannot override to \\'{3}\\'.', elementName, propertyName, PROP_CONTEXTS[key], ctx);\n }\n\n PROP_CONTEXTS[key] = ctx;\n return this;\n };\n\n /* Default property contexts.\n *\n * Copy of https://github.com/angular/angular/blob/6.0.6/packages/compiler/src/schema/dom_security_schema.ts#L31-L58\n * Changing:\n * - SecurityContext.* => SCE_CONTEXTS/$sce.*\n * - STYLE => CSS\n * - various URL => MEDIA_URL\n * - *|formAction, form|action URL => RESOURCE_URL (like the attribute)\n */\n (function registerNativePropertyContexts() {\n function registerContext(ctx, values) {\n forEach(values, function(v) { PROP_CONTEXTS[v.toLowerCase()] = ctx; });\n }\n\n registerContext(SCE_CONTEXTS.HTML, [\n 'iframe|srcdoc',\n '*|innerHTML',\n '*|outerHTML'\n ]);\n registerContext(SCE_CONTEXTS.CSS, ['*|style']);\n registerContext(SCE_CONTEXTS.URL, [\n 'area|href', 'area|ping',\n 'a|href', 'a|ping',\n 'blockquote|cite',\n 'body|background',\n 'del|cite',\n 'input|src',\n 'ins|cite',\n 'q|cite'\n ]);\n registerContext(SCE_CONTEXTS.MEDIA_URL, [\n 'audio|src',\n 'img|src', 'img|srcset',\n 'source|src', 'source|srcset',\n 'track|src',\n 'video|src', 'video|poster'\n ]);\n registerContext(SCE_CONTEXTS.RESOURCE_URL, [\n '*|formAction',\n 'applet|code', 'applet|codebase',\n 'base|href',\n 'embed|src',\n 'frame|src',\n 'form|action',\n 'head|profile',\n 'html|manifest',\n 'iframe|src',\n 'link|href',\n 'media|src',\n 'object|codebase', 'object|data',\n 'script|src'\n ]);\n })();\n\n\n this.$get = [\n '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',\n '$controller', '$rootScope', '$sce', '$animate',\n function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,\n $controller, $rootScope, $sce, $animate) {\n\n var SIMPLE_ATTR_NAME = /^\\w/;\n var specialAttrHolder = window.document.createElement('div');\n\n\n var commentDirectivesEnabled = commentDirectivesEnabledConfig;\n var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig;\n\n\n var onChangesTtl = TTL;\n // The onChanges hooks should all be run together in a single digest\n // When changes occur, the call to trigger their hooks will be added to this queue\n var onChangesQueue;\n\n // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest\n function flushOnChangesQueue() {\n try {\n if (!(--onChangesTtl)) {\n // We have hit the TTL limit so reset everything\n onChangesQueue = undefined;\n throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\\n', TTL);\n }\n // We must run this hook in an apply since the $$postDigest runs outside apply\n $rootScope.$apply(function() {\n for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {\n try {\n onChangesQueue[i]();\n } catch (e) {\n $exceptionHandler(e);\n }\n }\n // Reset the queue to trigger a new schedule next time there is a change\n onChangesQueue = undefined;\n });\n } finally {\n onChangesTtl++;\n }\n }\n\n\n function sanitizeSrcset(value, invokeType) {\n if (!value) {\n return value;\n }\n if (!isString(value)) {\n throw $compileMinErr('srcset', 'Can\\'t pass trusted values to `{0}`: \"{1}\"', invokeType, value.toString());\n }\n\n // Such values are a bit too complex to handle automatically inside $sce.\n // Instead, we sanitize each of the URIs individually, which works, even dynamically.\n\n // It's not possible to work around this using `$sce.trustAsMediaUrl`.\n // If you want to programmatically set explicitly trusted unsafe URLs, you should use\n // `$sce.trustAsHtml` on the whole `img` tag and inject it into the DOM using the\n // `ng-bind-html` directive.\n\n var result = '';\n\n // first check if there are spaces because it's not the same pattern\n var trimmedSrcset = trim(value);\n // ( 999x ,| 999w ,| ,|, )\n var srcPattern = /(\\s+\\d+x\\s*,|\\s+\\d+w\\s*,|\\s+,|,\\s+)/;\n var pattern = /\\s/.test(trimmedSrcset) ? srcPattern : /(,)/;\n\n // split srcset into tuple of uri and descriptor except for the last item\n var rawUris = trimmedSrcset.split(pattern);\n\n // for each tuples\n var nbrUrisWith2parts = Math.floor(rawUris.length / 2);\n for (var i = 0; i < nbrUrisWith2parts; i++) {\n var innerIdx = i * 2;\n // sanitize the uri\n result += $sce.getTrustedMediaUrl(trim(rawUris[innerIdx]));\n // add the descriptor\n result += ' ' + trim(rawUris[innerIdx + 1]);\n }\n\n // split the last item into uri and descriptor\n var lastTuple = trim(rawUris[i * 2]).split(/\\s/);\n\n // sanitize the last uri\n result += $sce.getTrustedMediaUrl(trim(lastTuple[0]));\n\n // and add the last descriptor if any\n if (lastTuple.length === 2) {\n result += (' ' + trim(lastTuple[1]));\n }\n return result;\n }\n\n\n function Attributes(element, attributesToCopy) {\n if (attributesToCopy) {\n var keys = Object.keys(attributesToCopy);\n var i, l, key;\n\n for (i = 0, l = keys.length; i < l; i++) {\n key = keys[i];\n this[key] = attributesToCopy[key];\n }\n } else {\n this.$attr = {};\n }\n\n this.$$element = element;\n }\n\n Attributes.prototype = {\n /**\n * @ngdoc method\n * @name $compile.directive.Attributes#$normalize\n * @kind function\n *\n * @description\n * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or\n * `data-`) to its normalized, camelCase form.\n *\n * Also there is special case for Moz prefix starting with upper case letter.\n *\n * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}\n *\n * @param {string} name Name to normalize\n */\n $normalize: directiveNormalize,\n\n\n /**\n * @ngdoc method\n * @name $compile.directive.Attributes#$addClass\n * @kind function\n *\n * @description\n * Adds the CSS class value specified by the classVal parameter to the element. If animations\n * are enabled then an animation will be triggered for the class addition.\n *\n * @param {string} classVal The className value that will be added to the element\n */\n $addClass: function(classVal) {\n if (classVal && classVal.length > 0) {\n $animate.addClass(this.$$element, classVal);\n }\n },\n\n /**\n * @ngdoc method\n * @name $compile.directive.Attributes#$removeClass\n * @kind function\n *\n * @description\n * Removes the CSS class value specified by the classVal parameter from the element. If\n * animations are enabled then an animation will be triggered for the class removal.\n *\n * @param {string} classVal The className value that will be removed from the element\n */\n $removeClass: function(classVal) {\n if (classVal && classVal.length > 0) {\n $animate.removeClass(this.$$element, classVal);\n }\n },\n\n /**\n * @ngdoc method\n * @name $compile.directive.Attributes#$updateClass\n * @kind function\n *\n * @description\n * Adds and removes the appropriate CSS class values to the element based on the difference\n * between the new and old CSS class values (specified as newClasses and oldClasses).\n *\n * @param {string} newClasses The current CSS className value\n * @param {string} oldClasses The former CSS className value\n */\n $updateClass: function(newClasses, oldClasses) {\n var toAdd = tokenDifference(newClasses, oldClasses);\n if (toAdd && toAdd.length) {\n $animate.addClass(this.$$element, toAdd);\n }\n\n var toRemove = tokenDifference(oldClasses, newClasses);\n if (toRemove && toRemove.length) {\n $animate.removeClass(this.$$element, toRemove);\n }\n },\n\n /**\n * Set a normalized attribute on the element in a way such that all directives\n * can share the attribute. This function properly handles boolean attributes.\n * @param {string} key Normalized key. (ie ngAttribute)\n * @param {string|boolean} value The value to set. If `null` attribute will be deleted.\n * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.\n * Defaults to true.\n * @param {string=} attrName Optional none normalized name. Defaults to key.\n */\n $set: function(key, value, writeAttr, attrName) {\n // TODO: decide whether or not to throw an error if \"class\"\n // is set through this function since it may cause $updateClass to\n // become unstable.\n\n var node = this.$$element[0],\n booleanKey = getBooleanAttrName(node, key),\n aliasedKey = getAliasedAttrName(key),\n observer = key,\n nodeName;\n\n if (booleanKey) {\n this.$$element.prop(key, value);\n attrName = booleanKey;\n } else if (aliasedKey) {\n this[aliasedKey] = value;\n observer = aliasedKey;\n }\n\n this[key] = value;\n\n // translate normalized key to actual key\n if (attrName) {\n this.$attr[key] = attrName;\n } else {\n attrName = this.$attr[key];\n if (!attrName) {\n this.$attr[key] = attrName = snake_case(key, '-');\n }\n }\n\n nodeName = nodeName_(this.$$element);\n\n // Sanitize img[srcset] values.\n if (nodeName === 'img' && key === 'srcset') {\n this[key] = value = sanitizeSrcset(value, '$set(\\'srcset\\', value)');\n }\n\n if (writeAttr !== false) {\n if (value === null || isUndefined(value)) {\n this.$$element.removeAttr(attrName);\n } else {\n if (SIMPLE_ATTR_NAME.test(attrName)) {\n // jQuery skips special boolean attrs treatment in XML nodes for\n // historical reasons and hence AngularJS cannot freely call\n // `.attr(attrName, false) with such attributes. To avoid issues\n // in XHTML, call `removeAttr` in such cases instead.\n // See https://github.com/jquery/jquery/issues/4249\n if (booleanKey && value === false) {\n this.$$element.removeAttr(attrName);\n } else {\n this.$$element.attr(attrName, value);\n }\n } else {\n setSpecialAttr(this.$$element[0], attrName, value);\n }\n }\n }\n\n // fire observers\n var $$observers = this.$$observers;\n if ($$observers) {\n forEach($$observers[observer], function(fn) {\n try {\n fn(value);\n } catch (e) {\n $exceptionHandler(e);\n }\n });\n }\n },\n\n\n /**\n * @ngdoc method\n * @name $compile.directive.Attributes#$observe\n * @kind function\n *\n * @description\n * Observes an interpolated attribute.\n *\n * The observer function will be invoked once during the next `$digest` following\n * compilation. The observer is then invoked whenever the interpolated value\n * changes.\n *\n * @param {string} key Normalized key. (ie ngAttribute) .\n * @param {function(interpolatedValue)} fn Function that will be called whenever\n the interpolated value of the attribute changes.\n * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation\n * guide} for more info.\n * @returns {function()} Returns a deregistration function for this observer.\n */\n $observe: function(key, fn) {\n var attrs = this,\n $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),\n listeners = ($$observers[key] || ($$observers[key] = []));\n\n listeners.push(fn);\n $rootScope.$evalAsync(function() {\n if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {\n // no one registered attribute interpolation function, so lets call it manually\n fn(attrs[key]);\n }\n });\n\n return function() {\n arrayRemove(listeners, fn);\n };\n }\n };\n\n function setSpecialAttr(element, attrName, value) {\n // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`\n // so we have to jump through some hoops to get such an attribute\n // https://github.com/angular/angular.js/pull/13318\n specialAttrHolder.innerHTML = '';\n var attributes = specialAttrHolder.firstChild.attributes;\n var attribute = attributes[0];\n // We have to remove the attribute from its container element before we can add it to the destination element\n attributes.removeNamedItem(attribute.name);\n attribute.value = value;\n element.attributes.setNamedItem(attribute);\n }\n\n function safeAddClass($element, className) {\n try {\n $element.addClass(className);\n } catch (e) {\n // ignore, since it means that we are trying to set class on\n // SVG element, where class name is read-only.\n }\n }\n\n\n var startSymbol = $interpolate.startSymbol(),\n endSymbol = $interpolate.endSymbol(),\n denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}')\n ? identity\n : function denormalizeTemplate(template) {\n return template.replace(/\\{\\{/g, startSymbol).replace(/}}/g, endSymbol);\n },\n NG_PREFIX_BINDING = /^ng(Attr|Prop|On)([A-Z].*)$/;\n var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;\n\n compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {\n var bindings = $element.data('$binding') || [];\n\n if (isArray(binding)) {\n bindings = bindings.concat(binding);\n } else {\n bindings.push(binding);\n }\n\n $element.data('$binding', bindings);\n } : noop;\n\n compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {\n safeAddClass($element, 'ng-binding');\n } : noop;\n\n compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {\n var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';\n $element.data(dataName, scope);\n } : noop;\n\n compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {\n safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');\n } : noop;\n\n compile.$$createComment = function(directiveName, comment) {\n var content = '';\n if (debugInfoEnabled) {\n content = ' ' + (directiveName || '') + ': ';\n if (comment) content += comment + ' ';\n }\n return window.document.createComment(content);\n };\n\n return compile;\n\n //================================\n\n function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,\n previousCompileContext) {\n if (!($compileNodes instanceof jqLite)) {\n // jquery always rewraps, whereas we need to preserve the original selector so that we can\n // modify it.\n $compileNodes = jqLite($compileNodes);\n }\n var compositeLinkFn =\n compileNodes($compileNodes, transcludeFn, $compileNodes,\n maxPriority, ignoreDirective, previousCompileContext);\n compile.$$addScopeClass($compileNodes);\n var namespace = null;\n return function publicLinkFn(scope, cloneConnectFn, options) {\n if (!$compileNodes) {\n throw $compileMinErr('multilink', 'This element has already been linked.');\n }\n assertArg(scope, 'scope');\n\n if (previousCompileContext && previousCompileContext.needsNewScope) {\n // A parent directive did a replace and a directive on this element asked\n // for transclusion, which caused us to lose a layer of element on which\n // we could hold the new transclusion scope, so we will create it manually\n // here.\n scope = scope.$parent.$new();\n }\n\n options = options || {};\n var parentBoundTranscludeFn = options.parentBoundTranscludeFn,\n transcludeControllers = options.transcludeControllers,\n futureParentElement = options.futureParentElement;\n\n // When `parentBoundTranscludeFn` is passed, it is a\n // `controllersBoundTransclude` function (it was previously passed\n // as `transclude` to directive.link) so we must unwrap it to get\n // its `boundTranscludeFn`\n if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {\n parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;\n }\n\n if (!namespace) {\n namespace = detectNamespaceForChildElements(futureParentElement);\n }\n var $linkNode;\n if (namespace !== 'html') {\n // When using a directive with replace:true and templateUrl the $compileNodes\n // (or a child element inside of them)\n // might change, so we need to recreate the namespace adapted compileNodes\n // for call to the link function.\n // Note: This will already clone the nodes...\n $linkNode = jqLite(\n wrapTemplate(namespace, jqLite('
').append($compileNodes).html())\n );\n } else if (cloneConnectFn) {\n // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart\n // and sometimes changes the structure of the DOM.\n $linkNode = JQLitePrototype.clone.call($compileNodes);\n } else {\n $linkNode = $compileNodes;\n }\n\n if (transcludeControllers) {\n for (var controllerName in transcludeControllers) {\n $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);\n }\n }\n\n compile.$$addScopeInfo($linkNode, scope);\n\n if (cloneConnectFn) cloneConnectFn($linkNode, scope);\n if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);\n\n if (!cloneConnectFn) {\n $compileNodes = compositeLinkFn = null;\n }\n return $linkNode;\n };\n }\n\n function detectNamespaceForChildElements(parentElement) {\n // TODO: Make this detect MathML as well...\n var node = parentElement && parentElement[0];\n if (!node) {\n return 'html';\n } else {\n return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';\n }\n }\n\n /**\n * Compile function matches each node in nodeList against the directives. Once all directives\n * for a particular node are collected their compile functions are executed. The compile\n * functions return values - the linking functions - are combined into a composite linking\n * function, which is the a linking function for the node.\n *\n * @param {NodeList} nodeList an array of nodes or NodeList to compile\n * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the\n * scope argument is auto-generated to the new child of the transcluded parent scope.\n * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then\n * the rootElement must be set the jqLite collection of the compile root. This is\n * needed so that the jqLite collection items can be replaced with widgets.\n * @param {number=} maxPriority Max directive priority.\n * @returns {Function} A composite linking function of all of the matched directives or null.\n */\n function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,\n previousCompileContext) {\n var linkFns = [],\n // `nodeList` can be either an element's `.childNodes` (live NodeList)\n // or a jqLite/jQuery collection or an array\n notLiveList = isArray(nodeList) || (nodeList instanceof jqLite),\n attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;\n\n\n for (var i = 0; i < nodeList.length; i++) {\n attrs = new Attributes();\n\n // Support: IE 11 only\n // Workaround for #11781 and #14924\n if (msie === 11) {\n mergeConsecutiveTextNodes(nodeList, i, notLiveList);\n }\n\n // We must always refer to `nodeList[i]` hereafter,\n // since the nodes can be replaced underneath us.\n directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,\n ignoreDirective);\n\n nodeLinkFn = (directives.length)\n ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,\n null, [], [], previousCompileContext)\n : null;\n\n if (nodeLinkFn && nodeLinkFn.scope) {\n compile.$$addScopeClass(attrs.$$element);\n }\n\n childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||\n !(childNodes = nodeList[i].childNodes) ||\n !childNodes.length)\n ? null\n : compileNodes(childNodes,\n nodeLinkFn ? (\n (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)\n && nodeLinkFn.transclude) : transcludeFn);\n\n if (nodeLinkFn || childLinkFn) {\n linkFns.push(i, nodeLinkFn, childLinkFn);\n linkFnFound = true;\n nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;\n }\n\n //use the previous context only for the first element in the virtual group\n previousCompileContext = null;\n }\n\n // return a linking function if we have found anything, null otherwise\n return linkFnFound ? compositeLinkFn : null;\n\n function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {\n var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;\n var stableNodeList;\n\n\n if (nodeLinkFnFound) {\n // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our\n // offsets don't get screwed up\n var nodeListLength = nodeList.length;\n stableNodeList = new Array(nodeListLength);\n\n // create a sparse array by only copying the elements which have a linkFn\n for (i = 0; i < linkFns.length; i += 3) {\n idx = linkFns[i];\n stableNodeList[idx] = nodeList[idx];\n }\n } else {\n stableNodeList = nodeList;\n }\n\n for (i = 0, ii = linkFns.length; i < ii;) {\n node = stableNodeList[linkFns[i++]];\n nodeLinkFn = linkFns[i++];\n childLinkFn = linkFns[i++];\n\n if (nodeLinkFn) {\n if (nodeLinkFn.scope) {\n childScope = scope.$new();\n compile.$$addScopeInfo(jqLite(node), childScope);\n } else {\n childScope = scope;\n }\n\n if (nodeLinkFn.transcludeOnThisElement) {\n childBoundTranscludeFn = createBoundTranscludeFn(\n scope, nodeLinkFn.transclude, parentBoundTranscludeFn);\n\n } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {\n childBoundTranscludeFn = parentBoundTranscludeFn;\n\n } else if (!parentBoundTranscludeFn && transcludeFn) {\n childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);\n\n } else {\n childBoundTranscludeFn = null;\n }\n\n nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);\n\n } else if (childLinkFn) {\n childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);\n }\n }\n }\n }\n\n function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) {\n var node = nodeList[idx];\n var parent = node.parentNode;\n var sibling;\n\n if (node.nodeType !== NODE_TYPE_TEXT) {\n return;\n }\n\n while (true) {\n sibling = parent ? node.nextSibling : nodeList[idx + 1];\n if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) {\n break;\n }\n\n node.nodeValue = node.nodeValue + sibling.nodeValue;\n\n if (sibling.parentNode) {\n sibling.parentNode.removeChild(sibling);\n }\n if (notLiveList && sibling === nodeList[idx + 1]) {\n nodeList.splice(idx + 1, 1);\n }\n }\n }\n\n function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {\n function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {\n\n if (!transcludedScope) {\n transcludedScope = scope.$new(false, containingScope);\n transcludedScope.$$transcluded = true;\n }\n\n return transcludeFn(transcludedScope, cloneFn, {\n parentBoundTranscludeFn: previousBoundTranscludeFn,\n transcludeControllers: controllers,\n futureParentElement: futureParentElement\n });\n }\n\n // We need to attach the transclusion slots onto the `boundTranscludeFn`\n // so that they are available inside the `controllersBoundTransclude` function\n var boundSlots = boundTranscludeFn.$$slots = createMap();\n for (var slotName in transcludeFn.$$slots) {\n if (transcludeFn.$$slots[slotName]) {\n boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);\n } else {\n boundSlots[slotName] = null;\n }\n }\n\n return boundTranscludeFn;\n }\n\n /**\n * Looks for directives on the given node and adds them to the directive collection which is\n * sorted.\n *\n * @param node Node to search.\n * @param directives An array to which the directives are added to. This array is sorted before\n * the function returns.\n * @param attrs The shared attrs object which is used to populate the normalized attributes.\n * @param {number=} maxPriority Max directive priority.\n */\n function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {\n var nodeType = node.nodeType,\n attrsMap = attrs.$attr,\n match,\n nodeName,\n className;\n\n switch (nodeType) {\n case NODE_TYPE_ELEMENT: /* Element */\n\n nodeName = nodeName_(node);\n\n // use the node name: \n addDirective(directives,\n directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective);\n\n // iterate over the attributes\n for (var attr, name, nName, value, ngPrefixMatch, nAttrs = node.attributes,\n j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {\n var attrStartName = false;\n var attrEndName = false;\n\n var isNgAttr = false, isNgProp = false, isNgEvent = false;\n var multiElementMatch;\n\n attr = nAttrs[j];\n name = attr.name;\n value = attr.value;\n\n nName = directiveNormalize(name.toLowerCase());\n\n // Support ng-attr-*, ng-prop-* and ng-on-*\n if ((ngPrefixMatch = nName.match(NG_PREFIX_BINDING))) {\n isNgAttr = ngPrefixMatch[1] === 'Attr';\n isNgProp = ngPrefixMatch[1] === 'Prop';\n isNgEvent = ngPrefixMatch[1] === 'On';\n\n // Normalize the non-prefixed name\n name = name.replace(PREFIX_REGEXP, '')\n .toLowerCase()\n .substr(4 + ngPrefixMatch[1].length).replace(/_(.)/g, function(match, letter) {\n return letter.toUpperCase();\n });\n\n // Support *-start / *-end multi element directives\n } else if ((multiElementMatch = nName.match(MULTI_ELEMENT_DIR_RE)) && directiveIsMultiElement(multiElementMatch[1])) {\n attrStartName = name;\n attrEndName = name.substr(0, name.length - 5) + 'end';\n name = name.substr(0, name.length - 6);\n }\n\n if (isNgProp || isNgEvent) {\n attrs[nName] = value;\n attrsMap[nName] = attr.name;\n\n if (isNgProp) {\n addPropertyDirective(node, directives, nName, name);\n } else {\n addEventDirective(directives, nName, name);\n }\n } else {\n // Update nName for cases where a prefix was removed\n // NOTE: the .toLowerCase() is unnecessary and causes https://github.com/angular/angular.js/issues/16624 for ng-attr-*\n nName = directiveNormalize(name.toLowerCase());\n attrsMap[nName] = name;\n\n if (isNgAttr || !attrs.hasOwnProperty(nName)) {\n attrs[nName] = value;\n if (getBooleanAttrName(node, nName)) {\n attrs[nName] = true; // presence means true\n }\n }\n\n addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);\n addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,\n attrEndName);\n }\n }\n\n if (nodeName === 'input' && node.getAttribute('type') === 'hidden') {\n // Hidden input elements can have strange behaviour when navigating back to the page\n // This tells the browser not to try to cache and reinstate previous values\n node.setAttribute('autocomplete', 'off');\n }\n\n // use class as directive\n if (!cssClassDirectivesEnabled) break;\n className = node.className;\n if (isObject(className)) {\n // Maybe SVGAnimatedString\n className = className.animVal;\n }\n if (isString(className) && className !== '') {\n while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) {\n nName = directiveNormalize(match[2]);\n if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {\n attrs[nName] = trim(match[3]);\n }\n className = className.substr(match.index + match[0].length);\n }\n }\n break;\n case NODE_TYPE_TEXT: /* Text Node */\n addTextInterpolateDirective(directives, node.nodeValue);\n break;\n case NODE_TYPE_COMMENT: /* Comment */\n if (!commentDirectivesEnabled) break;\n collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);\n break;\n }\n\n directives.sort(byPriority);\n return directives;\n }\n\n function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) {\n // function created because of performance, try/catch disables\n // the optimization of the whole function #14848\n try {\n var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);\n if (match) {\n var nName = directiveNormalize(match[1]);\n if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {\n attrs[nName] = trim(match[2]);\n }\n }\n } catch (e) {\n // turns out that under some circumstances IE9 throws errors when one attempts to read\n // comment's node value.\n // Just ignore it and continue. (Can't seem to reproduce in test case.)\n }\n }\n\n /**\n * Given a node with a directive-start it collects all of the siblings until it finds\n * directive-end.\n * @param node\n * @param attrStart\n * @param attrEnd\n * @returns {*}\n */\n function groupScan(node, attrStart, attrEnd) {\n var nodes = [];\n var depth = 0;\n if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {\n do {\n if (!node) {\n throw $compileMinErr('uterdir',\n 'Unterminated attribute, found \\'{0}\\' but no matching \\'{1}\\' found.',\n attrStart, attrEnd);\n }\n if (node.nodeType === NODE_TYPE_ELEMENT) {\n if (node.hasAttribute(attrStart)) depth++;\n if (node.hasAttribute(attrEnd)) depth--;\n }\n nodes.push(node);\n node = node.nextSibling;\n } while (depth > 0);\n } else {\n nodes.push(node);\n }\n\n return jqLite(nodes);\n }\n\n /**\n * Wrapper for linking function which converts normal linking function into a grouped\n * linking function.\n * @param linkFn\n * @param attrStart\n * @param attrEnd\n * @returns {Function}\n */\n function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {\n return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {\n element = groupScan(element[0], attrStart, attrEnd);\n return linkFn(scope, element, attrs, controllers, transcludeFn);\n };\n }\n\n /**\n * A function generator that is used to support both eager and lazy compilation\n * linking function.\n * @param eager\n * @param $compileNodes\n * @param transcludeFn\n * @param maxPriority\n * @param ignoreDirective\n * @param previousCompileContext\n * @returns {Function}\n */\n function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {\n var compiled;\n\n if (eager) {\n return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);\n }\n return /** @this */ function lazyCompilation() {\n if (!compiled) {\n compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);\n\n // Null out all of these references in order to make them eligible for garbage collection\n // since this is a potentially long lived closure\n $compileNodes = transcludeFn = previousCompileContext = null;\n }\n return compiled.apply(this, arguments);\n };\n }\n\n /**\n * Once the directives have been collected, their compile functions are executed. This method\n * is responsible for inlining directive templates as well as terminating the application\n * of the directives if the terminal directive has been reached.\n *\n * @param {Array} directives Array of collected directives to execute their compile function.\n * this needs to be pre-sorted by priority order.\n * @param {Node} compileNode The raw DOM node to apply the compile functions to\n * @param {Object} templateAttrs The shared attribute function\n * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the\n * scope argument is auto-generated to the new\n * child of the transcluded parent scope.\n * @param {JQLite} jqCollection If we are working on the root of the compile tree then this\n * argument has the root jqLite array so that we can replace nodes\n * on it.\n * @param {Object=} originalReplaceDirective An optional directive that will be ignored when\n * compiling the transclusion.\n * @param {Array.} preLinkFns\n * @param {Array.} postLinkFns\n * @param {Object} previousCompileContext Context used for previous compilation of the current\n * node\n * @returns {Function} linkFn\n */\n function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,\n jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,\n previousCompileContext) {\n previousCompileContext = previousCompileContext || {};\n\n var terminalPriority = -Number.MAX_VALUE,\n newScopeDirective = previousCompileContext.newScopeDirective,\n controllerDirectives = previousCompileContext.controllerDirectives,\n newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,\n templateDirective = previousCompileContext.templateDirective,\n nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,\n hasTranscludeDirective = false,\n hasTemplate = false,\n hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,\n $compileNode = templateAttrs.$$element = jqLite(compileNode),\n directive,\n directiveName,\n $template,\n replaceDirective = originalReplaceDirective,\n childTranscludeFn = transcludeFn,\n linkFn,\n didScanForMultipleTransclusion = false,\n mightHaveMultipleTransclusionError = false,\n directiveValue;\n\n // executes all directives on the current element\n for (var i = 0, ii = directives.length; i < ii; i++) {\n directive = directives[i];\n var attrStart = directive.$$start;\n var attrEnd = directive.$$end;\n\n // collect multiblock sections\n if (attrStart) {\n $compileNode = groupScan(compileNode, attrStart, attrEnd);\n }\n $template = undefined;\n\n if (terminalPriority > directive.priority) {\n break; // prevent further processing of directives\n }\n\n directiveValue = directive.scope;\n\n if (directiveValue) {\n\n // skip the check for directives with async templates, we'll check the derived sync\n // directive when the template arrives\n if (!directive.templateUrl) {\n if (isObject(directiveValue)) {\n // This directive is trying to add an isolated scope.\n // Check that there is no scope of any kind already\n assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,\n directive, $compileNode);\n newIsolateScopeDirective = directive;\n } else {\n // This directive is trying to add a child scope.\n // Check that there is no isolated scope already\n assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,\n $compileNode);\n }\n }\n\n newScopeDirective = newScopeDirective || directive;\n }\n\n directiveName = directive.name;\n\n // If we encounter a condition that can result in transclusion on the directive,\n // then scan ahead in the remaining directives for others that may cause a multiple\n // transclusion error to be thrown during the compilation process. If a matching directive\n // is found, then we know that when we encounter a transcluded directive, we need to eagerly\n // compile the `transclude` function rather than doing it lazily in order to throw\n // exceptions at the correct time\n if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))\n || (directive.transclude && !directive.$$tlb))) {\n var candidateDirective;\n\n for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) {\n if ((candidateDirective.transclude && !candidateDirective.$$tlb)\n || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {\n mightHaveMultipleTransclusionError = true;\n break;\n }\n }\n\n didScanForMultipleTransclusion = true;\n }\n\n if (!directive.templateUrl && directive.controller) {\n controllerDirectives = controllerDirectives || createMap();\n assertNoDuplicate('\\'' + directiveName + '\\' controller',\n controllerDirectives[directiveName], directive, $compileNode);\n controllerDirectives[directiveName] = directive;\n }\n\n directiveValue = directive.transclude;\n\n if (directiveValue) {\n hasTranscludeDirective = true;\n\n // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.\n // This option should only be used by directives that know how to safely handle element transclusion,\n // where the transcluded nodes are added or replaced after linking.\n if (!directive.$$tlb) {\n assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);\n nonTlbTranscludeDirective = directive;\n }\n\n if (directiveValue === 'element') {\n hasElementTranscludeDirective = true;\n terminalPriority = directive.priority;\n $template = $compileNode;\n $compileNode = templateAttrs.$$element =\n jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));\n compileNode = $compileNode[0];\n replaceWith(jqCollection, sliceArgs($template), compileNode);\n\n childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,\n replaceDirective && replaceDirective.name, {\n // Don't pass in:\n // - controllerDirectives - otherwise we'll create duplicates controllers\n // - newIsolateScopeDirective or templateDirective - combining templates with\n // element transclusion doesn't make sense.\n //\n // We need only nonTlbTranscludeDirective so that we prevent putting transclusion\n // on the same element more than once.\n nonTlbTranscludeDirective: nonTlbTranscludeDirective\n });\n } else {\n\n var slots = createMap();\n\n if (!isObject(directiveValue)) {\n $template = jqLite(jqLiteClone(compileNode)).contents();\n } else {\n\n // We have transclusion slots,\n // collect them up, compile them and store their transclusion functions\n $template = window.document.createDocumentFragment();\n\n var slotMap = createMap();\n var filledSlots = createMap();\n\n // Parse the element selectors\n forEach(directiveValue, function(elementSelector, slotName) {\n // If an element selector starts with a ? then it is optional\n var optional = (elementSelector.charAt(0) === '?');\n elementSelector = optional ? elementSelector.substring(1) : elementSelector;\n\n slotMap[elementSelector] = slotName;\n\n // We explicitly assign `null` since this implies that a slot was defined but not filled.\n // Later when calling boundTransclusion functions with a slot name we only error if the\n // slot is `undefined`\n slots[slotName] = null;\n\n // filledSlots contains `true` for all slots that are either optional or have been\n // filled. This is used to check that we have not missed any required slots\n filledSlots[slotName] = optional;\n });\n\n // Add the matching elements into their slot\n forEach($compileNode.contents(), function(node) {\n var slotName = slotMap[directiveNormalize(nodeName_(node))];\n if (slotName) {\n filledSlots[slotName] = true;\n slots[slotName] = slots[slotName] || window.document.createDocumentFragment();\n slots[slotName].appendChild(node);\n } else {\n $template.appendChild(node);\n }\n });\n\n // Check for required slots that were not filled\n forEach(filledSlots, function(filled, slotName) {\n if (!filled) {\n throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);\n }\n });\n\n for (var slotName in slots) {\n if (slots[slotName]) {\n // Only define a transclusion function if the slot was filled\n var slotCompileNodes = jqLite(slots[slotName].childNodes);\n slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slotCompileNodes, transcludeFn);\n }\n }\n\n $template = jqLite($template.childNodes);\n }\n\n $compileNode.empty(); // clear contents\n childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,\n undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});\n childTranscludeFn.$$slots = slots;\n }\n }\n\n if (directive.template) {\n hasTemplate = true;\n assertNoDuplicate('template', templateDirective, directive, $compileNode);\n templateDirective = directive;\n\n directiveValue = (isFunction(directive.template))\n ? directive.template($compileNode, templateAttrs)\n : directive.template;\n\n directiveValue = denormalizeTemplate(directiveValue);\n\n if (directive.replace) {\n replaceDirective = directive;\n if (jqLiteIsTextNode(directiveValue)) {\n $template = [];\n } else {\n $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));\n }\n compileNode = $template[0];\n\n if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {\n throw $compileMinErr('tplrt',\n 'Template for directive \\'{0}\\' must have exactly one root element. {1}',\n directiveName, '');\n }\n\n replaceWith(jqCollection, $compileNode, compileNode);\n\n var newTemplateAttrs = {$attr: {}};\n\n // combine directives from the original node and from the template:\n // - take the array of directives for this element\n // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)\n // - collect directives from the template and sort them by priority\n // - combine directives as: processed + template + unprocessed\n var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);\n var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));\n\n if (newIsolateScopeDirective || newScopeDirective) {\n // The original directive caused the current element to be replaced but this element\n // also needs to have a new scope, so we need to tell the template directives\n // that they would need to get their scope from further up, if they require transclusion\n markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);\n }\n directives = directives.concat(templateDirectives).concat(unprocessedDirectives);\n mergeTemplateAttributes(templateAttrs, newTemplateAttrs);\n\n ii = directives.length;\n } else {\n $compileNode.html(directiveValue);\n }\n }\n\n if (directive.templateUrl) {\n hasTemplate = true;\n assertNoDuplicate('template', templateDirective, directive, $compileNode);\n templateDirective = directive;\n\n if (directive.replace) {\n replaceDirective = directive;\n }\n\n // eslint-disable-next-line no-func-assign\n nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,\n templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {\n controllerDirectives: controllerDirectives,\n newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,\n newIsolateScopeDirective: newIsolateScopeDirective,\n templateDirective: templateDirective,\n nonTlbTranscludeDirective: nonTlbTranscludeDirective\n });\n ii = directives.length;\n } else if (directive.compile) {\n try {\n linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);\n var context = directive.$$originalDirective || directive;\n if (isFunction(linkFn)) {\n addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);\n } else if (linkFn) {\n addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);\n }\n } catch (e) {\n $exceptionHandler(e, startingTag($compileNode));\n }\n }\n\n if (directive.terminal) {\n nodeLinkFn.terminal = true;\n terminalPriority = Math.max(terminalPriority, directive.priority);\n }\n\n }\n\n nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;\n nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;\n nodeLinkFn.templateOnThisElement = hasTemplate;\n nodeLinkFn.transclude = childTranscludeFn;\n\n previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;\n\n // might be normal or delayed nodeLinkFn depending on if templateUrl is present\n return nodeLinkFn;\n\n ////////////////////\n\n function addLinkFns(pre, post, attrStart, attrEnd) {\n if (pre) {\n if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);\n pre.require = directive.require;\n pre.directiveName = directiveName;\n if (newIsolateScopeDirective === directive || directive.$$isolateScope) {\n pre = cloneAndAnnotateFn(pre, {isolateScope: true});\n }\n preLinkFns.push(pre);\n }\n if (post) {\n if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);\n post.require = directive.require;\n post.directiveName = directiveName;\n if (newIsolateScopeDirective === directive || directive.$$isolateScope) {\n post = cloneAndAnnotateFn(post, {isolateScope: true});\n }\n postLinkFns.push(post);\n }\n }\n\n function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {\n var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,\n attrs, scopeBindingInfo;\n\n if (compileNode === linkNode) {\n attrs = templateAttrs;\n $element = templateAttrs.$$element;\n } else {\n $element = jqLite(linkNode);\n attrs = new Attributes($element, templateAttrs);\n }\n\n controllerScope = scope;\n if (newIsolateScopeDirective) {\n isolateScope = scope.$new(true);\n } else if (newScopeDirective) {\n controllerScope = scope.$parent;\n }\n\n if (boundTranscludeFn) {\n // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`\n // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`\n transcludeFn = controllersBoundTransclude;\n transcludeFn.$$boundTransclude = boundTranscludeFn;\n // expose the slots on the `$transclude` function\n transcludeFn.isSlotFilled = function(slotName) {\n return !!boundTranscludeFn.$$slots[slotName];\n };\n }\n\n if (controllerDirectives) {\n elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);\n }\n\n if (newIsolateScopeDirective) {\n // Initialize isolate scope bindings for new isolate scope directive.\n compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||\n templateDirective === newIsolateScopeDirective.$$originalDirective)));\n compile.$$addScopeClass($element, true);\n isolateScope.$$isolateBindings =\n newIsolateScopeDirective.$$isolateBindings;\n scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,\n isolateScope.$$isolateBindings,\n newIsolateScopeDirective);\n if (scopeBindingInfo.removeWatches) {\n isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);\n }\n }\n\n // Initialize bindToController bindings\n for (var name in elementControllers) {\n var controllerDirective = controllerDirectives[name];\n var controller = elementControllers[name];\n var bindings = controllerDirective.$$bindings.bindToController;\n\n controller.instance = controller();\n $element.data('$' + controllerDirective.name + 'Controller', controller.instance);\n controller.bindingInfo =\n initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);\n }\n\n // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy\n forEach(controllerDirectives, function(controllerDirective, name) {\n var require = controllerDirective.require;\n if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {\n extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));\n }\n });\n\n // Handle the init and destroy lifecycle hooks on all controllers that have them\n forEach(elementControllers, function(controller) {\n var controllerInstance = controller.instance;\n if (isFunction(controllerInstance.$onChanges)) {\n try {\n controllerInstance.$onChanges(controller.bindingInfo.initialChanges);\n } catch (e) {\n $exceptionHandler(e);\n }\n }\n if (isFunction(controllerInstance.$onInit)) {\n try {\n controllerInstance.$onInit();\n } catch (e) {\n $exceptionHandler(e);\n }\n }\n if (isFunction(controllerInstance.$doCheck)) {\n controllerScope.$watch(function() { controllerInstance.$doCheck(); });\n controllerInstance.$doCheck();\n }\n if (isFunction(controllerInstance.$onDestroy)) {\n controllerScope.$on('$destroy', function callOnDestroyHook() {\n controllerInstance.$onDestroy();\n });\n }\n });\n\n // PRELINKING\n for (i = 0, ii = preLinkFns.length; i < ii; i++) {\n linkFn = preLinkFns[i];\n invokeLinkFn(linkFn,\n linkFn.isolateScope ? isolateScope : scope,\n $element,\n attrs,\n linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),\n transcludeFn\n );\n }\n\n // RECURSION\n // We only pass the isolate scope, if the isolate directive has a template,\n // otherwise the child elements do not belong to the isolate directive.\n var scopeToChild = scope;\n if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {\n scopeToChild = isolateScope;\n }\n if (childLinkFn) {\n childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);\n }\n\n // POSTLINKING\n for (i = postLinkFns.length - 1; i >= 0; i--) {\n linkFn = postLinkFns[i];\n invokeLinkFn(linkFn,\n linkFn.isolateScope ? isolateScope : scope,\n $element,\n attrs,\n linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),\n transcludeFn\n );\n }\n\n // Trigger $postLink lifecycle hooks\n forEach(elementControllers, function(controller) {\n var controllerInstance = controller.instance;\n if (isFunction(controllerInstance.$postLink)) {\n controllerInstance.$postLink();\n }\n });\n\n // This is the function that is injected as `$transclude`.\n // Note: all arguments are optional!\n function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {\n var transcludeControllers;\n // No scope passed in:\n if (!isScope(scope)) {\n slotName = futureParentElement;\n futureParentElement = cloneAttachFn;\n cloneAttachFn = scope;\n scope = undefined;\n }\n\n if (hasElementTranscludeDirective) {\n transcludeControllers = elementControllers;\n }\n if (!futureParentElement) {\n futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;\n }\n if (slotName) {\n // slotTranscludeFn can be one of three things:\n // * a transclude function - a filled slot\n // * `null` - an optional slot that was not filled\n // * `undefined` - a slot that was not declared (i.e. invalid)\n var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];\n if (slotTranscludeFn) {\n return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);\n } else if (isUndefined(slotTranscludeFn)) {\n throw $compileMinErr('noslot',\n 'No parent directive that requires a transclusion with slot name \"{0}\". ' +\n 'Element: {1}',\n slotName, startingTag($element));\n }\n } else {\n return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);\n }\n }\n }\n }\n\n function getControllers(directiveName, require, $element, elementControllers) {\n var value;\n\n if (isString(require)) {\n var match = require.match(REQUIRE_PREFIX_REGEXP);\n var name = require.substring(match[0].length);\n var inheritType = match[1] || match[3];\n var optional = match[2] === '?';\n\n //If only parents then start at the parent element\n if (inheritType === '^^') {\n $element = $element.parent();\n //Otherwise attempt getting the controller from elementControllers in case\n //the element is transcluded (and has no data) and to avoid .data if possible\n } else {\n value = elementControllers && elementControllers[name];\n value = value && value.instance;\n }\n\n if (!value) {\n var dataName = '$' + name + 'Controller';\n\n if (inheritType === '^^' && $element[0] && $element[0].nodeType === NODE_TYPE_DOCUMENT) {\n // inheritedData() uses the documentElement when it finds the document, so we would\n // require from the element itself.\n value = null;\n } else {\n value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);\n }\n }\n\n if (!value && !optional) {\n throw $compileMinErr('ctreq',\n 'Controller \\'{0}\\', required by directive \\'{1}\\', can\\'t be found!',\n name, directiveName);\n }\n } else if (isArray(require)) {\n value = [];\n for (var i = 0, ii = require.length; i < ii; i++) {\n value[i] = getControllers(directiveName, require[i], $element, elementControllers);\n }\n } else if (isObject(require)) {\n value = {};\n forEach(require, function(controller, property) {\n value[property] = getControllers(directiveName, controller, $element, elementControllers);\n });\n }\n\n return value || null;\n }\n\n function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {\n var elementControllers = createMap();\n for (var controllerKey in controllerDirectives) {\n var directive = controllerDirectives[controllerKey];\n var locals = {\n $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,\n $element: $element,\n $attrs: attrs,\n $transclude: transcludeFn\n };\n\n var controller = directive.controller;\n if (controller === '@') {\n controller = attrs[directive.name];\n }\n\n var controllerInstance = $controller(controller, locals, true, directive.controllerAs);\n\n // For directives with element transclusion the element is a comment.\n // In this case .data will not attach any data.\n // Instead, we save the controllers for the element in a local hash and attach to .data\n // later, once we have the actual element.\n elementControllers[directive.name] = controllerInstance;\n $element.data('$' + directive.name + 'Controller', controllerInstance.instance);\n }\n return elementControllers;\n }\n\n // Depending upon the context in which a directive finds itself it might need to have a new isolated\n // or child scope created. For instance:\n // * if the directive has been pulled into a template because another directive with a higher priority\n // asked for element transclusion\n // * if the directive itself asks for transclusion but it is at the root of a template and the original\n // element was replaced. See https://github.com/angular/angular.js/issues/12936\n function markDirectiveScope(directives, isolateScope, newScope) {\n for (var j = 0, jj = directives.length; j < jj; j++) {\n directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});\n }\n }\n\n /**\n * looks up the directive and decorates it with exception handling and proper parameters. We\n * call this the boundDirective.\n *\n * @param {string} name name of the directive to look up.\n * @param {string} location The directive must be found in specific format.\n * String containing any of theses characters:\n *\n * * `E`: element name\n * * `A': attribute\n * * `C`: class\n * * `M`: comment\n * @returns {boolean} true if directive was added.\n */\n function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,\n endAttrName) {\n if (name === ignoreDirective) return null;\n var match = null;\n if (hasDirectives.hasOwnProperty(name)) {\n for (var directive, directives = $injector.get(name + Suffix),\n i = 0, ii = directives.length; i < ii; i++) {\n directive = directives[i];\n if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&\n directive.restrict.indexOf(location) !== -1) {\n if (startAttrName) {\n directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});\n }\n if (!directive.$$bindings) {\n var bindings = directive.$$bindings =\n parseDirectiveBindings(directive, directive.name);\n if (isObject(bindings.isolateScope)) {\n directive.$$isolateBindings = bindings.isolateScope;\n }\n }\n tDirectives.push(directive);\n match = directive;\n }\n }\n }\n return match;\n }\n\n\n /**\n * looks up the directive and returns true if it is a multi-element directive,\n * and therefore requires DOM nodes between -start and -end markers to be grouped\n * together.\n *\n * @param {string} name name of the directive to look up.\n * @returns true if directive was registered as multi-element.\n */\n function directiveIsMultiElement(name) {\n if (hasDirectives.hasOwnProperty(name)) {\n for (var directive, directives = $injector.get(name + Suffix),\n i = 0, ii = directives.length; i < ii; i++) {\n directive = directives[i];\n if (directive.multiElement) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * When the element is replaced with HTML template then the new attributes\n * on the template need to be merged with the existing attributes in the DOM.\n * The desired effect is to have both of the attributes present.\n *\n * @param {object} dst destination attributes (original DOM)\n * @param {object} src source attributes (from the directive template)\n */\n function mergeTemplateAttributes(dst, src) {\n var srcAttr = src.$attr,\n dstAttr = dst.$attr;\n\n // reapply the old attributes to the new element\n forEach(dst, function(value, key) {\n if (key.charAt(0) !== '$') {\n if (src[key] && src[key] !== value) {\n if (value.length) {\n value += (key === 'style' ? ';' : ' ') + src[key];\n } else {\n value = src[key];\n }\n }\n dst.$set(key, value, true, srcAttr[key]);\n }\n });\n\n // copy the new attributes on the old attrs object\n forEach(src, function(value, key) {\n // Check if we already set this attribute in the loop above.\n // `dst` will never contain hasOwnProperty as DOM parser won't let it.\n // You will get an \"InvalidCharacterError: DOM Exception 5\" error if you\n // have an attribute like \"has-own-property\" or \"data-has-own-property\", etc.\n if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {\n dst[key] = value;\n\n if (key !== 'class' && key !== 'style') {\n dstAttr[key] = srcAttr[key];\n }\n }\n });\n }\n\n\n function compileTemplateUrl(directives, $compileNode, tAttrs,\n $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {\n var linkQueue = [],\n afterTemplateNodeLinkFn,\n afterTemplateChildLinkFn,\n beforeTemplateCompileNode = $compileNode[0],\n origAsyncDirective = directives.shift(),\n derivedSyncDirective = inherit(origAsyncDirective, {\n templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective\n }),\n templateUrl = (isFunction(origAsyncDirective.templateUrl))\n ? origAsyncDirective.templateUrl($compileNode, tAttrs)\n : origAsyncDirective.templateUrl,\n templateNamespace = origAsyncDirective.templateNamespace;\n\n $compileNode.empty();\n\n $templateRequest(templateUrl)\n .then(function(content) {\n var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;\n\n content = denormalizeTemplate(content);\n\n if (origAsyncDirective.replace) {\n if (jqLiteIsTextNode(content)) {\n $template = [];\n } else {\n $template = removeComments(wrapTemplate(templateNamespace, trim(content)));\n }\n compileNode = $template[0];\n\n if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {\n throw $compileMinErr('tplrt',\n 'Template for directive \\'{0}\\' must have exactly one root element. {1}',\n origAsyncDirective.name, templateUrl);\n }\n\n tempTemplateAttrs = {$attr: {}};\n replaceWith($rootElement, $compileNode, compileNode);\n var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);\n\n if (isObject(origAsyncDirective.scope)) {\n // the original directive that caused the template to be loaded async required\n // an isolate scope\n markDirectiveScope(templateDirectives, true);\n }\n directives = templateDirectives.concat(directives);\n mergeTemplateAttributes(tAttrs, tempTemplateAttrs);\n } else {\n compileNode = beforeTemplateCompileNode;\n $compileNode.html(content);\n }\n\n directives.unshift(derivedSyncDirective);\n\n afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,\n childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,\n previousCompileContext);\n forEach($rootElement, function(node, i) {\n if (node === compileNode) {\n $rootElement[i] = $compileNode[0];\n }\n });\n afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);\n\n while (linkQueue.length) {\n var scope = linkQueue.shift(),\n beforeTemplateLinkNode = linkQueue.shift(),\n linkRootElement = linkQueue.shift(),\n boundTranscludeFn = linkQueue.shift(),\n linkNode = $compileNode[0];\n\n if (scope.$$destroyed) continue;\n\n if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {\n var oldClasses = beforeTemplateLinkNode.className;\n\n if (!(previousCompileContext.hasElementTranscludeDirective &&\n origAsyncDirective.replace)) {\n // it was cloned therefore we have to clone as well.\n linkNode = jqLiteClone(compileNode);\n }\n replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);\n\n // Copy in CSS classes from original node\n safeAddClass(jqLite(linkNode), oldClasses);\n }\n if (afterTemplateNodeLinkFn.transcludeOnThisElement) {\n childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);\n } else {\n childBoundTranscludeFn = boundTranscludeFn;\n }\n afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,\n childBoundTranscludeFn);\n }\n linkQueue = null;\n }).catch(function(error) {\n if (isError(error)) {\n $exceptionHandler(error);\n }\n });\n\n return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {\n var childBoundTranscludeFn = boundTranscludeFn;\n if (scope.$$destroyed) return;\n if (linkQueue) {\n linkQueue.push(scope,\n node,\n rootElement,\n childBoundTranscludeFn);\n } else {\n if (afterTemplateNodeLinkFn.transcludeOnThisElement) {\n childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);\n }\n afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);\n }\n };\n }\n\n\n /**\n * Sorting function for bound directives.\n */\n function byPriority(a, b) {\n var diff = b.priority - a.priority;\n if (diff !== 0) return diff;\n if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;\n return a.index - b.index;\n }\n\n function assertNoDuplicate(what, previousDirective, directive, element) {\n\n function wrapModuleNameIfDefined(moduleName) {\n return moduleName ?\n (' (module: ' + moduleName + ')') :\n '';\n }\n\n if (previousDirective) {\n throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',\n previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),\n directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));\n }\n }\n\n\n function addTextInterpolateDirective(directives, text) {\n var interpolateFn = $interpolate(text, true);\n if (interpolateFn) {\n directives.push({\n priority: 0,\n compile: function textInterpolateCompileFn(templateNode) {\n var templateNodeParent = templateNode.parent(),\n hasCompileParent = !!templateNodeParent.length;\n\n // When transcluding a template that has bindings in the root\n // we don't have a parent and thus need to add the class during linking fn.\n if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);\n\n return function textInterpolateLinkFn(scope, node) {\n var parent = node.parent();\n if (!hasCompileParent) compile.$$addBindingClass(parent);\n compile.$$addBindingInfo(parent, interpolateFn.expressions);\n scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {\n node[0].nodeValue = value;\n });\n };\n }\n });\n }\n }\n\n\n function wrapTemplate(type, template) {\n type = lowercase(type || 'html');\n switch (type) {\n case 'svg':\n case 'math':\n var wrapper = window.document.createElement('div');\n wrapper.innerHTML = '<' + type + '>' + template + '';\n return wrapper.childNodes[0].childNodes;\n default:\n return template;\n }\n }\n\n\n function getTrustedAttrContext(nodeName, attrNormalizedName) {\n if (attrNormalizedName === 'srcdoc') {\n return $sce.HTML;\n }\n // All nodes with src attributes require a RESOURCE_URL value, except for\n // img and various html5 media nodes, which require the MEDIA_URL context.\n if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') {\n if (['img', 'video', 'audio', 'source', 'track'].indexOf(nodeName) === -1) {\n return $sce.RESOURCE_URL;\n }\n return $sce.MEDIA_URL;\n } else if (attrNormalizedName === 'xlinkHref') {\n // Some xlink:href are okay, most aren't\n if (nodeName === 'image') return $sce.MEDIA_URL;\n if (nodeName === 'a') return $sce.URL;\n return $sce.RESOURCE_URL;\n } else if (\n // Formaction\n (nodeName === 'form' && attrNormalizedName === 'action') ||\n // If relative URLs can go where they are not expected to, then\n // all sorts of trust issues can arise.\n (nodeName === 'base' && attrNormalizedName === 'href') ||\n // links can be stylesheets or imports, which can run script in the current origin\n (nodeName === 'link' && attrNormalizedName === 'href')\n ) {\n return $sce.RESOURCE_URL;\n } else if (nodeName === 'a' && (attrNormalizedName === 'href' ||\n attrNormalizedName === 'ngHref')) {\n return $sce.URL;\n }\n }\n\n function getTrustedPropContext(nodeName, propNormalizedName) {\n var prop = propNormalizedName.toLowerCase();\n return PROP_CONTEXTS[nodeName + '|' + prop] || PROP_CONTEXTS['*|' + prop];\n }\n\n function sanitizeSrcsetPropertyValue(value) {\n return sanitizeSrcset($sce.valueOf(value), 'ng-prop-srcset');\n }\n function addPropertyDirective(node, directives, attrName, propName) {\n if (EVENT_HANDLER_ATTR_REGEXP.test(propName)) {\n throw $compileMinErr('nodomevents', 'Property bindings for HTML DOM event properties are disallowed');\n }\n\n var nodeName = nodeName_(node);\n var trustedContext = getTrustedPropContext(nodeName, propName);\n\n var sanitizer = identity;\n // Sanitize img[srcset] + source[srcset] values.\n if (propName === 'srcset' && (nodeName === 'img' || nodeName === 'source')) {\n sanitizer = sanitizeSrcsetPropertyValue;\n } else if (trustedContext) {\n sanitizer = $sce.getTrusted.bind($sce, trustedContext);\n }\n\n directives.push({\n priority: 100,\n compile: function ngPropCompileFn(_, attr) {\n var ngPropGetter = $parse(attr[attrName]);\n var ngPropWatch = $parse(attr[attrName], function sceValueOf(val) {\n // Unwrap the value to compare the actual inner safe value, not the wrapper object.\n return $sce.valueOf(val);\n });\n\n return {\n pre: function ngPropPreLinkFn(scope, $element) {\n function applyPropValue() {\n var propValue = ngPropGetter(scope);\n $element[0][propName] = sanitizer(propValue);\n }\n\n applyPropValue();\n scope.$watch(ngPropWatch, applyPropValue);\n }\n };\n }\n });\n }\n\n function addEventDirective(directives, attrName, eventName) {\n directives.push(\n createEventDirective($parse, $rootScope, $exceptionHandler, attrName, eventName, /*forceAsync=*/false)\n );\n }\n\n function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) {\n var nodeName = nodeName_(node);\n var trustedContext = getTrustedAttrContext(nodeName, name);\n var mustHaveExpression = !isNgAttr;\n var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr;\n\n var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing);\n\n // no interpolation found -> ignore\n if (!interpolateFn) return;\n\n if (name === 'multiple' && nodeName === 'select') {\n throw $compileMinErr('selmulti',\n 'Binding to the \\'multiple\\' attribute is not supported. Element: {0}',\n startingTag(node));\n }\n\n if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {\n throw $compileMinErr('nodomevents', 'Interpolations for HTML DOM event attributes are disallowed');\n }\n\n directives.push({\n priority: 100,\n compile: function() {\n return {\n pre: function attrInterpolatePreLinkFn(scope, element, attr) {\n var $$observers = (attr.$$observers || (attr.$$observers = createMap()));\n\n // If the attribute has changed since last $interpolate()ed\n var newValue = attr[name];\n if (newValue !== value) {\n // we need to interpolate again since the attribute value has been updated\n // (e.g. by another directive's compile function)\n // ensure unset/empty values make interpolateFn falsy\n interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);\n value = newValue;\n }\n\n // if attribute was updated so that there is no interpolation going on we don't want to\n // register any observers\n if (!interpolateFn) return;\n\n // initialize attr object so that it's ready in case we need the value for isolate\n // scope initialization, otherwise the value would not be available from isolate\n // directive's linking fn during linking phase\n attr[name] = interpolateFn(scope);\n\n ($$observers[name] || ($$observers[name] = [])).$$inter = true;\n (attr.$$observers && attr.$$observers[name].$$scope || scope).\n $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {\n //special case for class attribute addition + removal\n //so that class changes can tap into the animation\n //hooks provided by the $animate service. Be sure to\n //skip animations when the first digest occurs (when\n //both the new and the old values are the same) since\n //the CSS classes are the non-interpolated values\n if (name === 'class' && newValue !== oldValue) {\n attr.$updateClass(newValue, oldValue);\n } else {\n attr.$set(name, newValue);\n }\n });\n }\n };\n }\n });\n }\n\n\n /**\n * This is a special jqLite.replaceWith, which can replace items which\n * have no parents, provided that the containing jqLite collection is provided.\n *\n * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes\n * in the root of the tree.\n * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep\n * the shell, but replace its DOM node reference.\n * @param {Node} newNode The new DOM node.\n */\n function replaceWith($rootElement, elementsToRemove, newNode) {\n var firstElementToRemove = elementsToRemove[0],\n removeCount = elementsToRemove.length,\n parent = firstElementToRemove.parentNode,\n i, ii;\n\n if ($rootElement) {\n for (i = 0, ii = $rootElement.length; i < ii; i++) {\n if ($rootElement[i] === firstElementToRemove) {\n $rootElement[i++] = newNode;\n for (var j = i, j2 = j + removeCount - 1,\n jj = $rootElement.length;\n j < jj; j++, j2++) {\n if (j2 < jj) {\n $rootElement[j] = $rootElement[j2];\n } else {\n delete $rootElement[j];\n }\n }\n $rootElement.length -= removeCount - 1;\n\n // If the replaced element is also the jQuery .context then replace it\n // .context is a deprecated jQuery api, so we should set it only when jQuery set it\n // http://api.jquery.com/context/\n if ($rootElement.context === firstElementToRemove) {\n $rootElement.context = newNode;\n }\n break;\n }\n }\n }\n\n if (parent) {\n parent.replaceChild(newNode, firstElementToRemove);\n }\n\n // Append all the `elementsToRemove` to a fragment. This will...\n // - remove them from the DOM\n // - allow them to still be traversed with .nextSibling\n // - allow a single fragment.qSA to fetch all elements being removed\n var fragment = window.document.createDocumentFragment();\n for (i = 0; i < removeCount; i++) {\n fragment.appendChild(elementsToRemove[i]);\n }\n\n if (jqLite.hasData(firstElementToRemove)) {\n // Copy over user data (that includes AngularJS's $scope etc.). Don't copy private\n // data here because there's no public interface in jQuery to do that and copying over\n // event listeners (which is the main use of private data) wouldn't work anyway.\n jqLite.data(newNode, jqLite.data(firstElementToRemove));\n\n // Remove $destroy event listeners from `firstElementToRemove`\n jqLite(firstElementToRemove).off('$destroy');\n }\n\n // Cleanup any data/listeners on the elements and children.\n // This includes invoking the $destroy event on any elements with listeners.\n jqLite.cleanData(fragment.querySelectorAll('*'));\n\n // Update the jqLite collection to only contain the `newNode`\n for (i = 1; i < removeCount; i++) {\n delete elementsToRemove[i];\n }\n elementsToRemove[0] = newNode;\n elementsToRemove.length = 1;\n }\n\n\n function cloneAndAnnotateFn(fn, annotation) {\n return extend(function() { return fn.apply(null, arguments); }, fn, annotation);\n }\n\n\n function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {\n try {\n linkFn(scope, $element, attrs, controllers, transcludeFn);\n } catch (e) {\n $exceptionHandler(e, startingTag($element));\n }\n }\n\n function strictBindingsCheck(attrName, directiveName) {\n if (strictComponentBindingsEnabled) {\n throw $compileMinErr('missingattr',\n 'Attribute \\'{0}\\' of \\'{1}\\' is non-optional and must be set!',\n attrName, directiveName);\n }\n }\n\n // Set up $watches for isolate scope and controller bindings.\n function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {\n var removeWatchCollection = [];\n var initialChanges = {};\n var changes;\n\n forEach(bindings, function initializeBinding(definition, scopeName) {\n var attrName = definition.attrName,\n optional = definition.optional,\n mode = definition.mode, // @, =, <, or &\n lastValue,\n parentGet, parentSet, compare, removeWatch;\n\n switch (mode) {\n\n case '@':\n if (!optional && !hasOwnProperty.call(attrs, attrName)) {\n strictBindingsCheck(attrName, directive.name);\n destination[scopeName] = attrs[attrName] = undefined;\n\n }\n removeWatch = attrs.$observe(attrName, function(value) {\n if (isString(value) || isBoolean(value)) {\n var oldValue = destination[scopeName];\n recordChanges(scopeName, value, oldValue);\n destination[scopeName] = value;\n }\n });\n attrs.$$observers[attrName].$$scope = scope;\n lastValue = attrs[attrName];\n if (isString(lastValue)) {\n // If the attribute has been provided then we trigger an interpolation to ensure\n // the value is there for use in the link fn\n destination[scopeName] = $interpolate(lastValue)(scope);\n } else if (isBoolean(lastValue)) {\n // If the attributes is one of the BOOLEAN_ATTR then AngularJS will have converted\n // the value to boolean rather than a string, so we special case this situation\n destination[scopeName] = lastValue;\n }\n initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);\n removeWatchCollection.push(removeWatch);\n break;\n\n case '=':\n if (!hasOwnProperty.call(attrs, attrName)) {\n if (optional) break;\n strictBindingsCheck(attrName, directive.name);\n attrs[attrName] = undefined;\n }\n if (optional && !attrs[attrName]) break;\n\n parentGet = $parse(attrs[attrName]);\n if (parentGet.literal) {\n compare = equals;\n } else {\n compare = simpleCompare;\n }\n parentSet = parentGet.assign || function() {\n // reset the change, or we will throw this exception on every $digest\n lastValue = destination[scopeName] = parentGet(scope);\n throw $compileMinErr('nonassign',\n 'Expression \\'{0}\\' in attribute \\'{1}\\' used with directive \\'{2}\\' is non-assignable!',\n attrs[attrName], attrName, directive.name);\n };\n lastValue = destination[scopeName] = parentGet(scope);\n var parentValueWatch = function parentValueWatch(parentValue) {\n if (!compare(parentValue, destination[scopeName])) {\n // we are out of sync and need to copy\n if (!compare(parentValue, lastValue)) {\n // parent changed and it has precedence\n destination[scopeName] = parentValue;\n } else {\n // if the parent can be assigned then do so\n parentSet(scope, parentValue = destination[scopeName]);\n }\n }\n lastValue = parentValue;\n return lastValue;\n };\n parentValueWatch.$stateful = true;\n if (definition.collection) {\n removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);\n } else {\n removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);\n }\n removeWatchCollection.push(removeWatch);\n break;\n\n case '<':\n if (!hasOwnProperty.call(attrs, attrName)) {\n if (optional) break;\n strictBindingsCheck(attrName, directive.name);\n attrs[attrName] = undefined;\n }\n if (optional && !attrs[attrName]) break;\n\n parentGet = $parse(attrs[attrName]);\n var isLiteral = parentGet.literal;\n\n var initialValue = destination[scopeName] = parentGet(scope);\n initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);\n\n removeWatch = scope[definition.collection ? '$watchCollection' : '$watch'](parentGet, function parentValueWatchAction(newValue, oldValue) {\n if (oldValue === newValue) {\n if (oldValue === initialValue || (isLiteral && equals(oldValue, initialValue))) {\n return;\n }\n oldValue = initialValue;\n }\n recordChanges(scopeName, newValue, oldValue);\n destination[scopeName] = newValue;\n });\n\n removeWatchCollection.push(removeWatch);\n break;\n\n case '&':\n if (!optional && !hasOwnProperty.call(attrs, attrName)) {\n strictBindingsCheck(attrName, directive.name);\n }\n // Don't assign Object.prototype method to scope\n parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;\n\n // Don't assign noop to destination if expression is not valid\n if (parentGet === noop && optional) break;\n\n destination[scopeName] = function(locals) {\n return parentGet(scope, locals);\n };\n break;\n }\n });\n\n function recordChanges(key, currentValue, previousValue) {\n if (isFunction(destination.$onChanges) && !simpleCompare(currentValue, previousValue)) {\n // If we have not already scheduled the top level onChangesQueue handler then do so now\n if (!onChangesQueue) {\n scope.$$postDigest(flushOnChangesQueue);\n onChangesQueue = [];\n }\n // If we have not already queued a trigger of onChanges for this controller then do so now\n if (!changes) {\n changes = {};\n onChangesQueue.push(triggerOnChangesHook);\n }\n // If the has been a change on this property already then we need to reuse the previous value\n if (changes[key]) {\n previousValue = changes[key].previousValue;\n }\n // Store this change\n changes[key] = new SimpleChange(previousValue, currentValue);\n }\n }\n\n function triggerOnChangesHook() {\n destination.$onChanges(changes);\n // Now clear the changes so that we schedule onChanges when more changes arrive\n changes = undefined;\n }\n\n return {\n initialChanges: initialChanges,\n removeWatches: removeWatchCollection.length && function removeWatches() {\n for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {\n removeWatchCollection[i]();\n }\n }\n };\n }\n }];\n}\n\nfunction SimpleChange(previous, current) {\n this.previousValue = previous;\n this.currentValue = current;\n}\nSimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };\n\n\nvar PREFIX_REGEXP = /^((?:x|data)[:\\-_])/i;\nvar SPECIAL_CHARS_REGEXP = /[:\\-_]+(.)/g;\n\n/**\n * Converts all accepted directives format into proper directive name.\n * @param name Name to normalize\n */\nfunction directiveNormalize(name) {\n return name\n .replace(PREFIX_REGEXP, '')\n .replace(SPECIAL_CHARS_REGEXP, function(_, letter, offset) {\n return offset ? letter.toUpperCase() : letter;\n });\n}\n\n/**\n * @ngdoc type\n * @name $compile.directive.Attributes\n *\n * @description\n * A shared object between directive compile / linking functions which contains normalized DOM\n * element attributes. The values reflect current binding state `{{ }}`. The normalization is\n * needed since all of these are treated as equivalent in AngularJS:\n *\n * ```\n * \n * ```\n */\n\n/**\n * @ngdoc property\n * @name $compile.directive.Attributes#$attr\n *\n * @description\n * A map of DOM element attribute names to the normalized name. This is\n * needed to do reverse lookup from normalized name back to actual name.\n */\n\n\n/**\n * @ngdoc method\n * @name $compile.directive.Attributes#$set\n * @kind function\n *\n * @description\n * Set DOM element attribute value.\n *\n *\n * @param {string} name Normalized element attribute name of the property to modify. The name is\n * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}\n * property to the original name.\n * @param {string} value Value to set the attribute to. The value can be an interpolated string.\n */\n\n\n\n/**\n * Closure compiler type information\n */\n\nfunction nodesetLinkingFn(\n /* angular.Scope */ scope,\n /* NodeList */ nodeList,\n /* Element */ rootElement,\n /* function(Function) */ boundTranscludeFn\n) {}\n\nfunction directiveLinkingFn(\n /* nodesetLinkingFn */ nodesetLinkingFn,\n /* angular.Scope */ scope,\n /* Node */ node,\n /* Element */ rootElement,\n /* function(Function) */ boundTranscludeFn\n) {}\n\nfunction tokenDifference(str1, str2) {\n var values = '',\n tokens1 = str1.split(/\\s+/),\n tokens2 = str2.split(/\\s+/);\n\n outer:\n for (var i = 0; i < tokens1.length; i++) {\n var token = tokens1[i];\n for (var j = 0; j < tokens2.length; j++) {\n if (token === tokens2[j]) continue outer;\n }\n values += (values.length > 0 ? ' ' : '') + token;\n }\n return values;\n}\n\nfunction removeComments(jqNodes) {\n jqNodes = jqLite(jqNodes);\n var i = jqNodes.length;\n\n if (i <= 1) {\n return jqNodes;\n }\n\n while (i--) {\n var node = jqNodes[i];\n if (node.nodeType === NODE_TYPE_COMMENT ||\n (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) {\n splice.call(jqNodes, i, 1);\n }\n }\n return jqNodes;\n}\n\nvar $controllerMinErr = minErr('$controller');\n\n\nvar CNTRL_REG = /^(\\S+)(\\s+as\\s+([\\w$]+))?$/;\nfunction identifierForController(controller, ident) {\n if (ident && isString(ident)) return ident;\n if (isString(controller)) {\n var match = CNTRL_REG.exec(controller);\n if (match) return match[3];\n }\n}\n\n\n/**\n * @ngdoc provider\n * @name $controllerProvider\n * @this\n *\n * @description\n * The {@link ng.$controller $controller service} is used by AngularJS to create new\n * controllers.\n *\n * This provider allows controller registration via the\n * {@link ng.$controllerProvider#register register} method.\n */\nfunction $ControllerProvider() {\n var controllers = {};\n\n /**\n * @ngdoc method\n * @name $controllerProvider#has\n * @param {string} name Controller name to check.\n */\n this.has = function(name) {\n return controllers.hasOwnProperty(name);\n };\n\n /**\n * @ngdoc method\n * @name $controllerProvider#register\n * @param {string|Object} name Controller name, or an object map of controllers where the keys are\n * the names and the values are the constructors.\n * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI\n * annotations in the array notation).\n */\n this.register = function(name, constructor) {\n assertNotHasOwnProperty(name, 'controller');\n if (isObject(name)) {\n extend(controllers, name);\n } else {\n controllers[name] = constructor;\n }\n };\n\n this.$get = ['$injector', function($injector) {\n\n /**\n * @ngdoc service\n * @name $controller\n * @requires $injector\n *\n * @param {Function|string} constructor If called with a function then it's considered to be the\n * controller constructor function. Otherwise it's considered to be a string which is used\n * to retrieve the controller constructor using the following steps:\n *\n * * check if a controller with given name is registered via `$controllerProvider`\n * * check if evaluating the string on the current scope returns a constructor\n *\n * The string can use the `controller as property` syntax, where the controller instance is published\n * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this\n * to work correctly.\n *\n * @param {Object} locals Injection locals for Controller.\n * @return {Object} Instance of given controller.\n *\n * @description\n * `$controller` service is responsible for instantiating controllers.\n *\n * It's just a simple call to {@link auto.$injector $injector}, but extracted into\n * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).\n */\n return function $controller(expression, locals, later, ident) {\n // PRIVATE API:\n // param `later` --- indicates that the controller's constructor is invoked at a later time.\n // If true, $controller will allocate the object with the correct\n // prototype chain, but will not invoke the controller until a returned\n // callback is invoked.\n // param `ident` --- An optional label which overrides the label parsed from the controller\n // expression, if any.\n var instance, match, constructor, identifier;\n later = later === true;\n if (ident && isString(ident)) {\n identifier = ident;\n }\n\n if (isString(expression)) {\n match = expression.match(CNTRL_REG);\n if (!match) {\n throw $controllerMinErr('ctrlfmt',\n 'Badly formed controller string \\'{0}\\'. ' +\n 'Must match `__name__ as __id__` or `__name__`.', expression);\n }\n constructor = match[1];\n identifier = identifier || match[3];\n expression = controllers.hasOwnProperty(constructor)\n ? controllers[constructor]\n : getter(locals.$scope, constructor, true);\n\n if (!expression) {\n throw $controllerMinErr('ctrlreg',\n 'The controller with the name \\'{0}\\' is not registered.', constructor);\n }\n\n assertArgFn(expression, constructor, true);\n }\n\n if (later) {\n // Instantiate controller later:\n // This machinery is used to create an instance of the object before calling the\n // controller's constructor itself.\n //\n // This allows properties to be added to the controller before the constructor is\n // invoked. Primarily, this is used for isolate scope bindings in $compile.\n //\n // This feature is not intended for use by applications, and is thus not documented\n // publicly.\n // Object creation: http://jsperf.com/create-constructor/2\n var controllerPrototype = (isArray(expression) ?\n expression[expression.length - 1] : expression).prototype;\n instance = Object.create(controllerPrototype || null);\n\n if (identifier) {\n addIdentifier(locals, identifier, instance, constructor || expression.name);\n }\n\n return extend(function $controllerInit() {\n var result = $injector.invoke(expression, instance, locals, constructor);\n if (result !== instance && (isObject(result) || isFunction(result))) {\n instance = result;\n if (identifier) {\n // If result changed, re-assign controllerAs value to scope.\n addIdentifier(locals, identifier, instance, constructor || expression.name);\n }\n }\n return instance;\n }, {\n instance: instance,\n identifier: identifier\n });\n }\n\n instance = $injector.instantiate(expression, locals, constructor);\n\n if (identifier) {\n addIdentifier(locals, identifier, instance, constructor || expression.name);\n }\n\n return instance;\n };\n\n function addIdentifier(locals, identifier, instance, name) {\n if (!(locals && isObject(locals.$scope))) {\n throw minErr('$controller')('noscp',\n 'Cannot export controller \\'{0}\\' as \\'{1}\\'! No $scope object provided via `locals`.',\n name, identifier);\n }\n\n locals.$scope[identifier] = instance;\n }\n }];\n}\n\n/**\n * @ngdoc service\n * @name $document\n * @requires $window\n * @this\n *\n * @description\n * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.\n *\n * @example\n \n \n
\n

$document title:

\n

window.document title:

\n
\n
\n \n angular.module('documentExample', [])\n .controller('ExampleController', ['$scope', '$document', function($scope, $document) {\n $scope.title = $document[0].title;\n $scope.windowTitle = angular.element(window.document)[0].title;\n }]);\n \n
\n */\nfunction $DocumentProvider() {\n this.$get = ['$window', function(window) {\n return jqLite(window.document);\n }];\n}\n\n\n/**\n * @private\n * @this\n * Listens for document visibility change and makes the current status accessible.\n */\nfunction $$IsDocumentHiddenProvider() {\n this.$get = ['$document', '$rootScope', function($document, $rootScope) {\n var doc = $document[0];\n var hidden = doc && doc.hidden;\n\n $document.on('visibilitychange', changeListener);\n\n $rootScope.$on('$destroy', function() {\n $document.off('visibilitychange', changeListener);\n });\n\n function changeListener() {\n hidden = doc.hidden;\n }\n\n return function() {\n return hidden;\n };\n }];\n}\n\n/**\n * @ngdoc service\n * @name $exceptionHandler\n * @requires ng.$log\n * @this\n *\n * @description\n * Any uncaught exception in AngularJS expressions is delegated to this service.\n * The default implementation simply delegates to `$log.error` which logs it into\n * the browser console.\n *\n * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by\n * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.\n *\n * ## Example:\n *\n * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught\n * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead\n * of `$log.error()`.\n *\n * ```js\n * angular.\n * module('exceptionOverwrite', []).\n * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {\n * return function myExceptionHandler(exception, cause) {\n * logErrorsToBackend(exception, cause);\n * $log.warn(exception, cause);\n * };\n * }]);\n * ```\n *\n *
\n * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`\n * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}\n * (unless executed during a digest).\n *\n * If you wish, you can manually delegate exceptions, e.g.\n * `try { ... } catch(e) { $exceptionHandler(e); }`\n *\n * @param {Error} exception Exception associated with the error.\n * @param {string=} cause Optional information about the context in which\n * the error was thrown.\n *\n */\nfunction $ExceptionHandlerProvider() {\n this.$get = ['$log', function($log) {\n return function(exception, cause) {\n $log.error.apply($log, arguments);\n };\n }];\n}\n\nvar $$ForceReflowProvider = /** @this */ function() {\n this.$get = ['$document', function($document) {\n return function(domNode) {\n //the line below will force the browser to perform a repaint so\n //that all the animated elements within the animation frame will\n //be properly updated and drawn on screen. This is required to\n //ensure that the preparation animation is properly flushed so that\n //the active state picks up from there. DO NOT REMOVE THIS LINE.\n //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH\n //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND\n //WILL TAKE YEARS AWAY FROM YOUR LIFE.\n if (domNode) {\n if (!domNode.nodeType && domNode instanceof jqLite) {\n domNode = domNode[0];\n }\n } else {\n domNode = $document[0].body;\n }\n return domNode.offsetWidth + 1;\n };\n }];\n};\n\nvar APPLICATION_JSON = 'application/json';\nvar CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};\nvar JSON_START = /^\\[|^\\{(?!\\{)/;\nvar JSON_ENDS = {\n '[': /]$/,\n '{': /}$/\n};\nvar JSON_PROTECTION_PREFIX = /^\\)]\\}',?\\n/;\nvar $httpMinErr = minErr('$http');\n\nfunction serializeValue(v) {\n if (isObject(v)) {\n return isDate(v) ? v.toISOString() : toJson(v);\n }\n return v;\n}\n\n\n/** @this */\nfunction $HttpParamSerializerProvider() {\n /**\n * @ngdoc service\n * @name $httpParamSerializer\n * @description\n *\n * Default {@link $http `$http`} params serializer that converts objects to strings\n * according to the following rules:\n *\n * * `{'foo': 'bar'}` results in `foo=bar`\n * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)\n * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)\n * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)\n *\n * Note that serializer will sort the request parameters alphabetically.\n */\n\n this.$get = function() {\n return function ngParamSerializer(params) {\n if (!params) return '';\n var parts = [];\n forEachSorted(params, function(value, key) {\n if (value === null || isUndefined(value) || isFunction(value)) return;\n if (isArray(value)) {\n forEach(value, function(v) {\n parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));\n });\n } else {\n parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));\n }\n });\n\n return parts.join('&');\n };\n };\n}\n\n/** @this */\nfunction $HttpParamSerializerJQLikeProvider() {\n /**\n * @ngdoc service\n * @name $httpParamSerializerJQLike\n *\n * @description\n *\n * Alternative {@link $http `$http`} params serializer that follows\n * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.\n * The serializer will also sort the params alphabetically.\n *\n * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:\n *\n * ```js\n * $http({\n * url: myUrl,\n * method: 'GET',\n * params: myParams,\n * paramSerializer: '$httpParamSerializerJQLike'\n * });\n * ```\n *\n * It is also possible to set it as the default `paramSerializer` in the\n * {@link $httpProvider#defaults `$httpProvider`}.\n *\n * Additionally, you can inject the serializer and use it explicitly, for example to serialize\n * form data for submission:\n *\n * ```js\n * .controller(function($http, $httpParamSerializerJQLike) {\n * //...\n *\n * $http({\n * url: myUrl,\n * method: 'POST',\n * data: $httpParamSerializerJQLike(myData),\n * headers: {\n * 'Content-Type': 'application/x-www-form-urlencoded'\n * }\n * });\n *\n * });\n * ```\n *\n */\n this.$get = function() {\n return function jQueryLikeParamSerializer(params) {\n if (!params) return '';\n var parts = [];\n serialize(params, '', true);\n return parts.join('&');\n\n function serialize(toSerialize, prefix, topLevel) {\n if (isArray(toSerialize)) {\n forEach(toSerialize, function(value, index) {\n serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');\n });\n } else if (isObject(toSerialize) && !isDate(toSerialize)) {\n forEachSorted(toSerialize, function(value, key) {\n serialize(value, prefix +\n (topLevel ? '' : '[') +\n key +\n (topLevel ? '' : ']'));\n });\n } else {\n if (isFunction(toSerialize)) {\n toSerialize = toSerialize();\n }\n parts.push(encodeUriQuery(prefix) + '=' +\n (toSerialize == null ? '' : encodeUriQuery(serializeValue(toSerialize))));\n }\n }\n };\n };\n}\n\nfunction defaultHttpResponseTransform(data, headers) {\n if (isString(data)) {\n // Strip json vulnerability protection prefix and trim whitespace\n var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();\n\n if (tempData) {\n var contentType = headers('Content-Type');\n var hasJsonContentType = contentType && (contentType.indexOf(APPLICATION_JSON) === 0);\n\n if (hasJsonContentType || isJsonLike(tempData)) {\n try {\n data = fromJson(tempData);\n } catch (e) {\n if (!hasJsonContentType) {\n return data;\n }\n throw $httpMinErr('baddata', 'Data must be a valid JSON object. Received: \"{0}\". ' +\n 'Parse error: \"{1}\"', data, e);\n }\n }\n }\n }\n\n return data;\n}\n\nfunction isJsonLike(str) {\n var jsonStart = str.match(JSON_START);\n return jsonStart && JSON_ENDS[jsonStart[0]].test(str);\n}\n\n/**\n * Parse headers into key value object\n *\n * @param {string} headers Raw headers as a string\n * @returns {Object} Parsed headers as key value object\n */\nfunction parseHeaders(headers) {\n var parsed = createMap(), i;\n\n function fillInParsed(key, val) {\n if (key) {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n }\n\n if (isString(headers)) {\n forEach(headers.split('\\n'), function(line) {\n i = line.indexOf(':');\n fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));\n });\n } else if (isObject(headers)) {\n forEach(headers, function(headerVal, headerKey) {\n fillInParsed(lowercase(headerKey), trim(headerVal));\n });\n }\n\n return parsed;\n}\n\n\n/**\n * Returns a function that provides access to parsed headers.\n *\n * Headers are lazy parsed when first requested.\n * @see parseHeaders\n *\n * @param {(string|Object)} headers Headers to provide access to.\n * @returns {function(string=)} Returns a getter function which if called with:\n *\n * - if called with an argument returns a single header value or null\n * - if called with no arguments returns an object containing all headers.\n */\nfunction headersGetter(headers) {\n var headersObj;\n\n return function(name) {\n if (!headersObj) headersObj = parseHeaders(headers);\n\n if (name) {\n var value = headersObj[lowercase(name)];\n if (value === undefined) {\n value = null;\n }\n return value;\n }\n\n return headersObj;\n };\n}\n\n\n/**\n * Chain all given functions\n *\n * This function is used for both request and response transforming\n *\n * @param {*} data Data to transform.\n * @param {function(string=)} headers HTTP headers getter fn.\n * @param {number} status HTTP status code of the response.\n * @param {(Function|Array.)} fns Function or an array of functions.\n * @returns {*} Transformed data.\n */\nfunction transformData(data, headers, status, fns) {\n if (isFunction(fns)) {\n return fns(data, headers, status);\n }\n\n forEach(fns, function(fn) {\n data = fn(data, headers, status);\n });\n\n return data;\n}\n\n\nfunction isSuccess(status) {\n return 200 <= status && status < 300;\n}\n\n\n/**\n * @ngdoc provider\n * @name $httpProvider\n * @this\n *\n * @description\n * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.\n */\nfunction $HttpProvider() {\n /**\n * @ngdoc property\n * @name $httpProvider#defaults\n * @description\n *\n * Object containing default values for all {@link ng.$http $http} requests.\n *\n * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with\n * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses\n * by default. See {@link $http#caching $http Caching} for more information.\n *\n * - **`defaults.headers`** - {Object} - Default headers for all $http requests.\n * Refer to {@link ng.$http#setting-http-headers $http} for documentation on\n * setting default headers.\n * - **`defaults.headers.common`**\n * - **`defaults.headers.post`**\n * - **`defaults.headers.put`**\n * - **`defaults.headers.patch`**\n *\n * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the\n * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the\n * {@link $jsonpCallbacks} service. Defaults to `'callback'`.\n *\n * - **`defaults.paramSerializer`** - `{string|function(Object):string}` - A function\n * used to the prepare string representation of request parameters (specified as an object).\n * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.\n * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.\n *\n * - **`defaults.transformRequest`** -\n * `{Array|function(data, headersGetter)}` -\n * An array of functions (or a single function) which are applied to the request data.\n * By default, this is an array with one request transformation function:\n *\n * - If the `data` property of the request configuration object contains an object, serialize it\n * into JSON format.\n *\n * - **`defaults.transformResponse`** -\n * `{Array|function(data, headersGetter, status)}` -\n * An array of functions (or a single function) which are applied to the response data. By default,\n * this is an array which applies one response transformation function that does two things:\n *\n * - If XSRF prefix is detected, strip it\n * (see {@link ng.$http#security-considerations Security Considerations in the $http docs}).\n * - If the `Content-Type` is `application/json` or the response looks like JSON,\n * deserialize it using a JSON parser.\n *\n * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.\n * Defaults value is `'XSRF-TOKEN'`.\n *\n * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the\n * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.\n *\n */\n var defaults = this.defaults = {\n // transform incoming response data\n transformResponse: [defaultHttpResponseTransform],\n\n // transform outgoing request data\n transformRequest: [function(d) {\n return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;\n }],\n\n // default headers\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n },\n post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),\n put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),\n patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)\n },\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n paramSerializer: '$httpParamSerializer',\n\n jsonpCallbackParam: 'callback'\n };\n\n var useApplyAsync = false;\n /**\n * @ngdoc method\n * @name $httpProvider#useApplyAsync\n * @description\n *\n * Configure $http service to combine processing of multiple http responses received at around\n * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in\n * significant performance improvement for bigger applications that make many HTTP requests\n * concurrently (common during application bootstrap).\n *\n * Defaults to false. If no value is specified, returns the current configured value.\n *\n * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred\n * \"apply\" on the next tick, giving time for subsequent requests in a roughly ~10ms window\n * to load and share the same digest cycle.\n *\n * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.\n * otherwise, returns the current configured value.\n */\n this.useApplyAsync = function(value) {\n if (isDefined(value)) {\n useApplyAsync = !!value;\n return this;\n }\n return useApplyAsync;\n };\n\n /**\n * @ngdoc property\n * @name $httpProvider#interceptors\n * @description\n *\n * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}\n * pre-processing of request or postprocessing of responses.\n *\n * These service factories are ordered by request, i.e. they are applied in the same order as the\n * array, on request, but reverse order, on response.\n *\n * {@link ng.$http#interceptors Interceptors detailed info}\n */\n var interceptorFactories = this.interceptors = [];\n\n /**\n * @ngdoc property\n * @name $httpProvider#xsrfWhitelistedOrigins\n * @description\n *\n * Array containing URLs whose origins are trusted to receive the XSRF token. See the\n * {@link ng.$http#security-considerations Security Considerations} sections for more details on\n * XSRF.\n *\n * **Note:** An \"origin\" consists of the [URI scheme](https://en.wikipedia.org/wiki/URI_scheme),\n * the [hostname](https://en.wikipedia.org/wiki/Hostname) and the\n * [port number](https://en.wikipedia.org/wiki/Port_(computer_networking). For `http:` and\n * `https:`, the port number can be omitted if using th default ports (80 and 443 respectively).\n * Examples: `http://example.com`, `https://api.example.com:9876`\n *\n *
\n * It is not possible to whitelist specific URLs/paths. The `path`, `query` and `fragment` parts\n * of a URL will be ignored. For example, `https://foo.com/path/bar?query=baz#fragment` will be\n * treated as `https://foo.com`, meaning that **all** requests to URLs starting with\n * `https://foo.com/` will include the XSRF token.\n *
\n *\n * @example\n *\n * ```js\n * // App served from `https://example.com/`.\n * angular.\n * module('xsrfWhitelistedOriginsExample', []).\n * config(['$httpProvider', function($httpProvider) {\n * $httpProvider.xsrfWhitelistedOrigins.push('https://api.example.com');\n * }]).\n * run(['$http', function($http) {\n * // The XSRF token will be sent.\n * $http.get('https://api.example.com/preferences').then(...);\n *\n * // The XSRF token will NOT be sent.\n * $http.get('https://stats.example.com/activity').then(...);\n * }]);\n * ```\n */\n var xsrfWhitelistedOrigins = this.xsrfWhitelistedOrigins = [];\n\n this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce',\n function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) {\n\n var defaultCache = $cacheFactory('$http');\n\n /**\n * Make sure that default param serializer is exposed as a function\n */\n defaults.paramSerializer = isString(defaults.paramSerializer) ?\n $injector.get(defaults.paramSerializer) : defaults.paramSerializer;\n\n /**\n * Interceptors stored in reverse order. Inner interceptors before outer interceptors.\n * The reversal is needed so that we can build up the interception chain around the\n * server request.\n */\n var reversedInterceptors = [];\n\n forEach(interceptorFactories, function(interceptorFactory) {\n reversedInterceptors.unshift(isString(interceptorFactory)\n ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));\n });\n\n /**\n * A function to check request URLs against a list of allowed origins.\n */\n var urlIsAllowedOrigin = urlIsAllowedOriginFactory(xsrfWhitelistedOrigins);\n\n /**\n * @ngdoc service\n * @kind function\n * @name $http\n * @requires ng.$httpBackend\n * @requires $cacheFactory\n * @requires $rootScope\n * @requires $q\n * @requires $injector\n *\n * @description\n * The `$http` service is a core AngularJS service that facilitates communication with the remote\n * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)\n * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).\n *\n * For unit testing applications that use `$http` service, see\n * {@link ngMock.$httpBackend $httpBackend mock}.\n *\n * For a higher level of abstraction, please check out the {@link ngResource.$resource\n * $resource} service.\n *\n * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by\n * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage\n * it is important to familiarize yourself with these APIs and the guarantees they provide.\n *\n *\n * ## General usage\n * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —\n * that is used to generate an HTTP request and returns a {@link ng.$q promise} that is\n * resolved (request success) or rejected (request failure) with a\n * {@link ng.$http#$http-returns response} object.\n *\n * ```js\n * // Simple GET request example:\n * $http({\n * method: 'GET',\n * url: '/someUrl'\n * }).then(function successCallback(response) {\n * // this callback will be called asynchronously\n * // when the response is available\n * }, function errorCallback(response) {\n * // called asynchronously if an error occurs\n * // or server returns response with an error status.\n * });\n * ```\n *\n *\n * ## Shortcut methods\n *\n * Shortcut methods are also available. All shortcut methods require passing in the URL, and\n * request data must be passed in for POST/PUT requests. An optional config can be passed as the\n * last argument.\n *\n * ```js\n * $http.get('/someUrl', config).then(successCallback, errorCallback);\n * $http.post('/someUrl', data, config).then(successCallback, errorCallback);\n * ```\n *\n * Complete list of shortcut methods:\n *\n * - {@link ng.$http#get $http.get}\n * - {@link ng.$http#head $http.head}\n * - {@link ng.$http#post $http.post}\n * - {@link ng.$http#put $http.put}\n * - {@link ng.$http#delete $http.delete}\n * - {@link ng.$http#jsonp $http.jsonp}\n * - {@link ng.$http#patch $http.patch}\n *\n *\n * ## Writing Unit Tests that use $http\n * When unit testing (using {@link ngMock ngMock}), it is necessary to call\n * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending\n * request using trained responses.\n *\n * ```\n * $httpBackend.expectGET(...);\n * $http.get(...);\n * $httpBackend.flush();\n * ```\n *\n * ## Setting HTTP Headers\n *\n * The $http service will automatically add certain HTTP headers to all requests. These defaults\n * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration\n * object, which currently contains this default configuration:\n *\n * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):\n * - Accept: application/json, text/plain, \\*/\\*\n * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)\n * - `Content-Type: application/json`\n * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)\n * - `Content-Type: application/json`\n *\n * To add or overwrite these defaults, simply add or remove a property from these configuration\n * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object\n * with the lowercased HTTP method name as the key, e.g.\n * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.\n *\n * The defaults can also be set at runtime via the `$http.defaults` object in the same\n * fashion. For example:\n *\n * ```\n * module.run(function($http) {\n * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';\n * });\n * ```\n *\n * In addition, you can supply a `headers` property in the config object passed when\n * calling `$http(config)`, which overrides the defaults without changing them globally.\n *\n * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,\n * Use the `headers` property, setting the desired header to `undefined`. For example:\n *\n * ```js\n * var req = {\n * method: 'POST',\n * url: 'http://example.com',\n * headers: {\n * 'Content-Type': undefined\n * },\n * data: { test: 'test' }\n * }\n *\n * $http(req).then(function(){...}, function(){...});\n * ```\n *\n * ## Transforming Requests and Responses\n *\n * Both requests and responses can be transformed using transformation functions: `transformRequest`\n * and `transformResponse`. These properties can be a single function that returns\n * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,\n * which allows you to `push` or `unshift` a new transformation function into the transformation chain.\n *\n *
\n * **Note:** AngularJS does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.\n * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).\n * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest\n * function will be reflected on the scope and in any templates where the object is data-bound.\n * To prevent this, transform functions should have no side-effects.\n * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.\n *
\n *\n * ### Default Transformations\n *\n * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and\n * `defaults.transformResponse` properties. If a request does not provide its own transformations\n * then these will be applied.\n *\n * You can augment or replace the default transformations by modifying these properties by adding to or\n * replacing the array.\n *\n * AngularJS provides the following default transformations:\n *\n * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`) is\n * an array with one function that does the following:\n *\n * - If the `data` property of the request configuration object contains an object, serialize it\n * into JSON format.\n *\n * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`) is\n * an array with one function that does the following:\n *\n * - If XSRF prefix is detected, strip it (see Security Considerations section below).\n * - If the `Content-Type` is `application/json` or the response looks like JSON,\n * deserialize it using a JSON parser.\n *\n *\n * ### Overriding the Default Transformations Per Request\n *\n * If you wish to override the request/response transformations only for a single request then provide\n * `transformRequest` and/or `transformResponse` properties on the configuration object passed\n * into `$http`.\n *\n * Note that if you provide these properties on the config object the default transformations will be\n * overwritten. If you wish to augment the default transformations then you must include them in your\n * local transformation array.\n *\n * The following code demonstrates adding a new response transformation to be run after the default response\n * transformations have been run.\n *\n * ```js\n * function appendTransform(defaults, transform) {\n *\n * // We can't guarantee that the default transformation is an array\n * defaults = angular.isArray(defaults) ? defaults : [defaults];\n *\n * // Append the new transformation to the defaults\n * return defaults.concat(transform);\n * }\n *\n * $http({\n * url: '...',\n * method: 'GET',\n * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {\n * return doTransform(value);\n * })\n * });\n * ```\n *\n *\n * ## Caching\n *\n * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must\n * set the config.cache value or the default cache value to TRUE or to a cache object (created\n * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes\n * precedence over the default cache value.\n *\n * In order to:\n * * cache all responses - set the default cache value to TRUE or to a cache object\n * * cache a specific response - set config.cache value to TRUE or to a cache object\n *\n * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,\n * then the default `$cacheFactory(\"$http\")` object is used.\n *\n * The default cache value can be set by updating the\n * {@link ng.$http#defaults `$http.defaults.cache`} property or the\n * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.\n *\n * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using\n * the relevant cache object. The next time the same request is made, the response is returned\n * from the cache without sending a request to the server.\n *\n * Take note that:\n *\n * * Only GET and JSONP requests are cached.\n * * The cache key is the request URL including search parameters; headers are not considered.\n * * Cached responses are returned asynchronously, in the same way as responses from the server.\n * * If multiple identical requests are made using the same cache, which is not yet populated,\n * one request will be made to the server and remaining requests will return the same response.\n * * A cache-control header on the response does not affect if or how responses are cached.\n *\n *\n * ## Interceptors\n *\n * Before you start creating interceptors, be sure to understand the\n * {@link ng.$q $q and deferred/promise APIs}.\n *\n * For purposes of global error handling, authentication, or any kind of synchronous or\n * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be\n * able to intercept requests before they are handed to the server and\n * responses before they are handed over to the application code that\n * initiated these requests. The interceptors leverage the {@link ng.$q\n * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.\n *\n * The interceptors are service factories that are registered with the `$httpProvider` by\n * adding them to the `$httpProvider.interceptors` array. The factory is called and\n * injected with dependencies (if specified) and returns the interceptor.\n *\n * There are two kinds of interceptors (and two kinds of rejection interceptors):\n *\n * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to\n * modify the `config` object or create a new one. The function needs to return the `config`\n * object directly, or a promise containing the `config` or a new `config` object.\n * * `requestError`: interceptor gets called when a previous interceptor threw an error or\n * resolved with a rejection.\n * * `response`: interceptors get called with http `response` object. The function is free to\n * modify the `response` object or create a new one. The function needs to return the `response`\n * object directly, or as a promise containing the `response` or a new `response` object.\n * * `responseError`: interceptor gets called when a previous interceptor threw an error or\n * resolved with a rejection.\n *\n *\n * ```js\n * // register the interceptor as a service\n * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {\n * return {\n * // optional method\n * 'request': function(config) {\n * // do something on success\n * return config;\n * },\n *\n * // optional method\n * 'requestError': function(rejection) {\n * // do something on error\n * if (canRecover(rejection)) {\n * return responseOrNewPromise\n * }\n * return $q.reject(rejection);\n * },\n *\n *\n *\n * // optional method\n * 'response': function(response) {\n * // do something on success\n * return response;\n * },\n *\n * // optional method\n * 'responseError': function(rejection) {\n * // do something on error\n * if (canRecover(rejection)) {\n * return responseOrNewPromise\n * }\n * return $q.reject(rejection);\n * }\n * };\n * });\n *\n * $httpProvider.interceptors.push('myHttpInterceptor');\n *\n *\n * // alternatively, register the interceptor via an anonymous factory\n * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {\n * return {\n * 'request': function(config) {\n * // same as above\n * },\n *\n * 'response': function(response) {\n * // same as above\n * }\n * };\n * });\n * ```\n *\n * ## Security Considerations\n *\n * When designing web applications, consider security threats from:\n *\n * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)\n * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)\n *\n * Both server and the client must cooperate in order to eliminate these threats. AngularJS comes\n * pre-configured with strategies that address these issues, but for this to work backend server\n * cooperation is required.\n *\n * ### JSON Vulnerability Protection\n *\n * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)\n * allows third party website to turn your JSON resource URL into\n * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To\n * counter this your server can prefix all JSON requests with following string `\")]}',\\n\"`.\n * AngularJS will automatically strip the prefix before processing it as JSON.\n *\n * For example if your server needs to return:\n * ```js\n * ['one','two']\n * ```\n *\n * which is vulnerable to attack, your server can return:\n * ```js\n * )]}',\n * ['one','two']\n * ```\n *\n * AngularJS will strip the prefix, before processing the JSON.\n *\n *\n * ### Cross Site Request Forgery (XSRF) Protection\n *\n * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by\n * which the attacker can trick an authenticated user into unknowingly executing actions on your\n * website. AngularJS provides a mechanism to counter XSRF. When performing XHR requests, the\n * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP\n * header (by default `X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read\n * the cookie, your server can be assured that the XHR came from JavaScript running on your\n * domain.\n *\n * To take advantage of this, your server needs to set a token in a JavaScript readable session\n * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the\n * server can verify that the cookie matches the `X-XSRF-TOKEN` HTTP header, and therefore be\n * sure that only JavaScript running on your domain could have sent the request. The token must\n * be unique for each user and must be verifiable by the server (to prevent the JavaScript from\n * making up its own tokens). We recommend that the token is a digest of your site's\n * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))\n * for added security.\n *\n * The header will — by default — **not** be set for cross-domain requests. This\n * prevents unauthorized servers (e.g. malicious or compromised 3rd-party APIs) from gaining\n * access to your users' XSRF tokens and exposing them to Cross Site Request Forgery. If you\n * want to, you can whitelist additional origins to also receive the XSRF token, by adding them\n * to {@link ng.$httpProvider#xsrfWhitelistedOrigins xsrfWhitelistedOrigins}. This might be\n * useful, for example, if your application, served from `example.com`, needs to access your API\n * at `api.example.com`.\n * See {@link ng.$httpProvider#xsrfWhitelistedOrigins $httpProvider.xsrfWhitelistedOrigins} for\n * more details.\n *\n *
\n * **Warning**
\n * Only whitelist origins that you have control over and make sure you understand the\n * implications of doing so.\n *
\n *\n * The name of the cookie and the header can be specified using the `xsrfCookieName` and\n * `xsrfHeaderName` properties of either `$httpProvider.defaults` at config-time,\n * `$http.defaults` at run-time, or the per-request config object.\n *\n * In order to prevent collisions in environments where multiple AngularJS apps share the\n * same domain or subdomain, we recommend that each application uses a unique cookie name.\n *\n *\n * @param {object} config Object describing the request to be made and how it should be\n * processed. The object has following properties:\n *\n * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)\n * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested;\n * or an object created by a call to `$sce.trustAsResourceUrl(url)`.\n * - **params** – `{Object.}` – Map of strings or objects which will be serialized\n * with the `paramSerializer` and appended as GET parameters.\n * - **data** – `{string|Object}` – Data to be sent as the request message data.\n * - **headers** – `{Object}` – Map of strings or functions which return strings representing\n * HTTP headers to send to the server. If the return value of a function is null, the\n * header will not be sent. Functions accept a config object as an argument.\n * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.\n * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.\n * The handler will be called in the context of a `$apply` block.\n * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload\n * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.\n * The handler will be called in the context of a `$apply` block.\n * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.\n * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.\n * - **transformRequest** –\n * `{function(data, headersGetter)|Array.}` –\n * transform function or an array of such functions. The transform function takes the http\n * request body and headers and returns its transformed (typically serialized) version.\n * See {@link ng.$http#overriding-the-default-transformations-per-request\n * Overriding the Default Transformations}\n * - **transformResponse** –\n * `{function(data, headersGetter, status)|Array.}` –\n * transform function or an array of such functions. The transform function takes the http\n * response body, headers and status and returns its transformed (typically deserialized) version.\n * See {@link ng.$http#overriding-the-default-transformations-per-request\n * Overriding the Default Transformations}\n * - **paramSerializer** - `{string|function(Object):string}` - A function used to\n * prepare the string representation of request parameters (specified as an object).\n * If specified as string, it is interpreted as function registered with the\n * {@link $injector $injector}, which means you can create your own serializer\n * by registering it as a {@link auto.$provide#service service}.\n * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};\n * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}\n * - **cache** – `{boolean|Object}` – A boolean value or object created with\n * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.\n * See {@link $http#caching $http Caching} for more information.\n * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}\n * that should abort the request when resolved.\n *\n * A numerical timeout or a promise returned from {@link ng.$timeout $timeout}, will set\n * the `xhrStatus` in the {@link $http#$http-returns response} to \"timeout\", and any other\n * resolved promise will set it to \"abort\", following standard XMLHttpRequest behavior.\n *\n * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the\n * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)\n * for more information.\n * - **responseType** - `{string}` - see\n * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).\n *\n * @returns {HttpPromise} A {@link ng.$q `Promise}` that will be resolved (request success)\n * or rejected (request failure) with a response object.\n *\n * The response object has these properties:\n *\n * - **data** – `{string|Object}` – The response body transformed with\n * the transform functions.\n * - **status** – `{number}` – HTTP status code of the response.\n * - **headers** – `{function([headerName])}` – Header getter function.\n * - **config** – `{Object}` – The configuration object that was used\n * to generate the request.\n * - **statusText** – `{string}` – HTTP status text of the response.\n * - **xhrStatus** – `{string}` – Status of the XMLHttpRequest\n * (`complete`, `error`, `timeout` or `abort`).\n *\n *\n * A response status code between 200 and 299 is considered a success status\n * and will result in the success callback being called. Any response status\n * code outside of that range is considered an error status and will result\n * in the error callback being called.\n * Also, status codes less than -1 are normalized to zero. -1 usually means\n * the request was aborted, e.g. using a `config.timeout`. More information\n * about the status might be available in the `xhrStatus` property.\n *\n * Note that if the response is a redirect, XMLHttpRequest will transparently\n * follow it, meaning that the outcome (success or error) will be determined\n * by the final response status code.\n *\n *\n * @property {Array.} pendingRequests Array of config objects for currently pending\n * requests. This is primarily meant to be used for debugging purposes.\n *\n *\n * @example\n\n\n
\n \n \n
\n \n \n \n
http status code: {{status}}
\n
http response data: {{data}}
\n
\n
\n\n angular.module('httpExample', [])\n .config(['$sceDelegateProvider', function($sceDelegateProvider) {\n // We must whitelist the JSONP endpoint that we are using to show that we trust it\n $sceDelegateProvider.resourceUrlWhitelist([\n 'self',\n 'https://angularjs.org/**'\n ]);\n }])\n .controller('FetchController', ['$scope', '$http', '$templateCache',\n function($scope, $http, $templateCache) {\n $scope.method = 'GET';\n $scope.url = 'http-hello.html';\n\n $scope.fetch = function() {\n $scope.code = null;\n $scope.response = null;\n\n $http({method: $scope.method, url: $scope.url, cache: $templateCache}).\n then(function(response) {\n $scope.status = response.status;\n $scope.data = response.data;\n }, function(response) {\n $scope.data = response.data || 'Request failed';\n $scope.status = response.status;\n });\n };\n\n $scope.updateModel = function(method, url) {\n $scope.method = method;\n $scope.url = url;\n };\n }]);\n\n\n Hello, $http!\n\n\n var status = element(by.binding('status'));\n var data = element(by.binding('data'));\n var fetchBtn = element(by.id('fetchbtn'));\n var sampleGetBtn = element(by.id('samplegetbtn'));\n var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));\n\n it('should make an xhr GET request', function() {\n sampleGetBtn.click();\n fetchBtn.click();\n expect(status.getText()).toMatch('200');\n expect(data.getText()).toMatch(/Hello, \\$http!/);\n });\n\n// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185\n// it('should make a JSONP request to angularjs.org', function() {\n// var sampleJsonpBtn = element(by.id('samplejsonpbtn'));\n// sampleJsonpBtn.click();\n// fetchBtn.click();\n// expect(status.getText()).toMatch('200');\n// expect(data.getText()).toMatch(/Super Hero!/);\n// });\n\n it('should make JSONP request to invalid URL and invoke the error handler',\n function() {\n invalidJsonpBtn.click();\n fetchBtn.click();\n expect(status.getText()).toMatch('0');\n expect(data.getText()).toMatch('Request failed');\n });\n\n
\n */\n function $http(requestConfig) {\n\n if (!isObject(requestConfig)) {\n throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);\n }\n\n if (!isString($sce.valueOf(requestConfig.url))) {\n throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url);\n }\n\n var config = extend({\n method: 'get',\n transformRequest: defaults.transformRequest,\n transformResponse: defaults.transformResponse,\n paramSerializer: defaults.paramSerializer,\n jsonpCallbackParam: defaults.jsonpCallbackParam\n }, requestConfig);\n\n config.headers = mergeHeaders(requestConfig);\n config.method = uppercase(config.method);\n config.paramSerializer = isString(config.paramSerializer) ?\n $injector.get(config.paramSerializer) : config.paramSerializer;\n\n $browser.$$incOutstandingRequestCount('$http');\n\n var requestInterceptors = [];\n var responseInterceptors = [];\n var promise = $q.resolve(config);\n\n // apply interceptors\n forEach(reversedInterceptors, function(interceptor) {\n if (interceptor.request || interceptor.requestError) {\n requestInterceptors.unshift(interceptor.request, interceptor.requestError);\n }\n if (interceptor.response || interceptor.responseError) {\n responseInterceptors.push(interceptor.response, interceptor.responseError);\n }\n });\n\n promise = chainInterceptors(promise, requestInterceptors);\n promise = promise.then(serverRequest);\n promise = chainInterceptors(promise, responseInterceptors);\n promise = promise.finally(completeOutstandingRequest);\n\n return promise;\n\n\n function chainInterceptors(promise, interceptors) {\n for (var i = 0, ii = interceptors.length; i < ii;) {\n var thenFn = interceptors[i++];\n var rejectFn = interceptors[i++];\n\n promise = promise.then(thenFn, rejectFn);\n }\n\n interceptors.length = 0;\n\n return promise;\n }\n\n function completeOutstandingRequest() {\n $browser.$$completeOutstandingRequest(noop, '$http');\n }\n\n function executeHeaderFns(headers, config) {\n var headerContent, processedHeaders = {};\n\n forEach(headers, function(headerFn, header) {\n if (isFunction(headerFn)) {\n headerContent = headerFn(config);\n if (headerContent != null) {\n processedHeaders[header] = headerContent;\n }\n } else {\n processedHeaders[header] = headerFn;\n }\n });\n\n return processedHeaders;\n }\n\n function mergeHeaders(config) {\n var defHeaders = defaults.headers,\n reqHeaders = extend({}, config.headers),\n defHeaderName, lowercaseDefHeaderName, reqHeaderName;\n\n defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);\n\n // using for-in instead of forEach to avoid unnecessary iteration after header has been found\n defaultHeadersIteration:\n for (defHeaderName in defHeaders) {\n lowercaseDefHeaderName = lowercase(defHeaderName);\n\n for (reqHeaderName in reqHeaders) {\n if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {\n continue defaultHeadersIteration;\n }\n }\n\n reqHeaders[defHeaderName] = defHeaders[defHeaderName];\n }\n\n // execute if header value is a function for merged headers\n return executeHeaderFns(reqHeaders, shallowCopy(config));\n }\n\n function serverRequest(config) {\n var headers = config.headers;\n var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);\n\n // strip content-type if data is undefined\n if (isUndefined(reqData)) {\n forEach(headers, function(value, header) {\n if (lowercase(header) === 'content-type') {\n delete headers[header];\n }\n });\n }\n\n if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {\n config.withCredentials = defaults.withCredentials;\n }\n\n // send request\n return sendReq(config, reqData).then(transformResponse, transformResponse);\n }\n\n function transformResponse(response) {\n // make a copy since the response must be cacheable\n var resp = extend({}, response);\n resp.data = transformData(response.data, response.headers, response.status,\n config.transformResponse);\n return (isSuccess(response.status))\n ? resp\n : $q.reject(resp);\n }\n }\n\n $http.pendingRequests = [];\n\n /**\n * @ngdoc method\n * @name $http#get\n *\n * @description\n * Shortcut method to perform `GET` request.\n *\n * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;\n * or an object created by a call to `$sce.trustAsResourceUrl(url)`.\n * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.\n * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.\n * See {@link ng.$http#$http-returns `$http()` return value}.\n */\n\n /**\n * @ngdoc method\n * @name $http#delete\n *\n * @description\n * Shortcut method to perform `DELETE` request.\n *\n * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;\n * or an object created by a call to `$sce.trustAsResourceUrl(url)`.\n * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.\n * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.\n * See {@link ng.$http#$http-returns `$http()` return value}.\n */\n\n /**\n * @ngdoc method\n * @name $http#head\n *\n * @description\n * Shortcut method to perform `HEAD` request.\n *\n * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;\n * or an object created by a call to `$sce.trustAsResourceUrl(url)`.\n * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.\n * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.\n * See {@link ng.$http#$http-returns `$http()` return value}.\n */\n\n /**\n * @ngdoc method\n * @name $http#jsonp\n *\n * @description\n * Shortcut method to perform `JSONP` request.\n *\n * Note that, since JSONP requests are sensitive because the response is given full access to the browser,\n * the url must be declared, via {@link $sce} as a trusted resource URL.\n * You can trust a URL by adding it to the whitelist via\n * {@link $sceDelegateProvider#resourceUrlWhitelist `$sceDelegateProvider.resourceUrlWhitelist`} or\n * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}.\n *\n * You should avoid generating the URL for the JSONP request from user provided data.\n * Provide additional query parameters via `params` property of the `config` parameter, rather than\n * modifying the URL itself.\n *\n * JSONP requests must specify a callback to be used in the response from the server. This callback\n * is passed as a query parameter in the request. You must specify the name of this parameter by\n * setting the `jsonpCallbackParam` property on the request config object.\n *\n * ```\n * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})\n * ```\n *\n * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`.\n * Initially this is set to `'callback'`.\n *\n *
\n * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback\n * parameter value should go.\n *
\n *\n * If you would like to customise where and how the callbacks are stored then try overriding\n * or decorating the {@link $jsonpCallbacks} service.\n *\n * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;\n * or an object created by a call to `$sce.trustAsResourceUrl(url)`.\n * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.\n * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.\n * See {@link ng.$http#$http-returns `$http()` return value}.\n */\n createShortMethods('get', 'delete', 'head', 'jsonp');\n\n /**\n * @ngdoc method\n * @name $http#post\n *\n * @description\n * Shortcut method to perform `POST` request.\n *\n * @param {string} url Relative or absolute URL specifying the destination of the request\n * @param {*} data Request content\n * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.\n * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.\n * See {@link ng.$http#$http-returns `$http()` return value}.\n */\n\n /**\n * @ngdoc method\n * @name $http#put\n *\n * @description\n * Shortcut method to perform `PUT` request.\n *\n * @param {string} url Relative or absolute URL specifying the destination of the request\n * @param {*} data Request content\n * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.\n * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.\n * See {@link ng.$http#$http-returns `$http()` return value}.\n */\n\n /**\n * @ngdoc method\n * @name $http#patch\n *\n * @description\n * Shortcut method to perform `PATCH` request.\n *\n * @param {string} url Relative or absolute URL specifying the destination of the request\n * @param {*} data Request content\n * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.\n * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.\n * See {@link ng.$http#$http-returns `$http()` return value}.\n */\n createShortMethodsWithData('post', 'put', 'patch');\n\n /**\n * @ngdoc property\n * @name $http#defaults\n *\n * @description\n * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of\n * default headers, withCredentials as well as request and response transformations.\n *\n * See \"Setting HTTP Headers\" and \"Transforming Requests and Responses\" sections above.\n */\n $http.defaults = defaults;\n\n\n return $http;\n\n\n function createShortMethods(names) {\n forEach(arguments, function(name) {\n $http[name] = function(url, config) {\n return $http(extend({}, config || {}, {\n method: name,\n url: url\n }));\n };\n });\n }\n\n\n function createShortMethodsWithData(name) {\n forEach(arguments, function(name) {\n $http[name] = function(url, data, config) {\n return $http(extend({}, config || {}, {\n method: name,\n url: url,\n data: data\n }));\n };\n });\n }\n\n\n /**\n * Makes the request.\n *\n * !!! ACCESSES CLOSURE VARS:\n * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests\n */\n function sendReq(config, reqData) {\n var deferred = $q.defer(),\n promise = deferred.promise,\n cache,\n cachedResp,\n reqHeaders = config.headers,\n isJsonp = lowercase(config.method) === 'jsonp',\n url = config.url;\n\n if (isJsonp) {\n // JSONP is a pretty sensitive operation where we're allowing a script to have full access to\n // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL.\n url = $sce.getTrustedResourceUrl(url);\n } else if (!isString(url)) {\n // If it is not a string then the URL must be a $sce trusted object\n url = $sce.valueOf(url);\n }\n\n url = buildUrl(url, config.paramSerializer(config.params));\n\n if (isJsonp) {\n // Check the url and add the JSONP callback placeholder\n url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam);\n }\n\n $http.pendingRequests.push(config);\n promise.then(removePendingReq, removePendingReq);\n\n if ((config.cache || defaults.cache) && config.cache !== false &&\n (config.method === 'GET' || config.method === 'JSONP')) {\n cache = isObject(config.cache) ? config.cache\n : isObject(/** @type {?} */ (defaults).cache)\n ? /** @type {?} */ (defaults).cache\n : defaultCache;\n }\n\n if (cache) {\n cachedResp = cache.get(url);\n if (isDefined(cachedResp)) {\n if (isPromiseLike(cachedResp)) {\n // cached request has already been sent, but there is no response yet\n cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);\n } else {\n // serving from cache\n if (isArray(cachedResp)) {\n resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3], cachedResp[4]);\n } else {\n resolvePromise(cachedResp, 200, {}, 'OK', 'complete');\n }\n }\n } else {\n // put the promise for the non-transformed response into cache as a placeholder\n cache.put(url, promise);\n }\n }\n\n\n // if we won't have the response in cache, set the xsrf headers and\n // send the request to the backend\n if (isUndefined(cachedResp)) {\n var xsrfValue = urlIsAllowedOrigin(config.url)\n ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]\n : undefined;\n if (xsrfValue) {\n reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;\n }\n\n $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,\n config.withCredentials, config.responseType,\n createApplyHandlers(config.eventHandlers),\n createApplyHandlers(config.uploadEventHandlers));\n }\n\n return promise;\n\n function createApplyHandlers(eventHandlers) {\n if (eventHandlers) {\n var applyHandlers = {};\n forEach(eventHandlers, function(eventHandler, key) {\n applyHandlers[key] = function(event) {\n if (useApplyAsync) {\n $rootScope.$applyAsync(callEventHandler);\n } else if ($rootScope.$$phase) {\n callEventHandler();\n } else {\n $rootScope.$apply(callEventHandler);\n }\n\n function callEventHandler() {\n eventHandler(event);\n }\n };\n });\n return applyHandlers;\n }\n }\n\n\n /**\n * Callback registered to $httpBackend():\n * - caches the response if desired\n * - resolves the raw $http promise\n * - calls $apply\n */\n function done(status, response, headersString, statusText, xhrStatus) {\n if (cache) {\n if (isSuccess(status)) {\n cache.put(url, [status, response, parseHeaders(headersString), statusText, xhrStatus]);\n } else {\n // remove promise from the cache\n cache.remove(url);\n }\n }\n\n function resolveHttpPromise() {\n resolvePromise(response, status, headersString, statusText, xhrStatus);\n }\n\n if (useApplyAsync) {\n $rootScope.$applyAsync(resolveHttpPromise);\n } else {\n resolveHttpPromise();\n if (!$rootScope.$$phase) $rootScope.$apply();\n }\n }\n\n\n /**\n * Resolves the raw $http promise.\n */\n function resolvePromise(response, status, headers, statusText, xhrStatus) {\n //status: HTTP response status code, 0, -1 (aborted by timeout / promise)\n status = status >= -1 ? status : 0;\n\n (isSuccess(status) ? deferred.resolve : deferred.reject)({\n data: response,\n status: status,\n headers: headersGetter(headers),\n config: config,\n statusText: statusText,\n xhrStatus: xhrStatus\n });\n }\n\n function resolvePromiseWithResult(result) {\n resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText, result.xhrStatus);\n }\n\n function removePendingReq() {\n var idx = $http.pendingRequests.indexOf(config);\n if (idx !== -1) $http.pendingRequests.splice(idx, 1);\n }\n }\n\n\n function buildUrl(url, serializedParams) {\n if (serializedParams.length > 0) {\n url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;\n }\n return url;\n }\n\n function sanitizeJsonpCallbackParam(url, cbKey) {\n var parts = url.split('?');\n if (parts.length > 2) {\n // Throw if the url contains more than one `?` query indicator\n throw $httpMinErr('badjsonp', 'Illegal use more than one \"?\", in url, \"{1}\"', url);\n }\n var params = parseKeyValue(parts[1]);\n forEach(params, function(value, key) {\n if (value === 'JSON_CALLBACK') {\n // Throw if the url already contains a reference to JSON_CALLBACK\n throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, \"{0}\"', url);\n }\n if (key === cbKey) {\n // Throw if the callback param was already provided\n throw $httpMinErr('badjsonp', 'Illegal use of callback param, \"{0}\", in url, \"{1}\"', cbKey, url);\n }\n });\n\n // Add in the JSON_CALLBACK callback param value\n url += ((url.indexOf('?') === -1) ? '?' : '&') + cbKey + '=JSON_CALLBACK';\n\n return url;\n }\n }];\n}\n\n/**\n * @ngdoc service\n * @name $xhrFactory\n * @this\n *\n * @description\n * Factory function used to create XMLHttpRequest objects.\n *\n * Replace or decorate this service to create your own custom XMLHttpRequest objects.\n *\n * ```\n * angular.module('myApp', [])\n * .factory('$xhrFactory', function() {\n * return function createXhr(method, url) {\n * return new window.XMLHttpRequest({mozSystem: true});\n * };\n * });\n * ```\n *\n * @param {string} method HTTP method of the request (GET, POST, PUT, ..)\n * @param {string} url URL of the request.\n */\nfunction $xhrFactoryProvider() {\n this.$get = function() {\n return function createXhr() {\n return new window.XMLHttpRequest();\n };\n };\n}\n\n/**\n * @ngdoc service\n * @name $httpBackend\n * @requires $jsonpCallbacks\n * @requires $document\n * @requires $xhrFactory\n * @this\n *\n * @description\n * HTTP backend used by the {@link ng.$http service} that delegates to\n * XMLHttpRequest object or JSONP and deals with browser incompatibilities.\n *\n * You should never need to use this service directly, instead use the higher-level abstractions:\n * {@link ng.$http $http} or {@link ngResource.$resource $resource}.\n *\n * During testing this implementation is swapped with {@link ngMock.$httpBackend mock\n * $httpBackend} which can be trained with responses.\n */\nfunction $HttpBackendProvider() {\n this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {\n return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);\n }];\n}\n\nfunction createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {\n // TODO(vojta): fix the signature\n return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {\n url = url || $browser.url();\n\n if (lowercase(method) === 'jsonp') {\n var callbackPath = callbacks.createCallback(url);\n var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {\n // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)\n var response = (status === 200) && callbacks.getResponse(callbackPath);\n completeRequest(callback, status, response, '', text, 'complete');\n callbacks.removeCallback(callbackPath);\n });\n } else {\n\n var xhr = createXhr(method, url);\n var abortedByTimeout = false;\n\n xhr.open(method, url, true);\n forEach(headers, function(value, key) {\n if (isDefined(value)) {\n xhr.setRequestHeader(key, value);\n }\n });\n\n xhr.onload = function requestLoaded() {\n var statusText = xhr.statusText || '';\n\n // responseText is the old-school way of retrieving response (supported by IE9)\n // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)\n var response = ('response' in xhr) ? xhr.response : xhr.responseText;\n\n // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)\n var status = xhr.status === 1223 ? 204 : xhr.status;\n\n // fix status code when it is 0 (0 status is undocumented).\n // Occurs when accessing file resources or on Android 4.1 stock browser\n // while retrieving files from application cache.\n if (status === 0) {\n status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;\n }\n\n completeRequest(callback,\n status,\n response,\n xhr.getAllResponseHeaders(),\n statusText,\n 'complete');\n };\n\n var requestError = function() {\n // The response is always empty\n // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error\n completeRequest(callback, -1, null, null, '', 'error');\n };\n\n var requestAborted = function() {\n completeRequest(callback, -1, null, null, '', abortedByTimeout ? 'timeout' : 'abort');\n };\n\n var requestTimeout = function() {\n // The response is always empty\n // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error\n completeRequest(callback, -1, null, null, '', 'timeout');\n };\n\n xhr.onerror = requestError;\n xhr.ontimeout = requestTimeout;\n xhr.onabort = requestAborted;\n\n forEach(eventHandlers, function(value, key) {\n xhr.addEventListener(key, value);\n });\n\n forEach(uploadEventHandlers, function(value, key) {\n xhr.upload.addEventListener(key, value);\n });\n\n if (withCredentials) {\n xhr.withCredentials = true;\n }\n\n if (responseType) {\n try {\n xhr.responseType = responseType;\n } catch (e) {\n // WebKit added support for the json responseType value on 09/03/2013\n // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are\n // known to throw when setting the value \"json\" as the response type. Other older\n // browsers implementing the responseType\n //\n // The json response type can be ignored if not supported, because JSON payloads are\n // parsed on the client-side regardless.\n if (responseType !== 'json') {\n throw e;\n }\n }\n }\n\n xhr.send(isUndefined(post) ? null : post);\n }\n\n // Since we are using xhr.abort() when a request times out, we have to set a flag that\n // indicates to requestAborted if the request timed out or was aborted.\n //\n // http.timeout = numerical timeout timeout\n // http.timeout = $timeout timeout\n // http.timeout = promise abort\n // xhr.abort() abort (The xhr object is normally inaccessible, but\n // can be exposed with the xhrFactory)\n if (timeout > 0) {\n var timeoutId = $browserDefer(function() {\n timeoutRequest('timeout');\n }, timeout);\n } else if (isPromiseLike(timeout)) {\n timeout.then(function() {\n timeoutRequest(isDefined(timeout.$$timeoutId) ? 'timeout' : 'abort');\n });\n }\n\n function timeoutRequest(reason) {\n abortedByTimeout = reason === 'timeout';\n if (jsonpDone) {\n jsonpDone();\n }\n if (xhr) {\n xhr.abort();\n }\n }\n\n function completeRequest(callback, status, response, headersString, statusText, xhrStatus) {\n // cancel timeout and subsequent timeout promise resolution\n if (isDefined(timeoutId)) {\n $browserDefer.cancel(timeoutId);\n }\n jsonpDone = xhr = null;\n\n callback(status, response, headersString, statusText, xhrStatus);\n }\n };\n\n function jsonpReq(url, callbackPath, done) {\n url = url.replace('JSON_CALLBACK', callbackPath);\n // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:\n // - fetches local scripts via XHR and evals them\n // - adds and immediately removes script elements from the document\n var script = rawDocument.createElement('script'), callback = null;\n script.type = 'text/javascript';\n script.src = url;\n script.async = true;\n\n callback = function(event) {\n script.removeEventListener('load', callback);\n script.removeEventListener('error', callback);\n rawDocument.body.removeChild(script);\n script = null;\n var status = -1;\n var text = 'unknown';\n\n if (event) {\n if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) {\n event = { type: 'error' };\n }\n text = event.type;\n status = event.type === 'error' ? 404 : 200;\n }\n\n if (done) {\n done(status, text);\n }\n };\n\n script.addEventListener('load', callback);\n script.addEventListener('error', callback);\n rawDocument.body.appendChild(script);\n return callback;\n }\n}\n\nvar $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');\n$interpolateMinErr.throwNoconcat = function(text) {\n throw $interpolateMinErr('noconcat',\n 'Error while interpolating: {0}\\nStrict Contextual Escaping disallows ' +\n 'interpolations that concatenate multiple expressions when a trusted value is ' +\n 'required. See http://docs.angularjs.org/api/ng.$sce', text);\n};\n\n$interpolateMinErr.interr = function(text, err) {\n return $interpolateMinErr('interr', 'Can\\'t interpolate: {0}\\n{1}', text, err.toString());\n};\n\n/**\n * @ngdoc provider\n * @name $interpolateProvider\n * @this\n *\n * @description\n *\n * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.\n *\n *
\n * This feature is sometimes used to mix different markup languages, e.g. to wrap an AngularJS\n * template within a Python Jinja template (or any other template language). Mixing templating\n * languages is **very dangerous**. The embedding template language will not safely escape AngularJS\n * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)\n * security bugs!\n *
\n *\n * @example\n\n\n\n
\n //demo.label//\n
\n
\n\n it('should interpolate binding with custom symbols', function() {\n expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');\n });\n\n
\n */\nfunction $InterpolateProvider() {\n var startSymbol = '{{';\n var endSymbol = '}}';\n\n /**\n * @ngdoc method\n * @name $interpolateProvider#startSymbol\n * @description\n * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.\n *\n * @param {string=} value new value to set the starting symbol to.\n * @returns {string|self} Returns the symbol when used as getter and self if used as setter.\n */\n this.startSymbol = function(value) {\n if (value) {\n startSymbol = value;\n return this;\n }\n return startSymbol;\n };\n\n /**\n * @ngdoc method\n * @name $interpolateProvider#endSymbol\n * @description\n * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.\n *\n * @param {string=} value new value to set the ending symbol to.\n * @returns {string|self} Returns the symbol when used as getter and self if used as setter.\n */\n this.endSymbol = function(value) {\n if (value) {\n endSymbol = value;\n return this;\n }\n return endSymbol;\n };\n\n\n this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {\n var startSymbolLength = startSymbol.length,\n endSymbolLength = endSymbol.length,\n escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),\n escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');\n\n function escape(ch) {\n return '\\\\\\\\\\\\' + ch;\n }\n\n function unescapeText(text) {\n return text.replace(escapedStartRegexp, startSymbol).\n replace(escapedEndRegexp, endSymbol);\n }\n\n // TODO: this is the same as the constantWatchDelegate in parse.js\n function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {\n var unwatch = scope.$watch(function constantInterpolateWatch(scope) {\n unwatch();\n return constantInterp(scope);\n }, listener, objectEquality);\n return unwatch;\n }\n\n /**\n * @ngdoc service\n * @name $interpolate\n * @kind function\n *\n * @requires $parse\n * @requires $sce\n *\n * @description\n *\n * Compiles a string with markup into an interpolation function. This service is used by the\n * HTML {@link ng.$compile $compile} service for data binding. See\n * {@link ng.$interpolateProvider $interpolateProvider} for configuring the\n * interpolation markup.\n *\n *\n * ```js\n * var $interpolate = ...; // injected\n * var exp = $interpolate('Hello {{name | uppercase}}!');\n * expect(exp({name:'AngularJS'})).toEqual('Hello ANGULARJS!');\n * ```\n *\n * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is\n * `true`, the interpolation function will return `undefined` unless all embedded expressions\n * evaluate to a value other than `undefined`.\n *\n * ```js\n * var $interpolate = ...; // injected\n * var context = {greeting: 'Hello', name: undefined };\n *\n * // default \"forgiving\" mode\n * var exp = $interpolate('{{greeting}} {{name}}!');\n * expect(exp(context)).toEqual('Hello !');\n *\n * // \"allOrNothing\" mode\n * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);\n * expect(exp(context)).toBeUndefined();\n * context.name = 'AngularJS';\n * expect(exp(context)).toEqual('Hello AngularJS!');\n * ```\n *\n * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.\n *\n * #### Escaped Interpolation\n * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers\n * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).\n * It will be rendered as a regular start/end marker, and will not be interpreted as an expression\n * or binding.\n *\n * This enables web-servers to prevent script injection attacks and defacing attacks, to some\n * degree, while also enabling code examples to work without relying on the\n * {@link ng.directive:ngNonBindable ngNonBindable} directive.\n *\n * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,\n * replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all\n * interpolation start/end markers with their escaped counterparts.**\n *\n * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered\n * output when the $interpolate service processes the text. So, for HTML elements interpolated\n * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter\n * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,\n * this is typically useful only when user-data is used in rendering a template from the server, or\n * when otherwise untrusted data is used by a directive.\n *\n * \n * \n *
\n *

{{apptitle}}: \\{\\{ username = \"defaced value\"; \\}\\}\n *

\n *

{{username}} attempts to inject code which will deface the\n * application, but fails to accomplish their task, because the server has correctly\n * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)\n * characters.

\n *

Instead, the result of the attempted script injection is visible, and can be removed\n * from the database by an administrator.

\n *
\n *
\n *
\n *\n * @knownIssue\n * It is currently not possible for an interpolated expression to contain the interpolation end\n * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.\n * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.\n *\n * @knownIssue\n * All directives and components must use the standard `{{` `}}` interpolation symbols\n * in their templates. If you change the application interpolation symbols the {@link $compile}\n * service will attempt to denormalize the standard symbols to the custom symbols.\n * The denormalization process is not clever enough to know not to replace instances of the standard\n * symbols where they would not normally be treated as interpolation symbols. For example in the following\n * code snippet the closing braces of the literal object will get incorrectly denormalized:\n *\n * ```\n *
\n * ```\n *\n * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.\n *\n * @param {string} text The text with markup to interpolate.\n * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have\n * embedded expression in order to return an interpolation function. Strings with no\n * embedded expression will return null for the interpolation function.\n * @param {string=} trustedContext when provided, the returned function passes the interpolated\n * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,\n * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that\n * provides Strict Contextual Escaping for details.\n * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined\n * unless all embedded expressions evaluate to a value other than `undefined`.\n * @returns {function(context)} an interpolation function which is used to compute the\n * interpolated string. The function has these parameters:\n *\n * - `context`: evaluation context for all expressions embedded in the interpolated text\n */\n function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {\n var contextAllowsConcatenation = trustedContext === $sce.URL || trustedContext === $sce.MEDIA_URL;\n\n // Provide a quick exit and simplified result function for text with no interpolation\n if (!text.length || text.indexOf(startSymbol) === -1) {\n if (mustHaveExpression) return;\n\n var unescapedText = unescapeText(text);\n if (contextAllowsConcatenation) {\n unescapedText = $sce.getTrusted(trustedContext, unescapedText);\n }\n var constantInterp = valueFn(unescapedText);\n constantInterp.exp = text;\n constantInterp.expressions = [];\n constantInterp.$$watchDelegate = constantWatchDelegate;\n\n return constantInterp;\n }\n\n allOrNothing = !!allOrNothing;\n var startIndex,\n endIndex,\n index = 0,\n expressions = [],\n parseFns,\n textLength = text.length,\n exp,\n concat = [],\n expressionPositions = [],\n singleExpression;\n\n\n while (index < textLength) {\n if (((startIndex = text.indexOf(startSymbol, index)) !== -1) &&\n ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) {\n if (index !== startIndex) {\n concat.push(unescapeText(text.substring(index, startIndex)));\n }\n exp = text.substring(startIndex + startSymbolLength, endIndex);\n expressions.push(exp);\n index = endIndex + endSymbolLength;\n expressionPositions.push(concat.length);\n concat.push(''); // Placeholder that will get replaced with the evaluated expression.\n } else {\n // we did not find an interpolation, so we have to add the remainder to the separators array\n if (index !== textLength) {\n concat.push(unescapeText(text.substring(index)));\n }\n break;\n }\n }\n\n singleExpression = concat.length === 1 && expressionPositions.length === 1;\n // Intercept expression if we need to stringify concatenated inputs, which may be SCE trusted\n // objects rather than simple strings\n // (we don't modify the expression if the input consists of only a single trusted input)\n var interceptor = contextAllowsConcatenation && singleExpression ? undefined : parseStringifyInterceptor;\n parseFns = expressions.map(function(exp) { return $parse(exp, interceptor); });\n\n // Concatenating expressions makes it hard to reason about whether some combination of\n // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a\n // single expression be used for some $sce-managed secure contexts (RESOURCE_URLs mostly),\n // we ensure that the value that's used is assigned or constructed by some JS code somewhere\n // that is more testable or make it obvious that you bound the value to some user controlled\n // value. This helps reduce the load when auditing for XSS issues.\n\n // Note that URL and MEDIA_URL $sce contexts do not need this, since `$sce` can sanitize the values\n // passed to it. In that case, `$sce.getTrusted` will be called on either the single expression\n // or on the overall concatenated string (losing trusted types used in the mix, by design).\n // Both these methods will sanitize plain strings. Also, HTML could be included, but since it's\n // only used in srcdoc attributes, this would not be very useful.\n\n if (!mustHaveExpression || expressions.length) {\n var compute = function(values) {\n for (var i = 0, ii = expressions.length; i < ii; i++) {\n if (allOrNothing && isUndefined(values[i])) return;\n concat[expressionPositions[i]] = values[i];\n }\n\n if (contextAllowsConcatenation) {\n // If `singleExpression` then `concat[0]` might be a \"trusted\" value or `null`, rather than a string\n return $sce.getTrusted(trustedContext, singleExpression ? concat[0] : concat.join(''));\n } else if (trustedContext && concat.length > 1) {\n // This context does not allow more than one part, e.g. expr + string or exp + exp.\n $interpolateMinErr.throwNoconcat(text);\n }\n // In an unprivileged context or only one part: just concatenate and return.\n return concat.join('');\n };\n\n return extend(function interpolationFn(context) {\n var i = 0;\n var ii = expressions.length;\n var values = new Array(ii);\n\n try {\n for (; i < ii; i++) {\n values[i] = parseFns[i](context);\n }\n\n return compute(values);\n } catch (err) {\n $exceptionHandler($interpolateMinErr.interr(text, err));\n }\n\n }, {\n // all of these properties are undocumented for now\n exp: text, //just for compatibility with regular watchers created via $watch\n expressions: expressions,\n $$watchDelegate: function(scope, listener) {\n var lastValue;\n return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) {\n var currValue = compute(values);\n listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);\n lastValue = currValue;\n });\n }\n });\n }\n\n function parseStringifyInterceptor(value) {\n try {\n // In concatenable contexts, getTrusted comes at the end, to avoid sanitizing individual\n // parts of a full URL. We don't care about losing the trustedness here.\n // In non-concatenable contexts, where there is only one expression, this interceptor is\n // not applied to the expression.\n value = (trustedContext && !contextAllowsConcatenation) ?\n $sce.getTrusted(trustedContext, value) :\n $sce.valueOf(value);\n return allOrNothing && !isDefined(value) ? value : stringify(value);\n } catch (err) {\n $exceptionHandler($interpolateMinErr.interr(text, err));\n }\n }\n }\n\n\n /**\n * @ngdoc method\n * @name $interpolate#startSymbol\n * @description\n * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.\n *\n * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change\n * the symbol.\n *\n * @returns {string} start symbol.\n */\n $interpolate.startSymbol = function() {\n return startSymbol;\n };\n\n\n /**\n * @ngdoc method\n * @name $interpolate#endSymbol\n * @description\n * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.\n *\n * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change\n * the symbol.\n *\n * @returns {string} end symbol.\n */\n $interpolate.endSymbol = function() {\n return endSymbol;\n };\n\n return $interpolate;\n }];\n}\n\nvar $intervalMinErr = minErr('$interval');\n\n/** @this */\nfunction $IntervalProvider() {\n this.$get = ['$$intervalFactory', '$window',\n function($$intervalFactory, $window) {\n var intervals = {};\n var setIntervalFn = function(tick, delay, deferred) {\n var id = $window.setInterval(tick, delay);\n intervals[id] = deferred;\n return id;\n };\n var clearIntervalFn = function(id) {\n $window.clearInterval(id);\n delete intervals[id];\n };\n\n /**\n * @ngdoc service\n * @name $interval\n *\n * @description\n * AngularJS's wrapper for `window.setInterval`. The `fn` function is executed every `delay`\n * milliseconds.\n *\n * The return value of registering an interval function is a promise. This promise will be\n * notified upon each tick of the interval, and will be resolved after `count` iterations, or\n * run indefinitely if `count` is not defined. The value of the notification will be the\n * number of iterations that have run.\n * To cancel an interval, call `$interval.cancel(promise)`.\n *\n * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to\n * move forward by `millis` milliseconds and trigger any functions scheduled to run in that\n * time.\n *\n *
\n * **Note**: Intervals created by this service must be explicitly destroyed when you are finished\n * with them. In particular they are not automatically destroyed when a controller's scope or a\n * directive's element are destroyed.\n * You should take this into consideration and make sure to always cancel the interval at the\n * appropriate moment. See the example below for more details on how and when to do this.\n *
\n *\n * @param {function()} fn A function that should be called repeatedly. If no additional arguments\n * are passed (see below), the function is called with the current iteration count.\n * @param {number} delay Number of milliseconds between each function call.\n * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat\n * indefinitely.\n * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\n * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\n * @param {...*=} Pass additional parameters to the executed function.\n * @returns {promise} A promise which will be notified on each iteration. It will resolve once all iterations of the interval complete.\n *\n * @example\n * \n * \n * \n *\n *
\n *
\n *
\n * Current time is: \n *
\n * Blood 1 : {{blood_1}}\n * Blood 2 : {{blood_2}}\n * \n * \n * \n *
\n *
\n *\n *
\n *
\n */\n var interval = $$intervalFactory(setIntervalFn, clearIntervalFn);\n\n /**\n * @ngdoc method\n * @name $interval#cancel\n *\n * @description\n * Cancels a task associated with the `promise`.\n *\n * @param {Promise=} promise returned by the `$interval` function.\n * @returns {boolean} Returns `true` if the task was successfully canceled.\n */\n interval.cancel = function(promise) {\n if (!promise) return false;\n\n if (!promise.hasOwnProperty('$$intervalId')) {\n throw $intervalMinErr('badprom',\n '`$interval.cancel()` called with a promise that was not generated by `$interval()`.');\n }\n\n if (!intervals.hasOwnProperty(promise.$$intervalId)) return false;\n\n var id = promise.$$intervalId;\n var deferred = intervals[id];\n\n // Interval cancels should not report an unhandled promise.\n markQExceptionHandled(deferred.promise);\n deferred.reject('canceled');\n clearIntervalFn(id);\n\n return true;\n };\n\n return interval;\n }];\n}\n\n/** @this */\nfunction $$IntervalFactoryProvider() {\n this.$get = ['$browser', '$q', '$$q', '$rootScope',\n function($browser, $q, $$q, $rootScope) {\n return function intervalFactory(setIntervalFn, clearIntervalFn) {\n return function intervalFn(fn, delay, count, invokeApply) {\n var hasParams = arguments.length > 4,\n args = hasParams ? sliceArgs(arguments, 4) : [],\n iteration = 0,\n skipApply = isDefined(invokeApply) && !invokeApply,\n deferred = (skipApply ? $$q : $q).defer(),\n promise = deferred.promise;\n\n count = isDefined(count) ? count : 0;\n\n function callback() {\n if (!hasParams) {\n fn(iteration);\n } else {\n fn.apply(null, args);\n }\n }\n\n function tick() {\n if (skipApply) {\n $browser.defer(callback);\n } else {\n $rootScope.$evalAsync(callback);\n }\n deferred.notify(iteration++);\n\n if (count > 0 && iteration >= count) {\n deferred.resolve(iteration);\n clearIntervalFn(promise.$$intervalId);\n }\n\n if (!skipApply) $rootScope.$apply();\n }\n\n promise.$$intervalId = setIntervalFn(tick, delay, deferred, skipApply);\n\n return promise;\n };\n };\n }];\n}\n\n/**\n * @ngdoc service\n * @name $jsonpCallbacks\n * @requires $window\n * @description\n * This service handles the lifecycle of callbacks to handle JSONP requests.\n * Override this service if you wish to customise where the callbacks are stored and\n * how they vary compared to the requested url.\n */\nvar $jsonpCallbacksProvider = /** @this */ function() {\n this.$get = function() {\n var callbacks = angular.callbacks;\n var callbackMap = {};\n\n function createCallback(callbackId) {\n var callback = function(data) {\n callback.data = data;\n callback.called = true;\n };\n callback.id = callbackId;\n return callback;\n }\n\n return {\n /**\n * @ngdoc method\n * @name $jsonpCallbacks#createCallback\n * @param {string} url the url of the JSONP request\n * @returns {string} the callback path to send to the server as part of the JSONP request\n * @description\n * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback\n * to pass to the server, which will be used to call the callback with its payload in the JSONP response.\n */\n createCallback: function(url) {\n var callbackId = '_' + (callbacks.$$counter++).toString(36);\n var callbackPath = 'angular.callbacks.' + callbackId;\n var callback = createCallback(callbackId);\n callbackMap[callbackPath] = callbacks[callbackId] = callback;\n return callbackPath;\n },\n /**\n * @ngdoc method\n * @name $jsonpCallbacks#wasCalled\n * @param {string} callbackPath the path to the callback that was sent in the JSONP request\n * @returns {boolean} whether the callback has been called, as a result of the JSONP response\n * @description\n * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the\n * callback that was passed in the request.\n */\n wasCalled: function(callbackPath) {\n return callbackMap[callbackPath].called;\n },\n /**\n * @ngdoc method\n * @name $jsonpCallbacks#getResponse\n * @param {string} callbackPath the path to the callback that was sent in the JSONP request\n * @returns {*} the data received from the response via the registered callback\n * @description\n * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback\n * in the JSONP response.\n */\n getResponse: function(callbackPath) {\n return callbackMap[callbackPath].data;\n },\n /**\n * @ngdoc method\n * @name $jsonpCallbacks#removeCallback\n * @param {string} callbackPath the path to the callback that was sent in the JSONP request\n * @description\n * {@link $httpBackend} calls this method to remove the callback after the JSONP request has\n * completed or timed-out.\n */\n removeCallback: function(callbackPath) {\n var callback = callbackMap[callbackPath];\n delete callbacks[callback.id];\n delete callbackMap[callbackPath];\n }\n };\n };\n};\n\n/**\n * @ngdoc service\n * @name $locale\n *\n * @description\n * $locale service provides localization rules for various AngularJS components. As of right now the\n * only public api is:\n *\n * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)\n */\n\n/* global stripHash: true */\n\nvar PATH_MATCH = /^([^?#]*)(\\?([^#]*))?(#(.*))?$/,\n DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};\nvar $locationMinErr = minErr('$location');\n\n\n/**\n * Encode path using encodeUriSegment, ignoring forward slashes\n *\n * @param {string} path Path to encode\n * @returns {string}\n */\nfunction encodePath(path) {\n var segments = path.split('/'),\n i = segments.length;\n\n while (i--) {\n // decode forward slashes to prevent them from being double encoded\n segments[i] = encodeUriSegment(segments[i].replace(/%2F/g, '/'));\n }\n\n return segments.join('/');\n}\n\nfunction decodePath(path, html5Mode) {\n var segments = path.split('/'),\n i = segments.length;\n\n while (i--) {\n segments[i] = decodeURIComponent(segments[i]);\n if (html5Mode) {\n // encode forward slashes to prevent them from being mistaken for path separators\n segments[i] = segments[i].replace(/\\//g, '%2F');\n }\n }\n\n return segments.join('/');\n}\n\nfunction normalizePath(pathValue, searchValue, hashValue) {\n var search = toKeyValue(searchValue),\n hash = hashValue ? '#' + encodeUriSegment(hashValue) : '',\n path = encodePath(pathValue);\n\n return path + (search ? '?' + search : '') + hash;\n}\n\nfunction parseAbsoluteUrl(absoluteUrl, locationObj) {\n var parsedUrl = urlResolve(absoluteUrl);\n\n locationObj.$$protocol = parsedUrl.protocol;\n locationObj.$$host = parsedUrl.hostname;\n locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;\n}\n\nvar DOUBLE_SLASH_REGEX = /^\\s*[\\\\/]{2,}/;\nfunction parseAppUrl(url, locationObj, html5Mode) {\n\n if (DOUBLE_SLASH_REGEX.test(url)) {\n throw $locationMinErr('badpath', 'Invalid url \"{0}\".', url);\n }\n\n var prefixed = (url.charAt(0) !== '/');\n if (prefixed) {\n url = '/' + url;\n }\n var match = urlResolve(url);\n var path = prefixed && match.pathname.charAt(0) === '/' ? match.pathname.substring(1) : match.pathname;\n locationObj.$$path = decodePath(path, html5Mode);\n locationObj.$$search = parseKeyValue(match.search);\n locationObj.$$hash = decodeURIComponent(match.hash);\n\n // make sure path starts with '/';\n if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') {\n locationObj.$$path = '/' + locationObj.$$path;\n }\n}\n\nfunction startsWith(str, search) {\n return str.slice(0, search.length) === search;\n}\n\n/**\n *\n * @param {string} base\n * @param {string} url\n * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with\n * the expected string.\n */\nfunction stripBaseUrl(base, url) {\n if (startsWith(url, base)) {\n return url.substr(base.length);\n }\n}\n\nfunction stripHash(url) {\n var index = url.indexOf('#');\n return index === -1 ? url : url.substr(0, index);\n}\n\nfunction stripFile(url) {\n return url.substr(0, stripHash(url).lastIndexOf('/') + 1);\n}\n\n/* return the server only (scheme://host:port) */\nfunction serverBase(url) {\n return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));\n}\n\n\n/**\n * LocationHtml5Url represents a URL\n * This object is exposed as $location service when HTML5 mode is enabled and supported\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} appBaseNoFile application base URL stripped of any filename\n * @param {string} basePrefix URL path prefix\n */\nfunction LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {\n this.$$html5 = true;\n basePrefix = basePrefix || '';\n parseAbsoluteUrl(appBase, this);\n\n\n /**\n * Parse given HTML5 (regular) URL string into properties\n * @param {string} url HTML5 URL\n * @private\n */\n this.$$parse = function(url) {\n var pathUrl = stripBaseUrl(appBaseNoFile, url);\n if (!isString(pathUrl)) {\n throw $locationMinErr('ipthprfx', 'Invalid url \"{0}\", missing path prefix \"{1}\".', url,\n appBaseNoFile);\n }\n\n parseAppUrl(pathUrl, this, true);\n\n if (!this.$$path) {\n this.$$path = '/';\n }\n\n this.$$compose();\n };\n\n this.$$normalizeUrl = function(url) {\n return appBaseNoFile + url.substr(1); // first char is always '/'\n };\n\n this.$$parseLinkUrl = function(url, relHref) {\n if (relHref && relHref[0] === '#') {\n // special case for links to hash fragments:\n // keep the old url and only replace the hash fragment\n this.hash(relHref.slice(1));\n return true;\n }\n var appUrl, prevAppUrl;\n var rewrittenUrl;\n\n\n if (isDefined(appUrl = stripBaseUrl(appBase, url))) {\n prevAppUrl = appUrl;\n if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {\n rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);\n } else {\n rewrittenUrl = appBase + prevAppUrl;\n }\n } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {\n rewrittenUrl = appBaseNoFile + appUrl;\n } else if (appBaseNoFile === url + '/') {\n rewrittenUrl = appBaseNoFile;\n }\n if (rewrittenUrl) {\n this.$$parse(rewrittenUrl);\n }\n return !!rewrittenUrl;\n };\n}\n\n\n/**\n * LocationHashbangUrl represents URL\n * This object is exposed as $location service when developer doesn't opt into html5 mode.\n * It also serves as the base class for html5 mode fallback on legacy browsers.\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} appBaseNoFile application base URL stripped of any filename\n * @param {string} hashPrefix hashbang prefix\n */\nfunction LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {\n\n parseAbsoluteUrl(appBase, this);\n\n\n /**\n * Parse given hashbang URL into properties\n * @param {string} url Hashbang URL\n * @private\n */\n this.$$parse = function(url) {\n var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);\n var withoutHashUrl;\n\n if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {\n\n // The rest of the URL starts with a hash so we have\n // got either a hashbang path or a plain hash fragment\n withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);\n if (isUndefined(withoutHashUrl)) {\n // There was no hashbang prefix so we just have a hash fragment\n withoutHashUrl = withoutBaseUrl;\n }\n\n } else {\n // There was no hashbang path nor hash fragment:\n // If we are in HTML5 mode we use what is left as the path;\n // Otherwise we ignore what is left\n if (this.$$html5) {\n withoutHashUrl = withoutBaseUrl;\n } else {\n withoutHashUrl = '';\n if (isUndefined(withoutBaseUrl)) {\n appBase = url;\n /** @type {?} */ (this).replace();\n }\n }\n }\n\n parseAppUrl(withoutHashUrl, this, false);\n\n this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);\n\n this.$$compose();\n\n /*\n * In Windows, on an anchor node on documents loaded from\n * the filesystem, the browser will return a pathname\n * prefixed with the drive name ('/C:/path') when a\n * pathname without a drive is set:\n * * a.setAttribute('href', '/foo')\n * * a.pathname === '/C:/foo' //true\n *\n * Inside of AngularJS, we're always using pathnames that\n * do not include drive names for routing.\n */\n function removeWindowsDriveName(path, url, base) {\n /*\n Matches paths for file protocol on windows,\n such as /C:/foo/bar, and captures only /foo/bar.\n */\n var windowsFilePathExp = /^\\/[A-Z]:(\\/.*)/;\n\n var firstPathSegmentMatch;\n\n //Get the relative path from the input URL.\n if (startsWith(url, base)) {\n url = url.replace(base, '');\n }\n\n // The input URL intentionally contains a first path segment that ends with a colon.\n if (windowsFilePathExp.exec(url)) {\n return path;\n }\n\n firstPathSegmentMatch = windowsFilePathExp.exec(path);\n return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;\n }\n };\n\n this.$$normalizeUrl = function(url) {\n return appBase + (url ? hashPrefix + url : '');\n };\n\n this.$$parseLinkUrl = function(url, relHref) {\n if (stripHash(appBase) === stripHash(url)) {\n this.$$parse(url);\n return true;\n }\n return false;\n };\n}\n\n\n/**\n * LocationHashbangUrl represents URL\n * This object is exposed as $location service when html5 history api is enabled but the browser\n * does not support it.\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} appBaseNoFile application base URL stripped of any filename\n * @param {string} hashPrefix hashbang prefix\n */\nfunction LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {\n this.$$html5 = true;\n LocationHashbangUrl.apply(this, arguments);\n\n this.$$parseLinkUrl = function(url, relHref) {\n if (relHref && relHref[0] === '#') {\n // special case for links to hash fragments:\n // keep the old url and only replace the hash fragment\n this.hash(relHref.slice(1));\n return true;\n }\n\n var rewrittenUrl;\n var appUrl;\n\n if (appBase === stripHash(url)) {\n rewrittenUrl = url;\n } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {\n rewrittenUrl = appBase + hashPrefix + appUrl;\n } else if (appBaseNoFile === url + '/') {\n rewrittenUrl = appBaseNoFile;\n }\n if (rewrittenUrl) {\n this.$$parse(rewrittenUrl);\n }\n return !!rewrittenUrl;\n };\n\n this.$$normalizeUrl = function(url) {\n // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'\n return appBase + hashPrefix + url;\n };\n}\n\n\nvar locationPrototype = {\n\n /**\n * Ensure absolute URL is initialized.\n * @private\n */\n $$absUrl:'',\n\n /**\n * Are we in html5 mode?\n * @private\n */\n $$html5: false,\n\n /**\n * Has any change been replacing?\n * @private\n */\n $$replace: false,\n\n /**\n * Compose url and update `url` and `absUrl` property\n * @private\n */\n $$compose: function() {\n this.$$url = normalizePath(this.$$path, this.$$search, this.$$hash);\n this.$$absUrl = this.$$normalizeUrl(this.$$url);\n this.$$urlUpdatedByLocation = true;\n },\n\n /**\n * @ngdoc method\n * @name $location#absUrl\n *\n * @description\n * This method is getter only.\n *\n * Return full URL representation with all segments encoded according to rules specified in\n * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo\n * var absUrl = $location.absUrl();\n * // => \"http://example.com/#/some/path?foo=bar&baz=xoxo\"\n * ```\n *\n * @return {string} full URL\n */\n absUrl: locationGetter('$$absUrl'),\n\n /**\n * @ngdoc method\n * @name $location#url\n *\n * @description\n * This method is getter / setter.\n *\n * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.\n *\n * Change path, search and hash, when called with parameter and return `$location`.\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo\n * var url = $location.url();\n * // => \"/some/path?foo=bar&baz=xoxo\"\n * ```\n *\n * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)\n * @return {string} url\n */\n url: function(url) {\n if (isUndefined(url)) {\n return this.$$url;\n }\n\n var match = PATH_MATCH.exec(url);\n if (match[1] || url === '') this.path(decodeURIComponent(match[1]));\n if (match[2] || match[1] || url === '') this.search(match[3] || '');\n this.hash(match[5] || '');\n\n return this;\n },\n\n /**\n * @ngdoc method\n * @name $location#protocol\n *\n * @description\n * This method is getter only.\n *\n * Return protocol of current URL.\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo\n * var protocol = $location.protocol();\n * // => \"http\"\n * ```\n *\n * @return {string} protocol of current URL\n */\n protocol: locationGetter('$$protocol'),\n\n /**\n * @ngdoc method\n * @name $location#host\n *\n * @description\n * This method is getter only.\n *\n * Return host of current URL.\n *\n * Note: compared to the non-AngularJS version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo\n * var host = $location.host();\n * // => \"example.com\"\n *\n * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo\n * host = $location.host();\n * // => \"example.com\"\n * host = location.host;\n * // => \"example.com:8080\"\n * ```\n *\n * @return {string} host of current URL.\n */\n host: locationGetter('$$host'),\n\n /**\n * @ngdoc method\n * @name $location#port\n *\n * @description\n * This method is getter only.\n *\n * Return port of current URL.\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo\n * var port = $location.port();\n * // => 80\n * ```\n *\n * @return {Number} port\n */\n port: locationGetter('$$port'),\n\n /**\n * @ngdoc method\n * @name $location#path\n *\n * @description\n * This method is getter / setter.\n *\n * Return path of current URL when called without any parameter.\n *\n * Change path when called with parameter and return `$location`.\n *\n * Note: Path should always begin with forward slash (/), this method will add the forward slash\n * if it is missing.\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo\n * var path = $location.path();\n * // => \"/some/path\"\n * ```\n *\n * @param {(string|number)=} path New path\n * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter\n */\n path: locationGetterSetter('$$path', function(path) {\n path = path !== null ? path.toString() : '';\n return path.charAt(0) === '/' ? path : '/' + path;\n }),\n\n /**\n * @ngdoc method\n * @name $location#search\n *\n * @description\n * This method is getter / setter.\n *\n * Return search part (as object) of current URL when called without any parameter.\n *\n * Change search part when called with parameter and return `$location`.\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo\n * var searchObject = $location.search();\n * // => {foo: 'bar', baz: 'xoxo'}\n *\n * // set foo to 'yipee'\n * $location.search('foo', 'yipee');\n * // $location.search() => {foo: 'yipee', baz: 'xoxo'}\n * ```\n *\n * @param {string|Object.|Object.>} search New search params - string or\n * hash object.\n *\n * When called with a single argument the method acts as a setter, setting the `search` component\n * of `$location` to the specified value.\n *\n * If the argument is a hash object containing an array of values, these values will be encoded\n * as duplicate search parameters in the URL.\n *\n * @param {(string|Number|Array|boolean)=} paramValue If `search` is a string or number, then `paramValue`\n * will override only a single search property.\n *\n * If `paramValue` is an array, it will override the property of the `search` component of\n * `$location` specified via the first argument.\n *\n * If `paramValue` is `null`, the property specified via the first argument will be deleted.\n *\n * If `paramValue` is `true`, the property specified via the first argument will be added with no\n * value nor trailing equal sign.\n *\n * @return {Object} If called with no arguments returns the parsed `search` object. If called with\n * one or more arguments returns `$location` object itself.\n */\n search: function(search, paramValue) {\n switch (arguments.length) {\n case 0:\n return this.$$search;\n case 1:\n if (isString(search) || isNumber(search)) {\n search = search.toString();\n this.$$search = parseKeyValue(search);\n } else if (isObject(search)) {\n search = copy(search, {});\n // remove object undefined or null properties\n forEach(search, function(value, key) {\n if (value == null) delete search[key];\n });\n\n this.$$search = search;\n } else {\n throw $locationMinErr('isrcharg',\n 'The first argument of the `$location#search()` call must be a string or an object.');\n }\n break;\n default:\n if (isUndefined(paramValue) || paramValue === null) {\n delete this.$$search[search];\n } else {\n this.$$search[search] = paramValue;\n }\n }\n\n this.$$compose();\n return this;\n },\n\n /**\n * @ngdoc method\n * @name $location#hash\n *\n * @description\n * This method is getter / setter.\n *\n * Returns the hash fragment when called without any parameters.\n *\n * Changes the hash fragment when called with a parameter and returns `$location`.\n *\n *\n * ```js\n * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue\n * var hash = $location.hash();\n * // => \"hashValue\"\n * ```\n *\n * @param {(string|number)=} hash New hash fragment\n * @return {string} hash\n */\n hash: locationGetterSetter('$$hash', function(hash) {\n return hash !== null ? hash.toString() : '';\n }),\n\n /**\n * @ngdoc method\n * @name $location#replace\n *\n * @description\n * If called, all changes to $location during the current `$digest` will replace the current history\n * record, instead of adding a new one.\n */\n replace: function() {\n this.$$replace = true;\n return this;\n }\n};\n\nforEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {\n Location.prototype = Object.create(locationPrototype);\n\n /**\n * @ngdoc method\n * @name $location#state\n *\n * @description\n * This method is getter / setter.\n *\n * Return the history state object when called without any parameter.\n *\n * Change the history state object when called with one parameter and return `$location`.\n * The state object is later passed to `pushState` or `replaceState`.\n *\n * NOTE: This method is supported only in HTML5 mode and only in browsers supporting\n * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support\n * older browsers (like IE9 or Android < 4.0), don't use this method.\n *\n * @param {object=} state State object for pushState or replaceState\n * @return {object} state\n */\n Location.prototype.state = function(state) {\n if (!arguments.length) {\n return this.$$state;\n }\n\n if (Location !== LocationHtml5Url || !this.$$html5) {\n throw $locationMinErr('nostate', 'History API state support is available only ' +\n 'in HTML5 mode and only in browsers supporting HTML5 History API');\n }\n // The user might modify `stateObject` after invoking `$location.state(stateObject)`\n // but we're changing the $$state reference to $browser.state() during the $digest\n // so the modification window is narrow.\n this.$$state = isUndefined(state) ? null : state;\n this.$$urlUpdatedByLocation = true;\n\n return this;\n };\n});\n\n\nfunction locationGetter(property) {\n return /** @this */ function() {\n return this[property];\n };\n}\n\n\nfunction locationGetterSetter(property, preprocess) {\n return /** @this */ function(value) {\n if (isUndefined(value)) {\n return this[property];\n }\n\n this[property] = preprocess(value);\n this.$$compose();\n\n return this;\n };\n}\n\n\n/**\n * @ngdoc service\n * @name $location\n *\n * @requires $rootElement\n *\n * @description\n * The $location service parses the URL in the browser address bar (based on the\n * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL\n * available to your application. Changes to the URL in the address bar are reflected into\n * $location service and changes to $location are reflected into the browser address bar.\n *\n * **The $location service:**\n *\n * - Exposes the current URL in the browser address bar, so you can\n * - Watch and observe the URL.\n * - Change the URL.\n * - Synchronizes the URL with the browser when the user\n * - Changes the address bar.\n * - Clicks the back or forward button (or clicks a History link).\n * - Clicks on a link.\n * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).\n *\n * For more information see {@link guide/$location Developer Guide: Using $location}\n */\n\n/**\n * @ngdoc provider\n * @name $locationProvider\n * @this\n *\n * @description\n * Use the `$locationProvider` to configure how the application deep linking paths are stored.\n */\nfunction $LocationProvider() {\n var hashPrefix = '!',\n html5Mode = {\n enabled: false,\n requireBase: true,\n rewriteLinks: true\n };\n\n /**\n * @ngdoc method\n * @name $locationProvider#hashPrefix\n * @description\n * The default value for the prefix is `'!'`.\n * @param {string=} prefix Prefix for hash part (containing path and search)\n * @returns {*} current value if used as getter or itself (chaining) if used as setter\n */\n this.hashPrefix = function(prefix) {\n if (isDefined(prefix)) {\n hashPrefix = prefix;\n return this;\n } else {\n return hashPrefix;\n }\n };\n\n /**\n * @ngdoc method\n * @name $locationProvider#html5Mode\n * @description\n * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.\n * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported\n * properties:\n * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to\n * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not\n * support `pushState`.\n * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies\n * whether or not a tag is required to be present. If `enabled` and `requireBase` are\n * true, and a base tag is not present, an error will be thrown when `$location` is injected.\n * See the {@link guide/$location $location guide for more information}\n * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled,\n * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will\n * only happen on links with an attribute that matches the given string. For example, if set\n * to `'internal-link'`, then the URL will only be rewritten for `` links.\n * Note that [attribute name normalization](guide/directive#normalization) does not apply\n * here, so `'internalLink'` will **not** match `'internal-link'`.\n *\n * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter\n */\n this.html5Mode = function(mode) {\n if (isBoolean(mode)) {\n html5Mode.enabled = mode;\n return this;\n } else if (isObject(mode)) {\n\n if (isBoolean(mode.enabled)) {\n html5Mode.enabled = mode.enabled;\n }\n\n if (isBoolean(mode.requireBase)) {\n html5Mode.requireBase = mode.requireBase;\n }\n\n if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) {\n html5Mode.rewriteLinks = mode.rewriteLinks;\n }\n\n return this;\n } else {\n return html5Mode;\n }\n };\n\n /**\n * @ngdoc event\n * @name $location#$locationChangeStart\n * @eventType broadcast on root scope\n * @description\n * Broadcasted before a URL will change.\n *\n * This change can be prevented by calling\n * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more\n * details about event object. Upon successful change\n * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.\n *\n * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when\n * the browser supports the HTML5 History API.\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {string} newUrl New URL\n * @param {string=} oldUrl URL that was before it was changed.\n * @param {string=} newState New history state object\n * @param {string=} oldState History state object that was before it was changed.\n */\n\n /**\n * @ngdoc event\n * @name $location#$locationChangeSuccess\n * @eventType broadcast on root scope\n * @description\n * Broadcasted after a URL was changed.\n *\n * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when\n * the browser supports the HTML5 History API.\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {string} newUrl New URL\n * @param {string=} oldUrl URL that was before it was changed.\n * @param {string=} newState New history state object\n * @param {string=} oldState History state object that was before it was changed.\n */\n\n this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',\n function($rootScope, $browser, $sniffer, $rootElement, $window) {\n var $location,\n LocationMode,\n baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''\n initialUrl = $browser.url(),\n appBase;\n\n if (html5Mode.enabled) {\n if (!baseHref && html5Mode.requireBase) {\n throw $locationMinErr('nobase',\n '$location in HTML5 mode requires a tag to be present!');\n }\n appBase = serverBase(initialUrl) + (baseHref || '/');\n LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;\n } else {\n appBase = stripHash(initialUrl);\n LocationMode = LocationHashbangUrl;\n }\n var appBaseNoFile = stripFile(appBase);\n\n $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);\n $location.$$parseLinkUrl(initialUrl, initialUrl);\n\n $location.$$state = $browser.state();\n\n var IGNORE_URI_REGEXP = /^\\s*(javascript|mailto):/i;\n\n // Determine if two URLs are equal despite potentially having different encoding/normalizing\n // such as $location.absUrl() vs $browser.url()\n // See https://github.com/angular/angular.js/issues/16592\n function urlsEqual(a, b) {\n return a === b || urlResolve(a).href === urlResolve(b).href;\n }\n\n function setBrowserUrlWithFallback(url, replace, state) {\n var oldUrl = $location.url();\n var oldState = $location.$$state;\n try {\n $browser.url(url, replace, state);\n\n // Make sure $location.state() returns referentially identical (not just deeply equal)\n // state object; this makes possible quick checking if the state changed in the digest\n // loop. Checking deep equality would be too expensive.\n $location.$$state = $browser.state();\n } catch (e) {\n // Restore old values if pushState fails\n $location.url(oldUrl);\n $location.$$state = oldState;\n\n throw e;\n }\n }\n\n $rootElement.on('click', function(event) {\n var rewriteLinks = html5Mode.rewriteLinks;\n // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)\n // currently we open nice url link and redirect then\n\n if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return;\n\n var elm = jqLite(event.target);\n\n // traverse the DOM up to find first A tag\n while (nodeName_(elm[0]) !== 'a') {\n // ignore rewriting if no A tag (reached root element, or no parent - removed from document)\n if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;\n }\n\n if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return;\n\n var absHref = elm.prop('href');\n // get the actual href attribute - see\n // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx\n var relHref = elm.attr('href') || elm.attr('xlink:href');\n\n if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {\n // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during\n // an animation.\n absHref = urlResolve(absHref.animVal).href;\n }\n\n // Ignore when url is started with javascript: or mailto:\n if (IGNORE_URI_REGEXP.test(absHref)) return;\n\n if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {\n if ($location.$$parseLinkUrl(absHref, relHref)) {\n // We do a preventDefault for all urls that are part of the AngularJS application,\n // in html5mode and also without, so that we are able to abort navigation without\n // getting double entries in the location history.\n event.preventDefault();\n // update location manually\n if ($location.absUrl() !== $browser.url()) {\n $rootScope.$apply();\n }\n }\n }\n });\n\n\n // rewrite hashbang url <> html5 url\n if ($location.absUrl() !== initialUrl) {\n $browser.url($location.absUrl(), true);\n }\n\n var initializing = true;\n\n // update $location when $browser url changes\n $browser.onUrlChange(function(newUrl, newState) {\n\n if (!startsWith(newUrl, appBaseNoFile)) {\n // If we are navigating outside of the app then force a reload\n $window.location.href = newUrl;\n return;\n }\n\n $rootScope.$evalAsync(function() {\n var oldUrl = $location.absUrl();\n var oldState = $location.$$state;\n var defaultPrevented;\n $location.$$parse(newUrl);\n $location.$$state = newState;\n\n defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,\n newState, oldState).defaultPrevented;\n\n // if the location was changed by a `$locationChangeStart` handler then stop\n // processing this location change\n if ($location.absUrl() !== newUrl) return;\n\n if (defaultPrevented) {\n $location.$$parse(oldUrl);\n $location.$$state = oldState;\n setBrowserUrlWithFallback(oldUrl, false, oldState);\n } else {\n initializing = false;\n afterLocationChange(oldUrl, oldState);\n }\n });\n if (!$rootScope.$$phase) $rootScope.$digest();\n });\n\n // update browser\n $rootScope.$watch(function $locationWatch() {\n if (initializing || $location.$$urlUpdatedByLocation) {\n $location.$$urlUpdatedByLocation = false;\n\n var oldUrl = $browser.url();\n var newUrl = $location.absUrl();\n var oldState = $browser.state();\n var currentReplace = $location.$$replace;\n var urlOrStateChanged = !urlsEqual(oldUrl, newUrl) ||\n ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);\n\n if (initializing || urlOrStateChanged) {\n initializing = false;\n\n $rootScope.$evalAsync(function() {\n var newUrl = $location.absUrl();\n var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,\n $location.$$state, oldState).defaultPrevented;\n\n // if the location was changed by a `$locationChangeStart` handler then stop\n // processing this location change\n if ($location.absUrl() !== newUrl) return;\n\n if (defaultPrevented) {\n $location.$$parse(oldUrl);\n $location.$$state = oldState;\n } else {\n if (urlOrStateChanged) {\n setBrowserUrlWithFallback(newUrl, currentReplace,\n oldState === $location.$$state ? null : $location.$$state);\n }\n afterLocationChange(oldUrl, oldState);\n }\n });\n }\n }\n\n $location.$$replace = false;\n\n // we don't need to return anything because $evalAsync will make the digest loop dirty when\n // there is a change\n });\n\n return $location;\n\n function afterLocationChange(oldUrl, oldState) {\n $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,\n $location.$$state, oldState);\n }\n}];\n}\n\n/**\n * @ngdoc service\n * @name $log\n * @requires $window\n *\n * @description\n * Simple service for logging. Default implementation safely writes the message\n * into the browser's console (if present).\n *\n * The main purpose of this service is to simplify debugging and troubleshooting.\n *\n * To reveal the location of the calls to `$log` in the JavaScript console,\n * you can \"blackbox\" the AngularJS source in your browser:\n *\n * [Mozilla description of blackboxing](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Black_box_a_source).\n * [Chrome description of blackboxing](https://developer.chrome.com/devtools/docs/blackboxing).\n *\n * Note: Not all browsers support blackboxing.\n *\n * The default is to log `debug` messages. You can use\n * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.\n *\n * @example\n \n \n angular.module('logExample', [])\n .controller('LogController', ['$scope', '$log', function($scope, $log) {\n $scope.$log = $log;\n $scope.message = 'Hello World!';\n }]);\n \n \n
\n

Reload this page with open console, enter text and hit the log button...

\n \n \n \n \n \n \n
\n
\n
\n */\n\n/**\n * @ngdoc provider\n * @name $logProvider\n * @this\n *\n * @description\n * Use the `$logProvider` to configure how the application logs messages\n */\nfunction $LogProvider() {\n var debug = true,\n self = this;\n\n /**\n * @ngdoc method\n * @name $logProvider#debugEnabled\n * @description\n * @param {boolean=} flag enable or disable debug level messages\n * @returns {*} current value if used as getter or itself (chaining) if used as setter\n */\n this.debugEnabled = function(flag) {\n if (isDefined(flag)) {\n debug = flag;\n return this;\n } else {\n return debug;\n }\n };\n\n this.$get = ['$window', function($window) {\n // Support: IE 9-11, Edge 12-14+\n // IE/Edge display errors in such a way that it requires the user to click in 4 places\n // to see the stack trace. There is no way to feature-detect it so there's a chance\n // of the user agent sniffing to go wrong but since it's only about logging, this shouldn't\n // break apps. Other browsers display errors in a sensible way and some of them map stack\n // traces along source maps if available so it makes sense to let browsers display it\n // as they want.\n var formatStackTrace = msie || /\\bEdge\\//.test($window.navigator && $window.navigator.userAgent);\n\n return {\n /**\n * @ngdoc method\n * @name $log#log\n *\n * @description\n * Write a log message\n */\n log: consoleLog('log'),\n\n /**\n * @ngdoc method\n * @name $log#info\n *\n * @description\n * Write an information message\n */\n info: consoleLog('info'),\n\n /**\n * @ngdoc method\n * @name $log#warn\n *\n * @description\n * Write a warning message\n */\n warn: consoleLog('warn'),\n\n /**\n * @ngdoc method\n * @name $log#error\n *\n * @description\n * Write an error message\n */\n error: consoleLog('error'),\n\n /**\n * @ngdoc method\n * @name $log#debug\n *\n * @description\n * Write a debug message\n */\n debug: (function() {\n var fn = consoleLog('debug');\n\n return function() {\n if (debug) {\n fn.apply(self, arguments);\n }\n };\n })()\n };\n\n function formatError(arg) {\n if (isError(arg)) {\n if (arg.stack && formatStackTrace) {\n arg = (arg.message && arg.stack.indexOf(arg.message) === -1)\n ? 'Error: ' + arg.message + '\\n' + arg.stack\n : arg.stack;\n } else if (arg.sourceURL) {\n arg = arg.message + '\\n' + arg.sourceURL + ':' + arg.line;\n }\n }\n return arg;\n }\n\n function consoleLog(type) {\n var console = $window.console || {},\n logFn = console[type] || console.log || noop;\n\n return function() {\n var args = [];\n forEach(arguments, function(arg) {\n args.push(formatError(arg));\n });\n // Support: IE 9 only\n // console methods don't inherit from Function.prototype in IE 9 so we can't\n // call `logFn.apply(console, args)` directly.\n return Function.prototype.apply.call(logFn, console, args);\n };\n }\n }];\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Any commits to this file should be reviewed with security in mind. *\n * Changes to this file can potentially create security vulnerabilities. *\n * An approval from 2 Core members with history of modifying *\n * this file is required. *\n * *\n * Does the change somehow allow for arbitrary javascript to be executed? *\n * Or allows for someone to change the prototype of built-in objects? *\n * Or gives undesired access to variables likes document or window? *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\nvar $parseMinErr = minErr('$parse');\n\nvar objectValueOf = {}.constructor.prototype.valueOf;\n\n// Sandboxing AngularJS Expressions\n// ------------------------------\n// AngularJS expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by\n// various means such as obtaining a reference to native JS functions like the Function constructor.\n//\n// As an example, consider the following AngularJS expression:\n//\n// {}.toString.constructor('alert(\"evil JS code\")')\n//\n// It is important to realize that if you create an expression from a string that contains user provided\n// content then it is possible that your application contains a security vulnerability to an XSS style attack.\n//\n// See https://docs.angularjs.org/guide/security\n\n\nfunction getStringValue(name) {\n // Property names must be strings. This means that non-string objects cannot be used\n // as keys in an object. Any non-string object, including a number, is typecasted\n // into a string via the toString method.\n // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names\n //\n // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it\n // to a string. It's not always possible. If `name` is an object and its `toString` method is\n // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:\n //\n // TypeError: Cannot convert object to primitive value\n //\n // For performance reasons, we don't catch this error here and allow it to propagate up the call\n // stack. Note that you'll get the same error in JavaScript if you try to access a property using\n // such a 'broken' object as a key.\n return name + '';\n}\n\n\nvar OPERATORS = createMap();\nforEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });\nvar ESCAPE = {'n':'\\n', 'f':'\\f', 'r':'\\r', 't':'\\t', 'v':'\\v', '\\'':'\\'', '\"':'\"'};\n\n\n/////////////////////////////////////////\n\n\n/**\n * @constructor\n */\nvar Lexer = function Lexer(options) {\n this.options = options;\n};\n\nLexer.prototype = {\n constructor: Lexer,\n\n lex: function(text) {\n this.text = text;\n this.index = 0;\n this.tokens = [];\n\n while (this.index < this.text.length) {\n var ch = this.text.charAt(this.index);\n if (ch === '\"' || ch === '\\'') {\n this.readString(ch);\n } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {\n this.readNumber();\n } else if (this.isIdentifierStart(this.peekMultichar())) {\n this.readIdent();\n } else if (this.is(ch, '(){}[].,;:?')) {\n this.tokens.push({index: this.index, text: ch});\n this.index++;\n } else if (this.isWhitespace(ch)) {\n this.index++;\n } else {\n var ch2 = ch + this.peek();\n var ch3 = ch2 + this.peek(2);\n var op1 = OPERATORS[ch];\n var op2 = OPERATORS[ch2];\n var op3 = OPERATORS[ch3];\n if (op1 || op2 || op3) {\n var token = op3 ? ch3 : (op2 ? ch2 : ch);\n this.tokens.push({index: this.index, text: token, operator: true});\n this.index += token.length;\n } else {\n this.throwError('Unexpected next character ', this.index, this.index + 1);\n }\n }\n }\n return this.tokens;\n },\n\n is: function(ch, chars) {\n return chars.indexOf(ch) !== -1;\n },\n\n peek: function(i) {\n var num = i || 1;\n return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;\n },\n\n isNumber: function(ch) {\n return ('0' <= ch && ch <= '9') && typeof ch === 'string';\n },\n\n isWhitespace: function(ch) {\n // IE treats non-breaking space as \\u00A0\n return (ch === ' ' || ch === '\\r' || ch === '\\t' ||\n ch === '\\n' || ch === '\\v' || ch === '\\u00A0');\n },\n\n isIdentifierStart: function(ch) {\n return this.options.isIdentifierStart ?\n this.options.isIdentifierStart(ch, this.codePointAt(ch)) :\n this.isValidIdentifierStart(ch);\n },\n\n isValidIdentifierStart: function(ch) {\n return ('a' <= ch && ch <= 'z' ||\n 'A' <= ch && ch <= 'Z' ||\n '_' === ch || ch === '$');\n },\n\n isIdentifierContinue: function(ch) {\n return this.options.isIdentifierContinue ?\n this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :\n this.isValidIdentifierContinue(ch);\n },\n\n isValidIdentifierContinue: function(ch, cp) {\n return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);\n },\n\n codePointAt: function(ch) {\n if (ch.length === 1) return ch.charCodeAt(0);\n // eslint-disable-next-line no-bitwise\n return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;\n },\n\n peekMultichar: function() {\n var ch = this.text.charAt(this.index);\n var peek = this.peek();\n if (!peek) {\n return ch;\n }\n var cp1 = ch.charCodeAt(0);\n var cp2 = peek.charCodeAt(0);\n if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {\n return ch + peek;\n }\n return ch;\n },\n\n isExpOperator: function(ch) {\n return (ch === '-' || ch === '+' || this.isNumber(ch));\n },\n\n throwError: function(error, start, end) {\n end = end || this.index;\n var colStr = (isDefined(start)\n ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'\n : ' ' + end);\n throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',\n error, colStr, this.text);\n },\n\n readNumber: function() {\n var number = '';\n var start = this.index;\n while (this.index < this.text.length) {\n var ch = lowercase(this.text.charAt(this.index));\n if (ch === '.' || this.isNumber(ch)) {\n number += ch;\n } else {\n var peekCh = this.peek();\n if (ch === 'e' && this.isExpOperator(peekCh)) {\n number += ch;\n } else if (this.isExpOperator(ch) &&\n peekCh && this.isNumber(peekCh) &&\n number.charAt(number.length - 1) === 'e') {\n number += ch;\n } else if (this.isExpOperator(ch) &&\n (!peekCh || !this.isNumber(peekCh)) &&\n number.charAt(number.length - 1) === 'e') {\n this.throwError('Invalid exponent');\n } else {\n break;\n }\n }\n this.index++;\n }\n this.tokens.push({\n index: start,\n text: number,\n constant: true,\n value: Number(number)\n });\n },\n\n readIdent: function() {\n var start = this.index;\n this.index += this.peekMultichar().length;\n while (this.index < this.text.length) {\n var ch = this.peekMultichar();\n if (!this.isIdentifierContinue(ch)) {\n break;\n }\n this.index += ch.length;\n }\n this.tokens.push({\n index: start,\n text: this.text.slice(start, this.index),\n identifier: true\n });\n },\n\n readString: function(quote) {\n var start = this.index;\n this.index++;\n var string = '';\n var rawString = quote;\n var escape = false;\n while (this.index < this.text.length) {\n var ch = this.text.charAt(this.index);\n rawString += ch;\n if (escape) {\n if (ch === 'u') {\n var hex = this.text.substring(this.index + 1, this.index + 5);\n if (!hex.match(/[\\da-f]{4}/i)) {\n this.throwError('Invalid unicode escape [\\\\u' + hex + ']');\n }\n this.index += 4;\n string += String.fromCharCode(parseInt(hex, 16));\n } else {\n var rep = ESCAPE[ch];\n string = string + (rep || ch);\n }\n escape = false;\n } else if (ch === '\\\\') {\n escape = true;\n } else if (ch === quote) {\n this.index++;\n this.tokens.push({\n index: start,\n text: rawString,\n constant: true,\n value: string\n });\n return;\n } else {\n string += ch;\n }\n this.index++;\n }\n this.throwError('Unterminated quote', start);\n }\n};\n\nvar AST = function AST(lexer, options) {\n this.lexer = lexer;\n this.options = options;\n};\n\nAST.Program = 'Program';\nAST.ExpressionStatement = 'ExpressionStatement';\nAST.AssignmentExpression = 'AssignmentExpression';\nAST.ConditionalExpression = 'ConditionalExpression';\nAST.LogicalExpression = 'LogicalExpression';\nAST.BinaryExpression = 'BinaryExpression';\nAST.UnaryExpression = 'UnaryExpression';\nAST.CallExpression = 'CallExpression';\nAST.MemberExpression = 'MemberExpression';\nAST.Identifier = 'Identifier';\nAST.Literal = 'Literal';\nAST.ArrayExpression = 'ArrayExpression';\nAST.Property = 'Property';\nAST.ObjectExpression = 'ObjectExpression';\nAST.ThisExpression = 'ThisExpression';\nAST.LocalsExpression = 'LocalsExpression';\n\n// Internal use only\nAST.NGValueParameter = 'NGValueParameter';\n\nAST.prototype = {\n ast: function(text) {\n this.text = text;\n this.tokens = this.lexer.lex(text);\n\n var value = this.program();\n\n if (this.tokens.length !== 0) {\n this.throwError('is an unexpected token', this.tokens[0]);\n }\n\n return value;\n },\n\n program: function() {\n var body = [];\n while (true) {\n if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))\n body.push(this.expressionStatement());\n if (!this.expect(';')) {\n return { type: AST.Program, body: body};\n }\n }\n },\n\n expressionStatement: function() {\n return { type: AST.ExpressionStatement, expression: this.filterChain() };\n },\n\n filterChain: function() {\n var left = this.expression();\n while (this.expect('|')) {\n left = this.filter(left);\n }\n return left;\n },\n\n expression: function() {\n return this.assignment();\n },\n\n assignment: function() {\n var result = this.ternary();\n if (this.expect('=')) {\n if (!isAssignable(result)) {\n throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');\n }\n\n result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};\n }\n return result;\n },\n\n ternary: function() {\n var test = this.logicalOR();\n var alternate;\n var consequent;\n if (this.expect('?')) {\n alternate = this.expression();\n if (this.consume(':')) {\n consequent = this.expression();\n return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};\n }\n }\n return test;\n },\n\n logicalOR: function() {\n var left = this.logicalAND();\n while (this.expect('||')) {\n left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };\n }\n return left;\n },\n\n logicalAND: function() {\n var left = this.equality();\n while (this.expect('&&')) {\n left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};\n }\n return left;\n },\n\n equality: function() {\n var left = this.relational();\n var token;\n while ((token = this.expect('==','!=','===','!=='))) {\n left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };\n }\n return left;\n },\n\n relational: function() {\n var left = this.additive();\n var token;\n while ((token = this.expect('<', '>', '<=', '>='))) {\n left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };\n }\n return left;\n },\n\n additive: function() {\n var left = this.multiplicative();\n var token;\n while ((token = this.expect('+','-'))) {\n left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };\n }\n return left;\n },\n\n multiplicative: function() {\n var left = this.unary();\n var token;\n while ((token = this.expect('*','/','%'))) {\n left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };\n }\n return left;\n },\n\n unary: function() {\n var token;\n if ((token = this.expect('+', '-', '!'))) {\n return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };\n } else {\n return this.primary();\n }\n },\n\n primary: function() {\n var primary;\n if (this.expect('(')) {\n primary = this.filterChain();\n this.consume(')');\n } else if (this.expect('[')) {\n primary = this.arrayDeclaration();\n } else if (this.expect('{')) {\n primary = this.object();\n } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {\n primary = copy(this.selfReferential[this.consume().text]);\n } else if (this.options.literals.hasOwnProperty(this.peek().text)) {\n primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};\n } else if (this.peek().identifier) {\n primary = this.identifier();\n } else if (this.peek().constant) {\n primary = this.constant();\n } else {\n this.throwError('not a primary expression', this.peek());\n }\n\n var next;\n while ((next = this.expect('(', '[', '.'))) {\n if (next.text === '(') {\n primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };\n this.consume(')');\n } else if (next.text === '[') {\n primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };\n this.consume(']');\n } else if (next.text === '.') {\n primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };\n } else {\n this.throwError('IMPOSSIBLE');\n }\n }\n return primary;\n },\n\n filter: function(baseExpression) {\n var args = [baseExpression];\n var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};\n\n while (this.expect(':')) {\n args.push(this.expression());\n }\n\n return result;\n },\n\n parseArguments: function() {\n var args = [];\n if (this.peekToken().text !== ')') {\n do {\n args.push(this.filterChain());\n } while (this.expect(','));\n }\n return args;\n },\n\n identifier: function() {\n var token = this.consume();\n if (!token.identifier) {\n this.throwError('is not a valid identifier', token);\n }\n return { type: AST.Identifier, name: token.text };\n },\n\n constant: function() {\n // TODO check that it is a constant\n return { type: AST.Literal, value: this.consume().value };\n },\n\n arrayDeclaration: function() {\n var elements = [];\n if (this.peekToken().text !== ']') {\n do {\n if (this.peek(']')) {\n // Support trailing commas per ES5.1.\n break;\n }\n elements.push(this.expression());\n } while (this.expect(','));\n }\n this.consume(']');\n\n return { type: AST.ArrayExpression, elements: elements };\n },\n\n object: function() {\n var properties = [], property;\n if (this.peekToken().text !== '}') {\n do {\n if (this.peek('}')) {\n // Support trailing commas per ES5.1.\n break;\n }\n property = {type: AST.Property, kind: 'init'};\n if (this.peek().constant) {\n property.key = this.constant();\n property.computed = false;\n this.consume(':');\n property.value = this.expression();\n } else if (this.peek().identifier) {\n property.key = this.identifier();\n property.computed = false;\n if (this.peek(':')) {\n this.consume(':');\n property.value = this.expression();\n } else {\n property.value = property.key;\n }\n } else if (this.peek('[')) {\n this.consume('[');\n property.key = this.expression();\n this.consume(']');\n property.computed = true;\n this.consume(':');\n property.value = this.expression();\n } else {\n this.throwError('invalid key', this.peek());\n }\n properties.push(property);\n } while (this.expect(','));\n }\n this.consume('}');\n\n return {type: AST.ObjectExpression, properties: properties };\n },\n\n throwError: function(msg, token) {\n throw $parseMinErr('syntax',\n 'Syntax Error: Token \\'{0}\\' {1} at column {2} of the expression [{3}] starting at [{4}].',\n token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));\n },\n\n consume: function(e1) {\n if (this.tokens.length === 0) {\n throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);\n }\n\n var token = this.expect(e1);\n if (!token) {\n this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());\n }\n return token;\n },\n\n peekToken: function() {\n if (this.tokens.length === 0) {\n throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);\n }\n return this.tokens[0];\n },\n\n peek: function(e1, e2, e3, e4) {\n return this.peekAhead(0, e1, e2, e3, e4);\n },\n\n peekAhead: function(i, e1, e2, e3, e4) {\n if (this.tokens.length > i) {\n var token = this.tokens[i];\n var t = token.text;\n if (t === e1 || t === e2 || t === e3 || t === e4 ||\n (!e1 && !e2 && !e3 && !e4)) {\n return token;\n }\n }\n return false;\n },\n\n expect: function(e1, e2, e3, e4) {\n var token = this.peek(e1, e2, e3, e4);\n if (token) {\n this.tokens.shift();\n return token;\n }\n return false;\n },\n\n selfReferential: {\n 'this': {type: AST.ThisExpression },\n '$locals': {type: AST.LocalsExpression }\n }\n};\n\nfunction ifDefined(v, d) {\n return typeof v !== 'undefined' ? v : d;\n}\n\nfunction plusFn(l, r) {\n if (typeof l === 'undefined') return r;\n if (typeof r === 'undefined') return l;\n return l + r;\n}\n\nfunction isStateless($filter, filterName) {\n var fn = $filter(filterName);\n return !fn.$stateful;\n}\n\nvar PURITY_ABSOLUTE = 1;\nvar PURITY_RELATIVE = 2;\n\n// Detect nodes which could depend on non-shallow state of objects\nfunction isPure(node, parentIsPure) {\n switch (node.type) {\n // Computed members might invoke a stateful toString()\n case AST.MemberExpression:\n if (node.computed) {\n return false;\n }\n break;\n\n // Unary always convert to primative\n case AST.UnaryExpression:\n return PURITY_ABSOLUTE;\n\n // The binary + operator can invoke a stateful toString().\n case AST.BinaryExpression:\n return node.operator !== '+' ? PURITY_ABSOLUTE : false;\n\n // Functions / filters probably read state from within objects\n case AST.CallExpression:\n return false;\n }\n\n return (undefined === parentIsPure) ? PURITY_RELATIVE : parentIsPure;\n}\n\nfunction findConstantAndWatchExpressions(ast, $filter, parentIsPure) {\n var allConstants;\n var argsToWatch;\n var isStatelessFilter;\n\n var astIsPure = ast.isPure = isPure(ast, parentIsPure);\n\n switch (ast.type) {\n case AST.Program:\n allConstants = true;\n forEach(ast.body, function(expr) {\n findConstantAndWatchExpressions(expr.expression, $filter, astIsPure);\n allConstants = allConstants && expr.expression.constant;\n });\n ast.constant = allConstants;\n break;\n case AST.Literal:\n ast.constant = true;\n ast.toWatch = [];\n break;\n case AST.UnaryExpression:\n findConstantAndWatchExpressions(ast.argument, $filter, astIsPure);\n ast.constant = ast.argument.constant;\n ast.toWatch = ast.argument.toWatch;\n break;\n case AST.BinaryExpression:\n findConstantAndWatchExpressions(ast.left, $filter, astIsPure);\n findConstantAndWatchExpressions(ast.right, $filter, astIsPure);\n ast.constant = ast.left.constant && ast.right.constant;\n ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);\n break;\n case AST.LogicalExpression:\n findConstantAndWatchExpressions(ast.left, $filter, astIsPure);\n findConstantAndWatchExpressions(ast.right, $filter, astIsPure);\n ast.constant = ast.left.constant && ast.right.constant;\n ast.toWatch = ast.constant ? [] : [ast];\n break;\n case AST.ConditionalExpression:\n findConstantAndWatchExpressions(ast.test, $filter, astIsPure);\n findConstantAndWatchExpressions(ast.alternate, $filter, astIsPure);\n findConstantAndWatchExpressions(ast.consequent, $filter, astIsPure);\n ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;\n ast.toWatch = ast.constant ? [] : [ast];\n break;\n case AST.Identifier:\n ast.constant = false;\n ast.toWatch = [ast];\n break;\n case AST.MemberExpression:\n findConstantAndWatchExpressions(ast.object, $filter, astIsPure);\n if (ast.computed) {\n findConstantAndWatchExpressions(ast.property, $filter, astIsPure);\n }\n ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);\n ast.toWatch = ast.constant ? [] : [ast];\n break;\n case AST.CallExpression:\n isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false;\n allConstants = isStatelessFilter;\n argsToWatch = [];\n forEach(ast.arguments, function(expr) {\n findConstantAndWatchExpressions(expr, $filter, astIsPure);\n allConstants = allConstants && expr.constant;\n argsToWatch.push.apply(argsToWatch, expr.toWatch);\n });\n ast.constant = allConstants;\n ast.toWatch = isStatelessFilter ? argsToWatch : [ast];\n break;\n case AST.AssignmentExpression:\n findConstantAndWatchExpressions(ast.left, $filter, astIsPure);\n findConstantAndWatchExpressions(ast.right, $filter, astIsPure);\n ast.constant = ast.left.constant && ast.right.constant;\n ast.toWatch = [ast];\n break;\n case AST.ArrayExpression:\n allConstants = true;\n argsToWatch = [];\n forEach(ast.elements, function(expr) {\n findConstantAndWatchExpressions(expr, $filter, astIsPure);\n allConstants = allConstants && expr.constant;\n argsToWatch.push.apply(argsToWatch, expr.toWatch);\n });\n ast.constant = allConstants;\n ast.toWatch = argsToWatch;\n break;\n case AST.ObjectExpression:\n allConstants = true;\n argsToWatch = [];\n forEach(ast.properties, function(property) {\n findConstantAndWatchExpressions(property.value, $filter, astIsPure);\n allConstants = allConstants && property.value.constant;\n argsToWatch.push.apply(argsToWatch, property.value.toWatch);\n if (property.computed) {\n //`{[key]: value}` implicitly does `key.toString()` which may be non-pure\n findConstantAndWatchExpressions(property.key, $filter, /*parentIsPure=*/false);\n allConstants = allConstants && property.key.constant;\n argsToWatch.push.apply(argsToWatch, property.key.toWatch);\n }\n });\n ast.constant = allConstants;\n ast.toWatch = argsToWatch;\n break;\n case AST.ThisExpression:\n ast.constant = false;\n ast.toWatch = [];\n break;\n case AST.LocalsExpression:\n ast.constant = false;\n ast.toWatch = [];\n break;\n }\n}\n\nfunction getInputs(body) {\n if (body.length !== 1) return;\n var lastExpression = body[0].expression;\n var candidate = lastExpression.toWatch;\n if (candidate.length !== 1) return candidate;\n return candidate[0] !== lastExpression ? candidate : undefined;\n}\n\nfunction isAssignable(ast) {\n return ast.type === AST.Identifier || ast.type === AST.MemberExpression;\n}\n\nfunction assignableAST(ast) {\n if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {\n return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};\n }\n}\n\nfunction isLiteral(ast) {\n return ast.body.length === 0 ||\n ast.body.length === 1 && (\n ast.body[0].expression.type === AST.Literal ||\n ast.body[0].expression.type === AST.ArrayExpression ||\n ast.body[0].expression.type === AST.ObjectExpression);\n}\n\nfunction isConstant(ast) {\n return ast.constant;\n}\n\nfunction ASTCompiler($filter) {\n this.$filter = $filter;\n}\n\nASTCompiler.prototype = {\n compile: function(ast) {\n var self = this;\n this.state = {\n nextId: 0,\n filters: {},\n fn: {vars: [], body: [], own: {}},\n assign: {vars: [], body: [], own: {}},\n inputs: []\n };\n findConstantAndWatchExpressions(ast, self.$filter);\n var extra = '';\n var assignable;\n this.stage = 'assign';\n if ((assignable = assignableAST(ast))) {\n this.state.computing = 'assign';\n var result = this.nextId();\n this.recurse(assignable, result);\n this.return_(result);\n extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');\n }\n var toWatch = getInputs(ast.body);\n self.stage = 'inputs';\n forEach(toWatch, function(watch, key) {\n var fnKey = 'fn' + key;\n self.state[fnKey] = {vars: [], body: [], own: {}};\n self.state.computing = fnKey;\n var intoId = self.nextId();\n self.recurse(watch, intoId);\n self.return_(intoId);\n self.state.inputs.push({name: fnKey, isPure: watch.isPure});\n watch.watchId = key;\n });\n this.state.computing = 'fn';\n this.stage = 'main';\n this.recurse(ast);\n var fnString =\n // The build and minification steps remove the string \"use strict\" from the code, but this is done using a regex.\n // This is a workaround for this until we do a better job at only removing the prefix only when we should.\n '\"' + this.USE + ' ' + this.STRICT + '\";\\n' +\n this.filterPrefix() +\n 'var fn=' + this.generateFunction('fn', 's,l,a,i') +\n extra +\n this.watchFns() +\n 'return fn;';\n\n // eslint-disable-next-line no-new-func\n var fn = (new Function('$filter',\n 'getStringValue',\n 'ifDefined',\n 'plus',\n fnString))(\n this.$filter,\n getStringValue,\n ifDefined,\n plusFn);\n this.state = this.stage = undefined;\n return fn;\n },\n\n USE: 'use',\n\n STRICT: 'strict',\n\n watchFns: function() {\n var result = [];\n var inputs = this.state.inputs;\n var self = this;\n forEach(inputs, function(input) {\n result.push('var ' + input.name + '=' + self.generateFunction(input.name, 's'));\n if (input.isPure) {\n result.push(input.name, '.isPure=' + JSON.stringify(input.isPure) + ';');\n }\n });\n if (inputs.length) {\n result.push('fn.inputs=[' + inputs.map(function(i) { return i.name; }).join(',') + '];');\n }\n return result.join('');\n },\n\n generateFunction: function(name, params) {\n return 'function(' + params + '){' +\n this.varsPrefix(name) +\n this.body(name) +\n '};';\n },\n\n filterPrefix: function() {\n var parts = [];\n var self = this;\n forEach(this.state.filters, function(id, filter) {\n parts.push(id + '=$filter(' + self.escape(filter) + ')');\n });\n if (parts.length) return 'var ' + parts.join(',') + ';';\n return '';\n },\n\n varsPrefix: function(section) {\n return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';\n },\n\n body: function(section) {\n return this.state[section].body.join('');\n },\n\n recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {\n var left, right, self = this, args, expression, computed;\n recursionFn = recursionFn || noop;\n if (!skipWatchIdCheck && isDefined(ast.watchId)) {\n intoId = intoId || this.nextId();\n this.if_('i',\n this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),\n this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)\n );\n return;\n }\n switch (ast.type) {\n case AST.Program:\n forEach(ast.body, function(expression, pos) {\n self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });\n if (pos !== ast.body.length - 1) {\n self.current().body.push(right, ';');\n } else {\n self.return_(right);\n }\n });\n break;\n case AST.Literal:\n expression = this.escape(ast.value);\n this.assign(intoId, expression);\n recursionFn(intoId || expression);\n break;\n case AST.UnaryExpression:\n this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });\n expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';\n this.assign(intoId, expression);\n recursionFn(expression);\n break;\n case AST.BinaryExpression:\n this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });\n this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });\n if (ast.operator === '+') {\n expression = this.plus(left, right);\n } else if (ast.operator === '-') {\n expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);\n } else {\n expression = '(' + left + ')' + ast.operator + '(' + right + ')';\n }\n this.assign(intoId, expression);\n recursionFn(expression);\n break;\n case AST.LogicalExpression:\n intoId = intoId || this.nextId();\n self.recurse(ast.left, intoId);\n self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));\n recursionFn(intoId);\n break;\n case AST.ConditionalExpression:\n intoId = intoId || this.nextId();\n self.recurse(ast.test, intoId);\n self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));\n recursionFn(intoId);\n break;\n case AST.Identifier:\n intoId = intoId || this.nextId();\n if (nameId) {\n nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');\n nameId.computed = false;\n nameId.name = ast.name;\n }\n self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),\n function() {\n self.if_(self.stage === 'inputs' || 's', function() {\n if (create && create !== 1) {\n self.if_(\n self.isNull(self.nonComputedMember('s', ast.name)),\n self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));\n }\n self.assign(intoId, self.nonComputedMember('s', ast.name));\n });\n }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))\n );\n recursionFn(intoId);\n break;\n case AST.MemberExpression:\n left = nameId && (nameId.context = this.nextId()) || this.nextId();\n intoId = intoId || this.nextId();\n self.recurse(ast.object, left, undefined, function() {\n self.if_(self.notNull(left), function() {\n if (ast.computed) {\n right = self.nextId();\n self.recurse(ast.property, right);\n self.getStringValue(right);\n if (create && create !== 1) {\n self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));\n }\n expression = self.computedMember(left, right);\n self.assign(intoId, expression);\n if (nameId) {\n nameId.computed = true;\n nameId.name = right;\n }\n } else {\n if (create && create !== 1) {\n self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));\n }\n expression = self.nonComputedMember(left, ast.property.name);\n self.assign(intoId, expression);\n if (nameId) {\n nameId.computed = false;\n nameId.name = ast.property.name;\n }\n }\n }, function() {\n self.assign(intoId, 'undefined');\n });\n recursionFn(intoId);\n }, !!create);\n break;\n case AST.CallExpression:\n intoId = intoId || this.nextId();\n if (ast.filter) {\n right = self.filter(ast.callee.name);\n args = [];\n forEach(ast.arguments, function(expr) {\n var argument = self.nextId();\n self.recurse(expr, argument);\n args.push(argument);\n });\n expression = right + '(' + args.join(',') + ')';\n self.assign(intoId, expression);\n recursionFn(intoId);\n } else {\n right = self.nextId();\n left = {};\n args = [];\n self.recurse(ast.callee, right, left, function() {\n self.if_(self.notNull(right), function() {\n forEach(ast.arguments, function(expr) {\n self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {\n args.push(argument);\n });\n });\n if (left.name) {\n expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';\n } else {\n expression = right + '(' + args.join(',') + ')';\n }\n self.assign(intoId, expression);\n }, function() {\n self.assign(intoId, 'undefined');\n });\n recursionFn(intoId);\n });\n }\n break;\n case AST.AssignmentExpression:\n right = this.nextId();\n left = {};\n this.recurse(ast.left, undefined, left, function() {\n self.if_(self.notNull(left.context), function() {\n self.recurse(ast.right, right);\n expression = self.member(left.context, left.name, left.computed) + ast.operator + right;\n self.assign(intoId, expression);\n recursionFn(intoId || expression);\n });\n }, 1);\n break;\n case AST.ArrayExpression:\n args = [];\n forEach(ast.elements, function(expr) {\n self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {\n args.push(argument);\n });\n });\n expression = '[' + args.join(',') + ']';\n this.assign(intoId, expression);\n recursionFn(intoId || expression);\n break;\n case AST.ObjectExpression:\n args = [];\n computed = false;\n forEach(ast.properties, function(property) {\n if (property.computed) {\n computed = true;\n }\n });\n if (computed) {\n intoId = intoId || this.nextId();\n this.assign(intoId, '{}');\n forEach(ast.properties, function(property) {\n if (property.computed) {\n left = self.nextId();\n self.recurse(property.key, left);\n } else {\n left = property.key.type === AST.Identifier ?\n property.key.name :\n ('' + property.key.value);\n }\n right = self.nextId();\n self.recurse(property.value, right);\n self.assign(self.member(intoId, left, property.computed), right);\n });\n } else {\n forEach(ast.properties, function(property) {\n self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {\n args.push(self.escape(\n property.key.type === AST.Identifier ? property.key.name :\n ('' + property.key.value)) +\n ':' + expr);\n });\n });\n expression = '{' + args.join(',') + '}';\n this.assign(intoId, expression);\n }\n recursionFn(intoId || expression);\n break;\n case AST.ThisExpression:\n this.assign(intoId, 's');\n recursionFn(intoId || 's');\n break;\n case AST.LocalsExpression:\n this.assign(intoId, 'l');\n recursionFn(intoId || 'l');\n break;\n case AST.NGValueParameter:\n this.assign(intoId, 'v');\n recursionFn(intoId || 'v');\n break;\n }\n },\n\n getHasOwnProperty: function(element, property) {\n var key = element + '.' + property;\n var own = this.current().own;\n if (!own.hasOwnProperty(key)) {\n own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');\n }\n return own[key];\n },\n\n assign: function(id, value) {\n if (!id) return;\n this.current().body.push(id, '=', value, ';');\n return id;\n },\n\n filter: function(filterName) {\n if (!this.state.filters.hasOwnProperty(filterName)) {\n this.state.filters[filterName] = this.nextId(true);\n }\n return this.state.filters[filterName];\n },\n\n ifDefined: function(id, defaultValue) {\n return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';\n },\n\n plus: function(left, right) {\n return 'plus(' + left + ',' + right + ')';\n },\n\n return_: function(id) {\n this.current().body.push('return ', id, ';');\n },\n\n if_: function(test, alternate, consequent) {\n if (test === true) {\n alternate();\n } else {\n var body = this.current().body;\n body.push('if(', test, '){');\n alternate();\n body.push('}');\n if (consequent) {\n body.push('else{');\n consequent();\n body.push('}');\n }\n }\n },\n\n not: function(expression) {\n return '!(' + expression + ')';\n },\n\n isNull: function(expression) {\n return expression + '==null';\n },\n\n notNull: function(expression) {\n return expression + '!=null';\n },\n\n nonComputedMember: function(left, right) {\n var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/;\n var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;\n if (SAFE_IDENTIFIER.test(right)) {\n return left + '.' + right;\n } else {\n return left + '[\"' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '\"]';\n }\n },\n\n computedMember: function(left, right) {\n return left + '[' + right + ']';\n },\n\n member: function(left, right, computed) {\n if (computed) return this.computedMember(left, right);\n return this.nonComputedMember(left, right);\n },\n\n getStringValue: function(item) {\n this.assign(item, 'getStringValue(' + item + ')');\n },\n\n lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {\n var self = this;\n return function() {\n self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);\n };\n },\n\n lazyAssign: function(id, value) {\n var self = this;\n return function() {\n self.assign(id, value);\n };\n },\n\n stringEscapeRegex: /[^ a-zA-Z0-9]/g,\n\n stringEscapeFn: function(c) {\n return '\\\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);\n },\n\n escape: function(value) {\n if (isString(value)) return '\\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\\'';\n if (isNumber(value)) return value.toString();\n if (value === true) return 'true';\n if (value === false) return 'false';\n if (value === null) return 'null';\n if (typeof value === 'undefined') return 'undefined';\n\n throw $parseMinErr('esc', 'IMPOSSIBLE');\n },\n\n nextId: function(skip, init) {\n var id = 'v' + (this.state.nextId++);\n if (!skip) {\n this.current().vars.push(id + (init ? '=' + init : ''));\n }\n return id;\n },\n\n current: function() {\n return this.state[this.state.computing];\n }\n};\n\n\nfunction ASTInterpreter($filter) {\n this.$filter = $filter;\n}\n\nASTInterpreter.prototype = {\n compile: function(ast) {\n var self = this;\n findConstantAndWatchExpressions(ast, self.$filter);\n var assignable;\n var assign;\n if ((assignable = assignableAST(ast))) {\n assign = this.recurse(assignable);\n }\n var toWatch = getInputs(ast.body);\n var inputs;\n if (toWatch) {\n inputs = [];\n forEach(toWatch, function(watch, key) {\n var input = self.recurse(watch);\n input.isPure = watch.isPure;\n watch.input = input;\n inputs.push(input);\n watch.watchId = key;\n });\n }\n var expressions = [];\n forEach(ast.body, function(expression) {\n expressions.push(self.recurse(expression.expression));\n });\n var fn = ast.body.length === 0 ? noop :\n ast.body.length === 1 ? expressions[0] :\n function(scope, locals) {\n var lastValue;\n forEach(expressions, function(exp) {\n lastValue = exp(scope, locals);\n });\n return lastValue;\n };\n if (assign) {\n fn.assign = function(scope, value, locals) {\n return assign(scope, locals, value);\n };\n }\n if (inputs) {\n fn.inputs = inputs;\n }\n return fn;\n },\n\n recurse: function(ast, context, create) {\n var left, right, self = this, args;\n if (ast.input) {\n return this.inputs(ast.input, ast.watchId);\n }\n switch (ast.type) {\n case AST.Literal:\n return this.value(ast.value, context);\n case AST.UnaryExpression:\n right = this.recurse(ast.argument);\n return this['unary' + ast.operator](right, context);\n case AST.BinaryExpression:\n left = this.recurse(ast.left);\n right = this.recurse(ast.right);\n return this['binary' + ast.operator](left, right, context);\n case AST.LogicalExpression:\n left = this.recurse(ast.left);\n right = this.recurse(ast.right);\n return this['binary' + ast.operator](left, right, context);\n case AST.ConditionalExpression:\n return this['ternary?:'](\n this.recurse(ast.test),\n this.recurse(ast.alternate),\n this.recurse(ast.consequent),\n context\n );\n case AST.Identifier:\n return self.identifier(ast.name, context, create);\n case AST.MemberExpression:\n left = this.recurse(ast.object, false, !!create);\n if (!ast.computed) {\n right = ast.property.name;\n }\n if (ast.computed) right = this.recurse(ast.property);\n return ast.computed ?\n this.computedMember(left, right, context, create) :\n this.nonComputedMember(left, right, context, create);\n case AST.CallExpression:\n args = [];\n forEach(ast.arguments, function(expr) {\n args.push(self.recurse(expr));\n });\n if (ast.filter) right = this.$filter(ast.callee.name);\n if (!ast.filter) right = this.recurse(ast.callee, true);\n return ast.filter ?\n function(scope, locals, assign, inputs) {\n var values = [];\n for (var i = 0; i < args.length; ++i) {\n values.push(args[i](scope, locals, assign, inputs));\n }\n var value = right.apply(undefined, values, inputs);\n return context ? {context: undefined, name: undefined, value: value} : value;\n } :\n function(scope, locals, assign, inputs) {\n var rhs = right(scope, locals, assign, inputs);\n var value;\n if (rhs.value != null) {\n var values = [];\n for (var i = 0; i < args.length; ++i) {\n values.push(args[i](scope, locals, assign, inputs));\n }\n value = rhs.value.apply(rhs.context, values);\n }\n return context ? {value: value} : value;\n };\n case AST.AssignmentExpression:\n left = this.recurse(ast.left, true, 1);\n right = this.recurse(ast.right);\n return function(scope, locals, assign, inputs) {\n var lhs = left(scope, locals, assign, inputs);\n var rhs = right(scope, locals, assign, inputs);\n lhs.context[lhs.name] = rhs;\n return context ? {value: rhs} : rhs;\n };\n case AST.ArrayExpression:\n args = [];\n forEach(ast.elements, function(expr) {\n args.push(self.recurse(expr));\n });\n return function(scope, locals, assign, inputs) {\n var value = [];\n for (var i = 0; i < args.length; ++i) {\n value.push(args[i](scope, locals, assign, inputs));\n }\n return context ? {value: value} : value;\n };\n case AST.ObjectExpression:\n args = [];\n forEach(ast.properties, function(property) {\n if (property.computed) {\n args.push({key: self.recurse(property.key),\n computed: true,\n value: self.recurse(property.value)\n });\n } else {\n args.push({key: property.key.type === AST.Identifier ?\n property.key.name :\n ('' + property.key.value),\n computed: false,\n value: self.recurse(property.value)\n });\n }\n });\n return function(scope, locals, assign, inputs) {\n var value = {};\n for (var i = 0; i < args.length; ++i) {\n if (args[i].computed) {\n value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);\n } else {\n value[args[i].key] = args[i].value(scope, locals, assign, inputs);\n }\n }\n return context ? {value: value} : value;\n };\n case AST.ThisExpression:\n return function(scope) {\n return context ? {value: scope} : scope;\n };\n case AST.LocalsExpression:\n return function(scope, locals) {\n return context ? {value: locals} : locals;\n };\n case AST.NGValueParameter:\n return function(scope, locals, assign) {\n return context ? {value: assign} : assign;\n };\n }\n },\n\n 'unary+': function(argument, context) {\n return function(scope, locals, assign, inputs) {\n var arg = argument(scope, locals, assign, inputs);\n if (isDefined(arg)) {\n arg = +arg;\n } else {\n arg = 0;\n }\n return context ? {value: arg} : arg;\n };\n },\n 'unary-': function(argument, context) {\n return function(scope, locals, assign, inputs) {\n var arg = argument(scope, locals, assign, inputs);\n if (isDefined(arg)) {\n arg = -arg;\n } else {\n arg = -0;\n }\n return context ? {value: arg} : arg;\n };\n },\n 'unary!': function(argument, context) {\n return function(scope, locals, assign, inputs) {\n var arg = !argument(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary+': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var lhs = left(scope, locals, assign, inputs);\n var rhs = right(scope, locals, assign, inputs);\n var arg = plusFn(lhs, rhs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary-': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var lhs = left(scope, locals, assign, inputs);\n var rhs = right(scope, locals, assign, inputs);\n var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);\n return context ? {value: arg} : arg;\n };\n },\n 'binary*': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary/': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary%': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary===': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary!==': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary==': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n // eslint-disable-next-line eqeqeq\n var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary!=': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n // eslint-disable-next-line eqeqeq\n var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary<': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary>': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary<=': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary>=': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary&&': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'binary||': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n 'ternary?:': function(test, alternate, consequent, context) {\n return function(scope, locals, assign, inputs) {\n var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },\n value: function(value, context) {\n return function() { return context ? {context: undefined, name: undefined, value: value} : value; };\n },\n identifier: function(name, context, create) {\n return function(scope, locals, assign, inputs) {\n var base = locals && (name in locals) ? locals : scope;\n if (create && create !== 1 && base && base[name] == null) {\n base[name] = {};\n }\n var value = base ? base[name] : undefined;\n if (context) {\n return {context: base, name: name, value: value};\n } else {\n return value;\n }\n };\n },\n computedMember: function(left, right, context, create) {\n return function(scope, locals, assign, inputs) {\n var lhs = left(scope, locals, assign, inputs);\n var rhs;\n var value;\n if (lhs != null) {\n rhs = right(scope, locals, assign, inputs);\n rhs = getStringValue(rhs);\n if (create && create !== 1) {\n if (lhs && !(lhs[rhs])) {\n lhs[rhs] = {};\n }\n }\n value = lhs[rhs];\n }\n if (context) {\n return {context: lhs, name: rhs, value: value};\n } else {\n return value;\n }\n };\n },\n nonComputedMember: function(left, right, context, create) {\n return function(scope, locals, assign, inputs) {\n var lhs = left(scope, locals, assign, inputs);\n if (create && create !== 1) {\n if (lhs && lhs[right] == null) {\n lhs[right] = {};\n }\n }\n var value = lhs != null ? lhs[right] : undefined;\n if (context) {\n return {context: lhs, name: right, value: value};\n } else {\n return value;\n }\n };\n },\n inputs: function(input, watchId) {\n return function(scope, value, locals, inputs) {\n if (inputs) return inputs[watchId];\n return input(scope, value, locals);\n };\n }\n};\n\n/**\n * @constructor\n */\nfunction Parser(lexer, $filter, options) {\n this.ast = new AST(lexer, options);\n this.astCompiler = options.csp ? new ASTInterpreter($filter) :\n new ASTCompiler($filter);\n}\n\nParser.prototype = {\n constructor: Parser,\n\n parse: function(text) {\n var ast = this.getAst(text);\n var fn = this.astCompiler.compile(ast.ast);\n fn.literal = isLiteral(ast.ast);\n fn.constant = isConstant(ast.ast);\n fn.oneTime = ast.oneTime;\n return fn;\n },\n\n getAst: function(exp) {\n var oneTime = false;\n exp = exp.trim();\n\n if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {\n oneTime = true;\n exp = exp.substring(2);\n }\n return {\n ast: this.ast.ast(exp),\n oneTime: oneTime\n };\n }\n};\n\nfunction getValueOf(value) {\n return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);\n}\n\n///////////////////////////////////\n\n/**\n * @ngdoc service\n * @name $parse\n * @kind function\n *\n * @description\n *\n * Converts AngularJS {@link guide/expression expression} into a function.\n *\n * ```js\n * var getter = $parse('user.name');\n * var setter = getter.assign;\n * var context = {user:{name:'AngularJS'}};\n * var locals = {user:{name:'local'}};\n *\n * expect(getter(context)).toEqual('AngularJS');\n * setter(context, 'newValue');\n * expect(context.user.name).toEqual('newValue');\n * expect(getter(context, locals)).toEqual('local');\n * ```\n *\n *\n * @param {string} expression String expression to compile.\n * @returns {function(context, locals)} a function which represents the compiled expression:\n *\n * * `context` – `{object}` – an object against which any expressions embedded in the strings\n * are evaluated against (typically a scope object).\n * * `locals` – `{object=}` – local variables context object, useful for overriding values in\n * `context`.\n *\n * The returned function also has the following properties:\n * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript\n * literal.\n * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript\n * constant literals.\n * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be\n * set to a function to change its value on the given context.\n *\n */\n\n\n/**\n * @ngdoc provider\n * @name $parseProvider\n * @this\n *\n * @description\n * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}\n * service.\n */\nfunction $ParseProvider() {\n var cache = createMap();\n var literals = {\n 'true': true,\n 'false': false,\n 'null': null,\n 'undefined': undefined\n };\n var identStart, identContinue;\n\n /**\n * @ngdoc method\n * @name $parseProvider#addLiteral\n * @description\n *\n * Configure $parse service to add literal values that will be present as literal at expressions.\n *\n * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.\n * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.\n *\n **/\n this.addLiteral = function(literalName, literalValue) {\n literals[literalName] = literalValue;\n };\n\n /**\n * @ngdoc method\n * @name $parseProvider#setIdentifierFns\n *\n * @description\n *\n * Allows defining the set of characters that are allowed in AngularJS expressions. The function\n * `identifierStart` will get called to know if a given character is a valid character to be the\n * first character for an identifier. The function `identifierContinue` will get called to know if\n * a given character is a valid character to be a follow-up identifier character. The functions\n * `identifierStart` and `identifierContinue` will receive as arguments the single character to be\n * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in\n * mind that the `string` parameter can be two characters long depending on the character\n * representation. It is expected for the function to return `true` or `false`, whether that\n * character is allowed or not.\n *\n * Since this function will be called extensively, keep the implementation of these functions fast,\n * as the performance of these functions have a direct impact on the expressions parsing speed.\n *\n * @param {function=} identifierStart The function that will decide whether the given character is\n * a valid identifier start character.\n * @param {function=} identifierContinue The function that will decide whether the given character is\n * a valid identifier continue character.\n */\n this.setIdentifierFns = function(identifierStart, identifierContinue) {\n identStart = identifierStart;\n identContinue = identifierContinue;\n return this;\n };\n\n this.$get = ['$filter', function($filter) {\n var noUnsafeEval = csp().noUnsafeEval;\n var $parseOptions = {\n csp: noUnsafeEval,\n literals: copy(literals),\n isIdentifierStart: isFunction(identStart) && identStart,\n isIdentifierContinue: isFunction(identContinue) && identContinue\n };\n $parse.$$getAst = $$getAst;\n return $parse;\n\n function $parse(exp, interceptorFn) {\n var parsedExpression, cacheKey;\n\n switch (typeof exp) {\n case 'string':\n exp = exp.trim();\n cacheKey = exp;\n\n parsedExpression = cache[cacheKey];\n\n if (!parsedExpression) {\n var lexer = new Lexer($parseOptions);\n var parser = new Parser(lexer, $filter, $parseOptions);\n parsedExpression = parser.parse(exp);\n\n cache[cacheKey] = addWatchDelegate(parsedExpression);\n }\n return addInterceptor(parsedExpression, interceptorFn);\n\n case 'function':\n return addInterceptor(exp, interceptorFn);\n\n default:\n return addInterceptor(noop, interceptorFn);\n }\n }\n\n function $$getAst(exp) {\n var lexer = new Lexer($parseOptions);\n var parser = new Parser(lexer, $filter, $parseOptions);\n return parser.getAst(exp).ast;\n }\n\n function expressionInputDirtyCheck(newValue, oldValueOfValue, compareObjectIdentity) {\n\n if (newValue == null || oldValueOfValue == null) { // null/undefined\n return newValue === oldValueOfValue;\n }\n\n if (typeof newValue === 'object') {\n\n // attempt to convert the value to a primitive type\n // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can\n // be cheaply dirty-checked\n newValue = getValueOf(newValue);\n\n if (typeof newValue === 'object' && !compareObjectIdentity) {\n // objects/arrays are not supported - deep-watching them would be too expensive\n return false;\n }\n\n // fall-through to the primitive equality check\n }\n\n //Primitive or NaN\n // eslint-disable-next-line no-self-compare\n return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);\n }\n\n function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {\n var inputExpressions = parsedExpression.inputs;\n var lastResult;\n\n if (inputExpressions.length === 1) {\n var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails\n inputExpressions = inputExpressions[0];\n return scope.$watch(function expressionInputWatch(scope) {\n var newInputValue = inputExpressions(scope);\n if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf, inputExpressions.isPure)) {\n lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);\n oldInputValueOf = newInputValue && getValueOf(newInputValue);\n }\n return lastResult;\n }, listener, objectEquality, prettyPrintExpression);\n }\n\n var oldInputValueOfValues = [];\n var oldInputValues = [];\n for (var i = 0, ii = inputExpressions.length; i < ii; i++) {\n oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails\n oldInputValues[i] = null;\n }\n\n return scope.$watch(function expressionInputsWatch(scope) {\n var changed = false;\n\n for (var i = 0, ii = inputExpressions.length; i < ii; i++) {\n var newInputValue = inputExpressions[i](scope);\n if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i], inputExpressions[i].isPure))) {\n oldInputValues[i] = newInputValue;\n oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);\n }\n }\n\n if (changed) {\n lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);\n }\n\n return lastResult;\n }, listener, objectEquality, prettyPrintExpression);\n }\n\n function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {\n var isDone = parsedExpression.literal ? isAllDefined : isDefined;\n var unwatch, lastValue;\n\n var exp = parsedExpression.$$intercepted || parsedExpression;\n var post = parsedExpression.$$interceptor || identity;\n\n var useInputs = parsedExpression.inputs && !exp.inputs;\n\n // Propogate the literal/inputs/constant attributes\n // ... but not oneTime since we are handling it\n oneTimeWatch.literal = parsedExpression.literal;\n oneTimeWatch.constant = parsedExpression.constant;\n oneTimeWatch.inputs = parsedExpression.inputs;\n\n // Allow other delegates to run on this wrapped expression\n addWatchDelegate(oneTimeWatch);\n\n unwatch = scope.$watch(oneTimeWatch, listener, objectEquality, prettyPrintExpression);\n\n return unwatch;\n\n function unwatchIfDone() {\n if (isDone(lastValue)) {\n unwatch();\n }\n }\n\n function oneTimeWatch(scope, locals, assign, inputs) {\n lastValue = useInputs && inputs ? inputs[0] : exp(scope, locals, assign, inputs);\n if (isDone(lastValue)) {\n scope.$$postDigest(unwatchIfDone);\n }\n return post(lastValue);\n }\n }\n\n function isAllDefined(value) {\n var allDefined = true;\n forEach(value, function(val) {\n if (!isDefined(val)) allDefined = false;\n });\n return allDefined;\n }\n\n function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n var unwatch = scope.$watch(function constantWatch(scope) {\n unwatch();\n return parsedExpression(scope);\n }, listener, objectEquality);\n return unwatch;\n }\n\n function addWatchDelegate(parsedExpression) {\n if (parsedExpression.constant) {\n parsedExpression.$$watchDelegate = constantWatchDelegate;\n } else if (parsedExpression.oneTime) {\n parsedExpression.$$watchDelegate = oneTimeWatchDelegate;\n } else if (parsedExpression.inputs) {\n parsedExpression.$$watchDelegate = inputsWatchDelegate;\n }\n\n return parsedExpression;\n }\n\n function chainInterceptors(first, second) {\n function chainedInterceptor(value) {\n return second(first(value));\n }\n chainedInterceptor.$stateful = first.$stateful || second.$stateful;\n chainedInterceptor.$$pure = first.$$pure && second.$$pure;\n\n return chainedInterceptor;\n }\n\n function addInterceptor(parsedExpression, interceptorFn) {\n if (!interceptorFn) return parsedExpression;\n\n // Extract any existing interceptors out of the parsedExpression\n // to ensure the original parsedExpression is always the $$intercepted\n if (parsedExpression.$$interceptor) {\n interceptorFn = chainInterceptors(parsedExpression.$$interceptor, interceptorFn);\n parsedExpression = parsedExpression.$$intercepted;\n }\n\n var useInputs = false;\n\n var fn = function interceptedExpression(scope, locals, assign, inputs) {\n var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);\n return interceptorFn(value);\n };\n\n // Maintain references to the interceptor/intercepted\n fn.$$intercepted = parsedExpression;\n fn.$$interceptor = interceptorFn;\n\n // Propogate the literal/oneTime/constant attributes\n fn.literal = parsedExpression.literal;\n fn.oneTime = parsedExpression.oneTime;\n fn.constant = parsedExpression.constant;\n\n // Treat the interceptor like filters.\n // If it is not $stateful then only watch its inputs.\n // If the expression itself has no inputs then use the full expression as an input.\n if (!interceptorFn.$stateful) {\n useInputs = !parsedExpression.inputs;\n fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];\n\n if (!interceptorFn.$$pure) {\n fn.inputs = fn.inputs.map(function(e) {\n // Remove the isPure flag of inputs when it is not absolute because they are now wrapped in a\n // non-pure interceptor function.\n if (e.isPure === PURITY_RELATIVE) {\n return function depurifier(s) { return e(s); };\n }\n return e;\n });\n }\n }\n\n return addWatchDelegate(fn);\n }\n }];\n}\n\n/**\n * @ngdoc service\n * @name $q\n * @requires $rootScope\n *\n * @description\n * A service that helps you run functions asynchronously, and use their return values (or exceptions)\n * when they are done processing.\n *\n * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred\n * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).\n *\n * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred\n * implementations, and the other which resembles ES6 (ES2015) promises to some degree.\n *\n * ## $q constructor\n *\n * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`\n * function as the first argument. This is similar to the native Promise implementation from ES6,\n * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).\n *\n * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are\n * available yet.\n *\n * It can be used like so:\n *\n * ```js\n * // for the purpose of this example let's assume that variables `$q` and `okToGreet`\n * // are available in the current lexical scope (they could have been injected or passed in).\n *\n * function asyncGreet(name) {\n * // perform some asynchronous operation, resolve or reject the promise when appropriate.\n * return $q(function(resolve, reject) {\n * setTimeout(function() {\n * if (okToGreet(name)) {\n * resolve('Hello, ' + name + '!');\n * } else {\n * reject('Greeting ' + name + ' is not allowed.');\n * }\n * }, 1000);\n * });\n * }\n *\n * var promise = asyncGreet('Robin Hood');\n * promise.then(function(greeting) {\n * alert('Success: ' + greeting);\n * }, function(reason) {\n * alert('Failed: ' + reason);\n * });\n * ```\n *\n * Note: progress/notify callbacks are not currently supported via the ES6-style interface.\n *\n * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.\n *\n * However, the more traditional CommonJS-style usage is still available, and documented below.\n *\n * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an\n * interface for interacting with an object that represents the result of an action that is\n * performed asynchronously, and may or may not be finished at any given point in time.\n *\n * From the perspective of dealing with error handling, deferred and promise APIs are to\n * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.\n *\n * ```js\n * // for the purpose of this example let's assume that variables `$q` and `okToGreet`\n * // are available in the current lexical scope (they could have been injected or passed in).\n *\n * function asyncGreet(name) {\n * var deferred = $q.defer();\n *\n * setTimeout(function() {\n * deferred.notify('About to greet ' + name + '.');\n *\n * if (okToGreet(name)) {\n * deferred.resolve('Hello, ' + name + '!');\n * } else {\n * deferred.reject('Greeting ' + name + ' is not allowed.');\n * }\n * }, 1000);\n *\n * return deferred.promise;\n * }\n *\n * var promise = asyncGreet('Robin Hood');\n * promise.then(function(greeting) {\n * alert('Success: ' + greeting);\n * }, function(reason) {\n * alert('Failed: ' + reason);\n * }, function(update) {\n * alert('Got notification: ' + update);\n * });\n * ```\n *\n * At first it might not be obvious why this extra complexity is worth the trouble. The payoff\n * comes in the way of guarantees that promise and deferred APIs make, see\n * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.\n *\n * Additionally the promise api allows for composition that is very hard to do with the\n * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.\n * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the\n * section on serial or parallel joining of promises.\n *\n * ## The Deferred API\n *\n * A new instance of deferred is constructed by calling `$q.defer()`.\n *\n * The purpose of the deferred object is to expose the associated Promise instance as well as APIs\n * that can be used for signaling the successful or unsuccessful completion, as well as the status\n * of the task.\n *\n * **Methods**\n *\n * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection\n * constructed via `$q.reject`, the promise will be rejected instead.\n * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to\n * resolving it with a rejection constructed via `$q.reject`.\n * - `notify(value)` - provides updates on the status of the promise's execution. This may be called\n * multiple times before the promise is either resolved or rejected.\n *\n * **Properties**\n *\n * - promise – `{Promise}` – promise object associated with this deferred.\n *\n *\n * ## The Promise API\n *\n * A new promise instance is created when a deferred instance is created and can be retrieved by\n * calling `deferred.promise`.\n *\n * The purpose of the promise object is to allow for interested parties to get access to the result\n * of the deferred task when it completes.\n *\n * **Methods**\n *\n * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or\n * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously\n * as soon as the result is available. The callbacks are called with a single argument: the result\n * or rejection reason. Additionally, the notify callback may be called zero or more times to\n * provide a progress indication, before the promise is resolved or rejected.\n *\n * This method *returns a new promise* which is resolved or rejected via the return value of the\n * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved\n * with the value which is resolved in that promise using\n * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).\n * It also notifies via the return value of the `notifyCallback` method. The promise cannot be\n * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback\n * arguments are optional.\n *\n * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`\n *\n * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,\n * but to do so without modifying the final value. This is useful to release resources or do some\n * clean-up that needs to be done whether the promise was rejected or resolved. See the [full\n * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for\n * more information.\n *\n * ## Chaining promises\n *\n * Because calling the `then` method of a promise returns a new derived promise, it is easily\n * possible to create a chain of promises:\n *\n * ```js\n * promiseB = promiseA.then(function(result) {\n * return result + 1;\n * });\n *\n * // promiseB will be resolved immediately after promiseA is resolved and its value\n * // will be the result of promiseA incremented by 1\n * ```\n *\n * It is possible to create chains of any length and since a promise can be resolved with another\n * promise (which will defer its resolution further), it is possible to pause/defer resolution of\n * the promises at any point in the chain. This makes it possible to implement powerful APIs like\n * $http's response interceptors.\n *\n *\n * ## Differences between Kris Kowal's Q and $q\n *\n * There are two main differences:\n *\n * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation\n * mechanism in AngularJS, which means faster propagation of resolution or rejection into your\n * models and avoiding unnecessary browser repaints, which would result in flickering UI.\n * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains\n * all the important functionality needed for common async tasks.\n *\n * ## Testing\n *\n * ```js\n * it('should simulate promise', inject(function($q, $rootScope) {\n * var deferred = $q.defer();\n * var promise = deferred.promise;\n * var resolvedValue;\n *\n * promise.then(function(value) { resolvedValue = value; });\n * expect(resolvedValue).toBeUndefined();\n *\n * // Simulate resolving of promise\n * deferred.resolve(123);\n * // Note that the 'then' function does not get called synchronously.\n * // This is because we want the promise API to always be async, whether or not\n * // it got called synchronously or asynchronously.\n * expect(resolvedValue).toBeUndefined();\n *\n * // Propagate promise resolution to 'then' functions using $apply().\n * $rootScope.$apply();\n * expect(resolvedValue).toEqual(123);\n * }));\n * ```\n *\n * @param {function(function, function)} resolver Function which is responsible for resolving or\n * rejecting the newly created promise. The first parameter is a function which resolves the\n * promise, the second parameter is a function which rejects the promise.\n *\n * @returns {Promise} The newly created promise.\n */\n/**\n * @ngdoc provider\n * @name $qProvider\n * @this\n *\n * @description\n */\nfunction $QProvider() {\n var errorOnUnhandledRejections = true;\n this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {\n return qFactory(function(callback) {\n $rootScope.$evalAsync(callback);\n }, $exceptionHandler, errorOnUnhandledRejections);\n }];\n\n /**\n * @ngdoc method\n * @name $qProvider#errorOnUnhandledRejections\n * @kind function\n *\n * @description\n * Retrieves or overrides whether to generate an error when a rejected promise is not handled.\n * This feature is enabled by default.\n *\n * @param {boolean=} value Whether to generate an error when a rejected promise is not handled.\n * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for\n * chaining otherwise.\n */\n this.errorOnUnhandledRejections = function(value) {\n if (isDefined(value)) {\n errorOnUnhandledRejections = value;\n return this;\n } else {\n return errorOnUnhandledRejections;\n }\n };\n}\n\n/** @this */\nfunction $$QProvider() {\n var errorOnUnhandledRejections = true;\n this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {\n return qFactory(function(callback) {\n $browser.defer(callback);\n }, $exceptionHandler, errorOnUnhandledRejections);\n }];\n\n this.errorOnUnhandledRejections = function(value) {\n if (isDefined(value)) {\n errorOnUnhandledRejections = value;\n return this;\n } else {\n return errorOnUnhandledRejections;\n }\n };\n}\n\n/**\n * Constructs a promise manager.\n *\n * @param {function(function)} nextTick Function for executing functions in the next turn.\n * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for\n * debugging purposes.\n * @param {boolean=} errorOnUnhandledRejections Whether an error should be generated on unhandled\n * promises rejections.\n * @returns {object} Promise manager.\n */\nfunction qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) {\n var $qMinErr = minErr('$q', TypeError);\n var queueSize = 0;\n var checkQueue = [];\n\n /**\n * @ngdoc method\n * @name ng.$q#defer\n * @kind function\n *\n * @description\n * Creates a `Deferred` object which represents a task which will finish in the future.\n *\n * @returns {Deferred} Returns a new instance of deferred.\n */\n function defer() {\n return new Deferred();\n }\n\n function Deferred() {\n var promise = this.promise = new Promise();\n //Non prototype methods necessary to support unbound execution :/\n this.resolve = function(val) { resolvePromise(promise, val); };\n this.reject = function(reason) { rejectPromise(promise, reason); };\n this.notify = function(progress) { notifyPromise(promise, progress); };\n }\n\n\n function Promise() {\n this.$$state = { status: 0 };\n }\n\n extend(Promise.prototype, {\n then: function(onFulfilled, onRejected, progressBack) {\n if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {\n return this;\n }\n var result = new Promise();\n\n this.$$state.pending = this.$$state.pending || [];\n this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);\n if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);\n\n return result;\n },\n\n 'catch': function(callback) {\n return this.then(null, callback);\n },\n\n 'finally': function(callback, progressBack) {\n return this.then(function(value) {\n return handleCallback(value, resolve, callback);\n }, function(error) {\n return handleCallback(error, reject, callback);\n }, progressBack);\n }\n });\n\n function processQueue(state) {\n var fn, promise, pending;\n\n pending = state.pending;\n state.processScheduled = false;\n state.pending = undefined;\n try {\n for (var i = 0, ii = pending.length; i < ii; ++i) {\n markQStateExceptionHandled(state);\n promise = pending[i][0];\n fn = pending[i][state.status];\n try {\n if (isFunction(fn)) {\n resolvePromise(promise, fn(state.value));\n } else if (state.status === 1) {\n resolvePromise(promise, state.value);\n } else {\n rejectPromise(promise, state.value);\n }\n } catch (e) {\n rejectPromise(promise, e);\n // This error is explicitly marked for being passed to the $exceptionHandler\n if (e && e.$$passToExceptionHandler === true) {\n exceptionHandler(e);\n }\n }\n }\n } finally {\n --queueSize;\n if (errorOnUnhandledRejections && queueSize === 0) {\n nextTick(processChecks);\n }\n }\n }\n\n function processChecks() {\n // eslint-disable-next-line no-unmodified-loop-condition\n while (!queueSize && checkQueue.length) {\n var toCheck = checkQueue.shift();\n if (!isStateExceptionHandled(toCheck)) {\n markQStateExceptionHandled(toCheck);\n var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value);\n if (isError(toCheck.value)) {\n exceptionHandler(toCheck.value, errorMessage);\n } else {\n exceptionHandler(errorMessage);\n }\n }\n }\n }\n\n function scheduleProcessQueue(state) {\n if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !isStateExceptionHandled(state)) {\n if (queueSize === 0 && checkQueue.length === 0) {\n nextTick(processChecks);\n }\n checkQueue.push(state);\n }\n if (state.processScheduled || !state.pending) return;\n state.processScheduled = true;\n ++queueSize;\n nextTick(function() { processQueue(state); });\n }\n\n function resolvePromise(promise, val) {\n if (promise.$$state.status) return;\n if (val === promise) {\n $$reject(promise, $qMinErr(\n 'qcycle',\n 'Expected promise to be resolved with value other than itself \\'{0}\\'',\n val));\n } else {\n $$resolve(promise, val);\n }\n\n }\n\n function $$resolve(promise, val) {\n var then;\n var done = false;\n try {\n if (isObject(val) || isFunction(val)) then = val.then;\n if (isFunction(then)) {\n promise.$$state.status = -1;\n then.call(val, doResolve, doReject, doNotify);\n } else {\n promise.$$state.value = val;\n promise.$$state.status = 1;\n scheduleProcessQueue(promise.$$state);\n }\n } catch (e) {\n doReject(e);\n }\n\n function doResolve(val) {\n if (done) return;\n done = true;\n $$resolve(promise, val);\n }\n function doReject(val) {\n if (done) return;\n done = true;\n $$reject(promise, val);\n }\n function doNotify(progress) {\n notifyPromise(promise, progress);\n }\n }\n\n function rejectPromise(promise, reason) {\n if (promise.$$state.status) return;\n $$reject(promise, reason);\n }\n\n function $$reject(promise, reason) {\n promise.$$state.value = reason;\n promise.$$state.status = 2;\n scheduleProcessQueue(promise.$$state);\n }\n\n function notifyPromise(promise, progress) {\n var callbacks = promise.$$state.pending;\n\n if ((promise.$$state.status <= 0) && callbacks && callbacks.length) {\n nextTick(function() {\n var callback, result;\n for (var i = 0, ii = callbacks.length; i < ii; i++) {\n result = callbacks[i][0];\n callback = callbacks[i][3];\n try {\n notifyPromise(result, isFunction(callback) ? callback(progress) : progress);\n } catch (e) {\n exceptionHandler(e);\n }\n }\n });\n }\n }\n\n /**\n * @ngdoc method\n * @name $q#reject\n * @kind function\n *\n * @description\n * Creates a promise that is resolved as rejected with the specified `reason`. This api should be\n * used to forward rejection in a chain of promises. If you are dealing with the last promise in\n * a promise chain, you don't need to worry about it.\n *\n * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of\n * `reject` as the `throw` keyword in JavaScript. This also means that if you \"catch\" an error via\n * a promise error callback and you want to forward the error to the promise derived from the\n * current promise, you have to \"rethrow\" the error by returning a rejection constructed via\n * `reject`.\n *\n * ```js\n * promiseB = promiseA.then(function(result) {\n * // success: do something and resolve promiseB\n * // with the old or a new result\n * return result;\n * }, function(reason) {\n * // error: handle the error if possible and\n * // resolve promiseB with newPromiseOrValue,\n * // otherwise forward the rejection to promiseB\n * if (canHandle(reason)) {\n * // handle the error and recover\n * return newPromiseOrValue;\n * }\n * return $q.reject(reason);\n * });\n * ```\n *\n * @param {*} reason Constant, message, exception or an object representing the rejection reason.\n * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.\n */\n function reject(reason) {\n var result = new Promise();\n rejectPromise(result, reason);\n return result;\n }\n\n function handleCallback(value, resolver, callback) {\n var callbackOutput = null;\n try {\n if (isFunction(callback)) callbackOutput = callback();\n } catch (e) {\n return reject(e);\n }\n if (isPromiseLike(callbackOutput)) {\n return callbackOutput.then(function() {\n return resolver(value);\n }, reject);\n } else {\n return resolver(value);\n }\n }\n\n /**\n * @ngdoc method\n * @name $q#when\n * @kind function\n *\n * @description\n * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.\n * This is useful when you are dealing with an object that might or might not be a promise, or if\n * the promise comes from a source that can't be trusted.\n *\n * @param {*} value Value or a promise\n * @param {Function=} successCallback\n * @param {Function=} errorCallback\n * @param {Function=} progressCallback\n * @returns {Promise} Returns a promise of the passed value or promise\n */\n\n\n function when(value, callback, errback, progressBack) {\n var result = new Promise();\n resolvePromise(result, value);\n return result.then(callback, errback, progressBack);\n }\n\n /**\n * @ngdoc method\n * @name $q#resolve\n * @kind function\n *\n * @description\n * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.\n *\n * @param {*} value Value or a promise\n * @param {Function=} successCallback\n * @param {Function=} errorCallback\n * @param {Function=} progressCallback\n * @returns {Promise} Returns a promise of the passed value or promise\n */\n var resolve = when;\n\n /**\n * @ngdoc method\n * @name $q#all\n * @kind function\n *\n * @description\n * Combines multiple promises into a single promise that is resolved when all of the input\n * promises are resolved.\n *\n * @param {Array.|Object.} promises An array or hash of promises.\n * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,\n * each value corresponding to the promise at the same index/key in the `promises` array/hash.\n * If any of the promises is resolved with a rejection, this resulting promise will be rejected\n * with the same rejection value.\n */\n\n function all(promises) {\n var result = new Promise(),\n counter = 0,\n results = isArray(promises) ? [] : {};\n\n forEach(promises, function(promise, key) {\n counter++;\n when(promise).then(function(value) {\n results[key] = value;\n if (!(--counter)) resolvePromise(result, results);\n }, function(reason) {\n rejectPromise(result, reason);\n });\n });\n\n if (counter === 0) {\n resolvePromise(result, results);\n }\n\n return result;\n }\n\n /**\n * @ngdoc method\n * @name $q#race\n * @kind function\n *\n * @description\n * Returns a promise that resolves or rejects as soon as one of those promises\n * resolves or rejects, with the value or reason from that promise.\n *\n * @param {Array.|Object.} promises An array or hash of promises.\n * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises`\n * resolves or rejects, with the value or reason from that promise.\n */\n\n function race(promises) {\n var deferred = defer();\n\n forEach(promises, function(promise) {\n when(promise).then(deferred.resolve, deferred.reject);\n });\n\n return deferred.promise;\n }\n\n function $Q(resolver) {\n if (!isFunction(resolver)) {\n throw $qMinErr('norslvr', 'Expected resolverFn, got \\'{0}\\'', resolver);\n }\n\n var promise = new Promise();\n\n function resolveFn(value) {\n resolvePromise(promise, value);\n }\n\n function rejectFn(reason) {\n rejectPromise(promise, reason);\n }\n\n resolver(resolveFn, rejectFn);\n\n return promise;\n }\n\n // Let's make the instanceof operator work for promises, so that\n // `new $q(fn) instanceof $q` would evaluate to true.\n $Q.prototype = Promise.prototype;\n\n $Q.defer = defer;\n $Q.reject = reject;\n $Q.when = when;\n $Q.resolve = resolve;\n $Q.all = all;\n $Q.race = race;\n\n return $Q;\n}\n\nfunction isStateExceptionHandled(state) {\n return !!state.pur;\n}\nfunction markQStateExceptionHandled(state) {\n state.pur = true;\n}\nfunction markQExceptionHandled(q) {\n // Built-in `$q` promises will always have a `$$state` property. This check is to allow\n // overwriting `$q` with a different promise library (e.g. Bluebird + angular-bluebird-promises).\n // (Currently, this is the only method that might be called with a promise, even if it is not\n // created by the built-in `$q`.)\n if (q.$$state) {\n markQStateExceptionHandled(q.$$state);\n }\n}\n\n/** @this */\nfunction $$RAFProvider() { //rAF\n this.$get = ['$window', '$timeout', function($window, $timeout) {\n var requestAnimationFrame = $window.requestAnimationFrame ||\n $window.webkitRequestAnimationFrame;\n\n var cancelAnimationFrame = $window.cancelAnimationFrame ||\n $window.webkitCancelAnimationFrame ||\n $window.webkitCancelRequestAnimationFrame;\n\n var rafSupported = !!requestAnimationFrame;\n var raf = rafSupported\n ? function(fn) {\n var id = requestAnimationFrame(fn);\n return function() {\n cancelAnimationFrame(id);\n };\n }\n : function(fn) {\n var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666\n return function() {\n $timeout.cancel(timer);\n };\n };\n\n raf.supported = rafSupported;\n\n return raf;\n }];\n}\n\n/**\n * DESIGN NOTES\n *\n * The design decisions behind the scope are heavily favored for speed and memory consumption.\n *\n * The typical use of scope is to watch the expressions, which most of the time return the same\n * value as last time so we optimize the operation.\n *\n * Closures construction is expensive in terms of speed as well as memory:\n * - No closures, instead use prototypical inheritance for API\n * - Internal state needs to be stored on scope directly, which means that private state is\n * exposed as $$____ properties\n *\n * Loop operations are optimized by using while(count--) { ... }\n * - This means that in order to keep the same order of execution as addition we have to add\n * items to the array at the beginning (unshift) instead of at the end (push)\n *\n * Child scopes are created and removed often\n * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists\n *\n * There are fewer watches than observers. This is why you don't want the observer to be implemented\n * in the same way as watch. Watch requires return of the initialization function which is expensive\n * to construct.\n */\n\n\n/**\n * @ngdoc provider\n * @name $rootScopeProvider\n * @description\n *\n * Provider for the $rootScope service.\n */\n\n/**\n * @ngdoc method\n * @name $rootScopeProvider#digestTtl\n * @description\n *\n * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and\n * assuming that the model is unstable.\n *\n * The current default is 10 iterations.\n *\n * In complex applications it's possible that the dependencies between `$watch`s will result in\n * several digest iterations. However if an application needs more than the default 10 digest\n * iterations for its model to stabilize then you should investigate what is causing the model to\n * continuously change during the digest.\n *\n * Increasing the TTL could have performance implications, so you should not change it without\n * proper justification.\n *\n * @param {number} limit The number of digest iterations.\n */\n\n\n/**\n * @ngdoc service\n * @name $rootScope\n * @this\n *\n * @description\n *\n * Every application has a single root {@link ng.$rootScope.Scope scope}.\n * All other scopes are descendant scopes of the root scope. Scopes provide separation\n * between the model and the view, via a mechanism for watching the model for changes.\n * They also provide event emission/broadcast and subscription facility. See the\n * {@link guide/scope developer guide on scopes}.\n */\nfunction $RootScopeProvider() {\n var TTL = 10;\n var $rootScopeMinErr = minErr('$rootScope');\n var lastDirtyWatch = null;\n var applyAsyncId = null;\n\n this.digestTtl = function(value) {\n if (arguments.length) {\n TTL = value;\n }\n return TTL;\n };\n\n function createChildScopeClass(parent) {\n function ChildScope() {\n this.$$watchers = this.$$nextSibling =\n this.$$childHead = this.$$childTail = null;\n this.$$listeners = {};\n this.$$listenerCount = {};\n this.$$watchersCount = 0;\n this.$id = nextUid();\n this.$$ChildScope = null;\n this.$$suspended = false;\n }\n ChildScope.prototype = parent;\n return ChildScope;\n }\n\n this.$get = ['$exceptionHandler', '$parse', '$browser',\n function($exceptionHandler, $parse, $browser) {\n\n function destroyChildScope($event) {\n $event.currentScope.$$destroyed = true;\n }\n\n function cleanUpScope($scope) {\n\n // Support: IE 9 only\n if (msie === 9) {\n // There is a memory leak in IE9 if all child scopes are not disconnected\n // completely when a scope is destroyed. So this code will recurse up through\n // all this scopes children\n //\n // See issue https://github.com/angular/angular.js/issues/10706\n if ($scope.$$childHead) {\n cleanUpScope($scope.$$childHead);\n }\n if ($scope.$$nextSibling) {\n cleanUpScope($scope.$$nextSibling);\n }\n }\n\n // The code below works around IE9 and V8's memory leaks\n //\n // See:\n // - https://code.google.com/p/v8/issues/detail?id=2073#c26\n // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909\n // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451\n\n $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =\n $scope.$$childTail = $scope.$root = $scope.$$watchers = null;\n }\n\n /**\n * @ngdoc type\n * @name $rootScope.Scope\n *\n * @description\n * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the\n * {@link auto.$injector $injector}. Child scopes are created using the\n * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when\n * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for\n * an in-depth introduction and usage examples.\n *\n *\n * ## Inheritance\n * A scope can inherit from a parent scope, as in this example:\n * ```js\n var parent = $rootScope;\n var child = parent.$new();\n\n parent.salutation = \"Hello\";\n expect(child.salutation).toEqual('Hello');\n\n child.salutation = \"Welcome\";\n expect(child.salutation).toEqual('Welcome');\n expect(parent.salutation).toEqual('Hello');\n * ```\n *\n * When interacting with `Scope` in tests, additional helper methods are available on the\n * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional\n * details.\n *\n *\n * @param {Object.=} providers Map of service factory which need to be\n * provided for the current scope. Defaults to {@link ng}.\n * @param {Object.=} instanceCache Provides pre-instantiated services which should\n * append/override services provided by `providers`. This is handy\n * when unit-testing and having the need to override a default\n * service.\n * @returns {Object} Newly created scope.\n *\n */\n function Scope() {\n this.$id = nextUid();\n this.$$phase = this.$parent = this.$$watchers =\n this.$$nextSibling = this.$$prevSibling =\n this.$$childHead = this.$$childTail = null;\n this.$root = this;\n this.$$destroyed = false;\n this.$$suspended = false;\n this.$$listeners = {};\n this.$$listenerCount = {};\n this.$$watchersCount = 0;\n this.$$isolateBindings = null;\n }\n\n /**\n * @ngdoc property\n * @name $rootScope.Scope#$id\n *\n * @description\n * Unique scope ID (monotonically increasing) useful for debugging.\n */\n\n /**\n * @ngdoc property\n * @name $rootScope.Scope#$parent\n *\n * @description\n * Reference to the parent scope.\n */\n\n /**\n * @ngdoc property\n * @name $rootScope.Scope#$root\n *\n * @description\n * Reference to the root scope.\n */\n\n Scope.prototype = {\n constructor: Scope,\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$new\n * @kind function\n *\n * @description\n * Creates a new child {@link ng.$rootScope.Scope scope}.\n *\n * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.\n * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.\n *\n * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is\n * desired for the scope and its child scopes to be permanently detached from the parent and\n * thus stop participating in model change detection and listener notification by invoking.\n *\n * @param {boolean} isolate If true, then the scope does not prototypically inherit from the\n * parent scope. The scope is isolated, as it can not see parent scope properties.\n * When creating widgets, it is useful for the widget to not accidentally read parent\n * state.\n *\n * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`\n * of the newly created scope. Defaults to `this` scope if not provided.\n * This is used when creating a transclude scope to correctly place it\n * in the scope hierarchy while maintaining the correct prototypical\n * inheritance.\n *\n * @returns {Object} The newly created child scope.\n *\n */\n $new: function(isolate, parent) {\n var child;\n\n parent = parent || this;\n\n if (isolate) {\n child = new Scope();\n child.$root = this.$root;\n } else {\n // Only create a child scope class if somebody asks for one,\n // but cache it to allow the VM to optimize lookups.\n if (!this.$$ChildScope) {\n this.$$ChildScope = createChildScopeClass(this);\n }\n child = new this.$$ChildScope();\n }\n child.$parent = parent;\n child.$$prevSibling = parent.$$childTail;\n if (parent.$$childHead) {\n parent.$$childTail.$$nextSibling = child;\n parent.$$childTail = child;\n } else {\n parent.$$childHead = parent.$$childTail = child;\n }\n\n // When the new scope is not isolated or we inherit from `this`, and\n // the parent scope is destroyed, the property `$$destroyed` is inherited\n // prototypically. In all other cases, this property needs to be set\n // when the parent scope is destroyed.\n // The listener needs to be added after the parent is set\n if (isolate || parent !== this) child.$on('$destroy', destroyChildScope);\n\n return child;\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$watch\n * @kind function\n *\n * @description\n * Registers a `listener` callback to be executed whenever the `watchExpression` changes.\n *\n * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest\n * $digest()} and should return the value that will be watched. (`watchExpression` should not change\n * its value when executed multiple times with the same input because it may be executed multiple\n * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be\n * [idempotent](http://en.wikipedia.org/wiki/Idempotence).)\n * - The `listener` is called only when the value from the current `watchExpression` and the\n * previous call to `watchExpression` are not equal (with the exception of the initial run,\n * see below). Inequality is determined according to reference inequality,\n * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)\n * via the `!==` Javascript operator, unless `objectEquality == true`\n * (see next point)\n * - When `objectEquality == true`, inequality of the `watchExpression` is determined\n * according to the {@link angular.equals} function. To save the value of the object for\n * later comparison, the {@link angular.copy} function is used. This therefore means that\n * watching complex objects will have adverse memory and performance implications.\n * - This should not be used to watch for changes in objects that are (or contain)\n * [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}.\n * - The watch `listener` may change the model, which may trigger other `listener`s to fire.\n * This is achieved by rerunning the watchers until no changes are detected. The rerun\n * iteration limit is 10 to prevent an infinite loop deadlock.\n *\n *\n * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,\n * you can register a `watchExpression` function with no `listener`. (Be prepared for\n * multiple calls to your `watchExpression` because it will execute multiple times in a\n * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)\n *\n * After a watcher is registered with the scope, the `listener` fn is called asynchronously\n * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the\n * watcher. In rare cases, this is undesirable because the listener is called when the result\n * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you\n * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the\n * listener was called due to initialization.\n *\n *\n *\n * @example\n * ```js\n // let's assume that scope was dependency injected as the $rootScope\n var scope = $rootScope;\n scope.name = 'misko';\n scope.counter = 0;\n\n expect(scope.counter).toEqual(0);\n scope.$watch('name', function(newValue, oldValue) {\n scope.counter = scope.counter + 1;\n });\n expect(scope.counter).toEqual(0);\n\n scope.$digest();\n // the listener is always called during the first $digest loop after it was registered\n expect(scope.counter).toEqual(1);\n\n scope.$digest();\n // but now it will not be called unless the value changes\n expect(scope.counter).toEqual(1);\n\n scope.name = 'adam';\n scope.$digest();\n expect(scope.counter).toEqual(2);\n\n\n\n // Using a function as a watchExpression\n var food;\n scope.foodCounter = 0;\n expect(scope.foodCounter).toEqual(0);\n scope.$watch(\n // This function returns the value being watched. It is called for each turn of the $digest loop\n function() { return food; },\n // This is the change listener, called when the value returned from the above function changes\n function(newValue, oldValue) {\n if ( newValue !== oldValue ) {\n // Only increment the counter if the value changed\n scope.foodCounter = scope.foodCounter + 1;\n }\n }\n );\n // No digest has been run so the counter will be zero\n expect(scope.foodCounter).toEqual(0);\n\n // Run the digest but since food has not changed count will still be zero\n scope.$digest();\n expect(scope.foodCounter).toEqual(0);\n\n // Update food and run digest. Now the counter will increment\n food = 'cheeseburger';\n scope.$digest();\n expect(scope.foodCounter).toEqual(1);\n\n * ```\n *\n *\n *\n * @param {(function()|string)} watchExpression Expression that is evaluated on each\n * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers\n * a call to the `listener`.\n *\n * - `string`: Evaluated as {@link guide/expression expression}\n * - `function(scope)`: called with current `scope` as a parameter.\n * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value\n * of `watchExpression` changes.\n *\n * - `newVal` contains the current value of the `watchExpression`\n * - `oldVal` contains the previous value of the `watchExpression`\n * - `scope` refers to the current scope\n * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of\n * comparing for reference equality.\n * @returns {function()} Returns a deregistration function for this listener.\n */\n $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {\n var get = $parse(watchExp);\n var fn = isFunction(listener) ? listener : noop;\n\n if (get.$$watchDelegate) {\n return get.$$watchDelegate(this, fn, objectEquality, get, watchExp);\n }\n var scope = this,\n array = scope.$$watchers,\n watcher = {\n fn: fn,\n last: initWatchVal,\n get: get,\n exp: prettyPrintExpression || watchExp,\n eq: !!objectEquality\n };\n\n lastDirtyWatch = null;\n\n if (!array) {\n array = scope.$$watchers = [];\n array.$$digestWatchIndex = -1;\n }\n // we use unshift since we use a while loop in $digest for speed.\n // the while loop reads in reverse order.\n array.unshift(watcher);\n array.$$digestWatchIndex++;\n incrementWatchersCount(this, 1);\n\n return function deregisterWatch() {\n var index = arrayRemove(array, watcher);\n if (index >= 0) {\n incrementWatchersCount(scope, -1);\n if (index < array.$$digestWatchIndex) {\n array.$$digestWatchIndex--;\n }\n }\n lastDirtyWatch = null;\n };\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$watchGroup\n * @kind function\n *\n * @description\n * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.\n * If any one expression in the collection changes the `listener` is executed.\n *\n * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return\n * values are examined for changes on every call to `$digest`.\n * - The `listener` is called whenever any expression in the `watchExpressions` array changes.\n *\n * @param {Array.} watchExpressions Array of expressions that will be individually\n * watched using {@link ng.$rootScope.Scope#$watch $watch()}\n *\n * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any\n * expression in `watchExpressions` changes\n * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching\n * those of `watchExpression`\n * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching\n * those of `watchExpression`\n * The `scope` refers to the current scope.\n * @returns {function()} Returns a de-registration function for all listeners.\n */\n $watchGroup: function(watchExpressions, listener) {\n var oldValues = new Array(watchExpressions.length);\n var newValues = new Array(watchExpressions.length);\n var deregisterFns = [];\n var self = this;\n var changeReactionScheduled = false;\n var firstRun = true;\n\n if (!watchExpressions.length) {\n // No expressions means we call the listener ASAP\n var shouldCall = true;\n self.$evalAsync(function() {\n if (shouldCall) listener(newValues, newValues, self);\n });\n return function deregisterWatchGroup() {\n shouldCall = false;\n };\n }\n\n if (watchExpressions.length === 1) {\n // Special case size of one\n return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {\n newValues[0] = value;\n oldValues[0] = oldValue;\n listener(newValues, (value === oldValue) ? newValues : oldValues, scope);\n });\n }\n\n forEach(watchExpressions, function(expr, i) {\n var unwatchFn = self.$watch(expr, function watchGroupSubAction(value) {\n newValues[i] = value;\n if (!changeReactionScheduled) {\n changeReactionScheduled = true;\n self.$evalAsync(watchGroupAction);\n }\n });\n deregisterFns.push(unwatchFn);\n });\n\n function watchGroupAction() {\n changeReactionScheduled = false;\n\n try {\n if (firstRun) {\n firstRun = false;\n listener(newValues, newValues, self);\n } else {\n listener(newValues, oldValues, self);\n }\n } finally {\n for (var i = 0; i < watchExpressions.length; i++) {\n oldValues[i] = newValues[i];\n }\n }\n }\n\n return function deregisterWatchGroup() {\n while (deregisterFns.length) {\n deregisterFns.shift()();\n }\n };\n },\n\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$watchCollection\n * @kind function\n *\n * @description\n * Shallow watches the properties of an object and fires whenever any of the properties change\n * (for arrays, this implies watching the array items; for object maps, this implies watching\n * the properties). If a change is detected, the `listener` callback is fired.\n *\n * - The `obj` collection is observed via standard $watch operation and is examined on every\n * call to $digest() to see if any items have been added, removed, or moved.\n * - The `listener` is called whenever anything within the `obj` has changed. Examples include\n * adding, removing, and moving items belonging to an object or array.\n *\n *\n * @example\n * ```js\n $scope.names = ['igor', 'matias', 'misko', 'james'];\n $scope.dataCount = 4;\n\n $scope.$watchCollection('names', function(newNames, oldNames) {\n $scope.dataCount = newNames.length;\n });\n\n expect($scope.dataCount).toEqual(4);\n $scope.$digest();\n\n //still at 4 ... no changes\n expect($scope.dataCount).toEqual(4);\n\n $scope.names.pop();\n $scope.$digest();\n\n //now there's been a change\n expect($scope.dataCount).toEqual(3);\n * ```\n *\n *\n * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The\n * expression value should evaluate to an object or an array which is observed on each\n * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the\n * collection will trigger a call to the `listener`.\n *\n * @param {function(newCollection, oldCollection, scope)} listener a callback function called\n * when a change is detected.\n * - The `newCollection` object is the newly modified data obtained from the `obj` expression\n * - The `oldCollection` object is a copy of the former collection data.\n * Due to performance considerations, the`oldCollection` value is computed only if the\n * `listener` function declares two or more arguments.\n * - The `scope` argument refers to the current scope.\n *\n * @returns {function()} Returns a de-registration function for this listener. When the\n * de-registration function is executed, the internal watch operation is terminated.\n */\n $watchCollection: function(obj, listener) {\n // Mark the interceptor as\n // ... $$pure when literal since the instance will change when any input changes\n $watchCollectionInterceptor.$$pure = $parse(obj).literal;\n // ... $stateful when non-literal since we must read the state of the collection\n $watchCollectionInterceptor.$stateful = !$watchCollectionInterceptor.$$pure;\n\n var self = this;\n // the current value, updated on each dirty-check run\n var newValue;\n // a shallow copy of the newValue from the last dirty-check run,\n // updated to match newValue during dirty-check run\n var oldValue;\n // a shallow copy of the newValue from when the last change happened\n var veryOldValue;\n // only track veryOldValue if the listener is asking for it\n var trackVeryOldValue = (listener.length > 1);\n var changeDetected = 0;\n var changeDetector = $parse(obj, $watchCollectionInterceptor);\n var internalArray = [];\n var internalObject = {};\n var initRun = true;\n var oldLength = 0;\n\n function $watchCollectionInterceptor(_value) {\n newValue = _value;\n var newLength, key, bothNaN, newItem, oldItem;\n\n // If the new value is undefined, then return undefined as the watch may be a one-time watch\n if (isUndefined(newValue)) return;\n\n if (!isObject(newValue)) { // if primitive\n if (oldValue !== newValue) {\n oldValue = newValue;\n changeDetected++;\n }\n } else if (isArrayLike(newValue)) {\n if (oldValue !== internalArray) {\n // we are transitioning from something which was not an array into array.\n oldValue = internalArray;\n oldLength = oldValue.length = 0;\n changeDetected++;\n }\n\n newLength = newValue.length;\n\n if (oldLength !== newLength) {\n // if lengths do not match we need to trigger change notification\n changeDetected++;\n oldValue.length = oldLength = newLength;\n }\n // copy the items to oldValue and look for changes.\n for (var i = 0; i < newLength; i++) {\n oldItem = oldValue[i];\n newItem = newValue[i];\n\n // eslint-disable-next-line no-self-compare\n bothNaN = (oldItem !== oldItem) && (newItem !== newItem);\n if (!bothNaN && (oldItem !== newItem)) {\n changeDetected++;\n oldValue[i] = newItem;\n }\n }\n } else {\n if (oldValue !== internalObject) {\n // we are transitioning from something which was not an object into object.\n oldValue = internalObject = {};\n oldLength = 0;\n changeDetected++;\n }\n // copy the items to oldValue and look for changes.\n newLength = 0;\n for (key in newValue) {\n if (hasOwnProperty.call(newValue, key)) {\n newLength++;\n newItem = newValue[key];\n oldItem = oldValue[key];\n\n if (key in oldValue) {\n // eslint-disable-next-line no-self-compare\n bothNaN = (oldItem !== oldItem) && (newItem !== newItem);\n if (!bothNaN && (oldItem !== newItem)) {\n changeDetected++;\n oldValue[key] = newItem;\n }\n } else {\n oldLength++;\n oldValue[key] = newItem;\n changeDetected++;\n }\n }\n }\n if (oldLength > newLength) {\n // we used to have more keys, need to find them and destroy them.\n changeDetected++;\n for (key in oldValue) {\n if (!hasOwnProperty.call(newValue, key)) {\n oldLength--;\n delete oldValue[key];\n }\n }\n }\n }\n return changeDetected;\n }\n\n function $watchCollectionAction() {\n if (initRun) {\n initRun = false;\n listener(newValue, newValue, self);\n } else {\n listener(newValue, veryOldValue, self);\n }\n\n // make a copy for the next time a collection is changed\n if (trackVeryOldValue) {\n if (!isObject(newValue)) {\n //primitive\n veryOldValue = newValue;\n } else if (isArrayLike(newValue)) {\n veryOldValue = new Array(newValue.length);\n for (var i = 0; i < newValue.length; i++) {\n veryOldValue[i] = newValue[i];\n }\n } else { // if object\n veryOldValue = {};\n for (var key in newValue) {\n if (hasOwnProperty.call(newValue, key)) {\n veryOldValue[key] = newValue[key];\n }\n }\n }\n }\n }\n\n return this.$watch(changeDetector, $watchCollectionAction);\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$digest\n * @kind function\n *\n * @description\n * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and\n * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change\n * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}\n * until no more listeners are firing. This means that it is possible to get into an infinite\n * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of\n * iterations exceeds 10.\n *\n * Usually, you don't call `$digest()` directly in\n * {@link ng.directive:ngController controllers} or in\n * {@link ng.$compileProvider#directive directives}.\n * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within\n * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.\n *\n * If you want to be notified whenever `$digest()` is called,\n * you can register a `watchExpression` function with\n * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.\n *\n * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.\n *\n * @example\n * ```js\n var scope = ...;\n scope.name = 'misko';\n scope.counter = 0;\n\n expect(scope.counter).toEqual(0);\n scope.$watch('name', function(newValue, oldValue) {\n scope.counter = scope.counter + 1;\n });\n expect(scope.counter).toEqual(0);\n\n scope.$digest();\n // the listener is always called during the first $digest loop after it was registered\n expect(scope.counter).toEqual(1);\n\n scope.$digest();\n // but now it will not be called unless the value changes\n expect(scope.counter).toEqual(1);\n\n scope.name = 'adam';\n scope.$digest();\n expect(scope.counter).toEqual(2);\n * ```\n *\n */\n $digest: function() {\n var watch, value, last, fn, get,\n watchers,\n dirty, ttl = TTL,\n next, current, target = asyncQueue.length ? $rootScope : this,\n watchLog = [],\n logIdx, asyncTask;\n\n beginPhase('$digest');\n // Check for changes to browser url that happened in sync before the call to $digest\n $browser.$$checkUrlChange();\n\n if (this === $rootScope && applyAsyncId !== null) {\n // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then\n // cancel the scheduled $apply and flush the queue of expressions to be evaluated.\n $browser.defer.cancel(applyAsyncId);\n flushApplyAsync();\n }\n\n lastDirtyWatch = null;\n\n do { // \"while dirty\" loop\n dirty = false;\n current = target;\n\n // It's safe for asyncQueuePosition to be a local variable here because this loop can't\n // be reentered recursively. Calling $digest from a function passed to $evalAsync would\n // lead to a '$digest already in progress' error.\n for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {\n try {\n asyncTask = asyncQueue[asyncQueuePosition];\n fn = asyncTask.fn;\n fn(asyncTask.scope, asyncTask.locals);\n } catch (e) {\n $exceptionHandler(e);\n }\n lastDirtyWatch = null;\n }\n asyncQueue.length = 0;\n\n traverseScopesLoop:\n do { // \"traverse the scopes\" loop\n if ((watchers = !current.$$suspended && current.$$watchers)) {\n // process our watches\n watchers.$$digestWatchIndex = watchers.length;\n while (watchers.$$digestWatchIndex--) {\n try {\n watch = watchers[watchers.$$digestWatchIndex];\n // Most common watches are on primitives, in which case we can short\n // circuit it with === operator, only when === fails do we use .equals\n if (watch) {\n get = watch.get;\n if ((value = get(current)) !== (last = watch.last) &&\n !(watch.eq\n ? equals(value, last)\n : (isNumberNaN(value) && isNumberNaN(last)))) {\n dirty = true;\n lastDirtyWatch = watch;\n watch.last = watch.eq ? copy(value, null) : value;\n fn = watch.fn;\n fn(value, ((last === initWatchVal) ? value : last), current);\n if (ttl < 5) {\n logIdx = 4 - ttl;\n if (!watchLog[logIdx]) watchLog[logIdx] = [];\n watchLog[logIdx].push({\n msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,\n newVal: value,\n oldVal: last\n });\n }\n } else if (watch === lastDirtyWatch) {\n // If the most recently dirty watcher is now clean, short circuit since the remaining watchers\n // have already been tested.\n dirty = false;\n break traverseScopesLoop;\n }\n }\n } catch (e) {\n $exceptionHandler(e);\n }\n }\n }\n\n // Insanity Warning: scope depth-first traversal\n // yes, this code is a bit crazy, but it works and we have tests to prove it!\n // this piece should be kept in sync with the traversal in $broadcast\n // (though it differs due to having the extra check for $$suspended and does not\n // check $$listenerCount)\n if (!(next = ((!current.$$suspended && current.$$watchersCount && current.$$childHead) ||\n (current !== target && current.$$nextSibling)))) {\n while (current !== target && !(next = current.$$nextSibling)) {\n current = current.$parent;\n }\n }\n } while ((current = next));\n\n // `break traverseScopesLoop;` takes us to here\n\n if ((dirty || asyncQueue.length) && !(ttl--)) {\n clearPhase();\n throw $rootScopeMinErr('infdig',\n '{0} $digest() iterations reached. Aborting!\\n' +\n 'Watchers fired in the last 5 iterations: {1}',\n TTL, watchLog);\n }\n\n } while (dirty || asyncQueue.length);\n\n clearPhase();\n\n // postDigestQueuePosition isn't local here because this loop can be reentered recursively.\n while (postDigestQueuePosition < postDigestQueue.length) {\n try {\n postDigestQueue[postDigestQueuePosition++]();\n } catch (e) {\n $exceptionHandler(e);\n }\n }\n postDigestQueue.length = postDigestQueuePosition = 0;\n\n // Check for changes to browser url that happened during the $digest\n // (for which no event is fired; e.g. via `history.pushState()`)\n $browser.$$checkUrlChange();\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$suspend\n * @kind function\n *\n * @description\n * Suspend watchers of this scope subtree so that they will not be invoked during digest.\n *\n * This can be used to optimize your application when you know that running those watchers\n * is redundant.\n *\n * **Warning**\n *\n * Suspending scopes from the digest cycle can have unwanted and difficult to debug results.\n * Only use this approach if you are confident that you know what you are doing and have\n * ample tests to ensure that bindings get updated as you expect.\n *\n * Some of the things to consider are:\n *\n * * Any external event on a directive/component will not trigger a digest while the hosting\n * scope is suspended - even if the event handler calls `$apply()` or `$rootScope.$digest()`.\n * * Transcluded content exists on a scope that inherits from outside a directive but exists\n * as a child of the directive's containing scope. If the containing scope is suspended the\n * transcluded scope will also be suspended, even if the scope from which the transcluded\n * scope inherits is not suspended.\n * * Multiple directives trying to manage the suspended status of a scope can confuse each other:\n * * A call to `$suspend()` on an already suspended scope is a no-op.\n * * A call to `$resume()` on a non-suspended scope is a no-op.\n * * If two directives suspend a scope, then one of them resumes the scope, the scope will no\n * longer be suspended. This could result in the other directive believing a scope to be\n * suspended when it is not.\n * * If a parent scope is suspended then all its descendants will be also excluded from future\n * digests whether or not they have been suspended themselves. Note that this also applies to\n * isolate child scopes.\n * * Calling `$digest()` directly on a descendant of a suspended scope will still run the watchers\n * for that scope and its descendants. When digesting we only check whether the current scope is\n * locally suspended, rather than checking whether it has a suspended ancestor.\n * * Calling `$resume()` on a scope that has a suspended ancestor will not cause the scope to be\n * included in future digests until all its ancestors have been resumed.\n * * Resolved promises, e.g. from explicit `$q` deferreds and `$http` calls, trigger `$apply()`\n * against the `$rootScope` and so will still trigger a global digest even if the promise was\n * initiated by a component that lives on a suspended scope.\n */\n $suspend: function() {\n this.$$suspended = true;\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$isSuspended\n * @kind function\n *\n * @description\n * Call this method to determine if this scope has been explicitly suspended. It will not\n * tell you whether an ancestor has been suspended.\n * To determine if this scope will be excluded from a digest triggered at the $rootScope,\n * for example, you must check all its ancestors:\n *\n * ```\n * function isExcludedFromDigest(scope) {\n * while(scope) {\n * if (scope.$isSuspended()) return true;\n * scope = scope.$parent;\n * }\n * return false;\n * ```\n *\n * Be aware that a scope may not be included in digests if it has a suspended ancestor,\n * even if `$isSuspended()` returns false.\n *\n * @returns true if the current scope has been suspended.\n */\n $isSuspended: function() {\n return this.$$suspended;\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$resume\n * @kind function\n *\n * @description\n * Resume watchers of this scope subtree in case it was suspended.\n *\n * See {@link $rootScope.Scope#$suspend} for information about the dangers of using this approach.\n */\n $resume: function() {\n this.$$suspended = false;\n },\n\n /**\n * @ngdoc event\n * @name $rootScope.Scope#$destroy\n * @eventType broadcast on scope being destroyed\n *\n * @description\n * Broadcasted when a scope and its children are being destroyed.\n *\n * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to\n * clean up DOM bindings before an element is removed from the DOM.\n */\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$destroy\n * @kind function\n *\n * @description\n * Removes the current scope (and all of its children) from the parent scope. Removal implies\n * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer\n * propagate to the current scope and its children. Removal also implies that the current\n * scope is eligible for garbage collection.\n *\n * The `$destroy()` is usually used by directives such as\n * {@link ng.directive:ngRepeat ngRepeat} for managing the\n * unrolling of the loop.\n *\n * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.\n * Application code can register a `$destroy` event handler that will give it a chance to\n * perform any necessary cleanup.\n *\n * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to\n * clean up DOM bindings before an element is removed from the DOM.\n */\n $destroy: function() {\n // We can't destroy a scope that has been already destroyed.\n if (this.$$destroyed) return;\n var parent = this.$parent;\n\n this.$broadcast('$destroy');\n this.$$destroyed = true;\n\n if (this === $rootScope) {\n //Remove handlers attached to window when $rootScope is removed\n $browser.$$applicationDestroyed();\n }\n\n incrementWatchersCount(this, -this.$$watchersCount);\n for (var eventName in this.$$listenerCount) {\n decrementListenerCount(this, this.$$listenerCount[eventName], eventName);\n }\n\n // sever all the references to parent scopes (after this cleanup, the current scope should\n // not be retained by any of our references and should be eligible for garbage collection)\n if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling;\n if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling;\n if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;\n if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;\n\n // Disable listeners, watchers and apply/digest methods\n this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;\n this.$on = this.$watch = this.$watchGroup = function() { return noop; };\n this.$$listeners = {};\n\n // Disconnect the next sibling to prevent `cleanUpScope` destroying those too\n this.$$nextSibling = null;\n cleanUpScope(this);\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$eval\n * @kind function\n *\n * @description\n * Executes the `expression` on the current scope and returns the result. Any exceptions in\n * the expression are propagated (uncaught). This is useful when evaluating AngularJS\n * expressions.\n *\n * @example\n * ```js\n var scope = ng.$rootScope.Scope();\n scope.a = 1;\n scope.b = 2;\n\n expect(scope.$eval('a+b')).toEqual(3);\n expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);\n * ```\n *\n * @param {(string|function())=} expression An AngularJS expression to be executed.\n *\n * - `string`: execute using the rules as defined in {@link guide/expression expression}.\n * - `function(scope)`: execute the function with the current `scope` parameter.\n *\n * @param {(object)=} locals Local variables object, useful for overriding values in scope.\n * @returns {*} The result of evaluating the expression.\n */\n $eval: function(expr, locals) {\n return $parse(expr)(this, locals);\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$evalAsync\n * @kind function\n *\n * @description\n * Executes the expression on the current scope at a later point in time.\n *\n * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only\n * that:\n *\n * - it will execute after the function that scheduled the evaluation (preferably before DOM\n * rendering).\n * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after\n * `expression` execution.\n *\n * Any exceptions from the execution of the expression are forwarded to the\n * {@link ng.$exceptionHandler $exceptionHandler} service.\n *\n * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle\n * will be scheduled. However, it is encouraged to always call code that changes the model\n * from within an `$apply` call. That includes code evaluated via `$evalAsync`.\n *\n * @param {(string|function())=} expression An AngularJS expression to be executed.\n *\n * - `string`: execute using the rules as defined in {@link guide/expression expression}.\n * - `function(scope)`: execute the function with the current `scope` parameter.\n *\n * @param {(object)=} locals Local variables object, useful for overriding values in scope.\n */\n $evalAsync: function(expr, locals) {\n // if we are outside of an $digest loop and this is the first time we are scheduling async\n // task also schedule async auto-flush\n if (!$rootScope.$$phase && !asyncQueue.length) {\n $browser.defer(function() {\n if (asyncQueue.length) {\n $rootScope.$digest();\n }\n }, null, '$evalAsync');\n }\n\n asyncQueue.push({scope: this, fn: $parse(expr), locals: locals});\n },\n\n $$postDigest: function(fn) {\n postDigestQueue.push(fn);\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$apply\n * @kind function\n *\n * @description\n * `$apply()` is used to execute an expression in AngularJS from outside of the AngularJS\n * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).\n * Because we are calling into the AngularJS framework we need to perform proper scope life\n * cycle of {@link ng.$exceptionHandler exception handling},\n * {@link ng.$rootScope.Scope#$digest executing watches}.\n *\n * **Life cycle: Pseudo-Code of `$apply()`**\n *\n * ```js\n function $apply(expr) {\n try {\n return $eval(expr);\n } catch (e) {\n $exceptionHandler(e);\n } finally {\n $root.$digest();\n }\n }\n * ```\n *\n *\n * Scope's `$apply()` method transitions through the following stages:\n *\n * 1. The {@link guide/expression expression} is executed using the\n * {@link ng.$rootScope.Scope#$eval $eval()} method.\n * 2. Any exceptions from the execution of the expression are forwarded to the\n * {@link ng.$exceptionHandler $exceptionHandler} service.\n * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the\n * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.\n *\n *\n * @param {(string|function())=} exp An AngularJS expression to be executed.\n *\n * - `string`: execute using the rules as defined in {@link guide/expression expression}.\n * - `function(scope)`: execute the function with current `scope` parameter.\n *\n * @returns {*} The result of evaluating the expression.\n */\n $apply: function(expr) {\n try {\n beginPhase('$apply');\n try {\n return this.$eval(expr);\n } finally {\n clearPhase();\n }\n } catch (e) {\n $exceptionHandler(e);\n } finally {\n try {\n $rootScope.$digest();\n } catch (e) {\n $exceptionHandler(e);\n // eslint-disable-next-line no-unsafe-finally\n throw e;\n }\n }\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$applyAsync\n * @kind function\n *\n * @description\n * Schedule the invocation of $apply to occur at a later time. The actual time difference\n * varies across browsers, but is typically around ~10 milliseconds.\n *\n * This can be used to queue up multiple expressions which need to be evaluated in the same\n * digest.\n *\n * @param {(string|function())=} exp An AngularJS expression to be executed.\n *\n * - `string`: execute using the rules as defined in {@link guide/expression expression}.\n * - `function(scope)`: execute the function with current `scope` parameter.\n */\n $applyAsync: function(expr) {\n var scope = this;\n if (expr) {\n applyAsyncQueue.push($applyAsyncExpression);\n }\n expr = $parse(expr);\n scheduleApplyAsync();\n\n function $applyAsyncExpression() {\n scope.$eval(expr);\n }\n },\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$on\n * @kind function\n *\n * @description\n * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for\n * discussion of event life cycle.\n *\n * The event listener function format is: `function(event, args...)`. The `event` object\n * passed into the listener has the following attributes:\n *\n * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or\n * `$broadcast`-ed.\n * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the\n * event propagates through the scope hierarchy, this property is set to null.\n * - `name` - `{string}`: name of the event.\n * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel\n * further event propagation (available only for events that were `$emit`-ed).\n * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag\n * to true.\n * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.\n *\n * @param {string} name Event name to listen on.\n * @param {function(event, ...args)} listener Function to call when the event is emitted.\n * @returns {function()} Returns a deregistration function for this listener.\n */\n $on: function(name, listener) {\n var namedListeners = this.$$listeners[name];\n if (!namedListeners) {\n this.$$listeners[name] = namedListeners = [];\n }\n namedListeners.push(listener);\n\n var current = this;\n do {\n if (!current.$$listenerCount[name]) {\n current.$$listenerCount[name] = 0;\n }\n current.$$listenerCount[name]++;\n } while ((current = current.$parent));\n\n var self = this;\n return function() {\n var indexOfListener = namedListeners.indexOf(listener);\n if (indexOfListener !== -1) {\n // Use delete in the hope of the browser deallocating the memory for the array entry,\n // while not shifting the array indexes of other listeners.\n // See issue https://github.com/angular/angular.js/issues/16135\n delete namedListeners[indexOfListener];\n decrementListenerCount(self, 1, name);\n }\n };\n },\n\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$emit\n * @kind function\n *\n * @description\n * Dispatches an event `name` upwards through the scope hierarchy notifying the\n * registered {@link ng.$rootScope.Scope#$on} listeners.\n *\n * The event life cycle starts at the scope on which `$emit` was called. All\n * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get\n * notified. Afterwards, the event traverses upwards toward the root scope and calls all\n * registered listeners along the way. The event will stop propagating if one of the listeners\n * cancels it.\n *\n * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed\n * onto the {@link ng.$exceptionHandler $exceptionHandler} service.\n *\n * @param {string} name Event name to emit.\n * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.\n * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).\n */\n $emit: function(name, args) {\n var empty = [],\n namedListeners,\n scope = this,\n stopPropagation = false,\n event = {\n name: name,\n targetScope: scope,\n stopPropagation: function() {stopPropagation = true;},\n preventDefault: function() {\n event.defaultPrevented = true;\n },\n defaultPrevented: false\n },\n listenerArgs = concat([event], arguments, 1),\n i, length;\n\n do {\n namedListeners = scope.$$listeners[name] || empty;\n event.currentScope = scope;\n for (i = 0, length = namedListeners.length; i < length; i++) {\n\n // if listeners were deregistered, defragment the array\n if (!namedListeners[i]) {\n namedListeners.splice(i, 1);\n i--;\n length--;\n continue;\n }\n try {\n //allow all listeners attached to the current scope to run\n namedListeners[i].apply(null, listenerArgs);\n } catch (e) {\n $exceptionHandler(e);\n }\n }\n //if any listener on the current scope stops propagation, prevent bubbling\n if (stopPropagation) {\n break;\n }\n //traverse upwards\n scope = scope.$parent;\n } while (scope);\n\n event.currentScope = null;\n\n return event;\n },\n\n\n /**\n * @ngdoc method\n * @name $rootScope.Scope#$broadcast\n * @kind function\n *\n * @description\n * Dispatches an event `name` downwards to all child scopes (and their children) notifying the\n * registered {@link ng.$rootScope.Scope#$on} listeners.\n *\n * The event life cycle starts at the scope on which `$broadcast` was called. All\n * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get\n * notified. Afterwards, the event propagates to all direct and indirect scopes of the current\n * scope and calls all registered listeners along the way. The event cannot be canceled.\n *\n * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed\n * onto the {@link ng.$exceptionHandler $exceptionHandler} service.\n *\n * @param {string} name Event name to broadcast.\n * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.\n * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}\n */\n $broadcast: function(name, args) {\n var target = this,\n current = target,\n next = target,\n event = {\n name: name,\n targetScope: target,\n preventDefault: function() {\n event.defaultPrevented = true;\n },\n defaultPrevented: false\n };\n\n if (!target.$$listenerCount[name]) return event;\n\n var listenerArgs = concat([event], arguments, 1),\n listeners, i, length;\n\n //down while you can, then up and next sibling or up and next sibling until back at root\n while ((current = next)) {\n event.currentScope = current;\n listeners = current.$$listeners[name] || [];\n for (i = 0, length = listeners.length; i < length; i++) {\n // if listeners were deregistered, defragment the array\n if (!listeners[i]) {\n listeners.splice(i, 1);\n i--;\n length--;\n continue;\n }\n\n try {\n listeners[i].apply(null, listenerArgs);\n } catch (e) {\n $exceptionHandler(e);\n }\n }\n\n // Insanity Warning: scope depth-first traversal\n // yes, this code is a bit crazy, but it works and we have tests to prove it!\n // this piece should be kept in sync with the traversal in $digest\n // (though it differs due to having the extra check for $$listenerCount and\n // does not check $$suspended)\n if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||\n (current !== target && current.$$nextSibling)))) {\n while (current !== target && !(next = current.$$nextSibling)) {\n current = current.$parent;\n }\n }\n }\n\n event.currentScope = null;\n return event;\n }\n };\n\n var $rootScope = new Scope();\n\n //The internal queues. Expose them on the $rootScope for debugging/testing purposes.\n var asyncQueue = $rootScope.$$asyncQueue = [];\n var postDigestQueue = $rootScope.$$postDigestQueue = [];\n var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];\n\n var postDigestQueuePosition = 0;\n\n return $rootScope;\n\n\n function beginPhase(phase) {\n if ($rootScope.$$phase) {\n throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);\n }\n\n $rootScope.$$phase = phase;\n }\n\n function clearPhase() {\n $rootScope.$$phase = null;\n }\n\n function incrementWatchersCount(current, count) {\n do {\n current.$$watchersCount += count;\n } while ((current = current.$parent));\n }\n\n function decrementListenerCount(current, count, name) {\n do {\n current.$$listenerCount[name] -= count;\n\n if (current.$$listenerCount[name] === 0) {\n delete current.$$listenerCount[name];\n }\n } while ((current = current.$parent));\n }\n\n /**\n * function used as an initial value for watchers.\n * because it's unique we can easily tell it apart from other values\n */\n function initWatchVal() {}\n\n function flushApplyAsync() {\n while (applyAsyncQueue.length) {\n try {\n applyAsyncQueue.shift()();\n } catch (e) {\n $exceptionHandler(e);\n }\n }\n applyAsyncId = null;\n }\n\n function scheduleApplyAsync() {\n if (applyAsyncId === null) {\n applyAsyncId = $browser.defer(function() {\n $rootScope.$apply(flushApplyAsync);\n }, null, '$applyAsync');\n }\n }\n }];\n}\n\n/**\n * @ngdoc service\n * @name $rootElement\n *\n * @description\n * The root element of AngularJS application. This is either the element where {@link\n * ng.directive:ngApp ngApp} was declared or the element passed into\n * {@link angular.bootstrap}. The element represents the root element of application. It is also the\n * location where the application's {@link auto.$injector $injector} service gets\n * published, and can be retrieved using `$rootElement.injector()`.\n */\n\n\n// the implementation is in angular.bootstrap\n\n/**\n * @this\n * @description\n * Private service to sanitize uris for links and images. Used by $compile and $sanitize.\n */\nfunction $$SanitizeUriProvider() {\n\n var aHrefSanitizationWhitelist = /^\\s*(https?|s?ftp|mailto|tel|file):/,\n imgSrcSanitizationWhitelist = /^\\s*((https?|ftp|file|blob):|data:image\\/)/;\n\n /**\n * @description\n * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n * urls during a[href] sanitization.\n *\n * The sanitization is a security measure aimed at prevent XSS attacks via HTML anchor links.\n *\n * Any url due to be assigned to an `a[href]` attribute via interpolation is marked as requiring\n * the $sce.URL security context. When interpolation occurs a call is made to `$sce.trustAsUrl(url)`\n * which in turn may call `$$sanitizeUri(url, isMedia)` to sanitize the potentially malicious URL.\n *\n * If the URL matches the `aHrefSanitizationWhitelist` regular expression, it is returned unchanged.\n *\n * If there is no match the URL is returned prefixed with `'unsafe:'` to ensure that when it is written\n * to the DOM it is inactive and potentially malicious code will not be executed.\n *\n * @param {RegExp=} regexp New regexp to whitelist urls with.\n * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n * chaining otherwise.\n */\n this.aHrefSanitizationWhitelist = function(regexp) {\n if (isDefined(regexp)) {\n aHrefSanitizationWhitelist = regexp;\n return this;\n }\n return aHrefSanitizationWhitelist;\n };\n\n\n /**\n * @description\n * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n * urls during img[src] sanitization.\n *\n * The sanitization is a security measure aimed at prevent XSS attacks via HTML image src links.\n *\n * Any URL due to be assigned to an `img[src]` attribute via interpolation is marked as requiring\n * the $sce.MEDIA_URL security context. When interpolation occurs a call is made to\n * `$sce.trustAsMediaUrl(url)` which in turn may call `$$sanitizeUri(url, isMedia)` to sanitize\n * the potentially malicious URL.\n *\n * If the URL matches the `aImgSanitizationWhitelist` regular expression, it is returned unchanged.\n *\n * If there is no match the URL is returned prefixed with `'unsafe:'` to ensure that when it is written\n * to the DOM it is inactive and potentially malicious code will not be executed.\n *\n * @param {RegExp=} regexp New regexp to whitelist urls with.\n * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n * chaining otherwise.\n */\n this.imgSrcSanitizationWhitelist = function(regexp) {\n if (isDefined(regexp)) {\n imgSrcSanitizationWhitelist = regexp;\n return this;\n }\n return imgSrcSanitizationWhitelist;\n };\n\n this.$get = function() {\n return function sanitizeUri(uri, isMediaUrl) {\n // if (!uri) return uri;\n var regex = isMediaUrl ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;\n var normalizedVal = urlResolve(uri && uri.trim()).href;\n if (normalizedVal !== '' && !normalizedVal.match(regex)) {\n return 'unsafe:' + normalizedVal;\n }\n return uri;\n };\n };\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Any commits to this file should be reviewed with security in mind. *\n * Changes to this file can potentially create security vulnerabilities. *\n * An approval from 2 Core members with history of modifying *\n * this file is required. *\n * *\n * Does the change somehow allow for arbitrary javascript to be executed? *\n * Or allows for someone to change the prototype of built-in objects? *\n * Or gives undesired access to variables likes document or window? *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/* exported $SceProvider, $SceDelegateProvider */\n\nvar $sceMinErr = minErr('$sce');\n\nvar SCE_CONTEXTS = {\n // HTML is used when there's HTML rendered (e.g. ng-bind-html, iframe srcdoc binding).\n HTML: 'html',\n\n // Style statements or stylesheets. Currently unused in AngularJS.\n CSS: 'css',\n\n // An URL used in a context where it refers to the source of media, which are not expected to be run\n // as scripts, such as an image, audio, video, etc.\n MEDIA_URL: 'mediaUrl',\n\n // An URL used in a context where it does not refer to a resource that loads code.\n // A value that can be trusted as a URL can also trusted as a MEDIA_URL.\n URL: 'url',\n\n // RESOURCE_URL is a subtype of URL used where the referred-to resource could be interpreted as\n // code. (e.g. ng-include, script src binding, templateUrl)\n // A value that can be trusted as a RESOURCE_URL, can also trusted as a URL and a MEDIA_URL.\n RESOURCE_URL: 'resourceUrl',\n\n // Script. Currently unused in AngularJS.\n JS: 'js'\n};\n\n// Helper functions follow.\n\nvar UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g;\n\nfunction snakeToCamel(name) {\n return name\n .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace);\n}\n\nfunction adjustMatcher(matcher) {\n if (matcher === 'self') {\n return matcher;\n } else if (isString(matcher)) {\n // Strings match exactly except for 2 wildcards - '*' and '**'.\n // '*' matches any character except those from the set ':/.?&'.\n // '**' matches any character (like .* in a RegExp).\n // More than 2 *'s raises an error as it's ill defined.\n if (matcher.indexOf('***') > -1) {\n throw $sceMinErr('iwcard',\n 'Illegal sequence *** in string matcher. String: {0}', matcher);\n }\n matcher = escapeForRegexp(matcher).\n replace(/\\\\\\*\\\\\\*/g, '.*').\n replace(/\\\\\\*/g, '[^:/.?&;]*');\n return new RegExp('^' + matcher + '$');\n } else if (isRegExp(matcher)) {\n // The only other type of matcher allowed is a Regexp.\n // Match entire URL / disallow partial matches.\n // Flags are reset (i.e. no global, ignoreCase or multiline)\n return new RegExp('^' + matcher.source + '$');\n } else {\n throw $sceMinErr('imatcher',\n 'Matchers may only be \"self\", string patterns or RegExp objects');\n }\n}\n\n\nfunction adjustMatchers(matchers) {\n var adjustedMatchers = [];\n if (isDefined(matchers)) {\n forEach(matchers, function(matcher) {\n adjustedMatchers.push(adjustMatcher(matcher));\n });\n }\n return adjustedMatchers;\n}\n\n\n/**\n * @ngdoc service\n * @name $sceDelegate\n * @kind function\n *\n * @description\n *\n * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict\n * Contextual Escaping (SCE)} services to AngularJS.\n *\n * For an overview of this service and the functionnality it provides in AngularJS, see the main\n * page for {@link ng.$sce SCE}. The current page is targeted for developers who need to alter how\n * SCE works in their application, which shouldn't be needed in most cases.\n *\n *
\n * AngularJS strongly relies on contextual escaping for the security of bindings: disabling or\n * modifying this might cause cross site scripting (XSS) vulnerabilities. For libraries owners,\n * changes to this service will also influence users, so be extra careful and document your changes.\n *
\n *\n * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of\n * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is\n * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to\n * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things\n * work because `$sce` delegates to `$sceDelegate` for these operations.\n *\n * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.\n *\n * The default instance of `$sceDelegate` should work out of the box with little pain. While you\n * can override it completely to change the behavior of `$sce`, the common case would\n * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting\n * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as\n * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist\n * $sceDelegateProvider.resourceUrlWhitelist} and {@link\n * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}\n */\n\n/**\n * @ngdoc provider\n * @name $sceDelegateProvider\n * @this\n *\n * @description\n *\n * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate\n * $sceDelegate service}, used as a delegate for {@link ng.$sce Strict Contextual Escaping (SCE)}.\n *\n * The `$sceDelegateProvider` allows one to get/set the whitelists and blacklists used to ensure\n * that the URLs used for sourcing AngularJS templates and other script-running URLs are safe (all\n * places that use the `$sce.RESOURCE_URL` context). See\n * {@link ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist}\n * and\n * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist},\n *\n * For the general details about this service in AngularJS, read the main page for {@link ng.$sce\n * Strict Contextual Escaping (SCE)}.\n *\n * **Example**: Consider the following case.
\n *\n * - your app is hosted at url `http://myapp.example.com/`\n * - but some of your templates are hosted on other domains you control such as\n * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.\n * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.\n *\n * Here is what a secure configuration for this scenario might look like:\n *\n * ```\n * angular.module('myApp', []).config(function($sceDelegateProvider) {\n * $sceDelegateProvider.resourceUrlWhitelist([\n * // Allow same origin resource loads.\n * 'self',\n * // Allow loading from our assets domain. Notice the difference between * and **.\n * 'http://srv*.assets.example.com/**'\n * ]);\n *\n * // The blacklist overrides the whitelist so the open redirect here is blocked.\n * $sceDelegateProvider.resourceUrlBlacklist([\n * 'http://myapp.example.com/clickThru**'\n * ]);\n * });\n * ```\n * Note that an empty whitelist will block every resource URL from being loaded, and will require\n * you to manually mark each one as trusted with `$sce.trustAsResourceUrl`. However, templates\n * requested by {@link ng.$templateRequest $templateRequest} that are present in\n * {@link ng.$templateCache $templateCache} will not go through this check. If you have a mechanism\n * to populate your templates in that cache at config time, then it is a good idea to remove 'self'\n * from that whitelist. This helps to mitigate the security impact of certain types of issues, like\n * for instance attacker-controlled `ng-includes`.\n */\n\nfunction $SceDelegateProvider() {\n this.SCE_CONTEXTS = SCE_CONTEXTS;\n\n // Resource URLs can also be trusted by policy.\n var resourceUrlWhitelist = ['self'],\n resourceUrlBlacklist = [];\n\n /**\n * @ngdoc method\n * @name $sceDelegateProvider#resourceUrlWhitelist\n * @kind function\n *\n * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value\n * provided. This must be an array or null. A snapshot of this array is used so further\n * changes to the array are ignored.\n * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items\n * allowed in this array.\n *\n * @return {Array} The currently set whitelist array.\n *\n * @description\n * Sets/Gets the whitelist of trusted resource URLs.\n *\n * The **default value** when no whitelist has been explicitly set is `['self']` allowing only\n * same origin resource requests.\n *\n *
\n * **Note:** the default whitelist of 'self' is not recommended if your app shares its origin\n * with other apps! It is a good idea to limit it to only your application's directory.\n *
\n */\n this.resourceUrlWhitelist = function(value) {\n if (arguments.length) {\n resourceUrlWhitelist = adjustMatchers(value);\n }\n return resourceUrlWhitelist;\n };\n\n /**\n * @ngdoc method\n * @name $sceDelegateProvider#resourceUrlBlacklist\n * @kind function\n *\n * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value\n * provided. This must be an array or null. A snapshot of this array is used so further\n * changes to the array are ignored.

\n * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items\n * allowed in this array.

\n * The typical usage for the blacklist is to **block\n * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as\n * these would otherwise be trusted but actually return content from the redirected domain.\n *

\n * Finally, **the blacklist overrides the whitelist** and has the final say.\n *\n * @return {Array} The currently set blacklist array.\n *\n * @description\n * Sets/Gets the blacklist of trusted resource URLs.\n *\n * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there\n * is no blacklist.)\n */\n\n this.resourceUrlBlacklist = function(value) {\n if (arguments.length) {\n resourceUrlBlacklist = adjustMatchers(value);\n }\n return resourceUrlBlacklist;\n };\n\n this.$get = ['$injector', '$$sanitizeUri', function($injector, $$sanitizeUri) {\n\n var htmlSanitizer = function htmlSanitizer(html) {\n throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');\n };\n\n if ($injector.has('$sanitize')) {\n htmlSanitizer = $injector.get('$sanitize');\n }\n\n\n function matchUrl(matcher, parsedUrl) {\n if (matcher === 'self') {\n return urlIsSameOrigin(parsedUrl) || urlIsSameOriginAsBaseUrl(parsedUrl);\n } else {\n // definitely a regex. See adjustMatchers()\n return !!matcher.exec(parsedUrl.href);\n }\n }\n\n function isResourceUrlAllowedByPolicy(url) {\n var parsedUrl = urlResolve(url.toString());\n var i, n, allowed = false;\n // Ensure that at least one item from the whitelist allows this url.\n for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {\n if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {\n allowed = true;\n break;\n }\n }\n if (allowed) {\n // Ensure that no item from the blacklist blocked this url.\n for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {\n if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {\n allowed = false;\n break;\n }\n }\n }\n return allowed;\n }\n\n function generateHolderType(Base) {\n var holderType = function TrustedValueHolderType(trustedValue) {\n this.$$unwrapTrustedValue = function() {\n return trustedValue;\n };\n };\n if (Base) {\n holderType.prototype = new Base();\n }\n holderType.prototype.valueOf = function sceValueOf() {\n return this.$$unwrapTrustedValue();\n };\n holderType.prototype.toString = function sceToString() {\n return this.$$unwrapTrustedValue().toString();\n };\n return holderType;\n }\n\n var trustedValueHolderBase = generateHolderType(),\n byType = {};\n\n byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);\n byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);\n byType[SCE_CONTEXTS.MEDIA_URL] = generateHolderType(trustedValueHolderBase);\n byType[SCE_CONTEXTS.URL] = generateHolderType(byType[SCE_CONTEXTS.MEDIA_URL]);\n byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);\n byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);\n\n /**\n * @ngdoc method\n * @name $sceDelegate#trustAs\n *\n * @description\n * Returns a trusted representation of the parameter for the specified context. This trusted\n * object will later on be used as-is, without any security check, by bindings or directives\n * that require this security context.\n * For instance, marking a string as trusted for the `$sce.HTML` context will entirely bypass\n * the potential `$sanitize` call in corresponding `$sce.HTML` bindings or directives, such as\n * `ng-bind-html`. Note that in most cases you won't need to call this function: if you have the\n * sanitizer loaded, passing the value itself will render all the HTML that does not pose a\n * security risk.\n *\n * See {@link ng.$sceDelegate#getTrusted getTrusted} for the function that will consume those\n * trusted values, and {@link ng.$sce $sce} for general documentation about strict contextual\n * escaping.\n *\n * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`,\n * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`.\n *\n * @param {*} value The value that should be considered trusted.\n * @return {*} A trusted representation of value, that can be used in the given context.\n */\n function trustAs(type, trustedValue) {\n var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);\n if (!Constructor) {\n throw $sceMinErr('icontext',\n 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',\n type, trustedValue);\n }\n if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {\n return trustedValue;\n }\n // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting\n // mutable objects, we ensure here that the value passed in is actually a string.\n if (typeof trustedValue !== 'string') {\n throw $sceMinErr('itype',\n 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',\n type);\n }\n return new Constructor(trustedValue);\n }\n\n /**\n * @ngdoc method\n * @name $sceDelegate#valueOf\n *\n * @description\n * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs\n * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link\n * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.\n *\n * If the passed parameter is not a value that had been returned by {@link\n * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, it must be returned as-is.\n *\n * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}\n * call or anything else.\n * @return {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs\n * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns\n * `value` unchanged.\n */\n function valueOf(maybeTrusted) {\n if (maybeTrusted instanceof trustedValueHolderBase) {\n return maybeTrusted.$$unwrapTrustedValue();\n } else {\n return maybeTrusted;\n }\n }\n\n /**\n * @ngdoc method\n * @name $sceDelegate#getTrusted\n *\n * @description\n * Given an object and a security context in which to assign it, returns a value that's safe to\n * use in this context, which was represented by the parameter. To do so, this function either\n * unwraps the safe type it has been given (for instance, a {@link ng.$sceDelegate#trustAs\n * `$sceDelegate.trustAs`} result), or it might try to sanitize the value given, depending on\n * the context and sanitizer availablility.\n *\n * The contexts that can be sanitized are $sce.MEDIA_URL, $sce.URL and $sce.HTML. The first two are available\n * by default, and the third one relies on the `$sanitize` service (which may be loaded through\n * the `ngSanitize` module). Furthermore, for $sce.RESOURCE_URL context, a plain string may be\n * accepted if the resource url policy defined by {@link ng.$sceDelegateProvider#resourceUrlWhitelist\n * `$sceDelegateProvider.resourceUrlWhitelist`} and {@link ng.$sceDelegateProvider#resourceUrlBlacklist\n * `$sceDelegateProvider.resourceUrlBlacklist`} accepts that resource.\n *\n * This function will throw if the safe type isn't appropriate for this context, or if the\n * value given cannot be accepted in the context (which might be caused by sanitization not\n * being available, or the value not being recognized as safe).\n *\n *

\n * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting\n * (XSS) vulnerability in your application.\n *
\n *\n * @param {string} type The context in which this value is to be used (such as `$sce.HTML`).\n * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs\n * `$sceDelegate.trustAs`} call, or anything else (which will not be considered trusted.)\n * @return {*} A version of the value that's safe to use in the given context, or throws an\n * exception if this is impossible.\n */\n function getTrusted(type, maybeTrusted) {\n if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {\n return maybeTrusted;\n }\n var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);\n // If maybeTrusted is a trusted class instance or subclass instance, then unwrap and return\n // as-is.\n if (constructor && maybeTrusted instanceof constructor) {\n return maybeTrusted.$$unwrapTrustedValue();\n }\n\n // If maybeTrusted is a trusted class instance but not of the correct trusted type\n // then unwrap it and allow it to pass through to the rest of the checks\n if (isFunction(maybeTrusted.$$unwrapTrustedValue)) {\n maybeTrusted = maybeTrusted.$$unwrapTrustedValue();\n }\n\n // If we get here, then we will either sanitize the value or throw an exception.\n if (type === SCE_CONTEXTS.MEDIA_URL || type === SCE_CONTEXTS.URL) {\n // we attempt to sanitize non-resource URLs\n return $$sanitizeUri(maybeTrusted.toString(), type === SCE_CONTEXTS.MEDIA_URL);\n } else if (type === SCE_CONTEXTS.RESOURCE_URL) {\n if (isResourceUrlAllowedByPolicy(maybeTrusted)) {\n return maybeTrusted;\n } else {\n throw $sceMinErr('insecurl',\n 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',\n maybeTrusted.toString());\n }\n } else if (type === SCE_CONTEXTS.HTML) {\n // htmlSanitizer throws its own error when no sanitizer is available.\n return htmlSanitizer(maybeTrusted);\n }\n // Default error when the $sce service has no way to make the input safe.\n throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');\n }\n\n return { trustAs: trustAs,\n getTrusted: getTrusted,\n valueOf: valueOf };\n }];\n}\n\n\n/**\n * @ngdoc provider\n * @name $sceProvider\n * @this\n *\n * @description\n *\n * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.\n * - enable/disable Strict Contextual Escaping (SCE) in a module\n * - override the default implementation with a custom delegate\n *\n * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.\n */\n\n/**\n * @ngdoc service\n * @name $sce\n * @kind function\n *\n * @description\n *\n * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.\n *\n * ## Strict Contextual Escaping\n *\n * Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render\n * trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and\n * (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.\n *\n * ### Overview\n *\n * To systematically block XSS security bugs, AngularJS treats all values as untrusted by default in\n * HTML or sensitive URL bindings. When binding untrusted values, AngularJS will automatically\n * run security checks on them (sanitizations, whitelists, depending on context), or throw when it\n * cannot guarantee the security of the result. That behavior depends strongly on contexts: HTML\n * can be sanitized, but template URLs cannot, for instance.\n *\n * To illustrate this, consider the `ng-bind-html` directive. It renders its value directly as HTML:\n * we call that the *context*. When given an untrusted input, AngularJS will attempt to sanitize it\n * before rendering if a sanitizer is available, and throw otherwise. To bypass sanitization and\n * render the input as-is, you will need to mark it as trusted for that context before attempting\n * to bind it.\n *\n * As of version 1.2, AngularJS ships with SCE enabled by default.\n *\n * ### In practice\n *\n * Here's an example of a binding in a privileged context:\n *\n * ```\n * \n *
\n * ```\n *\n * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE\n * disabled, this application allows the user to render arbitrary HTML into the DIV, which would\n * be an XSS security bug. In a more realistic example, one may be rendering user comments, blog\n * articles, etc. via bindings. (HTML is just one example of a context where rendering user\n * controlled input creates security vulnerabilities.)\n *\n * For the case of HTML, you might use a library, either on the client side, or on the server side,\n * to sanitize unsafe HTML before binding to the value and rendering it in the document.\n *\n * How would you ensure that every place that used these types of bindings was bound to a value that\n * was sanitized by your library (or returned as safe for rendering by your server?) How can you\n * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some\n * properties/fields and forgot to update the binding to the sanitized value?\n *\n * To be secure by default, AngularJS makes sure bindings go through that sanitization, or\n * any similar validation process, unless there's a good reason to trust the given value in this\n * context. That trust is formalized with a function call. This means that as a developer, you\n * can assume all untrusted bindings are safe. Then, to audit your code for binding security issues,\n * you just need to ensure the values you mark as trusted indeed are safe - because they were\n * received from your server, sanitized by your library, etc. You can organize your codebase to\n * help with this - perhaps allowing only the files in a specific directory to do this.\n * Ensuring that the internal API exposed by that code doesn't markup arbitrary values as safe then\n * becomes a more manageable task.\n *\n * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}\n * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to\n * build the trusted versions of your values.\n *\n * ### How does it work?\n *\n * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted\n * $sce.getTrusted(context, value)} rather than to the value directly. Think of this function as\n * a way to enforce the required security context in your data sink. Directives use {@link\n * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs\n * the {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. Also,\n * when binding without directives, AngularJS will understand the context of your bindings\n * automatically.\n *\n * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link\n * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly\n * simplified):\n *\n * ```\n * var ngBindHtmlDirective = ['$sce', function($sce) {\n * return function(scope, element, attr) {\n * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {\n * element.html(value || '');\n * });\n * };\n * }];\n * ```\n *\n * ### Impact on loading templates\n *\n * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as\n * `templateUrl`'s specified by {@link guide/directive directives}.\n *\n * By default, AngularJS only loads templates from the same domain and protocol as the application\n * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl\n * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or\n * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist\n * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.\n *\n * *Please note*:\n * The browser's\n * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)\n * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)\n * policy apply in addition to this and may further restrict whether the template is successfully\n * loaded. This means that without the right CORS policy, loading templates from a different domain\n * won't work on all browsers. Also, loading templates from `file://` URL does not work on some\n * browsers.\n *\n * ### This feels like too much overhead\n *\n * It's important to remember that SCE only applies to interpolation expressions.\n *\n * If your expressions are constant literals, they're automatically trusted and you don't need to\n * call `$sce.trustAs` on them (e.g.\n * `
implicitly trusted'\">
`) just works (remember to include the\n * `ngSanitize` module). The `$sceDelegate` will also use the `$sanitize` service if it is available\n * when binding untrusted values to `$sce.HTML` context.\n * AngularJS provides an implementation in `angular-sanitize.js`, and if you\n * wish to use it, you will also need to depend on the {@link ngSanitize `ngSanitize`} module in\n * your application.\n *\n * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load\n * templates in `ng-include` from your application's domain without having to even know about SCE.\n * It blocks loading templates from other domains or loading templates over http from an https\n * served document. You can change these by setting your own custom {@link\n * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link\n * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.\n *\n * This significantly reduces the overhead. It is far easier to pay the small overhead and have an\n * application that's secure and can be audited to verify that with much more ease than bolting\n * security onto an application later.\n *\n * \n * ### What trusted context types are supported?\n *\n * | Context | Notes |\n * |---------------------|----------------|\n * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |\n * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |\n * | `$sce.MEDIA_URL` | For URLs that are safe to render as media. Is automatically converted from string by sanitizing when needed. |\n * | `$sce.URL` | For URLs that are safe to follow as links. Is automatically converted from string by sanitizing when needed. Note that `$sce.URL` makes a stronger statement about the URL than `$sce.MEDIA_URL` does and therefore contexts requiring values trusted for `$sce.URL` can be used anywhere that values trusted for `$sce.MEDIA_URL` are required.|\n * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.)

Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` or `$sce.MEDIA_URL` do and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` or `$sce.MEDIA_URL` are required.

The {@link $sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider#resourceUrlWhitelist()} and {@link $sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider#resourceUrlBlacklist()} can be used to restrict trusted origins for `RESOURCE_URL` |\n * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |\n *\n *\n *
\n * Be aware that, before AngularJS 1.7.0, `a[href]` and `img[src]` used to sanitize their\n * interpolated values directly rather than rely upon {@link ng.$sce#getTrusted `$sce.getTrusted`}.\n *\n * **As of 1.7.0, this is no longer the case.**\n *\n * Now such interpolations are marked as requiring `$sce.URL` (for `a[href]`) or `$sce.MEDIA_URL`\n * (for `img[src]`), so that the sanitization happens (via `$sce.getTrusted...`) when the `$interpolate`\n * service evaluates the expressions.\n *
\n *\n * There are no CSS or JS context bindings in AngularJS currently, so their corresponding `$sce.trustAs`\n * functions aren't useful yet. This might evolve.\n *\n * ### Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} \n *\n * Each element in these arrays must be one of the following:\n *\n * - **'self'**\n * - The special **string**, `'self'`, can be used to match against all URLs of the **same\n * domain** as the application document using the **same protocol**.\n * - **String** (except the special value `'self'`)\n * - The string is matched against the full *normalized / absolute URL* of the resource\n * being tested (substring matches are not good enough.)\n * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters\n * match themselves.\n * - `*`: matches zero or more occurrences of any character other than one of the following 6\n * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use\n * in a whitelist.\n * - `**`: matches zero or more occurrences of *any* character. As such, it's not\n * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.\n * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might\n * not have been the intention.) Its usage at the very end of the path is ok. (e.g.\n * http://foo.example.com/templates/**).\n * - **RegExp** (*see caveat below*)\n * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax\n * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to\n * accidentally introduce a bug when one updates a complex expression (imho, all regexes should\n * have good test coverage). For instance, the use of `.` in the regex is correct only in a\n * small number of cases. A `.` character in the regex used when matching the scheme or a\n * subdomain could be matched against a `:` or literal `.` that was likely not intended. It\n * is highly recommended to use the string patterns and only fall back to regular expressions\n * as a last resort.\n * - The regular expression must be an instance of RegExp (i.e. not a string.) It is\n * matched against the **entire** *normalized / absolute URL* of the resource being tested\n * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags\n * present on the RegExp (such as multiline, global, ignoreCase) are ignored.\n * - If you are generating your JavaScript from some other templating engine (not\n * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),\n * remember to escape your regular expression (and be aware that you might need more than\n * one level of escaping depending on your templating engine and the way you interpolated\n * the value.) Do make use of your platform's escaping mechanism as it might be good\n * enough before coding your own. E.g. Ruby has\n * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)\n * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).\n * Javascript lacks a similar built in function for escaping. Take a look at Google\n * Closure library's [goog.string.regExpEscape(s)](\n * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).\n *\n * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.\n *\n * ### Show me an example using SCE.\n *\n * \n * \n *
\n *

\n * User comments
\n * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when\n * $sanitize is available. If $sanitize isn't available, this results in an error instead of an\n * exploit.\n *
\n *
\n * {{userComment.name}}:\n * \n *
\n *
\n *
\n *
\n *
\n *\n * \n * angular.module('mySceApp', ['ngSanitize'])\n * .controller('AppController', ['$http', '$templateCache', '$sce',\n * function AppController($http, $templateCache, $sce) {\n * var self = this;\n * $http.get('test_data.json', {cache: $templateCache}).then(function(response) {\n * self.userComments = response.data;\n * });\n * self.explicitlyTrustedHtml = $sce.trustAsHtml(\n * 'Hover over this text.');\n * }]);\n * \n *\n * \n * [\n * { \"name\": \"Alice\",\n * \"htmlComment\":\n * \"Is anyone reading this?\"\n * },\n * { \"name\": \"Bob\",\n * \"htmlComment\": \"Yes! Am I the only other one?\"\n * }\n * ]\n * \n *\n * \n * describe('SCE doc demo', function() {\n * it('should sanitize untrusted values', function() {\n * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML'))\n * .toBe('Is anyone reading this?');\n * });\n *\n * it('should NOT sanitize explicitly trusted values', function() {\n * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe(\n * 'Hover over this text.');\n * });\n * });\n * \n *
\n *\n *\n *\n * ## Can I disable SCE completely?\n *\n * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits\n * for little coding overhead. It will be much harder to take an SCE disabled application and\n * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE\n * for cases where you have a lot of existing code that was written before SCE was introduced and\n * you're migrating them a module at a time. Also do note that this is an app-wide setting, so if\n * you are writing a library, you will cause security bugs applications using it.\n *\n * That said, here's how you can completely disable SCE:\n *\n * ```\n * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {\n * // Completely disable SCE. For demonstration purposes only!\n * // Do not use in new projects or libraries.\n * $sceProvider.enabled(false);\n * });\n * ```\n *\n */\n\nfunction $SceProvider() {\n var enabled = true;\n\n /**\n * @ngdoc method\n * @name $sceProvider#enabled\n * @kind function\n *\n * @param {boolean=} value If provided, then enables/disables SCE application-wide.\n * @return {boolean} True if SCE is enabled, false otherwise.\n *\n * @description\n * Enables/disables SCE and returns the current value.\n */\n this.enabled = function(value) {\n if (arguments.length) {\n enabled = !!value;\n }\n return enabled;\n };\n\n\n /* Design notes on the default implementation for SCE.\n *\n * The API contract for the SCE delegate\n * -------------------------------------\n * The SCE delegate object must provide the following 3 methods:\n *\n * - trustAs(contextEnum, value)\n * This method is used to tell the SCE service that the provided value is OK to use in the\n * contexts specified by contextEnum. It must return an object that will be accepted by\n * getTrusted() for a compatible contextEnum and return this value.\n *\n * - valueOf(value)\n * For values that were not produced by trustAs(), return them as is. For values that were\n * produced by trustAs(), return the corresponding input value to trustAs. Basically, if\n * trustAs is wrapping the given values into some type, this operation unwraps it when given\n * such a value.\n *\n * - getTrusted(contextEnum, value)\n * This function should return the value that is safe to use in the context specified by\n * contextEnum or throw and exception otherwise.\n *\n * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be\n * opaque or wrapped in some holder object. That happens to be an implementation detail. For\n * instance, an implementation could maintain a registry of all trusted objects by context. In\n * such a case, trustAs() would return the same object that was passed in. getTrusted() would\n * return the same object passed in if it was found in the registry under a compatible context or\n * throw an exception otherwise. An implementation might only wrap values some of the time based\n * on some criteria. getTrusted() might return a value and not throw an exception for special\n * constants or objects even if not wrapped. All such implementations fulfill this contract.\n *\n *\n * A note on the inheritance model for SCE contexts\n * ------------------------------------------------\n * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This\n * is purely an implementation details.\n *\n * The contract is simply this:\n *\n * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)\n * will also succeed.\n *\n * Inheritance happens to capture this in a natural way. In some future, we may not use\n * inheritance anymore. That is OK because no code outside of sce.js and sceSpecs.js would need to\n * be aware of this detail.\n */\n\n this.$get = ['$parse', '$sceDelegate', function(\n $parse, $sceDelegate) {\n // Support: IE 9-11 only\n // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow\n // the \"expression(javascript expression)\" syntax which is insecure.\n if (enabled && msie < 8) {\n throw $sceMinErr('iequirks',\n 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +\n 'mode. You can fix this by adding the text to the top of your HTML ' +\n 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');\n }\n\n var sce = shallowCopy(SCE_CONTEXTS);\n\n /**\n * @ngdoc method\n * @name $sce#isEnabled\n * @kind function\n *\n * @return {Boolean} True if SCE is enabled, false otherwise. If you want to set the value, you\n * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.\n *\n * @description\n * Returns a boolean indicating if SCE is enabled.\n */\n sce.isEnabled = function() {\n return enabled;\n };\n sce.trustAs = $sceDelegate.trustAs;\n sce.getTrusted = $sceDelegate.getTrusted;\n sce.valueOf = $sceDelegate.valueOf;\n\n if (!enabled) {\n sce.trustAs = sce.getTrusted = function(type, value) { return value; };\n sce.valueOf = identity;\n }\n\n /**\n * @ngdoc method\n * @name $sce#parseAs\n *\n * @description\n * Converts AngularJS {@link guide/expression expression} into a function. This is like {@link\n * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it\n * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,\n * *result*)}\n *\n * @param {string} type The SCE context in which this result will be used.\n * @param {string} expression String expression to compile.\n * @return {function(context, locals)} A function which represents the compiled expression:\n *\n * * `context` – `{object}` – an object against which any expressions embedded in the\n * strings are evaluated against (typically a scope object).\n * * `locals` – `{object=}` – local variables context object, useful for overriding values\n * in `context`.\n */\n sce.parseAs = function sceParseAs(type, expr) {\n var parsed = $parse(expr);\n if (parsed.literal && parsed.constant) {\n return parsed;\n } else {\n return $parse(expr, function(value) {\n return sce.getTrusted(type, value);\n });\n }\n };\n\n /**\n * @ngdoc method\n * @name $sce#trustAs\n *\n * @description\n * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, returns a\n * wrapped object that represents your value, and the trust you have in its safety for the given\n * context. AngularJS can then use that value as-is in bindings of the specified secure context.\n * This is used in bindings for `ng-bind-html`, `ng-include`, and most `src` attribute\n * interpolations. See {@link ng.$sce $sce} for strict contextual escaping.\n *\n * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`,\n * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`.\n *\n * @param {*} value The value that that should be considered trusted.\n * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`\n * in the context you specified.\n */\n\n /**\n * @ngdoc method\n * @name $sce#trustAsHtml\n *\n * @description\n * Shorthand method. `$sce.trustAsHtml(value)` →\n * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}\n *\n * @param {*} value The value to mark as trusted for `$sce.HTML` context.\n * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`\n * in `$sce.HTML` context (like `ng-bind-html`).\n */\n\n /**\n * @ngdoc method\n * @name $sce#trustAsCss\n *\n * @description\n * Shorthand method. `$sce.trustAsCss(value)` →\n * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.CSS, value)`}\n *\n * @param {*} value The value to mark as trusted for `$sce.CSS` context.\n * @return {*} A wrapped version of value that can be used as a trusted variant\n * of your `value` in `$sce.CSS` context. This context is currently unused, so there are\n * almost no reasons to use this function so far.\n */\n\n /**\n * @ngdoc method\n * @name $sce#trustAsUrl\n *\n * @description\n * Shorthand method. `$sce.trustAsUrl(value)` →\n * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}\n *\n * @param {*} value The value to mark as trusted for `$sce.URL` context.\n * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`\n * in `$sce.URL` context. That context is currently unused, so there are almost no reasons\n * to use this function so far.\n */\n\n /**\n * @ngdoc method\n * @name $sce#trustAsResourceUrl\n *\n * @description\n * Shorthand method. `$sce.trustAsResourceUrl(value)` →\n * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}\n *\n * @param {*} value The value to mark as trusted for `$sce.RESOURCE_URL` context.\n * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`\n * in `$sce.RESOURCE_URL` context (template URLs in `ng-include`, most `src` attribute\n * bindings, ...)\n */\n\n /**\n * @ngdoc method\n * @name $sce#trustAsJs\n *\n * @description\n * Shorthand method. `$sce.trustAsJs(value)` →\n * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}\n *\n * @param {*} value The value to mark as trusted for `$sce.JS` context.\n * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`\n * in `$sce.JS` context. That context is currently unused, so there are almost no reasons to\n * use this function so far.\n */\n\n /**\n * @ngdoc method\n * @name $sce#getTrusted\n *\n * @description\n * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,\n * takes any input, and either returns a value that's safe to use in the specified context,\n * or throws an exception. This function is aware of trusted values created by the `trustAs`\n * function and its shorthands, and when contexts are appropriate, returns the unwrapped value\n * as-is. Finally, this function can also throw when there is no way to turn `maybeTrusted` in a\n * safe value (e.g., no sanitization is available or possible.)\n *\n * @param {string} type The context in which this value is to be used.\n * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs\n * `$sce.trustAs`} call, or anything else (which will not be considered trusted.)\n * @return {*} A version of the value that's safe to use in the given context, or throws an\n * exception if this is impossible.\n */\n\n /**\n * @ngdoc method\n * @name $sce#getTrustedHtml\n *\n * @description\n * Shorthand method. `$sce.getTrustedHtml(value)` →\n * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}\n *\n * @param {*} value The value to pass to `$sce.getTrusted`.\n * @return {*} The return value of `$sce.getTrusted($sce.HTML, value)`\n */\n\n /**\n * @ngdoc method\n * @name $sce#getTrustedCss\n *\n * @description\n * Shorthand method. `$sce.getTrustedCss(value)` →\n * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}\n *\n * @param {*} value The value to pass to `$sce.getTrusted`.\n * @return {*} The return value of `$sce.getTrusted($sce.CSS, value)`\n */\n\n /**\n * @ngdoc method\n * @name $sce#getTrustedUrl\n *\n * @description\n * Shorthand method. `$sce.getTrustedUrl(value)` →\n * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}\n *\n * @param {*} value The value to pass to `$sce.getTrusted`.\n * @return {*} The return value of `$sce.getTrusted($sce.URL, value)`\n */\n\n /**\n * @ngdoc method\n * @name $sce#getTrustedResourceUrl\n *\n * @description\n * Shorthand method. `$sce.getTrustedResourceUrl(value)` →\n * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}\n *\n * @param {*} value The value to pass to `$sceDelegate.getTrusted`.\n * @return {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`\n */\n\n /**\n * @ngdoc method\n * @name $sce#getTrustedJs\n *\n * @description\n * Shorthand method. `$sce.getTrustedJs(value)` →\n * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}\n *\n * @param {*} value The value to pass to `$sce.getTrusted`.\n * @return {*} The return value of `$sce.getTrusted($sce.JS, value)`\n */\n\n /**\n * @ngdoc method\n * @name $sce#parseAsHtml\n *\n * @description\n * Shorthand method. `$sce.parseAsHtml(expression string)` →\n * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}\n *\n * @param {string} expression String expression to compile.\n * @return {function(context, locals)} A function which represents the compiled expression:\n *\n * * `context` – `{object}` – an object against which any expressions embedded in the\n * strings are evaluated against (typically a scope object).\n * * `locals` – `{object=}` – local variables context object, useful for overriding values\n * in `context`.\n */\n\n /**\n * @ngdoc method\n * @name $sce#parseAsCss\n *\n * @description\n * Shorthand method. `$sce.parseAsCss(value)` →\n * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}\n *\n * @param {string} expression String expression to compile.\n * @return {function(context, locals)} A function which represents the compiled expression:\n *\n * * `context` – `{object}` – an object against which any expressions embedded in the\n * strings are evaluated against (typically a scope object).\n * * `locals` – `{object=}` – local variables context object, useful for overriding values\n * in `context`.\n */\n\n /**\n * @ngdoc method\n * @name $sce#parseAsUrl\n *\n * @description\n * Shorthand method. `$sce.parseAsUrl(value)` →\n * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}\n *\n * @param {string} expression String expression to compile.\n * @return {function(context, locals)} A function which represents the compiled expression:\n *\n * * `context` – `{object}` – an object against which any expressions embedded in the\n * strings are evaluated against (typically a scope object).\n * * `locals` – `{object=}` – local variables context object, useful for overriding values\n * in `context`.\n */\n\n /**\n * @ngdoc method\n * @name $sce#parseAsResourceUrl\n *\n * @description\n * Shorthand method. `$sce.parseAsResourceUrl(value)` →\n * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}\n *\n * @param {string} expression String expression to compile.\n * @return {function(context, locals)} A function which represents the compiled expression:\n *\n * * `context` – `{object}` – an object against which any expressions embedded in the\n * strings are evaluated against (typically a scope object).\n * * `locals` – `{object=}` – local variables context object, useful for overriding values\n * in `context`.\n */\n\n /**\n * @ngdoc method\n * @name $sce#parseAsJs\n *\n * @description\n * Shorthand method. `$sce.parseAsJs(value)` →\n * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}\n *\n * @param {string} expression String expression to compile.\n * @return {function(context, locals)} A function which represents the compiled expression:\n *\n * * `context` – `{object}` – an object against which any expressions embedded in the\n * strings are evaluated against (typically a scope object).\n * * `locals` – `{object=}` – local variables context object, useful for overriding values\n * in `context`.\n */\n\n // Shorthand delegations.\n var parse = sce.parseAs,\n getTrusted = sce.getTrusted,\n trustAs = sce.trustAs;\n\n forEach(SCE_CONTEXTS, function(enumValue, name) {\n var lName = lowercase(name);\n sce[snakeToCamel('parse_as_' + lName)] = function(expr) {\n return parse(enumValue, expr);\n };\n sce[snakeToCamel('get_trusted_' + lName)] = function(value) {\n return getTrusted(enumValue, value);\n };\n sce[snakeToCamel('trust_as_' + lName)] = function(value) {\n return trustAs(enumValue, value);\n };\n });\n\n return sce;\n }];\n}\n\n/* exported $SnifferProvider */\n\n/**\n * !!! This is an undocumented \"private\" service !!!\n *\n * @name $sniffer\n * @requires $window\n * @requires $document\n * @this\n *\n * @property {boolean} history Does the browser support html5 history api ?\n * @property {boolean} transitions Does the browser support CSS transition events ?\n * @property {boolean} animations Does the browser support CSS animation events ?\n *\n * @description\n * This is very simple implementation of testing browser's features.\n */\nfunction $SnifferProvider() {\n this.$get = ['$window', '$document', function($window, $document) {\n var eventSupport = {},\n // Chrome Packaged Apps are not allowed to access `history.pushState`.\n // If not sandboxed, they can be detected by the presence of `chrome.app.runtime`\n // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by\n // the presence of an extension runtime ID and the absence of other Chrome runtime APIs\n // (see https://developer.chrome.com/apps/manifest/sandbox).\n // (NW.js apps have access to Chrome APIs, but do support `history`.)\n isNw = $window.nw && $window.nw.process,\n isChromePackagedApp =\n !isNw &&\n $window.chrome &&\n ($window.chrome.app && $window.chrome.app.runtime ||\n !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id),\n hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,\n android =\n toInt((/android (\\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),\n boxee = /Boxee/i.test(($window.navigator || {}).userAgent),\n document = $document[0] || {},\n bodyStyle = document.body && document.body.style,\n transitions = false,\n animations = false;\n\n if (bodyStyle) {\n // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x\n // Mentioned browsers need a -webkit- prefix for transitions & animations.\n transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle);\n animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle);\n }\n\n\n return {\n // Android has history.pushState, but it does not update location correctly\n // so let's not use the history API at all.\n // http://code.google.com/p/android/issues/detail?id=17471\n // https://github.com/angular/angular.js/issues/904\n\n // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has\n // so let's not use the history API also\n // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined\n history: !!(hasHistoryPushState && !(android < 4) && !boxee),\n hasEvent: function(event) {\n // Support: IE 9-11 only\n // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have\n // it. In particular the event is not fired when backspace or delete key are pressed or\n // when cut operation is performed.\n // IE10+ implements 'input' event but it erroneously fires under various situations,\n // e.g. when placeholder changes, or a form is focused.\n if (event === 'input' && msie) return false;\n\n if (isUndefined(eventSupport[event])) {\n var divElm = document.createElement('div');\n eventSupport[event] = 'on' + event in divElm;\n }\n\n return eventSupport[event];\n },\n csp: csp(),\n transitions: transitions,\n animations: animations,\n android: android\n };\n }];\n}\n\n/**\n * ! This is a private undocumented service !\n *\n * @name $$taskTrackerFactory\n * @description\n * A function to create `TaskTracker` instances.\n *\n * A `TaskTracker` can keep track of pending tasks (grouped by type) and can notify interested\n * parties when all pending tasks (or tasks of a specific type) have been completed.\n *\n * @param {$log} log - A logger instance (such as `$log`). Used to log error during callback\n * execution.\n *\n * @this\n */\nfunction $$TaskTrackerFactoryProvider() {\n this.$get = valueFn(function(log) { return new TaskTracker(log); });\n}\n\nfunction TaskTracker(log) {\n var self = this;\n var taskCounts = {};\n var taskCallbacks = [];\n\n var ALL_TASKS_TYPE = self.ALL_TASKS_TYPE = '$$all$$';\n var DEFAULT_TASK_TYPE = self.DEFAULT_TASK_TYPE = '$$default$$';\n\n /**\n * Execute the specified function and decrement the appropriate `taskCounts` counter.\n * If the counter reaches 0, all corresponding `taskCallbacks` are executed.\n *\n * @param {Function} fn - The function to execute.\n * @param {string=} [taskType=DEFAULT_TASK_TYPE] - The type of task that is being completed.\n */\n self.completeTask = completeTask;\n\n /**\n * Increase the task count for the specified task type (or the default task type if non is\n * specified).\n *\n * @param {string=} [taskType=DEFAULT_TASK_TYPE] - The type of task whose count will be increased.\n */\n self.incTaskCount = incTaskCount;\n\n /**\n * Execute the specified callback when all pending tasks have been completed.\n *\n * If there are no pending tasks, the callback is executed immediately. You can optionally limit\n * the tasks that will be waited for to a specific type, by passing a `taskType`.\n *\n * @param {function} callback - The function to call when there are no pending tasks.\n * @param {string=} [taskType=ALL_TASKS_TYPE] - The type of tasks that will be waited for.\n */\n self.notifyWhenNoPendingTasks = notifyWhenNoPendingTasks;\n\n function completeTask(fn, taskType) {\n taskType = taskType || DEFAULT_TASK_TYPE;\n\n try {\n fn();\n } finally {\n decTaskCount(taskType);\n\n var countForType = taskCounts[taskType];\n var countForAll = taskCounts[ALL_TASKS_TYPE];\n\n // If at least one of the queues (`ALL_TASKS_TYPE` or `taskType`) is empty, run callbacks.\n if (!countForAll || !countForType) {\n var getNextCallback = !countForAll ? getLastCallback : getLastCallbackForType;\n var nextCb;\n\n while ((nextCb = getNextCallback(taskType))) {\n try {\n nextCb();\n } catch (e) {\n log.error(e);\n }\n }\n }\n }\n }\n\n function decTaskCount(taskType) {\n taskType = taskType || DEFAULT_TASK_TYPE;\n if (taskCounts[taskType]) {\n taskCounts[taskType]--;\n taskCounts[ALL_TASKS_TYPE]--;\n }\n }\n\n function getLastCallback() {\n var cbInfo = taskCallbacks.pop();\n return cbInfo && cbInfo.cb;\n }\n\n function getLastCallbackForType(taskType) {\n for (var i = taskCallbacks.length - 1; i >= 0; --i) {\n var cbInfo = taskCallbacks[i];\n if (cbInfo.type === taskType) {\n taskCallbacks.splice(i, 1);\n return cbInfo.cb;\n }\n }\n }\n\n function incTaskCount(taskType) {\n taskType = taskType || DEFAULT_TASK_TYPE;\n taskCounts[taskType] = (taskCounts[taskType] || 0) + 1;\n taskCounts[ALL_TASKS_TYPE] = (taskCounts[ALL_TASKS_TYPE] || 0) + 1;\n }\n\n function notifyWhenNoPendingTasks(callback, taskType) {\n taskType = taskType || ALL_TASKS_TYPE;\n if (!taskCounts[taskType]) {\n callback();\n } else {\n taskCallbacks.push({type: taskType, cb: callback});\n }\n }\n}\n\nvar $templateRequestMinErr = minErr('$templateRequest');\n\n/**\n * @ngdoc provider\n * @name $templateRequestProvider\n * @this\n *\n * @description\n * Used to configure the options passed to the {@link $http} service when making a template request.\n *\n * For example, it can be used for specifying the \"Accept\" header that is sent to the server, when\n * requesting a template.\n */\nfunction $TemplateRequestProvider() {\n\n var httpOptions;\n\n /**\n * @ngdoc method\n * @name $templateRequestProvider#httpOptions\n * @description\n * The options to be passed to the {@link $http} service when making the request.\n * You can use this to override options such as the \"Accept\" header for template requests.\n *\n * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the\n * options if not overridden here.\n *\n * @param {string=} value new value for the {@link $http} options.\n * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.\n */\n this.httpOptions = function(val) {\n if (val) {\n httpOptions = val;\n return this;\n }\n return httpOptions;\n };\n\n /**\n * @ngdoc service\n * @name $templateRequest\n *\n * @description\n * The `$templateRequest` service runs security checks then downloads the provided template using\n * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request\n * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the\n * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the\n * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted\n * when `tpl` is of type string and `$templateCache` has the matching entry.\n *\n * If you want to pass custom options to the `$http` service, such as setting the Accept header you\n * can configure this via {@link $templateRequestProvider#httpOptions}.\n *\n * `$templateRequest` is used internally by {@link $compile}, {@link ngRoute.$route}, and directives such\n * as {@link ngInclude} to download and cache templates.\n *\n * 3rd party modules should use `$templateRequest` if their services or directives are loading\n * templates.\n *\n * @param {string|TrustedResourceUrl} tpl The HTTP request template URL\n * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty\n *\n * @return {Promise} a promise for the HTTP response data of the given URL.\n *\n * @property {number} totalPendingRequests total amount of pending template requests being downloaded.\n */\n this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce',\n function($exceptionHandler, $templateCache, $http, $q, $sce) {\n\n function handleRequestFn(tpl, ignoreRequestError) {\n handleRequestFn.totalPendingRequests++;\n\n // We consider the template cache holds only trusted templates, so\n // there's no need to go through whitelisting again for keys that already\n // are included in there. This also makes AngularJS accept any script\n // directive, no matter its name. However, we still need to unwrap trusted\n // types.\n if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {\n tpl = $sce.getTrustedResourceUrl(tpl);\n }\n\n var transformResponse = $http.defaults && $http.defaults.transformResponse;\n\n if (isArray(transformResponse)) {\n transformResponse = transformResponse.filter(function(transformer) {\n return transformer !== defaultHttpResponseTransform;\n });\n } else if (transformResponse === defaultHttpResponseTransform) {\n transformResponse = null;\n }\n\n return $http.get(tpl, extend({\n cache: $templateCache,\n transformResponse: transformResponse\n }, httpOptions))\n .finally(function() {\n handleRequestFn.totalPendingRequests--;\n })\n .then(function(response) {\n return $templateCache.put(tpl, response.data);\n }, handleError);\n\n function handleError(resp) {\n if (!ignoreRequestError) {\n resp = $templateRequestMinErr('tpload',\n 'Failed to load template: {0} (HTTP status: {1} {2})',\n tpl, resp.status, resp.statusText);\n\n $exceptionHandler(resp);\n }\n\n return $q.reject(resp);\n }\n }\n\n handleRequestFn.totalPendingRequests = 0;\n\n return handleRequestFn;\n }\n ];\n}\n\n/** @this */\nfunction $$TestabilityProvider() {\n this.$get = ['$rootScope', '$browser', '$location',\n function($rootScope, $browser, $location) {\n\n /**\n * @name $testability\n *\n * @description\n * The private $$testability service provides a collection of methods for use when debugging\n * or by automated test and debugging tools.\n */\n var testability = {};\n\n /**\n * @name $$testability#findBindings\n *\n * @description\n * Returns an array of elements that are bound (via ng-bind or {{}})\n * to expressions matching the input.\n *\n * @param {Element} element The element root to search from.\n * @param {string} expression The binding expression to match.\n * @param {boolean} opt_exactMatch If true, only returns exact matches\n * for the expression. Filters and whitespace are ignored.\n */\n testability.findBindings = function(element, expression, opt_exactMatch) {\n var bindings = element.getElementsByClassName('ng-binding');\n var matches = [];\n forEach(bindings, function(binding) {\n var dataBinding = angular.element(binding).data('$binding');\n if (dataBinding) {\n forEach(dataBinding, function(bindingName) {\n if (opt_exactMatch) {\n var matcher = new RegExp('(^|\\\\s)' + escapeForRegexp(expression) + '(\\\\s|\\\\||$)');\n if (matcher.test(bindingName)) {\n matches.push(binding);\n }\n } else {\n if (bindingName.indexOf(expression) !== -1) {\n matches.push(binding);\n }\n }\n });\n }\n });\n return matches;\n };\n\n /**\n * @name $$testability#findModels\n *\n * @description\n * Returns an array of elements that are two-way found via ng-model to\n * expressions matching the input.\n *\n * @param {Element} element The element root to search from.\n * @param {string} expression The model expression to match.\n * @param {boolean} opt_exactMatch If true, only returns exact matches\n * for the expression.\n */\n testability.findModels = function(element, expression, opt_exactMatch) {\n var prefixes = ['ng-', 'data-ng-', 'ng\\\\:'];\n for (var p = 0; p < prefixes.length; ++p) {\n var attributeEquals = opt_exactMatch ? '=' : '*=';\n var selector = '[' + prefixes[p] + 'model' + attributeEquals + '\"' + expression + '\"]';\n var elements = element.querySelectorAll(selector);\n if (elements.length) {\n return elements;\n }\n }\n };\n\n /**\n * @name $$testability#getLocation\n *\n * @description\n * Shortcut for getting the location in a browser agnostic way. Returns\n * the path, search, and hash. (e.g. /path?a=b#hash)\n */\n testability.getLocation = function() {\n return $location.url();\n };\n\n /**\n * @name $$testability#setLocation\n *\n * @description\n * Shortcut for navigating to a location without doing a full page reload.\n *\n * @param {string} url The location url (path, search and hash,\n * e.g. /path?a=b#hash) to go to.\n */\n testability.setLocation = function(url) {\n if (url !== $location.url()) {\n $location.url(url);\n $rootScope.$digest();\n }\n };\n\n /**\n * @name $$testability#whenStable\n *\n * @description\n * Calls the callback when all pending tasks are completed.\n *\n * Types of tasks waited for include:\n * - Pending timeouts (via {@link $timeout}).\n * - Pending HTTP requests (via {@link $http}).\n * - In-progress route transitions (via {@link $route}).\n * - Pending tasks scheduled via {@link $rootScope#$applyAsync}.\n * - Pending tasks scheduled via {@link $rootScope#$evalAsync}.\n * These include tasks scheduled via `$evalAsync()` indirectly (such as {@link $q} promises).\n *\n * @param {function} callback\n */\n testability.whenStable = function(callback) {\n $browser.notifyWhenNoOutstandingRequests(callback);\n };\n\n return testability;\n }];\n}\n\nvar $timeoutMinErr = minErr('$timeout');\n\n/** @this */\nfunction $TimeoutProvider() {\n this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',\n function($rootScope, $browser, $q, $$q, $exceptionHandler) {\n\n var deferreds = {};\n\n\n /**\n * @ngdoc service\n * @name $timeout\n *\n * @description\n * AngularJS's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch\n * block and delegates any exceptions to\n * {@link ng.$exceptionHandler $exceptionHandler} service.\n *\n * The return value of calling `$timeout` is a promise, which will be resolved when\n * the delay has passed and the timeout function, if provided, is executed.\n *\n * To cancel a timeout request, call `$timeout.cancel(promise)`.\n *\n * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to\n * synchronously flush the queue of deferred functions.\n *\n * If you only want a promise that will be resolved after some specified delay\n * then you can call `$timeout` without the `fn` function.\n *\n * @param {function()=} fn A function, whose execution should be delayed.\n * @param {number=} [delay=0] Delay in milliseconds.\n * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\n * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\n * @param {...*=} Pass additional parameters to the executed function.\n * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise\n * will be resolved with the return value of the `fn` function.\n *\n */\n function timeout(fn, delay, invokeApply) {\n if (!isFunction(fn)) {\n invokeApply = delay;\n delay = fn;\n fn = noop;\n }\n\n var args = sliceArgs(arguments, 3),\n skipApply = (isDefined(invokeApply) && !invokeApply),\n deferred = (skipApply ? $$q : $q).defer(),\n promise = deferred.promise,\n timeoutId;\n\n timeoutId = $browser.defer(function() {\n try {\n deferred.resolve(fn.apply(null, args));\n } catch (e) {\n deferred.reject(e);\n $exceptionHandler(e);\n } finally {\n delete deferreds[promise.$$timeoutId];\n }\n\n if (!skipApply) $rootScope.$apply();\n }, delay, '$timeout');\n\n promise.$$timeoutId = timeoutId;\n deferreds[timeoutId] = deferred;\n\n return promise;\n }\n\n\n /**\n * @ngdoc method\n * @name $timeout#cancel\n *\n * @description\n * Cancels a task associated with the `promise`. As a result of this, the promise will be\n * resolved with a rejection.\n *\n * @param {Promise=} promise Promise returned by the `$timeout` function.\n * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully\n * canceled.\n */\n timeout.cancel = function(promise) {\n if (!promise) return false;\n\n if (!promise.hasOwnProperty('$$timeoutId')) {\n throw $timeoutMinErr('badprom',\n '`$timeout.cancel()` called with a promise that was not generated by `$timeout()`.');\n }\n\n if (!deferreds.hasOwnProperty(promise.$$timeoutId)) return false;\n\n var id = promise.$$timeoutId;\n var deferred = deferreds[id];\n\n // Timeout cancels should not report an unhandled promise.\n markQExceptionHandled(deferred.promise);\n deferred.reject('canceled');\n delete deferreds[id];\n\n return $browser.defer.cancel(id);\n };\n\n return timeout;\n }];\n}\n\n// NOTE: The usage of window and document instead of $window and $document here is\n// deliberate. This service depends on the specific behavior of anchor nodes created by the\n// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and\n// cause us to break tests. In addition, when the browser resolves a URL for XHR, it\n// doesn't know about mocked locations and resolves URLs to the real document - which is\n// exactly the behavior needed here. There is little value is mocking these out for this\n// service.\nvar urlParsingNode = window.document.createElement('a');\nvar originUrl = urlResolve(window.location.href);\nvar baseUrlParsingNode;\n\nurlParsingNode.href = 'http://[::1]';\n\n// Support: IE 9-11 only, Edge 16-17 only (fixed in 18 Preview)\n// IE/Edge don't wrap IPv6 addresses' hostnames in square brackets\n// when parsed out of an anchor element.\nvar ipv6InBrackets = urlParsingNode.hostname === '[::1]';\n\n/**\n *\n * Implementation Notes for non-IE browsers\n * ----------------------------------------\n * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,\n * results both in the normalizing and parsing of the URL. Normalizing means that a relative\n * URL will be resolved into an absolute URL in the context of the application document.\n * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related\n * properties are all populated to reflect the normalized URL. This approach has wide\n * compatibility - Safari 1+, Mozilla 1+ etc. See\n * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html\n *\n * Implementation Notes for IE\n * ---------------------------\n * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other\n * browsers. However, the parsed components will not be set if the URL assigned did not specify\n * them. (e.g. if you assign a.href = \"foo\", then a.protocol, a.host, etc. will be empty.) We\n * work around that by performing the parsing in a 2nd step by taking a previously normalized\n * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the\n * properties such as protocol, hostname, port, etc.\n *\n * References:\n * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement\n * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html\n * http://url.spec.whatwg.org/#urlutils\n * https://github.com/angular/angular.js/pull/2902\n * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/\n *\n * @kind function\n * @param {string|object} url The URL to be parsed. If `url` is not a string, it will be returned\n * unchanged.\n * @description Normalizes and parses a URL.\n * @returns {object} Returns the normalized URL as a dictionary.\n *\n * | member name | Description |\n * |---------------|------------------------------------------------------------------------|\n * | href | A normalized version of the provided URL if it was not an absolute URL |\n * | protocol | The protocol without the trailing colon |\n * | host | The host and port (if the port is non-default) of the normalizedUrl |\n * | search | The search params, minus the question mark |\n * | hash | The hash string, minus the hash symbol |\n * | hostname | The hostname |\n * | port | The port, without \":\" |\n * | pathname | The pathname, beginning with \"/\" |\n *\n */\nfunction urlResolve(url) {\n if (!isString(url)) return url;\n\n var href = url;\n\n // Support: IE 9-11 only\n if (msie) {\n // Normalize before parse. Refer Implementation Notes on why this is\n // done in two steps on IE.\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n var hostname = urlParsingNode.hostname;\n\n if (!ipv6InBrackets && hostname.indexOf(':') > -1) {\n hostname = '[' + hostname + ']';\n }\n\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/')\n ? urlParsingNode.pathname\n : '/' + urlParsingNode.pathname\n };\n}\n\n/**\n * Parse a request URL and determine whether this is a same-origin request as the application\n * document.\n *\n * @param {string|object} requestUrl The url of the request as a string that will be resolved\n * or a parsed URL object.\n * @returns {boolean} Whether the request is for the same origin as the application document.\n */\nfunction urlIsSameOrigin(requestUrl) {\n return urlsAreSameOrigin(requestUrl, originUrl);\n}\n\n/**\n * Parse a request URL and determine whether it is same-origin as the current document base URL.\n *\n * Note: The base URL is usually the same as the document location (`location.href`) but can\n * be overriden by using the `` tag.\n *\n * @param {string|object} requestUrl The url of the request as a string that will be resolved\n * or a parsed URL object.\n * @returns {boolean} Whether the URL is same-origin as the document base URL.\n */\nfunction urlIsSameOriginAsBaseUrl(requestUrl) {\n return urlsAreSameOrigin(requestUrl, getBaseUrl());\n}\n\n/**\n * Create a function that can check a URL's origin against a list of allowed/whitelisted origins.\n * The current location's origin is implicitly trusted.\n *\n * @param {string[]} whitelistedOriginUrls - A list of URLs (strings), whose origins are trusted.\n *\n * @returns {Function} - A function that receives a URL (string or parsed URL object) and returns\n * whether it is of an allowed origin.\n */\nfunction urlIsAllowedOriginFactory(whitelistedOriginUrls) {\n var parsedAllowedOriginUrls = [originUrl].concat(whitelistedOriginUrls.map(urlResolve));\n\n /**\n * Check whether the specified URL (string or parsed URL object) has an origin that is allowed\n * based on a list of whitelisted-origin URLs. The current location's origin is implicitly\n * trusted.\n *\n * @param {string|Object} requestUrl - The URL to be checked (provided as a string that will be\n * resolved or a parsed URL object).\n *\n * @returns {boolean} - Whether the specified URL is of an allowed origin.\n */\n return function urlIsAllowedOrigin(requestUrl) {\n var parsedUrl = urlResolve(requestUrl);\n return parsedAllowedOriginUrls.some(urlsAreSameOrigin.bind(null, parsedUrl));\n };\n}\n\n/**\n * Determine if two URLs share the same origin.\n *\n * @param {string|Object} url1 - First URL to compare as a string or a normalized URL in the form of\n * a dictionary object returned by `urlResolve()`.\n * @param {string|object} url2 - Second URL to compare as a string or a normalized URL in the form\n * of a dictionary object returned by `urlResolve()`.\n *\n * @returns {boolean} - True if both URLs have the same origin, and false otherwise.\n */\nfunction urlsAreSameOrigin(url1, url2) {\n url1 = urlResolve(url1);\n url2 = urlResolve(url2);\n\n return (url1.protocol === url2.protocol &&\n url1.host === url2.host);\n}\n\n/**\n * Returns the current document base URL.\n * @returns {string}\n */\nfunction getBaseUrl() {\n if (window.document.baseURI) {\n return window.document.baseURI;\n }\n\n // `document.baseURI` is available everywhere except IE\n if (!baseUrlParsingNode) {\n baseUrlParsingNode = window.document.createElement('a');\n baseUrlParsingNode.href = '.';\n\n // Work-around for IE bug described in Implementation Notes. The fix in `urlResolve()` is not\n // suitable here because we need to track changes to the base URL.\n baseUrlParsingNode = baseUrlParsingNode.cloneNode(false);\n }\n return baseUrlParsingNode.href;\n}\n\n/**\n * @ngdoc service\n * @name $window\n * @this\n *\n * @description\n * A reference to the browser's `window` object. While `window`\n * is globally available in JavaScript, it causes testability problems, because\n * it is a global variable. In AngularJS we always refer to it through the\n * `$window` service, so it may be overridden, removed or mocked for testing.\n *\n * Expressions, like the one defined for the `ngClick` directive in the example\n * below, are evaluated with respect to the current scope. Therefore, there is\n * no risk of inadvertently coding in a dependency on a global value in such an\n * expression.\n *\n * @example\n \n \n \n
\n \n \n
\n
\n \n it('should display the greeting in the input box', function() {\n element(by.model('greeting')).sendKeys('Hello, E2E Tests');\n // If we click the button it will block the test runner\n // element(':button').click();\n });\n \n
\n */\nfunction $WindowProvider() {\n this.$get = valueFn(window);\n}\n\n/**\n * @name $$cookieReader\n * @requires $document\n *\n * @description\n * This is a private service for reading cookies used by $http and ngCookies\n *\n * @return {Object} a key/value map of the current cookies\n */\nfunction $$CookieReader($document) {\n var rawDocument = $document[0] || {};\n var lastCookies = {};\n var lastCookieString = '';\n\n function safeGetCookie(rawDocument) {\n try {\n return rawDocument.cookie || '';\n } catch (e) {\n return '';\n }\n }\n\n function safeDecodeURIComponent(str) {\n try {\n return decodeURIComponent(str);\n } catch (e) {\n return str;\n }\n }\n\n return function() {\n var cookieArray, cookie, i, index, name;\n var currentCookieString = safeGetCookie(rawDocument);\n\n if (currentCookieString !== lastCookieString) {\n lastCookieString = currentCookieString;\n cookieArray = lastCookieString.split('; ');\n lastCookies = {};\n\n for (i = 0; i < cookieArray.length; i++) {\n cookie = cookieArray[i];\n index = cookie.indexOf('=');\n if (index > 0) { //ignore nameless cookies\n name = safeDecodeURIComponent(cookie.substring(0, index));\n // the first value that is seen for a cookie is the most\n // specific one. values for the same cookie name that\n // follow are for less specific paths.\n if (isUndefined(lastCookies[name])) {\n lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));\n }\n }\n }\n }\n return lastCookies;\n };\n}\n\n$$CookieReader.$inject = ['$document'];\n\n/** @this */\nfunction $$CookieReaderProvider() {\n this.$get = $$CookieReader;\n}\n\n/* global currencyFilter: true,\n dateFilter: true,\n filterFilter: true,\n jsonFilter: true,\n limitToFilter: true,\n lowercaseFilter: true,\n numberFilter: true,\n orderByFilter: true,\n uppercaseFilter: true,\n */\n\n/**\n * @ngdoc provider\n * @name $filterProvider\n * @description\n *\n * Filters are just functions which transform input to an output. However filters need to be\n * Dependency Injected. To achieve this a filter definition consists of a factory function which is\n * annotated with dependencies and is responsible for creating a filter function.\n *\n *
\n * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`.\n * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace\n * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores\n * (`myapp_subsection_filterx`).\n *
\n *\n * ```js\n * // Filter registration\n * function MyModule($provide, $filterProvider) {\n * // create a service to demonstrate injection (not always needed)\n * $provide.value('greet', function(name){\n * return 'Hello ' + name + '!';\n * });\n *\n * // register a filter factory which uses the\n * // greet service to demonstrate DI.\n * $filterProvider.register('greet', function(greet){\n * // return the filter function which uses the greet service\n * // to generate salutation\n * return function(text) {\n * // filters need to be forgiving so check input validity\n * return text && greet(text) || text;\n * };\n * });\n * }\n * ```\n *\n * The filter function is registered with the `$injector` under the filter name suffix with\n * `Filter`.\n *\n * ```js\n * it('should be the same instance', inject(\n * function($filterProvider) {\n * $filterProvider.register('reverse', function(){\n * return ...;\n * });\n * },\n * function($filter, reverseFilter) {\n * expect($filter('reverse')).toBe(reverseFilter);\n * });\n * ```\n *\n *\n * For more information about how AngularJS filters work, and how to create your own filters, see\n * {@link guide/filter Filters} in the AngularJS Developer Guide.\n */\n\n/**\n * @ngdoc service\n * @name $filter\n * @kind function\n * @description\n * Filters are used for formatting data displayed to the user.\n *\n * They can be used in view templates, controllers or services. AngularJS comes\n * with a collection of [built-in filters](api/ng/filter), but it is easy to\n * define your own as well.\n *\n * The general syntax in templates is as follows:\n *\n * ```html\n * {{ expression [| filter_name[:parameter_value] ... ] }}\n * ```\n *\n * @param {String} name Name of the filter function to retrieve\n * @return {Function} the filter function\n * @example\n \n \n
\n

{{ originalText }}

\n

{{ filteredText }}

\n
\n
\n\n \n angular.module('filterExample', [])\n .controller('MainCtrl', function($scope, $filter) {\n $scope.originalText = 'hello';\n $scope.filteredText = $filter('uppercase')($scope.originalText);\n });\n \n
\n */\n$FilterProvider.$inject = ['$provide'];\n/** @this */\nfunction $FilterProvider($provide) {\n var suffix = 'Filter';\n\n /**\n * @ngdoc method\n * @name $filterProvider#register\n * @param {string|Object} name Name of the filter function, or an object map of filters where\n * the keys are the filter names and the values are the filter factories.\n *\n *
\n * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`.\n * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace\n * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores\n * (`myapp_subsection_filterx`).\n *
\n * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.\n * @returns {Object} Registered filter instance, or if a map of filters was provided then a map\n * of the registered filter instances.\n */\n function register(name, factory) {\n if (isObject(name)) {\n var filters = {};\n forEach(name, function(filter, key) {\n filters[key] = register(key, filter);\n });\n return filters;\n } else {\n return $provide.factory(name + suffix, factory);\n }\n }\n this.register = register;\n\n this.$get = ['$injector', function($injector) {\n return function(name) {\n return $injector.get(name + suffix);\n };\n }];\n\n ////////////////////////////////////////\n\n /* global\n currencyFilter: false,\n dateFilter: false,\n filterFilter: false,\n jsonFilter: false,\n limitToFilter: false,\n lowercaseFilter: false,\n numberFilter: false,\n orderByFilter: false,\n uppercaseFilter: false\n */\n\n register('currency', currencyFilter);\n register('date', dateFilter);\n register('filter', filterFilter);\n register('json', jsonFilter);\n register('limitTo', limitToFilter);\n register('lowercase', lowercaseFilter);\n register('number', numberFilter);\n register('orderBy', orderByFilter);\n register('uppercase', uppercaseFilter);\n}\n\n/**\n * @ngdoc filter\n * @name filter\n * @kind function\n *\n * @description\n * Selects a subset of items from `array` and returns it as a new array.\n *\n * @param {Array} array The source array.\n *
\n * **Note**: If the array contains objects that reference themselves, filtering is not possible.\n *
\n * @param {string|Object|function()} expression The predicate to be used for selecting items from\n * `array`.\n *\n * Can be one of:\n *\n * - `string`: The string is used for matching against the contents of the `array`. All strings or\n * objects with string properties in `array` that match this string will be returned. This also\n * applies to nested object properties.\n * The predicate can be negated by prefixing the string with `!`.\n *\n * - `Object`: A pattern object can be used to filter specific properties on objects contained\n * by `array`. For example `{name:\"M\", phone:\"1\"}` predicate will return an array of items\n * which have property `name` containing \"M\" and property `phone` containing \"1\". A special\n * property name (`$` by default) can be used (e.g. as in `{$: \"text\"}`) to accept a match\n * against any property of the object or its nested object properties. That's equivalent to the\n * simple substring match with a `string` as described above. The special property name can be\n * overwritten, using the `anyPropertyKey` parameter.\n * The predicate can be negated by prefixing the string with `!`.\n * For example `{name: \"!M\"}` predicate will return an array of items which have property `name`\n * not containing \"M\".\n *\n * Note that a named property will match properties on the same level only, while the special\n * `$` property will match properties on the same level or deeper. E.g. an array item like\n * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but\n * **will** be matched by `{$: 'John'}`.\n *\n * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.\n * The function is called for each element of the array, with the element, its index, and\n * the entire array itself as arguments.\n *\n * The final result is an array of those elements that the predicate returned true for.\n *\n * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in\n * determining if values retrieved using `expression` (when it is not a function) should be\n * considered a match based on the expected value (from the filter expression) and actual\n * value (from the object in the array).\n *\n * Can be one of:\n *\n * - `function(actual, expected)`:\n * The function will be given the object value and the predicate value to compare and\n * should return true if both values should be considered equal.\n *\n * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.\n * This is essentially strict comparison of expected and actual.\n *\n * - `false`: A short hand for a function which will look for a substring match in a case\n * insensitive way. Primitive values are converted to strings. Objects are not compared against\n * primitives, unless they have a custom `toString` method (e.g. `Date` objects).\n *\n *\n * Defaults to `false`.\n *\n * @param {string} [anyPropertyKey] The special property name that matches against any property.\n * By default `$`.\n *\n * @example\n \n \n
\n\n \n
\n \n \n \n \n \n
NamePhone
{{friend.name}}{{friend.phone}}
\n
\n
\n
\n
\n
\n \n \n \n \n \n \n
NamePhone
{{friendObj.name}}{{friendObj.phone}}
\n \n \n var expectFriendNames = function(expectedNames, key) {\n element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {\n arr.forEach(function(wd, i) {\n expect(wd.getText()).toMatch(expectedNames[i]);\n });\n });\n };\n\n it('should search across all fields when filtering with a string', function() {\n var searchText = element(by.model('searchText'));\n searchText.clear();\n searchText.sendKeys('m');\n expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');\n\n searchText.clear();\n searchText.sendKeys('76');\n expectFriendNames(['John', 'Julie'], 'friend');\n });\n\n it('should search in specific fields when filtering with a predicate object', function() {\n var searchAny = element(by.model('search.$'));\n searchAny.clear();\n searchAny.sendKeys('i');\n expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');\n });\n it('should use a equal comparison when comparator is true', function() {\n var searchName = element(by.model('search.name'));\n var strict = element(by.model('strict'));\n searchName.clear();\n searchName.sendKeys('Julie');\n strict.click();\n expectFriendNames(['Julie'], 'friendObj');\n });\n \n \n */\n\nfunction filterFilter() {\n return function(array, expression, comparator, anyPropertyKey) {\n if (!isArrayLike(array)) {\n if (array == null) {\n return array;\n } else {\n throw minErr('filter')('notarray', 'Expected array but received: {0}', array);\n }\n }\n\n anyPropertyKey = anyPropertyKey || '$';\n var expressionType = getTypeForFilter(expression);\n var predicateFn;\n var matchAgainstAnyProp;\n\n switch (expressionType) {\n case 'function':\n predicateFn = expression;\n break;\n case 'boolean':\n case 'null':\n case 'number':\n case 'string':\n matchAgainstAnyProp = true;\n // falls through\n case 'object':\n predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);\n break;\n default:\n return array;\n }\n\n return Array.prototype.filter.call(array, predicateFn);\n };\n}\n\n// Helper functions for `filterFilter`\nfunction createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {\n var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);\n var predicateFn;\n\n if (comparator === true) {\n comparator = equals;\n } else if (!isFunction(comparator)) {\n comparator = function(actual, expected) {\n if (isUndefined(actual)) {\n // No substring matching against `undefined`\n return false;\n }\n if ((actual === null) || (expected === null)) {\n // No substring matching against `null`; only match against `null`\n return actual === expected;\n }\n if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {\n // Should not compare primitives against objects, unless they have custom `toString` method\n return false;\n }\n\n actual = lowercase('' + actual);\n expected = lowercase('' + expected);\n return actual.indexOf(expected) !== -1;\n };\n }\n\n predicateFn = function(item) {\n if (shouldMatchPrimitives && !isObject(item)) {\n return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);\n }\n return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);\n };\n\n return predicateFn;\n}\n\nfunction deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {\n var actualType = getTypeForFilter(actual);\n var expectedType = getTypeForFilter(expected);\n\n if ((expectedType === 'string') && (expected.charAt(0) === '!')) {\n return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp);\n } else if (isArray(actual)) {\n // In case `actual` is an array, consider it a match\n // if ANY of it's items matches `expected`\n return actual.some(function(item) {\n return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp);\n });\n }\n\n switch (actualType) {\n case 'object':\n var key;\n if (matchAgainstAnyProp) {\n for (key in actual) {\n // Under certain, rare, circumstances, key may not be a string and `charAt` will be undefined\n // See: https://github.com/angular/angular.js/issues/15644\n if (key.charAt && (key.charAt(0) !== '$') &&\n deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {\n return true;\n }\n }\n return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false);\n } else if (expectedType === 'object') {\n for (key in expected) {\n var expectedVal = expected[key];\n if (isFunction(expectedVal) || isUndefined(expectedVal)) {\n continue;\n }\n\n var matchAnyProperty = key === anyPropertyKey;\n var actualVal = matchAnyProperty ? actual : actual[key];\n if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {\n return false;\n }\n }\n return true;\n } else {\n return comparator(actual, expected);\n }\n case 'function':\n return false;\n default:\n return comparator(actual, expected);\n }\n}\n\n// Used for easily differentiating between `null` and actual `object`\nfunction getTypeForFilter(val) {\n return (val === null) ? 'null' : typeof val;\n}\n\nvar MAX_DIGITS = 22;\nvar DECIMAL_SEP = '.';\nvar ZERO_CHAR = '0';\n\n/**\n * @ngdoc filter\n * @name currency\n * @kind function\n *\n * @description\n * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default\n * symbol for current locale is used.\n *\n * @param {number} amount Input to filter.\n * @param {string=} symbol Currency symbol or identifier to be displayed.\n * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale\n * @returns {string} Formatted number.\n *\n *\n * @example\n \n \n \n
\n
\n default currency symbol ($): {{amount | currency}}
\n custom currency identifier (USD$): {{amount | currency:\"USD$\"}}
\n no fractions (0): {{amount | currency:\"USD$\":0}}\n
\n
\n \n it('should init with 1234.56', function() {\n expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');\n expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');\n expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');\n });\n it('should update', function() {\n if (browser.params.browser === 'safari') {\n // Safari does not understand the minus key. See\n // https://github.com/angular/protractor/issues/481\n return;\n }\n element(by.model('amount')).clear();\n element(by.model('amount')).sendKeys('-1234');\n expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');\n expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');\n expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');\n });\n \n
\n */\ncurrencyFilter.$inject = ['$locale'];\nfunction currencyFilter($locale) {\n var formats = $locale.NUMBER_FORMATS;\n return function(amount, currencySymbol, fractionSize) {\n if (isUndefined(currencySymbol)) {\n currencySymbol = formats.CURRENCY_SYM;\n }\n\n if (isUndefined(fractionSize)) {\n fractionSize = formats.PATTERNS[1].maxFrac;\n }\n\n // If the currency symbol is empty, trim whitespace around the symbol\n var currencySymbolRe = !currencySymbol ? /\\s*\\u00A4\\s*/g : /\\u00A4/g;\n\n // if null or undefined pass it through\n return (amount == null)\n ? amount\n : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).\n replace(currencySymbolRe, currencySymbol);\n };\n}\n\n/**\n * @ngdoc filter\n * @name number\n * @kind function\n *\n * @description\n * Formats a number as text.\n *\n * If the input is null or undefined, it will just be returned.\n * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.\n * If the input is not a number an empty string is returned.\n *\n *\n * @param {number|string} number Number to format.\n * @param {(number|string)=} fractionSize Number of decimal places to round the number to.\n * If this is not provided then the fraction size is computed from the current locale's number\n * formatting pattern. In the case of the default locale, it will be 3.\n * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current\n * locale (e.g., in the en_US locale it will have \".\" as the decimal separator and\n * include \",\" group separators after each third digit).\n *\n * @example\n \n \n \n
\n
\n Default formatting: {{val | number}}
\n No fractions: {{val | number:0}}
\n Negative number: {{-val | number:4}}\n
\n
\n \n it('should format numbers', function() {\n expect(element(by.id('number-default')).getText()).toBe('1,234.568');\n expect(element(by.binding('val | number:0')).getText()).toBe('1,235');\n expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');\n });\n\n it('should update', function() {\n element(by.model('val')).clear();\n element(by.model('val')).sendKeys('3374.333');\n expect(element(by.id('number-default')).getText()).toBe('3,374.333');\n expect(element(by.binding('val | number:0')).getText()).toBe('3,374');\n expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');\n });\n \n
\n */\nnumberFilter.$inject = ['$locale'];\nfunction numberFilter($locale) {\n var formats = $locale.NUMBER_FORMATS;\n return function(number, fractionSize) {\n\n // if null or undefined pass it through\n return (number == null)\n ? number\n : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,\n fractionSize);\n };\n}\n\n/**\n * Parse a number (as a string) into three components that can be used\n * for formatting the number.\n *\n * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)\n *\n * @param {string} numStr The number to parse\n * @return {object} An object describing this number, containing the following keys:\n * - d : an array of digits containing leading zeros as necessary\n * - i : the number of the digits in `d` that are to the left of the decimal point\n * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`\n *\n */\nfunction parse(numStr) {\n var exponent = 0, digits, numberOfIntegerDigits;\n var i, j, zeros;\n\n // Decimal point?\n if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {\n numStr = numStr.replace(DECIMAL_SEP, '');\n }\n\n // Exponential form?\n if ((i = numStr.search(/e/i)) > 0) {\n // Work out the exponent.\n if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;\n numberOfIntegerDigits += +numStr.slice(i + 1);\n numStr = numStr.substring(0, i);\n } else if (numberOfIntegerDigits < 0) {\n // There was no decimal point or exponent so it is an integer.\n numberOfIntegerDigits = numStr.length;\n }\n\n // Count the number of leading zeros.\n for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ }\n\n if (i === (zeros = numStr.length)) {\n // The digits are all zero.\n digits = [0];\n numberOfIntegerDigits = 1;\n } else {\n // Count the number of trailing zeros\n zeros--;\n while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;\n\n // Trailing zeros are insignificant so ignore them\n numberOfIntegerDigits -= i;\n digits = [];\n // Convert string to array of digits without leading/trailing zeros.\n for (j = 0; i <= zeros; i++, j++) {\n digits[j] = +numStr.charAt(i);\n }\n }\n\n // If the number overflows the maximum allowed digits then use an exponent.\n if (numberOfIntegerDigits > MAX_DIGITS) {\n digits = digits.splice(0, MAX_DIGITS - 1);\n exponent = numberOfIntegerDigits - 1;\n numberOfIntegerDigits = 1;\n }\n\n return { d: digits, e: exponent, i: numberOfIntegerDigits };\n}\n\n/**\n * Round the parsed number to the specified number of decimal places\n * This function changed the parsedNumber in-place\n */\nfunction roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {\n var digits = parsedNumber.d;\n var fractionLen = digits.length - parsedNumber.i;\n\n // determine fractionSize if it is not specified; `+fractionSize` converts it to a number\n fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;\n\n // The index of the digit to where rounding is to occur\n var roundAt = fractionSize + parsedNumber.i;\n var digit = digits[roundAt];\n\n if (roundAt > 0) {\n // Drop fractional digits beyond `roundAt`\n digits.splice(Math.max(parsedNumber.i, roundAt));\n\n // Set non-fractional digits beyond `roundAt` to 0\n for (var j = roundAt; j < digits.length; j++) {\n digits[j] = 0;\n }\n } else {\n // We rounded to zero so reset the parsedNumber\n fractionLen = Math.max(0, fractionLen);\n parsedNumber.i = 1;\n digits.length = Math.max(1, roundAt = fractionSize + 1);\n digits[0] = 0;\n for (var i = 1; i < roundAt; i++) digits[i] = 0;\n }\n\n if (digit >= 5) {\n if (roundAt - 1 < 0) {\n for (var k = 0; k > roundAt; k--) {\n digits.unshift(0);\n parsedNumber.i++;\n }\n digits.unshift(1);\n parsedNumber.i++;\n } else {\n digits[roundAt - 1]++;\n }\n }\n\n // Pad out with zeros to get the required fraction length\n for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);\n\n\n // Do any carrying, e.g. a digit was rounded up to 10\n var carry = digits.reduceRight(function(carry, d, i, digits) {\n d = d + carry;\n digits[i] = d % 10;\n return Math.floor(d / 10);\n }, 0);\n if (carry) {\n digits.unshift(carry);\n parsedNumber.i++;\n }\n}\n\n/**\n * Format a number into a string\n * @param {number} number The number to format\n * @param {{\n * minFrac, // the minimum number of digits required in the fraction part of the number\n * maxFrac, // the maximum number of digits required in the fraction part of the number\n * gSize, // number of digits in each group of separated digits\n * lgSize, // number of digits in the last group of digits before the decimal separator\n * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))\n * posPre, // the string to go in front of a positive number\n * negSuf, // the string to go after a negative number (e.g. `)`)\n * posSuf // the string to go after a positive number\n * }} pattern\n * @param {string} groupSep The string to separate groups of number (e.g. `,`)\n * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)\n * @param {[type]} fractionSize The size of the fractional part of the number\n * @return {string} The number formatted as a string\n */\nfunction formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {\n\n if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';\n\n var isInfinity = !isFinite(number);\n var isZero = false;\n var numStr = Math.abs(number) + '',\n formattedText = '',\n parsedNumber;\n\n if (isInfinity) {\n formattedText = '\\u221e';\n } else {\n parsedNumber = parse(numStr);\n\n roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);\n\n var digits = parsedNumber.d;\n var integerLen = parsedNumber.i;\n var exponent = parsedNumber.e;\n var decimals = [];\n isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);\n\n // pad zeros for small numbers\n while (integerLen < 0) {\n digits.unshift(0);\n integerLen++;\n }\n\n // extract decimals digits\n if (integerLen > 0) {\n decimals = digits.splice(integerLen, digits.length);\n } else {\n decimals = digits;\n digits = [0];\n }\n\n // format the integer digits with grouping separators\n var groups = [];\n if (digits.length >= pattern.lgSize) {\n groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));\n }\n while (digits.length > pattern.gSize) {\n groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));\n }\n if (digits.length) {\n groups.unshift(digits.join(''));\n }\n formattedText = groups.join(groupSep);\n\n // append the decimal digits\n if (decimals.length) {\n formattedText += decimalSep + decimals.join('');\n }\n\n if (exponent) {\n formattedText += 'e+' + exponent;\n }\n }\n if (number < 0 && !isZero) {\n return pattern.negPre + formattedText + pattern.negSuf;\n } else {\n return pattern.posPre + formattedText + pattern.posSuf;\n }\n}\n\nfunction padNumber(num, digits, trim, negWrap) {\n var neg = '';\n if (num < 0 || (negWrap && num <= 0)) {\n if (negWrap) {\n num = -num + 1;\n } else {\n num = -num;\n neg = '-';\n }\n }\n num = '' + num;\n while (num.length < digits) num = ZERO_CHAR + num;\n if (trim) {\n num = num.substr(num.length - digits);\n }\n return neg + num;\n}\n\n\nfunction dateGetter(name, size, offset, trim, negWrap) {\n offset = offset || 0;\n return function(date) {\n var value = date['get' + name]();\n if (offset > 0 || value > -offset) {\n value += offset;\n }\n if (value === 0 && offset === -12) value = 12;\n return padNumber(value, size, trim, negWrap);\n };\n}\n\nfunction dateStrGetter(name, shortForm, standAlone) {\n return function(date, formats) {\n var value = date['get' + name]();\n var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');\n var get = uppercase(propPrefix + name);\n\n return formats[get][value];\n };\n}\n\nfunction timeZoneGetter(date, formats, offset) {\n var zone = -1 * offset;\n var paddedZone = (zone >= 0) ? '+' : '';\n\n paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +\n padNumber(Math.abs(zone % 60), 2);\n\n return paddedZone;\n}\n\nfunction getFirstThursdayOfYear(year) {\n // 0 = index of January\n var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();\n // 4 = index of Thursday (+1 to account for 1st = 5)\n // 11 = index of *next* Thursday (+1 account for 1st = 12)\n return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);\n}\n\nfunction getThursdayThisWeek(datetime) {\n return new Date(datetime.getFullYear(), datetime.getMonth(),\n // 4 = index of Thursday\n datetime.getDate() + (4 - datetime.getDay()));\n}\n\nfunction weekGetter(size) {\n return function(date) {\n var firstThurs = getFirstThursdayOfYear(date.getFullYear()),\n thisThurs = getThursdayThisWeek(date);\n\n var diff = +thisThurs - +firstThurs,\n result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week\n\n return padNumber(result, size);\n };\n}\n\nfunction ampmGetter(date, formats) {\n return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];\n}\n\nfunction eraGetter(date, formats) {\n return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];\n}\n\nfunction longEraGetter(date, formats) {\n return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];\n}\n\nvar DATE_FORMATS = {\n yyyy: dateGetter('FullYear', 4, 0, false, true),\n yy: dateGetter('FullYear', 2, 0, true, true),\n y: dateGetter('FullYear', 1, 0, false, true),\n MMMM: dateStrGetter('Month'),\n MMM: dateStrGetter('Month', true),\n MM: dateGetter('Month', 2, 1),\n M: dateGetter('Month', 1, 1),\n LLLL: dateStrGetter('Month', false, true),\n dd: dateGetter('Date', 2),\n d: dateGetter('Date', 1),\n HH: dateGetter('Hours', 2),\n H: dateGetter('Hours', 1),\n hh: dateGetter('Hours', 2, -12),\n h: dateGetter('Hours', 1, -12),\n mm: dateGetter('Minutes', 2),\n m: dateGetter('Minutes', 1),\n ss: dateGetter('Seconds', 2),\n s: dateGetter('Seconds', 1),\n // while ISO 8601 requires fractions to be prefixed with `.` or `,`\n // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions\n sss: dateGetter('Milliseconds', 3),\n EEEE: dateStrGetter('Day'),\n EEE: dateStrGetter('Day', true),\n a: ampmGetter,\n Z: timeZoneGetter,\n ww: weekGetter(2),\n w: weekGetter(1),\n G: eraGetter,\n GG: eraGetter,\n GGG: eraGetter,\n GGGG: longEraGetter\n};\n\nvar DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))([\\s\\S]*)/,\n NUMBER_STRING = /^-?\\d+$/;\n\n/**\n * @ngdoc filter\n * @name date\n * @kind function\n *\n * @description\n * Formats `date` to a string based on the requested `format`.\n *\n * `format` string can be composed of the following elements:\n *\n * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)\n * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)\n * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)\n * * `'MMMM'`: Month in year (January-December)\n * * `'MMM'`: Month in year (Jan-Dec)\n * * `'MM'`: Month in year, padded (01-12)\n * * `'M'`: Month in year (1-12)\n * * `'LLLL'`: Stand-alone month in year (January-December)\n * * `'dd'`: Day in month, padded (01-31)\n * * `'d'`: Day in month (1-31)\n * * `'EEEE'`: Day in Week,(Sunday-Saturday)\n * * `'EEE'`: Day in Week, (Sun-Sat)\n * * `'HH'`: Hour in day, padded (00-23)\n * * `'H'`: Hour in day (0-23)\n * * `'hh'`: Hour in AM/PM, padded (01-12)\n * * `'h'`: Hour in AM/PM, (1-12)\n * * `'mm'`: Minute in hour, padded (00-59)\n * * `'m'`: Minute in hour (0-59)\n * * `'ss'`: Second in minute, padded (00-59)\n * * `'s'`: Second in minute (0-59)\n * * `'sss'`: Millisecond in second, padded (000-999)\n * * `'a'`: AM/PM marker\n * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)\n * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year\n * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year\n * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')\n * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')\n *\n * `format` string can also be one of the following predefined\n * {@link guide/i18n localizable formats}:\n *\n * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale\n * (e.g. Sep 3, 2010 12:05:08 PM)\n * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)\n * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale\n * (e.g. Friday, September 3, 2010)\n * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)\n * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)\n * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)\n * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)\n * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)\n *\n * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.\n * `\"h 'in the morning'\"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence\n * (e.g. `\"h 'o''clock'\"`).\n *\n * Any other characters in the `format` string will be output as-is.\n *\n * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or\n * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its\n * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is\n * specified in the string input, the time is considered to be in the local timezone.\n * @param {string=} format Formatting rules (see Description). If not specified,\n * `mediumDate` is used.\n * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the\n * continental US time zone abbreviations, but for general use, use a time zone offset, for\n * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)\n * If not specified, the timezone of the browser will be used.\n * @returns {string} Formatted string or the input if input is not recognized as date/millis.\n *\n * @example\n \n \n {{1288323623006 | date:'medium'}}:\n {{1288323623006 | date:'medium'}}
\n {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}:\n {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}
\n {{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}:\n {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}
\n {{1288323623006 | date:\"MM/dd/yyyy 'at' h:mma\"}}:\n {{'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"}}
\n
\n \n it('should format date', function() {\n expect(element(by.binding(\"1288323623006 | date:'medium'\")).getText()).\n toMatch(/Oct 2\\d, 2010 \\d{1,2}:\\d{2}:\\d{2} (AM|PM)/);\n expect(element(by.binding(\"1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'\")).getText()).\n toMatch(/2010-10-2\\d \\d{2}:\\d{2}:\\d{2} (-|\\+)?\\d{4}/);\n expect(element(by.binding(\"'1288323623006' | date:'MM/dd/yyyy @ h:mma'\")).getText()).\n toMatch(/10\\/2\\d\\/2010 @ \\d{1,2}:\\d{2}(AM|PM)/);\n expect(element(by.binding(\"'1288323623006' | date:\\\"MM/dd/yyyy 'at' h:mma\\\"\")).getText()).\n toMatch(/10\\/2\\d\\/2010 at \\d{1,2}:\\d{2}(AM|PM)/);\n });\n \n
\n */\ndateFilter.$inject = ['$locale'];\nfunction dateFilter($locale) {\n\n\n var R_ISO8601_STR = /^(\\d{4})-?(\\d\\d)-?(\\d\\d)(?:T(\\d\\d)(?::?(\\d\\d)(?::?(\\d\\d)(?:\\.(\\d+))?)?)?(Z|([+-])(\\d\\d):?(\\d\\d))?)?$/;\n // 1 2 3 4 5 6 7 8 9 10 11\n function jsonStringToDate(string) {\n var match;\n if ((match = string.match(R_ISO8601_STR))) {\n var date = new Date(0),\n tzHour = 0,\n tzMin = 0,\n dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,\n timeSetter = match[8] ? date.setUTCHours : date.setHours;\n\n if (match[9]) {\n tzHour = toInt(match[9] + match[10]);\n tzMin = toInt(match[9] + match[11]);\n }\n dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));\n var h = toInt(match[4] || 0) - tzHour;\n var m = toInt(match[5] || 0) - tzMin;\n var s = toInt(match[6] || 0);\n var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);\n timeSetter.call(date, h, m, s, ms);\n return date;\n }\n return string;\n }\n\n\n return function(date, format, timezone) {\n var text = '',\n parts = [],\n fn, match;\n\n format = format || 'mediumDate';\n format = $locale.DATETIME_FORMATS[format] || format;\n if (isString(date)) {\n date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);\n }\n\n if (isNumber(date)) {\n date = new Date(date);\n }\n\n if (!isDate(date) || !isFinite(date.getTime())) {\n return date;\n }\n\n while (format) {\n match = DATE_FORMATS_SPLIT.exec(format);\n if (match) {\n parts = concat(parts, match, 1);\n format = parts.pop();\n } else {\n parts.push(format);\n format = null;\n }\n }\n\n var dateTimezoneOffset = date.getTimezoneOffset();\n if (timezone) {\n dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);\n date = convertTimezoneToLocal(date, timezone, true);\n }\n forEach(parts, function(value) {\n fn = DATE_FORMATS[value];\n text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)\n : value === '\\'\\'' ? '\\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\\'');\n });\n\n return text;\n };\n}\n\n\n/**\n * @ngdoc filter\n * @name json\n * @kind function\n *\n * @description\n * Allows you to convert a JavaScript object into JSON string.\n *\n * This filter is mostly useful for debugging. When using the double curly {{value}} notation\n * the binding is automatically converted to JSON.\n *\n * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.\n * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.\n * @returns {string} JSON string.\n *\n *\n * @example\n \n \n
{{ {'name':'value'} | json }}
\n
{{ {'name':'value'} | json:4 }}
\n
\n \n it('should jsonify filtered objects', function() {\n expect(element(by.id('default-spacing')).getText()).toMatch(/\\{\\n {2}\"name\": ?\"value\"\\n}/);\n expect(element(by.id('custom-spacing')).getText()).toMatch(/\\{\\n {4}\"name\": ?\"value\"\\n}/);\n });\n \n
\n *\n */\nfunction jsonFilter() {\n return function(object, spacing) {\n if (isUndefined(spacing)) {\n spacing = 2;\n }\n return toJson(object, spacing);\n };\n}\n\n\n/**\n * @ngdoc filter\n * @name lowercase\n * @kind function\n * @description\n * Converts string to lowercase.\n *\n * See the {@link ng.uppercase uppercase filter documentation} for a functionally identical example.\n *\n * @see angular.lowercase\n */\nvar lowercaseFilter = valueFn(lowercase);\n\n\n/**\n * @ngdoc filter\n * @name uppercase\n * @kind function\n * @description\n * Converts string to uppercase.\n * @example\n \n \n \n
\n \n

{{title}}

\n \n

{{title | uppercase}}

\n
\n
\n
\n */\nvar uppercaseFilter = valueFn(uppercase);\n\n/**\n * @ngdoc filter\n * @name limitTo\n * @kind function\n *\n * @description\n * Creates a new array or string containing only a specified number of elements. The elements are\n * taken from either the beginning or the end of the source array, string or number, as specified by\n * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported\n * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,\n * it is converted to a string.\n *\n * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.\n * @param {string|number} limit - The length of the returned array or string. If the `limit` number\n * is positive, `limit` number of items from the beginning of the source array/string are copied.\n * If the number is negative, `limit` number of items from the end of the source array/string\n * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,\n * the input will be returned unchanged.\n * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,\n * `begin` indicates an offset from the end of `input`. Defaults to `0`.\n * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had\n * less than `limit` elements.\n *\n * @example\n \n \n \n
\n \n

Output numbers: {{ numbers | limitTo:numLimit }}

\n \n

Output letters: {{ letters | limitTo:letterLimit }}

\n \n

Output long number: {{ longNumber | limitTo:longNumberLimit }}

\n
\n
\n \n var numLimitInput = element(by.model('numLimit'));\n var letterLimitInput = element(by.model('letterLimit'));\n var longNumberLimitInput = element(by.model('longNumberLimit'));\n var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));\n var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));\n var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));\n\n it('should limit the number array to first three items', function() {\n expect(numLimitInput.getAttribute('value')).toBe('3');\n expect(letterLimitInput.getAttribute('value')).toBe('3');\n expect(longNumberLimitInput.getAttribute('value')).toBe('3');\n expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');\n expect(limitedLetters.getText()).toEqual('Output letters: abc');\n expect(limitedLongNumber.getText()).toEqual('Output long number: 234');\n });\n\n // There is a bug in safari and protractor that doesn't like the minus key\n // it('should update the output when -3 is entered', function() {\n // numLimitInput.clear();\n // numLimitInput.sendKeys('-3');\n // letterLimitInput.clear();\n // letterLimitInput.sendKeys('-3');\n // longNumberLimitInput.clear();\n // longNumberLimitInput.sendKeys('-3');\n // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');\n // expect(limitedLetters.getText()).toEqual('Output letters: ghi');\n // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');\n // });\n\n it('should not exceed the maximum size of input array', function() {\n numLimitInput.clear();\n numLimitInput.sendKeys('100');\n letterLimitInput.clear();\n letterLimitInput.sendKeys('100');\n longNumberLimitInput.clear();\n longNumberLimitInput.sendKeys('100');\n expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');\n expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');\n expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');\n });\n \n
\n*/\nfunction limitToFilter() {\n return function(input, limit, begin) {\n if (Math.abs(Number(limit)) === Infinity) {\n limit = Number(limit);\n } else {\n limit = toInt(limit);\n }\n if (isNumberNaN(limit)) return input;\n\n if (isNumber(input)) input = input.toString();\n if (!isArrayLike(input)) return input;\n\n begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);\n begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;\n\n if (limit >= 0) {\n return sliceFn(input, begin, begin + limit);\n } else {\n if (begin === 0) {\n return sliceFn(input, limit, input.length);\n } else {\n return sliceFn(input, Math.max(0, begin + limit), begin);\n }\n }\n };\n}\n\nfunction sliceFn(input, begin, end) {\n if (isString(input)) return input.slice(begin, end);\n\n return slice.call(input, begin, end);\n}\n\n/**\n * @ngdoc filter\n * @name orderBy\n * @kind function\n *\n * @description\n * Returns an array containing the items from the specified `collection`, ordered by a `comparator`\n * function based on the values computed using the `expression` predicate.\n *\n * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in\n * `[{id: 'bar'}, {id: 'foo'}]`.\n *\n * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,\n * String, etc).\n *\n * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker\n * for the preceding one. The `expression` is evaluated against each item and the output is used\n * for comparing with other items.\n *\n * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in\n * ascending order.\n *\n * The comparison is done using the `comparator` function. If none is specified, a default, built-in\n * comparator is used (see below for details - in a nutshell, it compares numbers numerically and\n * strings alphabetically).\n *\n * ### Under the hood\n *\n * Ordering the specified `collection` happens in two phases:\n *\n * 1. All items are passed through the predicate (or predicates), and the returned values are saved\n * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed\n * through a predicate that extracts the value of the `label` property, would be transformed to:\n * ```\n * {\n * value: 'foo',\n * type: 'string',\n * index: ...\n * }\n * ```\n * **Note:** `null` values use `'null'` as their type.\n * 2. The comparator function is used to sort the items, based on the derived values, types and\n * indices.\n *\n * If you use a custom comparator, it will be called with pairs of objects of the form\n * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal\n * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the\n * second, or `1` otherwise.\n *\n * In order to ensure that the sorting will be deterministic across platforms, if none of the\n * specified predicates can distinguish between two items, `orderBy` will automatically introduce a\n * dummy predicate that returns the item's index as `value`.\n * (If you are using a custom comparator, make sure it can handle this predicate as well.)\n *\n * If a custom comparator still can't distinguish between two items, then they will be sorted based\n * on their index using the built-in comparator.\n *\n * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted\n * value for an item, `orderBy` will try to convert that object to a primitive value, before passing\n * it to the comparator. The following rules govern the conversion:\n *\n * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be\n * used instead.
\n * (If the object has a `valueOf()` method that returns another object, then the returned object\n * will be used in subsequent steps.)\n * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that\n * returns a primitive, its return value will be used instead.
\n * (If the object has a `toString()` method that returns another object, then the returned object\n * will be used in subsequent steps.)\n * 3. No conversion; the object itself is used.\n *\n * ### The default comparator\n *\n * The default, built-in comparator should be sufficient for most usecases. In short, it compares\n * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to\n * using their index in the original collection, sorts values of different types by type and puts\n * `undefined` and `null` values at the end of the sorted list.\n *\n * More specifically, it follows these steps to determine the relative order of items:\n *\n * 1. If the compared values are of different types:\n * - If one of the values is undefined, consider it \"greater than\" the other.\n * - Else if one of the values is null, consider it \"greater than\" the other.\n * - Else compare the types themselves alphabetically.\n * 2. If both values are of type `string`, compare them alphabetically in a case- and\n * locale-insensitive way.\n * 3. If both values are objects, compare their indices instead.\n * 4. Otherwise, return:\n * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).\n * - `-1`, if the 1st value is \"less than\" the 2nd value (compared using the `<` operator).\n * - `1`, otherwise.\n *\n * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being\n * saved as numbers and not strings.\n * **Note:** For the purpose of sorting, `null` and `undefined` are considered \"greater than\"\n * any other value (with undefined \"greater than\" null). This effectively means that `null`\n * and `undefined` values end up at the end of a list sorted in ascending order.\n * **Note:** `null` values use `'null'` as their type to be able to distinguish them from objects.\n *\n * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.\n * @param {(Function|string|Array.)=} expression - A predicate (or list of\n * predicates) to be used by the comparator to determine the order of elements.\n *\n * Can be one of:\n *\n * - `Function`: A getter function. This function will be called with each item as argument and\n * the return value will be used for sorting.\n * - `string`: An AngularJS expression. This expression will be evaluated against each item and the\n * result will be used for sorting. For example, use `'label'` to sort by a property called\n * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`\n * property.
\n * (The result of a constant expression is interpreted as a property name to be used for\n * comparison. For example, use `'\"special name\"'` (note the extra pair of quotes) to sort by a\n * property called `special name`.)
\n * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,\n * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,\n * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.\n * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the\n * relative order of two items, the next predicate is used as a tie-breaker.\n *\n * **Note:** If the predicate is missing or empty then it defaults to `'+'`.\n *\n * @param {boolean=} reverse - If `true`, reverse the sorting order.\n * @param {(Function)=} comparator - The comparator function used to determine the relative order of\n * value pairs. If omitted, the built-in comparator will be used.\n *\n * @returns {Array} - The sorted array.\n *\n *\n * @example\n * ### Ordering a table with `ngRepeat`\n *\n * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by\n * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means\n * it defaults to the built-in comparator.\n *\n \n \n
\n \n \n \n \n \n \n \n \n \n \n \n
NamePhone NumberAge
{{friend.name}}{{friend.phone}}{{friend.age}}
\n
\n
\n \n angular.module('orderByExample1', [])\n .controller('ExampleController', ['$scope', function($scope) {\n $scope.friends = [\n {name: 'John', phone: '555-1212', age: 10},\n {name: 'Mary', phone: '555-9876', age: 19},\n {name: 'Mike', phone: '555-4321', age: 21},\n {name: 'Adam', phone: '555-5678', age: 35},\n {name: 'Julie', phone: '555-8765', age: 29}\n ];\n }]);\n \n \n .friends {\n border-collapse: collapse;\n }\n\n .friends th {\n border-bottom: 1px solid;\n }\n .friends td, .friends th {\n border-left: 1px solid;\n padding: 5px 10px;\n }\n .friends td:first-child, .friends th:first-child {\n border-left: none;\n }\n \n \n // Element locators\n var names = element.all(by.repeater('friends').column('friend.name'));\n\n it('should sort friends by age in reverse order', function() {\n expect(names.get(0).getText()).toBe('Adam');\n expect(names.get(1).getText()).toBe('Julie');\n expect(names.get(2).getText()).toBe('Mike');\n expect(names.get(3).getText()).toBe('Mary');\n expect(names.get(4).getText()).toBe('John');\n });\n \n
\n *
\n *\n * @example\n * ### Changing parameters dynamically\n *\n * All parameters can be changed dynamically. The next example shows how you can make the columns of\n * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.\n *\n \n \n
\n
Sort by = {{propertyName}}; reverse = {{reverse}}
\n
\n \n
\n \n \n \n \n \n \n \n \n \n \n \n
\n \n \n \n \n \n \n \n \n
{{friend.name}}{{friend.phone}}{{friend.age}}
\n
\n
\n \n angular.module('orderByExample2', [])\n .controller('ExampleController', ['$scope', function($scope) {\n var friends = [\n {name: 'John', phone: '555-1212', age: 10},\n {name: 'Mary', phone: '555-9876', age: 19},\n {name: 'Mike', phone: '555-4321', age: 21},\n {name: 'Adam', phone: '555-5678', age: 35},\n {name: 'Julie', phone: '555-8765', age: 29}\n ];\n\n $scope.propertyName = 'age';\n $scope.reverse = true;\n $scope.friends = friends;\n\n $scope.sortBy = function(propertyName) {\n $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;\n $scope.propertyName = propertyName;\n };\n }]);\n \n \n .friends {\n border-collapse: collapse;\n }\n\n .friends th {\n border-bottom: 1px solid;\n }\n .friends td, .friends th {\n border-left: 1px solid;\n padding: 5px 10px;\n }\n .friends td:first-child, .friends th:first-child {\n border-left: none;\n }\n\n .sortorder:after {\n content: '\\25b2'; // BLACK UP-POINTING TRIANGLE\n }\n .sortorder.reverse:after {\n content: '\\25bc'; // BLACK DOWN-POINTING TRIANGLE\n }\n \n \n // Element locators\n var unsortButton = element(by.partialButtonText('unsorted'));\n var nameHeader = element(by.partialButtonText('Name'));\n var phoneHeader = element(by.partialButtonText('Phone'));\n var ageHeader = element(by.partialButtonText('Age'));\n var firstName = element(by.repeater('friends').column('friend.name').row(0));\n var lastName = element(by.repeater('friends').column('friend.name').row(4));\n\n it('should sort friends by some property, when clicking on the column header', function() {\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n\n phoneHeader.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Mary');\n\n nameHeader.click();\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('Mike');\n\n ageHeader.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Adam');\n });\n\n it('should sort friends in reverse order, when clicking on the same column', function() {\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n\n ageHeader.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Adam');\n\n ageHeader.click();\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n });\n\n it('should restore the original order, when clicking \"Set to unsorted\"', function() {\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n\n unsortButton.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Julie');\n });\n \n
\n *
\n *\n * @example\n * ### Using `orderBy` inside a controller\n *\n * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and\n * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory\n * and retrieve the `orderBy` filter with `$filter('orderBy')`.)\n *\n \n \n
\n
Sort by = {{propertyName}}; reverse = {{reverse}}
\n
\n \n
\n \n \n \n \n \n \n \n \n \n \n \n
\n \n \n \n \n \n \n \n \n
{{friend.name}}{{friend.phone}}{{friend.age}}
\n
\n
\n \n angular.module('orderByExample3', [])\n .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {\n var friends = [\n {name: 'John', phone: '555-1212', age: 10},\n {name: 'Mary', phone: '555-9876', age: 19},\n {name: 'Mike', phone: '555-4321', age: 21},\n {name: 'Adam', phone: '555-5678', age: 35},\n {name: 'Julie', phone: '555-8765', age: 29}\n ];\n\n $scope.propertyName = 'age';\n $scope.reverse = true;\n $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);\n\n $scope.sortBy = function(propertyName) {\n $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)\n ? !$scope.reverse : false;\n $scope.propertyName = propertyName;\n $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);\n };\n }]);\n \n \n .friends {\n border-collapse: collapse;\n }\n\n .friends th {\n border-bottom: 1px solid;\n }\n .friends td, .friends th {\n border-left: 1px solid;\n padding: 5px 10px;\n }\n .friends td:first-child, .friends th:first-child {\n border-left: none;\n }\n\n .sortorder:after {\n content: '\\25b2'; // BLACK UP-POINTING TRIANGLE\n }\n .sortorder.reverse:after {\n content: '\\25bc'; // BLACK DOWN-POINTING TRIANGLE\n }\n \n \n // Element locators\n var unsortButton = element(by.partialButtonText('unsorted'));\n var nameHeader = element(by.partialButtonText('Name'));\n var phoneHeader = element(by.partialButtonText('Phone'));\n var ageHeader = element(by.partialButtonText('Age'));\n var firstName = element(by.repeater('friends').column('friend.name').row(0));\n var lastName = element(by.repeater('friends').column('friend.name').row(4));\n\n it('should sort friends by some property, when clicking on the column header', function() {\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n\n phoneHeader.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Mary');\n\n nameHeader.click();\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('Mike');\n\n ageHeader.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Adam');\n });\n\n it('should sort friends in reverse order, when clicking on the same column', function() {\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n\n ageHeader.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Adam');\n\n ageHeader.click();\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n });\n\n it('should restore the original order, when clicking \"Set to unsorted\"', function() {\n expect(firstName.getText()).toBe('Adam');\n expect(lastName.getText()).toBe('John');\n\n unsortButton.click();\n expect(firstName.getText()).toBe('John');\n expect(lastName.getText()).toBe('Julie');\n });\n \n
\n *
\n *\n * @example\n * ### Using a custom comparator\n *\n * If you have very specific requirements about the way items are sorted, you can pass your own\n * comparator function. For example, you might need to compare some strings in a locale-sensitive\n * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`\n * argument - passing `false` retains the default sorting order, i.e. ascending.)\n *\n \n \n
\n
\n

Locale-sensitive Comparator

\n \n \n \n \n \n \n \n \n \n
NameFavorite Letter
{{friend.name}}{{friend.favoriteLetter}}
\n
\n
\n

Default Comparator

\n \n \n \n \n \n \n \n \n \n
NameFavorite Letter
{{friend.name}}{{friend.favoriteLetter}}
\n
\n
\n
\n \n angular.module('orderByExample4', [])\n .controller('ExampleController', ['$scope', function($scope) {\n $scope.friends = [\n {name: 'John', favoriteLetter: 'Ä'},\n {name: 'Mary', favoriteLetter: 'Ü'},\n {name: 'Mike', favoriteLetter: 'Ö'},\n {name: 'Adam', favoriteLetter: 'H'},\n {name: 'Julie', favoriteLetter: 'Z'}\n ];\n\n $scope.localeSensitiveComparator = function(v1, v2) {\n // If we don't get strings, just compare by index\n if (v1.type !== 'string' || v2.type !== 'string') {\n return (v1.index < v2.index) ? -1 : 1;\n }\n\n // Compare strings alphabetically, taking locale into account\n return v1.value.localeCompare(v2.value);\n };\n }]);\n \n \n .friends-container {\n display: inline-block;\n margin: 0 30px;\n }\n\n .friends {\n border-collapse: collapse;\n }\n\n .friends th {\n border-bottom: 1px solid;\n }\n .friends td, .friends th {\n border-left: 1px solid;\n padding: 5px 10px;\n }\n .friends td:first-child, .friends th:first-child {\n border-left: none;\n }\n \n \n // Element locators\n var container = element(by.css('.custom-comparator'));\n var names = container.all(by.repeater('friends').column('friend.name'));\n\n it('should sort friends by favorite letter (in correct alphabetical order)', function() {\n expect(names.get(0).getText()).toBe('John');\n expect(names.get(1).getText()).toBe('Adam');\n expect(names.get(2).getText()).toBe('Mike');\n expect(names.get(3).getText()).toBe('Mary');\n expect(names.get(4).getText()).toBe('Julie');\n });\n \n
\n *\n */\norderByFilter.$inject = ['$parse'];\nfunction orderByFilter($parse) {\n return function(array, sortPredicate, reverseOrder, compareFn) {\n\n if (array == null) return array;\n if (!isArrayLike(array)) {\n throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);\n }\n\n if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }\n if (sortPredicate.length === 0) { sortPredicate = ['+']; }\n\n var predicates = processPredicates(sortPredicate);\n\n var descending = reverseOrder ? -1 : 1;\n\n // Define the `compare()` function. Use a default comparator if none is specified.\n var compare = isFunction(compareFn) ? compareFn : defaultCompare;\n\n // The next three lines are a version of a Swartzian Transform idiom from Perl\n // (sometimes called the Decorate-Sort-Undecorate idiom)\n // See https://en.wikipedia.org/wiki/Schwartzian_transform\n var compareValues = Array.prototype.map.call(array, getComparisonObject);\n compareValues.sort(doComparison);\n array = compareValues.map(function(item) { return item.value; });\n\n return array;\n\n function getComparisonObject(value, index) {\n // NOTE: We are adding an extra `tieBreaker` value based on the element's index.\n // This will be used to keep the sort stable when none of the input predicates can\n // distinguish between two elements.\n return {\n value: value,\n tieBreaker: {value: index, type: 'number', index: index},\n predicateValues: predicates.map(function(predicate) {\n return getPredicateValue(predicate.get(value), index);\n })\n };\n }\n\n function doComparison(v1, v2) {\n for (var i = 0, ii = predicates.length; i < ii; i++) {\n var result = compare(v1.predicateValues[i], v2.predicateValues[i]);\n if (result) {\n return result * predicates[i].descending * descending;\n }\n }\n\n return (compare(v1.tieBreaker, v2.tieBreaker) || defaultCompare(v1.tieBreaker, v2.tieBreaker)) * descending;\n }\n };\n\n function processPredicates(sortPredicates) {\n return sortPredicates.map(function(predicate) {\n var descending = 1, get = identity;\n\n if (isFunction(predicate)) {\n get = predicate;\n } else if (isString(predicate)) {\n if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) {\n descending = predicate.charAt(0) === '-' ? -1 : 1;\n predicate = predicate.substring(1);\n }\n if (predicate !== '') {\n get = $parse(predicate);\n if (get.constant) {\n var key = get();\n get = function(value) { return value[key]; };\n }\n }\n }\n return {get: get, descending: descending};\n });\n }\n\n function isPrimitive(value) {\n switch (typeof value) {\n case 'number': /* falls through */\n case 'boolean': /* falls through */\n case 'string':\n return true;\n default:\n return false;\n }\n }\n\n function objectValue(value) {\n // If `valueOf` is a valid function use that\n if (isFunction(value.valueOf)) {\n value = value.valueOf();\n if (isPrimitive(value)) return value;\n }\n // If `toString` is a valid function and not the one from `Object.prototype` use that\n if (hasCustomToString(value)) {\n value = value.toString();\n if (isPrimitive(value)) return value;\n }\n\n return value;\n }\n\n function getPredicateValue(value, index) {\n var type = typeof value;\n if (value === null) {\n type = 'null';\n } else if (type === 'object') {\n value = objectValue(value);\n }\n return {value: value, type: type, index: index};\n }\n\n function defaultCompare(v1, v2) {\n var result = 0;\n var type1 = v1.type;\n var type2 = v2.type;\n\n if (type1 === type2) {\n var value1 = v1.value;\n var value2 = v2.value;\n\n if (type1 === 'string') {\n // Compare strings case-insensitively\n value1 = value1.toLowerCase();\n value2 = value2.toLowerCase();\n } else if (type1 === 'object') {\n // For basic objects, use the position of the object\n // in the collection instead of the value\n if (isObject(value1)) value1 = v1.index;\n if (isObject(value2)) value2 = v2.index;\n }\n\n if (value1 !== value2) {\n result = value1 < value2 ? -1 : 1;\n }\n } else {\n result = (type1 === 'undefined') ? 1 :\n (type2 === 'undefined') ? -1 :\n (type1 === 'null') ? 1 :\n (type2 === 'null') ? -1 :\n (type1 < type2) ? -1 : 1;\n }\n\n return result;\n }\n}\n\nfunction ngDirective(directive) {\n if (isFunction(directive)) {\n directive = {\n link: directive\n };\n }\n directive.restrict = directive.restrict || 'AC';\n return valueFn(directive);\n}\n\n/**\n * @ngdoc directive\n * @name a\n * @restrict E\n *\n * @description\n * Modifies the default behavior of the html a tag so that the default action is prevented when\n * the href attribute is empty.\n *\n * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive.\n */\nvar htmlAnchorDirective = valueFn({\n restrict: 'E',\n compile: function(element, attr) {\n if (!attr.href && !attr.xlinkHref) {\n return function(scope, element) {\n // If the linked element is not an anchor tag anymore, do nothing\n if (element[0].nodeName.toLowerCase() !== 'a') return;\n\n // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.\n var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?\n 'xlink:href' : 'href';\n element.on('click', function(event) {\n // if we have no href url, then don't navigate anywhere.\n if (!element.attr(href)) {\n event.preventDefault();\n }\n });\n };\n }\n }\n});\n\n/**\n * @ngdoc directive\n * @name ngHref\n * @restrict A\n * @priority 99\n *\n * @description\n * Using AngularJS markup like `{{hash}}` in an href attribute will\n * make the link go to the wrong URL if the user clicks it before\n * AngularJS has a chance to replace the `{{hash}}` markup with its\n * value. Until AngularJS replaces the markup the link will be broken\n * and will most likely return a 404 error. The `ngHref` directive\n * solves this problem.\n *\n * The wrong way to write it:\n * ```html\n * link1\n * ```\n *\n * The correct way to write it:\n * ```html\n * link1\n * ```\n *\n * @element A\n * @param {template} ngHref any string which can contain `{{}}` markup.\n *\n * @example\n * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes\n * in links and their different behaviors:\n \n \n
\n link 1 (link, don't reload)
\n link 2 (link, don't reload)
\n link 3 (link, reload!)
\n anchor (link, don't reload)
\n anchor (no link)
\n link (link, change location)\n
\n \n it('should execute ng-click but not reload when href without value', function() {\n element(by.id('link-1')).click();\n expect(element(by.model('value')).getAttribute('value')).toEqual('1');\n expect(element(by.id('link-1')).getAttribute('href')).toBe('');\n });\n\n it('should execute ng-click but not reload when href empty string', function() {\n element(by.id('link-2')).click();\n expect(element(by.model('value')).getAttribute('value')).toEqual('2');\n expect(element(by.id('link-2')).getAttribute('href')).toBe('');\n });\n\n it('should execute ng-click and change url when ng-href specified', function() {\n expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\\/123$/);\n\n element(by.id('link-3')).click();\n\n // At this point, we navigate away from an AngularJS page, so we need\n // to use browser.driver to get the base webdriver.\n\n browser.wait(function() {\n return browser.driver.getCurrentUrl().then(function(url) {\n return url.match(/\\/123$/);\n });\n }, 5000, 'page should navigate to /123');\n });\n\n it('should execute ng-click but not reload when href empty string and name specified', function() {\n element(by.id('link-4')).click();\n expect(element(by.model('value')).getAttribute('value')).toEqual('4');\n expect(element(by.id('link-4')).getAttribute('href')).toBe('');\n });\n\n it('should execute ng-click but not reload when no href but name specified', function() {\n element(by.id('link-5')).click();\n expect(element(by.model('value')).getAttribute('value')).toEqual('5');\n expect(element(by.id('link-5')).getAttribute('href')).toBe(null);\n });\n\n it('should only change url when only ng-href', function() {\n element(by.model('value')).clear();\n element(by.model('value')).sendKeys('6');\n expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\\/6$/);\n\n element(by.id('link-6')).click();\n\n // At this point, we navigate away from an AngularJS page, so we need\n // to use browser.driver to get the base webdriver.\n browser.wait(function() {\n return browser.driver.getCurrentUrl().then(function(url) {\n return url.match(/\\/6$/);\n });\n }, 5000, 'page should navigate to /6');\n });\n \n
\n */\n\n/**\n * @ngdoc directive\n * @name ngSrc\n * @restrict A\n * @priority 99\n *\n * @description\n * Using AngularJS markup like `{{hash}}` in a `src` attribute doesn't\n * work right: The browser will fetch from the URL with the literal\n * text `{{hash}}` until AngularJS replaces the expression inside\n * `{{hash}}`. The `ngSrc` directive solves this problem.\n *\n * The buggy way to write it:\n * ```html\n * \"Description\"/\n * ```\n *\n * The correct way to write it:\n * ```html\n * \"Description\"\n * ```\n *\n * @element IMG\n * @param {template} ngSrc any string which can contain `{{}}` markup.\n */\n\n/**\n * @ngdoc directive\n * @name ngSrcset\n * @restrict A\n * @priority 99\n *\n * @description\n * Using AngularJS markup like `{{hash}}` in a `srcset` attribute doesn't\n * work right: The browser will fetch from the URL with the literal\n * text `{{hash}}` until AngularJS replaces the expression inside\n * `{{hash}}`. The `ngSrcset` directive solves this problem.\n *\n * The buggy way to write it:\n * ```html\n * \"Description\"/\n * ```\n *\n * The correct way to write it:\n * ```html\n * \"Description\"\n * ```\n *\n * @element IMG\n * @param {template} ngSrcset any string which can contain `{{}}` markup.\n */\n\n/**\n * @ngdoc directive\n * @name ngDisabled\n * @restrict A\n * @priority 100\n *\n * @description\n *\n * This directive sets the `disabled` attribute on the element (typically a form control,\n * e.g. `input`, `button`, `select` etc.) if the\n * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.\n *\n * A special directive is necessary because we cannot use interpolation inside the `disabled`\n * attribute. See the {@link guide/interpolation interpolation guide} for more info.\n *\n * @example\n \n \n
\n \n
\n \n it('should toggle button', function() {\n expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();\n element(by.model('checked')).click();\n expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();\n });\n \n
\n *\n * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,\n * then the `disabled` attribute will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngChecked\n * @restrict A\n * @priority 100\n *\n * @description\n * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.\n *\n * Note that this directive should not be used together with {@link ngModel `ngModel`},\n * as this can lead to unexpected behavior.\n *\n * A special directive is necessary because we cannot use interpolation inside the `checked`\n * attribute. See the {@link guide/interpolation interpolation guide} for more info.\n *\n * @example\n \n \n
\n \n
\n \n it('should check both checkBoxes', function() {\n expect(element(by.id('checkFollower')).getAttribute('checked')).toBeFalsy();\n element(by.model('leader')).click();\n expect(element(by.id('checkFollower')).getAttribute('checked')).toBeTruthy();\n });\n \n
\n *\n * @element INPUT\n * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,\n * then the `checked` attribute will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngReadonly\n * @restrict A\n * @priority 100\n *\n * @description\n *\n * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.\n * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on\n * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.\n *\n * A special directive is necessary because we cannot use interpolation inside the `readonly`\n * attribute. See the {@link guide/interpolation interpolation guide} for more info.\n *\n * @example\n \n \n
\n \n
\n \n it('should toggle readonly attr', function() {\n expect(element(by.css('[type=\"text\"]')).getAttribute('readonly')).toBeFalsy();\n element(by.model('checked')).click();\n expect(element(by.css('[type=\"text\"]')).getAttribute('readonly')).toBeTruthy();\n });\n \n
\n *\n * @element INPUT\n * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,\n * then special attribute \"readonly\" will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngSelected\n * @restrict A\n * @priority 100\n *\n * @description\n *\n * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.\n *\n * A special directive is necessary because we cannot use interpolation inside the `selected`\n * attribute. See the {@link guide/interpolation interpolation guide} for more info.\n *\n *
\n * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only\n * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you\n * should not use `ngSelected` on the options, as `ngModel` will set the select value and\n * selected options.\n *
\n *\n * @example\n \n \n
\n \n
\n \n it('should select Greetings!', function() {\n expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();\n element(by.model('selected')).click();\n expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();\n });\n \n
\n *\n * @element OPTION\n * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,\n * then special attribute \"selected\" will be set on the element\n */\n\n/**\n * @ngdoc directive\n * @name ngOpen\n * @restrict A\n * @priority 100\n *\n * @description\n *\n * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.\n *\n * A special directive is necessary because we cannot use interpolation inside the `open`\n * attribute. See the {@link guide/interpolation interpolation guide} for more info.\n *\n * ## A note about browser compatibility\n *\n * Internet Explorer and Edge do not support the `details` element, it is\n * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.\n *\n * @example\n \n \n
\n
\n List\n
    \n
  • Apple
  • \n
  • Orange
  • \n
  • Durian
  • \n
\n
\n
\n \n it('should toggle open', function() {\n expect(element(by.id('details')).getAttribute('open')).toBeFalsy();\n element(by.model('open')).click();\n expect(element(by.id('details')).getAttribute('open')).toBeTruthy();\n });\n \n
\n *\n * @element DETAILS\n * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,\n * then special attribute \"open\" will be set on the element\n */\n\nvar ngAttributeAliasDirectives = {};\n\n// boolean attrs are evaluated\nforEach(BOOLEAN_ATTR, function(propName, attrName) {\n // binding to multiple is not supported\n if (propName === 'multiple') return;\n\n function defaultLinkFn(scope, element, attr) {\n scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {\n attr.$set(attrName, !!value);\n });\n }\n\n var normalized = directiveNormalize('ng-' + attrName);\n var linkFn = defaultLinkFn;\n\n if (propName === 'checked') {\n linkFn = function(scope, element, attr) {\n // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input\n if (attr.ngModel !== attr[normalized]) {\n defaultLinkFn(scope, element, attr);\n }\n };\n }\n\n ngAttributeAliasDirectives[normalized] = function() {\n return {\n restrict: 'A',\n priority: 100,\n link: linkFn\n };\n };\n});\n\n// aliased input attrs are evaluated\nforEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {\n ngAttributeAliasDirectives[ngAttr] = function() {\n return {\n priority: 100,\n link: function(scope, element, attr) {\n //special case ngPattern when a literal regular expression value\n //is used as the expression (this way we don't have to watch anything).\n if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') {\n var match = attr.ngPattern.match(REGEX_STRING_REGEXP);\n if (match) {\n attr.$set('ngPattern', new RegExp(match[1], match[2]));\n return;\n }\n }\n\n scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {\n attr.$set(ngAttr, value);\n });\n }\n };\n };\n});\n\n// ng-src, ng-srcset, ng-href are interpolated\nforEach(['src', 'srcset', 'href'], function(attrName) {\n var normalized = directiveNormalize('ng-' + attrName);\n ngAttributeAliasDirectives[normalized] = ['$sce', function($sce) {\n return {\n priority: 99, // it needs to run after the attributes are interpolated\n link: function(scope, element, attr) {\n var propName = attrName,\n name = attrName;\n\n if (attrName === 'href' &&\n toString.call(element.prop('href')) === '[object SVGAnimatedString]') {\n name = 'xlinkHref';\n attr.$attr[name] = 'xlink:href';\n propName = null;\n }\n\n // We need to sanitize the url at least once, in case it is a constant\n // non-interpolated attribute.\n attr.$set(normalized, $sce.getTrustedMediaUrl(attr[normalized]));\n\n attr.$observe(normalized, function(value) {\n if (!value) {\n if (attrName === 'href') {\n attr.$set(name, null);\n }\n return;\n }\n\n attr.$set(name, value);\n\n // Support: IE 9-11 only\n // On IE, if \"ng:src\" directive declaration is used and \"src\" attribute doesn't exist\n // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need\n // to set the property as well to achieve the desired effect.\n // We use attr[attrName] value since $set might have sanitized the url.\n if (msie && propName) element.prop(propName, attr[name]);\n });\n }\n };\n }];\n});\n\n/* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS\n */\nvar nullFormCtrl = {\n $addControl: noop,\n $getControls: valueFn([]),\n $$renameControl: nullFormRenameControl,\n $removeControl: noop,\n $setValidity: noop,\n $setDirty: noop,\n $setPristine: noop,\n $setSubmitted: noop,\n $$setSubmitted: noop\n},\nPENDING_CLASS = 'ng-pending',\nSUBMITTED_CLASS = 'ng-submitted';\n\nfunction nullFormRenameControl(control, name) {\n control.$name = name;\n}\n\n/**\n * @ngdoc type\n * @name form.FormController\n *\n * @property {boolean} $pristine True if user has not interacted with the form yet.\n * @property {boolean} $dirty True if user has already interacted with the form.\n * @property {boolean} $valid True if all of the containing forms and controls are valid.\n * @property {boolean} $invalid True if at least one containing control or form is invalid.\n * @property {boolean} $submitted True if user has submitted the form even if its invalid.\n *\n * @property {Object} $pending An object hash, containing references to controls or forms with\n * pending validators, where:\n *\n * - keys are validations tokens (error names).\n * - values are arrays of controls or forms that have a pending validator for the given error name.\n *\n * See {@link form.FormController#$error $error} for a list of built-in validation tokens.\n *\n * @property {Object} $error An object hash, containing references to controls or forms with failing\n * validators, where:\n *\n * - keys are validation tokens (error names),\n * - values are arrays of controls or forms that have a failing validator for the given error name.\n *\n * Built-in validation tokens:\n * - `email`\n * - `max`\n * - `maxlength`\n * - `min`\n * - `minlength`\n * - `number`\n * - `pattern`\n * - `required`\n * - `url`\n * - `date`\n * - `datetimelocal`\n * - `time`\n * - `week`\n * - `month`\n *\n * @description\n * `FormController` keeps track of all its controls and nested forms as well as the state of them,\n * such as being valid/invalid or dirty/pristine.\n *\n * Each {@link ng.directive:form form} directive creates an instance\n * of `FormController`.\n *\n */\n//asks for $scope to fool the BC controller module\nFormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];\nfunction FormController($element, $attrs, $scope, $animate, $interpolate) {\n this.$$controls = [];\n\n // init state\n this.$error = {};\n this.$$success = {};\n this.$pending = undefined;\n this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope);\n this.$dirty = false;\n this.$pristine = true;\n this.$valid = true;\n this.$invalid = false;\n this.$submitted = false;\n this.$$parentForm = nullFormCtrl;\n\n this.$$element = $element;\n this.$$animate = $animate;\n\n setupValidity(this);\n}\n\nFormController.prototype = {\n /**\n * @ngdoc method\n * @name form.FormController#$rollbackViewValue\n *\n * @description\n * Rollback all form controls pending updates to the `$modelValue`.\n *\n * Updates may be pending by a debounced event or because the input is waiting for a some future\n * event defined in `ng-model-options`. This method is typically needed by the reset button of\n * a form that uses `ng-model-options` to pend updates.\n */\n $rollbackViewValue: function() {\n forEach(this.$$controls, function(control) {\n control.$rollbackViewValue();\n });\n },\n\n /**\n * @ngdoc method\n * @name form.FormController#$commitViewValue\n *\n * @description\n * Commit all form controls pending updates to the `$modelValue`.\n *\n * Updates may be pending by a debounced event or because the input is waiting for a some future\n * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`\n * usually handles calling this in response to input events.\n */\n $commitViewValue: function() {\n forEach(this.$$controls, function(control) {\n control.$commitViewValue();\n });\n },\n\n /**\n * @ngdoc method\n * @name form.FormController#$addControl\n * @param {object} control control object, either a {@link form.FormController} or an\n * {@link ngModel.NgModelController}\n *\n * @description\n * Register a control with the form. Input elements using ngModelController do this automatically\n * when they are linked.\n *\n * Note that the current state of the control will not be reflected on the new parent form. This\n * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`\n * state.\n *\n * However, if the method is used programmatically, for example by adding dynamically created controls,\n * or controls that have been previously removed without destroying their corresponding DOM element,\n * it's the developers responsibility to make sure the current state propagates to the parent form.\n *\n * For example, if an input control is added that is already `$dirty` and has `$error` properties,\n * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.\n */\n $addControl: function(control) {\n // Breaking change - before, inputs whose name was \"hasOwnProperty\" were quietly ignored\n // and not added to the scope. Now we throw an error.\n assertNotHasOwnProperty(control.$name, 'input');\n this.$$controls.push(control);\n\n if (control.$name) {\n this[control.$name] = control;\n }\n\n control.$$parentForm = this;\n },\n\n /**\n * @ngdoc method\n * @name form.FormController#$getControls\n * @returns {Array} the controls that are currently part of this form\n *\n * @description\n * This method returns a **shallow copy** of the controls that are currently part of this form.\n * The controls can be instances of {@link form.FormController `FormController`}\n * ({@link ngForm \"child-forms\"}) and of {@link ngModel.NgModelController `NgModelController`}.\n * If you need access to the controls of child-forms, you have to call `$getControls()`\n * recursively on them.\n * This can be used for example to iterate over all controls to validate them.\n *\n * The controls can be accessed normally, but adding to, or removing controls from the array has\n * no effect on the form. Instead, use {@link form.FormController#$addControl `$addControl()`} and\n * {@link form.FormController#$removeControl `$removeControl()`} for this use-case.\n * Likewise, adding a control to, or removing a control from the form is not reflected\n * in the shallow copy. That means you should get a fresh copy from `$getControls()` every time\n * you need access to the controls.\n */\n $getControls: function() {\n return shallowCopy(this.$$controls);\n },\n\n // Private API: rename a form control\n $$renameControl: function(control, newName) {\n var oldName = control.$name;\n\n if (this[oldName] === control) {\n delete this[oldName];\n }\n this[newName] = control;\n control.$name = newName;\n },\n\n /**\n * @ngdoc method\n * @name form.FormController#$removeControl\n * @param {object} control control object, either a {@link form.FormController} or an\n * {@link ngModel.NgModelController}\n *\n * @description\n * Deregister a control from the form.\n *\n * Input elements using ngModelController do this automatically when they are destroyed.\n *\n * Note that only the removed control's validation state (`$errors`etc.) will be removed from the\n * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be\n * different from case to case. For example, removing the only `$dirty` control from a form may or\n * may not mean that the form is still `$dirty`.\n */\n $removeControl: function(control) {\n if (control.$name && this[control.$name] === control) {\n delete this[control.$name];\n }\n forEach(this.$pending, function(value, name) {\n // eslint-disable-next-line no-invalid-this\n this.$setValidity(name, null, control);\n }, this);\n forEach(this.$error, function(value, name) {\n // eslint-disable-next-line no-invalid-this\n this.$setValidity(name, null, control);\n }, this);\n forEach(this.$$success, function(value, name) {\n // eslint-disable-next-line no-invalid-this\n this.$setValidity(name, null, control);\n }, this);\n\n arrayRemove(this.$$controls, control);\n control.$$parentForm = nullFormCtrl;\n },\n\n /**\n * @ngdoc method\n * @name form.FormController#$setDirty\n *\n * @description\n * Sets the form to a dirty state.\n *\n * This method can be called to add the 'ng-dirty' class and set the form to a dirty\n * state (ng-dirty class). This method will also propagate to parent forms.\n */\n $setDirty: function() {\n this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);\n this.$$animate.addClass(this.$$element, DIRTY_CLASS);\n this.$dirty = true;\n this.$pristine = false;\n this.$$parentForm.$setDirty();\n },\n\n /**\n * @ngdoc method\n * @name form.FormController#$setPristine\n *\n * @description\n * Sets the form to its pristine state.\n *\n * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes\n * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted`\n * state to false.\n *\n * This method will also propagate to all the controls contained in this form.\n *\n * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after\n * saving or resetting it.\n */\n $setPristine: function() {\n this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);\n this.$dirty = false;\n this.$pristine = true;\n this.$submitted = false;\n forEach(this.$$controls, function(control) {\n control.$setPristine();\n });\n },\n\n /**\n * @ngdoc method\n * @name form.FormController#$setUntouched\n *\n * @description\n * Sets the form to its untouched state.\n *\n * This method can be called to remove the 'ng-touched' class and set the form controls to their\n * untouched state (ng-untouched class).\n *\n * Setting a form controls back to their untouched state is often useful when setting the form\n * back to its pristine state.\n */\n $setUntouched: function() {\n forEach(this.$$controls, function(control) {\n control.$setUntouched();\n });\n },\n\n /**\n * @ngdoc method\n * @name form.FormController#$setSubmitted\n *\n * @description\n * Sets the form to its `$submitted` state. This will also set `$submitted` on all child and\n * parent forms of the form.\n */\n $setSubmitted: function() {\n var rootForm = this;\n while (rootForm.$$parentForm && (rootForm.$$parentForm !== nullFormCtrl)) {\n rootForm = rootForm.$$parentForm;\n }\n rootForm.$$setSubmitted();\n },\n\n $$setSubmitted: function() {\n this.$$animate.addClass(this.$$element, SUBMITTED_CLASS);\n this.$submitted = true;\n forEach(this.$$controls, function(control) {\n if (control.$$setSubmitted) {\n control.$$setSubmitted();\n }\n });\n }\n};\n\n/**\n * @ngdoc method\n * @name form.FormController#$setValidity\n *\n * @description\n * Change the validity state of the form, and notify the parent form (if any).\n *\n * Application developers will rarely need to call this method directly. It is used internally, by\n * {@link ngModel.NgModelController#$setValidity NgModelController.$setValidity()}, to propagate a\n * control's validity state to the parent `FormController`.\n *\n * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be\n * assigned to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` (for\n * unfulfilled `$asyncValidators`), so that it is available for data-binding. The\n * `validationErrorKey` should be in camelCase and will get converted into dash-case for\n * class name. Example: `myError` will result in `ng-valid-my-error` and\n * `ng-invalid-my-error` classes and can be bound to as `{{ someForm.$error.myError }}`.\n * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending\n * (undefined), or skipped (null). Pending is used for unfulfilled `$asyncValidators`.\n * Skipped is used by AngularJS when validators do not run because of parse errors and when\n * `$asyncValidators` do not run because any of the `$validators` failed.\n * @param {NgModelController | FormController} controller - The controller whose validity state is\n * triggering the change.\n */\naddSetValidityMethod({\n clazz: FormController,\n set: function(object, property, controller) {\n var list = object[property];\n if (!list) {\n object[property] = [controller];\n } else {\n var index = list.indexOf(controller);\n if (index === -1) {\n list.push(controller);\n }\n }\n },\n unset: function(object, property, controller) {\n var list = object[property];\n if (!list) {\n return;\n }\n arrayRemove(list, controller);\n if (list.length === 0) {\n delete object[property];\n }\n }\n});\n\n/**\n * @ngdoc directive\n * @name ngForm\n * @restrict EAC\n *\n * @description\n * Helper directive that makes it possible to create control groups inside a\n * {@link ng.directive:form `form`} directive.\n * These \"child forms\" can be used, for example, to determine the validity of a sub-group of\n * controls.\n *\n *
\n * **Note**: `ngForm` cannot be used as a replacement for `
`, because it lacks its\n * [built-in HTML functionality](https://html.spec.whatwg.org/#the-form-element).\n * Specifically, you cannot submit `ngForm` like a `` tag. That means,\n * you cannot send data to the server with `ngForm`, or integrate it with\n * {@link ng.directive:ngSubmit `ngSubmit`}.\n *
\n *\n * @param {string=} ngForm|name Name of the form. If specified, the form controller will\n * be published into the related scope, under this name.\n *\n */\n\n /**\n * @ngdoc directive\n * @name form\n * @restrict E\n *\n * @description\n * Directive that instantiates\n * {@link form.FormController FormController}.\n *\n * If the `name` attribute is specified, the form controller is published onto the current scope under\n * this name.\n *\n * ## Alias: {@link ng.directive:ngForm `ngForm`}\n *\n * In AngularJS, forms can be nested. This means that the outer form is valid when all of the child\n * forms are valid as well. However, browsers do not allow nesting of `` elements, so\n * AngularJS provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to\n * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group\n * of controls needs to be determined.\n *\n * ## CSS classes\n * - `ng-valid` is set if the form is valid.\n * - `ng-invalid` is set if the form is invalid.\n * - `ng-pending` is set if the form is pending.\n * - `ng-pristine` is set if the form is pristine.\n * - `ng-dirty` is set if the form is dirty.\n * - `ng-submitted` is set if the form was submitted.\n *\n * Keep in mind that ngAnimate can detect each of these classes when added and removed.\n *\n *\n * ## Submitting a form and preventing the default action\n *\n * Since the role of forms in client-side AngularJS applications is different than in classical\n * roundtrip apps, it is desirable for the browser not to translate the form submission into a full\n * page reload that sends the data to the server. Instead some javascript logic should be triggered\n * to handle the form submission in an application-specific way.\n *\n * For this reason, AngularJS prevents the default action (form submission to the server) unless the\n * `` element has an `action` attribute specified.\n *\n * You can use one of the following two ways to specify what javascript method should be called when\n * a form is submitted:\n *\n * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element\n * - {@link ng.directive:ngClick ngClick} directive on the first\n * button or input field of type submit (input[type=submit])\n *\n * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}\n * or {@link ng.directive:ngClick ngClick} directives.\n * This is because of the following form submission rules in the HTML specification:\n *\n * - If a form has only one input field then hitting enter in this field triggers form submit\n * (`ngSubmit`)\n * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter\n * doesn't trigger submit\n * - if a form has one or more input fields and one or more buttons or input[type=submit] then\n * hitting enter in any of the input fields will trigger the click handler on the *first* button or\n * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)\n *\n * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is\n * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`\n * to have access to the updated model.\n *\n * @animations\n * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.\n * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any\n * other validations that are performed within the form. Animations in ngForm are similar to how\n * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well\n * as JS animations.\n *\n * The following example shows a simple way to utilize CSS transitions to style a form element\n * that has been rendered as invalid after it has been validated:\n *\n *
\n * //be sure to include ngAnimate as a module to hook into more\n * //advanced animations\n * .my-form {\n *   transition:0.5s linear all;\n *   background: white;\n * }\n * .my-form.ng-invalid {\n *   background: red;\n *   color:white;\n * }\n * 
\n *\n * @example\n \n \n \n \n \n userType: \n Required!
\n userType = {{userType}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n \n
\n \n it('should initialize to model', function() {\n var userType = element(by.binding('userType'));\n var valid = element(by.binding('myForm.input.$valid'));\n\n expect(userType.getText()).toContain('guest');\n expect(valid.getText()).toContain('true');\n });\n\n it('should be invalid if empty', function() {\n var userType = element(by.binding('userType'));\n var valid = element(by.binding('myForm.input.$valid'));\n var userInput = element(by.model('userType'));\n\n userInput.clear();\n userInput.sendKeys('');\n\n expect(userType.getText()).toEqual('userType =');\n expect(valid.getText()).toContain('false');\n });\n \n
\n *\n * @param {string=} name Name of the form. If specified, the form controller will be published into\n * related scope, under this name.\n */\nvar formDirectiveFactory = function(isNgForm) {\n return ['$timeout', '$parse', function($timeout, $parse) {\n var formDirective = {\n name: 'form',\n restrict: isNgForm ? 'EAC' : 'E',\n require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form\n controller: FormController,\n compile: function ngFormCompile(formElement, attr) {\n // Setup initial state of the control\n formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);\n\n var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);\n\n return {\n pre: function ngFormPreLink(scope, formElement, attr, ctrls) {\n var controller = ctrls[0];\n\n // if `action` attr is not present on the form, prevent the default action (submission)\n if (!('action' in attr)) {\n // we can't use jq events because if a form is destroyed during submission the default\n // action is not prevented. see #1238\n //\n // IE 9 is not affected because it doesn't fire a submit event and try to do a full\n // page reload if the form was destroyed by submission of the form via a click handler\n // on a button in the form. Looks like an IE9 specific bug.\n var handleFormSubmission = function(event) {\n scope.$apply(function() {\n controller.$commitViewValue();\n controller.$setSubmitted();\n });\n\n event.preventDefault();\n };\n\n formElement[0].addEventListener('submit', handleFormSubmission);\n\n // unregister the preventDefault listener so that we don't not leak memory but in a\n // way that will achieve the prevention of the default action.\n formElement.on('$destroy', function() {\n $timeout(function() {\n formElement[0].removeEventListener('submit', handleFormSubmission);\n }, 0, false);\n });\n }\n\n var parentFormCtrl = ctrls[1] || controller.$$parentForm;\n parentFormCtrl.$addControl(controller);\n\n var setter = nameAttr ? getSetter(controller.$name) : noop;\n\n if (nameAttr) {\n setter(scope, controller);\n attr.$observe(nameAttr, function(newValue) {\n if (controller.$name === newValue) return;\n setter(scope, undefined);\n controller.$$parentForm.$$renameControl(controller, newValue);\n setter = getSetter(controller.$name);\n setter(scope, controller);\n });\n }\n formElement.on('$destroy', function() {\n controller.$$parentForm.$removeControl(controller);\n setter(scope, undefined);\n extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards\n });\n }\n };\n }\n };\n\n return formDirective;\n\n function getSetter(expression) {\n if (expression === '') {\n //create an assignable expression, so forms with an empty name can be renamed later\n return $parse('this[\"\"]').assign;\n }\n return $parse(expression).assign || noop;\n }\n }];\n};\n\nvar formDirective = formDirectiveFactory();\nvar ngFormDirective = formDirectiveFactory(true);\n\n\n\n// helper methods\nfunction setupValidity(instance) {\n instance.$$classCache = {};\n instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS));\n}\nfunction addSetValidityMethod(context) {\n var clazz = context.clazz,\n set = context.set,\n unset = context.unset;\n\n clazz.prototype.$setValidity = function(validationErrorKey, state, controller) {\n if (isUndefined(state)) {\n createAndSet(this, '$pending', validationErrorKey, controller);\n } else {\n unsetAndCleanup(this, '$pending', validationErrorKey, controller);\n }\n if (!isBoolean(state)) {\n unset(this.$error, validationErrorKey, controller);\n unset(this.$$success, validationErrorKey, controller);\n } else {\n if (state) {\n unset(this.$error, validationErrorKey, controller);\n set(this.$$success, validationErrorKey, controller);\n } else {\n set(this.$error, validationErrorKey, controller);\n unset(this.$$success, validationErrorKey, controller);\n }\n }\n if (this.$pending) {\n cachedToggleClass(this, PENDING_CLASS, true);\n this.$valid = this.$invalid = undefined;\n toggleValidationCss(this, '', null);\n } else {\n cachedToggleClass(this, PENDING_CLASS, false);\n this.$valid = isObjectEmpty(this.$error);\n this.$invalid = !this.$valid;\n toggleValidationCss(this, '', this.$valid);\n }\n\n // re-read the state as the set/unset methods could have\n // combined state in this.$error[validationError] (used for forms),\n // where setting/unsetting only increments/decrements the value,\n // and does not replace it.\n var combinedState;\n if (this.$pending && this.$pending[validationErrorKey]) {\n combinedState = undefined;\n } else if (this.$error[validationErrorKey]) {\n combinedState = false;\n } else if (this.$$success[validationErrorKey]) {\n combinedState = true;\n } else {\n combinedState = null;\n }\n\n toggleValidationCss(this, validationErrorKey, combinedState);\n this.$$parentForm.$setValidity(validationErrorKey, combinedState, this);\n };\n\n function createAndSet(ctrl, name, value, controller) {\n if (!ctrl[name]) {\n ctrl[name] = {};\n }\n set(ctrl[name], value, controller);\n }\n\n function unsetAndCleanup(ctrl, name, value, controller) {\n if (ctrl[name]) {\n unset(ctrl[name], value, controller);\n }\n if (isObjectEmpty(ctrl[name])) {\n ctrl[name] = undefined;\n }\n }\n\n function cachedToggleClass(ctrl, className, switchValue) {\n if (switchValue && !ctrl.$$classCache[className]) {\n ctrl.$$animate.addClass(ctrl.$$element, className);\n ctrl.$$classCache[className] = true;\n } else if (!switchValue && ctrl.$$classCache[className]) {\n ctrl.$$animate.removeClass(ctrl.$$element, className);\n ctrl.$$classCache[className] = false;\n }\n }\n\n function toggleValidationCss(ctrl, validationErrorKey, isValid) {\n validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';\n\n cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true);\n cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false);\n }\n}\n\nfunction isObjectEmpty(obj) {\n if (obj) {\n for (var prop in obj) {\n if (obj.hasOwnProperty(prop)) {\n return false;\n }\n }\n }\n return true;\n}\n\n/* global\n VALID_CLASS: false,\n INVALID_CLASS: false,\n PRISTINE_CLASS: false,\n DIRTY_CLASS: false,\n ngModelMinErr: false\n*/\n\n// Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231\nvar ISO_DATE_REGEXP = /^\\d{4,}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+(?:[+-][0-2]\\d:[0-5]\\d|Z)$/;\n// See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)\n// Note: We are being more lenient, because browsers are too.\n// 1. Scheme\n// 2. Slashes\n// 3. Username\n// 4. Password\n// 5. Hostname\n// 6. Port\n// 7. Path\n// 8. Query\n// 9. Fragment\n// 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999\nvar URL_REGEXP = /^[a-z][a-z\\d.+-]*:\\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\\s:/?#]+|\\[[a-f\\d:]+])(?::\\d+)?(?:\\/[^?#]*)?(?:\\?[^#]*)?(?:#.*)?$/i;\n// eslint-disable-next-line max-len\nvar EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;\nvar NUMBER_REGEXP = /^\\s*(-|\\+)?(\\d+|(\\d*(\\.\\d*)))([eE][+-]?\\d+)?\\s*$/;\nvar DATE_REGEXP = /^(\\d{4,})-(\\d{2})-(\\d{2})$/;\nvar DATETIMELOCAL_REGEXP = /^(\\d{4,})-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d)(?::(\\d\\d)(\\.\\d{1,3})?)?$/;\nvar WEEK_REGEXP = /^(\\d{4,})-W(\\d\\d)$/;\nvar MONTH_REGEXP = /^(\\d{4,})-(\\d\\d)$/;\nvar TIME_REGEXP = /^(\\d\\d):(\\d\\d)(?::(\\d\\d)(\\.\\d{1,3})?)?$/;\n\nvar PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';\nvar PARTIAL_VALIDATION_TYPES = createMap();\nforEach('date,datetime-local,month,time,week'.split(','), function(type) {\n PARTIAL_VALIDATION_TYPES[type] = true;\n});\n\nvar inputType = {\n\n /**\n * @ngdoc input\n * @name input[text]\n *\n * @description\n * Standard HTML text input with AngularJS data binding, inherited by most of the `input` elements.\n *\n *\n * @param {string} ngModel Assignable AngularJS expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Adds `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n * minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n * any length.\n * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n * that contains the regular expression body that will be converted to a regular expression\n * as in the ngPattern directive.\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}\n * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.\n * If the expression evaluates to a RegExp object, then this is used directly.\n * If the expression evaluates to a string, then it will be converted to a RegExp\n * after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n * `new RegExp('^abc$')`.
\n * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n * start at the index of the last search's match, thus not taking the whole input value into\n * account.\n * @param {string=} ngChange AngularJS expression to be executed when input changes due to user\n * interaction with the input element.\n * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input.\n * This parameter is ignored for input[type=password] controls, which will never trim the\n * input.\n *\n * @example\n \n \n \n
\n \n
\n \n Required!\n \n Single word only!\n
\n text = {{example.text}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n
\n
\n \n var text = element(by.binding('example.text'));\n var valid = element(by.binding('myForm.input.$valid'));\n var input = element(by.model('example.text'));\n\n it('should initialize to model', function() {\n expect(text.getText()).toContain('guest');\n expect(valid.getText()).toContain('true');\n });\n\n it('should be invalid if empty', function() {\n input.clear();\n input.sendKeys('');\n\n expect(text.getText()).toEqual('text =');\n expect(valid.getText()).toContain('false');\n });\n\n it('should be invalid if multi word', function() {\n input.clear();\n input.sendKeys('hello world');\n\n expect(valid.getText()).toContain('false');\n });\n \n
\n */\n 'text': textInputType,\n\n /**\n * @ngdoc input\n * @name input[date]\n *\n * @description\n * Input with date validation and transformation. In browsers that do not yet support\n * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601\n * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many\n * modern browsers do not yet support this input type, it is important to provide cues to users on the\n * expected input format via a placeholder or label.\n *\n * The model must always be a Date object, otherwise AngularJS will throw an error.\n * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n *\n * The timezone to be used to read/write the `Date` instance in the model can be defined using\n * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n *\n * @param {string} ngModel Assignable AngularJS expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute\n * (e.g. `min=\"{{minDate | date:'yyyy-MM-dd'}}\"`). Note that `min` will also add native HTML5\n * constraint validation.\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\n * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute\n * (e.g. `max=\"{{maxDate | date:'yyyy-MM-dd'}}\"`). Note that `max` will also add native HTML5\n * constraint validation.\n * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string\n * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.\n * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string\n * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {string=} ngChange AngularJS expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n \n \n
\n \n Required!\n \n Not a valid date!\n
\n value = {{example.value | date: \"yyyy-MM-dd\"}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n
\n
\n \n var value = element(by.binding('example.value | date: \"yyyy-MM-dd\"'));\n var valid = element(by.binding('myForm.input.$valid'));\n\n // currently protractor/webdriver does not support\n // sending keys to all known HTML5 input controls\n // for various browsers (see https://github.com/angular/protractor/issues/562).\n function setInput(val) {\n // set the value of the element and force validation.\n var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n \"ipt.value = '\" + val + \"';\" +\n \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n browser.executeScript(scr);\n }\n\n it('should initialize to model', function() {\n expect(value.getText()).toContain('2013-10-22');\n expect(valid.getText()).toContain('myForm.input.$valid = true');\n });\n\n it('should be invalid if empty', function() {\n setInput('');\n expect(value.getText()).toEqual('value =');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n\n it('should be invalid if over max', function() {\n setInput('2015-01-01');\n expect(value.getText()).toContain('');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n \n
\n */\n 'date': createDateInputType('date', DATE_REGEXP,\n createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),\n 'yyyy-MM-dd'),\n\n /**\n * @ngdoc input\n * @name input[datetime-local]\n *\n * @description\n * Input with datetime validation and transformation. In browsers that do not yet support\n * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.\n *\n * The model must always be a Date object, otherwise AngularJS will throw an error.\n * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n *\n * The timezone to be used to read/write the `Date` instance in the model can be defined using\n * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n *\n * The format of the displayed time can be adjusted with the\n * {@link ng.directive:ngModelOptions#ngModelOptions-arguments ngModelOptions} `timeSecondsFormat`\n * and `timeStripZeroSeconds`.\n *\n * @param {string} ngModel Assignable AngularJS expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.\n * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation\n * inside this attribute (e.g. `min=\"{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}\"`).\n * Note that `min` will also add native HTML5 constraint validation.\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.\n * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation\n * inside this attribute (e.g. `max=\"{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}\"`).\n * Note that `max` will also add native HTML5 constraint validation.\n * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string\n * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.\n * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string\n * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {string=} ngChange AngularJS expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n \n \n
\n \n Required!\n \n Not a valid date!\n
\n value = {{example.value | date: \"yyyy-MM-ddTHH:mm:ss\"}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n
\n
\n \n var value = element(by.binding('example.value | date: \"yyyy-MM-ddTHH:mm:ss\"'));\n var valid = element(by.binding('myForm.input.$valid'));\n\n // currently protractor/webdriver does not support\n // sending keys to all known HTML5 input controls\n // for various browsers (https://github.com/angular/protractor/issues/562).\n function setInput(val) {\n // set the value of the element and force validation.\n var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n \"ipt.value = '\" + val + \"';\" +\n \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n browser.executeScript(scr);\n }\n\n it('should initialize to model', function() {\n expect(value.getText()).toContain('2010-12-28T14:57:00');\n expect(valid.getText()).toContain('myForm.input.$valid = true');\n });\n\n it('should be invalid if empty', function() {\n setInput('');\n expect(value.getText()).toEqual('value =');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n\n it('should be invalid if over max', function() {\n setInput('2015-01-01T23:59:00');\n expect(value.getText()).toContain('');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n \n
\n */\n 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,\n createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),\n 'yyyy-MM-ddTHH:mm:ss.sss'),\n\n /**\n * @ngdoc input\n * @name input[time]\n *\n * @description\n * Input with time validation and transformation. In browsers that do not yet support\n * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a\n * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.\n *\n * The model must always be a Date object, otherwise AngularJS will throw an error.\n * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n *\n * The timezone to be used to read/write the `Date` instance in the model can be defined using\n * {@link ng.directive:ngModelOptions#ngModelOptions-arguments ngModelOptions}. By default,\n * this is the timezone of the browser.\n *\n * The format of the displayed time can be adjusted with the\n * {@link ng.directive:ngModelOptions#ngModelOptions-arguments ngModelOptions} `timeSecondsFormat`\n * and `timeStripZeroSeconds`.\n *\n * @param {string} ngModel Assignable AngularJS expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.\n * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this\n * attribute (e.g. `min=\"{{minTime | date:'HH:mm:ss'}}\"`). Note that `min` will also add\n * native HTML5 constraint validation.\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.\n * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this\n * attribute (e.g. `max=\"{{maxTime | date:'HH:mm:ss'}}\"`). Note that `max` will also add\n * native HTML5 constraint validation.\n * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the\n * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.\n * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the\n * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {string=} ngChange AngularJS expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n \n \n
\n \n Required!\n \n Not a valid date!\n
\n value = {{example.value | date: \"HH:mm:ss\"}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n
\n
\n \n var value = element(by.binding('example.value | date: \"HH:mm:ss\"'));\n var valid = element(by.binding('myForm.input.$valid'));\n\n // currently protractor/webdriver does not support\n // sending keys to all known HTML5 input controls\n // for various browsers (https://github.com/angular/protractor/issues/562).\n function setInput(val) {\n // set the value of the element and force validation.\n var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n \"ipt.value = '\" + val + \"';\" +\n \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n browser.executeScript(scr);\n }\n\n it('should initialize to model', function() {\n expect(value.getText()).toContain('14:57:00');\n expect(valid.getText()).toContain('myForm.input.$valid = true');\n });\n\n it('should be invalid if empty', function() {\n setInput('');\n expect(value.getText()).toEqual('value =');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n\n it('should be invalid if over max', function() {\n setInput('23:59:00');\n expect(value.getText()).toContain('');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n \n
\n */\n 'time': createDateInputType('time', TIME_REGEXP,\n createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),\n 'HH:mm:ss.sss'),\n\n /**\n * @ngdoc input\n * @name input[week]\n *\n * @description\n * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support\n * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n * week format (yyyy-W##), for example: `2013-W02`.\n *\n * The model must always be a Date object, otherwise AngularJS will throw an error.\n * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n *\n * The value of the resulting Date object will be set to Thursday at 00:00:00 of the requested week,\n * due to ISO-8601 week numbering standards. Information on ISO's system for numbering the weeks of the\n * year can be found at: https://en.wikipedia.org/wiki/ISO_8601#Week_dates\n *\n * The timezone to be used to read/write the `Date` instance in the model can be defined using\n * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n *\n * @param {string} ngModel Assignable AngularJS expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.\n * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this\n * attribute (e.g. `min=\"{{minWeek | date:'yyyy-Www'}}\"`). Note that `min` will also add\n * native HTML5 constraint validation.\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.\n * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this\n * attribute (e.g. `max=\"{{maxWeek | date:'yyyy-Www'}}\"`). Note that `max` will also add\n * native HTML5 constraint validation.\n * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string\n * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.\n * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string\n * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {string=} ngChange AngularJS expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n \n
\n \n Required!\n \n Not a valid date!\n
\n value = {{example.value | date: \"yyyy-Www\"}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n
\n
\n \n var value = element(by.binding('example.value | date: \"yyyy-Www\"'));\n var valid = element(by.binding('myForm.input.$valid'));\n\n // currently protractor/webdriver does not support\n // sending keys to all known HTML5 input controls\n // for various browsers (https://github.com/angular/protractor/issues/562).\n function setInput(val) {\n // set the value of the element and force validation.\n var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n \"ipt.value = '\" + val + \"';\" +\n \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n browser.executeScript(scr);\n }\n\n it('should initialize to model', function() {\n expect(value.getText()).toContain('2013-W01');\n expect(valid.getText()).toContain('myForm.input.$valid = true');\n });\n\n it('should be invalid if empty', function() {\n setInput('');\n expect(value.getText()).toEqual('value =');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n\n it('should be invalid if over max', function() {\n setInput('2015-W01');\n expect(value.getText()).toContain('');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n \n
\n */\n 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),\n\n /**\n * @ngdoc input\n * @name input[month]\n *\n * @description\n * Input with month validation and transformation. In browsers that do not yet support\n * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n * month format (yyyy-MM), for example: `2009-01`.\n *\n * The model must always be a Date object, otherwise AngularJS will throw an error.\n * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n * If the model is not set to the first of the month, the next view to model update will set it\n * to the first of the month.\n *\n * The timezone to be used to read/write the `Date` instance in the model can be defined using\n * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n *\n * @param {string} ngModel Assignable AngularJS expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.\n * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this\n * attribute (e.g. `min=\"{{minMonth | date:'yyyy-MM'}}\"`). Note that `min` will also add\n * native HTML5 constraint validation.\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.\n * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this\n * attribute (e.g. `max=\"{{maxMonth | date:'yyyy-MM'}}\"`). Note that `max` will also add\n * native HTML5 constraint validation.\n * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string\n * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.\n * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string\n * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.\n\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {string=} ngChange AngularJS expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n \n \n
\n \n Required!\n \n Not a valid month!\n
\n value = {{example.value | date: \"yyyy-MM\"}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n
\n
\n \n var value = element(by.binding('example.value | date: \"yyyy-MM\"'));\n var valid = element(by.binding('myForm.input.$valid'));\n\n // currently protractor/webdriver does not support\n // sending keys to all known HTML5 input controls\n // for various browsers (https://github.com/angular/protractor/issues/562).\n function setInput(val) {\n // set the value of the element and force validation.\n var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n \"ipt.value = '\" + val + \"';\" +\n \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n browser.executeScript(scr);\n }\n\n it('should initialize to model', function() {\n expect(value.getText()).toContain('2013-10');\n expect(valid.getText()).toContain('myForm.input.$valid = true');\n });\n\n it('should be invalid if empty', function() {\n setInput('');\n expect(value.getText()).toEqual('value =');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n\n it('should be invalid if over max', function() {\n setInput('2015-01');\n expect(value.getText()).toContain('');\n expect(valid.getText()).toContain('myForm.input.$valid = false');\n });\n \n
\n */\n 'month': createDateInputType('month', MONTH_REGEXP,\n createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),\n 'yyyy-MM'),\n\n /**\n * @ngdoc input\n * @name input[number]\n *\n * @description\n * Text input with number validation and transformation. Sets the `number` validation\n * error if not a valid number.\n *\n *
\n * The model must always be of type `number` otherwise AngularJS will throw an error.\n * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}\n * error docs for more information and an example of how to convert your model if necessary.\n *
\n *\n *\n *\n * @knownIssue\n *\n * ### HTML5 constraint validation and `allowInvalid`\n *\n * In browsers that follow the\n * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),\n * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.\n * If a non-number is entered in the input, the browser will report the value as an empty string,\n * which means the view / model values in `ngModel` and subsequently the scope value\n * will also be an empty string.\n *\n * @knownIssue\n *\n * ### Large numbers and `step` validation\n *\n * The `step` validation will not work correctly for very large numbers (e.g. 9999999999) due to\n * Javascript's arithmetic limitations. If you need to handle large numbers, purpose-built\n * libraries (e.g. https://github.com/MikeMcl/big.js/), can be included into AngularJS by\n * {@link guide/forms#modifying-built-in-validators overwriting the validators}\n * for `number` and / or `step`, or by {@link guide/forms#custom-validation applying custom validators}\n * to an `input[text]` element. The source for `input[number]` type can be used as a starting\n * point for both implementations.\n *\n * @param {string} ngModel Assignable AngularJS expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.\n * Can be interpolated.\n * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.\n * Can be interpolated.\n * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`,\n * but does not trigger HTML5 native validation. Takes an expression.\n * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`,\n * but does not trigger HTML5 native validation. Takes an expression.\n * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint.\n * Can be interpolated.\n * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint,\n * but does not trigger HTML5 native validation. Takes an expression.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n * minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n * any length.\n * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n * that contains the regular expression body that will be converted to a regular expression\n * as in the ngPattern directive.\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}\n * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.\n * If the expression evaluates to a RegExp object, then this is used directly.\n * If the expression evaluates to a string, then it will be converted to a RegExp\n * after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n * `new RegExp('^abc$')`.
\n * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n * start at the index of the last search's match, thus not taking the whole input value into\n * account.\n * @param {string=} ngChange AngularJS expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n \n
\n \n Required!\n \n Not valid number!\n
\n value = {{example.value}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n
\n
\n \n var value = element(by.binding('example.value'));\n var valid = element(by.binding('myForm.input.$valid'));\n var input = element(by.model('example.value'));\n\n it('should initialize to model', function() {\n expect(value.getText()).toContain('12');\n expect(valid.getText()).toContain('true');\n });\n\n it('should be invalid if empty', function() {\n input.clear();\n input.sendKeys('');\n expect(value.getText()).toEqual('value =');\n expect(valid.getText()).toContain('false');\n });\n\n it('should be invalid if over max', function() {\n input.clear();\n input.sendKeys('123');\n expect(value.getText()).toEqual('value =');\n expect(valid.getText()).toContain('false');\n });\n \n
\n */\n 'number': numberInputType,\n\n\n /**\n * @ngdoc input\n * @name input[url]\n *\n * @description\n * Text input with URL validation. Sets the `url` validation error key if the content is not a\n * valid URL.\n *\n *
\n * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex\n * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify\n * the built-in validators (see the {@link guide/forms Forms guide})\n *
\n *\n * @param {string} ngModel Assignable AngularJS expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n * minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n * any length.\n * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n * that contains the regular expression body that will be converted to a regular expression\n * as in the ngPattern directive.\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}\n * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.\n * If the expression evaluates to a RegExp object, then this is used directly.\n * If the expression evaluates to a string, then it will be converted to a RegExp\n * after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n * `new RegExp('^abc$')`.
\n * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n * start at the index of the last search's match, thus not taking the whole input value into\n * account.\n * @param {string=} ngChange AngularJS expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n
\n \n var text = element(by.binding('url.text'));\n var valid = element(by.binding('myForm.input.$valid'));\n var input = element(by.model('url.text'));\n\n it('should initialize to model', function() {\n expect(text.getText()).toContain('http://google.com');\n expect(valid.getText()).toContain('true');\n });\n\n it('should be invalid if empty', function() {\n input.clear();\n input.sendKeys('');\n\n expect(text.getText()).toEqual('text =');\n expect(valid.getText()).toContain('false');\n });\n\n it('should be invalid if not url', function() {\n input.clear();\n input.sendKeys('box');\n\n expect(valid.getText()).toContain('false');\n });\n \n
\n */\n 'url': urlInputType,\n\n\n /**\n * @ngdoc input\n * @name input[email]\n *\n * @description\n * Text input with email validation. Sets the `email` validation error key if not a valid email\n * address.\n *\n *
\n * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex\n * used in Chromium, which may not fulfill your app's requirements.\n * If you need stricter (e.g. requiring a top-level domain), or more relaxed validation\n * (e.g. allowing IPv6 address literals) you can use `ng-pattern` or\n * modify the built-in validators (see the {@link guide/forms Forms guide}).\n *
\n *\n * @param {string} ngModel Assignable AngularJS expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n * minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n * any length.\n * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n * that contains the regular expression body that will be converted to a regular expression\n * as in the ngPattern directive.\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}\n * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.\n * If the expression evaluates to a RegExp object, then this is used directly.\n * If the expression evaluates to a string, then it will be converted to a RegExp\n * after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n * `new RegExp('^abc$')`.
\n * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n * start at the index of the last search's match, thus not taking the whole input value into\n * account.\n * @param {string=} ngChange AngularJS expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n \n
\n \n Required!\n \n Not valid email!\n
\n text = {{email.text}}
\n myForm.input.$valid = {{myForm.input.$valid}}
\n myForm.input.$error = {{myForm.input.$error}}
\n myForm.$valid = {{myForm.$valid}}
\n myForm.$error.required = {{!!myForm.$error.required}}
\n myForm.$error.email = {{!!myForm.$error.email}}
\n
\n
\n \n var text = element(by.binding('email.text'));\n var valid = element(by.binding('myForm.input.$valid'));\n var input = element(by.model('email.text'));\n\n it('should initialize to model', function() {\n expect(text.getText()).toContain('me@example.com');\n expect(valid.getText()).toContain('true');\n });\n\n it('should be invalid if empty', function() {\n input.clear();\n input.sendKeys('');\n expect(text.getText()).toEqual('text =');\n expect(valid.getText()).toContain('false');\n });\n\n it('should be invalid if not email', function() {\n input.clear();\n input.sendKeys('xxx');\n\n expect(valid.getText()).toContain('false');\n });\n \n
\n */\n 'email': emailInputType,\n\n\n /**\n * @ngdoc input\n * @name input[radio]\n *\n * @description\n * HTML radio button.\n *\n * **Note:**
\n * All inputs controlled by {@link ngModel ngModel} (including those of type `radio`) will use the\n * value of their `name` attribute to determine the property under which their\n * {@link ngModel.NgModelController NgModelController} will be published on the parent\n * {@link form.FormController FormController}. Thus, if you use the same `name` for multiple\n * inputs of a form (e.g. a group of radio inputs), only _one_ `NgModelController` will be\n * published on the parent `FormController` under that name. The rest of the controllers will\n * continue to work as expected, but you won't be able to access them as properties on the parent\n * `FormController`.\n *\n *
\n *

\n * In plain HTML forms, the `name` attribute is used to identify groups of radio inputs, so\n * that the browser can manage their state (checked/unchecked) based on the state of other\n * inputs in the same group.\n *

\n *

\n * In AngularJS forms, this is not necessary. The input's state will be updated based on the\n * value of the underlying model data.\n *

\n *
\n *\n *
\n * If you omit the `name` attribute on a radio input, `ngModel` will automatically assign it a\n * unique name.\n *
\n *\n * @param {string} ngModel Assignable AngularJS expression to data-bind to.\n * @param {string} value The value to which the `ngModel` expression should be set when selected.\n * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,\n * too. Use `ngValue` if you need complex models (`number`, `object`, ...).\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} ngChange AngularJS expression to be executed when input changes due to user\n * interaction with the input element.\n * @param {string} ngValue AngularJS expression to which `ngModel` will be be set when the radio\n * is selected. Should be used instead of the `value` attribute if you need\n * a non-string `ngModel` (`boolean`, `array`, ...).\n *\n * @example\n \n \n \n
\n
\n
\n
\n color = {{color.name | json}}
\n
\n Note that `ng-value=\"specialValue\"` sets radio item's value to be the value of `$scope.specialValue`.\n
\n \n it('should change state', function() {\n var inputs = element.all(by.model('color.name'));\n var color = element(by.binding('color.name'));\n\n expect(color.getText()).toContain('blue');\n\n inputs.get(0).click();\n expect(color.getText()).toContain('red');\n\n inputs.get(1).click();\n expect(color.getText()).toContain('green');\n });\n \n
\n */\n 'radio': radioInputType,\n\n /**\n * @ngdoc input\n * @name input[range]\n *\n * @description\n * Native range input with validation and transformation.\n *\n * The model for the range input must always be a `Number`.\n *\n * IE9 and other browsers that do not support the `range` type fall back\n * to a text input without any default values for `min`, `max` and `step`. Model binding,\n * validation and number parsing are nevertheless supported.\n *\n * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]`\n * in a way that never allows the input to hold an invalid value. That means:\n * - any non-numerical value is set to `(max + min) / 2`.\n * - any numerical value that is less than the current min val, or greater than the current max val\n * is set to the min / max val respectively.\n * - additionally, the current `step` is respected, so the nearest value that satisfies a step\n * is used.\n *\n * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))\n * for more info.\n *\n * This has the following consequences for AngularJS:\n *\n * Since the element value should always reflect the current model value, a range input\n * will set the bound ngModel expression to the value that the browser has set for the\n * input element. For example, in the following input ``,\n * if the application sets `model.value = null`, the browser will set the input to `'50'`.\n * AngularJS will then set the model to `50`, to prevent input and model value being out of sync.\n *\n * That means the model for range will immediately be set to `50` after `ngModel` has been\n * initialized. It also means a range input can never have the required error.\n *\n * This does not only affect changes to the model value, but also to the values of the `min`,\n * `max`, and `step` attributes. When these change in a way that will cause the browser to modify\n * the input value, AngularJS will also update the model value.\n *\n * Automatic value adjustment also means that a range input element can never have the `required`,\n * `min`, or `max` errors.\n *\n * However, `step` is currently only fully implemented by Firefox. Other browsers have problems\n * when the step value changes dynamically - they do not adjust the element value correctly, but\n * instead may set the `stepMismatch` error. If that's the case, the AngularJS will set the `step`\n * error on the input, and set the model to `undefined`.\n *\n * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do\n * not set the `min` and `max` attributes, which means that the browser won't automatically adjust\n * the input value based on their values, and will always assume min = 0, max = 100, and step = 1.\n *\n * @param {string} ngModel Assignable AngularJS expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} min Sets the `min` validation to ensure that the value entered is greater\n * than `min`. Can be interpolated.\n * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`.\n * Can be interpolated.\n * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`\n * Can be interpolated.\n * @param {expression=} ngChange AngularJS expression to be executed when the ngModel value changes due\n * to user interaction with the input element.\n * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the\n * element. **Note** : `ngChecked` should not be used alongside `ngModel`.\n * Checkout {@link ng.directive:ngChecked ngChecked} for usage.\n *\n * @example\n \n \n \n
\n\n Model as range: \n
\n Model as number:
\n Min:
\n Max:
\n value = {{value}}
\n myForm.range.$valid = {{myForm.range.$valid}}
\n myForm.range.$error = {{myForm.range.$error}}\n
\n
\n
\n\n * ## Range Input with ngMin & ngMax attributes\n\n * @example\n \n \n \n
\n Model as range: \n
\n Model as number:
\n Min:
\n Max:
\n value = {{value}}
\n myForm.range.$valid = {{myForm.range.$valid}}
\n myForm.range.$error = {{myForm.range.$error}}\n
\n
\n
\n\n */\n 'range': rangeInputType,\n\n /**\n * @ngdoc input\n * @name input[checkbox]\n *\n * @description\n * HTML checkbox.\n *\n * @param {string} ngModel Assignable AngularJS expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {expression=} ngTrueValue The value to which the expression should be set when selected.\n * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.\n * @param {string=} ngChange AngularJS expression to be executed when input changes due to user\n * interaction with the input element.\n *\n * @example\n \n \n \n
\n
\n
\n value1 = {{checkboxModel.value1}}
\n value2 = {{checkboxModel.value2}}
\n
\n
\n \n it('should change state', function() {\n var value1 = element(by.binding('checkboxModel.value1'));\n var value2 = element(by.binding('checkboxModel.value2'));\n\n expect(value1.getText()).toContain('true');\n expect(value2.getText()).toContain('YES');\n\n element(by.model('checkboxModel.value1')).click();\n element(by.model('checkboxModel.value2')).click();\n\n expect(value1.getText()).toContain('false');\n expect(value2.getText()).toContain('NO');\n });\n \n
\n */\n 'checkbox': checkboxInputType,\n\n 'hidden': noop,\n 'button': noop,\n 'submit': noop,\n 'reset': noop,\n 'file': noop\n};\n\nfunction stringBasedInputType(ctrl) {\n ctrl.$formatters.push(function(value) {\n return ctrl.$isEmpty(value) ? value : value.toString();\n });\n}\n\nfunction textInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n stringBasedInputType(ctrl);\n}\n\nfunction baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n var type = lowercase(element[0].type);\n\n // In composition mode, users are still inputting intermediate text buffer,\n // hold the listener until composition is done.\n // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent\n if (!$sniffer.android) {\n var composing = false;\n\n element.on('compositionstart', function() {\n composing = true;\n });\n\n // Support: IE9+\n element.on('compositionupdate', function(ev) {\n // End composition when ev.data is empty string on 'compositionupdate' event.\n // When the input de-focusses (e.g. by clicking away), IE triggers 'compositionupdate'\n // instead of 'compositionend'.\n if (isUndefined(ev.data) || ev.data === '') {\n composing = false;\n }\n });\n\n element.on('compositionend', function() {\n composing = false;\n listener();\n });\n }\n\n var timeout;\n\n var listener = function(ev) {\n if (timeout) {\n $browser.defer.cancel(timeout);\n timeout = null;\n }\n if (composing) return;\n var value = element.val(),\n event = ev && ev.type;\n\n // By default we will trim the value\n // If the attribute ng-trim exists we will avoid trimming\n // If input type is 'password', the value is never trimmed\n if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {\n value = trim(value);\n }\n\n // If a control is suffering from bad input (due to native validators), browsers discard its\n // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the\n // control's value is the same empty value twice in a row.\n if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {\n ctrl.$setViewValue(value, event);\n }\n };\n\n // if the browser does support \"input\" event, we are fine - except on IE9 which doesn't fire the\n // input event on backspace, delete or cut\n if ($sniffer.hasEvent('input')) {\n element.on('input', listener);\n } else {\n var deferListener = function(ev, input, origValue) {\n if (!timeout) {\n timeout = $browser.defer(function() {\n timeout = null;\n if (!input || input.value !== origValue) {\n listener(ev);\n }\n });\n }\n };\n\n element.on('keydown', /** @this */ function(event) {\n var key = event.keyCode;\n\n // ignore\n // command modifiers arrows\n if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;\n\n deferListener(event, this, this.value);\n });\n\n // if user modifies input value using context menu in IE, we need \"paste\", \"cut\" and \"drop\" events to catch it\n if ($sniffer.hasEvent('paste')) {\n element.on('paste cut drop', deferListener);\n }\n }\n\n // if user paste into input using mouse on older browser\n // or form autocomplete on newer browser, we need \"change\" event to catch it\n element.on('change', listener);\n\n // Some native input types (date-family) have the ability to change validity without\n // firing any input/change events.\n // For these event types, when native validators are present and the browser supports the type,\n // check for validity changes on various DOM events.\n if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {\n element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {\n if (!timeout) {\n var validity = this[VALIDITY_STATE_PROPERTY];\n var origBadInput = validity.badInput;\n var origTypeMismatch = validity.typeMismatch;\n timeout = $browser.defer(function() {\n timeout = null;\n if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {\n listener(ev);\n }\n });\n }\n });\n }\n\n ctrl.$render = function() {\n // Workaround for Firefox validation #12102.\n var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;\n if (element.val() !== value) {\n element.val(value);\n }\n };\n}\n\nfunction weekParser(isoWeek, existingDate) {\n if (isDate(isoWeek)) {\n return isoWeek;\n }\n\n if (isString(isoWeek)) {\n WEEK_REGEXP.lastIndex = 0;\n var parts = WEEK_REGEXP.exec(isoWeek);\n if (parts) {\n var year = +parts[1],\n week = +parts[2],\n hours = 0,\n minutes = 0,\n seconds = 0,\n milliseconds = 0,\n firstThurs = getFirstThursdayOfYear(year),\n addDays = (week - 1) * 7;\n\n if (existingDate) {\n hours = existingDate.getHours();\n minutes = existingDate.getMinutes();\n seconds = existingDate.getSeconds();\n milliseconds = existingDate.getMilliseconds();\n }\n\n return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);\n }\n }\n\n return NaN;\n}\n\nfunction createDateParser(regexp, mapping) {\n return function(iso, previousDate) {\n var parts, map;\n\n if (isDate(iso)) {\n return iso;\n }\n\n if (isString(iso)) {\n // When a date is JSON'ified to wraps itself inside of an extra\n // set of double quotes. This makes the date parsing code unable\n // to match the date string and parse it as a date.\n if (iso.charAt(0) === '\"' && iso.charAt(iso.length - 1) === '\"') {\n iso = iso.substring(1, iso.length - 1);\n }\n if (ISO_DATE_REGEXP.test(iso)) {\n return new Date(iso);\n }\n regexp.lastIndex = 0;\n parts = regexp.exec(iso);\n\n if (parts) {\n parts.shift();\n if (previousDate) {\n map = {\n yyyy: previousDate.getFullYear(),\n MM: previousDate.getMonth() + 1,\n dd: previousDate.getDate(),\n HH: previousDate.getHours(),\n mm: previousDate.getMinutes(),\n ss: previousDate.getSeconds(),\n sss: previousDate.getMilliseconds() / 1000\n };\n } else {\n map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };\n }\n\n forEach(parts, function(part, index) {\n if (index < mapping.length) {\n map[mapping[index]] = +part;\n }\n });\n\n var date = new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);\n if (map.yyyy < 100) {\n // In the constructor, 2-digit years map to 1900-1999.\n // Use `setFullYear()` to set the correct year.\n date.setFullYear(map.yyyy);\n }\n\n return date;\n }\n }\n\n return NaN;\n };\n}\n\nfunction createDateInputType(type, regexp, parseDate, format) {\n return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {\n badInputChecker(scope, element, attr, ctrl, type);\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n\n var isTimeType = type === 'time' || type === 'datetimelocal';\n var previousDate;\n var previousTimezone;\n\n ctrl.$parsers.push(function(value) {\n if (ctrl.$isEmpty(value)) return null;\n\n if (regexp.test(value)) {\n // Note: We cannot read ctrl.$modelValue, as there might be a different\n // parser/formatter in the processing chain so that the model\n // contains some different data format!\n return parseDateAndConvertTimeZoneToLocal(value, previousDate);\n }\n ctrl.$$parserName = type;\n return undefined;\n });\n\n ctrl.$formatters.push(function(value) {\n if (value && !isDate(value)) {\n throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);\n }\n if (isValidDate(value)) {\n previousDate = value;\n var timezone = ctrl.$options.getOption('timezone');\n\n if (timezone) {\n previousTimezone = timezone;\n previousDate = convertTimezoneToLocal(previousDate, timezone, true);\n }\n\n return formatter(value, timezone);\n } else {\n previousDate = null;\n previousTimezone = null;\n return '';\n }\n });\n\n if (isDefined(attr.min) || attr.ngMin) {\n var minVal = attr.min || $parse(attr.ngMin)(scope);\n var parsedMinVal = parseObservedDateValue(minVal);\n\n ctrl.$validators.min = function(value) {\n return !isValidDate(value) || isUndefined(parsedMinVal) || parseDate(value) >= parsedMinVal;\n };\n attr.$observe('min', function(val) {\n if (val !== minVal) {\n parsedMinVal = parseObservedDateValue(val);\n minVal = val;\n ctrl.$validate();\n }\n });\n }\n\n if (isDefined(attr.max) || attr.ngMax) {\n var maxVal = attr.max || $parse(attr.ngMax)(scope);\n var parsedMaxVal = parseObservedDateValue(maxVal);\n\n ctrl.$validators.max = function(value) {\n return !isValidDate(value) || isUndefined(parsedMaxVal) || parseDate(value) <= parsedMaxVal;\n };\n attr.$observe('max', function(val) {\n if (val !== maxVal) {\n parsedMaxVal = parseObservedDateValue(val);\n maxVal = val;\n ctrl.$validate();\n }\n });\n }\n\n function isValidDate(value) {\n // Invalid Date: getTime() returns NaN\n return value && !(value.getTime && value.getTime() !== value.getTime());\n }\n\n function parseObservedDateValue(val) {\n return isDefined(val) && !isDate(val) ? parseDateAndConvertTimeZoneToLocal(val) || undefined : val;\n }\n\n function parseDateAndConvertTimeZoneToLocal(value, previousDate) {\n var timezone = ctrl.$options.getOption('timezone');\n\n if (previousTimezone && previousTimezone !== timezone) {\n // If the timezone has changed, adjust the previousDate to the default timezone\n // so that the new date is converted with the correct timezone offset\n previousDate = addDateMinutes(previousDate, timezoneToOffset(previousTimezone));\n }\n\n var parsedDate = parseDate(value, previousDate);\n\n if (!isNaN(parsedDate) && timezone) {\n parsedDate = convertTimezoneToLocal(parsedDate, timezone);\n }\n return parsedDate;\n }\n\n function formatter(value, timezone) {\n var targetFormat = format;\n\n if (isTimeType && isString(ctrl.$options.getOption('timeSecondsFormat'))) {\n targetFormat = format\n .replace('ss.sss', ctrl.$options.getOption('timeSecondsFormat'))\n .replace(/:$/, '');\n }\n\n var formatted = $filter('date')(value, targetFormat, timezone);\n\n if (isTimeType && ctrl.$options.getOption('timeStripZeroSeconds')) {\n formatted = formatted.replace(/(?::00)?(?:\\.000)?$/, '');\n }\n\n return formatted;\n }\n };\n}\n\nfunction badInputChecker(scope, element, attr, ctrl, parserName) {\n var node = element[0];\n var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);\n if (nativeValidation) {\n ctrl.$parsers.push(function(value) {\n var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};\n if (validity.badInput || validity.typeMismatch) {\n ctrl.$$parserName = parserName;\n return undefined;\n }\n\n return value;\n });\n }\n}\n\nfunction numberFormatterParser(ctrl) {\n ctrl.$parsers.push(function(value) {\n if (ctrl.$isEmpty(value)) return null;\n if (NUMBER_REGEXP.test(value)) return parseFloat(value);\n\n ctrl.$$parserName = 'number';\n return undefined;\n });\n\n ctrl.$formatters.push(function(value) {\n if (!ctrl.$isEmpty(value)) {\n if (!isNumber(value)) {\n throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);\n }\n value = value.toString();\n }\n return value;\n });\n}\n\nfunction parseNumberAttrVal(val) {\n if (isDefined(val) && !isNumber(val)) {\n val = parseFloat(val);\n }\n return !isNumberNaN(val) ? val : undefined;\n}\n\nfunction isNumberInteger(num) {\n // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066\n // (minus the assumption that `num` is a number)\n\n // eslint-disable-next-line no-bitwise\n return (num | 0) === num;\n}\n\nfunction countDecimals(num) {\n var numString = num.toString();\n var decimalSymbolIndex = numString.indexOf('.');\n\n if (decimalSymbolIndex === -1) {\n if (-1 < num && num < 1) {\n // It may be in the exponential notation format (`1e-X`)\n var match = /e-(\\d+)$/.exec(numString);\n\n if (match) {\n return Number(match[1]);\n }\n }\n\n return 0;\n }\n\n return numString.length - decimalSymbolIndex - 1;\n}\n\nfunction isValidForStep(viewValue, stepBase, step) {\n // At this point `stepBase` and `step` are expected to be non-NaN values\n // and `viewValue` is expected to be a valid stringified number.\n var value = Number(viewValue);\n\n var isNonIntegerValue = !isNumberInteger(value);\n var isNonIntegerStepBase = !isNumberInteger(stepBase);\n var isNonIntegerStep = !isNumberInteger(step);\n\n // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or\n // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers.\n if (isNonIntegerValue || isNonIntegerStepBase || isNonIntegerStep) {\n var valueDecimals = isNonIntegerValue ? countDecimals(value) : 0;\n var stepBaseDecimals = isNonIntegerStepBase ? countDecimals(stepBase) : 0;\n var stepDecimals = isNonIntegerStep ? countDecimals(step) : 0;\n\n var decimalCount = Math.max(valueDecimals, stepBaseDecimals, stepDecimals);\n var multiplier = Math.pow(10, decimalCount);\n\n value = value * multiplier;\n stepBase = stepBase * multiplier;\n step = step * multiplier;\n\n if (isNonIntegerValue) value = Math.round(value);\n if (isNonIntegerStepBase) stepBase = Math.round(stepBase);\n if (isNonIntegerStep) step = Math.round(step);\n }\n\n return (value - stepBase) % step === 0;\n}\n\nfunction numberInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {\n badInputChecker(scope, element, attr, ctrl, 'number');\n numberFormatterParser(ctrl);\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n\n var parsedMinVal;\n\n if (isDefined(attr.min) || attr.ngMin) {\n var minVal = attr.min || $parse(attr.ngMin)(scope);\n parsedMinVal = parseNumberAttrVal(minVal);\n\n ctrl.$validators.min = function(modelValue, viewValue) {\n return ctrl.$isEmpty(viewValue) || isUndefined(parsedMinVal) || viewValue >= parsedMinVal;\n };\n\n attr.$observe('min', function(val) {\n if (val !== minVal) {\n parsedMinVal = parseNumberAttrVal(val);\n minVal = val;\n // TODO(matsko): implement validateLater to reduce number of validations\n ctrl.$validate();\n }\n });\n }\n\n if (isDefined(attr.max) || attr.ngMax) {\n var maxVal = attr.max || $parse(attr.ngMax)(scope);\n var parsedMaxVal = parseNumberAttrVal(maxVal);\n\n ctrl.$validators.max = function(modelValue, viewValue) {\n return ctrl.$isEmpty(viewValue) || isUndefined(parsedMaxVal) || viewValue <= parsedMaxVal;\n };\n\n attr.$observe('max', function(val) {\n if (val !== maxVal) {\n parsedMaxVal = parseNumberAttrVal(val);\n maxVal = val;\n // TODO(matsko): implement validateLater to reduce number of validations\n ctrl.$validate();\n }\n });\n }\n\n if (isDefined(attr.step) || attr.ngStep) {\n var stepVal = attr.step || $parse(attr.ngStep)(scope);\n var parsedStepVal = parseNumberAttrVal(stepVal);\n\n ctrl.$validators.step = function(modelValue, viewValue) {\n return ctrl.$isEmpty(viewValue) || isUndefined(parsedStepVal) ||\n isValidForStep(viewValue, parsedMinVal || 0, parsedStepVal);\n };\n\n attr.$observe('step', function(val) {\n // TODO(matsko): implement validateLater to reduce number of validations\n if (val !== stepVal) {\n parsedStepVal = parseNumberAttrVal(val);\n stepVal = val;\n ctrl.$validate();\n }\n\n });\n\n }\n}\n\nfunction rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n badInputChecker(scope, element, attr, ctrl, 'range');\n numberFormatterParser(ctrl);\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n\n var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range',\n minVal = supportsRange ? 0 : undefined,\n maxVal = supportsRange ? 100 : undefined,\n stepVal = supportsRange ? 1 : undefined,\n validity = element[0].validity,\n hasMinAttr = isDefined(attr.min),\n hasMaxAttr = isDefined(attr.max),\n hasStepAttr = isDefined(attr.step);\n\n var originalRender = ctrl.$render;\n\n ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ?\n //Browsers that implement range will set these values automatically, but reading the adjusted values after\n //$render would cause the min / max validators to be applied with the wrong value\n function rangeRender() {\n originalRender();\n ctrl.$setViewValue(element.val());\n } :\n originalRender;\n\n if (hasMinAttr) {\n minVal = parseNumberAttrVal(attr.min);\n\n ctrl.$validators.min = supportsRange ?\n // Since all browsers set the input to a valid value, we don't need to check validity\n function noopMinValidator() { return true; } :\n // non-support browsers validate the min val\n function minValidator(modelValue, viewValue) {\n return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;\n };\n\n setInitialValueAndObserver('min', minChange);\n }\n\n if (hasMaxAttr) {\n maxVal = parseNumberAttrVal(attr.max);\n\n ctrl.$validators.max = supportsRange ?\n // Since all browsers set the input to a valid value, we don't need to check validity\n function noopMaxValidator() { return true; } :\n // non-support browsers validate the max val\n function maxValidator(modelValue, viewValue) {\n return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;\n };\n\n setInitialValueAndObserver('max', maxChange);\n }\n\n if (hasStepAttr) {\n stepVal = parseNumberAttrVal(attr.step);\n\n ctrl.$validators.step = supportsRange ?\n function nativeStepValidator() {\n // Currently, only FF implements the spec on step change correctly (i.e. adjusting the\n // input element value to a valid value). It's possible that other browsers set the stepMismatch\n // validity error instead, so we can at least report an error in that case.\n return !validity.stepMismatch;\n } :\n // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would\n function stepValidator(modelValue, viewValue) {\n return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||\n isValidForStep(viewValue, minVal || 0, stepVal);\n };\n\n setInitialValueAndObserver('step', stepChange);\n }\n\n function setInitialValueAndObserver(htmlAttrName, changeFn) {\n // interpolated attributes set the attribute value only after a digest, but we need the\n // attribute value when the input is first rendered, so that the browser can adjust the\n // input value based on the min/max value\n element.attr(htmlAttrName, attr[htmlAttrName]);\n var oldVal = attr[htmlAttrName];\n attr.$observe(htmlAttrName, function wrappedObserver(val) {\n if (val !== oldVal) {\n oldVal = val;\n changeFn(val);\n }\n });\n }\n\n function minChange(val) {\n minVal = parseNumberAttrVal(val);\n // ignore changes before model is initialized\n if (isNumberNaN(ctrl.$modelValue)) {\n return;\n }\n\n if (supportsRange) {\n var elVal = element.val();\n // IE11 doesn't set the el val correctly if the minVal is greater than the element value\n if (minVal > elVal) {\n elVal = minVal;\n element.val(elVal);\n }\n ctrl.$setViewValue(elVal);\n } else {\n // TODO(matsko): implement validateLater to reduce number of validations\n ctrl.$validate();\n }\n }\n\n function maxChange(val) {\n maxVal = parseNumberAttrVal(val);\n // ignore changes before model is initialized\n if (isNumberNaN(ctrl.$modelValue)) {\n return;\n }\n\n if (supportsRange) {\n var elVal = element.val();\n // IE11 doesn't set the el val correctly if the maxVal is less than the element value\n if (maxVal < elVal) {\n element.val(maxVal);\n // IE11 and Chrome don't set the value to the minVal when max < min\n elVal = maxVal < minVal ? minVal : maxVal;\n }\n ctrl.$setViewValue(elVal);\n } else {\n // TODO(matsko): implement validateLater to reduce number of validations\n ctrl.$validate();\n }\n }\n\n function stepChange(val) {\n stepVal = parseNumberAttrVal(val);\n // ignore changes before model is initialized\n if (isNumberNaN(ctrl.$modelValue)) {\n return;\n }\n\n // Some browsers don't adjust the input value correctly, but set the stepMismatch error\n if (!supportsRange) {\n // TODO(matsko): implement validateLater to reduce number of validations\n ctrl.$validate();\n } else if (ctrl.$viewValue !== element.val()) {\n ctrl.$setViewValue(element.val());\n }\n }\n}\n\nfunction urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n // Note: no badInputChecker here by purpose as `url` is only a validation\n // in browsers, i.e. we can always read out input.value even if it is not valid!\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n stringBasedInputType(ctrl);\n\n ctrl.$validators.url = function(modelValue, viewValue) {\n var value = modelValue || viewValue;\n return ctrl.$isEmpty(value) || URL_REGEXP.test(value);\n };\n}\n\nfunction emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n // Note: no badInputChecker here by purpose as `url` is only a validation\n // in browsers, i.e. we can always read out input.value even if it is not valid!\n baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n stringBasedInputType(ctrl);\n\n ctrl.$validators.email = function(modelValue, viewValue) {\n var value = modelValue || viewValue;\n return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);\n };\n}\n\nfunction radioInputType(scope, element, attr, ctrl) {\n var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false';\n // make the name unique, if not defined\n if (isUndefined(attr.name)) {\n element.attr('name', nextUid());\n }\n\n var listener = function(ev) {\n var value;\n if (element[0].checked) {\n value = attr.value;\n if (doTrim) {\n value = trim(value);\n }\n ctrl.$setViewValue(value, ev && ev.type);\n }\n };\n\n element.on('change', listener);\n\n ctrl.$render = function() {\n var value = attr.value;\n if (doTrim) {\n value = trim(value);\n }\n element[0].checked = (value === ctrl.$viewValue);\n };\n\n attr.$observe('value', ctrl.$render);\n}\n\nfunction parseConstantExpr($parse, context, name, expression, fallback) {\n var parseFn;\n if (isDefined(expression)) {\n parseFn = $parse(expression);\n if (!parseFn.constant) {\n throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +\n '`{1}`.', name, expression);\n }\n return parseFn(context);\n }\n return fallback;\n}\n\nfunction checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {\n var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);\n var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);\n\n var listener = function(ev) {\n ctrl.$setViewValue(element[0].checked, ev && ev.type);\n };\n\n element.on('change', listener);\n\n ctrl.$render = function() {\n element[0].checked = ctrl.$viewValue;\n };\n\n // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`\n // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert\n // it to a boolean.\n ctrl.$isEmpty = function(value) {\n return value === false;\n };\n\n ctrl.$formatters.push(function(value) {\n return equals(value, trueValue);\n });\n\n ctrl.$parsers.push(function(value) {\n return value ? trueValue : falseValue;\n });\n}\n\n\n/**\n * @ngdoc directive\n * @name textarea\n * @restrict E\n *\n * @description\n * HTML textarea element control with AngularJS data-binding. The data-binding and validation\n * properties of this element are exactly the same as those of the\n * {@link ng.directive:input input element}.\n *\n * @param {string} ngModel Assignable AngularJS expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n * `required` when you want to data-bind to the `required` attribute.\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n * minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any\n * length.\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}\n * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.\n * If the expression evaluates to a RegExp object, then this is used directly.\n * If the expression evaluates to a string, then it will be converted to a RegExp\n * after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n * `new RegExp('^abc$')`.
\n * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n * start at the index of the last search's match, thus not taking the whole input value into\n * account.\n * @param {string=} ngChange AngularJS expression to be executed when input changes due to user\n * interaction with the input element.\n * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input.\n *\n * @knownIssue\n *\n * When specifying the `placeholder` attribute of `\n *
{{ list | json }}
\n * \n * \n * it(\"should split the text by newlines\", function() {\n * var listInput = element(by.model('list'));\n * var output = element(by.binding('list | json'));\n * listInput.sendKeys('abc\\ndef\\nghi');\n * expect(output.getText()).toContain('[\\n \"abc\",\\n \"def\",\\n \"ghi\"\\n]');\n * });\n * \n * \n *\n */\nvar ngListDirective = function() {\n return {\n restrict: 'A',\n priority: 100,\n require: 'ngModel',\n link: function(scope, element, attr, ctrl) {\n var ngList = attr.ngList || ', ';\n var trimValues = attr.ngTrim !== 'false';\n var separator = trimValues ? trim(ngList) : ngList;\n\n var parse = function(viewValue) {\n // If the viewValue is invalid (say required but empty) it will be `undefined`\n if (isUndefined(viewValue)) return;\n\n var list = [];\n\n if (viewValue) {\n forEach(viewValue.split(separator), function(value) {\n if (value) list.push(trimValues ? trim(value) : value);\n });\n }\n\n return list;\n };\n\n ctrl.$parsers.push(parse);\n ctrl.$formatters.push(function(value) {\n if (isArray(value)) {\n return value.join(ngList);\n }\n\n return undefined;\n });\n\n // Override the standard $isEmpty because an empty array means the input is empty.\n ctrl.$isEmpty = function(value) {\n return !value || !value.length;\n };\n }\n };\n};\n\n/* global VALID_CLASS: true,\n INVALID_CLASS: true,\n PRISTINE_CLASS: true,\n DIRTY_CLASS: true,\n UNTOUCHED_CLASS: true,\n TOUCHED_CLASS: true,\n PENDING_CLASS: true,\n addSetValidityMethod: true,\n setupValidity: true,\n defaultModelOptions: false\n*/\n\n\nvar VALID_CLASS = 'ng-valid',\n INVALID_CLASS = 'ng-invalid',\n PRISTINE_CLASS = 'ng-pristine',\n DIRTY_CLASS = 'ng-dirty',\n UNTOUCHED_CLASS = 'ng-untouched',\n TOUCHED_CLASS = 'ng-touched',\n EMPTY_CLASS = 'ng-empty',\n NOT_EMPTY_CLASS = 'ng-not-empty';\n\nvar ngModelMinErr = minErr('ngModel');\n\n/**\n * @ngdoc type\n * @name ngModel.NgModelController\n * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a\n * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue\n * is set.\n *\n * @property {*} $modelValue The value in the model that the control is bound to.\n *\n * @property {Array.} $parsers Array of functions to execute, as a pipeline, whenever\n * the control updates the ngModelController with a new {@link ngModel.NgModelController#$viewValue\n `$viewValue`} from the DOM, usually via user input.\n See {@link ngModel.NgModelController#$setViewValue `$setViewValue()`} for a detailed lifecycle explanation.\n Note that the `$parsers` are not called when the bound ngModel expression changes programmatically.\n\n The functions are called in array order, each passing\n its return value through to the next. The last return value is forwarded to the\n {@link ngModel.NgModelController#$validators `$validators`} collection.\n\n Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue\n `$viewValue`}.\n\n Returning `undefined` from a parser means a parse error occurred. In that case,\n no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`\n will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}\n is set to `true`. The parse error is stored in `ngModel.$error.parse`.\n\n This simple example shows a parser that would convert text input value to lowercase:\n * ```js\n * function parse(value) {\n * if (value) {\n * return value.toLowerCase();\n * }\n * }\n * ngModelController.$parsers.push(parse);\n * ```\n\n *\n * @property {Array.} $formatters Array of functions to execute, as a pipeline, whenever\n the bound ngModel expression changes programmatically. The `$formatters` are not called when the\n value of the control is changed by user interaction.\n\n Formatters are used to format / convert the {@link ngModel.NgModelController#$modelValue\n `$modelValue`} for display in the control.\n\n The functions are called in reverse array order, each passing the value through to the\n next. The last return value is used as the actual DOM value.\n\n This simple example shows a formatter that would convert the model value to uppercase:\n\n * ```js\n * function format(value) {\n * if (value) {\n * return value.toUpperCase();\n * }\n * }\n * ngModel.$formatters.push(format);\n * ```\n *\n * @property {Object.} $validators A collection of validators that are applied\n * whenever the model value changes. The key value within the object refers to the name of the\n * validator while the function refers to the validation operation. The validation operation is\n * provided with the model value as an argument and must return a true or false value depending\n * on the response of that validation.\n *\n * ```js\n * ngModel.$validators.validCharacters = function(modelValue, viewValue) {\n * var value = modelValue || viewValue;\n * return /[0-9]+/.test(value) &&\n * /[a-z]+/.test(value) &&\n * /[A-Z]+/.test(value) &&\n * /\\W+/.test(value);\n * };\n * ```\n *\n * @property {Object.} $asyncValidators A collection of validations that are expected to\n * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided\n * is expected to return a promise when it is run during the model validation process. Once the promise\n * is delivered then the validation status will be set to true when fulfilled and false when rejected.\n * When the asynchronous validators are triggered, each of the validators will run in parallel and the model\n * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator\n * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators\n * will only run once all synchronous validators have passed.\n *\n * Please note that if $http is used then it is important that the server returns a success HTTP response code\n * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.\n *\n * ```js\n * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {\n * var value = modelValue || viewValue;\n *\n * // Lookup user by username\n * return $http.get('/api/users/' + value).\n * then(function resolved() {\n * //username exists, this means validation fails\n * return $q.reject('exists');\n * }, function rejected() {\n * //username does not exist, therefore this validation passes\n * return true;\n * });\n * };\n * ```\n *\n * @property {Array.} $viewChangeListeners Array of functions to execute whenever\n * a change to {@link ngModel.NgModelController#$viewValue `$viewValue`} has caused a change\n * to {@link ngModel.NgModelController#$modelValue `$modelValue`}.\n * It is called with no arguments, and its return value is ignored.\n * This can be used in place of additional $watches against the model value.\n *\n * @property {Object} $error An object hash with all failing validator ids as keys.\n * @property {Object} $pending An object hash with all pending validator ids as keys.\n *\n * @property {boolean} $untouched True if control has not lost focus yet.\n * @property {boolean} $touched True if control has lost focus.\n * @property {boolean} $pristine True if user has not interacted with the control yet.\n * @property {boolean} $dirty True if user has already interacted with the control.\n * @property {boolean} $valid True if there is no error.\n * @property {boolean} $invalid True if at least one error on the control.\n * @property {string} $name The name attribute of the control.\n *\n * @description\n *\n * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.\n * The controller contains services for data-binding, validation, CSS updates, and value formatting\n * and parsing. It purposefully does not contain any logic which deals with DOM rendering or\n * listening to DOM events.\n * Such DOM related logic should be provided by other directives which make use of\n * `NgModelController` for data-binding to control elements.\n * AngularJS provides this DOM logic for most {@link input `input`} elements.\n * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example\n * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.\n *\n * @example\n * ### Custom Control Example\n * This example shows how to use `NgModelController` with a custom control to achieve\n * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)\n * collaborate together to achieve the desired result.\n *\n * `contenteditable` is an HTML5 attribute, which tells the browser to let the element\n * contents be edited in place by the user.\n *\n * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}\n * module to automatically remove \"bad\" content like inline event listener (e.g. ``).\n * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks\n * that content using the `$sce` service.\n *\n * \n \n [contenteditable] {\n border: 1px solid black;\n background-color: white;\n min-height: 20px;\n }\n\n .ng-invalid {\n border: 1px solid red;\n }\n\n \n \n angular.module('customControl', ['ngSanitize']).\n directive('contenteditable', ['$sce', function($sce) {\n return {\n restrict: 'A', // only activate on element attribute\n require: '?ngModel', // get a hold of NgModelController\n link: function(scope, element, attrs, ngModel) {\n if (!ngModel) return; // do nothing if no ng-model\n\n // Specify how UI should be updated\n ngModel.$render = function() {\n element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));\n };\n\n // Listen for change events to enable binding\n element.on('blur keyup change', function() {\n scope.$evalAsync(read);\n });\n read(); // initialize\n\n // Write data to the model\n function read() {\n var html = element.html();\n // When we clear the content editable the browser leaves a
behind\n // If strip-br attribute is provided then we strip this out\n if (attrs.stripBr && html === '
') {\n html = '';\n }\n ngModel.$setViewValue(html);\n }\n }\n };\n }]);\n
\n \n
\n
Change me!
\n Required!\n
\n \n
\n
\n \n it('should data-bind and become invalid', function() {\n if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') {\n // SafariDriver can't handle contenteditable\n // and Firefox driver can't clear contenteditables very well\n return;\n }\n var contentEditable = element(by.css('[contenteditable]'));\n var content = 'Change me!';\n\n expect(contentEditable.getText()).toEqual(content);\n\n contentEditable.clear();\n contentEditable.sendKeys(protractor.Key.BACK_SPACE);\n expect(contentEditable.getText()).toEqual('');\n expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);\n });\n \n *
\n *\n *\n */\nNgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate'];\nfunction NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) {\n this.$viewValue = Number.NaN;\n this.$modelValue = Number.NaN;\n this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.\n this.$validators = {};\n this.$asyncValidators = {};\n this.$parsers = [];\n this.$formatters = [];\n this.$viewChangeListeners = [];\n this.$untouched = true;\n this.$touched = false;\n this.$pristine = true;\n this.$dirty = false;\n this.$valid = true;\n this.$invalid = false;\n this.$error = {}; // keep invalid keys here\n this.$$success = {}; // keep valid keys here\n this.$pending = undefined; // keep pending keys here\n this.$name = $interpolate($attr.name || '', false)($scope);\n this.$$parentForm = nullFormCtrl;\n this.$options = defaultModelOptions;\n this.$$updateEvents = '';\n // Attach the correct context to the event handler function for updateOn\n this.$$updateEventHandler = this.$$updateEventHandler.bind(this);\n\n this.$$parsedNgModel = $parse($attr.ngModel);\n this.$$parsedNgModelAssign = this.$$parsedNgModel.assign;\n this.$$ngModelGet = this.$$parsedNgModel;\n this.$$ngModelSet = this.$$parsedNgModelAssign;\n this.$$pendingDebounce = null;\n this.$$parserValid = undefined;\n this.$$parserName = 'parse';\n\n this.$$currentValidationRunId = 0;\n\n this.$$scope = $scope;\n this.$$rootScope = $scope.$root;\n this.$$attr = $attr;\n this.$$element = $element;\n this.$$animate = $animate;\n this.$$timeout = $timeout;\n this.$$parse = $parse;\n this.$$q = $q;\n this.$$exceptionHandler = $exceptionHandler;\n\n setupValidity(this);\n setupModelWatcher(this);\n}\n\nNgModelController.prototype = {\n $$initGetterSetters: function() {\n if (this.$options.getOption('getterSetter')) {\n var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'),\n invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)');\n\n this.$$ngModelGet = function($scope) {\n var modelValue = this.$$parsedNgModel($scope);\n if (isFunction(modelValue)) {\n modelValue = invokeModelGetter($scope);\n }\n return modelValue;\n };\n this.$$ngModelSet = function($scope, newValue) {\n if (isFunction(this.$$parsedNgModel($scope))) {\n invokeModelSetter($scope, {$$$p: newValue});\n } else {\n this.$$parsedNgModelAssign($scope, newValue);\n }\n };\n } else if (!this.$$parsedNgModel.assign) {\n throw ngModelMinErr('nonassign', 'Expression \\'{0}\\' is non-assignable. Element: {1}',\n this.$$attr.ngModel, startingTag(this.$$element));\n }\n },\n\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$render\n *\n * @description\n * Called when the view needs to be updated. It is expected that the user of the ng-model\n * directive will implement this method.\n *\n * The `$render()` method is invoked in the following situations:\n *\n * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last\n * committed value then `$render()` is called to update the input control.\n * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and\n * the `$viewValue` are different from last time.\n *\n * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of\n * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`\n * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be\n * invoked if you only change a property on the objects.\n */\n $render: noop,\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$isEmpty\n *\n * @description\n * This is called when we need to determine if the value of an input is empty.\n *\n * For instance, the required directive does this to work out if the input has data or not.\n *\n * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.\n *\n * You can override this for input directives whose concept of being empty is different from the\n * default. The `checkboxInputType` directive does this because in its case a value of `false`\n * implies empty.\n *\n * @param {*} value The value of the input to check for emptiness.\n * @returns {boolean} True if `value` is \"empty\".\n */\n $isEmpty: function(value) {\n // eslint-disable-next-line no-self-compare\n return isUndefined(value) || value === '' || value === null || value !== value;\n },\n\n $$updateEmptyClasses: function(value) {\n if (this.$isEmpty(value)) {\n this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS);\n this.$$animate.addClass(this.$$element, EMPTY_CLASS);\n } else {\n this.$$animate.removeClass(this.$$element, EMPTY_CLASS);\n this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS);\n }\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$setPristine\n *\n * @description\n * Sets the control to its pristine state.\n *\n * This method can be called to remove the `ng-dirty` class and set the control to its pristine\n * state (`ng-pristine` class). A model is considered to be pristine when the control\n * has not been changed from when first compiled.\n */\n $setPristine: function() {\n this.$dirty = false;\n this.$pristine = true;\n this.$$animate.removeClass(this.$$element, DIRTY_CLASS);\n this.$$animate.addClass(this.$$element, PRISTINE_CLASS);\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$setDirty\n *\n * @description\n * Sets the control to its dirty state.\n *\n * This method can be called to remove the `ng-pristine` class and set the control to its dirty\n * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed\n * from when first compiled.\n */\n $setDirty: function() {\n this.$dirty = true;\n this.$pristine = false;\n this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);\n this.$$animate.addClass(this.$$element, DIRTY_CLASS);\n this.$$parentForm.$setDirty();\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$setUntouched\n *\n * @description\n * Sets the control to its untouched state.\n *\n * This method can be called to remove the `ng-touched` class and set the control to its\n * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched\n * by default, however this function can be used to restore that state if the model has\n * already been touched by the user.\n */\n $setUntouched: function() {\n this.$touched = false;\n this.$untouched = true;\n this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS);\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$setTouched\n *\n * @description\n * Sets the control to its touched state.\n *\n * This method can be called to remove the `ng-untouched` class and set the control to its\n * touched state (`ng-touched` class). A model is considered to be touched when the user has\n * first focused the control element and then shifted focus away from the control (blur event).\n */\n $setTouched: function() {\n this.$touched = true;\n this.$untouched = false;\n this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS);\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$rollbackViewValue\n *\n * @description\n * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,\n * which may be caused by a pending debounced event or because the input is waiting for some\n * future event.\n *\n * If you have an input that uses `ng-model-options` to set up debounced updates or updates that\n * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of\n * sync with the ngModel's `$modelValue`.\n *\n * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update\n * and reset the input to the last committed view value.\n *\n * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`\n * programmatically before these debounced/future events have resolved/occurred, because AngularJS's\n * dirty checking mechanism is not able to tell whether the model has actually changed or not.\n *\n * The `$rollbackViewValue()` method should be called before programmatically changing the model of an\n * input which may have such events pending. This is important in order to make sure that the\n * input field will be updated with the new model value and any pending operations are cancelled.\n *\n * @example\n * \n * \n * angular.module('cancel-update-example', [])\n *\n * .controller('CancelUpdateController', ['$scope', function($scope) {\n * $scope.model = {value1: '', value2: ''};\n *\n * $scope.setEmpty = function(e, value, rollback) {\n * if (e.keyCode === 27) {\n * e.preventDefault();\n * if (rollback) {\n * $scope.myForm[value].$rollbackViewValue();\n * }\n * $scope.model[value] = '';\n * }\n * };\n * }]);\n * \n * \n *
\n *

Both of these inputs are only updated if they are blurred. Hitting escape should\n * empty them. Follow these steps and observe the difference:

\n *
    \n *
  1. Type something in the input. You will see that the model is not yet updated
  2. \n *
  3. Press the Escape key.\n *
      \n *
    1. In the first example, nothing happens, because the model is already '', and no\n * update is detected. If you blur the input, the model will be set to the current view.\n *
    2. \n *
    3. In the second example, the pending update is cancelled, and the input is set back\n * to the last committed view value (''). Blurring the input does nothing.\n *
    4. \n *
    \n *
  4. \n *
\n *\n *
\n *
\n *

Without $rollbackViewValue():

\n * \n * value1: \"{{ model.value1 }}\"\n *
\n *\n *
\n *

With $rollbackViewValue():

\n * \n * value2: \"{{ model.value2 }}\"\n *
\n *
\n *
\n *
\n \n div {\n display: table-cell;\n }\n div:nth-child(1) {\n padding-right: 30px;\n }\n\n \n *
\n */\n $rollbackViewValue: function() {\n this.$$timeout.cancel(this.$$pendingDebounce);\n this.$viewValue = this.$$lastCommittedViewValue;\n this.$render();\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$validate\n *\n * @description\n * Runs each of the registered validators (first synchronous validators and then\n * asynchronous validators).\n * If the validity changes to invalid, the model will be set to `undefined`,\n * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.\n * If the validity changes to valid, it will set the model to the last available valid\n * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.\n */\n $validate: function() {\n\n // ignore $validate before model is initialized\n if (isNumberNaN(this.$modelValue)) {\n return;\n }\n\n var viewValue = this.$$lastCommittedViewValue;\n // Note: we use the $$rawModelValue as $modelValue might have been\n // set to undefined during a view -> model update that found validation\n // errors. We can't parse the view here, since that could change\n // the model although neither viewValue nor the model on the scope changed\n var modelValue = this.$$rawModelValue;\n\n var prevValid = this.$valid;\n var prevModelValue = this.$modelValue;\n\n var allowInvalid = this.$options.getOption('allowInvalid');\n\n var that = this;\n this.$$runValidators(modelValue, viewValue, function(allValid) {\n // If there was no change in validity, don't update the model\n // This prevents changing an invalid modelValue to undefined\n if (!allowInvalid && prevValid !== allValid) {\n // Note: Don't check this.$valid here, as we could have\n // external validators (e.g. calculated on the server),\n // that just call $setValidity and need the model value\n // to calculate their validity.\n that.$modelValue = allValid ? modelValue : undefined;\n\n if (that.$modelValue !== prevModelValue) {\n that.$$writeModelToScope();\n }\n }\n });\n },\n\n $$runValidators: function(modelValue, viewValue, doneCallback) {\n this.$$currentValidationRunId++;\n var localValidationRunId = this.$$currentValidationRunId;\n var that = this;\n\n // check parser error\n if (!processParseErrors()) {\n validationDone(false);\n return;\n }\n if (!processSyncValidators()) {\n validationDone(false);\n return;\n }\n processAsyncValidators();\n\n function processParseErrors() {\n var errorKey = that.$$parserName;\n\n if (isUndefined(that.$$parserValid)) {\n setValidity(errorKey, null);\n } else {\n if (!that.$$parserValid) {\n forEach(that.$validators, function(v, name) {\n setValidity(name, null);\n });\n forEach(that.$asyncValidators, function(v, name) {\n setValidity(name, null);\n });\n }\n\n // Set the parse error last, to prevent unsetting it, should a $validators key == parserName\n setValidity(errorKey, that.$$parserValid);\n return that.$$parserValid;\n }\n return true;\n }\n\n function processSyncValidators() {\n var syncValidatorsValid = true;\n forEach(that.$validators, function(validator, name) {\n var result = Boolean(validator(modelValue, viewValue));\n syncValidatorsValid = syncValidatorsValid && result;\n setValidity(name, result);\n });\n if (!syncValidatorsValid) {\n forEach(that.$asyncValidators, function(v, name) {\n setValidity(name, null);\n });\n return false;\n }\n return true;\n }\n\n function processAsyncValidators() {\n var validatorPromises = [];\n var allValid = true;\n forEach(that.$asyncValidators, function(validator, name) {\n var promise = validator(modelValue, viewValue);\n if (!isPromiseLike(promise)) {\n throw ngModelMinErr('nopromise',\n 'Expected asynchronous validator to return a promise but got \\'{0}\\' instead.', promise);\n }\n setValidity(name, undefined);\n validatorPromises.push(promise.then(function() {\n setValidity(name, true);\n }, function() {\n allValid = false;\n setValidity(name, false);\n }));\n });\n if (!validatorPromises.length) {\n validationDone(true);\n } else {\n that.$$q.all(validatorPromises).then(function() {\n validationDone(allValid);\n }, noop);\n }\n }\n\n function setValidity(name, isValid) {\n if (localValidationRunId === that.$$currentValidationRunId) {\n that.$setValidity(name, isValid);\n }\n }\n\n function validationDone(allValid) {\n if (localValidationRunId === that.$$currentValidationRunId) {\n\n doneCallback(allValid);\n }\n }\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$commitViewValue\n *\n * @description\n * Commit a pending update to the `$modelValue`.\n *\n * Updates may be pending by a debounced event or because the input is waiting for a some future\n * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`\n * usually handles calling this in response to input events.\n */\n $commitViewValue: function() {\n var viewValue = this.$viewValue;\n\n this.$$timeout.cancel(this.$$pendingDebounce);\n\n // If the view value has not changed then we should just exit, except in the case where there is\n // a native validator on the element. In this case the validation state may have changed even though\n // the viewValue has stayed empty.\n if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) {\n return;\n }\n this.$$updateEmptyClasses(viewValue);\n this.$$lastCommittedViewValue = viewValue;\n\n // change to dirty\n if (this.$pristine) {\n this.$setDirty();\n }\n this.$$parseAndValidate();\n },\n\n $$parseAndValidate: function() {\n var viewValue = this.$$lastCommittedViewValue;\n var modelValue = viewValue;\n var that = this;\n\n this.$$parserValid = isUndefined(modelValue) ? undefined : true;\n\n // Reset any previous parse error\n this.$setValidity(this.$$parserName, null);\n this.$$parserName = 'parse';\n\n if (this.$$parserValid) {\n for (var i = 0; i < this.$parsers.length; i++) {\n modelValue = this.$parsers[i](modelValue);\n if (isUndefined(modelValue)) {\n this.$$parserValid = false;\n break;\n }\n }\n }\n if (isNumberNaN(this.$modelValue)) {\n // this.$modelValue has not been touched yet...\n this.$modelValue = this.$$ngModelGet(this.$$scope);\n }\n var prevModelValue = this.$modelValue;\n var allowInvalid = this.$options.getOption('allowInvalid');\n this.$$rawModelValue = modelValue;\n\n if (allowInvalid) {\n this.$modelValue = modelValue;\n writeToModelIfNeeded();\n }\n\n // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.\n // This can happen if e.g. $setViewValue is called from inside a parser\n this.$$runValidators(modelValue, this.$$lastCommittedViewValue, function(allValid) {\n if (!allowInvalid) {\n // Note: Don't check this.$valid here, as we could have\n // external validators (e.g. calculated on the server),\n // that just call $setValidity and need the model value\n // to calculate their validity.\n that.$modelValue = allValid ? modelValue : undefined;\n writeToModelIfNeeded();\n }\n });\n\n function writeToModelIfNeeded() {\n if (that.$modelValue !== prevModelValue) {\n that.$$writeModelToScope();\n }\n }\n },\n\n $$writeModelToScope: function() {\n this.$$ngModelSet(this.$$scope, this.$modelValue);\n forEach(this.$viewChangeListeners, function(listener) {\n try {\n listener();\n } catch (e) {\n // eslint-disable-next-line no-invalid-this\n this.$$exceptionHandler(e);\n }\n }, this);\n },\n\n /**\n * @ngdoc method\n * @name ngModel.NgModelController#$setViewValue\n *\n * @description\n * Update the view value.\n *\n * This method should be called when a control wants to change the view value; typically,\n * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}\n * directive calls it when the value of the input changes and {@link ng.directive:select select}\n * calls it when an option is selected.\n *\n * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`\n * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged\n * value is sent directly for processing through the `$parsers` pipeline. After this, the `$validators` and\n * `$asyncValidators` are called and the value is applied to `$modelValue`.\n * Finally, the value is set to the **expression** specified in the `ng-model` attribute and\n * all the registered change listeners, in the `$viewChangeListeners` list are called.\n *\n * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`\n * and the `default` trigger is not listed, all those actions will remain pending until one of the\n * `updateOn` events is triggered on the DOM element.\n * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}\n * directive is used with a custom debounce for this particular event.\n * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`\n * is specified, once the timer runs out.\n *\n * When used with standard inputs, the view value will always be a string (which is in some cases\n * parsed into another type, such as a `Date` object for `input[date]`.)\n * However, custom controls might also pass objects to this method. In this case, we should make\n * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not\n * perform a deep watch of objects, it only looks for a change of identity. If you only change\n * the property of the object then ngModel will not realize that the object has changed and\n * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should\n * not change properties of the copy once it has been passed to `$setViewValue`.\n * Otherwise you may cause the model value on the scope to change incorrectly.\n *\n *
\n * In any case, the value passed to the method should always reflect the current value\n * of the control. For example, if you are calling `$setViewValue` for an input element,\n * you should pass the input DOM value. Otherwise, the control and the scope model become\n * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change\n * the control's DOM value in any way. If we want to change the control's DOM value\n * programmatically, we should update the `ngModel` scope expression. Its new value will be\n * picked up by the model controller, which will run it through the `$formatters`, `$render` it\n * to update the DOM, and finally call `$validate` on it.\n *
\n *\n * @param {*} value value from the view.\n * @param {string} trigger Event that triggered the update.\n */\n $setViewValue: function(value, trigger) {\n this.$viewValue = value;\n if (this.$options.getOption('updateOnDefault')) {\n this.$$debounceViewValueCommit(trigger);\n }\n },\n\n $$debounceViewValueCommit: function(trigger) {\n var debounceDelay = this.$options.getOption('debounce');\n\n if (isNumber(debounceDelay[trigger])) {\n debounceDelay = debounceDelay[trigger];\n } else if (isNumber(debounceDelay['default']) &&\n this.$options.getOption('updateOn').indexOf(trigger) === -1\n ) {\n debounceDelay = debounceDelay['default'];\n } else if (isNumber(debounceDelay['*'])) {\n debounceDelay = debounceDelay['*'];\n }\n\n this.$$timeout.cancel(this.$$pendingDebounce);\n var that = this;\n if (debounceDelay > 0) { // this fails if debounceDelay is an object\n this.$$pendingDebounce = this.$$timeout(function() {\n that.$commitViewValue();\n }, debounceDelay);\n } else if (this.$$rootScope.$$phase) {\n this.$commitViewValue();\n } else {\n this.$$scope.$apply(function() {\n that.$commitViewValue();\n });\n }\n },\n\n /**\n * @ngdoc method\n *\n * @name ngModel.NgModelController#$overrideModelOptions\n *\n * @description\n *\n * Override the current model options settings programmatically.\n *\n * The previous `ModelOptions` value will not be modified. Instead, a\n * new `ModelOptions` object will inherit from the previous one overriding\n * or inheriting settings that are defined in the given parameter.\n *\n * See {@link ngModelOptions} for information about what options can be specified\n * and how model option inheritance works.\n *\n *
\n * **Note:** this function only affects the options set on the `ngModelController`,\n * and not the options on the {@link ngModelOptions} directive from which they might have been\n * obtained initially.\n *
\n *\n *
\n * **Note:** it is not possible to override the `getterSetter` option.\n *
\n *\n * @param {Object} options a hash of settings to override the previous options\n *\n */\n $overrideModelOptions: function(options) {\n this.$options = this.$options.createChild(options);\n this.$$setUpdateOnEvents();\n },\n\n /**\n * @ngdoc method\n *\n * @name ngModel.NgModelController#$processModelValue\n\n * @description\n *\n * Runs the model -> view pipeline on the current\n * {@link ngModel.NgModelController#$modelValue $modelValue}.\n *\n * The following actions are performed by this method:\n *\n * - the `$modelValue` is run through the {@link ngModel.NgModelController#$formatters $formatters}\n * and the result is set to the {@link ngModel.NgModelController#$viewValue $viewValue}\n * - the `ng-empty` or `ng-not-empty` class is set on the element\n * - if the `$viewValue` has changed:\n * - {@link ngModel.NgModelController#$render $render} is called on the control\n * - the {@link ngModel.NgModelController#$validators $validators} are run and\n * the validation status is set.\n *\n * This method is called by ngModel internally when the bound scope value changes.\n * Application developers usually do not have to call this function themselves.\n *\n * This function can be used when the `$viewValue` or the rendered DOM value are not correctly\n * formatted and the `$modelValue` must be run through the `$formatters` again.\n *\n * @example\n * Consider a text input with an autocomplete list (for fruit), where the items are\n * objects with a name and an id.\n * A user enters `ap` and then selects `Apricot` from the list.\n * Based on this, the autocomplete widget will call `$setViewValue({name: 'Apricot', id: 443})`,\n * but the rendered value will still be `ap`.\n * The widget can then call `ctrl.$processModelValue()` to run the model -> view\n * pipeline again, which formats the object to the string `Apricot`,\n * then updates the `$viewValue`, and finally renders it in the DOM.\n *\n * \n \n
\n
\n Search Fruit:\n \n
\n
\n Model:
\n
{{selectedFruit | json}}
\n
\n
\n
\n \n angular.module('inputExample', [])\n .controller('inputController', function($scope) {\n $scope.items = [\n {name: 'Apricot', id: 443},\n {name: 'Clementine', id: 972},\n {name: 'Durian', id: 169},\n {name: 'Jackfruit', id: 982},\n {name: 'Strawberry', id: 863}\n ];\n })\n .component('basicAutocomplete', {\n bindings: {\n items: '<',\n onSelect: '&'\n },\n templateUrl: 'autocomplete.html',\n controller: function($element, $scope) {\n var that = this;\n var ngModel;\n\n that.$postLink = function() {\n ngModel = $element.find('input').controller('ngModel');\n\n ngModel.$formatters.push(function(value) {\n return (value && value.name) || value;\n });\n\n ngModel.$parsers.push(function(value) {\n var match = value;\n for (var i = 0; i < that.items.length; i++) {\n if (that.items[i].name === value) {\n match = that.items[i];\n break;\n }\n }\n\n return match;\n });\n };\n\n that.selectItem = function(item) {\n ngModel.$setViewValue(item);\n ngModel.$processModelValue();\n that.onSelect({item: item});\n };\n }\n });\n \n \n
\n \n
    \n
  • \n \n
  • \n
\n
\n
\n *
\n *\n */\n $processModelValue: function() {\n var viewValue = this.$$format();\n\n if (this.$viewValue !== viewValue) {\n this.$$updateEmptyClasses(viewValue);\n this.$viewValue = this.$$lastCommittedViewValue = viewValue;\n this.$render();\n // It is possible that model and view value have been updated during render\n this.$$runValidators(this.$modelValue, this.$viewValue, noop);\n }\n },\n\n /**\n * This method is called internally to run the $formatters on the $modelValue\n */\n $$format: function() {\n var formatters = this.$formatters,\n idx = formatters.length;\n\n var viewValue = this.$modelValue;\n while (idx--) {\n viewValue = formatters[idx](viewValue);\n }\n\n return viewValue;\n },\n\n /**\n * This method is called internally when the bound scope value changes.\n */\n $$setModelValue: function(modelValue) {\n this.$modelValue = this.$$rawModelValue = modelValue;\n this.$$parserValid = undefined;\n this.$processModelValue();\n },\n\n $$setUpdateOnEvents: function() {\n if (this.$$updateEvents) {\n this.$$element.off(this.$$updateEvents, this.$$updateEventHandler);\n }\n\n this.$$updateEvents = this.$options.getOption('updateOn');\n if (this.$$updateEvents) {\n this.$$element.on(this.$$updateEvents, this.$$updateEventHandler);\n }\n },\n\n $$updateEventHandler: function(ev) {\n this.$$debounceViewValueCommit(ev && ev.type);\n }\n};\n\nfunction setupModelWatcher(ctrl) {\n // model -> value\n // Note: we cannot use a normal scope.$watch as we want to detect the following:\n // 1. scope value is 'a'\n // 2. user enters 'b'\n // 3. ng-change kicks in and reverts scope value to 'a'\n // -> scope value did not change since the last digest as\n // ng-change executes in apply phase\n // 4. view should be changed back to 'a'\n ctrl.$$scope.$watch(function ngModelWatch(scope) {\n var modelValue = ctrl.$$ngModelGet(scope);\n\n // if scope model value and ngModel value are out of sync\n // This cannot be moved to the action function, because it would not catch the\n // case where the model is changed in the ngChange function or the model setter\n if (modelValue !== ctrl.$modelValue &&\n // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator\n // eslint-disable-next-line no-self-compare\n (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)\n ) {\n ctrl.$$setModelValue(modelValue);\n }\n\n return modelValue;\n });\n}\n\n/**\n * @ngdoc method\n * @name ngModel.NgModelController#$setValidity\n *\n * @description\n * Change the validity state, and notify the form.\n *\n * This method can be called within $parsers/$formatters or a custom validation implementation.\n * However, in most cases it should be sufficient to use the `ngModel.$validators` and\n * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.\n *\n * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned\n * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`\n * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.\n * The `validationErrorKey` should be in camelCase and will get converted into dash-case\n * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`\n * classes and can be bound to as `{{ someForm.someControl.$error.myError }}`.\n * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),\n * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.\n * Skipped is used by AngularJS when validators do not run because of parse errors and\n * when `$asyncValidators` do not run because any of the `$validators` failed.\n */\naddSetValidityMethod({\n clazz: NgModelController,\n set: function(object, property) {\n object[property] = true;\n },\n unset: function(object, property) {\n delete object[property];\n }\n});\n\n\n/**\n * @ngdoc directive\n * @name ngModel\n * @restrict A\n * @priority 1\n * @param {expression} ngModel assignable {@link guide/expression Expression} to bind to.\n *\n * @description\n * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a\n * property on the scope using {@link ngModel.NgModelController NgModelController},\n * which is created and exposed by this directive.\n *\n * `ngModel` is responsible for:\n *\n * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`\n * require.\n * - Providing validation behavior (i.e. required, number, email, url).\n * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).\n * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,\n * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.\n * - Registering the control with its parent {@link ng.directive:form form}.\n *\n * Note: `ngModel` will try to bind to the property given by evaluating the expression on the\n * current scope. If the property doesn't already exist on this scope, it will be created\n * implicitly and added to the scope.\n *\n * For best practices on using `ngModel`, see:\n *\n * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)\n *\n * For basic examples, how to use `ngModel`, see:\n *\n * - {@link ng.directive:input input}\n * - {@link input[text] text}\n * - {@link input[checkbox] checkbox}\n * - {@link input[radio] radio}\n * - {@link input[number] number}\n * - {@link input[email] email}\n * - {@link input[url] url}\n * - {@link input[date] date}\n * - {@link input[datetime-local] datetime-local}\n * - {@link input[time] time}\n * - {@link input[month] month}\n * - {@link input[week] week}\n * - {@link ng.directive:select select}\n * - {@link ng.directive:textarea textarea}\n *\n * ## Complex Models (objects or collections)\n *\n * By default, `ngModel` watches the model by reference, not value. This is important to know when\n * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the\n * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.\n *\n * The model must be assigned an entirely new object or collection before a re-rendering will occur.\n *\n * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression\n * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or\n * if the select is given the `multiple` attribute.\n *\n * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the\n * first level of the object (or only changing the properties of an item in the collection if it's an array) will still\n * not trigger a re-rendering of the model.\n *\n * ## CSS classes\n * The following CSS classes are added and removed on the associated input/select/textarea element\n * depending on the validity of the model.\n *\n * - `ng-valid`: the model is valid\n * - `ng-invalid`: the model is invalid\n * - `ng-valid-[key]`: for each valid key added by `$setValidity`\n * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`\n * - `ng-pristine`: the control hasn't been interacted with yet\n * - `ng-dirty`: the control has been interacted with\n * - `ng-touched`: the control has been blurred\n * - `ng-untouched`: the control hasn't been blurred\n * - `ng-pending`: any `$asyncValidators` are unfulfilled\n * - `ng-empty`: the view does not contain a value or the value is deemed \"empty\", as defined\n * by the {@link ngModel.NgModelController#$isEmpty} method\n * - `ng-not-empty`: the view contains a non-empty value\n *\n * Keep in mind that ngAnimate can detect each of these classes when added and removed.\n *\n * @animations\n * Animations within models are triggered when any of the associated CSS classes are added and removed\n * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,\n * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.\n * The animations that are triggered within ngModel are similar to how they work in ngClass and\n * animations can be hooked into using CSS transitions, keyframes as well as JS animations.\n *\n * The following example shows a simple way to utilize CSS transitions to style an input element\n * that has been rendered as invalid after it has been validated:\n *\n *
\n * //be sure to include ngAnimate as a module to hook into more\n * //advanced animations\n * .my-input {\n *   transition:0.5s linear all;\n *   background: white;\n * }\n * .my-input.ng-invalid {\n *   background: red;\n *   color:white;\n * }\n * 
\n *\n * @example\n * ### Basic Usage\n * \n \n \n \n

\n Update input to see transitions when valid/invalid.\n Integer is a valid value.\n

\n
\n \n
\n
\n *
\n *\n * @example\n * ### Binding to a getter/setter\n *\n * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a\n * function that returns a representation of the model when called with zero arguments, and sets\n * the internal state of a model when called with an argument. It's sometimes useful to use this\n * for models that have an internal representation that's different from what the model exposes\n * to the view.\n *\n *
\n * **Best Practice:** It's best to keep getters fast because AngularJS is likely to call them more\n * frequently than other parts of your code.\n *
\n *\n * You use this behavior by adding `ng-model-options=\"{ getterSetter: true }\"` to an element that\n * has `ng-model` attached to it. You can also add `ng-model-options=\"{ getterSetter: true }\"` to\n * a `
`, which will enable this behavior for all ``s within it. See\n * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.\n *\n * The following example shows how to use `ngModel` with a getter/setter:\n *\n * @example\n * \n \n
\n \n \n \n
user.name = 
\n
\n
\n \n angular.module('getterSetterExample', [])\n .controller('ExampleController', ['$scope', function($scope) {\n var _name = 'Brian';\n $scope.user = {\n name: function(newName) {\n // Note that newName can be undefined for two reasons:\n // 1. Because it is called as a getter and thus called with no arguments\n // 2. Because the property should actually be set to undefined. This happens e.g. if the\n // input is invalid\n return arguments.length ? (_name = newName) : _name;\n }\n };\n }]);\n \n *
\n */\nvar ngModelDirective = ['$rootScope', function($rootScope) {\n return {\n restrict: 'A',\n require: ['ngModel', '^?form', '^?ngModelOptions'],\n controller: NgModelController,\n // Prelink needs to run before any input directive\n // so that we can set the NgModelOptions in NgModelController\n // before anyone else uses it.\n priority: 1,\n compile: function ngModelCompile(element) {\n // Setup initial state of the control\n element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);\n\n return {\n pre: function ngModelPreLink(scope, element, attr, ctrls) {\n var modelCtrl = ctrls[0],\n formCtrl = ctrls[1] || modelCtrl.$$parentForm,\n optionsCtrl = ctrls[2];\n\n if (optionsCtrl) {\n modelCtrl.$options = optionsCtrl.$options;\n }\n\n modelCtrl.$$initGetterSetters();\n\n // notify others, especially parent forms\n formCtrl.$addControl(modelCtrl);\n\n attr.$observe('name', function(newValue) {\n if (modelCtrl.$name !== newValue) {\n modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);\n }\n });\n\n scope.$on('$destroy', function() {\n modelCtrl.$$parentForm.$removeControl(modelCtrl);\n });\n },\n post: function ngModelPostLink(scope, element, attr, ctrls) {\n var modelCtrl = ctrls[0];\n modelCtrl.$$setUpdateOnEvents();\n\n function setTouched() {\n modelCtrl.$setTouched();\n }\n\n element.on('blur', function() {\n if (modelCtrl.$touched) return;\n\n if ($rootScope.$$phase) {\n scope.$evalAsync(setTouched);\n } else {\n scope.$apply(setTouched);\n }\n });\n }\n };\n }\n };\n}];\n\n/* exported defaultModelOptions */\nvar defaultModelOptions;\nvar DEFAULT_REGEXP = /(\\s+|^)default(\\s+|$)/;\n\n/**\n * @ngdoc type\n * @name ModelOptions\n * @description\n * A container for the options set by the {@link ngModelOptions} directive\n */\nfunction ModelOptions(options) {\n this.$$options = options;\n}\n\nModelOptions.prototype = {\n\n /**\n * @ngdoc method\n * @name ModelOptions#getOption\n * @param {string} name the name of the option to retrieve\n * @returns {*} the value of the option\n * @description\n * Returns the value of the given option\n */\n getOption: function(name) {\n return this.$$options[name];\n },\n\n /**\n * @ngdoc method\n * @name ModelOptions#createChild\n * @param {Object} options a hash of options for the new child that will override the parent's options\n * @return {ModelOptions} a new `ModelOptions` object initialized with the given options.\n */\n createChild: function(options) {\n var inheritAll = false;\n\n // make a shallow copy\n options = extend({}, options);\n\n // Inherit options from the parent if specified by the value `\"$inherit\"`\n forEach(options, /** @this */ function(option, key) {\n if (option === '$inherit') {\n if (key === '*') {\n inheritAll = true;\n } else {\n options[key] = this.$$options[key];\n // `updateOn` is special so we must also inherit the `updateOnDefault` option\n if (key === 'updateOn') {\n options.updateOnDefault = this.$$options.updateOnDefault;\n }\n }\n } else {\n if (key === 'updateOn') {\n // If the `updateOn` property contains the `default` event then we have to remove\n // it from the event list and set the `updateOnDefault` flag.\n options.updateOnDefault = false;\n options[key] = trim(option.replace(DEFAULT_REGEXP, function() {\n options.updateOnDefault = true;\n return ' ';\n }));\n }\n }\n }, this);\n\n if (inheritAll) {\n // We have a property of the form: `\"*\": \"$inherit\"`\n delete options['*'];\n defaults(options, this.$$options);\n }\n\n // Finally add in any missing defaults\n defaults(options, defaultModelOptions.$$options);\n\n return new ModelOptions(options);\n }\n};\n\n\ndefaultModelOptions = new ModelOptions({\n updateOn: '',\n updateOnDefault: true,\n debounce: 0,\n getterSetter: false,\n allowInvalid: false,\n timezone: null\n});\n\n\n/**\n * @ngdoc directive\n * @name ngModelOptions\n * @restrict A\n * @priority 10\n *\n * @description\n * This directive allows you to modify the behaviour of {@link ngModel} directives within your\n * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel}\n * directives will use the options of their nearest `ngModelOptions` ancestor.\n *\n * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as\n * an AngularJS expression. This expression should evaluate to an object, whose properties contain\n * the settings. For example: `
\n *
\n * \n *
\n *
\n * ```\n *\n * the `input` element will have the following settings\n *\n * ```js\n * { allowInvalid: true, updateOn: 'default', debounce: 0 }\n * ```\n *\n * Notice that the `debounce` setting was not inherited and used the default value instead.\n *\n * You can specify that all undefined settings are automatically inherited from an ancestor by\n * including a property with key of `\"*\"` and value of `\"$inherit\"`.\n *\n * For example given the following fragment of HTML\n *\n *\n * ```html\n *
\n *
\n * \n *
\n *
\n * ```\n *\n * the `input` element will have the following settings\n *\n * ```js\n * { allowInvalid: true, updateOn: 'default', debounce: 200 }\n * ```\n *\n * Notice that the `debounce` setting now inherits the value from the outer `
` element.\n *\n * If you are creating a reusable component then you should be careful when using `\"*\": \"$inherit\"`\n * since you may inadvertently inherit a setting in the future that changes the behavior of your component.\n *\n *\n * ## Triggering and debouncing model updates\n *\n * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will\n * trigger a model update and/or a debouncing delay so that the actual update only takes place when\n * a timer expires; this timer will be reset after another change takes place.\n *\n * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might\n * be different from the value in the actual model. This means that if you update the model you\n * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in\n * order to make sure it is synchronized with the model and that any debounced action is canceled.\n *\n * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue}\n * method is by making sure the input is placed inside a form that has a `name` attribute. This is\n * important because `form` controllers are published to the related scope under the name in their\n * `name` attribute.\n *\n * Any pending changes will take place immediately when an enclosing form is submitted via the\n * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`\n * to have access to the updated model.\n *\n * ### Overriding immediate updates\n *\n * The following example shows how to override immediate updates. Changes on the inputs within the\n * form will update the model only when the control loses focus (blur event). If `escape` key is\n * pressed while the input field is focused, the value is reset to the value in the current model.\n *\n * \n * \n *
\n *
\n *
\n *
\n *
\n *
user.name = 
\n *
\n *
\n * \n * angular.module('optionsExample', [])\n * .controller('ExampleController', ['$scope', function($scope) {\n * $scope.user = { name: 'say', data: '' };\n *\n * $scope.cancel = function(e) {\n * if (e.keyCode === 27) {\n * $scope.userForm.userName.$rollbackViewValue();\n * }\n * };\n * }]);\n * \n * \n * var model = element(by.binding('user.name'));\n * var input = element(by.model('user.name'));\n * var other = element(by.model('user.data'));\n *\n * it('should allow custom events', function() {\n * input.sendKeys(' hello');\n * input.click();\n * expect(model.getText()).toEqual('say');\n * other.click();\n * expect(model.getText()).toEqual('say hello');\n * });\n *\n * it('should $rollbackViewValue when model changes', function() {\n * input.sendKeys(' hello');\n * expect(input.getAttribute('value')).toEqual('say hello');\n * input.sendKeys(protractor.Key.ESCAPE);\n * expect(input.getAttribute('value')).toEqual('say');\n * other.click();\n * expect(model.getText()).toEqual('say');\n * });\n * \n *
\n *\n * ### Debouncing updates\n *\n * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change.\n * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.\n *\n * \n * \n *
\n *
\n * Name:\n * \n *
\n *
\n *
user.name = 
\n *
\n *
\n * \n * angular.module('optionsExample', [])\n * .controller('ExampleController', ['$scope', function($scope) {\n * $scope.user = { name: 'say' };\n * }]);\n * \n *
\n *\n * ### Default events, extra triggers, and catch-all debounce values\n *\n * This example shows the relationship between \"default\" update events and\n * additional `updateOn` triggers.\n *\n * `default` events are those that are bound to the control, and when fired, update the `$viewValue`\n * via {@link ngModel.NgModelController#$setViewValue $setViewValue}. Every event that is not listed\n * in `updateOn` is considered a \"default\" event, since different control types have different\n * default events.\n *\n * The control in this example updates by \"default\", \"click\", and \"blur\", with different `debounce`\n * values. You can see that \"click\" doesn't have an individual `debounce` value -\n * therefore it uses the `*` debounce value.\n *\n * There is also a button that calls {@link ngModel.NgModelController#$setViewValue $setViewValue}\n * directly with a \"custom\" event. Since \"custom\" is not defined in the `updateOn` list,\n * it is considered a \"default\" event and will update the\n * control if \"default\" is defined in `updateOn`, and will receive the \"default\" debounce value.\n * Note that this is just to illustrate how custom controls would possibly call `$setViewValue`.\n *\n * You can change the `updateOn` and `debounce` configuration to test different scenarios. This\n * is done with {@link ngModel.NgModelController#$overrideModelOptions $overrideModelOptions}.\n *\n \n \n \n \n \n angular.module('optionsExample', [])\n .component('modelUpdateDemo', {\n templateUrl: 'template.html',\n controller: function() {\n this.name = 'Chinua';\n\n this.options = {\n updateOn: 'default blur click',\n debounce: {\n default: 2000,\n blur: 0,\n '*': 1000\n }\n };\n\n this.updateEvents = function() {\n var eventList = this.options.updateOn.split(' ');\n eventList.push('*');\n var events = {};\n\n for (var i = 0; i < eventList.length; i++) {\n events[eventList[i]] = this.options.debounce[eventList[i]];\n }\n\n this.events = events;\n };\n\n this.updateOptions = function() {\n var options = angular.extend(this.options, {\n updateOn: Object.keys(this.events).join(' ').replace('*', ''),\n debounce: this.events\n });\n\n this.form.input.$overrideModelOptions(options);\n };\n\n // Initialize the event form\n this.updateEvents();\n }\n });\n \n \n
\n Input: \n
\n Model: {{$ctrl.name}}\n
\n \n\n
\n
\n updateOn
\n \n\n \n \n \n \n \n \n \n \n \n
OptionDebounce value
{{key}}
\n\n
\n \n
\n
\n
\n *\n *\n * ## Model updates and validation\n *\n * The default behaviour in `ngModel` is that the model value is set to `undefined` when the\n * validation determines that the value is invalid. By setting the `allowInvalid` property to true,\n * the model will still be updated even if the value is invalid.\n *\n *\n * ## Connecting to the scope\n *\n * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression\n * on the scope refers to a \"getter/setter\" function rather than the value itself.\n *\n * The following example shows how to bind to getter/setters:\n *\n * \n * \n *
\n *
\n * \n *
\n *
user.name = 
\n *
\n *
\n * \n * angular.module('getterSetterExample', [])\n * .controller('ExampleController', ['$scope', function($scope) {\n * var _name = 'Brian';\n * $scope.user = {\n * name: function(newName) {\n * return angular.isDefined(newName) ? (_name = newName) : _name;\n * }\n * };\n * }]);\n * \n *
\n *\n *\n * ## Programmatically changing options\n *\n * The `ngModelOptions` expression is only evaluated once when the directive is linked; it is not\n * watched for changes. However, it is possible to override the options on a single\n * {@link ngModel.NgModelController} instance with\n * {@link ngModel.NgModelController#$overrideModelOptions `NgModelController#$overrideModelOptions()`}.\n * See also the example for\n * {@link ngModelOptions#default-events-extra-triggers-and-catch-all-debounce-values\n * Default events, extra triggers, and catch-all debounce values}.\n *\n *\n * ## Specifying timezones\n *\n * You can specify the timezone that date/time input directives expect by providing its name in the\n * `timezone` property.\n *\n *\n * ## Formatting the value of `time` and `datetime-local`\n *\n * With the options `timeSecondsFormat` and `timeStripZeroSeconds` it is possible to adjust the value\n * that is displayed in the control. Note that browsers may apply their own formatting\n * in the user interface.\n *\n \n \n \n \n \n angular.module('timeExample', [])\n .component('timeExample', {\n templateUrl: 'timeExample.html',\n controller: function() {\n this.time = new Date(1970, 0, 1, 14, 57, 0);\n\n this.options = {\n timeSecondsFormat: 'ss',\n timeStripZeroSeconds: true\n };\n\n this.optionChange = function() {\n this.timeForm.timeFormatted.$overrideModelOptions(this.options);\n this.time = new Date(this.time);\n };\n }\n });\n \n \n
\n Default:\n
\n With options:\n \n
\n\n Options:
\n timeSecondsFormat:\n \n
\n timeStripZeroSeconds:\n \n \n
\n *
\n *\n * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and\n * and its descendents.\n *\n * **General options**:\n *\n * - `updateOn`: string specifying which event should the input be bound to. You can set several\n * events using an space delimited list. There is a special event called `default` that\n * matches the default events belonging to the control. These are the events that are bound to\n * the control, and when fired, update the `$viewValue` via `$setViewValue`.\n *\n * `ngModelOptions` considers every event that is not listed in `updateOn` a \"default\" event,\n * since different control types use different default events.\n *\n * See also the section {@link ngModelOptions#triggering-and-debouncing-model-updates\n * Triggering and debouncing model updates}.\n *\n * - `debounce`: integer value which contains the debounce model update value in milliseconds. A\n * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a\n * custom value for each event. For example:\n * ```\n * ng-model-options=\"{\n * updateOn: 'default blur',\n * debounce: { 'default': 500, 'blur': 0 }\n * }\"\n * ```\n * You can use the `*` key to specify a debounce value that applies to all events that are not\n * specifically listed. In the following example, `mouseup` would have a debounce delay of 1000:\n * ```\n * ng-model-options=\"{\n * updateOn: 'default blur mouseup',\n * debounce: { 'default': 500, 'blur': 0, '*': 1000 }\n * }\"\n * ```\n * - `allowInvalid`: boolean value which indicates that the model can be set with values that did\n * not validate correctly instead of the default behavior of setting the model to undefined.\n * - `getterSetter`: boolean value which determines whether or not to treat functions bound to\n * `ngModel` as getters/setters.\n *\n *\n * **Input-type specific options**:\n *\n * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for\n * ``, ``, ... . It understands UTC/GMT and the\n * continental US time zone abbreviations, but for general use, use a time zone offset, for\n * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)\n * If not specified, the timezone of the browser will be used.\n * Note that changing the timezone will have no effect on the current date, and is only applied after\n * the next input / model change.\n *\n * - `timeSecondsFormat`: Defines if the `time` and `datetime-local` types should show seconds and\n * milliseconds. The option follows the format string of {@link date date filter}.\n * By default, the options is `undefined` which is equal to `'ss.sss'` (seconds and milliseconds).\n * The other options are `'ss'` (strips milliseconds), and `''` (empty string), which strips both\n * seconds and milliseconds.\n * Note that browsers that support `time` and `datetime-local` require the hour and minutes\n * part of the time string, and may show the value differently in the user interface.\n * {@link ngModelOptions#formatting-the-value-of-time-and-datetime-local- See the example}.\n *\n * - `timeStripZeroSeconds`: Defines if the `time` and `datetime-local` types should strip the\n * seconds and milliseconds from the formatted value if they are zero. This option is applied\n * after `timeSecondsFormat`.\n * This option can be used to make the formatting consistent over different browsers, as some\n * browsers with support for `time` will natively hide the milliseconds and\n * seconds if they are zero, but others won't, and browsers that don't implement these input\n * types will always show the full string.\n * {@link ngModelOptions#formatting-the-value-of-time-and-datetime-local- See the example}.\n *\n */\nvar ngModelOptionsDirective = function() {\n NgModelOptionsController.$inject = ['$attrs', '$scope'];\n function NgModelOptionsController($attrs, $scope) {\n this.$$attrs = $attrs;\n this.$$scope = $scope;\n }\n NgModelOptionsController.prototype = {\n $onInit: function() {\n var parentOptions = this.parentCtrl ? this.parentCtrl.$options : defaultModelOptions;\n var modelOptionsDefinition = this.$$scope.$eval(this.$$attrs.ngModelOptions);\n\n this.$options = parentOptions.createChild(modelOptionsDefinition);\n }\n };\n\n return {\n restrict: 'A',\n // ngModelOptions needs to run before ngModel and input directives\n priority: 10,\n require: {parentCtrl: '?^^ngModelOptions'},\n bindToController: true,\n controller: NgModelOptionsController\n };\n};\n\n\n// shallow copy over values from `src` that are not already specified on `dst`\nfunction defaults(dst, src) {\n forEach(src, function(value, key) {\n if (!isDefined(dst[key])) {\n dst[key] = value;\n }\n });\n}\n\n/**\n * @ngdoc directive\n * @name ngNonBindable\n * @restrict AC\n * @priority 1000\n * @element ANY\n *\n * @description\n * The `ngNonBindable` directive tells AngularJS not to compile or bind the contents of the current\n * DOM element, including directives on the element itself that have a lower priority than\n * `ngNonBindable`. This is useful if the element contains what appears to be AngularJS directives\n * and bindings but which should be ignored by AngularJS. This could be the case if you have a site\n * that displays snippets of code, for instance.\n *\n * @example\n * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,\n * but the one wrapped in `ngNonBindable` is left alone.\n *\n \n \n
Normal: {{1 + 2}}
\n
Ignored: {{1 + 2}}
\n
\n \n it('should check ng-non-bindable', function() {\n expect(element(by.binding('1 + 2')).getText()).toContain('3');\n expect(element.all(by.css('div')).last().getText()).toMatch(/1 \\+ 2/);\n });\n \n
\n */\nvar ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });\n\n/* exported ngOptionsDirective */\n\n/* global jqLiteRemove */\n\nvar ngOptionsMinErr = minErr('ngOptions');\n\n/**\n * @ngdoc directive\n * @name ngOptions\n * @restrict A\n *\n * @description\n *\n * The `ngOptions` attribute can be used to dynamically generate a list of ``\n * DOM element.\n * * `disable`: The result of this expression will be used to disable the rendered `
\\n\";","module.exports = \"\\n \\n \\n\\n \\n\\n \\n \\n\\n\";","'use strict';\n// B.2.3.6 String.prototype.fixed()\nrequire('./_string-html')('fixed', function (createHTML) {\n return function fixed() {\n return createHTML(this, 'tt', '', '');\n };\n});\n","// Imports\nvar ___CSS_LOADER_API_IMPORT___ = require(\"../../../../css-loader/dist/runtime/api.js\");\nvar ___CSS_LOADER_ICSS_IMPORT_0___ = require(\"-!../../../../css-loader/dist/cjs.js??ref--6-1!../../../../postcss-loader/src/index.js!../global/global.css\");\nvar ___CSS_LOADER_AT_RULE_IMPORT_0___ = require(\"-!../../../../css-loader/dist/cjs.js??ref--6-1!../../../../postcss-loader/src/index.js!../global/variables.css\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\nexports.i(___CSS_LOADER_ICSS_IMPORT_0___, \"\", true);\nexports.i(___CSS_LOADER_AT_RULE_IMPORT_0___);\n// Module\nexports.push([module.id, \".tooltip_182 {\\n max-width: 400px;\\n padding: 8px;\\n\\n text-align: left;\\n}\\n\", \"\"]);\n// Exports\nexports.locals = {\n\t\"unit\": \"\" + ___CSS_LOADER_ICSS_IMPORT_0___.locals[\"unit\"] + \"\",\n\t\"tooltip\": \"tooltip_182\"\n};\nmodule.exports = exports;\n","var content = require(\"!!../../../../css-loader/dist/cjs.js!../../../../postcss-loader/src/index.js!../../../../sass-loader/dist/cjs.js??ref--8-3!./table-legacy__toolbar.scss\");\ncontent = content.__esModule ? content.default : content;\n\nif (typeof content === 'string') {\n content = [[module.id, content, '']];\n}\n\nvar options = {}\n\noptions.insert = \"head\";\noptions.singleton = false;\n\nvar update = require(\"!../../../../style-loader/dist/runtime/injectStylesIntoStyleTag.js\")(content, options);\n\nif (content.locals) {\n module.exports = content.locals;\n}\n","// Imports\nvar ___CSS_LOADER_API_IMPORT___ = require(\"../../../../css-loader/dist/runtime/api.js\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\n// Module\nexports.push([module.id, \".ring-table__toolbar{background:inherit}.ring-table__toolbar-controls{display:block;position:relative;padding:16px 32px;min-height:24px;background:inherit;white-space:normal;white-space:initial}.ring-table__toolbar-controls.ring-table__toolbar-controls_fixed{z-index:2;z-index:calc(var(--ring-fixed-z-index) + 1);position:fixed;top:0;right:0;left:0}\", \"\"]);\n// Exports\nmodule.exports = exports;\n","module.exports = \"\\n\";","var content = require(\"!!../../../../css-loader/dist/cjs.js!../../../../postcss-loader/src/index.js!../../../../sass-loader/dist/cjs.js??ref--8-3!./table-legacy.scss\");\ncontent = content.__esModule ? content.default : content;\n\nif (typeof content === 'string') {\n content = [[module.id, content, '']];\n}\n\nvar options = {}\n\noptions.insert = \"head\";\noptions.singleton = false;\n\nvar update = require(\"!../../../../style-loader/dist/runtime/injectStylesIntoStyleTag.js\")(content, options);\n\nif (content.locals) {\n module.exports = content.locals;\n}\n","// Imports\nvar ___CSS_LOADER_API_IMPORT___ = require(\"../../../../css-loader/dist/runtime/api.js\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\n// Module\nexports.push([module.id, \".ring-table__toolbar{background:inherit}.ring-table__toolbar-controls{display:block;position:relative;padding:16px 32px;min-height:24px;background:inherit;white-space:normal;white-space:initial}.ring-table__toolbar-controls.ring-table__toolbar-controls_fixed{z-index:2;z-index:calc(var(--ring-fixed-z-index) + 1);position:fixed;top:0;right:0;left:0}.ring-table{width:100%;border-spacing:0;border-collapse:collapse;background-color:transparent;font-size:13px;font-size:var(--ring-font-size)}.ring-table__header{display:table-row;background-color:#f7f9fa;background-color:var(--ring-sidebar-background-color)}.ring-table__header-checkbox{display:inline-block;position:relative;top:1px;left:-2px}.ring-table__title{display:table-cell;position:relative;padding:0 8px;text-align:left;line-height:23px;white-space:nowrap;font-size:12px;font-size:var(--ring-font-size-smaller);font-weight:normal;color:#1f2326;color:var(--ring-text-color);border-top:1px solid #f7f9fa;border-top:1px solid var(--ring-sidebar-background-color);border-bottom:1px solid #dfe5eb;border-bottom:1px solid var(--ring-line-color)}.ring-table__title.ring-table__title_active{font-weight:bold}.ring-table__title:first-child{padding-left:32px}.ring-table__title:after{content:normal;display:block;position:absolute;top:-1px;bottom:0;width:1px;right:0;background-color:#f7f9fa;background-color:var(--ring-sidebar-background-color)}.ring-table__title_border:after{content:\\\"\\\"}.ring-table__title_nested{padding-left:40px}.ring-table__title_nested .ring-table__header-checkbox{left:-26px}.ring-table__toggle{display:inline-block;position:relative;top:9px;width:12px;height:9px;margin-left:16px;padding-bottom:21px;color:#dfe5eb;color:var(--ring-line-color);font-size:14px;cursor:pointer}@media (hover: hover), (-moz-touch-enabled: 0), (-ms-high-contrast: none), (-ms-high-contrast: active) {.ring-table__toggle:hover{color:#1f2326;color:var(--ring-text-color)}}.ring-table__toggle-icon{float:right}@media (hover: hover), (-moz-touch-enabled: 0), (-ms-high-contrast: none), (-ms-high-contrast: active) {.ring-table__toggle-icon:hover{color:#ff008c;color:var(--ring-link-hover-color)}}.ring-table__column-inline-avatar{display:inline-block;vertical-align:middle}.ring-table__column-inline-avatar-img{margin:-6px 8px}.ring-table__column_selector{min-width:24px;padding:0 !important;text-align:center}.ring-table__selector{display:inline-block;margin:0 0 0 4px}.ring-table__column{display:table-cell;border-width:1px;border-color:#f7f9fa;border-color:var(--ring-sidebar-background-color);border-top-style:solid;border-bottom-style:solid;border-collapse:collapse;padding:6px 8px;vertical-align:middle;white-space:nowrap}.ring-table__column:last-child{width:100%}.ring-table__column:first-child{padding-left:32px}.ring-table__column.ring-table__column_gap{background-color:#dfe5eb;background-color:var(--ring-line-color);border-bottom-color:transparent !important}.ring-table__column.ring-table__column_toggle{width:16px;padding:0;vertical-align:top;text-align:right}.ring-table__column_right{text-align:right}.ring-table__column_gray{color:#737577;color:var(--ring-secondary-color)}.ring-table__column_snuggle-right{padding-right:0}.ring-table__column_snuggle-left{padding-left:0}.ring-table__column_align-right{text-align:right}.ring-table__column_gap{border-right-style:solid;padding-left:16px !important}.ring-table__column-title{font-weight:bold}.ring-table__column_wide{min-width:80px}.ring-table__column_limited{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;max-width:400px}.ring-table__column_unlimited{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;width:100%;max-width:1px}.ring-table__column_narrow{min-width:24px;padding:0 !important}.ring-table__column-list:not(:last-child):after{content:\\\", \\\"}.ring-table__row{display:table-row;width:100%;height:40px}.ring-table__row.ring-table__row_ghost{background-color:#fff;background-color:var(--ring-content-background-color)}.ring-table__row.ring-table__row_implicit{opacity:.5}@media (hover: hover), (-moz-touch-enabled: 0), (-ms-high-contrast: none), (-ms-high-contrast: active) {.ring-table__row:hover{background-color:#f7f9fa;background-color:var(--ring-sidebar-background-color)}}@media (hover: hover), (-moz-touch-enabled: 0), (-ms-high-contrast: none), (-ms-high-contrast: active) {.ring-table__row:hover .ring-table__column_gap{background-color:#dfe5eb;background-color:var(--ring-line-color)}}@media (hover: hover), (-moz-touch-enabled: 0), (-ms-high-contrast: none), (-ms-high-contrast: active) {.ring-table__row.ring-table__row_unselectable:hover{background-color:transparent;background-color:initial}}.ring-table__row.ring-table__row_checked{background-color:#d4edff;background-color:var(--ring-selected-background-color)}.ring-table__row.ring-table__row_active-checked{background-color:#d4edff;background-color:var(--ring-selected-background-color)}.ring-table__row.ring-table__row_active .ring-table__column{border-color:#008eff;border-color:var(--ring-main-color);border-top-style:double}.ring-table__row.ring-table__row_active .ring-table__column_gap{border-color:#dfe5eb;border-color:var(--ring-line-color);border-top-style:none}.ring-table__row.ring-table__row_active .sidebar__btn{visibility:visible}.ring-table__group{display:table-row-group}.ring-table__description{margin-left:8px;font-size:12px;font-size:var(--ring-font-size-smaller);color:#737577;color:var(--ring-secondary-color)}.ring-table__avatar{width:24px;height:27px}.ring-table__avatar-img{width:24px;height:24px}.ring-table__header_sticky{position:fixed;display:none;top:0;width:auto;z-index:1;z-index:var(--ring-fixed-z-index)}.table__pager{padding:32px 32px}.table__pager-links{margin-bottom:16px}.table__pager-link{display:inline-block;margin-right:32px}.table__pager-link_disabled{color:#737577;color:var(--ring-secondary-color)}.table__pager-select{float:right;display:inline-block}\", \"\"]);\n// Exports\nmodule.exports = exports;\n","module.exports = \"
\\n \\n
\\n
\\n\";","module.exports = \"\\n \\n \\n\\n\";","module.exports = \"\\n\\n\";","module.exports = \"\\n\\n\";","module.exports = \"\\n\\n\";","// Imports\nvar ___CSS_LOADER_API_IMPORT___ = require(\"../../../../css-loader/dist/runtime/api.js\");\nvar ___CSS_LOADER_ICSS_IMPORT_0___ = require(\"-!../../../../css-loader/dist/cjs.js??ref--6-1!../../../../postcss-loader/src/index.js!../global/global.css\");\nvar ___CSS_LOADER_AT_RULE_IMPORT_0___ = require(\"-!../../../../css-loader/dist/cjs.js??ref--6-1!../../../../postcss-loader/src/index.js!../global/variables.css\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\nexports.i(___CSS_LOADER_ICSS_IMPORT_0___, \"\", true);\nexports.i(___CSS_LOADER_AT_RULE_IMPORT_0___);\n// Module\nexports.push([module.id, \"@media (hover: hover), (-moz-touch-enabled: 0), (-ms-high-contrast: none), (-ms-high-contrast: active) {.title_87d:hover:not(.selected_8b2) {\\n color: #ff008c;\\n color: var(--ring-link-hover-color);\\n outline-style: none;\\n box-shadow: inset 0 -1px 0 0 #ff008c;\\n box-shadow: inset 0 -1px 0 0 var(--ring-link-hover-color);\\n }}\\n\\n.tabs_e99 {\\n}\\n\\n.titles_733 {\\n display: inline-block;\\n\\n margin-bottom: 16px;\\n}\\n\\n.light_5cd .titles_733 {\\n box-shadow: inset 0 -1px 0 0 #dfe5eb;\\n box-shadow: inset 0 -1px 0 0 var(--ring-line-color);\\n}\\n\\n.dark_ab1 .titles_733 {\\n box-shadow: inset 0 -1px 0 0 #475159;\\n box-shadow: inset 0 -1px 0 0 var(--ring-dark-line-color);\\n}\\n\\n.title_87d {\\n\\n position: relative;\\n\\n display: inline-block;\\n\\n padding: 0;\\n\\n cursor: pointer;\\n\\n color: inherit;\\n\\n border: none;\\n background: none;\\n\\n line-height: 32px\\n}\\n\\n.title_87d:focus:not(.selected_8b2),\\n .title_87d:active:not(.selected_8b2) {\\n color: #ff008c;\\n color: var(--ring-link-hover-color);\\n outline-style: none;\\n box-shadow: inset 0 -1px 0 0 #ff008c;\\n box-shadow: inset 0 -1px 0 0 var(--ring-link-hover-color);\\n }\\n\\n.title_87d[disabled] {\\n pointer-events: none;\\n }\\n\\n.title_87d + .title_87d {\\n margin-left: 24px;\\n}\\n\\n.light_5cd .title_87d[disabled] {\\n color: #999;\\n color: var(--ring-disabled-color);\\n }\\n\\n.dark_ab1 .title_87d {\\n color: #888;\\n color: var(--ring-dark-secondary-color)\\n}\\n\\n.dark_ab1 .title_87d[disabled] {\\n color: #1f2326;\\n color: var(--ring-text-color);\\n }\\n\\n.selected_8b2 {\\n cursor: default;\\n\\n outline: none;\\n box-shadow: inset 0 -3px 0 0 #1f2326;\\n box-shadow: inset 0 -3px 0 0 var(--ring-text-color);\\n\\n font-weight: bold;\\n}\\n\\n.dark_ab1 .selected_8b2.selected_8b2 {\\n color: #fff;\\n color: var(--ring-dark-text-color);\\n box-shadow: inset 0 -3px 0 0 #008eff;\\n box-shadow: inset 0 -3px 0 0 var(--ring-main-color);\\n }\\n\\n.visible_523 {\\n position: absolute;\\n top: 0;\\n right: 0;\\n bottom: 0;\\n left: 0;\\n\\n text-align: center;\\n}\\n\\n.hidden_834 {\\n visibility: hidden;\\n\\n font-weight: bold;\\n}\\n\\n.tabCounter_8f8 {\\n padding-left: 8px;\\n\\n color: #737577;\\n\\n color: var(--ring-secondary-color);\\n\\n font-size: 12px;\\n font-weight: normal;\\n line-height: 19px; /* prevent jumps in Firefox */\\n}\\n\", \"\"]);\n// Exports\nexports.locals = {\n\t\"unit\": \"\" + ___CSS_LOADER_ICSS_IMPORT_0___.locals[\"unit\"] + \"\",\n\t\"line-shadow\": \"inset 0 -1px 0 0\",\n\t\"selected-line-shadow\": \"inset 0 -3px 0 0\",\n\t\"title\": \"title_87d \" + ___CSS_LOADER_ICSS_IMPORT_0___.locals[\"font\"] + \"\",\n\t\"selected\": \"selected_8b2\",\n\t\"tabs\": \"tabs_e99 \" + ___CSS_LOADER_ICSS_IMPORT_0___.locals[\"font\"] + \"\",\n\t\"titles\": \"titles_733\",\n\t\"light\": \"light_5cd\",\n\t\"dark\": \"dark_ab1\",\n\t\"visible\": \"visible_523\",\n\t\"hidden\": \"hidden_834\",\n\t\"tabCounter\": \"tabCounter_8f8\"\n};\nmodule.exports = exports;\n","module.exports = \"\\n \\n {{pane.title}}{{ pane.counter }}
{{pane.title}}{{ pane.counter }}
\\n \\n
\\n\\n
\\n\\n
\\n\";","// Imports\nvar ___CSS_LOADER_API_IMPORT___ = require(\"../../../../css-loader/dist/runtime/api.js\");\nvar ___CSS_LOADER_AT_RULE_IMPORT_0___ = require(\"-!../../../../css-loader/dist/cjs.js??ref--6-1!../../../../postcss-loader/src/index.js!../global/variables.css\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\nexports.i(___CSS_LOADER_AT_RULE_IMPORT_0___);\n// Module\nexports.push([module.id, \".tagsInput_cb1 {\\n padding-top: 2px;\\n padding-bottom: 2px;\\n\\n white-space: normal;\\n}\\n\\n.tagsInputLegacyMode_39b {\\n padding-top: 0;\\n padding-bottom: 1px;\\n\\n border: 1px solid #b8d1e5;\\n\\n border: 1px solid var(--ring-borders-color);\\n background-color: #fff;\\n background-color: var(--ring-content-background-color)\\n}\\n\\n.tagsInputLegacyMode_39b .tagsList_925 {\\n padding-top: 1px;\\n\\n line-height: 20px;\\n }\\n\\n.tagsInputLegacyMode_39b .tag_292 {\\n margin-right: 2px;\\n }\\n\\n.tagsInputDisabled_c7c {\\n pointer-events: none;\\n\\n color: #999;\\n\\n color: var(--ring-disabled-color)\\n}\\n\\n.tagsInputDisabled_c7c .underline_417 {\\n border-bottom-style: dashed;\\n }\\n\\n.tagsInputFocused_61f {\\n border-color: #008eff;\\n border-color: var(--ring-main-color);\\n}\\n\\n.tagsList_925 {\\n display: inline-block;\\n\\n box-sizing: border-box;\\n\\n width: 100%;\\n margin-bottom: -1px;\\n\\n padding-left: 2px;\\n\\n line-height: 22px;\\n}\\n\\n.tagsSelect_aac {\\n margin-bottom: -1px\\n}\\n\\n.tagsSelect_aac > div {\\n min-height: 20px;\\n }\\n\\n.tagsSelect_aac input {\\n min-height: 20px;\\n }\\n\\n.underline_417 {\\n height: 1px;\\n\\n border-bottom: #b8d1e5 1px solid;\\n\\n border-bottom: var(--ring-borders-color) 1px solid;\\n}\\n\\n.focusUnderline_d8a {\\n width: 0;\\n height: 2px;\\n\\n margin-top: -1px;\\n\\n transition: width 0.15s ease-out;\\n\\n background: #008eff;\\n\\n background: var(--ring-main-color)\\n}\\n\\n.tagsInputFocused_61f .focusUnderline_d8a {\\n width: 100%\\n}\\n\", \"\"]);\n// Exports\nexports.locals = {\n\t\"tagsInput\": \"tagsInput_cb1\",\n\t\"tagsInputLegacyMode\": \"tagsInputLegacyMode_39b\",\n\t\"tagsList\": \"tagsList_925\",\n\t\"tag\": \"tag_292\",\n\t\"tagsInputDisabled\": \"tagsInputDisabled_c7c\",\n\t\"underline\": \"underline_417\",\n\t\"tagsInputFocused\": \"tagsInputFocused_61f\",\n\t\"tagsSelect\": \"tagsSelect_aac\",\n\t\"focusUnderline\": \"focusUnderline_d8a\"\n};\nmodule.exports = exports;\n","// Imports\nvar ___CSS_LOADER_API_IMPORT___ = require(\"../../../../css-loader/dist/runtime/api.js\");\nvar ___CSS_LOADER_ICSS_IMPORT_0___ = require(\"-!../../../../css-loader/dist/cjs.js??ref--6-1!../../../../postcss-loader/src/index.js!../global/global.css\");\nvar ___CSS_LOADER_AT_RULE_IMPORT_0___ = require(\"-!../../../../css-loader/dist/cjs.js??ref--6-1!../../../../postcss-loader/src/index.js!../global/variables.css\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\nexports.i(___CSS_LOADER_ICSS_IMPORT_0___, \"\", true);\nexports.i(___CSS_LOADER_AT_RULE_IMPORT_0___);\n// Module\nexports.push([module.id, \".toggle_2cd {\\n cursor: pointer\\n}\\n\\n@media (hover: hover), (-moz-touch-enabled: 0), (-ms-high-contrast: none), (-ms-high-contrast: active) {.toggle_2cd:hover .switch_7e5 {\\n background-color: #80c6ff;\\n background-color: var(--ring-border-hover-color);\\n }}\\n\\n.toggle_2cd.disabled_696 {\\n pointer-events: none;\\n }\\n\\n.label_a30 {\\n margin-left: 4px;\\n}\\n\\n.leftLabel_280 {\\n margin-right: 4px;\\n}\\n\\n.light_88b .switch_7e5 {\\n background-color: #b8d1e5;\\n background-color: var(--ring-icon-color)\\n }\\n\\n.light_88b .switch_7e5::before {\\n background-color: #fff;\\n background-color: var(--ring-content-background-color);\\n }\\n\\n.dark_6c3 .switch_7e5 {\\n background-color: #406380;\\n background-color: var(--ring-hint-color)\\n }\\n\\n.dark_6c3 .switch_7e5::before {\\n background-color: #000;\\n background-color: var(--ring-navigation-background-color);\\n }\\n\\n.switchWrapper_801 {\\n position: relative;\\n\\n display: inline-block;\\n\\n width: 24px;\\n height: 16px;\\n\\n vertical-align: -3px;\\n}\\n\\n.input_ee9 {\\n position: absolute;\\n top: 0;\\n left: 0;\\n\\n width: 100%;\\n height: 100%;\\n\\n margin: 0;\\n\\n opacity: 0;\\n}\\n\\n.switch_7e5 {\\n position: relative;\\n\\n display: block;\\n\\n width: 100%;\\n height: 100%;\\n\\n transition: background-color cubic-bezier(0.23, 1, 0.32, 1) 300ms;\\n\\n border-radius: 8px\\n}\\n\\n.input_ee9:focus + .switch_7e5 {\\n box-shadow: inset 0 0 0 1px #80c6ff, 0 0 0 1px #80c6ff;\\n box-shadow: inset 0 0 0 1px var(--ring-border-hover-color), 0 0 0 1px var(--ring-border-hover-color)\\n}\\n\\n.switch_7e5::before {\\n position: absolute;\\n top: 2px;\\n left: 0;\\n\\n width: 12px;\\n height: 12px;\\n\\n content: \\\"\\\";\\n\\n transition: transform cubic-bezier(0.23, 1, 0.32, 1) 300ms;\\n\\n transform: translateX(2px);\\n\\n border-radius: 6px;\\n }\\n\\n.input_ee9:checked + .switch_7e5 {\\n background-color: #008eff;\\n background-color: var(--ring-main-color);\\n}\\n\\n.input_ee9:checked + ::before {\\n transform: translateX(10px);\\n}\\n\\n.input_ee9[disabled] + ::after {\\n position: absolute;\\n top: 0;\\n left: 0;\\n\\n width: 100%;\\n height: 100%;\\n\\n content: \\\"\\\";\\n\\n border-radius: 8px;\\n background-image:\\n linear-gradient(\\n 45deg,\\n transparent,\\n transparent 37.5%,\\n rgba(255, 255, 255, 0.9) 37.5%,\\n rgba(255, 255, 255, 0.9) 50%,\\n transparent 50%,\\n transparent 87.5%,\\n rgba(255, 255, 255, 0.9) 87.5%,\\n rgba(255, 255, 255, 0.9)\\n );\\n background-repeat: repeat;\\n background-size: 4px 4px;\\n}\\n\\n.paleSwitch_fd2.paleSwitch_fd2 {\\n background-color: #cfdbe5;\\n background-color: var(--ring-pale-control-color);\\n}\\n\\n.input_ee9:checked + .paleSwitch_fd2 {\\n background-color: #80c6ff;\\n background-color: var(--ring-border-hover-color);\\n}\\n\", \"\"]);\n// Exports\nexports.locals = {\n\t\"unit\": \"\" + ___CSS_LOADER_ICSS_IMPORT_0___.locals[\"unit\"] + \"\",\n\t\"padding\": \"2px\",\n\t\"disabled-line-color\": \"rgba(255, 255, 255, 0.9)\",\n\t\"duration\": \"300ms\",\n\t\"timing-function\": \"cubic-bezier(0.23, 1, 0.32, 1)\",\n\t\"toggle\": \"toggle_2cd\",\n\t\"switch\": \"switch_7e5\",\n\t\"disabled\": \"disabled_696\",\n\t\"label\": \"label_a30\",\n\t\"leftLabel\": \"leftLabel_280\",\n\t\"light\": \"light_88b\",\n\t\"dark\": \"dark_6c3\",\n\t\"switchWrapper\": \"switchWrapper_801\",\n\t\"input\": \"input_ee9\",\n\t\"paleSwitch\": \"paleSwitch_fd2\"\n};\nmodule.exports = exports;\n","var content = require(\"!!../../../../css-loader/dist/cjs.js!../../../../postcss-loader/src/index.js!../../../../sass-loader/dist/cjs.js??ref--8-3!./tooltip-ng.scss\");\ncontent = content.__esModule ? content.default : content;\n\nif (typeof content === 'string') {\n content = [[module.id, content, '']];\n}\n\nvar options = {}\n\noptions.insert = \"head\";\noptions.singleton = false;\n\nvar update = require(\"!../../../../style-loader/dist/runtime/injectStylesIntoStyleTag.js\")(content, options);\n\nif (content.locals) {\n module.exports = content.locals;\n}\n","// Imports\nvar ___CSS_LOADER_API_IMPORT___ = require(\"../../../../css-loader/dist/runtime/api.js\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\n// Module\nexports.push([module.id, \".ring-tooltip-ng{max-width:400px;padding:8px;text-align:left}.ring-tooltip-ng__hint-icon{margin-left:8px;color:#b8d1e5;color:var(--ring-icon-color);cursor:pointer;position:relative;top:-2px}.ring-tooltip-ng_open .ring-tooltip-ng__hint-icon{color:#ff008c;color:var(--ring-link-hover-color)}\", \"\"]);\n// Exports\nmodule.exports = exports;\n","var content = require(\"!!../../../../css-loader/dist/cjs.js!../../../../postcss-loader/src/index.js!../../../../sass-loader/dist/cjs.js??ref--8-3!./input-size.scss\");\ncontent = content.__esModule ? content.default : content;\n\nif (typeof content === 'string') {\n content = [[module.id, content, '']];\n}\n\nvar options = {}\n\noptions.insert = \"head\";\noptions.singleton = false;\n\nvar update = require(\"!../../../../style-loader/dist/runtime/injectStylesIntoStyleTag.js\")(content, options);\n\nif (content.locals) {\n module.exports = content.locals;\n}\n","// Imports\nvar ___CSS_LOADER_API_IMPORT___ = require(\"../../../../css-loader/dist/runtime/api.js\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\n// Module\nexports.push([module.id, \".ring-error-bubble{z-index:2;box-sizing:border-box;display:none;position:absolute;top:0;left:calc(100% + 2px);min-height:24px;padding-right:16px;padding-left:16px;line-height:22px;border-radius:3px;border-radius:var(--ring-border-radius);border:1px solid rgba(0, 42, 76, 0.1);border:1px solid var(--ring-popup-border-color);color:#1f2326;color:var(--ring-text-color);font-size:12px;font-family:system-ui, -apple-system, Segoe UI, Roboto, Noto Sans, Ubuntu, Cantarell, Helvetica Neue, Arial, sans-serif;font-family:var(--ring-font-family);white-space:nowrap;color:#c22731;color:var(--ring-error-color);background:#fff;background:var(--ring-popup-background-color);box-shadow:0 2px 16px 0 rgba(0, 42, 76, 0.15);box-shadow:0 2px 16px 0 var(--ring-popup-shadow-color)}.ring-error-bubble.active{display:inline-block}.ring-error-bubble:before{content:\\\"\\\";transform:rotate(45deg);z-index:-1;z-index:var(--ring-invisible-element-z-index);position:absolute;top:7px;left:-5px;display:block;width:8px;height:8px;border:1px solid rgba(0, 42, 76, 0.1);border:1px solid var(--ring-popup-border-color);border-right:none;border-top:none;background:#fff;background:var(--ring-popup-background-color)}.ring-error-bubble_material{padding-left:8px;box-shadow:none;border:0;background-color:transparent;background:none}.ring-error-bubble_material:before{display:none}.ring-form__control .ring-error-bubble{top:1px}.ring-error-bubble-wrapper{position:relative}.ring-input-size_xs.ring-input-size_xs{display:inline-block;width:50px}.ring-input-size_xs.ring-input-size_xs~.ring-error-bubble{left:52px}.ring-input-size_s.ring-input-size_s{display:inline-block;width:100px}.ring-input-size_s.ring-input-size_s~.ring-error-bubble{left:102px}.ring-input-size_md.ring-input-size_md{display:inline-block;width:200px}.ring-input-size_md.ring-input-size_md~.ring-error-bubble{left:202px}.ring-input-size_l.ring-input-size_l{display:inline-block;width:400px}.ring-input-size_l.ring-input-size_l~.ring-error-bubble{left:402px}\", \"\"]);\n// Exports\nmodule.exports = exports;\n","var content = require(\"!!../../../../node_modules/css-loader/dist/cjs.js!../../../../node_modules/sass-loader/dist/cjs.js!./search.scss\");\ncontent = content.__esModule ? content.default : content;\n\nif (typeof content === 'string') {\n content = [[module.id, content, '']];\n}\n\nvar options = {}\n\noptions.insert = \"head\";\noptions.singleton = false;\n\nvar update = require(\"!../../../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js\")(content, options);\n\nif (content.locals) {\n module.exports = content.locals;\n}\n","// Imports\nvar ___CSS_LOADER_API_IMPORT___ = require(\"../../../../node_modules/css-loader/dist/runtime/api.js\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\n// Module\nexports.push([module.id, \".search button{border:none;fill:#637282;background:#f4f4f4}.search button:focus{outline:none}.popup-wrapper{min-width:calc(100% - 360px) !important}.indented{text-indent:10px}.disabled{color:gray}.template-wrapper{display:grid;grid-template-columns:auto auto}.template-name{justify-self:start}.template-description{color:gray;justify-self:end}\", \"\"]);\n// Exports\nmodule.exports = exports;\n","// Imports\nvar ___CSS_LOADER_API_IMPORT___ = require(\"../../../../node_modules/css-loader/dist/runtime/api.js\");\nvar ___CSS_LOADER_AT_RULE_IMPORT_0___ = require(\"-!../../../../node_modules/css-loader/dist/cjs.js!@jetbrains/ring-ui/components/global/variables.css\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\nexports.i(___CSS_LOADER_AT_RULE_IMPORT_0___);\n// Module\nexports.push([module.id, \"html,.app-root{height:100%}.search-root{margin:0;padding:0;background:var(--ring-content-background-color);font-family:var(--ring-font-family);font-size:var(--ring-font-size);line-height:var(--ring-line-height)}.search-content{padding-top:24px;margin:0 41px;position:absolute;top:0;right:0;z-index:8;background-color:#f4f4f4}\", \"\"]);\n// Exports\nmodule.exports = exports;\n","// Imports\nvar ___CSS_LOADER_API_IMPORT___ = require(\"../../../../css-loader/dist/runtime/api.js\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\n// Module\nexports.push([module.id, \"/* stylelint-disable color-no-hex */\\n\\n:root {\\n --ring-unit: 8px;\\n\\n /* Element */\\n --ring-line-color: #dfe5eb;\\n --ring-dark-line-color: #475159;\\n --ring-borders-color: #b8d1e5;\\n --ring-dark-borders-color: #406380;\\n --ring-icon-color: var(--ring-borders-color);\\n --ring-icon-secondary-color: #999;\\n --ring-border-disabled-color: #dbdbdb;\\n --ring-icon-disabled-color: #bbb;\\n --ring-border-hover-color: #80c6ff;\\n --ring-dark-border-hover-color: #70b1e6;\\n --ring-icon-hover-color: var(--ring-border-hover-color);\\n --ring-main-color: #008eff;\\n --ring-main-hover-color: #007ee5;\\n --ring-icon-error-color: #db5860;\\n --ring-icon-warning-color: #eda200;\\n --ring-icon-success-color: #59a869;\\n --ring-pale-control-color: #cfdbe5;\\n --ring-popup-border-components: 0, 42, 76;\\n --ring-popup-border-color: rgba(var(--ring-popup-border-components), 0.1);\\n --ring-popup-shadow-color: rgba(var(--ring-popup-border-components), 0.15);\\n --ring-message-shadow-color: rgba(var(--ring-popup-border-components), 0.3);\\n\\n /* Text */\\n --ring-search-color: #669ecc;\\n --ring-hint-color: #406380;\\n --ring-link-color: #0f5b99;\\n --ring-link-hover-color: #ff008c;\\n --ring-error-color: #c22731;\\n --ring-warning-color: #cc8b00;\\n --ring-success-color: #1b8833;\\n --ring-text-color: #1f2326;\\n --ring-dark-text-color: #fff;\\n --ring-heading-color: var(--ring-text-color);\\n --ring-secondary-color: #737577;\\n --ring-dark-secondary-color: #888;\\n --ring-disabled-color: #999;\\n --ring-dark-disabled-color: #444;\\n --ring-dark-active-color: #ccc;\\n\\n /* Background */\\n --ring-content-background-color: #fff;\\n --ring-popup-background-color: #fff;\\n --ring-sidebar-background-color: #f7f9fa;\\n --ring-selected-background-color: #d4edff;\\n --ring-hover-background-color: #ebf6ff;\\n --ring-dark-selected-background-color: #002a4d;\\n --ring-message-background-color: #111314;\\n --ring-navigation-background-color: #000;\\n --ring-tag-background-color: #e6ecf2;\\n --ring-removed-background-color: #ffd5cb;\\n --ring-warning-background-color: #faeccd;\\n --ring-added-background-color: #bce8bb;\\n\\n /* Code */\\n --ring-code-background-color: var(--ring-content-background-color);\\n --ring-code-color: #000;\\n --ring-code-comment-color: #707070;\\n --ring-code-meta-color: #707070;\\n --ring-code-keyword-color: #000080;\\n --ring-code-tag-background-color: #efefef;\\n --ring-code-tag-color: var(--ring-code-keyword-color);\\n --ring-code-tag-font-weight: bold;\\n --ring-code-field-color: #660e7a;\\n --ring-code-attribute-color: #00f;\\n --ring-code-number-color: var(--ring-code-attribute-color);\\n --ring-code-string-color: #007a00;\\n --ring-code-addition-color: #aadeaa;\\n --ring-code-deletion-color: #c8c8c8;\\n\\n /* Metrics */\\n --ring-border-radius: 3px;\\n --ring-border-radius-small: 2px;\\n --ring-font-size-larger: 14px;\\n --ring-font-size: 13px;\\n --ring-font-size-smaller: 12px;\\n --ring-line-height-taller: 21px;\\n --ring-line-height: 20px;\\n --ring-line-height-lower: 18px;\\n --ring-line-height-lowest: 16px;\\n --ring-ease: 0.3s ease-out;\\n --ring-fast-ease: 0.15s ease-out;\\n --ring-font-family: system-ui, Arial, sans-serif;\\n --ring-font-family-monospace: Menlo, \\\"Bitstream Vera Sans Mono\\\", \\\"Ubuntu Mono\\\", Consolas, \\\"Courier New\\\", Courier, monospace;\\n\\n /* Common z-index-values */\\n\\n /* Invisible element is an absolutely positioned element which should be below */\\n /* all other elements on the page */\\n --ring-invisible-element-z-index: -1;\\n\\n /* z-index for position: fixed elements */\\n --ring-fixed-z-index: 1;\\n\\n /* Elements that should overlay all other elements on the page */\\n --ring-overlay-z-index: 5;\\n\\n /* Alerts should de displayed above overlays */\\n --ring-alert-z-index: 6;\\n}\\n\", \"\"]);\n// Exports\nmodule.exports = exports;\n","/**\n * Commonly used icon colors.\n * @enum {string}\n */\nexport const Color = {\n BLUE: 'blue',\n DEFAULT: '',\n GRAY: 'gray',\n GREEN: 'green',\n MAGENTA: 'magenta',\n RED: 'red',\n WHITE: 'white'\n};\n\n/**\n * @enum {number}\n */\nexport const Size = {\n Size12: 12,\n Size14: 14,\n Size16: 16,\n Size18: 18,\n Size20: 20,\n Size24: 24,\n Size32: 32,\n Size40: 40,\n Size48: 48,\n Size64: 64,\n Size96: 96,\n Size128: 128\n};\n","export default function _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}","export default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n}","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nfunction componentWillMount() {\n // Call this.constructor.gDSFP to support sub-classes.\n var state = this.constructor.getDerivedStateFromProps(this.props, this.state);\n if (state !== null && state !== undefined) {\n this.setState(state);\n }\n}\n\nfunction componentWillReceiveProps(nextProps) {\n // Call this.constructor.gDSFP to support sub-classes.\n // Use the setState() updater to ensure state isn't stale in certain edge cases.\n function updater(prevState) {\n var state = this.constructor.getDerivedStateFromProps(nextProps, prevState);\n return state !== null && state !== undefined ? state : null;\n }\n // Binding \"this\" is important for shallow renderer support.\n this.setState(updater.bind(this));\n}\n\nfunction componentWillUpdate(nextProps, nextState) {\n try {\n var prevProps = this.props;\n var prevState = this.state;\n this.props = nextProps;\n this.state = nextState;\n this.__reactInternalSnapshotFlag = true;\n this.__reactInternalSnapshot = this.getSnapshotBeforeUpdate(\n prevProps,\n prevState\n );\n } finally {\n this.props = prevProps;\n this.state = prevState;\n }\n}\n\n// React may warn about cWM/cWRP/cWU methods being deprecated.\n// Add a flag to suppress these warnings for this special case.\ncomponentWillMount.__suppressDeprecationWarning = true;\ncomponentWillReceiveProps.__suppressDeprecationWarning = true;\ncomponentWillUpdate.__suppressDeprecationWarning = true;\n\nfunction polyfill(Component) {\n var prototype = Component.prototype;\n\n if (!prototype || !prototype.isReactComponent) {\n throw new Error('Can only polyfill class components');\n }\n\n if (\n typeof Component.getDerivedStateFromProps !== 'function' &&\n typeof prototype.getSnapshotBeforeUpdate !== 'function'\n ) {\n return Component;\n }\n\n // If new component APIs are defined, \"unsafe\" lifecycles won't be called.\n // Error if any of these lifecycles are present,\n // Because they would work differently between older and newer (16.3+) versions of React.\n var foundWillMountName = null;\n var foundWillReceivePropsName = null;\n var foundWillUpdateName = null;\n if (typeof prototype.componentWillMount === 'function') {\n foundWillMountName = 'componentWillMount';\n } else if (typeof prototype.UNSAFE_componentWillMount === 'function') {\n foundWillMountName = 'UNSAFE_componentWillMount';\n }\n if (typeof prototype.componentWillReceiveProps === 'function') {\n foundWillReceivePropsName = 'componentWillReceiveProps';\n } else if (typeof prototype.UNSAFE_componentWillReceiveProps === 'function') {\n foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';\n }\n if (typeof prototype.componentWillUpdate === 'function') {\n foundWillUpdateName = 'componentWillUpdate';\n } else if (typeof prototype.UNSAFE_componentWillUpdate === 'function') {\n foundWillUpdateName = 'UNSAFE_componentWillUpdate';\n }\n if (\n foundWillMountName !== null ||\n foundWillReceivePropsName !== null ||\n foundWillUpdateName !== null\n ) {\n var componentName = Component.displayName || Component.name;\n var newApiName =\n typeof Component.getDerivedStateFromProps === 'function'\n ? 'getDerivedStateFromProps()'\n : 'getSnapshotBeforeUpdate()';\n\n throw Error(\n 'Unsafe legacy lifecycles will not be called for components using new component APIs.\\n\\n' +\n componentName +\n ' uses ' +\n newApiName +\n ' but also contains the following legacy lifecycles:' +\n (foundWillMountName !== null ? '\\n ' + foundWillMountName : '') +\n (foundWillReceivePropsName !== null\n ? '\\n ' + foundWillReceivePropsName\n : '') +\n (foundWillUpdateName !== null ? '\\n ' + foundWillUpdateName : '') +\n '\\n\\nThe above lifecycles should be removed. Learn more about this warning here:\\n' +\n 'https://fb.me/react-async-component-lifecycle-hooks'\n );\n }\n\n // React <= 16.2 does not support static getDerivedStateFromProps.\n // As a workaround, use cWM and cWRP to invoke the new static lifecycle.\n // Newer versions of React will ignore these lifecycles if gDSFP exists.\n if (typeof Component.getDerivedStateFromProps === 'function') {\n prototype.componentWillMount = componentWillMount;\n prototype.componentWillReceiveProps = componentWillReceiveProps;\n }\n\n // React <= 16.2 does not support getSnapshotBeforeUpdate.\n // As a workaround, use cWU to invoke the new lifecycle.\n // Newer versions of React will ignore that lifecycle if gSBU exists.\n if (typeof prototype.getSnapshotBeforeUpdate === 'function') {\n if (typeof prototype.componentDidUpdate !== 'function') {\n throw new Error(\n 'Cannot polyfill getSnapshotBeforeUpdate() for components that do not define componentDidUpdate() on the prototype'\n );\n }\n\n prototype.componentWillUpdate = componentWillUpdate;\n\n var componentDidUpdate = prototype.componentDidUpdate;\n\n prototype.componentDidUpdate = function componentDidUpdatePolyfill(\n prevProps,\n prevState,\n maybeSnapshot\n ) {\n // 16.3+ will not execute our will-update method;\n // It will pass a snapshot value to did-update though.\n // Older versions will require our polyfilled will-update value.\n // We need to handle both cases, but can't just check for the presence of \"maybeSnapshot\",\n // Because for <= 15.x versions this might be a \"prevContext\" object.\n // We also can't just check \"__reactInternalSnapshot\",\n // Because get-snapshot might return a falsy value.\n // So check for the explicit __reactInternalSnapshotFlag flag to determine behavior.\n var snapshot = this.__reactInternalSnapshotFlag\n ? this.__reactInternalSnapshot\n : maybeSnapshot;\n\n componentDidUpdate.call(this, prevProps, prevState, snapshot);\n };\n }\n\n return Component;\n}\n\nexport { polyfill };\n","import React, { createFactory, Component, createElement } from 'react';\nimport _extends from '@babel/runtime/helpers/esm/extends';\nimport shallowEqual from 'fbjs/lib/shallowEqual';\nimport _inheritsLoose from '@babel/runtime/helpers/esm/inheritsLoose';\nimport { polyfill } from 'react-lifecycles-compat';\nimport _objectWithoutPropertiesLoose from '@babel/runtime/helpers/esm/objectWithoutPropertiesLoose';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport { createChangeEmitter } from 'change-emitter';\nimport $$observable from 'symbol-observable';\n\nvar setStatic = function setStatic(key, value) {\n return function (BaseComponent) {\n /* eslint-disable no-param-reassign */\n BaseComponent[key] = value;\n /* eslint-enable no-param-reassign */\n\n return BaseComponent;\n };\n};\n\nvar setDisplayName = function setDisplayName(displayName) {\n return setStatic('displayName', displayName);\n};\n\nvar getDisplayName = function getDisplayName(Component$$1) {\n if (typeof Component$$1 === 'string') {\n return Component$$1;\n }\n\n if (!Component$$1) {\n return undefined;\n }\n\n return Component$$1.displayName || Component$$1.name || 'Component';\n};\n\nvar wrapDisplayName = function wrapDisplayName(BaseComponent, hocName) {\n return hocName + \"(\" + getDisplayName(BaseComponent) + \")\";\n};\n\nvar mapProps = function mapProps(propsMapper) {\n return function (BaseComponent) {\n var factory = createFactory(BaseComponent);\n\n var MapProps = function MapProps(props) {\n return factory(propsMapper(props));\n };\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'mapProps'))(MapProps);\n }\n\n return MapProps;\n };\n};\n\nvar withProps = function withProps(input) {\n var hoc = mapProps(function (props) {\n return _extends({}, props, typeof input === 'function' ? input(props) : input);\n });\n\n if (process.env.NODE_ENV !== 'production') {\n return function (BaseComponent) {\n return setDisplayName(wrapDisplayName(BaseComponent, 'withProps'))(hoc(BaseComponent));\n };\n }\n\n return hoc;\n};\n\nvar pick = function pick(obj, keys) {\n var result = {};\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n\n if (obj.hasOwnProperty(key)) {\n result[key] = obj[key];\n }\n }\n\n return result;\n};\n\nvar withPropsOnChange = function withPropsOnChange(shouldMapOrKeys, propsMapper) {\n return function (BaseComponent) {\n var factory = createFactory(BaseComponent);\n var shouldMap = typeof shouldMapOrKeys === 'function' ? shouldMapOrKeys : function (props, nextProps) {\n return !shallowEqual(pick(props, shouldMapOrKeys), pick(nextProps, shouldMapOrKeys));\n };\n\n var WithPropsOnChange =\n /*#__PURE__*/\n function (_Component) {\n _inheritsLoose(WithPropsOnChange, _Component);\n\n function WithPropsOnChange() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _Component.call.apply(_Component, [this].concat(args)) || this;\n _this.state = {\n computedProps: propsMapper(_this.props),\n prevProps: _this.props\n };\n return _this;\n }\n\n WithPropsOnChange.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {\n if (shouldMap(prevState.prevProps, nextProps)) {\n return {\n computedProps: propsMapper(nextProps),\n prevProps: nextProps\n };\n }\n\n return {\n prevProps: nextProps\n };\n };\n\n var _proto = WithPropsOnChange.prototype;\n\n _proto.render = function render() {\n return factory(_extends({}, this.props, this.state.computedProps));\n };\n\n return WithPropsOnChange;\n }(Component);\n\n polyfill(WithPropsOnChange);\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'withPropsOnChange'))(WithPropsOnChange);\n }\n\n return WithPropsOnChange;\n };\n};\n\nvar mapValues = function mapValues(obj, func) {\n var result = {};\n /* eslint-disable no-restricted-syntax */\n\n for (var key in obj) {\n if (obj.hasOwnProperty(key)) {\n result[key] = func(obj[key], key);\n }\n }\n /* eslint-enable no-restricted-syntax */\n\n\n return result;\n};\n\nvar withHandlers = function withHandlers(handlers) {\n return function (BaseComponent) {\n var factory = createFactory(BaseComponent);\n\n var WithHandlers =\n /*#__PURE__*/\n function (_Component) {\n _inheritsLoose(WithHandlers, _Component);\n\n function WithHandlers() {\n var _this;\n\n for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {\n _args[_key] = arguments[_key];\n }\n\n _this = _Component.call.apply(_Component, [this].concat(_args)) || this;\n _this.handlers = mapValues(typeof handlers === 'function' ? handlers(_this.props) : handlers, function (createHandler) {\n return function () {\n var handler = createHandler(_this.props);\n\n if (process.env.NODE_ENV !== 'production' && typeof handler !== 'function') {\n console.error( // eslint-disable-line no-console\n 'withHandlers(): Expected a map of higher-order functions. ' + 'Refer to the docs for more info.');\n }\n\n return handler.apply(void 0, arguments);\n };\n });\n return _this;\n }\n\n var _proto = WithHandlers.prototype;\n\n _proto.render = function render() {\n return factory(_extends({}, this.props, this.handlers));\n };\n\n return WithHandlers;\n }(Component);\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'withHandlers'))(WithHandlers);\n }\n\n return WithHandlers;\n };\n};\n\nvar defaultProps = function defaultProps(props) {\n return function (BaseComponent) {\n var factory = createFactory(BaseComponent);\n\n var DefaultProps = function DefaultProps(ownerProps) {\n return factory(ownerProps);\n };\n\n DefaultProps.defaultProps = props;\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'defaultProps'))(DefaultProps);\n }\n\n return DefaultProps;\n };\n};\n\nvar omit = function omit(obj, keys) {\n var rest = _extends({}, obj);\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n\n if (rest.hasOwnProperty(key)) {\n delete rest[key];\n }\n }\n\n return rest;\n};\n\nvar renameProp = function renameProp(oldName, newName) {\n var hoc = mapProps(function (props) {\n var _extends2;\n\n return _extends({}, omit(props, [oldName]), (_extends2 = {}, _extends2[newName] = props[oldName], _extends2));\n });\n\n if (process.env.NODE_ENV !== 'production') {\n return function (BaseComponent) {\n return setDisplayName(wrapDisplayName(BaseComponent, 'renameProp'))(hoc(BaseComponent));\n };\n }\n\n return hoc;\n};\n\nvar keys = Object.keys;\n\nvar mapKeys = function mapKeys(obj, func) {\n return keys(obj).reduce(function (result, key) {\n var val = obj[key];\n /* eslint-disable no-param-reassign */\n\n result[func(val, key)] = val;\n /* eslint-enable no-param-reassign */\n\n return result;\n }, {});\n};\n\nvar renameProps = function renameProps(nameMap) {\n var hoc = mapProps(function (props) {\n return _extends({}, omit(props, keys(nameMap)), mapKeys(pick(props, keys(nameMap)), function (_, oldName) {\n return nameMap[oldName];\n }));\n });\n\n if (process.env.NODE_ENV !== 'production') {\n return function (BaseComponent) {\n return setDisplayName(wrapDisplayName(BaseComponent, 'renameProps'))(hoc(BaseComponent));\n };\n }\n\n return hoc;\n};\n\nvar flattenProp = function flattenProp(propName) {\n return function (BaseComponent) {\n var factory = createFactory(BaseComponent);\n\n var FlattenProp = function FlattenProp(props) {\n return factory(_extends({}, props, props[propName]));\n };\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'flattenProp'))(FlattenProp);\n }\n\n return FlattenProp;\n };\n};\n\nvar withState = function withState(stateName, stateUpdaterName, initialState) {\n return function (BaseComponent) {\n var factory = createFactory(BaseComponent);\n\n var WithState =\n /*#__PURE__*/\n function (_Component) {\n _inheritsLoose(WithState, _Component);\n\n function WithState() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _Component.call.apply(_Component, [this].concat(args)) || this;\n _this.state = {\n stateValue: typeof initialState === 'function' ? initialState(_this.props) : initialState\n };\n\n _this.updateStateValue = function (updateFn, callback) {\n return _this.setState(function (_ref) {\n var stateValue = _ref.stateValue;\n return {\n stateValue: typeof updateFn === 'function' ? updateFn(stateValue) : updateFn\n };\n }, callback);\n };\n\n return _this;\n }\n\n var _proto = WithState.prototype;\n\n _proto.render = function render() {\n var _extends2;\n\n return factory(_extends({}, this.props, (_extends2 = {}, _extends2[stateName] = this.state.stateValue, _extends2[stateUpdaterName] = this.updateStateValue, _extends2)));\n };\n\n return WithState;\n }(Component);\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'withState'))(WithState);\n }\n\n return WithState;\n };\n};\n\nvar withStateHandlers = function withStateHandlers(initialState, stateUpdaters) {\n return function (BaseComponent) {\n var factory = createFactory(BaseComponent);\n\n var WithStateHandlers =\n /*#__PURE__*/\n function (_Component) {\n _inheritsLoose(WithStateHandlers, _Component);\n\n function WithStateHandlers() {\n var _this;\n\n for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {\n _args[_key] = arguments[_key];\n }\n\n _this = _Component.call.apply(_Component, [this].concat(_args)) || this;\n _this.state = typeof initialState === 'function' ? initialState(_this.props) : initialState;\n _this.stateUpdaters = mapValues(stateUpdaters, function (handler) {\n return function (mayBeEvent) {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n // Having that functional form of setState can be called async\n // we need to persist SyntheticEvent\n if (mayBeEvent && typeof mayBeEvent.persist === 'function') {\n mayBeEvent.persist();\n }\n\n _this.setState(function (state, props) {\n return handler(state, props).apply(void 0, [mayBeEvent].concat(args));\n });\n };\n });\n return _this;\n }\n\n var _proto = WithStateHandlers.prototype;\n\n _proto.render = function render() {\n return factory(_extends({}, this.props, this.state, this.stateUpdaters));\n };\n\n return WithStateHandlers;\n }(Component);\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'withStateHandlers'))(WithStateHandlers);\n }\n\n return WithStateHandlers;\n };\n};\n\nvar noop = function noop() {};\n\nvar withReducer = function withReducer(stateName, dispatchName, reducer, initialState) {\n return function (BaseComponent) {\n var factory = createFactory(BaseComponent);\n\n var WithReducer =\n /*#__PURE__*/\n function (_Component) {\n _inheritsLoose(WithReducer, _Component);\n\n function WithReducer() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _Component.call.apply(_Component, [this].concat(args)) || this;\n _this.state = {\n stateValue: _this.initializeStateValue()\n };\n\n _this.dispatch = function (action, callback) {\n if (callback === void 0) {\n callback = noop;\n }\n\n return _this.setState(function (_ref) {\n var stateValue = _ref.stateValue;\n return {\n stateValue: reducer(stateValue, action)\n };\n }, function () {\n return callback(_this.state.stateValue);\n });\n };\n\n return _this;\n }\n\n var _proto = WithReducer.prototype;\n\n _proto.initializeStateValue = function initializeStateValue() {\n if (initialState !== undefined) {\n return typeof initialState === 'function' ? initialState(this.props) : initialState;\n }\n\n return reducer(undefined, {\n type: '@@recompose/INIT'\n });\n };\n\n _proto.render = function render() {\n var _extends2;\n\n return factory(_extends({}, this.props, (_extends2 = {}, _extends2[stateName] = this.state.stateValue, _extends2[dispatchName] = this.dispatch, _extends2)));\n };\n\n return WithReducer;\n }(Component);\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'withReducer'))(WithReducer);\n }\n\n return WithReducer;\n };\n};\n\nvar identity = function identity(Component$$1) {\n return Component$$1;\n};\n\nvar branch = function branch(test, left, right) {\n if (right === void 0) {\n right = identity;\n }\n\n return function (BaseComponent) {\n var leftFactory;\n var rightFactory;\n\n var Branch = function Branch(props) {\n if (test(props)) {\n leftFactory = leftFactory || createFactory(left(BaseComponent));\n return leftFactory(props);\n }\n\n rightFactory = rightFactory || createFactory(right(BaseComponent));\n return rightFactory(props);\n };\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'branch'))(Branch);\n }\n\n return Branch;\n };\n};\n\nvar renderComponent = function renderComponent(Component$$1) {\n return function (_) {\n var factory = createFactory(Component$$1);\n\n var RenderComponent = function RenderComponent(props) {\n return factory(props);\n };\n\n if (process.env.NODE_ENV !== 'production') {\n RenderComponent.displayName = wrapDisplayName(Component$$1, 'renderComponent');\n }\n\n return RenderComponent;\n };\n};\n\nvar Nothing =\n/*#__PURE__*/\nfunction (_Component) {\n _inheritsLoose(Nothing, _Component);\n\n function Nothing() {\n return _Component.apply(this, arguments) || this;\n }\n\n var _proto = Nothing.prototype;\n\n _proto.render = function render() {\n return null;\n };\n\n return Nothing;\n}(Component);\n\nvar renderNothing = function renderNothing(_) {\n return Nothing;\n};\n\nvar shouldUpdate = function shouldUpdate(test) {\n return function (BaseComponent) {\n var factory = createFactory(BaseComponent);\n\n var ShouldUpdate =\n /*#__PURE__*/\n function (_Component) {\n _inheritsLoose(ShouldUpdate, _Component);\n\n function ShouldUpdate() {\n return _Component.apply(this, arguments) || this;\n }\n\n var _proto = ShouldUpdate.prototype;\n\n _proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {\n return test(this.props, nextProps);\n };\n\n _proto.render = function render() {\n return factory(this.props);\n };\n\n return ShouldUpdate;\n }(Component);\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'shouldUpdate'))(ShouldUpdate);\n }\n\n return ShouldUpdate;\n };\n};\n\nvar pure = function pure(BaseComponent) {\n var hoc = shouldUpdate(function (props, nextProps) {\n return !shallowEqual(props, nextProps);\n });\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'pure'))(hoc(BaseComponent));\n }\n\n return hoc(BaseComponent);\n};\n\nvar onlyUpdateForKeys = function onlyUpdateForKeys(propKeys) {\n var hoc = shouldUpdate(function (props, nextProps) {\n return !shallowEqual(pick(nextProps, propKeys), pick(props, propKeys));\n });\n\n if (process.env.NODE_ENV !== 'production') {\n return function (BaseComponent) {\n return setDisplayName(wrapDisplayName(BaseComponent, 'onlyUpdateForKeys'))(hoc(BaseComponent));\n };\n }\n\n return hoc;\n};\n\nvar onlyUpdateForPropTypes = function onlyUpdateForPropTypes(BaseComponent) {\n var propTypes = BaseComponent.propTypes;\n\n if (process.env.NODE_ENV !== 'production') {\n if (!propTypes) {\n /* eslint-disable */\n console.error('A component without any `propTypes` was passed to ' + '`onlyUpdateForPropTypes()`. Check the implementation of the ' + (\"component with display name \\\"\" + getDisplayName(BaseComponent) + \"\\\".\"));\n /* eslint-enable */\n }\n }\n\n var propKeys = Object.keys(propTypes || {});\n var OnlyUpdateForPropTypes = onlyUpdateForKeys(propKeys)(BaseComponent);\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'onlyUpdateForPropTypes'))(OnlyUpdateForPropTypes);\n }\n\n return OnlyUpdateForPropTypes;\n};\n\nvar withContext = function withContext(childContextTypes, getChildContext) {\n return function (BaseComponent) {\n var factory = createFactory(BaseComponent);\n\n var WithContext =\n /*#__PURE__*/\n function (_Component) {\n _inheritsLoose(WithContext, _Component);\n\n function WithContext() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _Component.call.apply(_Component, [this].concat(args)) || this;\n\n _this.getChildContext = function () {\n return getChildContext(_this.props);\n };\n\n return _this;\n }\n\n var _proto = WithContext.prototype;\n\n _proto.render = function render() {\n return factory(this.props);\n };\n\n return WithContext;\n }(Component);\n\n WithContext.childContextTypes = childContextTypes;\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'withContext'))(WithContext);\n }\n\n return WithContext;\n };\n};\n\nvar getContext = function getContext(contextTypes) {\n return function (BaseComponent) {\n var factory = createFactory(BaseComponent);\n\n var GetContext = function GetContext(ownerProps, context) {\n return factory(_extends({}, ownerProps, context));\n };\n\n GetContext.contextTypes = contextTypes;\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'getContext'))(GetContext);\n }\n\n return GetContext;\n };\n};\n\nvar lifecycle = function lifecycle(spec) {\n return function (BaseComponent) {\n var factory = createFactory(BaseComponent);\n\n if (process.env.NODE_ENV !== 'production' && spec.hasOwnProperty('render')) {\n console.error('lifecycle() does not support the render method; its behavior is to ' + 'pass all props and state to the base component.');\n }\n\n var Lifecycle =\n /*#__PURE__*/\n function (_Component) {\n _inheritsLoose(Lifecycle, _Component);\n\n function Lifecycle() {\n return _Component.apply(this, arguments) || this;\n }\n\n var _proto = Lifecycle.prototype;\n\n _proto.render = function render() {\n return factory(_extends({}, this.props, this.state));\n };\n\n return Lifecycle;\n }(Component);\n\n Object.keys(spec).forEach(function (hook) {\n return Lifecycle.prototype[hook] = spec[hook];\n });\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'lifecycle'))(Lifecycle);\n }\n\n return Lifecycle;\n };\n};\n\nvar isClassComponent = function isClassComponent(Component$$1) {\n return Boolean(Component$$1 && Component$$1.prototype && typeof Component$$1.prototype.render === 'function');\n};\n\nvar toClass = function toClass(baseComponent) {\n var _class, _temp;\n\n return isClassComponent(baseComponent) ? baseComponent : (_temp = _class =\n /*#__PURE__*/\n function (_Component) {\n _inheritsLoose(ToClass, _Component);\n\n function ToClass() {\n return _Component.apply(this, arguments) || this;\n }\n\n var _proto = ToClass.prototype;\n\n _proto.render = function render() {\n if (typeof baseComponent === 'string') {\n return React.createElement(baseComponent, this.props);\n }\n\n return baseComponent(this.props, this.context);\n };\n\n return ToClass;\n }(Component), _class.displayName = getDisplayName(baseComponent), _class.propTypes = baseComponent.propTypes, _class.contextTypes = baseComponent.contextTypes, _class.defaultProps = baseComponent.defaultProps, _temp);\n};\n\nfunction toRenderProps(hoc) {\n var RenderPropsComponent = function RenderPropsComponent(props) {\n return props.children(props);\n };\n\n return hoc(RenderPropsComponent);\n}\n\nvar fromRenderProps = function fromRenderProps(RenderPropsComponent, propsMapper, renderPropName) {\n if (renderPropName === void 0) {\n renderPropName = 'children';\n }\n\n return function (BaseComponent) {\n var baseFactory = React.createFactory(BaseComponent);\n var renderPropsFactory = React.createFactory(RenderPropsComponent);\n\n var FromRenderProps = function FromRenderProps(ownerProps) {\n var _renderPropsFactory;\n\n return renderPropsFactory((_renderPropsFactory = {}, _renderPropsFactory[renderPropName] = function () {\n return baseFactory(_extends({}, ownerProps, propsMapper.apply(void 0, arguments)));\n }, _renderPropsFactory));\n };\n\n if (process.env.NODE_ENV !== 'production') {\n return setDisplayName(wrapDisplayName(BaseComponent, 'fromRenderProps'))(FromRenderProps);\n }\n\n return FromRenderProps;\n };\n};\n\nvar setPropTypes = function setPropTypes(propTypes) {\n return setStatic('propTypes', propTypes);\n};\n\nvar compose = function compose() {\n for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {\n funcs[_key] = arguments[_key];\n }\n\n return funcs.reduce(function (a, b) {\n return function () {\n return a(b.apply(void 0, arguments));\n };\n }, function (arg) {\n return arg;\n });\n};\n\nvar createSink = function createSink(callback) {\n var Sink =\n /*#__PURE__*/\n function (_Component) {\n _inheritsLoose(Sink, _Component);\n\n function Sink() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _Component.call.apply(_Component, [this].concat(args)) || this;\n _this.state = {};\n return _this;\n }\n\n Sink.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps) {\n callback(nextProps);\n return null;\n };\n\n var _proto = Sink.prototype;\n\n _proto.render = function render() {\n return null;\n };\n\n return Sink;\n }(Component);\n\n polyfill(Sink);\n return Sink;\n};\n\nvar componentFromProp = function componentFromProp(propName) {\n var Component$$1 = function Component$$1(props) {\n return createElement(props[propName], omit(props, [propName]));\n };\n\n Component$$1.displayName = \"componentFromProp(\" + propName + \")\";\n return Component$$1;\n};\n\nvar nest = function nest() {\n for (var _len = arguments.length, Components = new Array(_len), _key = 0; _key < _len; _key++) {\n Components[_key] = arguments[_key];\n }\n\n var factories = Components.map(createFactory);\n\n var Nest = function Nest(_ref) {\n var children = _ref.children,\n props = _objectWithoutPropertiesLoose(_ref, [\"children\"]);\n\n return factories.reduceRight(function (child, factory) {\n return factory(props, child);\n }, children);\n };\n\n if (process.env.NODE_ENV !== 'production') {\n var displayNames = Components.map(getDisplayName);\n Nest.displayName = \"nest(\" + displayNames.join(', ') + \")\";\n }\n\n return Nest;\n};\n\nvar hoistStatics = function hoistStatics(higherOrderComponent, blacklist) {\n return function (BaseComponent) {\n var NewComponent = higherOrderComponent(BaseComponent);\n hoistNonReactStatics(NewComponent, BaseComponent, blacklist);\n return NewComponent;\n };\n};\n\nvar _config = {\n fromESObservable: null,\n toESObservable: null\n};\n\nvar configureObservable = function configureObservable(c) {\n _config = c;\n};\n\nvar config = {\n fromESObservable: function fromESObservable(observable) {\n return typeof _config.fromESObservable === 'function' ? _config.fromESObservable(observable) : observable;\n },\n toESObservable: function toESObservable(stream) {\n return typeof _config.toESObservable === 'function' ? _config.toESObservable(stream) : stream;\n }\n};\n\nvar componentFromStreamWithConfig = function componentFromStreamWithConfig(config$$1) {\n return function (propsToVdom) {\n return (\n /*#__PURE__*/\n function (_Component) {\n _inheritsLoose(ComponentFromStream, _Component);\n\n function ComponentFromStream() {\n var _config$fromESObserva;\n\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _Component.call.apply(_Component, [this].concat(args)) || this;\n _this.state = {\n vdom: null\n };\n _this.propsEmitter = createChangeEmitter();\n _this.props$ = config$$1.fromESObservable((_config$fromESObserva = {\n subscribe: function subscribe(observer) {\n var unsubscribe = _this.propsEmitter.listen(function (props) {\n if (props) {\n observer.next(props);\n } else {\n observer.complete();\n }\n });\n\n return {\n unsubscribe: unsubscribe\n };\n }\n }, _config$fromESObserva[$$observable] = function () {\n return this;\n }, _config$fromESObserva));\n _this.vdom$ = config$$1.toESObservable(propsToVdom(_this.props$));\n return _this;\n }\n\n var _proto = ComponentFromStream.prototype;\n\n _proto.componentWillMount = function componentWillMount() {\n var _this2 = this;\n\n // Subscribe to child prop changes so we know when to re-render\n this.subscription = this.vdom$.subscribe({\n next: function next(vdom) {\n _this2.setState({\n vdom: vdom\n });\n }\n });\n this.propsEmitter.emit(this.props);\n };\n\n _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {\n // Receive new props from the owner\n this.propsEmitter.emit(nextProps);\n };\n\n _proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {\n return nextState.vdom !== this.state.vdom;\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n // Call without arguments to complete stream\n this.propsEmitter.emit(); // Clean-up subscription before un-mounting\n\n this.subscription.unsubscribe();\n };\n\n _proto.render = function render() {\n return this.state.vdom;\n };\n\n return ComponentFromStream;\n }(Component)\n );\n };\n};\n\nvar componentFromStream = function componentFromStream(propsToVdom) {\n return componentFromStreamWithConfig(config)(propsToVdom);\n};\n\nvar identity$1 = function identity(t) {\n return t;\n};\n\nvar mapPropsStreamWithConfig = function mapPropsStreamWithConfig(config$$1) {\n var componentFromStream$$1 = componentFromStreamWithConfig({\n fromESObservable: identity$1,\n toESObservable: identity$1\n });\n return function (transform) {\n return function (BaseComponent) {\n var factory = createFactory(BaseComponent);\n var fromESObservable = config$$1.fromESObservable,\n toESObservable = config$$1.toESObservable;\n return componentFromStream$$1(function (props$) {\n var _ref;\n\n return _ref = {\n subscribe: function subscribe(observer) {\n var subscription = toESObservable(transform(fromESObservable(props$))).subscribe({\n next: function next(childProps) {\n return observer.next(factory(childProps));\n }\n });\n return {\n unsubscribe: function unsubscribe() {\n return subscription.unsubscribe();\n }\n };\n }\n }, _ref[$$observable] = function () {\n return this;\n }, _ref;\n });\n };\n };\n};\n\nvar mapPropsStream = function mapPropsStream(transform) {\n var hoc = mapPropsStreamWithConfig(config)(transform);\n\n if (process.env.NODE_ENV !== 'production') {\n return function (BaseComponent) {\n return setDisplayName(wrapDisplayName(BaseComponent, 'mapPropsStream'))(hoc(BaseComponent));\n };\n }\n\n return hoc;\n};\n\nvar createEventHandlerWithConfig = function createEventHandlerWithConfig(config$$1) {\n return function () {\n var _config$fromESObserva;\n\n var emitter = createChangeEmitter();\n var stream = config$$1.fromESObservable((_config$fromESObserva = {\n subscribe: function subscribe(observer) {\n var unsubscribe = emitter.listen(function (value) {\n return observer.next(value);\n });\n return {\n unsubscribe: unsubscribe\n };\n }\n }, _config$fromESObserva[$$observable] = function () {\n return this;\n }, _config$fromESObserva));\n return {\n handler: emitter.emit,\n stream: stream\n };\n };\n};\nvar createEventHandler = createEventHandlerWithConfig(config);\n\n// Higher-order component helpers\n\nexport { mapProps, withProps, withPropsOnChange, withHandlers, defaultProps, renameProp, renameProps, flattenProp, withState, withStateHandlers, withReducer, branch, renderComponent, renderNothing, shouldUpdate, pure, onlyUpdateForKeys, onlyUpdateForPropTypes, withContext, getContext, lifecycle, toClass, toRenderProps, fromRenderProps, setStatic, setPropTypes, setDisplayName, compose, getDisplayName, wrapDisplayName, shallowEqual, isClassComponent, createSink, componentFromProp, nest, hoistStatics, componentFromStream, componentFromStreamWithConfig, mapPropsStream, mapPropsStreamWithConfig, createEventHandler, createEventHandlerWithConfig, configureObservable as setObservableConfig };\n","import Sniffr from 'sniffr';\n\nconst sniffr = new Sniffr();\nsniffr.sniff();\n\nexport default sniffr;\n","export default function memoize(fn) {\n const primitiveCache = new Map();\n const objectCache = new WeakMap();\n return function memoized(arg = '__singleValue__') {\n const cache = arg instanceof Object ? objectCache : primitiveCache;\n if (cache.has(arg)) {\n return cache.get(arg);\n }\n\n const value = fn(arg);\n cache.set(arg, value);\n return value;\n };\n}\n","// Inspired by https://github.com/sairion/svg-inline-react\nimport React from 'react';\nimport classNames from 'classnames';\nimport PropTypes from 'prop-types';\nimport {pure} from 'recompose';\n\nimport sniffer from '../global/sniffer';\nimport memoize from '../global/memoize';\n\nimport styles from './icon.css';\n\nconst isIE = sniffer.browser.name === 'ie';\n\nfunction convertReactSVGDOMProperty(str) {\n return str.replace(/[-|:]([a-z])/g, g => g[1].toUpperCase());\n}\n\nfunction serializeAttrs(map) {\n const res = {};\n for (let i = 0; i < map.length; i++) {\n const key = map[i].name;\n let prop = key;\n if (key === 'class') {\n prop = 'className';\n } else if (!key.startsWith('data-')) {\n prop = convertReactSVGDOMProperty(key);\n }\n\n res[prop] = map[i].value;\n }\n return res;\n}\n\nfunction getSVGInnerHTML(svgNode) {\n if (!isIE) {\n return svgNode.innerHTML;\n }\n // IE11 doesn't support svg.innerHTML https://stackoverflow.com/questions/28129956/get-innerhtml-of-svg-tag-result-in-undefined-in-ie\n const serializer = new XMLSerializer();\n\n return Array.from(svgNode.childNodes).\n map(child => serializer.serializeToString(child)).\n join('');\n}\n\nfunction extractSVGProps(svgNode) {\n const map = svgNode.attributes;\n return (map.length > 0) ? serializeAttrs(map) : null;\n}\n\nconst getSVGFromSource = memoize(src => {\n const svgContainer = document.createElement('div');\n svgContainer.innerHTML = src;\n const svg = svgContainer.firstElementChild;\n svg.remove ? svg.remove() : svgContainer.removeChild(svg);\n return {\n props: extractSVGProps(svg),\n html: getSVGInnerHTML(svg)\n };\n});\n\nfunction isCompatibilityMode(iconSrc) {\n const hasWidth = /width=\"[\\d\\.]+\"/ig.test(iconSrc);\n const hasHeight = /height=\"[\\d\\.]+\"/ig.test(iconSrc);\n return !hasWidth || !hasHeight;\n}\n\nfunction IconSVG({src, className, ...rest}) {\n const glyphClasses = classNames(styles.glyph, {\n [styles.compatibilityMode]: isCompatibilityMode(src)\n }, className);\n\n const {props, html} = getSVGFromSource(src);\n\n return (\n \n );\n}\n\nIconSVG.propTypes = {\n className: PropTypes.string,\n src: PropTypes.string.isRequired,\n style: PropTypes.object\n};\n\nexport default pure(IconSVG);\n","/**\n * @name Icon\n */\n\nimport React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport deprecate from 'util-deprecate';\n\nimport {Color, Size} from './icon__constants';\nimport styles from './icon.css';\nimport IconSVG from './icon__svg';\n\nconst warnSize = deprecate(\n () => {},\n `\\`size\\`, \\`width\\` and \\`height\\` props are not recommended to use in Ring UI \\`Icon\\` component. The intrinsic sizes of SVG icon (\\`width\\` and \\`height\\` SVG attributes) are used instead.\n\nWe strongly recommend to use icons handcrafted for particular sizes. If your icon doesn't exist in the desired size, please ask your designer to draw one. \"Responsive\" checkmark should be unchecked when exporting icon.'`\n);\n\nexport default class Icon extends PureComponent {\n static propTypes = {\n className: PropTypes.string,\n color: PropTypes.string,\n glyph: PropTypes.oneOfType([PropTypes.string, PropTypes.elementType]),\n height: PropTypes.number,\n size: PropTypes.number,\n width: PropTypes.number,\n loading: PropTypes.bool,\n suppressSizeWarning: PropTypes.bool\n };\n\n static defaultProps = ({\n className: '',\n color: Color.DEFAULT,\n glyph: ''\n });\n\n static Color = Color;\n static Size = Size;\n\n warnSize() {\n if (this.props.suppressSizeWarning) {\n return;\n }\n warnSize();\n }\n\n getStyle() {\n const {size, width, height} = this.props;\n if (width || height) {\n this.warnSize();\n return {width, height};\n }\n if (size) {\n this.warnSize();\n return {\n width: size,\n height: size\n };\n }\n return null;\n }\n\n getIconSource() {\n const {glyph} = this.props;\n return glyph?.isRingIcon ? glyph.glyph : glyph;\n }\n\n render() {\n const {\n className, size, color, loading, glyph, width, height, suppressSizeWarning,\n ...restProps\n } = this.props;\n\n const IconSrc = this.getIconSource();\n if (!IconSrc) {\n // eslint-disable-next-line no-console\n console.warn('No icon source passed to Icon component', this.props);\n return null;\n }\n\n const classes = classNames(styles.icon,\n {\n [styles[color]]: !!color,\n [styles.loading]: loading\n },\n className\n );\n\n return (\n \n {typeof IconSrc === 'string'\n ? \n : \n }\n \n );\n }\n}\n\nexport {Size};\n\nexport function iconHOC(glyph, displayName) {\n // eslint-disable-next-line react/no-multi-comp\n return class BoundIcon extends PureComponent {\n // Compatibility with angular\n static toString() {\n return glyph;\n }\n\n static displayName = displayName;\n\n static propTypes = {\n iconRef: PropTypes.func\n };\n\n static Color = Color;\n static Size = Size;\n static isRingIcon = true;\n static glyph = glyph;\n\n render() {\n const {iconRef, ...restProps} = this.props;\n return ;\n }\n };\n}\n","/* eslint-disable max-len */\n/* This is a generated file. If you want to change it, edit generate-exports instead. */\n\nimport activity from '@jetbrains/icons/activity.svg';\nimport add10px from '@jetbrains/icons/add-10px.svg';\nimport add20px from '@jetbrains/icons/add-20px.svg';\nimport add from '@jetbrains/icons/add.svg';\nimport analytics from '@jetbrains/icons/analytics.svg';\nimport archive from '@jetbrains/icons/archive.svg';\nimport arrowUp from '@jetbrains/icons/arrow-up.svg';\nimport artifacts from '@jetbrains/icons/artifacts.svg';\nimport asterisk10px from '@jetbrains/icons/asterisk-10px.svg';\nimport asterisk from '@jetbrains/icons/asterisk.svg';\nimport attachment from '@jetbrains/icons/attachment.svg';\nimport average from '@jetbrains/icons/average.svg';\nimport bars from '@jetbrains/icons/bars.svg';\nimport bell from '@jetbrains/icons/bell.svg';\nimport branches from '@jetbrains/icons/branches.svg';\nimport bug from '@jetbrains/icons/bug.svg';\nimport buildType14pxArrow from '@jetbrains/icons/buildType-14px-arrow.svg';\nimport buildType14pxFillArrow from '@jetbrains/icons/buildType-14px-fill-arrow.svg';\nimport buildType14pxFill from '@jetbrains/icons/buildType-14px-fill.svg';\nimport buildType14px from '@jetbrains/icons/buildType-14px.svg';\nimport buildType20pxArrow from '@jetbrains/icons/buildType-20px-arrow.svg';\nimport buildType20pxFillArrow from '@jetbrains/icons/buildType-20px-fill-arrow.svg';\nimport buildType20pxFill from '@jetbrains/icons/buildType-20px-fill.svg';\nimport buildType20px from '@jetbrains/icons/buildType-20px.svg';\nimport buildTypeComposite14pxArrow from '@jetbrains/icons/buildType-composite-14px-arrow.svg';\nimport buildTypeComposite14pxFillArrow from '@jetbrains/icons/buildType-composite-14px-fill-arrow.svg';\nimport buildTypeComposite14pxFill from '@jetbrains/icons/buildType-composite-14px-fill.svg';\nimport buildTypeComposite14px from '@jetbrains/icons/buildType-composite-14px.svg';\nimport buildTypeComposite20pxArrow from '@jetbrains/icons/buildType-composite-20px-arrow.svg';\nimport buildTypeComposite20pxFillArrow from '@jetbrains/icons/buildType-composite-20px-fill-arrow.svg';\nimport buildTypeComposite20pxFill from '@jetbrains/icons/buildType-composite-20px-fill.svg';\nimport buildTypeComposite20px from '@jetbrains/icons/buildType-composite-20px.svg';\nimport burndown from '@jetbrains/icons/burndown.svg';\nimport calendar from '@jetbrains/icons/calendar.svg';\nimport cancel20px from '@jetbrains/icons/cancel-20px.svg';\nimport cancel from '@jetbrains/icons/cancel.svg';\nimport caretDown10px from '@jetbrains/icons/caret-down-10px.svg';\nimport caretRight10px from '@jetbrains/icons/caret-right-10px.svg';\nimport change from '@jetbrains/icons/change.svg';\nimport checkmark from '@jetbrains/icons/checkmark.svg';\nimport chevron10px from '@jetbrains/icons/chevron-10px.svg';\nimport chevronDown from '@jetbrains/icons/chevron-down.svg';\nimport chevronLeft from '@jetbrains/icons/chevron-left.svg';\nimport chevronRight from '@jetbrains/icons/chevron-right.svg';\nimport chevronUp from '@jetbrains/icons/chevron-up.svg';\nimport close from '@jetbrains/icons/close.svg';\nimport cloud from '@jetbrains/icons/cloud.svg';\nimport code from '@jetbrains/icons/code.svg';\nimport collapse from '@jetbrains/icons/collapse.svg';\nimport comment from '@jetbrains/icons/comment.svg';\nimport compare from '@jetbrains/icons/compare.svg';\nimport copy from '@jetbrains/icons/copy.svg';\nimport crop from '@jetbrains/icons/crop.svg';\nimport data from '@jetbrains/icons/data.svg';\nimport dice from '@jetbrains/icons/dice.svg';\nimport disconnected from '@jetbrains/icons/disconnected.svg';\nimport distribution from '@jetbrains/icons/distribution.svg';\nimport doubleChevronLeft from '@jetbrains/icons/double-chevron-left.svg';\nimport doubleChevronRight from '@jetbrains/icons/double-chevron-right.svg';\nimport download from '@jetbrains/icons/download.svg';\nimport drag from '@jetbrains/icons/drag.svg';\nimport drop from '@jetbrains/icons/drop.svg';\nimport eMail from '@jetbrains/icons/e-mail.svg';\nimport earth from '@jetbrains/icons/earth.svg';\nimport emoji from '@jetbrains/icons/emoji.svg';\nimport entry from '@jetbrains/icons/entry.svg';\nimport exception20px from '@jetbrains/icons/exception-20px.svg';\nimport exception from '@jetbrains/icons/exception.svg';\nimport expand from '@jetbrains/icons/expand.svg';\nimport experiment20px from '@jetbrains/icons/experiment-20px.svg';\nimport eye from '@jetbrains/icons/eye.svg';\nimport fields from '@jetbrains/icons/fields.svg';\nimport fileAddAny from '@jetbrains/icons/file-add-any.svg';\nimport fileArchive from '@jetbrains/icons/file-archive.svg';\nimport fileAs from '@jetbrains/icons/file-as.svg';\nimport fileAspectj from '@jetbrains/icons/file-aspectj.svg';\nimport fileConfig from '@jetbrains/icons/file-config.svg';\nimport fileCss from '@jetbrains/icons/file-css.svg';\nimport fileCustom from '@jetbrains/icons/file-custom.svg';\nimport fileDiagram from '@jetbrains/icons/file-diagram.svg';\nimport fileDtd from '@jetbrains/icons/file-dtd.svg';\nimport fileHtaccess from '@jetbrains/icons/file-htaccess.svg';\nimport fileHtml from '@jetbrains/icons/file-html.svg';\nimport fileIdl from '@jetbrains/icons/file-idl.svg';\nimport fileJavaClass from '@jetbrains/icons/file-java-class.svg';\nimport fileJavaOutsideSource from '@jetbrains/icons/file-java-outside-source.svg';\nimport fileJava from '@jetbrains/icons/file-java.svg';\nimport fileJs from '@jetbrains/icons/file-js.svg';\nimport fileJsonDark from '@jetbrains/icons/file-json-dark.svg';\nimport fileJsonSchemaDark from '@jetbrains/icons/file-json-schema-dark.svg';\nimport fileJsonSchema from '@jetbrains/icons/file-json-schema.svg';\nimport fileJson from '@jetbrains/icons/file-json.svg';\nimport fileJsp from '@jetbrains/icons/file-jsp.svg';\nimport fileJspx from '@jetbrains/icons/file-jspx.svg';\nimport fileManifest from '@jetbrains/icons/file-manifest.svg';\nimport fileProperties from '@jetbrains/icons/file-properties.svg';\nimport fileRegexp from '@jetbrains/icons/file-regexp.svg';\nimport fileText from '@jetbrains/icons/file-text.svg';\nimport fileUiForm from '@jetbrains/icons/file-ui-form.svg';\nimport fileUnknown from '@jetbrains/icons/file-unknown.svg';\nimport fileWsdl from '@jetbrains/icons/file-wsdl.svg';\nimport fileXhtml from '@jetbrains/icons/file-xhtml.svg';\nimport fileXml from '@jetbrains/icons/file-xml.svg';\nimport fileXsd from '@jetbrains/icons/file-xsd.svg';\nimport fileYaml from '@jetbrains/icons/file-yaml.svg';\nimport file from '@jetbrains/icons/file.svg';\nimport filters from '@jetbrains/icons/filters.svg';\nimport flag from '@jetbrains/icons/flag.svg';\nimport folder from '@jetbrains/icons/folder.svg';\nimport frown from '@jetbrains/icons/frown.svg';\nimport gift20px from '@jetbrains/icons/gift-20px.svg';\nimport gift from '@jetbrains/icons/gift.svg';\nimport git from '@jetbrains/icons/git.svg';\nimport group from '@jetbrains/icons/group.svg';\nimport help20px from '@jetbrains/icons/help-20px.svg';\nimport help from '@jetbrains/icons/help.svg';\nimport history from '@jetbrains/icons/history.svg';\nimport hourglass20px from '@jetbrains/icons/hourglass-20px.svg';\nimport hourglass from '@jetbrains/icons/hourglass.svg';\nimport ignored from '@jetbrains/icons/ignored.svg';\nimport info from '@jetbrains/icons/info.svg';\nimport investigation14px from '@jetbrains/icons/investigation-14px.svg';\nimport investigation from '@jetbrains/icons/investigation.svg';\nimport lamp from '@jetbrains/icons/lamp.svg';\nimport link from '@jetbrains/icons/link.svg';\nimport lock from '@jetbrains/icons/lock.svg';\nimport magicWand from '@jetbrains/icons/magic-wand.svg';\nimport mammoth20px from '@jetbrains/icons/mammoth-20px.svg';\nimport marker from '@jetbrains/icons/marker.svg';\nimport meta from '@jetbrains/icons/meta.svg';\nimport modified10px from '@jetbrains/icons/modified-10px.svg';\nimport moreOptions from '@jetbrains/icons/more-options.svg';\nimport moveToTop from '@jetbrains/icons/move-to-top.svg';\nimport move from '@jetbrains/icons/move.svg';\nimport mute from '@jetbrains/icons/mute.svg';\nimport muted from '@jetbrains/icons/muted.svg';\nimport newWindow from '@jetbrains/icons/new-window.svg';\nimport noArtifacts from '@jetbrains/icons/no-artifacts.svg';\nimport ok20px from '@jetbrains/icons/ok-20px.svg';\nimport ok from '@jetbrains/icons/ok.svg';\nimport overtime from '@jetbrains/icons/overtime.svg';\nimport paused14px from '@jetbrains/icons/paused-14px.svg';\nimport paused from '@jetbrains/icons/paused.svg';\nimport pencil from '@jetbrains/icons/pencil.svg';\nimport pennant from '@jetbrains/icons/pennant.svg';\nimport permission from '@jetbrains/icons/permission.svg';\nimport pinEmpty from '@jetbrains/icons/pin-empty.svg';\nimport pinFilled from '@jetbrains/icons/pin-filled.svg';\nimport play from '@jetbrains/icons/play.svg';\nimport prClose from '@jetbrains/icons/pr-close.svg';\nimport prMerged from '@jetbrains/icons/pr-merged.svg';\nimport prOpen from '@jetbrains/icons/pr-open.svg';\nimport prUnknown from '@jetbrains/icons/pr-unknown.svg';\nimport printer from '@jetbrains/icons/printer.svg';\nimport project14pxArrow from '@jetbrains/icons/project-14px-arrow.svg';\nimport project14pxFillArrow from '@jetbrains/icons/project-14px-fill-arrow.svg';\nimport project14pxFill from '@jetbrains/icons/project-14px-fill.svg';\nimport project14px from '@jetbrains/icons/project-14px.svg';\nimport project20pxArrow from '@jetbrains/icons/project-20px-arrow.svg';\nimport project20pxFillArrow from '@jetbrains/icons/project-20px-fill-arrow.svg';\nimport project20pxFill from '@jetbrains/icons/project-20px-fill.svg';\nimport project20px from '@jetbrains/icons/project-20px.svg';\nimport puzzle from '@jetbrains/icons/puzzle.svg';\nimport rate from '@jetbrains/icons/rate.svg';\nimport redo from '@jetbrains/icons/redo.svg';\nimport remove10px from '@jetbrains/icons/remove-10px.svg';\nimport renamed10px from '@jetbrains/icons/renamed-10px.svg';\nimport reviewersGraph from '@jetbrains/icons/reviewers-graph.svg';\nimport search20px from '@jetbrains/icons/search-20px.svg';\nimport searchEmpty from '@jetbrains/icons/search-empty.svg';\nimport searchError from '@jetbrains/icons/search-error.svg';\nimport search from '@jetbrains/icons/search.svg';\nimport services20px from '@jetbrains/icons/services-20px.svg';\nimport services from '@jetbrains/icons/services.svg';\nimport settings20px from '@jetbrains/icons/settings-20px.svg';\nimport settings from '@jetbrains/icons/settings.svg';\nimport shield from '@jetbrains/icons/shield.svg';\nimport spinner20px from '@jetbrains/icons/spinner-20px.svg';\nimport spinnerStatic from '@jetbrains/icons/spinner-static.svg';\nimport spinner from '@jetbrains/icons/spinner.svg';\nimport stamp from '@jetbrains/icons/stamp.svg';\nimport starEmpty14px from '@jetbrains/icons/star-empty-14px.svg';\nimport starEmpty from '@jetbrains/icons/star-empty.svg';\nimport starFilled14px from '@jetbrains/icons/star-filled-14px.svg';\nimport starFilled from '@jetbrains/icons/star-filled.svg';\nimport stop from '@jetbrains/icons/stop.svg';\nimport table from '@jetbrains/icons/table.svg';\nimport tag from '@jetbrains/icons/tag.svg';\nimport task from '@jetbrains/icons/task.svg';\nimport template14pxArrow from '@jetbrains/icons/template-14px-arrow.svg';\nimport template14px from '@jetbrains/icons/template-14px.svg';\nimport template20pxArrow from '@jetbrains/icons/template-20px-arrow.svg';\nimport template20px from '@jetbrains/icons/template-20px.svg';\nimport time from '@jetbrains/icons/time.svg';\nimport torrent from '@jetbrains/icons/torrent.svg';\nimport trash from '@jetbrains/icons/trash.svg';\nimport treemap from '@jetbrains/icons/treemap.svg';\nimport umbrella from '@jetbrains/icons/umbrella.svg';\nimport unauthorized from '@jetbrains/icons/unauthorized.svg';\nimport undo from '@jetbrains/icons/undo.svg';\nimport unknownOs from '@jetbrains/icons/unknown-os.svg';\nimport unsorted10px from '@jetbrains/icons/unsorted-10px.svg';\nimport update from '@jetbrains/icons/update.svg';\nimport user20px from '@jetbrains/icons/user-20px.svg';\nimport userCancel20px from '@jetbrains/icons/user-cancel-20px.svg';\nimport userCancel from '@jetbrains/icons/user-cancel.svg';\nimport userException20px from '@jetbrains/icons/user-exception-20px.svg';\nimport userException from '@jetbrains/icons/user-exception.svg';\nimport userGear from '@jetbrains/icons/user-gear.svg';\nimport userHourglass20px from '@jetbrains/icons/user-hourglass-20px.svg';\nimport userHourglass from '@jetbrains/icons/user-hourglass.svg';\nimport userOk20px from '@jetbrains/icons/user-ok-20px.svg';\nimport userOk from '@jetbrains/icons/user-ok.svg';\nimport userSpinner20px from '@jetbrains/icons/user-spinner-20px.svg';\nimport userSpinner from '@jetbrains/icons/user-spinner.svg';\nimport userWarning20px from '@jetbrains/icons/user-warning-20px.svg';\nimport userWarning from '@jetbrains/icons/user-warning.svg';\nimport user from '@jetbrains/icons/user.svg';\nimport vcsRoot14pxArrow from '@jetbrains/icons/vcs-root-14px-arrow.svg';\nimport vcsRoot14px from '@jetbrains/icons/vcs-root-14px.svg';\nimport vcsRoot20pxArrow from '@jetbrains/icons/vcs-root-20px-arrow.svg';\nimport vcsRoot20px from '@jetbrains/icons/vcs-root-20px.svg';\nimport voteEmpty from '@jetbrains/icons/vote-empty.svg';\nimport voteFilled from '@jetbrains/icons/vote-filled.svg';\nimport warning14px from '@jetbrains/icons/warning-14px.svg';\nimport warning20px from '@jetbrains/icons/warning-20px.svg';\nimport warning from '@jetbrains/icons/warning.svg';\nimport wrap from '@jetbrains/icons/wrap.svg';\n\nimport {iconHOC} from './icon';\n\nexport const ActivityIcon = iconHOC(activity, 'ActivityIcon');\nexport const Add10pxIcon = iconHOC(add10px, 'Add10pxIcon');\nexport const Add20pxIcon = iconHOC(add20px, 'Add20pxIcon');\nexport const AddIcon = iconHOC(add, 'AddIcon');\nexport const AnalyticsIcon = iconHOC(analytics, 'AnalyticsIcon');\nexport const ArchiveIcon = iconHOC(archive, 'ArchiveIcon');\nexport const ArrowUpIcon = iconHOC(arrowUp, 'ArrowUpIcon');\nexport const ArtifactsIcon = iconHOC(artifacts, 'ArtifactsIcon');\nexport const Asterisk10pxIcon = iconHOC(asterisk10px, 'Asterisk10pxIcon');\nexport const AsteriskIcon = iconHOC(asterisk, 'AsteriskIcon');\nexport const AttachmentIcon = iconHOC(attachment, 'AttachmentIcon');\nexport const AverageIcon = iconHOC(average, 'AverageIcon');\nexport const BarsIcon = iconHOC(bars, 'BarsIcon');\nexport const BellIcon = iconHOC(bell, 'BellIcon');\nexport const BranchesIcon = iconHOC(branches, 'BranchesIcon');\nexport const BugIcon = iconHOC(bug, 'BugIcon');\nexport const BuildType14pxArrowIcon = iconHOC(buildType14pxArrow, 'BuildType14pxArrowIcon');\nexport const BuildType14pxFillArrowIcon = iconHOC(buildType14pxFillArrow, 'BuildType14pxFillArrowIcon');\nexport const BuildType14pxFillIcon = iconHOC(buildType14pxFill, 'BuildType14pxFillIcon');\nexport const BuildType14pxIcon = iconHOC(buildType14px, 'BuildType14pxIcon');\nexport const BuildType20pxArrowIcon = iconHOC(buildType20pxArrow, 'BuildType20pxArrowIcon');\nexport const BuildType20pxFillArrowIcon = iconHOC(buildType20pxFillArrow, 'BuildType20pxFillArrowIcon');\nexport const BuildType20pxFillIcon = iconHOC(buildType20pxFill, 'BuildType20pxFillIcon');\nexport const BuildType20pxIcon = iconHOC(buildType20px, 'BuildType20pxIcon');\nexport const BuildTypeComposite14pxArrowIcon = iconHOC(buildTypeComposite14pxArrow, 'BuildTypeComposite14pxArrowIcon');\nexport const BuildTypeComposite14pxFillArrowIcon = iconHOC(buildTypeComposite14pxFillArrow, 'BuildTypeComposite14pxFillArrowIcon');\nexport const BuildTypeComposite14pxFillIcon = iconHOC(buildTypeComposite14pxFill, 'BuildTypeComposite14pxFillIcon');\nexport const BuildTypeComposite14pxIcon = iconHOC(buildTypeComposite14px, 'BuildTypeComposite14pxIcon');\nexport const BuildTypeComposite20pxArrowIcon = iconHOC(buildTypeComposite20pxArrow, 'BuildTypeComposite20pxArrowIcon');\nexport const BuildTypeComposite20pxFillArrowIcon = iconHOC(buildTypeComposite20pxFillArrow, 'BuildTypeComposite20pxFillArrowIcon');\nexport const BuildTypeComposite20pxFillIcon = iconHOC(buildTypeComposite20pxFill, 'BuildTypeComposite20pxFillIcon');\nexport const BuildTypeComposite20pxIcon = iconHOC(buildTypeComposite20px, 'BuildTypeComposite20pxIcon');\nexport const BurndownIcon = iconHOC(burndown, 'BurndownIcon');\nexport const CalendarIcon = iconHOC(calendar, 'CalendarIcon');\nexport const Cancel20pxIcon = iconHOC(cancel20px, 'Cancel20pxIcon');\nexport const CancelIcon = iconHOC(cancel, 'CancelIcon');\nexport const CaretDown10pxIcon = iconHOC(caretDown10px, 'CaretDown10pxIcon');\nexport const CaretRight10pxIcon = iconHOC(caretRight10px, 'CaretRight10pxIcon');\nexport const ChangeIcon = iconHOC(change, 'ChangeIcon');\nexport const CheckmarkIcon = iconHOC(checkmark, 'CheckmarkIcon');\nexport const Chevron10pxIcon = iconHOC(chevron10px, 'Chevron10pxIcon');\nexport const ChevronDownIcon = iconHOC(chevronDown, 'ChevronDownIcon');\nexport const ChevronLeftIcon = iconHOC(chevronLeft, 'ChevronLeftIcon');\nexport const ChevronRightIcon = iconHOC(chevronRight, 'ChevronRightIcon');\nexport const ChevronUpIcon = iconHOC(chevronUp, 'ChevronUpIcon');\nexport const CloseIcon = iconHOC(close, 'CloseIcon');\nexport const CloudIcon = iconHOC(cloud, 'CloudIcon');\nexport const CodeIcon = iconHOC(code, 'CodeIcon');\nexport const CollapseIcon = iconHOC(collapse, 'CollapseIcon');\nexport const CommentIcon = iconHOC(comment, 'CommentIcon');\nexport const CompareIcon = iconHOC(compare, 'CompareIcon');\nexport const CopyIcon = iconHOC(copy, 'CopyIcon');\nexport const CropIcon = iconHOC(crop, 'CropIcon');\nexport const DataIcon = iconHOC(data, 'DataIcon');\nexport const DiceIcon = iconHOC(dice, 'DiceIcon');\nexport const DisconnectedIcon = iconHOC(disconnected, 'DisconnectedIcon');\nexport const DistributionIcon = iconHOC(distribution, 'DistributionIcon');\nexport const DoubleChevronLeftIcon = iconHOC(doubleChevronLeft, 'DoubleChevronLeftIcon');\nexport const DoubleChevronRightIcon = iconHOC(doubleChevronRight, 'DoubleChevronRightIcon');\nexport const DownloadIcon = iconHOC(download, 'DownloadIcon');\nexport const DragIcon = iconHOC(drag, 'DragIcon');\nexport const DropIcon = iconHOC(drop, 'DropIcon');\nexport const EMailIcon = iconHOC(eMail, 'EMailIcon');\nexport const EarthIcon = iconHOC(earth, 'EarthIcon');\nexport const EmojiIcon = iconHOC(emoji, 'EmojiIcon');\nexport const EntryIcon = iconHOC(entry, 'EntryIcon');\nexport const Exception20pxIcon = iconHOC(exception20px, 'Exception20pxIcon');\nexport const ExceptionIcon = iconHOC(exception, 'ExceptionIcon');\nexport const ExpandIcon = iconHOC(expand, 'ExpandIcon');\nexport const Experiment20pxIcon = iconHOC(experiment20px, 'Experiment20pxIcon');\nexport const EyeIcon = iconHOC(eye, 'EyeIcon');\nexport const FieldsIcon = iconHOC(fields, 'FieldsIcon');\nexport const FileAddAnyIcon = iconHOC(fileAddAny, 'FileAddAnyIcon');\nexport const FileArchiveIcon = iconHOC(fileArchive, 'FileArchiveIcon');\nexport const FileAsIcon = iconHOC(fileAs, 'FileAsIcon');\nexport const FileAspectjIcon = iconHOC(fileAspectj, 'FileAspectjIcon');\nexport const FileConfigIcon = iconHOC(fileConfig, 'FileConfigIcon');\nexport const FileCssIcon = iconHOC(fileCss, 'FileCssIcon');\nexport const FileCustomIcon = iconHOC(fileCustom, 'FileCustomIcon');\nexport const FileDiagramIcon = iconHOC(fileDiagram, 'FileDiagramIcon');\nexport const FileDtdIcon = iconHOC(fileDtd, 'FileDtdIcon');\nexport const FileHtaccessIcon = iconHOC(fileHtaccess, 'FileHtaccessIcon');\nexport const FileHtmlIcon = iconHOC(fileHtml, 'FileHtmlIcon');\nexport const FileIdlIcon = iconHOC(fileIdl, 'FileIdlIcon');\nexport const FileJavaClassIcon = iconHOC(fileJavaClass, 'FileJavaClassIcon');\nexport const FileJavaOutsideSourceIcon = iconHOC(fileJavaOutsideSource, 'FileJavaOutsideSourceIcon');\nexport const FileJavaIcon = iconHOC(fileJava, 'FileJavaIcon');\nexport const FileJsIcon = iconHOC(fileJs, 'FileJsIcon');\nexport const FileJsonDarkIcon = iconHOC(fileJsonDark, 'FileJsonDarkIcon');\nexport const FileJsonSchemaDarkIcon = iconHOC(fileJsonSchemaDark, 'FileJsonSchemaDarkIcon');\nexport const FileJsonSchemaIcon = iconHOC(fileJsonSchema, 'FileJsonSchemaIcon');\nexport const FileJsonIcon = iconHOC(fileJson, 'FileJsonIcon');\nexport const FileJspIcon = iconHOC(fileJsp, 'FileJspIcon');\nexport const FileJspxIcon = iconHOC(fileJspx, 'FileJspxIcon');\nexport const FileManifestIcon = iconHOC(fileManifest, 'FileManifestIcon');\nexport const FilePropertiesIcon = iconHOC(fileProperties, 'FilePropertiesIcon');\nexport const FileRegexpIcon = iconHOC(fileRegexp, 'FileRegexpIcon');\nexport const FileTextIcon = iconHOC(fileText, 'FileTextIcon');\nexport const FileUiFormIcon = iconHOC(fileUiForm, 'FileUiFormIcon');\nexport const FileUnknownIcon = iconHOC(fileUnknown, 'FileUnknownIcon');\nexport const FileWsdlIcon = iconHOC(fileWsdl, 'FileWsdlIcon');\nexport const FileXhtmlIcon = iconHOC(fileXhtml, 'FileXhtmlIcon');\nexport const FileXmlIcon = iconHOC(fileXml, 'FileXmlIcon');\nexport const FileXsdIcon = iconHOC(fileXsd, 'FileXsdIcon');\nexport const FileYamlIcon = iconHOC(fileYaml, 'FileYamlIcon');\nexport const FileIcon = iconHOC(file, 'FileIcon');\nexport const FiltersIcon = iconHOC(filters, 'FiltersIcon');\nexport const FlagIcon = iconHOC(flag, 'FlagIcon');\nexport const FolderIcon = iconHOC(folder, 'FolderIcon');\nexport const FrownIcon = iconHOC(frown, 'FrownIcon');\nexport const Gift20pxIcon = iconHOC(gift20px, 'Gift20pxIcon');\nexport const GiftIcon = iconHOC(gift, 'GiftIcon');\nexport const GitIcon = iconHOC(git, 'GitIcon');\nexport const GroupIcon = iconHOC(group, 'GroupIcon');\nexport const Help20pxIcon = iconHOC(help20px, 'Help20pxIcon');\nexport const HelpIcon = iconHOC(help, 'HelpIcon');\nexport const HistoryIcon = iconHOC(history, 'HistoryIcon');\nexport const Hourglass20pxIcon = iconHOC(hourglass20px, 'Hourglass20pxIcon');\nexport const HourglassIcon = iconHOC(hourglass, 'HourglassIcon');\nexport const IgnoredIcon = iconHOC(ignored, 'IgnoredIcon');\nexport const InfoIcon = iconHOC(info, 'InfoIcon');\nexport const Investigation14pxIcon = iconHOC(investigation14px, 'Investigation14pxIcon');\nexport const InvestigationIcon = iconHOC(investigation, 'InvestigationIcon');\nexport const LampIcon = iconHOC(lamp, 'LampIcon');\nexport const LinkIcon = iconHOC(link, 'LinkIcon');\nexport const LockIcon = iconHOC(lock, 'LockIcon');\nexport const MagicWandIcon = iconHOC(magicWand, 'MagicWandIcon');\nexport const Mammoth20pxIcon = iconHOC(mammoth20px, 'Mammoth20pxIcon');\nexport const MarkerIcon = iconHOC(marker, 'MarkerIcon');\nexport const MetaIcon = iconHOC(meta, 'MetaIcon');\nexport const Modified10pxIcon = iconHOC(modified10px, 'Modified10pxIcon');\nexport const MoreOptionsIcon = iconHOC(moreOptions, 'MoreOptionsIcon');\nexport const MoveToTopIcon = iconHOC(moveToTop, 'MoveToTopIcon');\nexport const MoveIcon = iconHOC(move, 'MoveIcon');\nexport const MuteIcon = iconHOC(mute, 'MuteIcon');\nexport const MutedIcon = iconHOC(muted, 'MutedIcon');\nexport const NewWindowIcon = iconHOC(newWindow, 'NewWindowIcon');\nexport const NoArtifactsIcon = iconHOC(noArtifacts, 'NoArtifactsIcon');\nexport const Ok20pxIcon = iconHOC(ok20px, 'Ok20pxIcon');\nexport const OkIcon = iconHOC(ok, 'OkIcon');\nexport const OvertimeIcon = iconHOC(overtime, 'OvertimeIcon');\nexport const Paused14pxIcon = iconHOC(paused14px, 'Paused14pxIcon');\nexport const PausedIcon = iconHOC(paused, 'PausedIcon');\nexport const PencilIcon = iconHOC(pencil, 'PencilIcon');\nexport const PennantIcon = iconHOC(pennant, 'PennantIcon');\nexport const PermissionIcon = iconHOC(permission, 'PermissionIcon');\nexport const PinEmptyIcon = iconHOC(pinEmpty, 'PinEmptyIcon');\nexport const PinFilledIcon = iconHOC(pinFilled, 'PinFilledIcon');\nexport const PlayIcon = iconHOC(play, 'PlayIcon');\nexport const PrCloseIcon = iconHOC(prClose, 'PrCloseIcon');\nexport const PrMergedIcon = iconHOC(prMerged, 'PrMergedIcon');\nexport const PrOpenIcon = iconHOC(prOpen, 'PrOpenIcon');\nexport const PrUnknownIcon = iconHOC(prUnknown, 'PrUnknownIcon');\nexport const PrinterIcon = iconHOC(printer, 'PrinterIcon');\nexport const Project14pxArrowIcon = iconHOC(project14pxArrow, 'Project14pxArrowIcon');\nexport const Project14pxFillArrowIcon = iconHOC(project14pxFillArrow, 'Project14pxFillArrowIcon');\nexport const Project14pxFillIcon = iconHOC(project14pxFill, 'Project14pxFillIcon');\nexport const Project14pxIcon = iconHOC(project14px, 'Project14pxIcon');\nexport const Project20pxArrowIcon = iconHOC(project20pxArrow, 'Project20pxArrowIcon');\nexport const Project20pxFillArrowIcon = iconHOC(project20pxFillArrow, 'Project20pxFillArrowIcon');\nexport const Project20pxFillIcon = iconHOC(project20pxFill, 'Project20pxFillIcon');\nexport const Project20pxIcon = iconHOC(project20px, 'Project20pxIcon');\nexport const PuzzleIcon = iconHOC(puzzle, 'PuzzleIcon');\nexport const RateIcon = iconHOC(rate, 'RateIcon');\nexport const RedoIcon = iconHOC(redo, 'RedoIcon');\nexport const Remove10pxIcon = iconHOC(remove10px, 'Remove10pxIcon');\nexport const Renamed10pxIcon = iconHOC(renamed10px, 'Renamed10pxIcon');\nexport const ReviewersGraphIcon = iconHOC(reviewersGraph, 'ReviewersGraphIcon');\nexport const Search20pxIcon = iconHOC(search20px, 'Search20pxIcon');\nexport const SearchEmptyIcon = iconHOC(searchEmpty, 'SearchEmptyIcon');\nexport const SearchErrorIcon = iconHOC(searchError, 'SearchErrorIcon');\nexport const SearchIcon = iconHOC(search, 'SearchIcon');\nexport const Services20pxIcon = iconHOC(services20px, 'Services20pxIcon');\nexport const ServicesIcon = iconHOC(services, 'ServicesIcon');\nexport const Settings20pxIcon = iconHOC(settings20px, 'Settings20pxIcon');\nexport const SettingsIcon = iconHOC(settings, 'SettingsIcon');\nexport const ShieldIcon = iconHOC(shield, 'ShieldIcon');\nexport const Spinner20pxIcon = iconHOC(spinner20px, 'Spinner20pxIcon');\nexport const SpinnerStaticIcon = iconHOC(spinnerStatic, 'SpinnerStaticIcon');\nexport const SpinnerIcon = iconHOC(spinner, 'SpinnerIcon');\nexport const StampIcon = iconHOC(stamp, 'StampIcon');\nexport const StarEmpty14pxIcon = iconHOC(starEmpty14px, 'StarEmpty14pxIcon');\nexport const StarEmptyIcon = iconHOC(starEmpty, 'StarEmptyIcon');\nexport const StarFilled14pxIcon = iconHOC(starFilled14px, 'StarFilled14pxIcon');\nexport const StarFilledIcon = iconHOC(starFilled, 'StarFilledIcon');\nexport const StopIcon = iconHOC(stop, 'StopIcon');\nexport const TableIcon = iconHOC(table, 'TableIcon');\nexport const TagIcon = iconHOC(tag, 'TagIcon');\nexport const TaskIcon = iconHOC(task, 'TaskIcon');\nexport const Template14pxArrowIcon = iconHOC(template14pxArrow, 'Template14pxArrowIcon');\nexport const Template14pxIcon = iconHOC(template14px, 'Template14pxIcon');\nexport const Template20pxArrowIcon = iconHOC(template20pxArrow, 'Template20pxArrowIcon');\nexport const Template20pxIcon = iconHOC(template20px, 'Template20pxIcon');\nexport const TimeIcon = iconHOC(time, 'TimeIcon');\nexport const TorrentIcon = iconHOC(torrent, 'TorrentIcon');\nexport const TrashIcon = iconHOC(trash, 'TrashIcon');\nexport const TreemapIcon = iconHOC(treemap, 'TreemapIcon');\nexport const UmbrellaIcon = iconHOC(umbrella, 'UmbrellaIcon');\nexport const UnauthorizedIcon = iconHOC(unauthorized, 'UnauthorizedIcon');\nexport const UndoIcon = iconHOC(undo, 'UndoIcon');\nexport const UnknownOsIcon = iconHOC(unknownOs, 'UnknownOsIcon');\nexport const Unsorted10pxIcon = iconHOC(unsorted10px, 'Unsorted10pxIcon');\nexport const UpdateIcon = iconHOC(update, 'UpdateIcon');\nexport const User20pxIcon = iconHOC(user20px, 'User20pxIcon');\nexport const UserCancel20pxIcon = iconHOC(userCancel20px, 'UserCancel20pxIcon');\nexport const UserCancelIcon = iconHOC(userCancel, 'UserCancelIcon');\nexport const UserException20pxIcon = iconHOC(userException20px, 'UserException20pxIcon');\nexport const UserExceptionIcon = iconHOC(userException, 'UserExceptionIcon');\nexport const UserGearIcon = iconHOC(userGear, 'UserGearIcon');\nexport const UserHourglass20pxIcon = iconHOC(userHourglass20px, 'UserHourglass20pxIcon');\nexport const UserHourglassIcon = iconHOC(userHourglass, 'UserHourglassIcon');\nexport const UserOk20pxIcon = iconHOC(userOk20px, 'UserOk20pxIcon');\nexport const UserOkIcon = iconHOC(userOk, 'UserOkIcon');\nexport const UserSpinner20pxIcon = iconHOC(userSpinner20px, 'UserSpinner20pxIcon');\nexport const UserSpinnerIcon = iconHOC(userSpinner, 'UserSpinnerIcon');\nexport const UserWarning20pxIcon = iconHOC(userWarning20px, 'UserWarning20pxIcon');\nexport const UserWarningIcon = iconHOC(userWarning, 'UserWarningIcon');\nexport const UserIcon = iconHOC(user, 'UserIcon');\nexport const VcsRoot14pxArrowIcon = iconHOC(vcsRoot14pxArrow, 'VcsRoot14pxArrowIcon');\nexport const VcsRoot14pxIcon = iconHOC(vcsRoot14px, 'VcsRoot14pxIcon');\nexport const VcsRoot20pxArrowIcon = iconHOC(vcsRoot20pxArrow, 'VcsRoot20pxArrowIcon');\nexport const VcsRoot20pxIcon = iconHOC(vcsRoot20px, 'VcsRoot20pxIcon');\nexport const VoteEmptyIcon = iconHOC(voteEmpty, 'VoteEmptyIcon');\nexport const VoteFilledIcon = iconHOC(voteFilled, 'VoteFilledIcon');\nexport const Warning14pxIcon = iconHOC(warning14px, 'Warning14pxIcon');\nexport const Warning20pxIcon = iconHOC(warning20px, 'Warning20pxIcon');\nexport const WarningIcon = iconHOC(warning, 'WarningIcon');\nexport const WrapIcon = iconHOC(wrap, 'WrapIcon');\n","import React, {createContext, forwardRef} from 'react';\nimport {pure, wrapDisplayName} from 'recompose';\n\nconst Theme = {\n LIGHT: 'light',\n DARK: 'dark'\n};\n\nexport const ThemeContext = createContext();\n\nexport const withTheme = (defaultTheme = Theme.LIGHT) => ComposedComponent => {\n // eslint-disable-next-line react/prop-types\n const WithTheme = pure(forwardRef(function WithTheme({theme, ...restProps}, ref) {\n return (\n \n {contextTheme => {\n const usedTheme = theme || contextTheme || defaultTheme;\n return (\n \n \n \n );\n }}\n \n );\n }));\n Object.assign(WithTheme, ComposedComponent);\n WithTheme.displayName = wrapDisplayName(ComposedComponent, 'withTheme');\n return WithTheme;\n};\n\nfunction applyTheme(params) {\n if (!params || !params.element || !params.currentTheme) {\n return;\n }\n\n if (params.prevTheme) {\n params.element.classList.remove(params.prevTheme);\n }\n\n params.element.classList.add(params.currentTheme);\n}\n\n\nexport {applyTheme};\nexport default Theme;\n","\nfunction expandMap(attrsMap) {\n return Object.entries(attrsMap).\n reduce((result, [key, value]) => (value ? [...result, key] : result), []);\n}\n\nexport default function joinDataTestAttributes(...attrs) {\n return attrs.\n filter(attr => !!attr).\n reduce((result, attr) => {\n if (typeof attr === 'object') {\n return [...result, ...expandMap(attr)];\n }\n return [...result, attr];\n }, []).\n join(' ');\n}\n","import memoize from './memoize';\n\nexport default memoize(declaration => {\n const [property, value] = declaration.split(': ');\n const camelCaseProperty = property.replace(/-(\\w)/g, (_, letter) => letter.toUpperCase());\n const div = document.createElement('div');\n if (div.style[camelCaseProperty] === undefined) {\n return false;\n }\n\n if (value) {\n div.style[camelCaseProperty] = value;\n return Boolean(div.style[camelCaseProperty]);\n }\n\n return true;\n});\n","/* global ConicGradient */\nimport 'conic-gradient';\n\nimport memoize from './memoize';\nimport supportsCss from './supports-css';\n\nconst conicGradient = memoize(({stops, size}) => (\n supportsCss('background-image: conic-gradient(white, black)')\n ? `conic-gradient(${stops})`\n : new ConicGradient({stops, size})\n));\n\nexport default stops => conicGradient(stops).toString();\n\nexport const conicGradientWithMask = (mask, stops, size) => {\n const gradient = conicGradient({stops, size});\n\n if (!mask.supports && gradient instanceof ConicGradient) {\n Object.defineProperty(gradient, 'svg', {\n value: gradient.svg.replace(' {\n const styleTag = document.createElement('style');\n styleTag.setAttribute('type', 'text/css');\n styleTag.textContent = styles;\n document.head.appendChild(styleTag);\n return styleTag;\n};\n\nexport const injectRuleSet = (selector, declarations) =>\n injectStyleSheet(`\n${selector} {\n ${Object.entries(declarations).map(([property, value]) => `${property}: ${value};`).join(`\n `)}\n}`);\n","const idCounters = {};\n\nexport default function getUID(name) {\n if (!name) {\n throw Error('Argument \"name\" is required in getUID()');\n }\n\n if (!idCounters[name]) {\n idCounters[name] = 0;\n }\n\n const id = String(idCounters[name]++);\n\n return name + id;\n}\n","import getUID from './get-uid';\nimport supportsCss from './supports-css';\n\nconst radialGradient = (length, stops) =>\n `radial-gradient(${length}, ${Object.entries(stops).map(entry => entry.join(' ')).join(', ')})`;\n\nexport default (length, stops) => {\n for (const prefix of ['', '-webkit-']) {\n const property = `${prefix}mask-image`;\n const declaration = `${property}: radial-gradient(black, white)`;\n if (supportsCss(declaration)) {\n return {\n supports: true,\n css: {\n [property]: radialGradient(length, stops)\n }\n };\n }\n }\n\n const gradientId = getUID('gradient');\n const maskId = getUID('mask');\n const svgDefs = `\n \n \n \n ${Object.entries(stops).map(([color, offset]) => `\n \n `).join('')}\n \n \n \n \n \n \n `;\n return {\n supports: false,\n css: {},\n maskId,\n svgDefs\n };\n};\n","import {conicGradientWithMask} from '../global/conic-gradient';\nimport {injectRuleSet} from '../global/inject-styles';\nimport memoize from '../global/memoize';\nimport radialGradientMask from '../global/radial-gradient-mask';\nimport Theme from '../global/theme';\n\nimport styles from './loader-inline.css';\n\nconst IMAGE_SIZE = 32;\n\nexport default memoize(() => {\n const mask = radialGradientMask(styles.unit, {\n /* eslint-disable no-magic-numbers */\n transparent: `${23 / 32 * 100}%`,\n white: `${25 / 32 * 100}%`\n /* eslint-enable */\n });\n\n injectRuleSet(\n `.${styles.loader}_${[Theme.LIGHT]}::after, .ring-loader-inline::after`,\n conicGradientWithMask(mask, '#ff00eb,#bd3bff,#008eff, #58ba00,#f48700,#ff00eb', IMAGE_SIZE)\n );\n\n injectRuleSet(\n `.${styles.loader}_${[Theme.DARK]}::after, .ring-loader-inline_dark::after`,\n conicGradientWithMask(mask, '#ff2eef,#d178ff,#289fff,#88d444,#ffe000,#ff2eef', IMAGE_SIZE)\n );\n});\n","import React, {PureComponent} from 'react';\nimport classNames from 'classnames';\nimport PropTypes from 'prop-types';\n\nimport Theme, {withTheme} from '../global/theme';\nimport dataTests from '../global/data-tests';\n\nimport styles from './loader-inline.css';\nimport injectStyles from './inject-styles';\n\n/**\n * @name Loader Inline\n */\n\nclass LoaderInline extends PureComponent {\n static propTypes = {\n theme: PropTypes.oneOf(Object.values(Theme)),\n className: PropTypes.string,\n 'data-test': PropTypes.string,\n children: PropTypes.node\n };\n\n componentDidMount() {\n injectStyles();\n }\n\n static Theme = Theme;\n\n render() {\n const {className, theme, 'data-test': dataTest, children, ...restProps} = this.props;\n\n const classes = classNames(\n styles.loader,\n className,\n `${styles.loader}_${theme}`\n );\n\n const loader = (\n \n );\n\n return children ? (\n <>\n {loader}\n {children}\n \n ) : loader;\n }\n}\n\nexport default withTheme()(LoaderInline);\n","/**\n * @name DOM\n */\n\nexport const getStyles = window.getComputedStyle.bind(window);\n\nexport function isMounted(node) {\n if (node === document) {\n return true;\n }\n\n return node instanceof Node && document.documentElement.contains(node.parentNode);\n}\n\nconst rectStub = {top: 0, right: 0, bottom: 0, left: 0, width: 0, height: 0};\n\nexport function getRect(node) {\n if (node instanceof Range || isMounted(node)) {\n const {top, right, bottom, left, width, height} = node.getBoundingClientRect();\n return {top, right, bottom, left, width, height};\n } else {\n return Object.assign({}, rectStub);\n }\n}\n\nexport function getPixelRatio() {\n return 'devicePixelRatio' in window ? window.devicePixelRatio : 1;\n}\n\nexport function getWindowHeight() {\n return window.innerHeight;\n}\n\nexport function getDocumentScrollTop() {\n return (document.documentElement && document.documentElement.scrollTop) ||\n document.body.scrollTop;\n}\n\nexport function getDocumentScrollLeft() {\n return (document.documentElement && document.documentElement.scrollLeft) ||\n document.body.scrollLeft;\n}\n\nexport const applyMethodToClasses = method => (classList, classes = '') => {\n classes.\n split(/\\s+/g).\n filter(className => !!className).\n forEach(className => classList[method](className));\n};\n\nexport const addClasses = applyMethodToClasses('add');\nexport const removeClasses = applyMethodToClasses('remove');\n\nexport function setRootStyleProperties(properties = {}) {\n const rootStyle = document.documentElement.style;\n\n Object.entries(properties).forEach(([key, value]) => {\n rootStyle.setProperty(key, value);\n });\n}\n\nexport function resetRootStyleProperties(properties = {}) {\n const rootStyle = document.documentElement.style;\n\n Object.keys(properties).\n forEach(key => rootStyle.removeProperty(key));\n}\n\nexport class Listeners {\n _all = new Set();\n\n add(el, event, handler, useCapture) {\n el.addEventListener(event, handler, useCapture);\n const dispatchFn = () => el.removeEventListener(event, handler, useCapture);\n this._all.add(dispatchFn);\n return dispatchFn;\n }\n\n remove(fn) {\n fn();\n this._all.delete(fn);\n }\n\n removeAll() {\n this._all.forEach(fn => this.remove(fn));\n }\n}\n\n// Synthetic events from Combokeys#trigger are plain objects\nexport function preventDefault(e) {\n if (e.preventDefault) {\n e.preventDefault();\n }\n}\n","import React, {Children, cloneElement, PureComponent} from 'react';\nimport {createPortal} from 'react-dom';\nimport classNames from 'classnames';\nimport PropTypes from 'prop-types';\n\nimport styles from './container.css';\n\n/**\n * @name Alert Container\n * @description Displays a stack of alerts on top of the page.\n * @extends {PureComponent}\n */\n\nexport default class Alerts extends PureComponent {\n static propTypes = {\n children: PropTypes.node,\n className: PropTypes.string\n };\n\n render() {\n const {children, className, ...restProps} = this.props;\n const classes = classNames(styles.alertContainer, className);\n const show = Children.count(children) > 0;\n\n if (!show) {\n return null;\n }\n\n return createPortal(\n \n {Children.map(children, child => {\n const alertClassNames = classNames(styles.alertInContainer, child.props.className);\n\n return cloneElement(child, {\n className: alertClassNames\n });\n })}\n
,\n document.body\n );\n }\n}\n","import 'dom4';\nimport React, {PureComponent} from 'react';\nimport classNames from 'classnames';\nimport PropTypes from 'prop-types';\n\nimport exceptionIcon from '@jetbrains/icons/exception.svg';\nimport checkmarkIcon from '@jetbrains/icons/checkmark.svg';\nimport warningIcon from '@jetbrains/icons/warning.svg';\nimport closeIcon from '@jetbrains/icons/close.svg';\n\nimport Icon from '../icon';\nimport Loader from '../loader-inline/loader-inline';\nimport {getRect} from '../global/dom';\nimport dataTests from '../global/data-tests';\n\nimport styles from './alert.css';\n\nexport const ANIMATION_TIME = 500;\n\n/**\n * @name Alert\n */\n\n/**\n * List of available alert types.\n * @enum {string}\n */\nconst Type = {\n ERROR: 'error',\n MESSAGE: 'message',\n SUCCESS: 'success',\n WARNING: 'warning',\n LOADING: 'loading'\n};\n\n/**\n * Lookup table of alert type to icon modifier.\n * @type {Object.}\n */\nconst TypeToIcon = {\n [Type.ERROR]: exceptionIcon,\n [Type.SUCCESS]: checkmarkIcon,\n [Type.WARNING]: warningIcon\n};\n\n/**\n * Lookup table of alert type to icon color.\n * @type {Object.}\n */\nconst TypeToIconColor = {\n [Type.ERROR]: Icon.Color.RED,\n [Type.SUCCESS]: Icon.Color.GREEN,\n [Type.WARNING]: Icon.Color.WHITE\n};\n\n/**\n * @constructor\n * @name Alert\n * @extends {ReactComponent}\n */\n/**\n * **Alert** is a component for displaying contextual notifications. If you want to display a stack of notifications, use **Alerts** instead.\n */\nexport default class Alert extends PureComponent {\n static propTypes = {\n timeout: PropTypes.number,\n /**\n * Fires when alert starts closing if timeout is out or user clicks \"Close\" button\n */\n onCloseRequest: PropTypes.func,\n onClose: PropTypes.func,\n isShaking: PropTypes.bool,\n isClosing: PropTypes.bool,\n /**\n * Whether an alert is rendered inside an **Alerts** container\n * or standalone.\n */\n inline: PropTypes.bool,\n showWithAnimation: PropTypes.bool,\n closeable: PropTypes.bool,\n type: PropTypes.oneOf(Object.values(Type)),\n\n children: PropTypes.node,\n className: PropTypes.string,\n captionClassName: PropTypes.string,\n 'data-test': PropTypes.string\n };\n\n /** @override */\n static defaultProps = {\n closeable: true,\n showWithAnimation: true,\n type: Type.MESSAGE,\n inline: true,\n isClosing: false,\n isShaking: false,\n timeout: 0,\n onClose: () => {},\n onCloseRequest: () => {}\n };\n\n state = {\n height: null\n };\n\n componentDidMount() {\n if (this.props.timeout > 0) {\n this.hideTimeout = setTimeout(this.closeRequest, this.props.timeout);\n }\n }\n\n componentDidUpdate() {\n if (this.props.isClosing) {\n this._close();\n }\n }\n\n componentWillUnmount() {\n clearTimeout(this.hideTimeout);\n }\n\n static Type = Type;\n\n closeRequest = (...args) => {\n const height = getRect(this.node).height;\n this.setState({height});\n return this.props.onCloseRequest(...args);\n };\n\n _close() {\n setTimeout(() => {\n this.props.onClose();\n }, ANIMATION_TIME);\n }\n\n /**\n * @param {SyntheticEvent} evt\n * @private\n */\n _handleCaptionsLinksClick = evt => {\n if (evt.target.matches('a')) {\n this.closeRequest(evt);\n }\n };\n\n /**\n * @private\n */\n _getCaption() {\n return (\n \n {this.props.children}\n \n );\n }\n\n /**\n * @private\n * @return {XML|string}\n */\n _getIcon() {\n const glyph = TypeToIcon[this.props.type];\n\n if (glyph) {\n return (\n \n );\n } else if (this.props.type === Type.LOADING) {\n return (\n \n );\n }\n\n return '';\n }\n\n storeAlertRef = node => {\n this.node = node;\n };\n\n render() {\n const {type, inline, isClosing, isShaking,\n showWithAnimation, className, 'data-test': dataTest} = this.props;\n\n const classes = classNames(className, {\n [styles.alert]: true,\n [styles.animationOpen]: showWithAnimation,\n [styles.error]: type === 'error',\n [styles.alertInline]: inline,\n [styles.animationClosing]: isClosing,\n [styles.animationShaking]: isShaking\n });\n\n const style = this.state.height ? {marginBottom: -this.state.height} : null;\n\n return (\n \n {this._getIcon()}\n {this._getCaption()}\n {\n this.props.closeable\n ? (\n \n \n \n )\n : ''\n }\n \n );\n }\n}\n\nexport {default as Container} from './container';\n","import React from 'react';\nimport {render} from 'react-dom';\n\nimport getUID from '../global/get-uid';\n\nimport Alert, {ANIMATION_TIME, Container as AlertContainer} from '../alert/alert';\n\n/**\n * @name Alert Service\n */\n\nclass AlertService {\n defaultTimeout = 0;\n // This alerts are stored in inverse order (last shown is first in array)\n showingAlerts = [];\n containerElement = document.createElement('div');\n\n _getShowingAlerts() {\n return [...this.showingAlerts];\n }\n\n renderAlertContainer(alerts) {\n if (alerts.length === 0) {\n return ;\n }\n\n return (\n \n {alerts.map(alert => {\n const {message, key, ...rest} = alert;\n return (\n {message}\n );\n })}\n \n );\n }\n\n /**\n * Renders alert container into virtual node to skip maintaining container\n */\n renderAlerts() {\n render(this.renderAlertContainer(this.showingAlerts), this.containerElement);\n }\n\n findSameAlert(message, type) {\n return this.showingAlerts.filter(it => it.type === type && it.message === message)[0];\n }\n\n startAlertClosing(alert) {\n alert.isClosing = true;\n this.renderAlerts();\n }\n\n remove(key) {\n const alertToClose = this.showingAlerts.filter(alert => alert.key === key)[0];\n if (!alertToClose) {\n return;\n }\n this.startAlertClosing(alertToClose);\n }\n\n removeWithoutAnimation(key) {\n this.showingAlerts = this.showingAlerts.filter(alert => alert.key !== key);\n this.renderAlerts();\n }\n\n stopShakingWhenAnimationDone(shakingAlert) {\n setTimeout(() => {\n shakingAlert.showWithAnimation = false;\n shakingAlert.isShaking = false;\n this.renderAlerts();\n }, ANIMATION_TIME);\n }\n\n addAlert(message, type, timeout = this.defaultTimeout, restOptions = {}) {\n const sameAlert = this.findSameAlert(message, type);\n if (sameAlert) {\n sameAlert.isShaking = true;\n this.renderAlerts();\n this.stopShakingWhenAnimationDone(sameAlert);\n return sameAlert.key;\n }\n\n const alert = {\n key: getUID('alert-service-'),\n message,\n type,\n timeout,\n isClosing: false,\n onCloseRequest: () => this.startAlertClosing(alert),\n onClose: () => this.removeWithoutAnimation(alert.key),\n ...restOptions\n };\n\n this.showingAlerts = [alert, ...this.showingAlerts];\n this.renderAlerts();\n return alert.key;\n }\n\n setDefaultTimeout(timeout) {\n this.defaultTimeout = timeout;\n }\n\n error(message, timeout) {\n return this.addAlert(message, Alert.Type.ERROR, timeout);\n }\n\n message(message, timeout) {\n return this.addAlert(message, Alert.Type.MESSAGE, timeout);\n }\n\n warning(message, timeout) {\n return this.addAlert(message, Alert.Type.WARNING, timeout);\n }\n\n successMessage(message, timeout) {\n return this.addAlert(message, Alert.Type.SUCCESS, timeout);\n }\n\n loadingMessage(message, timeout) {\n return this.addAlert(message, Alert.Type.LOADING, timeout);\n }\n}\n\nconst alertService = new AlertService();\nexport default alertService;\n","/**\n * @name Analytics\n */\nclass Analytics {\n constructor() {\n this._plugins = [];\n }\n\n config(plugins) {\n this._plugins = plugins;\n }\n\n track(rawTrackingData, /* optional */ additionalData) {\n if (!rawTrackingData) {\n return;\n }\n\n let splitIdx = rawTrackingData.indexOf(':');\n if (splitIdx < 0) {\n splitIdx = rawTrackingData.indexOf('_');\n }\n if (splitIdx < 0) {\n splitIdx = rawTrackingData.length;\n }\n\n const category = rawTrackingData.substr(0, splitIdx);\n const subcategory = rawTrackingData.substr(splitIdx + 1);\n\n this.trackEvent(category, subcategory, additionalData);\n }\n\n trackPageView(path) {\n this._plugins.forEach(plugin => {\n plugin.trackPageView(path);\n });\n }\n\n trackEvent(category, action, /* optional */ additionalData) {\n const subaction = additionalData ? action + this._buildSuffix(additionalData) : null;\n this._plugins.forEach(plugin => {\n plugin.trackEvent(category, action);\n if (subaction) {\n plugin.trackEvent(category, subaction);\n }\n });\n }\n\n trackShortcutEvent(category, action, /* optional */ additionalData) {\n this.trackEvent(category, action, additionalData);\n this.trackEvent('ring-shortcut', `${category}$${action}`, additionalData);\n }\n\n trackEntityProperties(entityName, entity, propertiesNames, /* optional */ additionalData) {\n for (let i = 0; i < propertiesNames.length; ++i) {\n const keys = propertiesNames[i].split('.');\n let value = entity;\n\n if (!keys.length) {\n continue;\n }\n\n for (let j = 0; j < keys.length; ++j) {\n if (value.hasOwnProperty(keys[j])) {\n value = value[keys[j]];\n } else {\n value = 'no-value';\n break;\n }\n }\n\n if (typeof value === 'string') {\n value = value.toLowerCase().replace(/[._]+/g, '-');\n }\n\n const resultAction = `${keys.join('-')}__${value}`;\n this.trackEvent(entityName, resultAction, additionalData);\n }\n }\n\n _buildSuffix(additionalData) {\n if (!additionalData) {\n return '';\n }\n\n let suffix = '';\n let key;\n for (key in additionalData) {\n if (additionalData.hasOwnProperty(key)) {\n suffix += `__${key}$${additionalData[key]}`;\n }\n }\n\n return suffix;\n }\n}\n\nexport default new Analytics();\n","/**\n *\n * @param {string?} gaId Google Analytics ID (should be undefined in development)\n * @constructor\n */\nexport default class AnalyticsGAPlugin {\n constructor(gaId, isDevelopment, domain) {\n if (!gaId && !isDevelopment) {\n return;\n }\n /* eslint-disable */\n (function (i, s, o, g, r, a, m) {\n i.GoogleAnalyticsObject = r;\n i[r] = i[r] || function () {\n (i[r].q = i[r].q || []).push(arguments)\n }, i[r].l = 1 * new Date();\n a = s.createElement(o),\n m = s.getElementsByTagName(o)[0];\n a.async = 1;\n a.src = g;\n m.parentNode.insertBefore(a, m)\n })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');\n /* eslint-enable */\n /**\n * UA-57284711-1 - ga key for development purpose\n */\n const key = gaId || 'UA-57284711-1';\n /* global ga */\n const gaCookieParams = domain ? {cookieDomain: domain} : {};\n ga('create', key, (!gaId ? {cookieDomain: 'none'} : gaCookieParams));\n ga('set', 'anonymizeIp', true);\n ga('set', 'allowAdFeatures', false);\n }\n\n trackEvent(category, action) {\n if (window.ga) {\n const eventOptions = {\n eventCategory: category,\n eventAction: action\n };\n ga('send', 'event', eventOptions);\n }\n }\n\n trackPageView(path) {\n if (window.ga) {\n ga('send', 'pageview', path);\n }\n }\n}\n","import sniffer from '../global/sniffer';\n\nconst AnalyticsCustomPluginUtils = {};\nconst SECOND = 1000;\nconst HOUR = 3600;\n\n/**\n * Statistics server does not accept undefined values and strings containing certain symbols\n * @param value\n * @param isCategory\n * @returns string, where forbidden symbols are replaced with '_'\n */\nAnalyticsCustomPluginUtils.reformatString = (value, isCategory) => {\n const str = String(value);\n /**\n * Category also cannot contain the '/' character (but an action can)\n */\n const regexp = isCategory ? /[.:;!@#^&*(){}\\[\\]?,%=+\\\\\\/]+/g : /[.:;!@#^&*(){}\\[\\]?,%=+\\\\]+/g;\n return str.replace(regexp, '_');\n};\n\nAnalyticsCustomPluginUtils.getPageViewDurationPresentation = durationMs => {\n const duration = durationMs / SECOND;\n if (duration > HOUR) {\n return 'more-than-hour';\n }\n\n /**\n * rounded duration possible values:\n * less than 1 second: [0, 1)\n * less than 2 seconds: [1, 2)\n * less than 4 seconds: [2, 4)\n * less than 16 seconds: [4, 16)\n * ....\n * n - less than 2^(n + 1) seconds\n */\n let roundedDuration = Math.floor(Math.pow(2, Math.floor(Math.log2(duration)) + 1));\n roundedDuration = (roundedDuration > 0) ? roundedDuration : 1;\n\n return `less-than-${roundedDuration}-sec`;\n};\n\nAnalyticsCustomPluginUtils.getScreenWidthPresentation = () => {\n /**\n * Sizes were taken from bootstrap's grid (xs, sm, md, lg)\n */\n // eslint-disable-next-line no-magic-numbers\n const sizes = [0, 768, 992, 1200];\n for (let i = 1; i < sizes.length; ++i) {\n if (window.innerWidth < sizes[i]) {\n return `[${sizes[i - 1]}px;${sizes[i]}px)`;\n }\n }\n return '[1200px;inf)';\n};\n\nAnalyticsCustomPluginUtils.npeSaveLowerCase = val => (val || 'unknown').toLowerCase();\n\nAnalyticsCustomPluginUtils.getUserAgentPresentation = () => {\n const name = AnalyticsCustomPluginUtils.npeSaveLowerCase(sniffer.browser.name || 'unknown');\n const majorVersion = sniffer.browser.version[0];\n const version = majorVersion || 'unknown';\n\n return `${name}$${version}`;\n};\n\nAnalyticsCustomPluginUtils.getDevicePixelRatioPresentation = () => {\n if (!window.devicePixelRatio || !window.devicePixelRatio.toFixed) {\n return 'unknown';\n }\n return String(window.devicePixelRatio.toFixed(1));\n};\n\nexport default AnalyticsCustomPluginUtils;\n","import AnalyticsCustomPluginUtils from './analytics__custom-plugin-utils';\n\nconst DEFAULT_FLUSH_INTERVAL = 10000;\nconst DEFAULT_FLUSH_MAX_PACK_SIZE = 100;\n\nexport default class AnalyticsCustomPlugin {\n constructor(send, isDevelopment, flushInterval, flushingAllowedChecker) {\n this._data = [];\n this.config({\n send,\n isDevelopment,\n flushInterval,\n flushingAllowedChecker\n });\n }\n\n /**\n * @param config\n * @property {function} config.send\n * @property {boolean} config.isDevelopment\n * @property {number} config.flushInterval\n * @property {function} config.flushingAllowedChecker\n * @property {number} config.flushMaxPackSize\n */\n config(config) {\n let checkFlushingAllowed = config.flushingAllowedChecker;\n if (typeof checkFlushingAllowed !== 'function') {\n checkFlushingAllowed = () => true;\n }\n\n this._flush = () => {\n if (this._data.length > 0 && checkFlushingAllowed()) {\n config.send(this._data);\n this._data = [];\n }\n };\n\n this._isDevelopment = config.isDevelopment;\n this._flushInterval = config.flushInterval || DEFAULT_FLUSH_INTERVAL;\n this._flushMaxPackSize = config.flushMaxPackSize || DEFAULT_FLUSH_MAX_PACK_SIZE;\n }\n\n trackEvent(category, action) {\n this._processEvent(category, action);\n }\n\n trackPageView(path) {\n if (this._lastPagePath === path) {\n return;\n }\n\n this._trackPageViewAdditionalInfo(path);\n this._processEvent('ring-page', path);\n this._processEvent(\n 'ring-navigator_user-agent',\n AnalyticsCustomPluginUtils.getUserAgentPresentation()\n );\n this._processEvent(\n 'ring-navigator_platform',\n AnalyticsCustomPluginUtils.npeSaveLowerCase(navigator.platform)\n );\n this._processEvent(\n 'ring-navigator_lang',\n AnalyticsCustomPluginUtils.npeSaveLowerCase(navigator.language)\n );\n this._processEvent(\n 'ring-device-pixel-ratio',\n AnalyticsCustomPluginUtils.getDevicePixelRatioPresentation()\n );\n this._processEvent(\n 'ring-screen-width',\n AnalyticsCustomPluginUtils.getScreenWidthPresentation()\n );\n }\n\n _initSendSchedule() {\n window.addEventListener('beforeunload', () => {\n this._trackPageViewAdditionalInfo();\n return this._flush();\n });\n\n setInterval(this._flush, this._flushInterval);\n this._hasSendSchedule = true;\n }\n\n _processEvent(rawCategory, rawAction) {\n if (!this._hasSendSchedule && this._flush) {\n this._initSendSchedule();\n }\n const category = AnalyticsCustomPluginUtils.reformatString(rawCategory, true);\n const action = AnalyticsCustomPluginUtils.reformatString(rawAction);\n if (this._isDevelopment) {\n console.log('TRACKING DATA = ', category, action); // eslint-disable-line no-console\n }\n this._addDataToFlushingPack({category, action});\n }\n\n _trackPageViewAdditionalInfo(newPagePath) {\n const currentTime = (new Date()).getTime();\n if (this._lastPagePath) {\n if (this._lastPageViewTime) {\n const duration = AnalyticsCustomPluginUtils.\n getPageViewDurationPresentation(currentTime - this._lastPageViewTime);\n this._processEvent(`ring-pageview-duration_${this._lastPagePath}`, duration);\n }\n }\n this._lastPageViewTime = currentTime;\n this._lastPagePath = newPagePath;\n }\n\n _addDataToFlushingPack(sendingData) {\n this._data.push(sendingData);\n\n if (this._data.length >= this._flushMaxPackSize) {\n this._flush();\n }\n }\n}\n","import angular from 'angular';\n\nimport analyticsInstance from '../analytics/analytics';\nimport AnalyticsGAPlugin from '../analytics/analytics__ga-plugin';\nimport AnalyticsCustomPlugin from '../analytics/analytics__custom-plugin';\n\n/**\n * @name Analytics Ng\n*/\n\nconst angularModule = angular.module('Ring.analytics', []);\n\n/**\n * @name analyticsProvider\n * @description Configures analytics with plugins.\n */\nangularModule.provider('analytics', function provider() {\n let configPlugins = [];\n /**\n * @param plugins\n */\n this.plugins = plugins => {\n configPlugins = plugins;\n };\n\n this.$get = function get($log, $injector) {\n const loadedPlugins = [];\n for (let i = 0; i < configPlugins.length; ++i) {\n if (typeof configPlugins[i] === 'string') {\n try {\n const plugin = $injector.get(configPlugins[i]);\n loadedPlugins.push(plugin);\n $log.debug(`analytics: loaded plugin ${configPlugins[i]}`);\n } catch (err) {\n $log.debug(`analytics: unable to load factory ${configPlugins[i]}`);\n }\n } else {\n loadedPlugins.push(configPlugins[i]);\n }\n }\n analyticsInstance.config(loadedPlugins);\n return analyticsInstance;\n };\n});\n\nangularModule.constant('AnalyticsGAPlugin', AnalyticsGAPlugin);\nangularModule.constant('AnalyticsCustomPlugin', AnalyticsCustomPlugin);\n\n/**\n * Enable page tracking\n */\nangularModule.run(function analyticsRun($rootScope, analytics) {\n $rootScope.$on('$routeChangeSuccess', (evt, current) => { // eslint-disable-line angular/on-watch\n /* eslint-disable angular/no-private-call */\n if (current && current.$$route && current.$$route.originalPath) {\n analytics.trackPageView(current.$$route.originalPath);\n }\n /* eslint-enable angular/no-private-call */\n });\n});\n\n/**\n * @ngdoc directive\n * @name rg-analytics\n *\n * @description\n * The `rg-analytics=\":\"` sends categoryName and eventName to analytics server on\n * user action, specified via attribute `rg-analytics-on` (e.g. rg-analytics-on='mouseover' means that analytics will be sent on mouseover,\n * rg-analytics-on='click' - on click). If there is no attribute rg-analytics-on, the default value 'click' is used.\n */\nangularModule.directive('rgAnalytics', function rgAnalyticsDirective(analytics) {\n return {\n restrict: 'A',\n replace: false,\n\n link: function link($scope, elem) {\n const eventType = elem.attr('rg-analytics-on') || 'click';\n angular.element(elem).bind(eventType, () => {\n analytics.track(elem.attr('rg-analytics'));\n });\n }\n };\n});\n\nexport default angularModule.name;\n","function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nfunction _extendableBuiltin(cls) {\n function ExtendableBuiltin() {\n cls.apply(this, arguments);\n }\n\n ExtendableBuiltin.prototype = Object.create(cls.prototype, {\n constructor: {\n value: cls,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(ExtendableBuiltin, cls);\n } else {\n ExtendableBuiltin.__proto__ = cls;\n }\n\n return ExtendableBuiltin;\n}\n\nvar ExtendableError = function (_extendableBuiltin2) {\n _inherits(ExtendableError, _extendableBuiltin2);\n\n function ExtendableError() {\n var message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';\n\n _classCallCheck(this, ExtendableError);\n\n // extending Error is weird and does not propagate `message`\n var _this = _possibleConstructorReturn(this, (ExtendableError.__proto__ || Object.getPrototypeOf(ExtendableError)).call(this, message));\n\n Object.defineProperty(_this, 'message', {\n configurable: true,\n enumerable: false,\n value: message,\n writable: true\n });\n\n Object.defineProperty(_this, 'name', {\n configurable: true,\n enumerable: false,\n value: _this.constructor.name,\n writable: true\n });\n\n if (Error.hasOwnProperty('captureStackTrace')) {\n Error.captureStackTrace(_this, _this.constructor);\n return _possibleConstructorReturn(_this);\n }\n\n Object.defineProperty(_this, 'stack', {\n configurable: true,\n enumerable: false,\n value: new Error(message).stack,\n writable: true\n });\n return _this;\n }\n\n return ExtendableError;\n}(_extendableBuiltin(Error));\n\nexport default ExtendableError;\n","import sniffer from './sniffer';\n\n/**\n * @description Provides a set of utilities for URL manipulation.\n */\n\n/**\n * @const {RegExp}\n */\nconst ORIGIN_PATTERN = /^[a-z]+:\\/\\/[^/]+/i;\n\n/**\n * @const {RegExp}\n */\nconst ABSOLUTE_URL_PATTERN = /^[a-z]+:\\/\\//i;\n\n/**\n * @const {RegExp}\n */\nexport const ENDING_SLASH_PATTERN = /\\/$/;\n\n/**\n * Get URI from the tag\n * @return {string|undefined} base URI\n */\nexport function getBaseURI() {\n const baseElement = document.getElementsByTagName('base')[0];\n return baseElement ? baseElement.href : undefined;\n}\n\n/**\n * Get absolute URI from the tag\n * @return {string} absolute base URI\n */\nexport function getAbsoluteBaseURL() {\n const baseUrl = getBaseURI();\n const host = `${window.location.protocol}//${window.location.host}`;\n\n let uri;\n if (baseUrl) {\n uri = ABSOLUTE_URL_PATTERN.test(baseUrl) ? baseUrl : host + baseUrl;\n } else {\n uri = host;\n }\n\n return uri;\n}\n\n/**\n * Get origin from the URL\n * @param {string} url URL to extract origin from\n * @returns {string|undefined} origin\n */\nexport function getOrigin(url) {\n const matches = url.match(ORIGIN_PATTERN);\n\n if (matches) {\n return matches[0];\n }\n\n return undefined;\n}\n\n/**\n * Get absolute URI from current page\n * @return {string} absolute URL of current page\n */\nexport function getAbsoluteURL() {\n return window.location.href.split('#')[0];\n}\n\n/**\n * Fixes the URL\n * If the URL is relative and the page contains a TAG, the URL will be converted to absolute\n * : some/path => /some/path\n * @param {string} url URL to fix\n * @param {Function} baseURIGetter a function that returns base URI\n * @return {string} fixed URL\n */\nexport function fixUrl(url, baseURIGetter = getBaseURI) {\n if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1 && url.indexOf('/') !== 0) {\n const baseUrl = baseURIGetter();\n\n if (baseUrl) {\n return baseUrl + url;\n }\n }\n\n return url;\n}\n\nexport function joinBaseURLAndPath(baseUrl, path) {\n if (!baseUrl || path.indexOf('http://') !== -1 || path.indexOf('https://') !== -1) {\n return path;\n }\n\n return baseUrl + path;\n}\n\n/**\n * Resolve URL for SVG icons\n * @param {string} relUrl The value of xlink:href\n * @param {Function} baseURIGetter a function that returns base URI\n * @param {Function} absoluteURLGetter a function that returns absolute URI of current page\n * @return {string} The URL relative to base URL for current page\n */\nexport function resolveRelativeURL(\n relUrl,\n baseURIGetter = getBaseURI,\n absoluteURLGetter = getAbsoluteURL\n) {\n if (baseURIGetter() &&\n (\n sniffer.browser.name === 'firefox' ||\n sniffer.browser.name === 'edge' ||\n // eslint-disable-next-line no-magic-numbers\n sniffer.browser.name === 'chrome' && sniffer.browser.version[0] >= 49\n )\n ) {\n return absoluteURLGetter() + relUrl;\n }\n\n return String(relUrl);\n}\n\n/**\n * Parses a queryString into an object.\n * ```\n * parseQueryString(\"access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=example&expires_in=3600\");\n * // is {access_token: \"2YotnFZFEjr1zCsicMWpAA\", state: \"xyz\", token_type: \"example\", expires_in: \"3600\"}\n * ```\n * @param {string} queryString query parameter string to parse\n * @return {AuthResponse} object with query parameters map\n */\nexport function parseQueryString(queryString) {\n if (queryString == null) {\n return {};\n }\n\n const queryParameterPairRE = /([^&;=]+)=?([^&;]*)/g;\n const FIRST_PAIR_ELEMENT = 1;\n const SECOND_PAIR_ELEMENT = 2;\n const urlParams = {};\n\n function decode(s) {\n return decodeURIComponent(s.replace(/\\+/g, ' '));\n }\n\n let matchedQueryPair;\n while ((matchedQueryPair = queryParameterPairRE.exec(queryString)) != null) {\n urlParams[decode(matchedQueryPair[FIRST_PAIR_ELEMENT])] =\n decode(matchedQueryPair[SECOND_PAIR_ELEMENT]);\n }\n\n return urlParams;\n}\n\n/**\n * Takes a URL as input and a params object.\n * Each property in the params is added to the URL as query string parameters\n * @param {string} url URL to add parameters to\n * @param {Object} params parameters to add\n * @returns {string} encoded URL\n */\nexport function encodeURL(url, params) {\n const equalsSign = '=';\n const firstSeparator = (url.indexOf('?') === -1) ? '?' : '&';\n\n let res = url;\n let k;\n let i = 0;\n\n for (k in params) {\n if (params.hasOwnProperty(k) && params[k] != null) {\n res += (i++ === 0 ? firstSeparator : '&') +\n encodeURIComponent(k) + equalsSign + encodeURIComponent(params[k]);\n }\n }\n\n return res;\n}\n\nexport function isDataURI(uri) {\n return uri.indexOf('data:') === 0;\n}\n","import ExtendableError from 'es6-error';\n\nimport {parseQueryString} from '../global/url';\n\n/**\n * @typedef {Object} AuthResponse\n * @property {?string} accessToken\n * @property {?string} state\n * @property {?string} token_type\n * @property {?string} expiresIn\n * @property {?string} scope\n * @property {?string} error\n */\n\nexport default class AuthResponseParser {\n constructor() {\n this._authResponse = this.readAuthResponseFromURL();\n }\n\n static AuthError = class AuthError extends ExtendableError {\n // Supports weird IE 11 failing test issue\n constructor(authResponse = {}) {\n super(authResponse.errorDescription);\n this.code = authResponse.error;\n this.uri = authResponse.errorUri;\n this.stateId = authResponse.state;\n }\n };\n\n static convertKey(key) {\n return key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());\n }\n\n /**\n * Check if the hash contains an access token.\n * If it does, return auth response. Otherwise return undefined.\n * Always clears the hash part of the URL.\n *\n * @throws {Error} if the auth server returned an error\n * @return {?AuthResponse}\n */\n getAuthResponseFromURL() {\n return this.validateAuthResponse(this._authResponse);\n }\n\n /**\n * Validates given authResponse.\n * If it contains a token - returns the token, if an error is found - throws the error,\n * otherwise - null\n * Always clears the hash part of the URL.\n *\n * @param authResponse {AuthResponse} parsed authResponse\n * @throws {Error} if the auth server returned an error\n * @return {?AuthResponse}\n */\n validateAuthResponse(authResponse) {\n\n // Check for errors\n if (authResponse.error) {\n throw new AuthResponseParser.AuthError(authResponse);\n }\n\n // If there is no token in the hash\n if (!authResponse.accessToken) {\n return null;\n }\n\n return authResponse;\n }\n\n /**\n * Reads the current accessToken from the URL.\n * Doesn't modify URL\n *\n * @return {AuthResponse}\n */\n readAuthResponseFromURL() {\n const authResponse = {};\n const rawAuthResponse = parseQueryString(this.getHash());\n Object.keys(rawAuthResponse).forEach(key => {\n if (key.indexOf('_') !== -1) {\n authResponse[AuthResponseParser.convertKey(key)] = rawAuthResponse[key];\n return;\n }\n\n authResponse[key] = rawAuthResponse[key];\n });\n\n return authResponse;\n }\n\n /**\n * @return {string} part of the URL after # sign.\n * @private\n */\n getHash() {\n // Because of stupid Firefox bug — https://bugzilla.mozilla.org/show_bug.cgi?id=483304\n const location = this.getLocation();\n return location && location.replace(/^[^#]*#?/, '');\n }\n\n /**\n * Current page location.\n * @return {string}\n */\n getLocation() {\n return window.location.toString();\n }\n}\n","import sniffer from '../global/sniffer';\n\nimport AuthResponseParser from './response-parser';\n\nconst NAVBAR_HEIGHT = 50;\nconst isEdge = sniffer.browser.name === 'edge';\nconst CLOSED_CHECK_INTERVAL = 200;\n\nexport default class WindowFlow {\n _timeoutId = null;\n\n constructor(requestBuilder, storage) {\n this._requestBuilder = requestBuilder;\n this._storage = storage;\n this._reset();\n }\n\n /**\n * Opens window with the given URL\n * @param {string} url\n * @private\n */\n _openWindow(url) {\n const height = 700;\n const width = 750;\n const screenHalves = 2;\n const top = (window.screen.height - height - NAVBAR_HEIGHT) / screenHalves;\n const left = (window.screen.width - width) / screenHalves;\n\n const loginWindow = window.open(\n isEdge ? null : url,\n 'HubLoginWindow',\n `height=${height}, width=${width}, left=${left}, top=${top}`\n );\n\n if (isEdge) {\n setTimeout(() => {\n loginWindow.location = url;\n }, 0);\n }\n\n return loginWindow;\n }\n\n /**\n * Initiates authorization in window\n */\n async _load() {\n const authRequest = await this._requestBuilder.prepareAuthRequest(\n // eslint-disable-next-line camelcase\n {request_credentials: 'required', auth_mode: 'bypass_to_login'},\n {nonRedirect: true}\n );\n\n return new Promise((resolve, reject) => {\n this.reject = reject;\n let cleanRun;\n\n const cleanUp = () => {\n if (cleanRun) {\n return;\n }\n cleanRun = true;\n /* eslint-disable no-use-before-define */\n removeStateListener();\n removeTokenListener();\n /* eslint-enable no-use-before-define */\n\n this._loginWindow.close();\n clearTimeout(this._timeoutId);\n };\n\n const removeTokenListener = this._storage.onTokenChange(token => {\n if (token) {\n cleanUp();\n resolve(token.accessToken);\n }\n });\n\n const removeStateListener = this._storage.onStateChange(authRequest.stateId, state => {\n if (state && state.error) {\n cleanUp();\n reject(new AuthResponseParser.AuthError(state));\n }\n });\n\n if (this._loginWindow === null || this._loginWindow.closed === true) {\n this._loginWindow = this._openWindow(authRequest.url);\n } else {\n this._loginWindow.location = authRequest.url;\n }\n\n this.checkIsClosed();\n });\n }\n\n checkIsClosed = () => {\n if (this._loginWindow.closed) {\n this.stop();\n return;\n }\n this._timeoutId = setTimeout(this.checkIsClosed, CLOSED_CHECK_INTERVAL);\n };\n\n _reset = () => {\n this._promise = null;\n this._loginWindow = null;\n clearTimeout(this._timeoutId);\n };\n\n stop() {\n if (this._loginWindow !== null) {\n this._loginWindow.close();\n }\n if (this.reject) {\n this.reject('Authorization window closed');\n }\n this._reset();\n }\n\n authorize() {\n if (this._promise !== null && this._loginWindow !== null && this._loginWindow.closed !== true) {\n this._loginWindow.focus();\n\n return this._promise;\n }\n\n this._promise = this._load();\n\n this._promise.then(this._reset, this._reset);\n\n return this._promise;\n }\n}\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\n\nconst LEFT_BUTTON = 0;\n// Cmd/Ctrl/Shift/Alt + Click should trigger default browser behaviour. Same applies to non-left clicks\nconst isPlainLeftClick = e =>\n e.button === LEFT_BUTTON && !e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey;\n\nexport default class ClickableLink extends PureComponent {\n static propTypes = {\n onClick: PropTypes.func,\n onPlainLeftClick: PropTypes.func,\n onConditionalClick: PropTypes.func,\n activeClassName: PropTypes.string,\n href: PropTypes.string.isRequired,\n children: PropTypes.node.isRequired\n };\n\n onClick = e => {\n const {onClick, onConditionalClick, onPlainLeftClick} = this.props;\n\n const isPlainLeft = isPlainLeftClick(e);\n\n if (onClick) {\n onClick(e);\n }\n\n if (onConditionalClick) {\n onConditionalClick(isPlainLeft, e);\n }\n\n if (onPlainLeftClick && isPlainLeft) {\n e.preventDefault();\n onPlainLeftClick(e);\n }\n };\n\n render() {\n const {\n onConditionalClick, onPlainLeftClick, activeClassName,\n href,\n children,\n ...restProps\n } = this.props;\n\n return {children};\n }\n}\n","import React, {Component} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport {pure} from 'recompose';\n\nimport memoize from '../global/memoize';\nimport dataTests from '../global/data-tests';\n\nimport ClickableLink from './clickableLink';\nimport styles from './link.css';\n\n/**\n * @name Link\n */\n\nlet isCompatibilityMode = false;\n\nexport function setCompatibilityMode(isEnabled) {\n isCompatibilityMode = isEnabled;\n}\n\nconst makeWrapText = memoize(innerClassName => {\n const WrapText = pure(function WrapText({className, children}) {\n const classes = classNames(styles.inner, className, innerClassName);\n return {children};\n });\n\n WrapText.propTypes = {\n className: PropTypes.string,\n children: PropTypes.node\n };\n\n return WrapText;\n});\n\nexport function linkHOC(ComposedComponent) {\n const isCustom = typeof ComposedComponent !== 'string' && ComposedComponent !== ClickableLink;\n\n return class Link extends Component {\n static propTypes = {\n className: PropTypes.string,\n innerClassName: PropTypes.string,\n active: PropTypes.bool,\n inherit: PropTypes.bool,\n pseudo: PropTypes.bool,\n hover: PropTypes.bool,\n children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),\n 'data-test': PropTypes.string,\n href: PropTypes.string,\n onPlainLeftClick: PropTypes.func,\n onClick: PropTypes.func\n };\n\n getChildren() {\n const {children, innerClassName} = this.props;\n\n const WrapText = makeWrapText(innerClassName);\n\n return typeof children === 'function'\n ? children(WrapText)\n : {children};\n }\n\n render() {\n const {\n active,\n inherit,\n pseudo,\n hover,\n className,\n 'data-test': dataTest,\n href,\n innerClassName, children, onPlainLeftClick, onClick,\n ...props\n } = this.props;\n const useButton = pseudo || !isCustom && href == null;\n\n const classes = classNames(styles.link, className, {\n [styles.active]: active,\n [styles.inherit]: inherit,\n [styles.hover]: hover,\n [styles.compatibilityUnderlineMode]: isCompatibilityMode,\n [styles.pseudo]: useButton\n });\n\n if (isCustom && !props.activeClassName) {\n props.activeClassName = styles.active;\n }\n\n if (useButton) {\n return (\n {this.getChildren()}\n );\n }\n\n return (\n \n {this.getChildren()}\n \n );\n }\n };\n}\n\nexport default linkHOC(ClickableLink);\n","import React, {Component} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport styles from './group.css';\n\n/**\n * @name Group\n */\n\nexport default class Group extends Component {\n static propTypes = {\n children: PropTypes.node,\n className: PropTypes.string\n };\n\n render() {\n const {children, className, ...restProps} = this.props;\n const classes = classNames(styles.group, className);\n\n return (\n \n {children}\n \n );\n }\n}\n","import React from 'react';\n\nimport alertService from '../alert-service/alert-service';\nimport Alert from '../alert/alert';\nimport Link from '../link/link';\nimport Group from '../group/group';\n\nimport styles from './down-notification.css';\n\nlet key = null;\n\nfunction renderAlert(message, type = Alert.Type.WARNING) {\n const existingAlert = alertService.showingAlerts.filter(alert => alert.key === key)[0];\n\n if (!existingAlert) {\n key = alertService.addAlert(message, type, 0, {closeable: false});\n } else {\n existingAlert.message = message;\n existingAlert.type = type;\n alertService.renderAlerts();\n }\n}\n\n/* eslint-disable react/prop-types */\nfunction Message({translations, onCheckAgain}) {\n const {backendIsNotAvailable, checkAgain, errorMessage} = translations;\n\n return (\n
\n \n
{backendIsNotAvailable}
\n
\n {errorMessage} \n {checkAgain}\n
\n );\n}\n/* eslint-enable */\n\nexport default function onBackendDown({onCheckAgain, translations}) {\n async function checkAgainWithoutClosing(e) {\n // Alert has weird behaviour of handling clicks by \"a\" tags\n e.stopPropagation();\n try {\n renderAlert('Connecting...', Alert.Type.LOADING);\n await onCheckAgain();\n } catch (err) {\n renderAlert(\n \n );\n }\n }\n\n renderAlert(\n \n );\n\n return () => alertService.remove(key);\n}\n","export default class Listeners {\n constructor() {\n this.removeAll();\n }\n\n trigger(event, data) {\n const handlers = this._all.get(event);\n\n if (handlers) {\n return Promise.all([...handlers].map(fn => fn(data)));\n }\n\n return Promise.resolve([]);\n }\n\n add(event, handler) {\n let handlers = this._all.get(event);\n\n if (!handlers) {\n handlers = new Set();\n this._all.set(event, handlers);\n }\n\n handlers.add(handler);\n }\n\n remove(event, handler) {\n const handlers = this._all.get(event);\n\n if (handlers) {\n handlers.delete(handler);\n }\n }\n\n removeAll() {\n this._all = new Map();\n }\n}\n","var support = {\n searchParams: 'URLSearchParams' in self,\n iterable: 'Symbol' in self && 'iterator' in Symbol,\n blob:\n 'FileReader' in self &&\n 'Blob' in self &&\n (function() {\n try {\n new Blob()\n return true\n } catch (e) {\n return false\n }\n })(),\n formData: 'FormData' in self,\n arrayBuffer: 'ArrayBuffer' in self\n}\n\nfunction isDataView(obj) {\n return obj && DataView.prototype.isPrototypeOf(obj)\n}\n\nif (support.arrayBuffer) {\n var viewClasses = [\n '[object Int8Array]',\n '[object Uint8Array]',\n '[object Uint8ClampedArray]',\n '[object Int16Array]',\n '[object Uint16Array]',\n '[object Int32Array]',\n '[object Uint32Array]',\n '[object Float32Array]',\n '[object Float64Array]'\n ]\n\n var isArrayBufferView =\n ArrayBuffer.isView ||\n function(obj) {\n return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1\n }\n}\n\nfunction normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name)\n }\n if (/[^a-z0-9\\-#$%&'*+.^_`|~]/i.test(name)) {\n throw new TypeError('Invalid character in header field name')\n }\n return name.toLowerCase()\n}\n\nfunction normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value)\n }\n return value\n}\n\n// Build a destructive iterator for the value list\nfunction iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift()\n return {done: value === undefined, value: value}\n }\n }\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n }\n }\n\n return iterator\n}\n\nexport function Headers(headers) {\n this.map = {}\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value)\n }, this)\n } else if (Array.isArray(headers)) {\n headers.forEach(function(header) {\n this.append(header[0], header[1])\n }, this)\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name])\n }, this)\n }\n}\n\nHeaders.prototype.append = function(name, value) {\n name = normalizeName(name)\n value = normalizeValue(value)\n var oldValue = this.map[name]\n this.map[name] = oldValue ? oldValue + ', ' + value : value\n}\n\nHeaders.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)]\n}\n\nHeaders.prototype.get = function(name) {\n name = normalizeName(name)\n return this.has(name) ? this.map[name] : null\n}\n\nHeaders.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n}\n\nHeaders.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value)\n}\n\nHeaders.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this)\n }\n }\n}\n\nHeaders.prototype.keys = function() {\n var items = []\n this.forEach(function(value, name) {\n items.push(name)\n })\n return iteratorFor(items)\n}\n\nHeaders.prototype.values = function() {\n var items = []\n this.forEach(function(value) {\n items.push(value)\n })\n return iteratorFor(items)\n}\n\nHeaders.prototype.entries = function() {\n var items = []\n this.forEach(function(value, name) {\n items.push([name, value])\n })\n return iteratorFor(items)\n}\n\nif (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries\n}\n\nfunction consumed(body) {\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true\n}\n\nfunction fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result)\n }\n reader.onerror = function() {\n reject(reader.error)\n }\n })\n}\n\nfunction readBlobAsArrayBuffer(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n reader.readAsArrayBuffer(blob)\n return promise\n}\n\nfunction readBlobAsText(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n reader.readAsText(blob)\n return promise\n}\n\nfunction readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf)\n var chars = new Array(view.length)\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i])\n }\n return chars.join('')\n}\n\nfunction bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength)\n view.set(new Uint8Array(buf))\n return view.buffer\n }\n}\n\nfunction Body() {\n this.bodyUsed = false\n\n this._initBody = function(body) {\n this._bodyInit = body\n if (!body) {\n this._bodyText = ''\n } else if (typeof body === 'string') {\n this._bodyText = body\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString()\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer)\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer])\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body)\n } else {\n this._bodyText = body = Object.prototype.toString.call(body)\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8')\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type)\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')\n }\n }\n }\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n }\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n return consumed(this) || Promise.resolve(this._bodyArrayBuffer)\n } else {\n return this.blob().then(readBlobAsArrayBuffer)\n }\n }\n }\n\n this.text = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n }\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n }\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n }\n\n return this\n}\n\n// HTTP methods whose capitalization should be normalized\nvar methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']\n\nfunction normalizeMethod(method) {\n var upcased = method.toUpperCase()\n return methods.indexOf(upcased) > -1 ? upcased : method\n}\n\nexport function Request(input, options) {\n options = options || {}\n var body = options.body\n\n if (input instanceof Request) {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url\n this.credentials = input.credentials\n if (!options.headers) {\n this.headers = new Headers(input.headers)\n }\n this.method = input.method\n this.mode = input.mode\n this.signal = input.signal\n if (!body && input._bodyInit != null) {\n body = input._bodyInit\n input.bodyUsed = true\n }\n } else {\n this.url = String(input)\n }\n\n this.credentials = options.credentials || this.credentials || 'same-origin'\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers)\n }\n this.method = normalizeMethod(options.method || this.method || 'GET')\n this.mode = options.mode || this.mode || null\n this.signal = options.signal || this.signal\n this.referrer = null\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body)\n}\n\nRequest.prototype.clone = function() {\n return new Request(this, {body: this._bodyInit})\n}\n\nfunction decode(body) {\n var form = new FormData()\n body\n .trim()\n .split('&')\n .forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=')\n var name = split.shift().replace(/\\+/g, ' ')\n var value = split.join('=').replace(/\\+/g, ' ')\n form.append(decodeURIComponent(name), decodeURIComponent(value))\n }\n })\n return form\n}\n\nfunction parseHeaders(rawHeaders) {\n var headers = new Headers()\n // Replace instances of \\r\\n and \\n followed by at least one space or horizontal tab with a space\n // https://tools.ietf.org/html/rfc7230#section-3.2\n var preProcessedHeaders = rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ')\n preProcessedHeaders.split(/\\r?\\n/).forEach(function(line) {\n var parts = line.split(':')\n var key = parts.shift().trim()\n if (key) {\n var value = parts.join(':').trim()\n headers.append(key, value)\n }\n })\n return headers\n}\n\nBody.call(Request.prototype)\n\nexport function Response(bodyInit, options) {\n if (!options) {\n options = {}\n }\n\n this.type = 'default'\n this.status = options.status === undefined ? 200 : options.status\n this.ok = this.status >= 200 && this.status < 300\n this.statusText = 'statusText' in options ? options.statusText : 'OK'\n this.headers = new Headers(options.headers)\n this.url = options.url || ''\n this._initBody(bodyInit)\n}\n\nBody.call(Response.prototype)\n\nResponse.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n}\n\nResponse.error = function() {\n var response = new Response(null, {status: 0, statusText: ''})\n response.type = 'error'\n return response\n}\n\nvar redirectStatuses = [301, 302, 303, 307, 308]\n\nResponse.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n}\n\nexport var DOMException = self.DOMException\ntry {\n new DOMException()\n} catch (err) {\n DOMException = function(message, name) {\n this.message = message\n this.name = name\n var error = Error(message)\n this.stack = error.stack\n }\n DOMException.prototype = Object.create(Error.prototype)\n DOMException.prototype.constructor = DOMException\n}\n\nexport function fetch(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init)\n\n if (request.signal && request.signal.aborted) {\n return reject(new DOMException('Aborted', 'AbortError'))\n }\n\n var xhr = new XMLHttpRequest()\n\n function abortXhr() {\n xhr.abort()\n }\n\n xhr.onload = function() {\n var options = {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n }\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')\n var body = 'response' in xhr ? xhr.response : xhr.responseText\n resolve(new Response(body, options))\n }\n\n xhr.onerror = function() {\n reject(new TypeError('Network request failed'))\n }\n\n xhr.ontimeout = function() {\n reject(new TypeError('Network request failed'))\n }\n\n xhr.onabort = function() {\n reject(new DOMException('Aborted', 'AbortError'))\n }\n\n xhr.open(request.method, request.url, true)\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true\n } else if (request.credentials === 'omit') {\n xhr.withCredentials = false\n }\n\n if ('responseType' in xhr && support.blob) {\n xhr.responseType = 'blob'\n }\n\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value)\n })\n\n if (request.signal) {\n request.signal.addEventListener('abort', abortXhr)\n\n xhr.onreadystatechange = function() {\n // DONE (success or failure)\n if (xhr.readyState === 4) {\n request.signal.removeEventListener('abort', abortXhr)\n }\n }\n }\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)\n })\n}\n\nfetch.polyfill = true\n\nif (!self.fetch) {\n self.fetch = fetch\n self.Headers = Headers\n self.Request = Request\n self.Response = Response\n}\n","import 'whatwg-fetch';\nimport ExtendableError from 'es6-error';\n\nimport {encodeURL, joinBaseURLAndPath} from '../global/url';\n\n/**\n * @name HTTP\n */\n\nconst TOKEN_TYPE = 'Bearer';\nconst STATUS_OK_IF_MORE_THAN = 200;\nconst STATUS_BAD_IF_MORE_THAN = 300;\n\nexport const defaultFetchConfig = {\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json'\n },\n credentials: 'same-origin'\n};\n\nexport class HTTPError extends ExtendableError {\n constructor(response, data = {}) {\n super(`${response.status} ${response.statusText || ''}`);\n this.data = data;\n this.status = response.status;\n }\n}\n\nexport const CODE = {\n UNAUTHORIZED: 401\n};\n\nexport default class HTTP {\n baseUrl = null;\n _requestsMeta = new WeakMap();\n\n constructor(auth, baseUrl, fetchConfig = {}) {\n if (auth) {\n this.setAuth(auth);\n }\n this.setBaseUrl(baseUrl);\n\n const {headers, ...defaultConfig} = defaultFetchConfig;\n\n this.fetchConfig = {\n ...defaultConfig,\n ...fetchConfig,\n headers: {\n ...headers,\n ...fetchConfig.headers\n }\n };\n }\n\n setAuth = auth => {\n this.requestToken = () => auth.requestToken();\n this.shouldRefreshToken = auth.constructor.shouldRefreshToken;\n this.forceTokenUpdate = () => auth.forceTokenUpdate();\n }\n\n setBaseUrl = baseUrl => {\n this.baseUrl = baseUrl;\n }\n\n _fetch(...args) {\n return fetch(...args);\n }\n\n _makeRequestUrl(url, queryObject) {\n const urlWithQuery = encodeURL(url, queryObject);\n return joinBaseURLAndPath(this.baseUrl, urlWithQuery);\n }\n\n _performRequest(url, token, params = {}) {\n const {headers, body, query = {}, sendRawBody, ...fetchConfig} = params;\n\n const combinedHeaders = {\n ...this.fetchConfig.headers,\n ...(token ? {Authorization: `${TOKEN_TYPE} ${token}`} : {}),\n ...headers\n };\n\n Object.keys(combinedHeaders).forEach(key => {\n if (combinedHeaders[key] === null || combinedHeaders[key] === undefined) {\n Reflect.deleteProperty(combinedHeaders, key);\n }\n });\n\n return this._fetch(\n this._makeRequestUrl(url, query),\n {\n ...this.fetchConfig,\n headers: combinedHeaders,\n ...fetchConfig,\n body: body && !sendRawBody ? JSON.stringify(body) : body\n }\n );\n }\n\n _storeRequestMeta(parsedResponse, rawResponse) {\n const {headers, ok, redirected, status, statusText, type, url} = rawResponse;\n this._requestsMeta.\n set(parsedResponse, {headers, ok, redirected, status, statusText, type, url});\n }\n\n async _processResponse(response) {\n const contentType = response.headers.get('content-type');\n const isJson = contentType && contentType.indexOf('application/json') !== -1;\n\n if (HTTP._isErrorStatus(response.status)) {\n let resJson;\n try {\n resJson = await (isJson ? response.json() : response.text());\n } catch (err) {\n // noop\n }\n\n throw new HTTPError(response, resJson);\n }\n\n try {\n const parsedResponse = await (isJson ? response.json() : {data: await response.text()});\n this._storeRequestMeta(parsedResponse, response);\n return parsedResponse;\n } catch (err) {\n return response;\n }\n }\n\n static _isErrorStatus(status) {\n return status < STATUS_OK_IF_MORE_THAN || status >= STATUS_BAD_IF_MORE_THAN;\n }\n\n fetch = async (url, params = {}) => {\n const {body, query = {}, ...fetchConfig} = params;\n\n const response = await this._fetch(\n this._makeRequestUrl(url, query),\n {\n ...fetchConfig,\n body: body ? JSON.stringify(body) : body\n }\n );\n\n return this._processResponse(response);\n }\n\n async authorizedFetch(...args) {\n const response = await this._performRequest(...args);\n\n return this._processResponse(response);\n }\n\n request = async (url, params) => {\n let token = await this.requestToken();\n let response = await this._performRequest(url, token, params);\n\n try {\n // Wait for result to catch an HTTP error\n return await this._processResponse(response);\n } catch (error) {\n if (!(error instanceof HTTPError)) {\n throw error;\n }\n\n const shouldRefreshToken = error.data.error !== undefined\n ? this.shouldRefreshToken(error.data.error)\n : false;\n\n if (shouldRefreshToken) {\n token = await this.forceTokenUpdate();\n response = await this._performRequest(url, token, params);\n\n return this._processResponse(response);\n }\n\n throw error;\n }\n }\n\n getMetaForResponse = response => this._requestsMeta.get(response);\n\n get = (url, params) => (\n this.request(url, {\n method: 'GET',\n ...params\n })\n )\n\n post = (url, params) => (\n this.request(url, {\n method: 'POST',\n ...params\n })\n )\n}\n","/**\n * @return {LocalStorage}\n * @param {{type: string}} config Set to \"session\" to use sessionStorage\n * @constructor\n */\nexport default class LocalStorage {\n static async safePromise(resolver) {\n try {\n return await new Promise(resolver);\n } catch (e) {\n if (e && e.name === 'NS_ERROR_FILE_CORRUPTED') {\n /* eslint-disable no-alert */\n window.alert('Sorry, it looks like your browser storage is corrupted. ' +\n 'Please clear your storage by going to Tools -> Clear Recent History -> Cookies' +\n ' and setting time range to \"Everything\". This will remove the corrupted browser storage across all sites.');\n /* eslint-enable no-alert */\n }\n throw e;\n }\n }\n\n constructor(config = {}) {\n this.storageType = config.type === 'session' ? 'sessionStorage' : 'localStorage';\n }\n\n /**\n * @param {string} name\n * @return {Promise}\n */\n get(name) {\n return this.constructor.safePromise(resolve => {\n const value = window[this.storageType].getItem(name);\n try {\n resolve(JSON.parse(value));\n } catch (e) {\n resolve(value);\n }\n });\n }\n\n /**\n * @param {string} name\n * @param {object} value\n * @return {Promise}\n */\n set(name, value) {\n return this.constructor.safePromise(resolve => {\n window[this.storageType].setItem(name, JSON.stringify(value));\n resolve(value);\n });\n }\n\n /**\n * @param {string} name\n * @return {Promise}\n */\n remove(name) {\n const storageType = this.storageType;\n\n return this.constructor.safePromise(resolve => {\n if (window[storageType].hasOwnProperty(name)) {\n window[storageType].removeItem(name);\n }\n resolve();\n });\n }\n\n /**\n * @param callback\n * @return {Promise}\n */\n each(callback) {\n const storageType = this.storageType;\n\n return this.constructor.safePromise(resolve => {\n const promises = [];\n\n for (const item in window[storageType]) {\n if (window[storageType].hasOwnProperty(item)) {\n let value = window[storageType].getItem(item);\n try {\n value = JSON.parse(value);\n } catch (e) {\n // Do nothing\n }\n\n promises.push(Promise.resolve(callback(item, value)));\n }\n }\n\n resolve(Promise.all(promises));\n });\n }\n\n /**\n * @param {string} name\n * @param {Function} callback\n * @return {Function}\n */\n on(name, callback) {\n function handleStorage(e) {\n if (e.key === name) {\n try {\n callback(JSON.parse(e.newValue));\n } catch (err) {\n callback(e.newValue);\n }\n }\n }\n\n window.addEventListener('storage', handleStorage, false);\n\n return () => window.removeEventListener('storage', handleStorage, false);\n }\n}\n","import deepEqual from 'deep-equal';\n\nconst DEFAULT_CHECK_DELAY = 3000;\nconst COOKIE_EXPIRES = 365;\nconst QUOTA = 4093;\n// eslint-disable-next-line no-magic-numbers\nconst SECONDS_IN_DAY = 24 * 60 * 60 * 1000;\n\n/**\n * @prop {string} cookieName\n *\n * @param {{cookieName: string}} config\n * @param {{checkDelay: number}} config\n * @param {{type: string}} config\n * @return {FallbackStorage}\n * @constructor\n */\nexport default class FallbackStorage {\n static DEFAULT_COOKIE_NAME = 'localStorage';\n static DEFAULT_SESSION_COOKIE_NAME = 'sessionStorage';\n static DEFAULT_CHECK_DELAY = DEFAULT_CHECK_DELAY;\n static COOKIE_EXPIRES = COOKIE_EXPIRES;\n\n /**\n * Maximum storage size\n * @see http://browsercookielimits.squawky.net/\n * @type {number}\n */\n static QUOTA = QUOTA;\n\n /**\n * @param {string} name\n * @param {string} value\n * @param {number} days\n * @private\n */\n static _createCookie(name, value, days) {\n let date;\n let expires;\n\n if (days) {\n date = new Date();\n date.setTime(date.getTime() + (days * SECONDS_IN_DAY));\n expires = `; expires=${date.toGMTString()}`;\n } else {\n expires = ';';\n }\n\n document.cookie = `${name}=${value}${expires}; path=/`;\n }\n\n /**\n *\n * @param {string} name\n * @return {string}\n * @private\n */\n static _readCookie(name) {\n const nameEQ = `${name}=`;\n const cookies = document.cookie.split(';');\n\n let cookie;\n for (let i = 0; i < cookies.length; i++) {\n cookie = cookies[i];\n while (cookie.charAt(0) === ' ') {\n cookie = cookie.substring(1, cookie.length);\n }\n\n if (cookie.indexOf(nameEQ) === 0) {\n return cookie.substring(nameEQ.length, cookie.length);\n }\n }\n\n return undefined;\n }\n\n constructor(config = {}) {\n const session = config.type === 'session';\n\n this.cookieName = config.cookieName ||\n (\n session\n ? this.constructor.DEFAULT_SESSION_COOKIE_NAME\n : this.constructor.DEFAULT_COOKIE_NAME\n );\n this.checkDelay = config.checkDelay || this.constructor.DEFAULT_CHECK_DELAY;\n this.expires = session ? this.constructor.COOKIE_EXPIRES : null;\n }\n\n /**\n * @return {Promise}\n * @private\n */\n _read() {\n return new Promise(resolve => {\n const rawData = FallbackStorage._readCookie(this.cookieName);\n resolve(JSON.parse(decodeURIComponent(rawData)));\n }).catch(() => ({}));\n }\n\n /**\n * @param data\n * @return {Promise}\n * @private\n */\n _write(data) {\n return new Promise(resolve => {\n const stringData = encodeURIComponent(JSON.stringify(data));\n FallbackStorage.\n _createCookie(this.cookieName, stringData === '{}' ? '' : stringData, this.expires);\n return resolve(data);\n });\n }\n\n /**\n * @param {string} key\n * @return {Promise}\n */\n get(key) {\n return this._read().then(data => data[key] || null);\n }\n\n /**\n * @param {string} key\n * @param {object} value\n * @return {Promise}\n */\n set(key, value) {\n return this._read().then(data => {\n if (key) {\n if (value != null) {\n data[key] = value;\n } else {\n Reflect.deleteProperty(data, key);\n }\n }\n\n return this._write(data);\n });\n }\n\n /**\n * @param {string} key\n * @return {Promise}\n */\n remove(key) {\n return this.set(key, null);\n }\n\n /**\n *\n * @param {function(string, value)} callback\n * @return {Promise}\n */\n each(callback) {\n if (typeof callback !== 'function') {\n return Promise.reject(new Error('Callback is not a function'));\n }\n\n return this._read().then(data => {\n const promises = [];\n for (const key in data) {\n if (data.hasOwnProperty(key)) {\n promises.push(callback(key, data[key]));\n }\n }\n return Promise.all(promises);\n });\n }\n\n /**\n * @param {string} key\n * @param {Function} callback\n * @return {Function}\n */\n on(key, callback) {\n let stop = false;\n\n const checkForChange = oldValue => {\n this.get(key).then(newValue => {\n if (stop) {\n return;\n }\n\n if (!deepEqual(oldValue, newValue)) {\n callback(newValue);\n }\n\n window.setTimeout(() => checkForChange(oldValue), this.checkDelay);\n });\n };\n\n this.get(key).then(checkForChange);\n\n return () => {\n stop = true;\n };\n }\n}\n","import LocalStorage from './storage__local';\nimport FallbackStorage from './storage__fallback';\n\n/**\n * @name Storage\n */\n\n/**\n * @constructor\n * @extends {LocalStorage}\n */\nlet Storage = LocalStorage;\n\n// Using try/catch here because of IE10+ protected mode and other browsers' quirks\n// See https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js\ntry {\n const temp = 'testStorage';\n localStorage.setItem(temp, temp);\n localStorage.removeItem(temp);\n} catch (e) {\n Storage = FallbackStorage;\n}\n\nconst ActualStorage = Storage;\nexport default ActualStorage;\n","import Storage from '../storage/storage';\nimport sniffr from '../global/sniffer';\n\n/**\n * @typedef {Object} StoredToken\n * @property {string} accessToken\n * @property {string[]} scopes\n * @property {number} expires\n */\n\n/**\n * @typedef {Object} StoredState\n * @property {Date} created\n * @property {string} restoreLocation\n * @property {string[]} scopes\n */\n\nconst DEFAULT_STATE_QUOTA = 102400; // 100 kb ~~ 200 tabs with a large list of scopes\n// eslint-disable-next-line no-magic-numbers\nconst DEFAULT_STATE_TTL = 1000 * 60 * 60 * 24; // nobody will need auth state after a day\nconst UPDATE_USER_TIMEOUT = 1000;\nconst isIE11 = sniffr.browser.name === 'ie' && sniffr.browser.versionString === '11.0';\n\nexport default class AuthStorage {\n /**\n * Custom storage for Auth\n * @param {{stateKeyPrefix: string, tokenKey: string, onTokenRemove: Function}} config\n */\n constructor(config) {\n this.messagePrefix = config.messagePrefix || '';\n this.stateKeyPrefix = config.stateKeyPrefix;\n this.tokenKey = config.tokenKey;\n this.userKey = config.userKey || 'user-key';\n this.stateTTL = config.stateTTL || DEFAULT_STATE_TTL;\n this._lastMessage = null;\n\n const StorageConstructor = config.storage || Storage;\n this.stateQuota = Math.min(\n config.stateQuota ||\n DEFAULT_STATE_QUOTA,\n StorageConstructor.QUOTA || Infinity\n );\n\n this._stateStorage = new StorageConstructor({\n cookieName: 'ring-state'\n });\n this._tokenStorage = new StorageConstructor({\n cookieName: 'ring-token'\n });\n this._messagesStorage = new StorageConstructor({\n cookieName: 'ring-message'\n });\n this._currentUserStorage = new StorageConstructor({\n cookieName: 'ring-user'\n });\n }\n\n /**\n * Add token change listener\n * @param {function(string)} fn Token change listener\n * @return {function()} remove listener function\n */\n onTokenChange(fn) {\n return this._tokenStorage.on(this.tokenKey, fn);\n }\n\n /**\n * Add state change listener\n * @param {string} stateKey State key\n * @param {function(string)} fn State change listener\n * @return {function()} remove listener function\n */\n onStateChange(stateKey, fn) {\n return this._stateStorage.on(this.stateKeyPrefix + stateKey, fn);\n }\n\n /**\n * Add state change listener\n * @param {string} key State key\n * @param {function(string)} fn State change listener\n * @return {function()} remove listener function\n */\n onMessage(key, fn) {\n return this._messagesStorage.on(this.messagePrefix + key, message => {\n //IE11 triggers storage events on same window where localStorage was updated\n if (isIE11 && message === this._lastMessage) {\n return null;\n }\n return fn(message);\n });\n }\n\n sendMessage(key, message = null) {\n this._lastMessage = message;\n this._messagesStorage.set(this.messagePrefix + key, message);\n }\n\n /**\n * Save authentication request state.\n *\n * @param {string} id Unique state identifier\n * @param {StoredState} state State to store\n * @param {boolean=} dontCleanAndRetryOnFail If falsy then remove all stored states and try again to save state\n */\n async saveState(id, state, dontCleanAndRetryOnFail) {\n state.created = Date.now();\n\n try {\n await this._stateStorage.set(this.stateKeyPrefix + id, state);\n } catch (e) {\n if (!dontCleanAndRetryOnFail) {\n await this.cleanStates();\n return this.saveState(id, state, true);\n } else {\n throw e;\n }\n }\n return undefined;\n }\n\n /**\n * Remove all stored states\n *\n * @return {Promise} promise that is resolved when OLD states [and some selected] are removed\n */\n async cleanStates(removeStateId) {\n const now = Date.now();\n\n const removalResult = await this._stateStorage.each((key, state) => {\n // Remove requested state\n if (key === this.stateKeyPrefix + removeStateId) {\n return this._stateStorage.remove(key);\n }\n\n if (key.indexOf(this.stateKeyPrefix) === 0) {\n // Clean old states\n if (state.created + this.stateTTL < now) {\n return this._stateStorage.remove(key);\n }\n\n // Data to clean up due quota\n return {\n key,\n created: state.created,\n size: JSON.stringify(state).length\n };\n }\n\n return undefined;\n });\n const currentStates = removalResult.filter(state => state);\n\n let stateStorageSize = currentStates.\n reduce((overallSize, state) => state.size + overallSize, 0);\n\n if (stateStorageSize > this.stateQuota) {\n currentStates.sort((a, b) => a.created > b.created);\n\n const removalPromises = currentStates.filter(state => {\n if (stateStorageSize > this.stateQuota) {\n stateStorageSize -= state.size;\n return true;\n }\n\n return false;\n }).map(state => this._stateStorage.remove(state.key));\n\n return removalPromises.length && Promise.all(removalPromises);\n }\n\n return undefined;\n }\n\n /**\n * Get state by id and remove stored states from the storage.\n *\n * @param {string} id unique state identifier\n * @return {Promise.}\n */\n async getState(id) {\n try {\n const result = await this._stateStorage.get(this.stateKeyPrefix + id);\n await this.cleanStates(id);\n return result;\n } catch (e) {\n await this.cleanStates(id);\n throw e;\n }\n }\n\n /**\n * @param {StoredToken} token\n * @return {Promise} promise that is resolved when the token is saved\n */\n saveToken(token) {\n return this._tokenStorage.set(this.tokenKey, token);\n }\n\n /**\n * @return {Promise.} promise that is resolved to the stored token\n */\n getToken() {\n return this._tokenStorage.get(this.tokenKey);\n }\n\n /**\n * Remove stored token if any.\n * @return {Promise} promise that is resolved when the token is wiped.\n */\n wipeToken() {\n return this._tokenStorage.remove(this.tokenKey);\n }\n\n /**\n * @param {function} loadUser user loader\n * @return {Promise.>} promise that is resolved to stored current user\n */\n async getCachedUser(loadUser) {\n const user = await this._currentUserStorage.get(this.userKey);\n const loadAndCache = () => loadUser().then(response => {\n this._currentUserStorage.set(this.userKey, response);\n return response;\n });\n\n if (user && user.id) {\n setTimeout(loadAndCache, UPDATE_USER_TIMEOUT);\n return user;\n } else {\n return loadAndCache();\n }\n }\n\n /**\n * Remove cached user if any\n */\n wipeCachedCurrentUser() {\n return this._currentUserStorage.remove(this.userKey);\n }\n\n /**\n * Wipes cache if user has changed\n */\n onUserChanged() {\n this.wipeCachedCurrentUser();\n }\n}\n\n","import uuid from 'simply-uuid';\n\nimport {encodeURL} from '../global/url';\n\nexport default class AuthRequestBuilder {\n /**\n * @param {{\n * authorization: string,\n * redirectUri: string?,\n * requestCredentials: string?,\n * clientId: string?,\n * scopes: string[]\n * }} config\n * @param {AuthStorage} storage\n */\n constructor(config, storage) {\n this.config = config;\n this.storage = storage;\n }\n\n /**\n * @return {string} random string used for state\n */\n static _uuid = uuid.generate;\n\n /**\n * Save state and build an auth server redirect URL.\n *\n * @param {object=} extraParams additional query parameters for auth request\n * @param {object=} extraState additional state parameters to save\n * @return {Promise.} promise that is resolved to authURL\n */\n async prepareAuthRequest(extraParams, extraState) {\n const stateId = AuthRequestBuilder._uuid();\n const scopes = this.config.scopes.map(scope => encodeURIComponent(scope));\n\n /* eslint-disable camelcase */\n const request = Object.assign({\n response_type: 'token',\n state: stateId,\n redirect_uri: this.config.redirectUri,\n request_credentials: this.config.requestCredentials,\n client_id: this.config.clientId,\n scope: scopes.join(' ')\n }, extraParams || {});\n /* eslint-enable camelcase */\n\n const authURL = encodeURL(this.config.authorization, request);\n\n const state = Object.assign({\n restoreLocation: window.location.href,\n scopes: this.config.scopes\n }, extraState || {});\n\n await this._saveState(stateId, state);\n return ({\n url: authURL,\n stateId\n });\n }\n\n /**\n * @param {string} id\n * @param {StoredState} storedState\n * @return {Promise}\n * @private\n */\n _saveState(id, storedState) {\n return this.storage.saveState(id, storedState);\n }\n}\n","import AuthResponseParser from './response-parser';\n\nexport const HUB_AUTH_PAGE_OPENED = 'HUB_AUTH_PAGE_OPENED';\n\nexport default class BackgroundFlow {\n constructor(requestBuilder, storage, timeout) {\n this._requestBuilder = requestBuilder;\n this._storage = storage;\n this._timeout = timeout;\n }\n\n /**\n * Creates a hidden iframe\n * @return {HTMLIFrameElement}\n * @private\n */\n _createHiddenFrame() {\n const iframe = document.createElement('iframe');\n\n iframe.style.border = iframe.style.width = iframe.style.height = '0px';\n iframe.style.visibility = 'hidden';\n iframe.style.position = 'fixed';\n iframe.style.left = '-10000px';\n window.document.body.appendChild(iframe);\n\n return iframe;\n }\n\n /**\n * Redirects the given iframe to the given URL\n * @param {HTMLIFrameElement} iframe\n * @param {string} url\n * @private\n */\n _redirectFrame(iframe, url) {\n iframe.src = `${url}&rnd=${Math.random()}`;\n }\n\n /**\n * Refreshes the access token in an iframe.\n *\n * @return {Promise.} promise that is resolved to access the token when it is loaded in a background iframe. The\n * promise is rejected if no token was received after {@link BackgroundToken.BACKGROUND_TIMEOUT} ms.\n */\n async _load() {\n const authRequest = await this._requestBuilder.\n // eslint-disable-next-line camelcase\n prepareAuthRequest({request_credentials: 'silent'}, {nonRedirect: true});\n\n return new Promise((resolve, reject) => {\n function onMessage(e) {\n if (e.data === HUB_AUTH_PAGE_OPENED) {\n reject(new Error('Failed to obtain/refresh token in background'));\n cleanUp();\n }\n }\n\n window.addEventListener('message', onMessage);\n\n const iframe = this._createHiddenFrame();\n\n let cleanRun;\n\n const timeout = setTimeout(() => {\n reject(new Error('Failed to refresh authorization'));\n cleanUp();\n }, this._timeout);\n\n const removeTokenListener = this._storage.onTokenChange(token => {\n if (token) {\n cleanUp();\n resolve(token.accessToken);\n }\n });\n\n const removeStateListener = this._storage.onStateChange(authRequest.stateId, state => {\n if (state && state.error) {\n cleanUp();\n reject(new AuthResponseParser.AuthError(state));\n }\n });\n\n function cleanUp() {\n if (cleanRun) {\n return;\n }\n cleanRun = true;\n clearTimeout(timeout);\n removeStateListener();\n removeTokenListener();\n window.removeEventListener('message', onMessage);\n window.document.body.removeChild(iframe);\n }\n\n this._redirectFrame(iframe, authRequest.url);\n });\n }\n\n authorize() {\n if (this._promise) {\n return this._promise;\n }\n\n const resetPromise = () => {\n this._promise = null;\n };\n\n this._promise = this._load();\n\n this._promise.then(resetPromise, resetPromise);\n\n return this._promise;\n }\n}\n","import ExtendableError from 'es6-error';\n\nimport {CODE} from '../http/http';\n\nexport default class TokenValidator {\n constructor(config, getUser, storage) {\n this._getUser = getUser;\n this._config = config;\n this._storage = storage;\n }\n\n /**\n * Returns epoch - seconds since 1970.\n * Used for calculation of expire times.\n * @return {number} epoch, seconds since 1970\n * @private\n */\n static _epoch() {\n const milliseconds = 1000.0;\n return Math.round(Date.now() / milliseconds);\n }\n\n /**\n * @const {number}\n */\n // eslint-disable-next-line no-magic-numbers\n static DEFAULT_REFRESH_BEFORE = 10 * 60; // 20 min in s\n\n /**\n * Error class for auth token validation\n *\n * @param {string} message Error message\n * @param {Error=} cause Error that caused this error\n */\n static TokenValidationError = class TokenValidationError extends ExtendableError {\n constructor(message, cause) {\n super(message);\n this.cause = cause;\n this.authRedirect = true;\n }\n };\n\n /**\n * Check token validity against all conditions.\n * @returns {Promise.}\n */\n validateTokenLocally() {\n return this._getValidatedToken([\n TokenValidator._validateExistence,\n TokenValidator._validateExpiration,\n this._validateScopes.bind(this)\n ]);\n }\n\n /**\n * Check token validity against all conditions.\n * @returns {Promise.}\n */\n validateToken() {\n return this._getValidatedToken([\n TokenValidator._validateExistence,\n TokenValidator._validateExpiration,\n this._validateScopes.bind(this),\n this._validateAgainstUser.bind(this)\n ]);\n }\n\n\n /**\n * Check if there is a token\n * @param {StoredToken} storedToken\n * @return {Promise.}\n * @private\n */\n static async _validateExistence(storedToken) {\n if (!storedToken || !storedToken.accessToken) {\n throw new TokenValidator.TokenValidationError('Token not found');\n }\n }\n\n /**\n * Check expiration\n * @param {StoredToken} storedToken\n * @return {Promise.}\n * @private\n */\n static async _validateExpiration({expires, lifeTime}) {\n const REFRESH_BEFORE_RATIO = 6;\n const refreshBefore = lifeTime\n ? Math.ceil(lifeTime / REFRESH_BEFORE_RATIO)\n : TokenValidator.DEFAULT_REFRESH_BEFORE;\n\n if (expires && expires < (TokenValidator._epoch() + refreshBefore)) {\n throw new TokenValidator.TokenValidationError('Token expired');\n }\n }\n\n /**\n * Check scopes\n * @param {StoredToken} storedToken\n * @return {Promise.}\n * @private\n */\n async _validateScopes(storedToken) {\n const {scope, optionalScopes} = this._config;\n const requiredScopes = optionalScopes\n ? scope.filter(scopeId => !optionalScopes.includes(scopeId))\n : scope;\n\n const hasAllScopes = requiredScopes.every(scopeId => storedToken.scopes.includes(scopeId));\n if (!hasAllScopes) {\n throw new TokenValidator.TokenValidationError('Token doesn\\'t match required scopes');\n }\n }\n\n /**\n * Check by error code if token should be refreshed\n * @param {string} error\n * @return {boolean}\n */\n static shouldRefreshToken(error) {\n return error === 'invalid_grant' ||\n error === 'invalid_request' ||\n error === 'invalid_token';\n }\n\n /**\n * Check scopes\n * @param {StoredToken} storedToken\n * @return {Promise.}\n * @private\n */\n async _validateAgainstUser(storedToken) {\n try {\n return await this._getUser(storedToken.accessToken);\n } catch (errorResponse) {\n\n let response = {};\n try {\n response = await errorResponse.response.json();\n } catch (e) {\n // Skip JSON parsing errors\n }\n\n if (\n errorResponse.status === CODE.UNAUTHORIZED ||\n TokenValidator.shouldRefreshToken(response.error)\n ) {\n // Token expired\n throw new TokenValidator.TokenValidationError(response.error || errorResponse.message);\n }\n\n // Request unexpectedly failed\n throw errorResponse;\n }\n }\n\n /**\n * Token Validator function\n * @typedef {(function(StoredToken): Promise)} TokenValidator\n */\n\n /**\n * Gets stored token and applies provided validators\n * @param {TokenValidator[]} validators An array of validation\n * functions to check the stored token against.\n * @return {Promise.} promise that is resolved to access token if the stored token is valid. If it is\n * invalid then the promise is rejected. If invalid token should be re-requested then rejection object will\n * have {authRedirect: true}.\n * @private\n */\n async _getValidatedToken(validators) {\n const storedToken = await this._storage.getToken();\n\n for (let i = 0; i < validators.length; i++) {\n await validators[i](storedToken);\n }\n\n return storedToken.accessToken;\n }\n}\n","import {fixUrl, getAbsoluteBaseURL} from '../global/url';\nimport Listeners from '../global/listeners';\nimport HTTP from '../http/http';\nimport promiseWithTimeout from '../global/promise-with-timeout';\n\nimport AuthStorage from './storage';\nimport AuthResponseParser from './response-parser';\nimport AuthRequestBuilder from './request-builder';\nimport BackgroundFlow from './background-flow';\nimport TokenValidator from './token-validator';\n\n/* eslint-disable no-magic-numbers */\nexport const DEFAULT_EXPIRES_TIMEOUT = 40 * 60;\nexport const DEFAULT_BACKGROUND_TIMEOUT = 10 * 1000;\nconst DEFAULT_BACKEND_CHECK_TIMEOUT = 10 * 1000;\nconst BACKGROUND_REDIRECT_TIMEOUT = 20 * 1000;\n/* eslint-enable no-magic-numbers */\n\nexport const USER_CHANGED_EVENT = 'userChange';\nexport const DOMAIN_USER_CHANGED_EVENT = 'domainUser';\nexport const LOGOUT_EVENT = 'logout';\nexport const LOGOUT_POSTPONED_EVENT = 'logoutPostponed';\nexport const USER_CHANGE_POSTPONED_EVENT = 'changePostponed';\n\nfunction noop() {}\n\nconst DEFAULT_CONFIG = {\n cacheCurrentUser: false,\n reloadOnUserChange: true,\n embeddedLogin: false,\n EmbeddedLoginFlow: null,\n clientId: '0-0-0-0-0',\n redirectUri: getAbsoluteBaseURL(),\n redirect: false,\n requestCredentials: 'default',\n backgroundRefreshTimeout: null,\n scope: [],\n userFields: ['guest', 'id', 'name', 'login', 'profile/avatar/url'],\n cleanHash: true,\n onLogout: noop,\n onPostponeChangedUser: () => {},\n onPostponeLogout: () => {},\n enableBackendStatusCheck: true,\n backendCheckTimeout: DEFAULT_BACKEND_CHECK_TIMEOUT,\n checkBackendIsUp: () => Promise.resolve(null),\n onBackendDown: () => {},\n\n defaultExpiresIn: DEFAULT_EXPIRES_TIMEOUT,\n translations: {\n login: 'Log in',\n loginTo: 'Log in to %serviceName%',\n cancel: 'Cancel',\n postpone: 'Postpone',\n youHaveLoggedInAs: 'You have logged in as another user: %userName%',\n applyChange: 'Apply change',\n backendIsNotAvailable: 'Connection lost',\n checkAgain: 'try again',\n nothingHappensLink: 'Click here if nothing happens',\n errorMessage: 'There may be a problem with your network connection. Make sure that you are online and'\n }\n};\n\nexport default class Auth {\n static DEFAULT_CONFIG = DEFAULT_CONFIG;\n static API_PATH = 'api/rest/';\n static API_AUTH_PATH = 'oauth2/auth';\n static API_PROFILE_PATH = 'users/me';\n static CLOSE_BACKEND_DOWN_MESSAGE = 'backend-check-succeeded';\n static CLOSE_WINDOW_MESSAGE = 'close-login-window';\n static shouldRefreshToken = TokenValidator.shouldRefreshToken;\n static storageIsUnavailable = !navigator.cookieEnabled;\n\n config = {};\n listeners = new Listeners();\n http = null;\n _service = {};\n _storage = null;\n _responseParser = new AuthResponseParser();\n _requestBuilder = null;\n _backgroundFlow = null;\n _embeddedFlow = null;\n _tokenValidator = null;\n _postponed = false;\n _backendCheckPromise = null;\n _authDialogService = undefined;\n\n constructor(config) {\n if (!config) {\n throw new Error('Config is required');\n }\n\n if (config.serverUri == null) {\n throw new Error('\\\"serverUri\\\" property is required');\n }\n\n const unsupportedParams = ['redirect_uri', 'request_credentials', 'client_id'].filter(param => config.hasOwnProperty(param));\n if (unsupportedParams.length !== 0) {\n throw new Error(`The following parameters are no longer supported: ${unsupportedParams.join(', ')}. Please change them from snake_case to camelCase.`);\n }\n\n config.userFields = config.userFields || [];\n\n this.config = {...Auth.DEFAULT_CONFIG, ...config};\n\n const {clientId, redirect, redirectUri, requestCredentials, scope} = this.config;\n const serverUriLength = this.config.serverUri.length;\n\n if (serverUriLength > 0 && this.config.serverUri.charAt(serverUriLength - 1) !== '/') {\n this.config.serverUri += '/';\n }\n\n this.config.userParams = {\n query: {\n fields: [...new Set(Auth.DEFAULT_CONFIG.userFields.concat(config.userFields))].join()\n }\n };\n\n if (!scope.includes(Auth.DEFAULT_CONFIG.clientId)) {\n scope.push(Auth.DEFAULT_CONFIG.clientId);\n }\n\n this._storage = new AuthStorage({\n messagePrefix: `${clientId}-message-`,\n stateKeyPrefix: `${clientId}-states-`,\n tokenKey: `${clientId}-token`,\n userKey: `${clientId}-user-`\n });\n\n this._domainStorage = new AuthStorage({messagePrefix: 'domain-message-'});\n\n this._requestBuilder = new AuthRequestBuilder({\n authorization: this.config.serverUri + Auth.API_PATH + Auth.API_AUTH_PATH,\n clientId,\n redirect,\n redirectUri,\n requestCredentials,\n scopes: scope\n }, this._storage);\n\n let {backgroundRefreshTimeout} = this.config;\n if (!backgroundRefreshTimeout) {\n backgroundRefreshTimeout = this.config.embeddedLogin\n ? DEFAULT_BACKGROUND_TIMEOUT\n : BACKGROUND_REDIRECT_TIMEOUT;\n }\n\n this._backgroundFlow = new BackgroundFlow(\n this._requestBuilder, this._storage, backgroundRefreshTimeout\n );\n if (this.config.EmbeddedLoginFlow) {\n this._embeddedFlow = new this.config.EmbeddedLoginFlow(\n this._requestBuilder,\n this._storage,\n this.config.translations\n );\n }\n\n const API_BASE = this.config.serverUri + Auth.API_PATH;\n const fetchConfig = config.fetchCredentials\n ? {credentials: config.fetchCredentials}\n : undefined;\n this.http = new HTTP(this, API_BASE, fetchConfig);\n\n const getUser = async token => {\n const user = await this.getUser(token);\n this.user = user;\n return user;\n };\n\n this._tokenValidator = new TokenValidator(this.config, getUser, this._storage);\n\n if (this.config.onLogout) {\n this.addListener(LOGOUT_EVENT, this.config.onLogout);\n }\n\n if (this.config.reloadOnUserChange === true) {\n this.addListener(USER_CHANGED_EVENT, () => this._reloadCurrentPage());\n }\n\n this.addListener(LOGOUT_POSTPONED_EVENT, () => this._setPostponed(true));\n this.addListener(USER_CHANGE_POSTPONED_EVENT, () => this._setPostponed(true));\n this.addListener(USER_CHANGED_EVENT, () => this._setPostponed(false));\n this.addListener(USER_CHANGED_EVENT, user => user && this._updateDomainUser(user.id));\n if (this.config.cacheCurrentUser) {\n this.addListener(LOGOUT_EVENT, () => this._storage.wipeCachedCurrentUser());\n this.addListener(USER_CHANGED_EVENT, () => this._storage.onUserChanged());\n }\n\n this._createInitDeferred();\n\n this.setUpPreconnect(config.serverUri);\n }\n\n _setPostponed(postponed = false) {\n this._postponed = postponed;\n }\n\n _updateDomainUser(userID) {\n this._domainStorage.sendMessage(DOMAIN_USER_CHANGED_EVENT, {\n userID,\n serviceID: this.config.clientId\n });\n }\n\n addListener(event, handler) {\n this.listeners.add(event, handler);\n }\n\n removeListener(event, handler) {\n this.listeners.remove(event, handler);\n }\n\n setAuthDialogService(authDialogService) {\n this._authDialogService = authDialogService;\n }\n\n setCurrentService(service) {\n this._service = service;\n }\n\n _createInitDeferred() {\n this._initDeferred = {};\n this._initDeferred.promise = new Promise((resolve, reject) => {\n this._initDeferred.resolve = resolve;\n this._initDeferred.reject = reject;\n });\n }\n\n /**\n * @return {Promise.} absolute URL promise that is resolved to a URL\n * that should be restored after returning back from auth server.\n */\n async init() {\n this._storage.onTokenChange(token => {\n const isGuest = this.user ? this.user.guest : false;\n\n if (isGuest && !token) {\n return;\n }\n\n if (!token) {\n this.logout();\n } else {\n this._detectUserChange(token.accessToken);\n }\n });\n\n this._domainStorage.onMessage(DOMAIN_USER_CHANGED_EVENT, ({userID, serviceID}) => {\n if (serviceID === this.config.clientId) {\n return;\n }\n if (this.user && userID === this.user.id) {\n return;\n }\n this.forceTokenUpdate();\n });\n\n let state;\n\n try {\n // Look for token or error in hash\n state = await this._checkForAuthResponse();\n } catch (error) {\n return this.handleInitError(error);\n }\n\n // Return endless promise in the background to avoid service start\n if (state && state.nonRedirect) {\n return new Promise(noop);\n }\n\n try {\n // Check if there is a valid token\n await this._tokenValidator.validateToken();\n\n\n // Checking if there is a message left by another app on this domain\n const message = await this._domainStorage._messagesStorage.get(`domain-message-${DOMAIN_USER_CHANGED_EVENT}`);\n if (message) {\n const {userID, serviceID} = message;\n if (serviceID !== this.config.clientId && (!userID || this.user.id !== userID)) {\n this.forceTokenUpdate();\n }\n }\n\n // Access token appears to be valid.\n // We may resolve restoreLocation URL now\n if (!state) {\n // Check if we have requested to restore state anyway\n state = await this._checkForStateRestoration();\n }\n this._initDeferred.resolve(state && state.restoreLocation);\n return state?.restoreLocation;\n } catch (error) {\n if (Auth.storageIsUnavailable) {\n this._initDeferred.resolve(); // No way to handle if cookies are disabled\n await this.requestUser(); // Someone may expect user to be loaded as a part of token validation\n return null;\n }\n return this.handleInitValidationError(error);\n }\n }\n\n async sendRedirect(error) {\n const authRequest = await this._requestBuilder.prepareAuthRequest();\n this._redirectCurrentPage(authRequest.url);\n\n throw error;\n }\n\n async handleInitError(error) {\n if (error.stateId) {\n try {\n const state = await this._storage.getState(error.stateId);\n\n if (state && state.nonRedirect) {\n state.error = error;\n this._storage.saveState(error.stateId, state);\n\n // Return endless promise in the background to avoid service start\n return new Promise(noop);\n }\n } catch (e) {\n // Throw the orginal error instead below\n }\n }\n\n throw error;\n }\n\n async handleInitValidationError(error) {\n // Redirect flow\n if (error.authRedirect && this.config.redirect) {\n return this.sendRedirect(error);\n }\n\n // Background flow\n if (error.authRedirect && !this.config.redirect) {\n try {\n await this._backgroundFlow.authorize();\n await this._tokenValidator.validateToken();\n this._initDeferred.resolve();\n return undefined;\n } catch (validationError) {\n // Fallback to redirect flow\n return this.sendRedirect(validationError);\n }\n }\n\n this._initDeferred.reject(error);\n throw error;\n }\n\n /**\n * Get token from local storage or request it if necessary.\n * Can redirect to login page.\n * @return {Promise.}\n */\n async requestToken() {\n if (this._postponed) {\n throw new Error('You should log in to be able to make requests');\n }\n\n try {\n await this._initDeferred.promise;\n\n if (Auth.storageIsUnavailable) {\n return null; // Forever guest if storage is unavailable\n }\n return await this._tokenValidator.validateTokenLocally();\n } catch (e) {\n return this.forceTokenUpdate();\n }\n }\n\n /**\n * Get new token in the background or redirect to the login page.\n * @return {Promise.}\n */\n async forceTokenUpdate() {\n try {\n if (!this._backendCheckPromise) {\n this._backendCheckPromise = this._checkBackendsStatusesIfEnabled();\n }\n await this._backendCheckPromise;\n } catch (e) {\n throw new Error('Cannot refresh token: backend is not available. Postponed by user.');\n } finally {\n this._backendCheckPromise = null;\n }\n\n try {\n return await this._backgroundFlow.authorize();\n } catch (error) {\n\n if (this._canShowDialogs()) {\n return this._showAuthDialog({nonInteractive: true, error});\n } else {\n const authRequest = await this._requestBuilder.prepareAuthRequest();\n this._redirectCurrentPage(authRequest.url);\n }\n\n throw new TokenValidator.TokenValidationError(error.message);\n }\n }\n\n async loadCurrentService() {\n if (this._service.serviceName) {\n return;\n }\n try {\n const {serviceName, iconUrl: serviceImage} = await this.http.get(`oauth2/interactive/login/settings?client_id=${this.config.clientId}`) || {};\n this.setCurrentService({serviceImage, serviceName});\n } catch (e) {\n // noop\n }\n }\n\n getAPIPath() {\n return this.config.serverUri + Auth.API_PATH;\n }\n\n /**\n * @return {Promise.}\n */\n getUser(accessToken) {\n if (this.config.cacheCurrentUser) {\n return this._storage.getCachedUser(\n () => this.http.authorizedFetch(Auth.API_PROFILE_PATH, accessToken, this.config.userParams)\n );\n } else {\n return this.http.authorizedFetch(Auth.API_PROFILE_PATH, accessToken, this.config.userParams);\n }\n }\n\n /**\n * @return {Promise.}\n */\n async requestUser() {\n if (this.user) {\n return this.user;\n }\n\n const accessToken = await this.requestToken();\n\n // If user was fetched during token request\n if (this.user) {\n return this.user;\n }\n\n const user = await this.getUser(accessToken);\n this.user = user;\n\n return user;\n }\n\n async updateUser() {\n this._setPostponed(false);\n const accessToken = await this.requestToken();\n this._storage.wipeCachedCurrentUser();\n const user = await this.getUser(accessToken);\n this.user = user;\n this.listeners.trigger(USER_CHANGED_EVENT, user);\n }\n\n async _detectUserChange(accessToken) {\n const windowWasOpen = this._isLoginWindowOpen;\n\n try {\n const user = await this.getUser(accessToken);\n const onApply = () => {\n this.user = user;\n this.listeners.trigger(USER_CHANGED_EVENT, user);\n };\n\n if (user && this.user && this.user.id !== user.id) {\n if (!this._canShowDialogs() || this.user.guest || windowWasOpen) {\n onApply();\n return;\n }\n if (user.guest) {\n this._showAuthDialog({nonInteractive: true});\n return;\n }\n\n await this._showUserChangedDialog({\n newUser: user,\n onApply,\n onPostpone: () => {\n this.listeners.trigger(USER_CHANGE_POSTPONED_EVENT);\n this.config.onPostponeChangedUser(this.user, user);\n }\n });\n\n }\n } catch (e) {\n // noop\n }\n }\n\n _beforeLogout(params) {\n if (this._canShowDialogs()) {\n this._showAuthDialog(params);\n return;\n }\n\n this.logout();\n }\n\n async _showAuthDialog({nonInteractive, error, canCancel} = {}) {\n const {embeddedLogin, onPostponeLogout, translations} = this.config;\n const cancelable = this.user.guest || canCancel;\n\n this._createInitDeferred();\n\n const closeDialog = () => {\n /* eslint-disable no-use-before-define */\n stopTokenListening();\n stopMessageListening();\n hide();\n /* eslint-enable no-use-before-define */\n };\n\n const onConfirm = () => {\n if (embeddedLogin !== true) {\n closeDialog();\n this.logout();\n return;\n }\n this._runEmbeddedLogin();\n };\n\n const onCancel = () => {\n this._embeddedFlow.stop();\n this._storage.sendMessage(Auth.CLOSE_WINDOW_MESSAGE, Date.now());\n closeDialog();\n if (!cancelable) {\n this._initDeferred.resolve();\n this.listeners.trigger(LOGOUT_POSTPONED_EVENT);\n onPostponeLogout();\n return;\n }\n\n if (this.user.guest && nonInteractive) {\n this.forceTokenUpdate();\n } else {\n this._initDeferred.resolve();\n }\n };\n\n const hide = this._authDialogService({\n ...this._service,\n loginCaption: translations.login,\n loginToCaption: translations.loginTo,\n confirmLabel: translations.login,\n cancelLabel: cancelable ? translations.cancel : translations.postpone,\n errorMessage: error && error.toString ? error.toString() : null,\n onConfirm,\n onCancel\n });\n\n const stopTokenListening = this._storage.onTokenChange(token => {\n if (token) {\n closeDialog();\n this._initDeferred.resolve();\n }\n });\n\n const stopMessageListening = this._storage.onMessage(\n Auth.CLOSE_WINDOW_MESSAGE,\n () => this._embeddedFlow.stop()\n );\n }\n\n async _showUserChangedDialog({newUser, onApply, onPostpone} = {}) {\n const {translations} = this.config;\n\n this._createInitDeferred();\n\n const done = () => {\n this._initDeferred.resolve();\n // eslint-disable-next-line no-use-before-define\n hide();\n };\n\n const hide = this._authDialogService({\n ...this._service,\n title: translations.youHaveLoggedInAs.replace('%userName%', newUser.name),\n loginCaption: translations.login,\n loginToCaption: translations.loginTo,\n confirmLabel: translations.applyChange,\n cancelLabel: translations.postpone,\n onConfirm: () => {\n done();\n onApply();\n },\n onCancel: () => {\n done();\n onPostpone();\n }\n });\n }\n\n async _showBackendDownDialog(backendError) {\n const {onBackendDown, translations} = this.config;\n const REPEAT_TIMEOUT = 5000;\n let timerId = null;\n\n return new Promise((resolve, reject) => {\n const done = () => {\n /* eslint-disable no-use-before-define */\n hide();\n window.removeEventListener('online', onCheckAgain);\n stopListeningCloseMessage();\n /* eslint-enable no-use-before-define */\n this._storage.sendMessage(Auth.CLOSE_BACKEND_DOWN_MESSAGE, Date.now());\n this._awaitingForBackendPromise = null;\n clearTimeout(timerId);\n };\n\n const stopListeningCloseMessage = this._storage.onMessage(\n Auth.CLOSE_BACKEND_DOWN_MESSAGE,\n () => {\n stopListeningCloseMessage();\n done();\n resolve();\n }\n );\n\n const onCheckAgain = async () => {\n await this._checkBackendsAreUp();\n done();\n resolve();\n };\n\n const onPostpone = () => {\n done();\n reject(new Error('Auth(@jetbrains/ring-ui): postponed by user'));\n };\n\n const hide = onBackendDown({onCheckAgain, onPostpone, backendError, translations});\n\n window.addEventListener('online', onCheckAgain);\n\n function networkWatchdog() {\n if (navigator && navigator.onLine) {\n onCheckAgain();\n }\n timerId = setTimeout(networkWatchdog, REPEAT_TIMEOUT);\n }\n\n timerId = setTimeout(networkWatchdog, REPEAT_TIMEOUT);\n });\n }\n\n /**\n * Wipe accessToken and redirect to auth page with required authorization\n */\n async logout(extraParams) {\n const requestParams = {\n // eslint-disable-next-line camelcase\n request_credentials: 'required',\n ...extraParams\n };\n\n await this._checkBackendsStatusesIfEnabled();\n await this.listeners.trigger(LOGOUT_EVENT);\n this._updateDomainUser(null);\n await this._storage.wipeToken();\n\n const authRequest = await this._requestBuilder.prepareAuthRequest(requestParams);\n this._redirectCurrentPage(authRequest.url);\n }\n\n async _runEmbeddedLogin() {\n this._storage.sendMessage(Auth.CLOSE_WINDOW_MESSAGE, Date.now());\n try {\n this._isLoginWindowOpen = true;\n return await this._embeddedFlow.authorize();\n } catch (e) {\n throw e;\n } finally {\n this._isLoginWindowOpen = false;\n }\n }\n\n /**\n * Wipe accessToken and redirect to auth page to obtain authorization data\n * if user is logged in or log her in otherwise\n */\n async login() {\n if (this.config.embeddedLogin) {\n await this._runEmbeddedLogin();\n return;\n }\n\n await this._checkBackendsStatusesIfEnabled();\n try {\n const accessToken = await this._backgroundFlow.authorize();\n const user = await this.getUser(accessToken);\n\n if (user.guest) {\n this._beforeLogout();\n } else {\n this.user = user;\n this.listeners.trigger(USER_CHANGED_EVENT, user);\n }\n } catch (e) {\n this._beforeLogout();\n }\n }\n\n async switchUser() {\n if (this.config.embeddedLogin) {\n await this._runEmbeddedLogin();\n }\n\n throw new Error('Auth: switchUser only supported for \"embeddedLogin\" mode');\n }\n\n /**\n * Check if the hash contains an access token.\n * If it does, extract the state, compare with\n * config, and store the auth response for later use.\n *\n * @return {Promise} promise that is resolved to restoreLocation URL, or rejected\n * @private\n */\n async _checkForAuthResponse() {\n // getAuthResponseURL may throw an exception\n const authResponse = this._responseParser.getAuthResponseFromURL();\n const {scope: defaultScope, defaultExpiresIn, cleanHash} = this.config;\n\n if (authResponse && cleanHash) {\n this.setHash('');\n }\n\n if (!authResponse) {\n return undefined;\n }\n\n const {state: stateId, scope, expiresIn, accessToken} = authResponse;\n const newState = await (stateId && this._storage.getState(stateId)) || {};\n\n const scopes = scope ? scope.split(' ') : newState.scopes || defaultScope || [];\n const effectiveExpiresIn = expiresIn ? parseInt(expiresIn, 10) : defaultExpiresIn;\n const expires = TokenValidator._epoch() + effectiveExpiresIn;\n\n await this._storage.saveToken({accessToken, scopes, expires, lifeTime: effectiveExpiresIn});\n\n return newState;\n }\n\n async _checkForStateRestoration() {\n const authResponse = this._responseParser.getAuthResponseFromURL();\n if (authResponse && this.config.cleanHash) {\n this.setHash('');\n }\n const stateId = authResponse?.restoreAuthState;\n return await (stateId && this._storage.getState(stateId)) || {};\n }\n\n _checkBackendsAreUp() {\n const {backendCheckTimeout} = this.config;\n return Promise.all([\n promiseWithTimeout(\n this.http.fetch('settings/public?fields=id'),\n backendCheckTimeout,\n {error: new Error('The authorization server is taking too long to respond. Please try again later.')}\n ),\n this.config.checkBackendIsUp()\n ]).catch(err => {\n if (err instanceof TypeError) {\n throw new TypeError('Could not connect to the server due to network error. Please check your connection and try again.');\n }\n throw err;\n });\n }\n\n async _checkBackendsStatusesIfEnabled() {\n if (!this.config.enableBackendStatusCheck) {\n return;\n }\n try {\n await this._checkBackendsAreUp();\n } catch (backendDownErr) {\n await this._showBackendDownDialog(backendDownErr);\n }\n }\n\n /**\n * Adds preconnect tag to help browser to establish connection to URL.\n * See https://w3c.github.io/resource-hints/\n * @param url Url to preconnect to.\n */\n async setUpPreconnect(url) {\n const linkNode = document.createElement('link');\n linkNode.rel = 'preconnect';\n linkNode.href = url;\n linkNode.pr = '1.0';\n document.head.appendChild(linkNode);\n }\n\n /**\n * Redirects current page to the given URL\n * @param {string} url\n * @private\n */\n _redirectCurrentPage(url) {\n\n window.location = fixUrl(url);\n }\n\n /**\n * Reloads current page\n */\n _reloadCurrentPage() {\n this._redirectCurrentPage(window.location.href);\n }\n\n _canShowDialogs() {\n return this.config.embeddedLogin && this._authDialogService;\n }\n\n /**\n * Sets the location hash\n * @param {string} hash\n */\n setHash(hash) {\n if (history.replaceState) {\n // NB! History.replaceState is used here, because Firefox saves\n // a record in history.\n // NB! URL to redirect is formed manually because baseURI could be messed up,\n // in which case it's not obvious where redirect will lead.\n const cleanedUrl = [\n window.location.pathname,\n window.location.search\n ].join('');\n\n const hashIfExist = hash ? `#${hash}` : '';\n\n history.replaceState(undefined, undefined, `${cleanedUrl}${hashIfExist}`);\n } else {\n window.location.hash = hash;\n }\n }\n}\n","// Useful for using fetch with timeout\n// https://github.com/github/fetch/issues/175#issuecomment-284787564\n\nexport default function promiseWithTimeout(promise, timeout, {error}) {\n return new Promise((resolve, reject) => {\n setTimeout(() => reject(error || new Error('Timeout')), timeout);\n\n promise.then(resolve, reject);\n });\n}\n","import WindowFlow from './window-flow';\nimport defaultOnBackendDown from './down-notification';\nimport Auth from './auth__core';\n\n/**\n * @name Auth\n *\n * @prop {object} config\n * @prop {string} config.serverUri\n * @prop {string} config.redirectUri\n * @prop {string} config.clientId\n * @prop {boolean=false} config.redirect — use redirects instead of loading the token in the background.\n * @prop {string[]} config.scope\n * @prop {string[]} config.optionalScopes\n * @prop {boolean} config.cleanHash - whether or not location.hash will be cleaned after authorization is completed.\n * Should be set to false in angular > 1.2.26 apps to prevent infinite redirect in Firefox\n * @prop {User?} user\n * @prop {string[]} config.userFields List of user data fields to be returned by auth.requestUser (default list is used in Header.HeaderHelper)\n * @prop {string[]} config.fetchCredentials\n *\n * @param {{\n * serverUri: string,\n * redirectUri: string?,\n * requestCredentials: string?,\n * clientId: string?,\n * scope: string[]?,\n * optionalScopes: string[]?,\n * cleanHash: boolean?,\n * fetchCredentials: string?,\n * userFields: string[]?\n * }} config\n *\n */\n\n/**\n * Extend Auth config with non-required and not pure-JS stuff\n */\nAuth.DEFAULT_CONFIG = {\n ...Auth.DEFAULT_CONFIG,\n EmbeddedLoginFlow: WindowFlow,\n onBackendDown: defaultOnBackendDown\n};\n\nexport * from './auth__core';\nexport default Auth;\n","export default function linearFunction(x0, y0, a) {\n return {\n y(x) {\n return +y0 + (x - x0) * a;\n },\n\n x(y) {\n return +x0 + (y - y0) / a;\n }\n };\n}\n\nexport function interpolateLinear(x0, x1, phase) {\n return linearFunction(x0, x0, phase).y(x1);\n}\n\n","import React, {Component, createContext} from 'react';\n\nimport {interpolateLinear} from '../global/linear-function';\n\nconst TITLE_RESIZE_END = 20;\nconst TITLE_RESIZE_THRESHOLD = 36;\n\nexport const PhaseContext = createContext();\nexport const ScrollHandlerContext = createContext();\n\nexport default function adaptiveIslandHOC(ComposedComponent) {\n\n return class AdaptiveIsland extends Component {\n static propTypes = ComposedComponent.propTypes;\n\n state = {\n phase: 0\n };\n\n onContentScroll = ({scrollTop, scrollHeight, clientHeight}) => {\n if (scrollHeight - clientHeight >=\n interpolateLinear(TITLE_RESIZE_THRESHOLD, TITLE_RESIZE_END, this.state.phase)) {\n const phase = Math.min(1, scrollTop / TITLE_RESIZE_END);\n this.setState({phase});\n }\n };\n\n render() {\n return (\n \n \n \n \n \n );\n }\n };\n}\n","import React, {Component} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport {interpolateLinear} from '../global/linear-function';\n\nimport styles from './island.css';\nimport {PhaseContext} from './adaptive-island-hoc';\n\nconst Start = {\n FONT_SIZE: 24,\n LINE_HEIGHT: 28,\n PADDING: 16\n};\n\nconst End = {\n FONT_SIZE: 13,\n LINE_HEIGHT: 28,\n\n // Compensation\n X: 0.4,\n Y: 0.1,\n SPACING: 1.09\n};\n\nconst BORDER_APPEAR_PHASE = 0.5;\n\nclass Header extends Component {\n static propTypes = {\n children: PropTypes.node,\n className: PropTypes.string,\n border: PropTypes.bool,\n wrapWithTitle: PropTypes.bool,\n phase: PropTypes.number\n };\n\n static defaultProps = {\n wrapWithTitle: true\n };\n\n style(name) {\n return interpolateLinear(Start[name] || 0, End[name] || 0, this.props.phase);\n }\n\n render() {\n const {children, className, wrapWithTitle, border, phase, ...restProps} = this.props;\n const classes = classNames(styles.header, className, {\n [styles.withBottomBorder]: border || phase >= BORDER_APPEAR_PHASE\n });\n\n\n const headerStyle = phase != null\n ? {\n lineHeight: `${this.style('LINE_HEIGHT')}px`, // need to append px because number is a valid line-height value\n paddingTop: this.style('PADDING')\n }\n : null;\n\n const scaleFont = phase != null && this.style('FONT_SIZE') / Start.FONT_SIZE;\n\n const titleStyle = (phase != null && phase < 1)\n ? {\n fontSize: Start.FONT_SIZE,\n transform: `translate(${this.style('X')}px, ${this.style('Y')}px) scale(${scaleFont})`,\n letterSpacing: this.style('SPACING')\n }\n : null;\n\n return (\n \n {wrapWithTitle &&\n (\n \n {children}\n \n )}\n\n {!wrapWithTitle && children}\n\n \n );\n }\n}\n\nconst HeaderWrapper = props => (\n \n {phase => {\n const addProps = phase != null ? {phase} : {};\n return
;\n }}\n \n);\n\nexport default HeaderWrapper;\n","export default function scheduleRAF(trailingCall) {\n let scheduledCb;\n let RAF;\n let trailingCallScheduled = false;\n\n function doSchedule() {\n RAF = window.requestAnimationFrame(() => {\n scheduledCb();\n if (trailingCallScheduled) {\n trailingCallScheduled = false;\n doSchedule();\n } else {\n RAF = null;\n scheduledCb = null;\n }\n });\n }\n\n return function schedule(cb) {\n scheduledCb = cb;\n if (!RAF) {\n doSchedule();\n } else if (trailingCall) {\n trailingCallScheduled = true;\n }\n };\n}\n","import React, {Component} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport createResizeDetector from 'element-resize-detector';\n\nimport scheduleRAF from '../global/schedule-raf';\n\nimport styles from './island.css';\nimport {ScrollHandlerContext} from './adaptive-island-hoc';\n\nconst scheduleScrollAction = scheduleRAF();\nconst noop = () => {};\nconst END_DISTANCE = 16;\n\nclass Content extends Component {\n static propTypes = {\n children: PropTypes.node,\n className: PropTypes.string,\n scrollableWrapperClassName: PropTypes.string,\n fade: PropTypes.bool,\n bottomBorder: PropTypes.bool,\n onScroll: PropTypes.func,\n onScrollToBottom: PropTypes.func\n };\n\n static defaultProps = {\n fade: true,\n bottomBorder: false,\n onScroll: noop,\n onScrollToBottom: noop\n };\n\n state = {\n scrolledToTop: true,\n scrolledToBottom: false\n };\n\n componentWillUnmount() {\n this.scrollableNode = null;\n if (!this.wrapperNode) {\n return;\n }\n this.resizeDetector.removeAllListeners(this.wrapperNode);\n }\n\n resizeDetector = createResizeDetector({strategy: 'scroll'});\n\n setWrapper = node => {\n if (!node) {\n return;\n }\n this.wrapperNode = node;\n this.resizeDetector.listenTo(node, this.calculateScrollPosition);\n };\n\n calculateScrollPosition = () => scheduleScrollAction(() => {\n const {scrollableNode} = this;\n if (!scrollableNode) {\n return;\n }\n const {scrollTop, scrollHeight, offsetHeight} = scrollableNode;\n const scrolledToTop = scrollTop === 0;\n const scrolledToBottom = offsetHeight + scrollTop >= scrollHeight - END_DISTANCE;\n\n if (scrolledToBottom) {\n this.props.onScrollToBottom();\n }\n\n this.setState({scrolledToTop, scrolledToBottom});\n });\n\n onScroll = () => {\n this.props.onScroll(this.scrollableNode);\n this.calculateScrollPosition();\n };\n\n setScrollableNodeAndCalculatePosition = node => {\n if (!node) {\n return;\n }\n this.scrollableNode = node;\n this.calculateScrollPosition();\n };\n\n render() {\n const {\n children, className, bottomBorder, scrollableWrapperClassName,\n onScroll, onScrollToBottom, fade, ...restProps\n } = this.props;\n const {scrolledToTop, scrolledToBottom} = this.state;\n\n const classes = classNames(styles.content, className, {\n [styles.contentWithTopFade]: fade && !scrolledToTop,\n [styles.contentWithBottomFade]: fade && !scrolledToBottom,\n [styles.withTransparentBottomBorder]: bottomBorder,\n [styles.withBottomBorder]: bottomBorder && !scrolledToBottom\n });\n\n const scrollableWrapperClasses = classNames(\n styles.scrollableWrapper,\n scrollableWrapperClassName\n );\n\n return (\n \n \n {fade && (\n
\n {children}\n
\n )}\n\n {!fade && children}\n \n \n );\n }\n}\n\nconst ContentWrapper = props => (\n \n {onScroll => {\n const addProps = onScroll != null ? {onScroll, bottomBorder: true} : {};\n return ;\n }}\n \n);\n\nexport default ContentWrapper;\n","import React, {Component} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport dataTests from '../global/data-tests';\n\nimport adaptiveIslandHOC from './adaptive-island-hoc';\n\nimport styles from './island.css';\n\n/**\n * @name Island\n */\n\nexport default class Island extends Component {\n static propTypes = {\n children: PropTypes.node,\n className: PropTypes.string,\n narrow: PropTypes.bool,\n withoutPaddings: PropTypes.bool,\n 'data-test': PropTypes.string\n };\n\n render() {\n const {\n children,\n className,\n narrow,\n withoutPaddings,\n 'data-test': dataTest,\n ...restProps\n } = this.props;\n const classes = classNames(styles.island, className, {\n [styles.narrowIsland]: narrow,\n [styles.withoutPaddings]: withoutPaddings\n });\n\n return (\n \n {children}\n \n );\n }\n}\n\nexport const AdaptiveIsland = adaptiveIslandHOC(Island);\n\nexport {default as Header} from './header';\nexport {default as Content} from './content';\n","import 'dom4';\nimport Combokeys from 'combokeys';\n\nimport sniffr from '../global/sniffer';\n\nclass Shortcuts {\n ALLOW_SHORTCUTS_SELECTOR = '.ring-js-shortcuts';\n ROOT_SCOPE = {\n scopeId: 'ROOT',\n options: {}\n };\n\n _scopes = {};\n\n combokeys = new Combokeys(document.documentElement);\n trigger = combo => this.combokeys.trigger(combo);\n\n constructor() {\n this.setFilter();\n this.setScope();\n }\n\n _dispatcher = (e, key) => {\n let currentScope;\n\n for (let i = this._scopeChain.length - 1; i >= 0; i--) {\n const scopeInChain = this._scopeChain[i];\n currentScope = this._scopes[scopeInChain.scopeId];\n\n if (currentScope && currentScope[key]) {\n const ret = currentScope[key](e, key, scopeInChain.scopeId);\n\n // Fall down in chain when returning true\n if (ret !== true) {\n return ret;\n }\n }\n\n if (scopeInChain.options.modal) {\n return true;\n }\n }\n\n return undefined;\n };\n\n /**\n * Binds a handler to a shortcut\n *\n * @param params.key {string | Array.) Keys to bind\n * @param params.handler {Function} Events handle\n * @param params.scope {string} Scope (optional)\n * @param params.type {string} Event type, will be passed to Combokeys (optional)\n */\n bind(params) {\n if (!(params instanceof Object) || typeof params.handler !== 'function') {\n throw new Error('Shortcut handler should exist');\n }\n\n if (!params.scope) {\n params.scope = this.ROOT_SCOPE.scopeId;\n }\n\n if (Array.isArray(params.key)) {\n for (let i = 0; i < params.key.length; i++) {\n this.bind(Object.assign({}, params, {key: params.key[i]}));\n }\n\n return;\n }\n\n if (typeof params.key !== 'string') {\n throw new Error('Shortcut key should exist');\n }\n\n if (!this._scopes[params.scope]) {\n this._scopes[params.scope] = {};\n }\n this._scopes[params.scope][params.key] = params.handler;\n\n this.combokeys.bind(params.key, this._dispatcher, this._getKeyboardEventType(params));\n }\n\n /**\n * Binds a map of shortcuts to handlers with common options\n *\n * @map {Object) Keys to handlers map\n * @options.scope {string} Scope (optional)\n * @options.type {string} Event type, will be passed to Combokeys (optional)\n */\n bindMap(map, options) {\n if (!(map instanceof Object)) {\n throw new Error('Shortcuts map shouldn\\'t be empty');\n }\n\n for (const key in map) {\n if (map.hasOwnProperty(key)) {\n this.bind(Object.assign({}, options || {}, {key, handler: map[key]}));\n }\n }\n }\n\n unbindScope(scope) {\n this._scopes[scope] = null;\n }\n\n getScope() {\n return this._scopeChain.slice(1);\n }\n\n hasScope(scopeId) {\n return this.indexOfScope(scopeId) !== -1;\n }\n\n /**\n * Adds a scope to the chain\n * @param scopeId id of scope to add\n * @param options options for pushing scope\n * @param options.modal whether keys should fall through this scope or not.\n * Useful for modals or overlays\n */\n pushScope(scopeId, options = {}) {\n if (scopeId) {\n const position = this.indexOfScope(scopeId);\n\n if (position !== -1) {\n this._scopeChain.splice(position, 1);\n }\n\n this._scopeChain.push(this.wrapScope(scopeId, options));\n }\n }\n\n popScope(scopeId) {\n if (scopeId) {\n const position = this.indexOfScope(scopeId);\n\n if (position !== -1) {\n return this._scopeChain.splice(position, this._scopeChain.length - 1);\n }\n }\n\n return undefined;\n }\n\n spliceScope(scopeId) {\n if (scopeId) {\n const position = this.indexOfScope(scopeId);\n\n if (position !== -1) {\n this._scopeChain.splice(position, 1);\n }\n }\n }\n\n setScope(scope) {\n if (scope) {\n let scopeChain;\n\n if (typeof scope === 'string' || (!Array.isArray(scope) && typeof scope === 'object' && scope !== null)) {\n scopeChain = [scope];\n } else {\n scopeChain = scope;\n }\n\n if (!Array.isArray(scopeChain)) {\n return;\n }\n\n scopeChain = scopeChain.map(scopeItem => {\n const isScopeId = typeof scopeItem === 'string';\n return isScopeId ? this.wrapScope(scopeItem) : scopeItem;\n });\n\n this._scopeChain = [this.ROOT_SCOPE].concat(scopeChain);\n } else {\n this._scopeChain = [this.ROOT_SCOPE];\n }\n }\n\n wrapScope(scopeId, options = {}) {\n return {scopeId, options};\n }\n\n hasKey(key, scope) {\n return !!(this._scopes[scope] && this._scopes[scope][key]);\n }\n\n _defaultFilter = (e, element/*, key*/) => {\n // if the element or its parents have the class \"ring-js-shortcuts\" then no need to stop\n if (\n element === document ||\n element.matches(this.ALLOW_SHORTCUTS_SELECTOR) ||\n element.closest(this.ALLOW_SHORTCUTS_SELECTOR)\n ) {\n return false;\n }\n\n // stop for input, select, and textarea\n return element.matches('input,select,textarea') || (element.contentEditable && element.contentEditable === 'true');\n };\n\n _getKeyboardEventType(params) {\n if (!params.type && sniffr.os.name === 'windows') {\n const isSystemShortcut = params.key.match(/ctrl/i) && params.key.match(/shift/i) && params.key.match(/[0-9]/);\n /**\n * Windows system shortcuts (ctrl+shift+[0-9] are caught by the OS on 'keydown', so let's use 'keyup'\n */\n if (isSystemShortcut) {\n return 'keyup';\n }\n }\n return params.type;\n }\n\n setFilter(fn) {\n this.combokeys.stopCallback = typeof fn === 'function' ? fn : this._defaultFilter;\n }\n\n indexOfScope(scopeId) {\n return this._scopeChain.findIndex(scope => scope.scopeId === scopeId);\n }\n\n reset() {\n this._scopes = {};\n this.setScope();\n this.combokeys.reset();\n }\n}\n\nexport default new Shortcuts();\n","import {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\n\nimport shortcuts from './core';\n\nexport default class Shortcuts extends PureComponent {\n static propTypes = {\n map: PropTypes.object.isRequired,\n scope: PropTypes.string.isRequired,\n options: PropTypes.object,\n disabled: PropTypes.bool,\n children: PropTypes.node\n };\n\n static defaultProps = {\n options: {}\n };\n\n componentDidMount() {\n if (!this.props.disabled) {\n this.turnShorcutsOn();\n }\n }\n\n componentDidUpdate(prevProps) {\n const {disabled} = this.props;\n if (!prevProps.disabled && disabled) {\n this.turnShorcutsOff();\n }\n if (prevProps.disabled && !disabled) {\n this.turnShorcutsOn();\n }\n }\n\n componentWillUnmount() {\n if (!this.props.disabled) {\n this.turnShorcutsOff();\n }\n }\n\n turnShorcutsOn() {\n const {map, scope, options} = this.props;\n shortcuts.bindMap(map, this.props);\n shortcuts.pushScope(scope, options);\n }\n\n turnShorcutsOff() {\n const {scope} = this.props;\n shortcuts.unbindScope(scope);\n shortcuts.spliceScope(scope);\n }\n\n render() {\n return this.props.children || null;\n }\n}\n","import React, {Component} from 'react';\nimport PropTypes from 'prop-types';\n\nimport styles from './tab-trap.css';\n\nexport const FOCUSABLE_ELEMENTS = 'input, button, select, textarea, a[href], *[tabindex]:not([data-trap-button]):not([data-scrollable-container])';\n\n/**\n * @name TabTrap\n */\n\nexport default class TabTrap extends Component {\n static propTypes = {\n children: PropTypes.node.isRequired,\n trapDisabled: PropTypes.bool,\n autoFocusFirst: PropTypes.bool,\n focusBackOnClose: PropTypes.bool\n };\n\n static defaultProps = {\n trapDisabled: false,\n autoFocusFirst: true,\n focusBackOnClose: true\n };\n\n componentDidMount() {\n this.previousFocusedNode = document.activeElement;\n\n if (this.props.autoFocusFirst) {\n this.focusFirst();\n } else if (\n !this.props.trapDisabled &&\n (!this.node || !this.node.contains(this.previousFocusedNode))\n ) {\n this.trapWithoutFocus = true;\n this.trapButtonNode.focus();\n }\n }\n\n componentWillUnmount() {\n this.restoreFocus();\n }\n\n restoreFocus() {\n if (!this.props.focusBackOnClose) {\n return;\n }\n const {previousFocusedNode} = this;\n if (previousFocusedNode && previousFocusedNode.focus) {\n previousFocusedNode.focus();\n }\n }\n\n containerRef = node => {\n if (!node) {\n return;\n }\n this.node = node;\n };\n\n focusElement = (first = true) => {\n const {node} = this;\n if (!node) {\n return;\n }\n\n const tabables = [...node.querySelectorAll(FOCUSABLE_ELEMENTS)].\n filter(item => item.tabIndex >= 0);\n\n const toBeFocused = first ? tabables[0] : tabables[tabables.length - 1];\n\n if (toBeFocused) {\n toBeFocused.focus();\n }\n };\n\n focusFirst = () => this.focusElement(true);\n\n focusLast = () => this.focusElement(false);\n\n focusLastIfEnabled = () => {\n if (this.trapWithoutFocus) {\n return;\n }\n this.focusLast();\n };\n\n handleBlurIfWithoutFocus = event => {\n if (!this.trapWithoutFocus) {\n return;\n }\n this.trapWithoutFocus = false;\n\n const newFocused = event.nativeEvent.relatedTarget;\n if (!newFocused) {\n return;\n }\n\n if (this.node.contains(newFocused)) {\n return;\n }\n\n this.focusLast();\n };\n\n trapButtonRef = node => {\n if (!node) {\n return;\n }\n\n this.trapButtonNode = node;\n };\n\n render() {\n const {children, trapDisabled, autoFocusFirst, focusBackOnClose, ...restProps} = this.props;\n\n if (trapDisabled) {\n return (\n \n {children}\n \n );\n }\n\n return (\n \n \n {children}\n \n \n );\n }\n}\n","import 'focus-visible';\nimport React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport chevronDown from '@jetbrains/icons/chevron-10px.svg';\n\nimport Icon, {Size} from '../icon';\nimport Theme, {withTheme} from '../global/theme';\nimport ClickableLink from '../link/clickableLink';\n\nimport styles from './button.css';\n\n/**\n * @name Button\n */\nclass Button extends PureComponent {\n static propTypes = {\n theme: PropTypes.string,\n active: PropTypes.bool,\n danger: PropTypes.bool,\n delayed: PropTypes.bool,\n loader: PropTypes.bool,\n primary: PropTypes.bool,\n blue(props, propName) {\n if (propName in props) {\n return new Error(`\"${propName}\" prop is deprecated. Use \"primary\" instead`);\n }\n return undefined;\n },\n short: PropTypes.bool,\n text: PropTypes.bool,\n inline: PropTypes.bool,\n dropdown: PropTypes.bool,\n\n href: PropTypes.string,\n\n icon: PropTypes.oneOfType([PropTypes.string, PropTypes.elementType]),\n iconSize: PropTypes.number,\n iconClassName: PropTypes.string,\n iconSuppressSizeWarning: PropTypes.bool,\n\n className: PropTypes.string,\n\n children: PropTypes.node\n };\n\n static IconSize = Size;\n static Theme = Theme;\n\n render() {\n const {\n // Modifiers\n theme,\n active,\n blue,\n danger,\n delayed,\n loader,\n primary,\n short,\n text,\n inline,\n dropdown,\n\n // Props\n icon,\n iconSize,\n iconClassName,\n iconSuppressSizeWarning,\n className,\n children,\n ...props\n } = this.props;\n\n const withNormalIcon = icon && !active && !danger && !primary && !props.disabled;\n const classes = classNames(\n styles.button,\n className,\n styles[theme],\n {\n [styles.active]: active,\n [styles.danger]: danger,\n [styles.delayed]: delayed,\n [styles.withIcon]: icon,\n [styles.onlyIcon]: icon && !children,\n [styles.withNormalIconLight]: (\n withNormalIcon && theme === Theme.LIGHT\n ),\n [styles.withNormalIconDark]: (\n withNormalIcon && theme === Theme.DARK\n ),\n [styles.withDangerIconLight]: (\n icon && danger && theme === Theme.LIGHT\n ),\n [styles.withDangerIconDark]: (\n icon && danger && theme === Theme.DARK\n ),\n [styles.loader]: loader && !icon,\n [styles.primary]: primary || blue,\n [styles.short]: short,\n [styles.text]: text,\n [styles.inline]: inline\n }\n );\n\n const content = (\n \n {icon && (\n \n \n \n )}\n {children && (\n {children}\n )}\n {dropdown && (\n \n )}\n \n );\n const isLink = !!props.href;\n\n const Tag = isLink ? ClickableLink : 'button';\n return (\n \n {loader && !text && !icon &&
}\n {content}\n \n );\n }\n}\n\nexport {Size as IconSize};\n\nexport default withTheme()(Button);\n","import 'dom4';\nimport {\n getDocumentScrollLeft,\n getDocumentScrollTop,\n getRect,\n getWindowHeight,\n isMounted\n} from '../global/dom';\n\nexport const Directions = {\n BOTTOM_RIGHT: 'BOTTOM_RIGHT',\n BOTTOM_LEFT: 'BOTTOM_LEFT',\n BOTTOM_CENTER: 'BOTTOM_CENTER',\n TOP_LEFT: 'TOP_LEFT',\n TOP_RIGHT: 'TOP_RIGHT',\n TOP_CENTER: 'TOP_CENTER',\n RIGHT_TOP: 'RIGHT_TOP',\n RIGHT_BOTTOM: 'RIGHT_BOTTOM',\n RIGHT_CENTER: 'RIGHT_CENTER',\n LEFT_TOP: 'LEFT_TOP',\n LEFT_BOTTOM: 'LEFT_BOTTOM',\n LEFT_CENTER: 'LEFT_CENTER'\n};\n\n/**\n * When positioning a popup, directions will be tried in the listed order.\n * @type {Array.}\n */\nexport const DEFAULT_DIRECTIONS = [\n Directions.BOTTOM_RIGHT, Directions.BOTTOM_LEFT, Directions.TOP_LEFT, Directions.TOP_RIGHT,\n Directions.RIGHT_TOP, Directions.RIGHT_BOTTOM, Directions.LEFT_TOP, Directions.LEFT_BOTTOM\n];\n\n/**\n * @enum {number}\n */\nexport const Dimension = {\n MARGIN: 16,\n BORDER_WIDTH: 1\n};\n\nexport const MinWidth = {\n TARGET: -1\n};\n\nexport const MaxHeight = {\n SCREEN: -1\n};\n\nexport const Display = {\n HIDDEN: 0,\n SHOWING: 1,\n SHOWN: 2\n};\n\nfunction getScrollingCoordinates(container) {\n if (container !== null) {\n return {\n top: container.scrollTop,\n left: container.scrollLeft\n };\n }\n\n return {\n top: getDocumentScrollTop(),\n left: getDocumentScrollLeft()\n };\n}\n\nfunction getPositionStyles(popup, anchorRect, anchorLeft, anchorTop, offset) {\n const popupWidth = popup.clientWidth;\n const popupHeight = popup.clientHeight;\n\n const anchorBottom = anchorTop + anchorRect.height;\n const anchorRight = anchorLeft + anchorRect.width;\n\n const popupLeft = anchorLeft - popupWidth;\n const popupTop = anchorTop - popupHeight;\n const popupRightToLeft = anchorRight - popupWidth;\n const popupHorizontalCenter = anchorLeft + anchorRect.width / 2 - popupWidth / 2;\n const popupVerticalCenter = anchorTop + anchorRect.height / 2 - popupHeight / 2;\n const popupBottomToTop = anchorBottom - popupHeight;\n\n return {\n [Directions.BOTTOM_RIGHT]: {left: anchorLeft, top: anchorBottom + offset},\n [Directions.BOTTOM_LEFT]: {left: popupRightToLeft, top: anchorBottom + offset},\n [Directions.BOTTOM_CENTER]: {left: popupHorizontalCenter, top: anchorBottom + offset},\n [Directions.TOP_RIGHT]: {left: anchorLeft, top: popupTop - offset},\n [Directions.TOP_LEFT]: {left: popupRightToLeft, top: popupTop - offset},\n [Directions.TOP_CENTER]: {left: popupHorizontalCenter, top: popupTop - offset},\n [Directions.LEFT_BOTTOM]: {left: popupLeft - offset, top: anchorTop},\n [Directions.LEFT_TOP]: {left: popupLeft - offset, top: popupBottomToTop},\n [Directions.LEFT_CENTER]: {left: popupLeft - offset, top: popupVerticalCenter},\n [Directions.RIGHT_BOTTOM]: {left: anchorRight + offset, top: anchorTop},\n [Directions.RIGHT_TOP]: {left: anchorRight + offset, top: popupBottomToTop},\n [Directions.RIGHT_CENTER]: {left: anchorRight + offset, top: popupVerticalCenter}\n };\n}\n\nfunction verticalOverflow(styles, scrollingCoordinates, attrs) {\n const containerHeight = attrs.container !== null\n ? attrs.container.clientHeight\n : getWindowHeight();\n const viewportMinX = scrollingCoordinates.top + attrs.sidePadding;\n const viewportMaxX = scrollingCoordinates.top + containerHeight - attrs.sidePadding;\n\n const topOverflow = Math.max(viewportMinX - styles.top, 0);\n\n const popupHeight = attrs.popup.clientHeight;\n const verticalDiff = styles.top + popupHeight - viewportMaxX;\n const bottomOverflow = Math.max(verticalDiff, 0);\n\n return topOverflow + bottomOverflow;\n}\n\nfunction horizontalOverflow(styles, scrollingCoordinates, attrs) {\n const containerWidth = attrs.container !== null ? attrs.container.clientWidth : window.innerWidth;\n const viewportMinY = scrollingCoordinates.left + attrs.sidePadding;\n const viewportMaxY = scrollingCoordinates.left + containerWidth - attrs.sidePadding;\n\n const leftOverflow = Math.max(viewportMinY - styles.left, 0);\n\n const popupWidth = attrs.popup.clientWidth;\n const horizontalDiff = styles.left + popupWidth - viewportMaxY;\n const rightOverflow = Math.max(horizontalDiff, 0);\n\n return leftOverflow + rightOverflow;\n}\n\nexport const positionPropKeys = [\n 'directions',\n 'autoPositioning',\n 'autoCorrectTopOverflow',\n 'sidePadding',\n 'top',\n 'left',\n 'offset',\n 'maxHeight',\n 'minWidth'\n];\n\nconst defaultcontainerRect = {\n top: 0,\n left: 0\n};\n\nfunction handleTopOffScreen({\n sidePadding, styles, anchorRect, maxHeight, popupScrollHeight, direction\n}) {\n const BORDER_COMPENSATION = 1;\n const {TOP_LEFT, TOP_RIGHT, TOP_CENTER, RIGHT_TOP, LEFT_TOP} = Directions;\n\n const openedToTop = [TOP_LEFT, TOP_RIGHT, TOP_CENTER, RIGHT_TOP, LEFT_TOP].includes(direction);\n\n if (!openedToTop) {\n return styles;\n }\n\n const isAttachedToAnchorTop = [TOP_LEFT, TOP_CENTER, TOP_RIGHT].includes(direction);\n const attachingPointY = (isAttachedToAnchorTop ? anchorRect.top : anchorRect.bottom);\n\n const effectiveHeight = maxHeight ? Math.min(popupScrollHeight, maxHeight) : popupScrollHeight;\n const hypotheticalTop = attachingPointY - effectiveHeight;\n\n if (hypotheticalTop <= sidePadding) {\n styles.top = sidePadding;\n styles.maxHeight = attachingPointY - sidePadding + BORDER_COMPENSATION;\n }\n\n return styles;\n}\n\n\nexport function maxHeightForDirection(direction, anchorNode, containerNode) {\n const container = containerNode || document.documentElement;\n const domRect = anchorNode.getBoundingClientRect();\n const containerRect = container.getBoundingClientRect();\n const topMaxHeight = Math.max(domRect.top - containerRect.top, 0);\n const containerHeight = Math.max(containerRect.height,\n // XXX\n // If container is the document element\n // then we check client height too because we may have situation when\n // \"height\" from \"getBoundingClientRect\" less then \"clientHeight\".\n container === document.documentElement ? container.clientHeight : 0);\n const bottomMaxHeight = Math.max(containerHeight - (topMaxHeight + domRect.height), 0);\n switch (direction) {\n case Directions.TOP_LEFT:\n case Directions.TOP_CENTER:\n case Directions.TOP_RIGHT:\n return topMaxHeight;\n case Directions.BOTTOM_LEFT:\n case Directions.BOTTOM_CENTER:\n case Directions.BOTTOM_RIGHT:\n return bottomMaxHeight;\n case Directions.LEFT_BOTTOM:\n case Directions.RIGHT_BOTTOM:\n return domRect.height + bottomMaxHeight;\n case Directions.LEFT_TOP:\n case Directions.RIGHT_TOP:\n return domRect.height + topMaxHeight;\n case Directions.RIGHT_CENTER:\n case Directions.LEFT_CENTER:\n return (domRect.height / 2) + Math.min(bottomMaxHeight / 2, topMaxHeight / 2);\n default:\n return null;\n }\n}\n\nexport default function position(attrs) {\n const {\n popup,\n anchor,\n container,\n directions,\n autoPositioning,\n sidePadding,\n top,\n left,\n offset,\n maxHeight,\n minWidth,\n autoCorrectTopOverflow = true\n } = attrs;\n\n let styles = {\n top: 0,\n left: 0\n };\n let chosenDirection = null;\n\n const containerRect = container !== null ? getRect(container) : defaultcontainerRect;\n const defaultAnchor = container !== null ? container : document.body;\n const anchorRect = getRect(isMounted(anchor) ? anchor : defaultAnchor);\n const scroll = getScrollingCoordinates(container);\n const anchorLeft = anchorRect.left + scroll.left + left - containerRect.left;\n const anchorTop = anchorRect.top + scroll.top + top - containerRect.top;\n\n if (popup) {\n const directionsMatrix = getPositionStyles(popup, anchorRect, anchorLeft, anchorTop, offset);\n if (!autoPositioning || directions.length === 1) {\n styles = directionsMatrix[directions[0]];\n chosenDirection = directions[0];\n } else {\n const sortedByIncreasingOverflow = directions.\n // Fall back to the first option\n concat(directions[0]).filter(direction => directionsMatrix[direction]).\n map(direction => ({styles: directionsMatrix[direction], direction})).\n sort(({styles: stylesA}, {styles: stylesB}) => {\n const overflowA =\n verticalOverflow(stylesA, scroll, attrs) +\n horizontalOverflow(stylesA, scroll, attrs);\n const overflowB =\n verticalOverflow(stylesB, scroll, attrs) +\n horizontalOverflow(stylesB, scroll, attrs);\n return overflowA - overflowB;\n });\n styles = sortedByIncreasingOverflow[0].styles;\n chosenDirection = sortedByIncreasingOverflow[0].direction;\n }\n\n // because of the anchor negative margin top and left also may become negative\n ['left', 'top'].forEach(key => {\n if (styles[key] < 0) {\n styles[key] = 0;\n }\n });\n }\n\n if (maxHeight === MaxHeight.SCREEN || maxHeight === 'screen') {\n // this feature works properly only when direction is BOTTOM_* or *_BOTTOM\n styles.maxHeight = window.innerHeight + scroll.top - styles.top - Dimension.MARGIN;\n } else if (maxHeight) {\n styles.maxHeight = maxHeight;\n }\n\n if (autoCorrectTopOverflow) {\n styles = handleTopOffScreen({\n sidePadding,\n styles,\n anchorRect,\n maxHeight,\n direction: chosenDirection,\n popupScrollHeight: popup.scrollHeight\n });\n }\n\n if (minWidth === MinWidth.TARGET || minWidth === 'target') {\n styles.minWidth = anchorRect.width;\n } else if (minWidth) {\n styles.minWidth = anchorRect.width < minWidth ? minWidth : anchorRect.width;\n }\n\n return {styles, direction: chosenDirection};\n}\n","/**\n * @name Popup\n */\n\nimport React, {createContext, forwardRef, PureComponent} from 'react';\nimport {createPortal} from 'react-dom';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport 'dom4';\n\nimport getUID from '../global/get-uid';\nimport scheduleRAF from '../global/schedule-raf';\nimport {Listeners, getStyles} from '../global/dom';\nimport Shortcuts from '../shortcuts/shortcuts';\nimport dataTests from '../global/data-tests';\n\nimport position, {\n DEFAULT_DIRECTIONS,\n Dimension,\n Directions,\n Display,\n MaxHeight,\n MinWidth,\n positionPropKeys\n} from './position';\nimport styles from './popup.css';\n\nconst stop = e => e.stopPropagation();\n\nconst PopupTargetContext = createContext();\nexport const PopupTarget = forwardRef(\n function PopupTarget({id, children, ...restProps}, ref) {\n const isFunctionChild = typeof children === 'function';\n const target = (\n \n {!isFunctionChild && children}\n
\n );\n return (\n \n {isFunctionChild ? children(target) : target}\n \n );\n }\n);\nPopupTarget.propTypes = {\n id: PropTypes.string.isRequired,\n children: PropTypes.oneOfType([PropTypes.node, PropTypes.func])\n};\n\n/**\n * @constructor\n * @name Popup\n * @extends {ReactComponent}\n */\nexport default class Popup extends PureComponent {\n static propTypes = {\n anchorElement: PropTypes.instanceOf(Node),\n target: PropTypes.string,\n className: PropTypes.string,\n style: PropTypes.object,\n hidden: PropTypes.bool.isRequired,\n onOutsideClick: PropTypes.func,\n onEscPress: PropTypes.func,\n // onCloseAttempt is a common callback for ESC pressing and outside clicking.\n // Use it if you don't need different behaviors for this cases.\n onCloseAttempt: PropTypes.func,\n children: PropTypes.oneOfType([\n PropTypes.arrayOf(PropTypes.node),\n PropTypes.node\n ]),\n dontCloseOnAnchorClick: PropTypes.bool,\n shortcuts: PropTypes.bool,\n keepMounted: PropTypes.bool, // pass this prop to preserve the popup's DOM state while hidden\n 'data-test': PropTypes.string,\n client: PropTypes.bool, // true means that it's never used in SSR\n\n directions: PropTypes.arrayOf(PropTypes.string),\n autoPositioning: PropTypes.bool,\n autoCorrectTopOverflow: PropTypes.bool,\n left: PropTypes.number,\n top: PropTypes.number,\n maxHeight: PropTypes.number,\n minWidth: PropTypes.number,\n sidePadding: PropTypes.number,\n\n attached: PropTypes.bool, // Popup adjacent to an input, without upper border and shadow\n\n onMouseDown: PropTypes.func,\n onMouseUp: PropTypes.func,\n onMouseOver: PropTypes.func,\n onMouseOut: PropTypes.func,\n onContextMenu: PropTypes.func,\n onDirectionChange: PropTypes.func,\n onShow: PropTypes.func\n };\n\n static defaultProps = {\n shortcuts: true,\n hidden: false,\n onOutsideClick() {},\n onEscPress() {},\n onCloseAttempt() {},\n dontCloseOnAnchorClick: false,\n keepMounted: false,\n\n directions: DEFAULT_DIRECTIONS,\n autoPositioning: true,\n autoCorrectTopOverflow: true,\n left: 0,\n top: 0,\n offset: 0,\n sidePadding: 8,\n\n attached: false,\n\n legacy: false\n };\n\n state = {\n display: Display.SHOWING\n };\n\n componentDidMount() {\n if (!this.props.client) {\n // eslint-disable-next-line react/no-did-mount-set-state\n this.setState({client: true});\n }\n if (!this.props.hidden) {\n this._setListenersEnabled(true);\n }\n }\n\n componentDidUpdate(prevProps, prevState) {\n const {hidden} = this.props;\n if (this.props !== prevProps) {\n\n if (prevProps.hidden !== hidden) {\n this._setListenersEnabled(!hidden);\n }\n\n this._redraw();\n }\n\n if (\n this.props.onShow &&\n !hidden &&\n this.state.display === Display.SHOWN &&\n (prevProps.hidden || prevState.display !== Display.SHOWN)\n ) {\n this.props.onShow();\n }\n }\n\n componentWillUnmount() {\n this._setListenersEnabled(false);\n this.popup = null;\n }\n\n shouldUseShortcuts() {\n const {shortcuts, hidden} = this.props;\n return shortcuts && !hidden;\n }\n\n listeners = new Listeners();\n redrawScheduler = scheduleRAF(true);\n uid = getUID('popup-');\n calculateDisplay = prevState => ({\n ...prevState,\n display: this.props.hidden\n ? Display.SHOWING\n : Display.SHOWN\n });\n\n static PopupProps = {\n Directions,\n Dimension,\n MinWidth,\n MaxHeight\n };\n\n portalRef = el => {\n this.node = el;\n this.parent = el && el.parentElement;\n if (el && this.getContainer()) {\n this._redraw();\n }\n };\n\n popupRef = el => {\n this.popup = el;\n this._redraw();\n };\n\n containerRef = el => {\n this.container = el;\n };\n\n getContainer() {\n const target = this.props.target || this.ringPopupTarget;\n return target && document.querySelector(`[data-portaltarget=${target}]`);\n }\n\n position() {\n const positionProps = positionPropKeys.reduce((acc, key) => {\n acc[key] = this.props[key];\n return acc;\n }, {});\n const container = this.getContainer();\n\n return position({\n popup: this.popup,\n container: container && getStyles(container).position !== 'static' ? container : null,\n anchor: this._getAnchor(),\n ...positionProps\n });\n }\n\n _updateDirection = newDirection => {\n if (this.state.direction !== newDirection) {\n this.setState({direction: newDirection});\n if (this.props.onDirectionChange) {\n this.props.onDirectionChange(newDirection);\n }\n }\n };\n\n _updatePosition = () => {\n if (this.popup) {\n this.popup.style.position = 'absolute';\n if (this.isVisible()) {\n const {styles: style, direction} = this.position();\n Object.keys(style).forEach(key => {\n const value = style[key];\n if (typeof value === 'number') {\n this.popup.style[key] = `${value}px`;\n } else {\n this.popup.style[key] = value.toString();\n }\n });\n this._updateDirection(direction);\n }\n this.setState(this.calculateDisplay);\n }\n };\n\n _redraw = () => {\n if (this.isVisible()) {\n this.redrawScheduler(this._updatePosition);\n }\n };\n\n _getAnchor() {\n return this.props.anchorElement || this.parent;\n }\n\n /**\n * @param {boolean} enable\n * @private\n */\n _setListenersEnabled(enable) {\n if (enable && !this._listenersEnabled) {\n setTimeout(() => {\n this._listenersEnabled = true;\n this.listeners.add(window, 'resize', this._redraw);\n this.listeners.add(window, 'scroll', this._redraw);\n this.listeners.add(document, 'click', this._onDocumentClick);\n let el = this._getAnchor();\n while (el) {\n this.listeners.add(el, 'scroll', this._redraw);\n el = el.parentElement;\n }\n }, 0);\n\n return;\n }\n\n if (!enable && this._listenersEnabled) {\n this.listeners.removeAll();\n this._listenersEnabled = false;\n }\n }\n\n /**\n * Returns visibility state\n * @return {boolean}\n */\n isVisible() {\n return !this.props.hidden;\n }\n\n _onCloseAttempt(evt, isEsc) {\n this.props.onCloseAttempt(evt, isEsc);\n }\n\n _onEscPress = evt => {\n this.props.onEscPress(evt);\n this._onCloseAttempt(evt, true);\n };\n\n /**\n * @param {jQuery.Event} evt\n * @private\n */\n _onDocumentClick = evt => {\n if (\n this.container && this.container.contains(evt.target) ||\n !this._listenersEnabled ||\n (\n this.props.dontCloseOnAnchorClick &&\n this._getAnchor() &&\n this._getAnchor().contains(evt.target)\n )\n ) {\n return;\n }\n\n this.props.onOutsideClick(evt);\n this._onCloseAttempt(evt, false);\n };\n\n getInternalContent() {\n return this.props.children;\n }\n\n shortcutsScope = this.uid;\n shortcutsMap = {\n esc: this._onEscPress\n };\n\n render() {\n const {\n className, style, hidden, attached, keepMounted, client,\n onMouseDown, onMouseUp, onMouseOver, onMouseOut, onContextMenu, 'data-test': dataTest\n } = this.props;\n const showing = this.state.display === Display.SHOWING;\n\n const classes = classNames(className, styles.popup, {\n [styles.attached]: attached,\n [styles.hidden]: hidden,\n [styles.showing]: showing\n });\n\n const direction = (this.state.direction || '').\n toLowerCase().replace(/[_]/g, '-');\n\n return (\n \n {value => {\n this.ringPopupTarget = value;\n return (\n \n {this.shouldUseShortcuts() &&\n (\n \n )\n }\n\n {(client || this.state.client) && (keepMounted || !hidden) && createPortal(\n \n \n {this.getInternalContent()}\n \n ,\n this.getContainer() || document.body\n )}\n \n );\n }}\n \n );\n }\n}\n","import scrollbarWidth from 'scrollbar-width';\n\nimport {bodyWithoutScroll} from './dialog.css';\n\nlet isPrevented = false;\nlet previousBodyWidth = null;\n\nexport default {\n prevent() {\n if (isPrevented) {\n return;\n }\n isPrevented = true;\n document.documentElement.classList.add(bodyWithoutScroll);\n\n const scrollWidth = scrollbarWidth();\n\n const bodyHasScroll = document.documentElement.scrollHeight > window.innerHeight;\n\n if (bodyHasScroll && scrollWidth > 0) {\n previousBodyWidth = document.documentElement.style.width;\n document.documentElement.style.width = `calc(100% - ${scrollWidth}px)`;\n }\n },\n\n reset() {\n if (!isPrevented) {\n return;\n }\n isPrevented = false;\n\n document.documentElement.classList.remove(bodyWithoutScroll);\n\n if (previousBodyWidth !== null) {\n document.documentElement.style.width = previousBodyWidth;\n previousBodyWidth = null;\n }\n }\n};\n","import React, {PureComponent} from 'react';\nimport {createPortal} from 'react-dom';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport closeIcon from '@jetbrains/icons/close.svg';\n\nimport {AdaptiveIsland} from '../island/island';\nimport getUID from '../global/get-uid';\nimport Shortcuts from '../shortcuts/shortcuts';\nimport TabTrap from '../tab-trap/tab-trap';\nimport Button from '../button/button';\nimport {PopupTarget} from '../popup/popup';\n\nimport ScrollPreventer from './dialog__body-scroll-preventer';\nimport styles from './dialog.css';\n\n/**\n * @name Dialog\n */\n\nfunction noop() {}\n\nexport default class Dialog extends PureComponent {\n static propTypes = {\n className: PropTypes.string,\n contentClassName: PropTypes.string,\n children: PropTypes.oneOfType([\n PropTypes.arrayOf(PropTypes.node),\n PropTypes.node\n ]),\n show: PropTypes.bool.isRequired,\n showCloseButton: PropTypes.bool,\n onOverlayClick: PropTypes.func,\n onEscPress: PropTypes.func,\n onCloseClick: PropTypes.func,\n // onCloseAttempt is a common callback for ESC pressing and overlay clicking.\n // Use it if you don't need different behaviors for this cases.\n onCloseAttempt: PropTypes.func,\n // focusTrap may break popups inside dialog, so use it carefully\n trapFocus: PropTypes.bool,\n autoFocusFirst: PropTypes.bool\n };\n\n static defaultProps = {\n onOverlayClick: noop,\n onEscPress: noop,\n onCloseClick: noop,\n onCloseAttempt: noop,\n showCloseButton: false,\n trapFocus: false,\n autoFocusFirst: true\n };\n\n state = {\n shortcutsScope: getUID('ring-dialog-')\n };\n\n componentDidMount() {\n this.toggleScrollPreventer();\n }\n\n componentDidUpdate(prevProps) {\n if (prevProps.show !== this.props.show) {\n this.toggleScrollPreventer();\n }\n }\n\n componentWillUnmount() {\n ScrollPreventer.reset();\n }\n\n uid = getUID('dialog-');\n\n toggleScrollPreventer() {\n if (this.props.show) {\n ScrollPreventer.prevent();\n } else {\n ScrollPreventer.reset();\n }\n }\n\n handleClick = event => {\n this.props.onOverlayClick(event);\n this.props.onCloseAttempt(event);\n };\n\n onCloseClick = event => {\n this.props.onCloseClick(event);\n this.props.onCloseAttempt(event);\n };\n\n getShortcutsMap = () => {\n const onEscape = event => {\n if (this.props.show) {\n this.props.onEscPress(event);\n this.props.onCloseAttempt(event);\n }\n };\n\n return {\n esc: onEscape\n };\n };\n\n dialogRef = tabTrap => {\n this.dialog = tabTrap && tabTrap.node;\n };\n\n render() {\n const {show, showCloseButton, onOverlayClick, onCloseAttempt, onEscPress, onCloseClick,\n children, className, contentClassName, trapFocus, ...restProps} = this.props;\n const classes = classNames(styles.container, className);\n const shortcutsMap = this.getShortcutsMap();\n\n return show && createPortal(\n \n {\n target => (\n \n \n {(onOverlayClick !== noop || onCloseAttempt !== noop) && (\n \n )}\n
\n \n {children}\n {showCloseButton &&\n (\n \n )\n }\n \n
\n {target}\n \n )\n }\n
,\n document.body\n );\n }\n}\n","import React, {Component} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport Dialog from '../dialog/dialog';\nimport Button from '../button/button';\n\nimport styles from './auth-dialog.css';\n\n/**\n * @name Auth Dialog\n */\n\nexport default class AuthDialog extends Component {\n static propTypes = {\n className: PropTypes.string,\n title: PropTypes.string,\n errorMessage: PropTypes.string,\n serviceImage: PropTypes.string,\n serviceName: PropTypes.string,\n loginCaption: PropTypes.string,\n loginToCaption: PropTypes.string,\n\n show: PropTypes.bool,\n cancelOnEsc: PropTypes.bool,\n confirmLabel: PropTypes.string,\n cancelLabel: PropTypes.string,\n\n onConfirm: PropTypes.func,\n onCancel: PropTypes.func\n };\n\n static defaultProps = {\n loginCaption: 'Log in',\n loginToCaption: 'Log in to %serviceName%',\n show: false,\n cancelOnEsc: true,\n confirmLabel: 'Log in',\n cancelLabel: 'Remain a guest',\n onConfirm: () => {},\n onCancel: () => {}\n };\n\n onEscPress = () => {\n if (this.props.cancelOnEsc) {\n this.props.onCancel();\n }\n };\n\n render() {\n const {\n show,\n className,\n errorMessage,\n serviceImage,\n serviceName,\n loginCaption,\n loginToCaption,\n confirmLabel,\n cancelLabel,\n onConfirm,\n onCancel\n } = this.props;\n\n const defaultTitle = serviceName ? loginToCaption : loginCaption;\n const title = (this.props.title || defaultTitle).replace('%serviceName%', serviceName);\n\n return (\n \n
\n {serviceImage && (\n \n )}\n
{title}
\n {errorMessage && (\n
{errorMessage}
\n )}\n \n {confirmLabel}\n \n \n {cancelLabel}\n \n
\n \n );\n }\n}\n\n","import React from 'react';\nimport {render} from 'react-dom';\n\nimport AuthDialog from '../auth-dialog/auth-dialog';\n\n/**\n * @name Auth Dialog Service\n */\n\nconst containerElement = document.createElement('div');\n\n/**\n * Renders AuthDialog into virtual node to skip maintaining container\n */\nfunction renderAuthDialog(props) {\n render(, containerElement);\n}\n\nexport default function showAuthDialog(props = {}) {\n renderAuthDialog({\n ...props,\n show: true\n });\n\n return () => {\n renderAuthDialog({show: false});\n };\n}\n","import angular from 'angular';\n\nimport Auth from '../auth/auth';\n\n/**\n * @name Auth Ng\n */\nconst angularModule = angular.module('Ring.auth', []);\n\nangularModule.provider('auth', function provider($httpProvider) {\n /**\n * @type Auth\n */\n let auth;\n /**\n * @type {{cleanHash: boolean}} config\n */\n const defaultConfig = {\n cleanHash: false //prevents infinite redirect on angular>1.2.26\n };\n\n this.init = authInstance => {\n auth = authInstance;\n };\n\n /**\n * @param {{\n * serverUri: string,\n * redirectUri: string?,\n * clientId: string?,\n * scope: string[]?,\n * cleanHash: boolean?\n * }} config\n */\n this.config = config => {\n const configCopy = angular.extend({}, defaultConfig, config);\n auth = new Auth(configCopy);\n };\n\n $httpProvider.interceptors.push(['$q', '$injector', 'auth', ($q, $injector, authInstance) => {\n function urlEndsWith(config, suffix) {\n return config &&\n config.url &&\n config.url.indexOf(suffix) === config.url.length - suffix.length;\n }\n\n return {\n request(config) {\n if (!authInstance || urlEndsWith(config, '.html') || (config && config.noAuthorization)) {\n // Don't intercept angular template requests\n return config;\n }\n return authInstance.promise.\n then(() => authInstance.auth.requestToken()).\n then(accessToken => {\n if (accessToken) {\n config.headers.Authorization = `Bearer ${accessToken}`;\n }\n return config;\n });\n },\n responseError(rejection) {\n if (authInstance && !urlEndsWith(rejection.config, '.html') &&\n rejection.data != null && Auth.shouldRefreshToken(rejection.data.error)) {\n\n // Use $injector to avoid circular dependency\n const $http = $injector.get('$http');\n const {data, method, params, url} = rejection.config;\n\n return authInstance.auth.\n forceTokenUpdate().\n then(() => $http({data, method, params, url}));\n }\n\n return $q.reject(rejection);\n }\n };\n }]);\n\n this.$get = function get($injector, $log, $sniffer) {\n // Do not try to init anything without config\n if (!auth) {\n $log.warn('Auth wasn\\'t initialized');\n return null;\n }\n\n if (auth.config.reloadOnUserChange === false) {\n auth.addListener('userChange', () => {\n const $route = $injector.get('$route');\n $route.reload();\n });\n }\n\n /**\n * @type {Promise.}\n */\n const authInitPromise = auth.init();\n\n /**\n * @param {string?} restoreLocationURL\n */\n function restoreLocation(restoreLocationURL) {\n if (restoreLocationURL) {\n const bases = document.getElementsByTagName('base');\n let baseURI = auth.config.redirectUri;\n\n if (bases.length > 0) {\n baseURI = bases[0].href;\n }\n\n if (restoreLocationURL.indexOf(baseURI) === 0) {\n const $location = $injector.get('$location');\n let relativeURI = restoreLocationURL.substr(baseURI.length);\n\n // We have to turn url with hash to simple relative url in HashbangInHtml5 mode\n // And there is no other and documented way to detect that mode\n // @see http://stackoverflow.com/a/16678065\n if ($location.$$html5 && !$sniffer.history) { // eslint-disable-line angular/no-private-call\n relativeURI = relativeURI.replace(/^#\\//, '');\n }\n\n $location.url(relativeURI).replace();\n }\n }\n }\n\n authInitPromise.then(restoreLocation, e => {\n if (!e.authRedirect) {\n $log.error(e);\n }\n });\n\n return {\n auth,\n requestUser: auth.requestUser.bind(auth),\n clientId: auth.config.clientId,\n logout: auth.logout.bind(auth),\n promise: authInitPromise\n };\n };\n});\n\nexport default angularModule.name;\n","/**\n * @name Autofocus Ng\n */\nimport angular from 'angular';\n\nimport {FOCUSABLE_ELEMENTS} from '../tab-trap/tab-trap';\n\nconst angularModule = angular.module('Ring.autofocus', []);\nconst RING_SELECT_SELECTOR = '[data-test=ring-select__focus]';\nconst RING_SELECT = 'rg-select';\n\nangularModule.directive('rgAutofocus', function rgAutofocusDirective() {\n\n /**\n * Focuses on element itself if it has \"focus\" method.\n * Searches and focuses on select's button or input if element is rg-select\n * @param element\n */\n function focusOnElement(element) {\n if (!element) {\n return;\n }\n\n if (element.hasAttribute(RING_SELECT) || element.tagName.toLowerCase() === RING_SELECT) {\n focusOnElement(element.querySelector(RING_SELECT_SELECTOR));\n return;\n }\n\n if (element.matches(FOCUSABLE_ELEMENTS) && element.focus) {\n element.focus();\n return;\n }\n\n const focusableChild = element.querySelector(FOCUSABLE_ELEMENTS);\n\n if (focusableChild && focusableChild.focus) {\n focusableChild.focus();\n }\n }\n\n return (scope, iElement, iAttrs) => {\n const element = iElement[0];\n scope.$watch(iAttrs.rgAutofocus, newValue => {\n if (newValue) {\n scope.$evalAsync(() => focusOnElement(element));\n }\n });\n };\n});\n\nexport default angularModule.name;\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport {encodeURL, isDataURI, parseQueryString} from '../global/url';\nimport {getPixelRatio} from '../global/dom';\n\nimport styles from './avatar.css';\n\n/**\n * @name Avatar\n */\n\nexport const Size = {\n Size18: 18,\n Size20: 20,\n Size24: 24,\n Size32: 32,\n Size40: 40,\n Size48: 48,\n Size56: 56\n};\n\nexport default class Avatar extends PureComponent {\n static propTypes = {\n dpr: PropTypes.number,\n className: PropTypes.string,\n size: PropTypes.number,\n style: PropTypes.object,\n url: PropTypes.string,\n round: PropTypes.bool,\n subavatar: PropTypes.string,\n subavatarSize: PropTypes.number\n };\n\n static defaultProps = {\n dpr: getPixelRatio(),\n size: Size.Size20,\n subavatarSize: Size.Size20 / 2,\n style: {}\n };\n\n state = {\n errorUrl: ''\n };\n\n handleError = () => {\n this.setState({errorUrl: this.props.url});\n };\n\n handleSuccess = () => {\n this.setState({errorUrl: ''});\n };\n\n render() {\n const {size, url, dpr, style, round, subavatar, subavatarSize, ...restProps} = this.props;\n const sizeString = `${size}px`;\n const subavatarSizeString = `${subavatarSize}px`;\n const borderRadius = size <= Size.Size18 ? 'var(--ring-border-radius-small)' : 'var(--ring-border-radius)';\n const styleObj = {\n borderRadius: round ? '50%' : borderRadius,\n height: sizeString,\n width: sizeString,\n ...style\n };\n\n const styleObjGroup = {\n borderRadius: '2px',\n height: subavatarSizeString,\n width: subavatarSizeString,\n ...style\n };\n\n if (!url || this.state.errorUrl === url) {\n return (\n \n );\n }\n\n let src = url;\n if (!isDataURI(url)) {\n const [urlStart, query] = url.split('?');\n const queryParams = {\n ...parseQueryString(query),\n dpr,\n size\n };\n\n src = encodeURL(urlStart, queryParams);\n }\n let subavatarSrc = null;\n if (subavatar && !isDataURI(subavatar)) {\n const [urlStart, query] = subavatar.split('?');\n const queryParams = {\n ...parseQueryString(query),\n dpr,\n subavatarSizeString\n };\n\n subavatarSrc = encodeURL(urlStart, queryParams);\n return (\n
\n \n \n
\n );\n } else {\n return (\n \n );\n }\n }\n}\n","import angular from 'angular';\n/**\n * This service is used by directive to correctly show messages.\n * You can decorate this service to provide your own localized messages.\n */\nconst angularModule = angular.module('Ring.message-bundle', []);\n\n/**\n * Empty i18n function. If project supports localization, it should decorate i18n\n * with translating function\n */\nfunction emptyI18n() {\n return str => str;\n}\n\nfunction RingMessageBundle(ringI18n) {\n const i18n = ringI18n;\n\n /* eslint-disable camelcase */\n this.form_required = () => i18n('Value is required');\n this.form_invalid = () => i18n('Value is invalid');\n this.form_url = () => i18n('Should be a valid URL');\n this.form_email = () => i18n('Should be a valid email');\n this.form_number = () => i18n('Should be a number');\n this.form_maxlength = () => i18n('Is too long');\n this.form_minlength = () => i18n('Is too short');\n this.form_pattern = () => i18n('Doesn\\'t match the pattern');\n this.form_equalvalue = () => i18n('Is not the same');\n this.form_unique = () => i18n('Is not unique');\n this.form_max = () => i18n('Is out of range');\n this.form_min = () => i18n('Is out of range');\n this.form_save = () => i18n('Save');\n this.form_saved = () => i18n('Saved');\n this.form_cancel = () => i18n('Cancel');\n this.avatareditor_nosupport = () => i18n('Sorry, your browser doesn\\'t support File API');\n this.avatareditor_noselected = () => i18n('No image file was selected');\n this.avatareditor_delete = () => i18n('Delete Image');\n this.avatareditor_add = () => i18n('Add Image');\n this.errorpage_seriouslywrong = () => i18n('Oh-oh... Something went seriously wrong.');\n this.errorpage_offline = () => i18n('There\\'s nothing we can do: The server seems to be offline.');\n this.errorpage_disconnected = () => i18n('Disconnected');\n this.errorpage_disconnectedmsg = () => i18n('No, no one\\'s there.');\n this.errorpage_401 = () => i18n('Authorization required');\n this.errorpage_401msg = () => i18n('You have requested access to a page that requires authorization, but the request is missing valid authentication credentials. It can also mean that your account has been banned.');\n this.errorpage_403 = () => i18n('Woah, you can\\'t touch this!');\n this.errorpage_403msg = () => i18n('Unfortunately, you are not allowed to access the page you\\'ve requested. It seems you don\\'t have sufficient permissions.');\n this.errorpage_404 = () => i18n('Nope, can\\'t find it!');\n this.errorpage_404msg = () => i18n('Despite our best efforts, there\\'s nothing here to show you with the URL you requested. Most likely the URL is invalid or you don\\'t have permissions to access the page.');\n this.errorpage_500 = () => i18n('Oh-oh... Something went seriously wrong');\n this.errorpage_500msg = () => i18n('Despite our best efforts, the server is not working properly.');\n this.select_options_not_found = () => i18n('No options found');\n this.select_loading = () => i18n('Loading...');\n this.select_label = () => i18n('Select an option');\n this.previous_page = () => i18n('previous');\n this.next_page = () => i18n('next page');\n this.first_page = () => i18n('First page');\n this.last_page = () => i18n('Last page');\n this.items_per_page = () => i18n('per page');\n this.confirmation_ok = () => i18n('Ok');\n this.confirmation_cancel = () => i18n('Cancel');\n/* eslint-enable camelcase */\n}\n\nangularModule.factory('ringI18n', emptyI18n);\nangularModule.service('RingMessageBundle', ['ringI18n', RingMessageBundle]);\n\nexport default angularModule.name;\n","export default class RingAngularComponent {\n static $inject = [];\n\n static get controller() {\n return this;\n }\n\n $inject = {};\n\n constructor(...args) {\n this.constructor.$inject.forEach((injectName, i) => {\n this.$inject[injectName] = args[i];\n });\n }\n}\n","import angular from 'angular';\n\nimport RingAngularComponent from '../global/ring-angular-component';\n\n/**\n * @name Template Ng\n*/\n\nconst angularModule = angular.module('Ring.template', []);\n\nclass RgTemplateController extends RingAngularComponent {\n static $inject = ['$scope', '$element', '$attrs', '$compile'];\n\n currentScope = null;\n\n constructor(...args) {\n super(...args);\n\n const {$scope, $attrs} = this.$inject;\n $scope.$watch($attrs.rgTemplate || $attrs.template, this.render);\n }\n\n render = template => {\n const {$scope, $element, $compile} = this.$inject;\n\n this.cleanup();\n\n this.currentScope = $scope.$new();\n\n this.currentScope.$evalAsync(() => {\n $element.html(template);\n this.addInnerClass();\n $compile($element.contents())(this.currentScope);\n });\n };\n\n addInnerClass = () => {\n const {rgTemplateClass} = this.$inject.$attrs;\n if (rgTemplateClass) {\n this.$inject.$element.contents().addClass(rgTemplateClass);\n }\n }\n\n cleanup() {\n if (this.currentScope) {\n this.currentScope.$destroy();\n this.currentScope = null;\n }\n }\n}\n\nangularModule.directive('rgTemplate', function rgTemplateDirective() {\n return {\n controller: RgTemplateController\n };\n});\n\nexport default angularModule.name;\n","import angular from 'angular';\nimport 'dom4';\n\nimport {Color} from '../icon/icon__constants';\nimport TemplateNg from '../template-ng/template-ng';\nimport styles from '../icon/icon.css';\n\n/**\n * @name Icon Ng\n */\n\nconst angularModule = angular.module('Ring.icon', [TemplateNg]);\nconst BASE64_PREFIX = 'data:image/svg+xml;base64,';\n\nangularModule.directive('rgIcon', function rgIconDirective() {\n return {\n restrict: 'E',\n scope: {\n glyph: '@',\n loading: '=?',\n color: '@?',\n size: '@?',\n height: '@?',\n width: '@?'\n },\n template: ``,\n controller: $scope => {\n function decodeBase64IfNeeded(glyph) {\n // This hack allows passing SVG content as string from angular templates like\n // \n const isEncoded = glyph.indexOf(BASE64_PREFIX) === 0;\n return isEncoded ? window.atob(glyph.replace(BASE64_PREFIX, '')) : glyph;\n }\n\n $scope.$watch('glyph', value => {\n if (!value) {\n return;\n }\n $scope.normalizedGlyph = decodeBase64IfNeeded(value);\n });\n },\n link: function link(scope, iElement, iAttrs) {\n iAttrs.$addClass('ring-icon'); // TODO: We keep this class for now for compatibility reasons (styles overrides)\n\n scope.$watch('loading', value => {\n if (value) {\n iAttrs.$addClass(styles.loading);\n } else {\n iAttrs.$removeClass(styles.loading);\n }\n });\n\n scope.$watch(() => scope.color && Color[scope.color] && styles[Color[scope.color]],\n (colorClass, prevColorClass) => {\n if (colorClass) {\n iAttrs.$addClass(colorClass);\n\n // Remove previous class, but don't remove initial one\n if (prevColorClass && prevColorClass !== colorClass) {\n iAttrs.$removeClass(prevColorClass);\n }\n }\n }\n );\n\n scope.$watchGroup(['size', 'width', 'height'], ([size, width, height]) => {\n const svgNode = iElement[0].querySelector('svg');\n\n if (size && !width && !height) {\n const sizeString = `${size}px`;\n const style = `width: ${sizeString}; height: ${sizeString};`;\n svgNode.setAttribute('style', style);\n return;\n }\n\n if (width) {\n svgNode.setAttribute('style', `width: ${width}px;`);\n }\n if (height) {\n svgNode.setAttribute('style', `height: ${height}px;`);\n }\n });\n }\n };\n});\n\nexport default angularModule.name;\n","import angular from 'angular';\n\nimport pencilIcon from '@jetbrains/icons/pencil.svg';\n\nimport messageBundleNg from '../message-bundle-ng/message-bundle-ng';\nimport alertService from '../alert-service/alert-service';\nimport IconNG from '../icon-ng/icon-ng';\n\nimport '../avatar-editor/avatar-editor.scss';\n\nconst angularModule = angular.module('Ring.avatar-editor', [messageBundleNg, IconNG]);\n\n/**\n * @name Avatar Editor Ng\n */\nfunction rgAvatarEditor() {\n return {\n restrict: 'E',\n scope: {\n model: '=ngModel',\n onSelect: '&',\n default: '@',\n ngDisabled: '=',\n showDeleteButton: '=?',\n showAddButton: '=?',\n deleteLabel: '@',\n addMessage: '@'\n },\n template: require('./avatar-editor-ng.html'),\n transclude: true,\n controller: [\n '$scope', '$attrs', 'RingMessageBundle',\n function controller($scope, $attrs, RingMessageBundle) {\n let fileInput;\n $scope.editIcon = pencilIcon;\n $scope.showAddButton = 'showAddButton' in $scope ? $scope.showAddButton : true;\n $scope.showDeleteButton = 'showDeleteButton' in $scope ? $scope.showDeleteButton : true;\n\n if ('controls' in $attrs) {\n $scope.controlled = true;\n }\n\n function createFileLoadListener(file) {\n return readEvent => {\n const data = readEvent.target.result;\n const result = $scope.onSelect({name: file.name, data});\n if (result && result.then) {\n result.then(() => {\n $scope.model = data;\n });\n } else if (result !== false) {\n $scope.$apply(() => {\n $scope.model = data;\n });\n }\n };\n }\n\n this.registerFileInput = input => {\n fileInput = input;\n fileInput.addEventListener('change', e => {\n let imageFileSelected = false;\n for (let i = 0; i < e.target.files.length; i++) {\n const file = e.target.files[i];\n if (file.type.indexOf('image/') === 0) {\n imageFileSelected = true;\n const reader = new FileReader();\n reader.onload = createFileLoadListener(file);\n reader.readAsDataURL(file);\n break;\n }\n }\n if (e.target.files.length && !imageFileSelected) {\n alertService.error(RingMessageBundle.avatareditor_noselected());\n }\n });\n };\n\n $scope.controls = {};\n\n function onClick(e) {\n e.stopPropagation();\n }\n\n $scope.controls.select = () => {\n if (!FileReader) {\n alertService.error(RingMessageBundle.avatareditor_nosupport());\n } else {\n fileInput.addEventListener('click', onClick);\n fileInput.dispatchEvent(new MouseEvent('click'));\n fileInput.removeEventListener('click', onClick);\n }\n };\n\n $scope.controls.remove = () => {\n const data = '';\n const result = $scope.onSelect({name: data, data});\n if (result && result.then) {\n result.then(() => {\n $scope.model = data;\n });\n } else if (result !== false) {\n $scope.model = data;\n }\n };\n\n $scope.getDeleteLabel = () => (\n $scope.deleteLabel || RingMessageBundle.avatareditor_delete()\n );\n\n $scope.getAddMessage = () => (\n $scope.addMessage || RingMessageBundle.avatareditor_add()\n );\n }\n ]\n };\n}\n\nfunction rgAvatarEditorFileInput() {\n return {\n restrict: 'A',\n require: '^rgAvatarEditor',\n link: function link(scope, iElement, iAttrs, avatarEditorCtrl) {\n avatarEditorCtrl.registerFileInput(iElement[0]);\n }\n };\n}\n\nangularModule.directive('rgAvatarEditor', rgAvatarEditor);\nangularModule.directive('rgAvatarEditorFileInput', rgAvatarEditorFileInput);\n\nexport default angularModule.name;\n","import React, {Component} from 'react';\nimport PropTypes from 'prop-types';\n\nexport default class Renderer extends Component {\n static propTypes = {\n className: PropTypes.string,\n nodes: PropTypes.array\n };\n\n componentDidMount() {\n const {nodes} = this.props;\n if (!this.node || !nodes || !nodes.length) {\n return;\n }\n const fragment = document.createDocumentFragment();\n nodes.forEach(nodeToRender => fragment.appendChild(nodeToRender));\n\n this.node.appendChild(fragment);\n }\n\n nodeRef = node => {\n this.node = node;\n };\n\n render() {\n const {className} = this.props;\n return (\n \n );\n }\n}\n","import angular from 'angular';\n\nimport React from 'react';\nimport {render, unmountComponentAtNode} from 'react-dom';\n\nimport RingAngularComponent from './ring-angular-component';\n\nimport DomRenderer from './react-dom-renderer';\n\nfunction getAngularComponentName(name) {\n return `rg${name}`;\n}\n\nfunction createAngularComponent(Component) {\n const propKeys = Object.keys(Component.propTypes);\n\n const bindings = {};\n propKeys.forEach(key => {\n bindings[key] = '<';\n });\n\n return class AngularComponent extends RingAngularComponent {\n static $inject = ['$scope', '$element', '$transclude'];\n\n static bindings = bindings;\n static transclude = true;\n\n $postLink() {\n const {$transclude} = this.$inject;\n\n $transclude(clone => {\n this.innerNodes = Array.from(clone);\n this.render();\n });\n }\n\n $onChanges() {\n if (!this.innerNodes) {\n return;\n }\n this.render();\n }\n\n $onDestroy() {\n unmountComponentAtNode(this.$inject.$element[0]);\n }\n\n render() {\n const {$scope, $element: {0: container}} = this.$inject;\n\n const props = {};\n propKeys.forEach(key => {\n if (this[key] !== undefined) {\n if (typeof this[key] === 'function') {\n props[key] = (...rest) => {\n const ret = this[key](...rest);\n $scope.$applyAsync();\n return ret;\n };\n } else {\n props[key] = this[key];\n }\n }\n });\n\n const hasInnerContent = this.innerNodes && this.innerNodes.length;\n\n render(\n \n {hasInnerContent ? : null}\n ,\n container\n );\n }\n };\n}\n\nfunction angularComponentFactory(Component, name) {\n const angularModuleName = `Ring.${name[0].toLowerCase() + name.slice(1)}`;\n\n return angular.\n module(angularModuleName, []).\n component(getAngularComponentName(name), createAngularComponent(Component));\n}\n\nexport default angularComponentFactory;\nexport {createAngularComponent};\n","/**\n * @name Avatar Ng\n */\nimport angularComponentFactory from '../global/angular-component-factory';\nimport Avatar from '../avatar/avatar';\n\nexport default angularComponentFactory(Avatar, 'Avatar').name;\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport dataTests from '../global/data-tests';\n\nimport style from './badge.css';\n\n/**\n * @name Badge\n */\nexport default class Badge extends PureComponent {\n static propTypes = {\n gray: PropTypes.bool,\n valid: PropTypes.bool,\n invalid: PropTypes.bool,\n disabled: PropTypes.bool,\n className: PropTypes.string,\n children: PropTypes.node,\n 'data-test': PropTypes.string\n };\n\n render() {\n const {\n // Modifiers\n gray,\n valid,\n invalid,\n disabled,\n\n // Props\n className,\n children,\n 'data-test': dataTest,\n ...props\n } = this.props;\n\n const classes = classNames(\n style.badge,\n className,\n {\n [style.gray]: gray,\n [style.valid]: valid,\n [style.invalid]: invalid,\n [style.disabled]: disabled\n }\n );\n\n return (\n \n {children}\n \n );\n }\n}\n","/**\n * @name Badge Ng\n*/\n\nimport angularComponentFactory from '../global/angular-component-factory';\nimport BadgeNg from '../badge/badge';\n\nexport default angularComponentFactory(BadgeNg, 'Badge').name;\n","import angular from 'angular';\n\nimport styles from '../link/link.css';\n\n/**\n * @name Link Ng\n */\n\n\nconst angularModule = angular.module('Ring.link', []);\n\nfunction rgLinkDirective() {\n return {\n restrict: 'E',\n transclude: true,\n replace: true,\n template: `\n\n `\n };\n}\n\nangularModule.directive('rgLink', rgLinkDirective);\n\nexport default angularModule.name;\n","import angular from 'angular';\n\nimport chevronRight from '@jetbrains/icons/chevron-right.svg';\n\nimport '../breadcrumb/breadcrumb.scss';\nimport LinkModule from '../link-ng/link-ng';\nimport IconModule from '../icon-ng/icon-ng';\n\n/**\n * @name Breadcrumb Ng\n */\n\n\nconst angularModule = angular.module('Ring.breadcrumb', [LinkModule, IconModule]);\n\nangularModule.filter('breadcrumbNgChevronIcon', () => () => chevronRight);\n\nangularModule.directive('rgBreadcrumb', function rgBreadcrumbDirective() {\n return {\n template: require('./breadcrumb-ng.html'),\n replace: true,\n transclude: true,\n restrict: 'E',\n\n scope: {\n label: '@',\n link: '@',\n onClick: '&'\n }\n };\n});\n\nexport default angularModule.name;\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport styles from './button-group.css';\n\nexport default class Caption extends PureComponent {\n static propTypes = {\n className: PropTypes.node\n }\n\n render() {\n const {className} = this.props;\n const classes = classNames(styles.caption, className);\n\n return (\n \n );\n }\n}\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport Caption from './caption';\nimport styles from './button-group.css';\n\n/**\n * @name Button Group\n */\nexport default class ButtonGroup extends PureComponent {\n static propTypes = {\n children: PropTypes.node,\n className: PropTypes.string\n }\n\n render() {\n const {className} = this.props;\n const classes = classNames(styles.buttonGroup, className);\n\n return (\n \n );\n }\n}\n\nexport {Caption};\n","import angular from 'angular';\n\nimport classNames from 'classnames';\nimport 'dom4';\n\nimport styles from '../button-group/button-group.css';\n\nimport {buttonGroup} from './button-group-ng.css';\n\n/**\n * @name Button Group Ng\n */\n\nconst angularModule = angular.module('Ring.button-group', []);\nconst buttonGroupClasses = classNames(styles.buttonGroup, buttonGroup);\n\nfunction rgButtonGroup() {\n return {\n restrict: 'A',\n link: function link($scope, iElement) {\n const element = iElement[0];\n element.classList.add(...buttonGroupClasses.split(' '));\n }\n };\n}\n\nfunction rgButtonGroupCaption() {\n return {\n restrict: 'A',\n link: function link($scope, iElement) {\n const element = iElement[0];\n element.classList.add(...styles.caption.split(' '));\n }\n };\n}\n\nangularModule.directive('rgButtonGroup', rgButtonGroup);\nangularModule.directive('rgButtonGroupCaption', rgButtonGroupCaption);\n\nexport default angularModule.name;\n","import angular from 'angular';\n\nimport 'dom4';\nimport classNames from 'classnames';\n\nimport RingAngularComponent from '../global/ring-angular-component';\nimport {addClasses, applyMethodToClasses, removeClasses} from '../global/dom';\nimport IconNG from '../icon-ng/icon-ng';\nimport Theme, {applyTheme} from '../global/theme';\nimport styles from '../button/button.css';\n\nimport overrides from './button-ng.css';\n\nconst {ringIconDefaultColor, iconMarginFix, transcludeSpacer} = overrides;\n\n/**\n * @name Button Ng\n */\n\n\nconst angularModule = angular.module('Ring.button', [IconNG]);\nconst ORDER_NOT_DEFINED = '-1';\nconst buttonClasses = classNames(\n styles.button,\n styles.buttonWithoutIcon,\n styles.light\n);\n\nexport const LOADER_BACKGROUND_SELECTOR = '.js-button-loader';\n\nclass ButtonController extends RingAngularComponent {\n static $inject = ['$element', '$attrs', '$scope', '$compile', '$log'];\n\n constructor(...args) {\n super(...args);\n\n const {$element, $attrs, $scope} = this.$inject;\n $scope.styles = styles;\n this.element = $element[0];\n\n const modifiers = ['delayed', 'loader', 'danger', 'short', 'active', 'text', 'inline', 'narrowRight'];\n const cl = this.element.classList;\n\n modifiers.forEach(mod => {\n $scope.$watch(() => $scope.$eval($attrs[mod]), val => {\n const attrName = `data-test-${mod}`;\n\n if (val) {\n addClasses(cl, styles[mod]);\n this.element.setAttribute(attrName, true);\n } else {\n removeClasses(cl, styles[mod]);\n this.element.removeAttribute(attrName);\n }\n\n if (mod === 'loader') {\n applyMethodToClasses(val ? 'add' : 'remove')(\n this.element.querySelector(LOADER_BACKGROUND_SELECTOR).classList,\n styles.loaderBackground\n );\n }\n });\n });\n\n const tabIndex = $attrs.tabindex || ORDER_NOT_DEFINED;\n if (tabIndex !== ORDER_NOT_DEFINED) {\n this.element.setAttribute('tabindex', tabIndex);\n }\n\n $scope.$watch(() => $scope.$eval($attrs.loader), val => {\n if (val) {\n this.element.setAttribute('tabindex', ORDER_NOT_DEFINED);\n } else if (tabIndex !== ORDER_NOT_DEFINED) {\n this.element.setAttribute('tabindex', tabIndex);\n } else {\n this.element.removeAttribute('tabindex');\n }\n });\n }\n\n $postLink() {\n const {$attrs} = this.$inject;\n if (!$attrs.hasOwnProperty('mode')) {\n addClasses(this.findTranscludeNode().classList, ringIconDefaultColor);\n }\n $attrs.$observe('mode', this.updateMode);\n $attrs.$observe('icon', this.updateIcon);\n $attrs.$observe('iconSize', this.updateIcon);\n $attrs.$observe('theme', this.updateTheme);\n }\n\n updateTheme = themeName => {\n if (isValidTheme(themeName)) {\n changeTheme(this.element, {currentTheme: themeName});\n }\n };\n\n findTranscludeNode = () => this.element.query('ng-transclude');\n\n updateMode = val => {\n const cl = this.element.classList;\n if (val === 'primary' || val === 'blue') {\n // Deprecation fallback. Someone please remove this one day.\n if (val === 'blue') {\n this.$inject.$log.warn(\n 'Ring UI ButtonNG doesn\\'t have \"blue\" mode anymore. Use \"primary\" mode instead.',\n this.element\n );\n }\n\n addClasses(cl, styles.primary);\n } else {\n removeClasses(cl, styles.primary);\n }\n };\n\n updateIcon = () => {\n const {$attrs, $compile, $scope} = this.$inject;\n const icon = this.element.query('rg-icon');\n const transcludeNode = this.findTranscludeNode();\n const glyph = $attrs.icon;\n const size = $attrs.iconSize;\n const cl = this.element.classList;\n\n if (glyph) {\n removeClasses(cl, styles.buttonWithoutIcon);\n addClasses(cl, styles.withIcon);\n addClasses(transcludeNode.classList, transcludeSpacer);\n icon.setAttribute('glyph', glyph);\n if (size) {\n icon.setAttribute('size', size);\n }\n } else {\n removeClasses(cl, styles.withIcon);\n addClasses(cl, styles.buttonWithoutIcon);\n removeClasses(transcludeNode.classList, transcludeSpacer);\n icon.removeAttribute('glyph');\n icon.removeAttribute('size');\n }\n\n if (glyph && !transcludeNode.textContent) {\n addClasses(cl, styles.onlyIcon);\n } else {\n removeClasses(cl, styles.onlyIcon);\n }\n\n $compile(icon)($scope);\n }\n}\n\n\nfunction isValidTheme(themeName) {\n return themeName && Object.values(Theme).some(theme => theme === themeName);\n}\n\nfunction changeTheme(element, data) {\n return applyTheme({\n element,\n prevTheme: data.prevTheme && styles[data.prevTheme] || styles.light,\n currentTheme: styles[data.currentTheme]\n });\n}\n\nfunction createButtonDirective(tagName) {\n return () => ({\n restrict: 'E',\n transclude: true,\n replace: true,\n require: {\n rgThemeCtrl: '?^^rgTheme'\n },\n template: `\n <${tagName} class=\"${buttonClasses}\">\n
\n \n `,\n controller: ButtonController,\n link: (scope, element, attrs, {rgThemeCtrl}) => {\n if (rgThemeCtrl) {\n changeTheme(element[0], {currentTheme: rgThemeCtrl.theme});\n rgThemeCtrl.on('change', (event, data) => changeTheme(element[0], data));\n }\n }\n });\n}\n\n\nangularModule.directive('rgButton', createButtonDirective('button'));\nangularModule.directive('rgButtonLink', createButtonDirective('a'));\n\nexport default angularModule.name;\n","import React, {PureComponent} from 'react';\nimport classNames from 'classnames';\nimport PropTypes from 'prop-types';\n\nimport styles from './button-set.css';\n\n/**\n * @name Button Set\n */\nexport default class ButtonSet extends PureComponent {\n static propTypes = {\n children: PropTypes.node,\n className: PropTypes.string\n };\n\n render() {\n const classes = classNames(styles.buttonSet, this.props.className);\n return (\n \n {this.props.children}\n \n );\n }\n}\n","/**\n * @name Button Set Ng\n */\nimport angular from 'angular';\n\nconst angularModule = angular.module('Ring.button-set', []);\n\nfunction rgButtonSet() {\n return {\n restrict: 'E',\n replace: true,\n scope: false,\n transclude: true,\n template: require('./button-set-ng.html')\n };\n}\n\nangularModule.directive('rgButtonSet', rgButtonSet);\n\nexport default angularModule.name;\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport styles from './button-toolbar.css';\n\n/**\n * @name Button Toolbar\n*/\n\nexport default class ButtonToolbar extends PureComponent {\n static propTypes = {\n children: PropTypes.node,\n className: PropTypes.string\n };\n\n render() {\n const {className} = this.props;\n const classes = classNames(styles.buttonToolbar, className);\n\n return (\n \n );\n }\n}\n\n","import {getRect} from '../global/dom';\n\n/**\n * @name Caret\n */\n\nexport default class Caret {\n /**\n * Line endings RegExp\n * @type {RegExp}\n */\n static returnRE = /\\r/g;\n\n /**\n * Line endings normalizer\n * Borrowed from jQuery\n * @see https://github.com/jquery/jquery/blob/master/src/attributes/val.js\n * @param value {*}\n * @return {*}\n */\n static normalizeNewlines(value) {\n return typeof value === 'string' ? value.replace(this.returnRE, '') : value;\n }\n\n constructor(target) {\n this.target = target;\n }\n\n isContentEditable() {\n return this.target.contentEditable === 'true';\n }\n\n /**\n * Set focus on target if possible\n */\n focus() {\n if (!document.activeElement || document.activeElement !== this.target) {\n this.target.focus();\n }\n }\n\n /**\n * Get caret position index\n * @return {number}\n */\n getPosition() {\n if (this.isContentEditable()) {\n this.focus();\n\n const selection = window.getSelection();\n\n if (!selection.rangeCount) {\n return 0;\n }\n\n const range1 = selection.getRangeAt(0);\n const range2 = range1.cloneRange();\n\n range2.selectNodeContents(this.target);\n range2.setEnd(range1.endContainer, range1.endOffset);\n\n if (range1.startOffset !== range1.endOffset) {\n return {startOffset: range1.startOffset,\n endOffset: range1.endOffset,\n position: range2.toString().length};\n }\n return range2.toString().length;\n }\n\n return this.target.selectionStart;\n }\n\n /**\n * Get relative position of query\n * @param {Node} curNode\n * @param {number} position\n * @return {{_correctedPosition: number, _curNode: Node}}\n */\n getRelativePosition(curNode, position) {\n let curPos = 0;\n let _curNode = curNode;\n const nodeTypeText = 3;\n if (!_curNode) {\n return {_curNode: this.target, _correctedPosition: position};\n }\n if (position === 0) {\n while (_curNode.nodeType !== nodeTypeText) {\n _curNode = _curNode.childNodes[0];\n }\n const _correctedPosition = position;\n return {_curNode, _correctedPosition};\n }\n let i = -1;\n if (_curNode && _curNode.nodeType !== undefined) {\n while (curPos < position && _curNode.nodeType !== nodeTypeText) {\n i++;\n if (_curNode.childNodes[i] !== null && _curNode.childNodes[i]) {\n curPos += _curNode.childNodes[i].textContent.length;\n if (curPos >= position) {\n _curNode = _curNode.childNodes[i];\n curPos -= _curNode.textContent.length;\n i = -1;\n }\n } else {\n break;\n }\n }\n }\n const _correctedPosition = position - curPos;\n return {_curNode, _correctedPosition};\n }\n\n /**\n * Set caret position index\n * @param {number} position\n * @return {number}\n */\n setPosition(position) {\n const isContentEditable = this.isContentEditable();\n let correctedPosition;\n let curNode = this.target && this.target.childNodes[0];\n if (position !== undefined) {\n if (position.startOffset !== undefined) {\n const range = new Range();\n const start = this.getRelativePosition(curNode, position.startOffset);\n range.setStart(start._curNode, start._correctedPosition);\n const end = this.getRelativePosition(curNode, position.endOffset);\n range.setEnd(end._curNode, end._correctedPosition);\n correctedPosition = range;\n } else if (position === -1) {\n const value = isContentEditable\n ? this.target.textContent\n : this.constructor.normalizeNewlines(this.target.value);\n correctedPosition = value.length;\n } else {\n const {_curNode, _correctedPosition} = this.getRelativePosition(curNode, position);\n curNode = _curNode;\n correctedPosition = _correctedPosition;\n }\n }\n\n if (isContentEditable) {\n this.focus();\n\n try {\n if (correctedPosition instanceof Range) {\n window.getSelection().removeAllRanges();\n window.getSelection().addRange(correctedPosition);\n } else {\n window.getSelection().collapse(curNode || this.target, correctedPosition);\n }\n } catch (e) {\n // Do nothing\n }\n\n } else {\n this.target.setSelectionRange(correctedPosition, correctedPosition);\n }\n\n return correctedPosition;\n }\n\n /**\n * Get caret position in pixels\n * @return {number}\n */\n getOffset() {\n let offset = 0;\n let range;\n\n try {\n // Both statements may throw\n range = window.getSelection().getRangeAt(0).cloneRange();\n range.setStart(range.startContainer, range.startOffset - 1);\n } catch (e) {\n return offset;\n }\n\n if (range && range.endOffset !== 0 && range.toString() !== '') {\n offset =\n getRect(range).right -\n getRect(this.target).left -\n (range.startContainer.offsetLeft || 0);\n }\n\n return offset;\n }\n}\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport checkmarkIcon from '@jetbrains/icons/checkmark.svg';\n\nimport Icon from '../icon/icon';\n\nimport styles from './checkbox.css';\n\n/**\n * @name Checkbox\n */\nexport default class Checkbox extends PureComponent {\n\n static propTypes = {\n name: PropTypes.string,\n label: PropTypes.string,\n className: PropTypes.string,\n defaultChecked: PropTypes.bool,\n checked: PropTypes.bool,\n disabled: PropTypes.bool,\n onChange: PropTypes.func,\n children: PropTypes.node\n };\n\n inputRef = el => {\n this.input = el;\n };\n\n render() {\n const {children, label, ...restProps} = this.props;\n\n const classes = classNames(\n styles.input,\n this.props.className\n );\n\n return (\n \n \n \n \n \n {label || children}\n \n );\n }\n}\n","function proxyAttrs(template, attrsWhitelist) {\n return function copyAttrs(iElement, iAttrs) {\n const PREFIX = 'data-proxy-';\n\n const attrsList = attrsWhitelist || Object.keys(iAttrs.$attr);\n let resultTemplate = template;\n\n attrsList.forEach(attrName => {\n if (iAttrs[attrName] !== undefined) {\n const attrLower = iAttrs.$attr[attrName];\n const attrValue = iAttrs[attrName];\n\n const attrFind = `${PREFIX}${attrLower}`.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n const attrReplace = `${attrLower}=\"${attrValue}\"`;\n\n resultTemplate = resultTemplate.replace(RegExp(`${attrFind}(=\"\")*`, 'g'), attrReplace);\n }\n });\n\n return resultTemplate;\n };\n}\n\nexport default proxyAttrs;\n","import angular from 'angular';\n\nimport checkmarkIcon from '@jetbrains/icons/checkmark.svg';\n\nimport IconNG from '../icon-ng/icon-ng';\nimport proxyAttrs from '../proxy-attrs/proxy-attrs';\n\nimport styles from '../checkbox/checkbox.css';\n\n/**\n * @name Checkbox Ng\n */\n\nconst angularModule = angular.module('Ring.checkbox', [IconNG]);\n\nlet idCounter = 0;\nconst CHECKBOX_ID_PREFIX = 'rg-checkbox-';\n\nangularModule.directive('rgCheckbox', function rgCheckboxDirective() {\n return {\n restrict: 'E',\n transclude: true,\n replace: true,\n template: proxyAttrs(`\n\n `),\n link: function link(scope, iElement) {\n scope.checkmarkIcon = checkmarkIcon;\n const input = iElement[0].query('input[type=\"checkbox\"]');\n\n const id = CHECKBOX_ID_PREFIX + idCounter++;\n iElement[0].setAttribute('for', id);\n input.setAttribute('id', id);\n }\n };\n});\n\nexport default angularModule.name;\n","export default function normalizeIndent(string) {\n const nonemptyRE = /\\S/;\n const indentRE = /^\\s*/;\n\n const lines = string.split(/\\n/g);\n const linesCopy = [...lines];\n\n //remove empty lines at the beginning and the end\n for (const line of linesCopy) {\n if (nonemptyRE.test(line)) {\n break;\n } else {\n lines.shift();\n }\n }\n\n for (const line of linesCopy.reverse()) {\n if (nonemptyRE.test(line)) {\n break;\n } else {\n lines.pop();\n }\n }\n\n const indents = lines.\n filter(line => nonemptyRE.test(line)).\n map(line => line.match(indentRE)[0].length);\n\n const minIndent = Math.min(...indents);\n\n return lines.\n map(line => line.slice(minIndent)).\n join('\\n');\n}\n","const TWO = 2;\n\nexport default function trivialTemplateTag(f) {\n return (strings, ...interpolations) => {\n const chunks = [...strings];\n // insert the interpolations where they belong to\n interpolations.forEach((value, i) =>\n chunks.splice(TWO * i + 1, 0, value));\n return f(chunks.join(''));\n };\n}\n","import highlight from 'highlight.js/lib/highlight';\nimport './highlight.css';\n\nimport cpp from 'highlight.js/lib/languages/cpp';\nimport xml from 'highlight.js/lib/languages/xml';\nimport bash from 'highlight.js/lib/languages/bash';\nimport clojure from 'highlight.js/lib/languages/clojure';\nimport coffeescript from 'highlight.js/lib/languages/coffeescript';\nimport cs from 'highlight.js/lib/languages/cs';\nimport css from 'highlight.js/lib/languages/css';\nimport markdown from 'highlight.js/lib/languages/markdown';\nimport dockerfile from 'highlight.js/lib/languages/dockerfile';\nimport elixir from 'highlight.js/lib/languages/elixir';\nimport elm from 'highlight.js/lib/languages/elm';\nimport ruby from 'highlight.js/lib/languages/ruby';\nimport erlang from 'highlight.js/lib/languages/erlang';\nimport glsl from 'highlight.js/lib/languages/glsl';\nimport go from 'highlight.js/lib/languages/go';\nimport gradle from 'highlight.js/lib/languages/gradle';\nimport groovy from 'highlight.js/lib/languages/groovy';\nimport handlebars from 'highlight.js/lib/languages/handlebars';\nimport haskell from 'highlight.js/lib/languages/haskell';\nimport java from 'highlight.js/lib/languages/java';\nimport javascript from 'highlight.js/lib/languages/javascript';\nimport json from 'highlight.js/lib/languages/json';\nimport kotlin from 'highlight.js/lib/languages/kotlin';\nimport less from 'highlight.js/lib/languages/less';\nimport livescript from 'highlight.js/lib/languages/livescript';\nimport lua from 'highlight.js/lib/languages/lua';\nimport makefile from 'highlight.js/lib/languages/makefile';\nimport perl from 'highlight.js/lib/languages/perl';\nimport php from 'highlight.js/lib/languages/php';\nimport powershell from 'highlight.js/lib/languages/powershell';\nimport python from 'highlight.js/lib/languages/python';\nimport r from 'highlight.js/lib/languages/r';\nimport rust from 'highlight.js/lib/languages/rust';\nimport scala from 'highlight.js/lib/languages/scala';\nimport scss from 'highlight.js/lib/languages/scss';\nimport shell from 'highlight.js/lib/languages/shell';\nimport sql from 'highlight.js/lib/languages/sql';\nimport swift from 'highlight.js/lib/languages/swift';\nimport yaml from 'highlight.js/lib/languages/yaml';\nimport twig from 'highlight.js/lib/languages/twig';\nimport typescript from 'highlight.js/lib/languages/typescript';\n\nhighlight.registerLanguage('cpp', cpp);\nhighlight.registerLanguage('xml', xml);\nhighlight.registerLanguage('bash', bash);\nhighlight.registerLanguage('clojure', clojure);\nhighlight.registerLanguage('coffeescript', coffeescript);\nhighlight.registerLanguage('cs', cs);\nhighlight.registerLanguage('css', css);\nhighlight.registerLanguage('markdown', markdown);\nhighlight.registerLanguage('dockerfile', dockerfile);\nhighlight.registerLanguage('elixir', elixir);\nhighlight.registerLanguage('elm', elm);\nhighlight.registerLanguage('ruby', ruby);\nhighlight.registerLanguage('erlang', erlang);\nhighlight.registerLanguage('glsl', glsl);\nhighlight.registerLanguage('go', go);\nhighlight.registerLanguage('gradle', gradle);\nhighlight.registerLanguage('groovy', groovy);\nhighlight.registerLanguage('handlebars', handlebars);\nhighlight.registerLanguage('haskell', haskell);\nhighlight.registerLanguage('java', java);\nhighlight.registerLanguage('javascript', javascript);\nhighlight.registerLanguage('json', json);\nhighlight.registerLanguage('kotlin', kotlin);\nhighlight.registerLanguage('less', less);\nhighlight.registerLanguage('livescript', livescript);\nhighlight.registerLanguage('lua', lua);\nhighlight.registerLanguage('makefile', makefile);\nhighlight.registerLanguage('perl', perl);\nhighlight.registerLanguage('php', php);\nhighlight.registerLanguage('powershell', powershell);\nhighlight.registerLanguage('python', python);\nhighlight.registerLanguage('r', r);\nhighlight.registerLanguage('rust', rust);\nhighlight.registerLanguage('scala', scala);\nhighlight.registerLanguage('scss', scss);\nhighlight.registerLanguage('shell', shell);\nhighlight.registerLanguage('sql', sql);\nhighlight.registerLanguage('swift', swift);\nhighlight.registerLanguage('yaml', yaml);\nhighlight.registerLanguage('twig', twig);\nhighlight.registerLanguage('typescript', typescript);\n\nexport default highlight;\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport normalizeIndent from '../global/normalize-indent';\nimport trivialTemplateTag from '../global/trivial-template-tag';\n\nimport highlight from './highlight';\nimport styles from './code.css';\nimport highlightStyles from './highlight.css';\n\nfunction noop() {}\n\n/**\n * @name Code\n */\n\nexport default class Code extends PureComponent {\n static propTypes = {\n className: PropTypes.string,\n code: PropTypes.string.isRequired,\n inline: PropTypes.bool,\n softWrap: PropTypes.bool,\n language: PropTypes.string,\n replacer: PropTypes.func,\n codeRef: PropTypes.oneOfType([\n PropTypes.shape({current: PropTypes.instanceOf(Element)}),\n PropTypes.func\n ])\n };\n\n static defaultProps = {\n inline: false,\n softWrap: false,\n replacer: noop\n };\n\n componentDidMount() {\n this.highlight();\n }\n\n componentDidUpdate() {\n this.highlight();\n }\n\n highlight() {\n if (!this.props.inline) {\n highlight.highlightBlock(this.codeRef);\n }\n this.props.replacer(this.codeRef);\n }\n\n get codeRef() {\n const {codeRef} = this.props;\n return !codeRef || this.isFunctionCodeRef ? this.code : codeRef.current;\n }\n\n get isFunctionCodeRef() {\n return typeof (this.props.codeRef) === 'function';\n }\n\n get initCodeRef() {\n const {codeRef} = this.props;\n if (codeRef && !this.isFunctionCodeRef) {\n return codeRef;\n }\n return ref => {\n this.code = ref;\n if (this.isFunctionCodeRef) {\n codeRef(this.code);\n }\n };\n }\n\n render() {\n const {code, className, inline, softWrap, language} = this.props;\n\n const Tag = inline ? 'span' : 'pre';\n const classes = classNames(styles.code, className, language, {\n [styles.inline]: inline,\n [styles.softWrap]: softWrap\n });\n\n return (\n \n \n {normalizeIndent(code)}\n \n \n );\n }\n}\n\nconst code = trivialTemplateTag(source => );\n\nexport {code, highlight};\n","/**\n * @name Compiler Ng\n */\nimport angular from 'angular';\n\nconst angularModule = angular.module('Ring.compiler', []).\n factory('rgCompiler', function rgCompilerFactory($q, $controller, $injector, $compile) {\n return options => {\n const template = options.template;\n const controller = options.controller;\n const controllerAs = options.controllerAs;\n const resolve = angular.extend({}, options.resolve);\n const bindToController = options.bindToController;\n\n angular.forEach(resolve, (value, key) => {\n if (angular.isString(value)) {\n resolve[key] = $injector.get(value);\n } else {\n // Use comma expression to disable babel-plugin-angular-annotate\n // Otherwise is fails with \"Maximum call stack size exceeded\" error\n resolve[key] = $injector.invoke((0, value));\n }\n });\n\n angular.extend(resolve, options.locals);\n\n return $q.all(resolve).then(locals => {\n const element = options.element || angular.element('
').\n html(template.trim()).\n contents();\n const linkFn = $compile(element, locals.$transclude);\n locals.$element = element;\n\n return {\n locals,\n element,\n link: function link(scope) {\n locals.$scope = scope;\n\n if (controller) {\n const invokeCtrl = $controller(controller, locals, true);\n\n if (bindToController) {\n angular.extend(invokeCtrl.instance, locals);\n }\n\n const ctrl = invokeCtrl();\n\n element.data('$ngControllerController', ctrl);\n\n if (controllerAs) {\n scope[controllerAs] = ctrl;\n }\n }\n\n return linkFn(scope);\n }\n };\n });\n };\n });\n\nexport default angularModule.name;\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport styles from './panel.css';\n\n/**\n * @name Panel\n */\nexport default class Panel extends PureComponent {\n static propTypes = {\n className: PropTypes.string,\n children: PropTypes.node\n };\n\n render() {\n const {className, children, ...props} = this.props;\n const classes = classNames(styles.panel, className);\n return (\n \n {children}\n
\n );\n }\n}\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\n\nimport Dialog from '../dialog/dialog';\nimport Button from '../button/button';\nimport {Content, Header} from '../island/island';\nimport Panel from '../panel/panel';\n\nimport styles from './confirm.css';\n\n/**\n * @name Confirm\n */\n\nexport default class Confirm extends PureComponent {\n static propTypes = {\n className: PropTypes.string,\n text: PropTypes.string,\n description: PropTypes.node,\n\n show: PropTypes.bool,\n rejectOnEsc: PropTypes.bool,\n inProgress: PropTypes.bool,\n cancelIsDefault: PropTypes.bool,\n confirmLabel: PropTypes.string,\n rejectLabel: PropTypes.string,\n\n onConfirm: PropTypes.func,\n onReject: PropTypes.func\n };\n\n static defaultProps = {\n text: null,\n description: null,\n show: false,\n rejectOnEsc: true,\n inProgress: false,\n cancelIsDefault: false,\n confirmLabel: 'OK',\n rejectLabel: 'Cancel',\n onConfirm: () => {},\n onReject: () => {}\n };\n\n onEscPress = () => {\n if (this.props.rejectOnEsc) {\n this.props.onReject();\n }\n };\n\n render() {\n const {\n show,\n className,\n inProgress,\n cancelIsDefault,\n text,\n description,\n confirmLabel,\n rejectLabel,\n onConfirm,\n onReject\n } = this.props;\n\n return (\n \n {text &&
{text}
}\n \n {description &&
{description}
}\n
\n \n \n {confirmLabel}\n \n \n {rejectLabel}\n \n \n \n );\n }\n}\n\n","import React from 'react';\nimport {render} from 'react-dom';\n\nimport Confirm from '../confirm/confirm';\n\n/**\n * @name Confirm Service\n */\n\nexport const containerElement = document.createElement('div');\n\n/**\n * Renders Confirm into virtual node to skip maintaining container\n */\nfunction renderConfirm(props) {\n render(, containerElement);\n}\n\nexport default function confirm({\n text,\n description,\n confirmLabel = 'OK',\n rejectLabel = 'Cancel',\n cancelIsDefault,\n onBeforeConfirm\n}) {\n return new Promise((resolve, reject) => {\n const props = {\n text,\n description,\n confirmLabel,\n rejectLabel,\n cancelIsDefault,\n show: true,\n\n onConfirm: () => {\n if (onBeforeConfirm) {\n renderConfirm({...props, inProgress: true});\n return Promise.resolve(onBeforeConfirm()).\n then(() => {\n renderConfirm({show: false});\n resolve();\n }).\n catch(err => {\n renderConfirm({show: false});\n reject(err);\n });\n }\n renderConfirm({show: false});\n return resolve();\n },\n\n onReject: () => {\n renderConfirm({show: false});\n reject(new Error('Confirm(@jetbrains/ring-ui): null exception'));\n }\n };\n\n renderConfirm(props);\n });\n}\n\nexport function hideConfirm() {\n renderConfirm({show: false});\n}\n","import angular from 'angular';\n\nimport confirm from '../confirm-service/confirm-service';\nimport MessageBundle from '../message-bundle-ng/message-bundle-ng';\n\n/**\n * @name Confirm Ng\n */\n\nconst angularModule = angular.module('Ring.confirm', [\n MessageBundle\n]);\n\nangularModule.service('confirm', function service($q, RingMessageBundle) {\n return function showConfirm(\n message, description, actionTitle, cancelTitle,\n cancelIsDefault, actionFn\n ) {\n return $q.when(confirm({\n text: message,\n description,\n confirmLabel: actionTitle || RingMessageBundle.confirmation_ok(),\n rejectLabel: cancelTitle || RingMessageBundle.confirmation_cancel(),\n cancelIsDefault,\n onBeforeConfirm: actionFn\n }));\n };\n});\n\nexport default angularModule.name;\n","import React, {Component} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport {Waypoint} from 'react-waypoint';\n\nimport styles from './content-layout.css';\n\nconst ABOVE = 'above';\nconst INSIDE = 'inside';\n\nexport default class Sidebar extends Component {\n static propTypes = {\n right: PropTypes.bool,\n children: PropTypes.node,\n className: PropTypes.string,\n containerClassName: PropTypes.string,\n fixedClassName: PropTypes.string,\n contentNode: PropTypes.object\n };\n\n state = {\n topIsOutside: true,\n bottomIsOutside: true\n };\n\n handleTopWaypoint = ({currentPosition}) => {\n this.setState({topIsOutside: currentPosition === ABOVE});\n };\n\n handleBottomWaypoint = ({currentPosition, waypointTop}) => {\n this.setState({\n sidebarVisibleHeight: waypointTop,\n bottomIsOutside: currentPosition !== INSIDE\n });\n };\n\n shouldUseFixation() {\n const {contentNode} = this.props;\n const {sidebarNode} = this;\n if (!contentNode || !sidebarNode) {\n return false;\n }\n return contentNode.offsetHeight >= sidebarNode.offsetHeight;\n }\n\n shouldFixateBottom() {\n const {topIsOutside, bottomIsOutside} = this.state;\n return !bottomIsOutside && topIsOutside && this.shouldUseFixation();\n }\n\n sidebarRef = node => {\n this.sidebarNode = node;\n };\n\n render() {\n const {right, children, className, containerClassName,\n fixedClassName, contentNode, ...restProps} = this.props;\n const {topIsOutside, bottomIsOutside, sidebarVisibleHeight} = this.state;\n\n const shouldFixateTop = bottomIsOutside && topIsOutside && this.shouldUseFixation();\n const shouldFixateBottom = this.shouldFixateBottom();\n\n const containerClasses = classNames(styles.sidebarContainer, containerClassName, {\n [styles.sidebarContainerRight]: right\n });\n\n const classes = classNames(styles.sidebar, className, {\n [styles.sidebarRight]: right,\n [styles.sidebarFixedTop]: shouldFixateTop,\n [styles.sidebarFixedBottom]: shouldFixateBottom,\n [fixedClassName]: shouldFixateTop || shouldFixateBottom\n });\n\n const style = {\n maxHeight: shouldFixateBottom && sidebarVisibleHeight ? `${sidebarVisibleHeight}px` : null\n };\n\n return (\n \n \n\n \n {children}\n \n\n
\n \n
\n \n );\n }\n}\n","import React, {cloneElement, Component} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport Sidebar from './sidebar';\nimport styles from './content-layout.css';\n\n/**\n * @name Content Layout\n */\n\nexport default class ContentLayout extends Component {\n static propTypes = {\n children: PropTypes.node,\n className: PropTypes.string,\n contentClassName: PropTypes.string,\n responsive: PropTypes.bool\n };\n\n static defaultProps = {\n responsive: true\n };\n\n state = {};\n\n saveContentNode = contentNode => {\n this.setState({contentNode});\n };\n\n render() {\n const {children, className, contentClassName, responsive, ...restProps} = this.props;\n\n const classes = classNames(styles.contentLayout, className, {\n [styles.contentLayoutResponsive]: responsive\n });\n\n const contentClasses = classNames(styles.contentLayoutContent, contentClassName);\n\n const childrenArray = React.Children.toArray(children);\n const sidebarChild = childrenArray.filter(child => child && child.type === Sidebar)[0];\n\n const sidebar = sidebarChild && cloneElement(sidebarChild, {\n contentNode: this.state.contentNode\n });\n const contentChildren = childrenArray.filter(child => child !== sidebarChild);\n\n return (\n \n {sidebar}\n \n {contentChildren}\n \n \n );\n }\n}\n\nexport {default as Sidebar} from './sidebar';\n","import React, {Component} from 'react';\nimport PropTypes from 'prop-types';\nimport {renderToStaticMarkup} from 'react-dom/server';\n\n/**\n * @name ContentEditable\n */\n\nfunction noop() {}\n\nexport default class ContentEditable extends Component {\n /** @override */\n static propTypes = {\n disabled: PropTypes.bool,\n tabIndex: PropTypes.number,\n componentDidUpdate: PropTypes.func,\n onComponentUpdate: PropTypes.func,\n className: PropTypes.string,\n children: PropTypes.node\n };\n\n static defaultProps = {\n disabled: false,\n tabIndex: 0,\n onInput: noop,\n onComponentUpdate: noop\n };\n\n static getDerivedStateFromProps = ({children}) => ({\n __html: children ? renderToStaticMarkup(children) : ''\n });\n\n state = {__html: ''};\n\n shouldComponentUpdate(nextProps, nextState) {\n return nextProps.disabled !== this.props.disabled ||\n nextState.__html !== this.state.__html;\n }\n\n componentDidUpdate(prevProps, prevState) {\n this.props.onComponentUpdate(prevProps, prevState);\n }\n\n render() {\n const {children, onComponentUpdate, disabled, tabIndex, ...props} = this.props;\n\n return (\n \n );\n }\n}\n","import React, {Component} from 'react';\nimport PropTypes from 'prop-types';\n\nexport default function focusSensorHOC(ComposedComponent) {\n return class FocusSensor extends Component {\n static propTypes = {\n ...ComposedComponent.propTypes,\n focused: PropTypes.bool,\n autofocus: PropTypes.bool,\n onFocus: PropTypes.func,\n onBlur: PropTypes.func\n };\n\n static defaultProps = {\n ...ComposedComponent.defaultProps,\n focused: false,\n autofocus: false,\n onFocus: () => {},\n onBlur: () => {}\n };\n\n state = {\n focused: this.props.focused\n };\n\n componentDidMount() {\n const {props: {autofocus}, node} = this;\n\n node.setAttribute('tabindex', '0');\n node.style.outline = 'none';\n\n document.addEventListener('focus', this.onFocusCapture, true);\n document.addEventListener('blur', this.onBlurCapture, true);\n\n if (autofocus) {\n node.focus();\n }\n }\n\n componentDidUpdate(prevProps) {\n const {focused} = this.props;\n if (focused && !prevProps.focused) {\n this.onFocusRestore();\n } else if (!focused && prevProps.focused) {\n this.onFocusReset();\n }\n }\n\n componentWillUnmount() {\n document.removeEventListener('focus', this.onFocusCapture, true);\n document.removeEventListener('blur', this.onBlurCapture, true);\n }\n\n _skipNextCapture = false;\n\n onRefUpdate = node => {\n if (node) {\n this.node = node;\n }\n };\n\n onFocusCapture = ({target}) => {\n if (this._skipNextCapture) {\n this._skipNextCapture = false;\n return;\n }\n const focused = this.node.contains(target);\n if (focused && !this.state.focused) {\n this.setState({focused: true});\n this.props.onFocus();\n }\n };\n\n onBlurCapture = ({target}) => {\n const {state: {focused}, node} = this;\n if (focused) {\n setTimeout(() => {\n const blurred = node.contains(target) && !node.contains(document.activeElement);\n if (blurred) {\n this.setState({focused: false});\n this.props.onBlur();\n }\n }, 1);\n }\n };\n\n onFocusRestore = () => {\n this._skipNextCapture = true;\n this.node.focus();\n };\n\n onFocusReset = () => {\n this.node.blur();\n };\n\n render() {\n return (\n \n );\n }\n };\n}\n","export default class Selection {\n constructor({\n data = [],\n selected = new Set(),\n focused = null,\n getKey = item => item.id,\n getChildren = () => [],\n isItemSelectable = () => true\n } = {}) {\n this._rawData = data;\n this._getChildren = getChildren;\n\n this._data = this._buildData(data);\n\n this._selected = selected;\n this._focused = focused;\n this._getKey = getKey;\n this._isItemSelectable = isItemSelectable;\n }\n\n _buildData(data) {\n return new Set(data);\n }\n\n _buildSelected(data, selected) {\n return new Set(selected);\n }\n\n cloneWith({data, selected, focused}) {\n const newData = data || this._rawData;\n\n let newSelected;\n if (data && !selected) {\n newSelected = new Set([...this._buildData(newData)].\n filter(item => [...this._selected].some(it => this._getKey(item) === this._getKey(it))));\n newSelected = this._buildSelected(this._buildData(newData), newSelected);\n } else if (selected) {\n newSelected = selected;\n } else {\n newSelected = this._selected;\n }\n newSelected = new Set([...newSelected].filter(item => this._isItemSelectable(item)));\n\n const cloneFocus = () => [...this._buildData(data)].filter(\n item => this._focused && this._getKey(item) === this._getKey(this._focused)\n )[0];\n\n const newFocused = focused === undefined ? this._focused : focused;\n\n return new this.constructor({\n data: newData,\n selected: newSelected,\n focused: (data && !focused) ? cloneFocus() : newFocused,\n getKey: this._getKey,\n getChildren: this._getChildren,\n isItemSelectable: this._isItemSelectable\n });\n }\n\n focus(value) {\n return this.cloneWith({focused: value});\n }\n\n moveUp() {\n const focused = this._focused;\n const data = [...this._data];\n\n if (!focused) {\n return this.cloneWith({focused: data[data.length - 1]});\n }\n\n const nextItem = data[data.indexOf(focused) - 1];\n if (nextItem) {\n return this.cloneWith({focused: nextItem});\n }\n\n return undefined;\n }\n\n moveDown() {\n const focused = this._focused;\n const data = [...this._data];\n\n if (!focused) {\n return this.cloneWith({focused: data[0]});\n }\n\n const nextItem = data[data.indexOf(focused) + 1];\n if (nextItem) {\n return this.cloneWith({focused: nextItem});\n }\n\n return undefined;\n }\n\n moveStart() {\n const data = [...this._data];\n\n if (data.length) {\n return this.cloneWith({focused: data[0]});\n }\n\n return undefined;\n }\n\n moveEnd() {\n const data = [...this._data];\n\n if (data.length) {\n return this.cloneWith({focused: data.pop()});\n }\n\n return undefined;\n }\n\n select(value = this._focused) {\n if (!value || !this._isItemSelectable(value)) {\n return this;\n }\n\n const selected = new Set(this._selected);\n selected.add(value);\n return this.cloneWith({selected});\n }\n\n deselect(value = this._focused) {\n if (!value || !this._isItemSelectable(value)) {\n return this;\n }\n\n const selected = new Set(this._selected);\n selected.delete(value);\n return this.cloneWith({selected});\n }\n\n toggleSelection(value = this._focused) {\n if (this.isSelected(value)) {\n return this.deselect(value);\n } else {\n return this.select(value);\n }\n }\n\n selectAll() {\n return this.cloneWith({selected: [...this._data]});\n }\n\n resetFocus() {\n return this.cloneWith({focused: null});\n }\n\n resetSelection() {\n return this.cloneWith({selected: new Set()});\n }\n\n reset() {\n return this.resetFocus().resetSelection();\n }\n\n isFocused(value) {\n return this._focused === value;\n }\n\n isSelected(value) {\n return this._selected.has(value);\n }\n\n getFocused() {\n return this._focused;\n }\n\n getSelected() {\n return new Set(this._selected);\n }\n\n getActive() {\n if (this._selected.size) {\n return new Set(this._selected);\n } else if (this._focused) {\n return new Set([this._focused]);\n } else {\n return new Set();\n }\n }\n}\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\n\nimport Selection from './selection';\n\nexport default function selectionShortcutsHOC(ComposedComponent) {\n return class SelectionShortcuts extends PureComponent {\n static propTypes = {\n ...ComposedComponent.propTypes,\n selection: PropTypes.instanceOf(Selection).isRequired,\n selectable: PropTypes.bool,\n onSelect: PropTypes.func,\n shortcuts: PropTypes.object\n };\n\n static defaultProps = {\n ...ComposedComponent.defaultProps,\n selectable: true,\n onSelect: () => {},\n shortcuts: {}\n };\n\n onUpPress = () => {\n const {selection, onSelect} = this.props;\n const newSelection = selection.moveUp();\n\n if (newSelection) {\n onSelect(newSelection);\n }\n\n return false;\n };\n\n onDownPress = () => {\n const {selection, onSelect} = this.props;\n const newSelection = selection.moveDown();\n\n if (newSelection) {\n onSelect(newSelection);\n }\n\n return false;\n };\n\n onShiftKeyDown = () => {\n const {selection} = this.props;\n\n if (selection.isSelected(selection.getFocused())) {\n this.shiftSelectionMode = 'deletion';\n } else {\n this.shiftSelectionMode = 'addition';\n }\n };\n\n shiftSelect = selection => {\n if (this.shiftSelectionMode === 'addition') {\n return selection.select();\n } else {\n return selection.deselect();\n }\n };\n\n onShiftUpPress = e => {\n e.preventDefault();\n const {selectable, selection, onSelect} = this.props;\n\n if (!selectable) {\n return;\n }\n\n const newSelection = this.shiftSelect(selection);\n const newMovedSelection = newSelection.moveUp();\n\n if (newMovedSelection) {\n onSelect(newMovedSelection);\n } else {\n onSelect(newSelection);\n }\n };\n\n onShiftDownPress = e => {\n e.preventDefault();\n const {selectable, selection, onSelect} = this.props;\n\n if (!selectable) {\n return;\n }\n\n const newSelection = this.shiftSelect(selection);\n const newMovedSelection = newSelection.moveDown();\n\n if (newMovedSelection) {\n onSelect(newMovedSelection);\n } else {\n onSelect(newSelection);\n }\n };\n\n onHomePress = () => {\n const {selection, onSelect} = this.props;\n\n const newSelection = selection.moveStart();\n if (newSelection) {\n onSelect(newSelection);\n }\n\n return false;\n };\n\n onEndPress = () => {\n const {selection, onSelect} = this.props;\n\n const newSelection = selection.moveEnd();\n if (newSelection) {\n onSelect(newSelection);\n }\n\n return false;\n };\n\n onSpacePress = () => {\n const {selectable, selection, onSelect} = this.props;\n\n if (!selectable) {\n return true;\n }\n\n onSelect(selection.toggleSelection());\n return false;\n };\n\n onEscPress = () => {\n const {selection, onSelect} = this.props;\n\n onSelect(selection.reset());\n //this.restoreFocusWithoutScroll();\n };\n\n onCmdAPress = () => {\n const {selectable, selection, onSelect} = this.props;\n\n if (!selectable) {\n return true;\n }\n\n onSelect(selection.selectAll());\n return false;\n };\n\n shortcutsMap = {\n up: this.onUpPress,\n down: this.onDownPress,\n shift: this.onShiftKeyDown,\n 'shift+up': this.onShiftUpPress,\n 'shift+down': this.onShiftDownPress,\n home: this.onHomePress,\n end: this.onEndPress,\n space: this.onSpacePress,\n esc: this.onEscPress,\n 'command+a': this.onCmdAPress,\n 'ctrl+a': this.onCmdAPress\n };\n\n render() {\n const {selection, selectable, onSelect} = this.props;\n return (\n \n );\n }\n };\n}\n","import React, {PureComponent} from 'react';\n\nexport default function disableHoverHOC(ComposedComponent) {\n return class DisableHover extends PureComponent {\n static propTypes = ComposedComponent.propTypes;\n static defaultProps = ComposedComponent.defaultProps;\n\n state = {\n disabledHover: false\n };\n\n componentDidMount() {\n document.addEventListener('mousemove', this.onMouseMove);\n document.addEventListener('keydown', this.onKeyDown, true);\n }\n\n componentWillUnmount() {\n document.removeEventListener('mousemove', this.onMouseMove);\n document.removeEventListener('keydown', this.onKeyDown, true);\n }\n\n onMouseMove = () => {\n if (this.state.disabledHover) {\n this.setState({disabledHover: false});\n }\n };\n\n onKeyDown = e => {\n const metaKeys = [16, 17, 18, 19, 20, 91]; // eslint-disable-line no-magic-numbers\n if (!this.state.disabledHover && !metaKeys.includes(e.keyCode)) {\n this.setState({disabledHover: true});\n }\n };\n\n render() {\n return (\n \n );\n }\n };\n}\n","import 'dom4';\nimport {getPixelRatio} from '../global/dom';\n\nimport styles from './loader.css';\n\nconst INITIAL_TICKS = 100;\n\nclass Particle {\n constructor({x, y, radius, color}) {\n this.radius = radius;\n this.x = x;\n this.y = y;\n this.color = color;\n\n this.decay = 0.01;\n this.life = 1;\n }\n\n step() {\n this.life -= this.decay;\n }\n\n isAlive() {\n return this.life >= 0;\n }\n\n draw(ctx) {\n const alpha = this.life >= 0 ? this.life : 0;\n ctx.fillStyle = `rgba(${this.color.r}, ${this.color.g}, ${this.color.b}, ${alpha})`;\n\n ctx.beginPath();\n ctx.arc(this.x + this.radius, this.y + this.radius, this.radius, 0, Math.PI * 2);\n ctx.fill();\n }\n}\n\nexport default class LoaderCore {\n static defaultProps = {\n size: 64,\n stop: false,\n colors: [\n {r: 215, g: 60, b: 234}, //#D73CEA\n {r: 145, g: 53, b: 224}, //#9135E0\n {r: 88, g: 72, b: 224}, //#5848F4\n {r: 37, g: 183, b: 255}, //#25B7FF\n {r: 89, g: 189, b: 0}, //#59BD00\n {r: 251, g: 172, b: 2}, //#FBAC02\n {r: 227, g: 37, b: 129} //#E32581\n ]\n };\n\n static calculateGradient(startColor, stopColor, position) {\n const calculateChannelValue = (a, b) => a + Math.round((b - a) * position);\n\n return {\n r: calculateChannelValue(startColor.r, stopColor.r),\n g: calculateChannelValue(startColor.g, stopColor.g),\n b: calculateChannelValue(startColor.b, stopColor.b)\n };\n }\n\n constructor(containerNode, props) {\n this.props = Object.assign({}, LoaderCore.defaultProps, props);\n this.renderInNode(containerNode);\n this.initializeLoader();\n\n this.isRunning = !this.props.stop;\n\n if (this.isRunning) {\n this.startAnimation();\n } else {\n this.draw();\n }\n }\n\n static getPixelRatio() {\n return getPixelRatio();\n }\n\n setCanvasSize() {\n const pixelRatio = LoaderCore.getPixelRatio();\n const canvasSize = this.props.size * pixelRatio;\n\n this.canvas.width = canvasSize;\n this.canvas.height = canvasSize;\n\n //Fixate canvas physical size to avoid real size scaling\n this.canvas.style.width = `${this.props.size}px`;\n this.canvas.style.height = `${this.props.size}px`;\n\n this.ctx = this.canvas.getContext('2d');\n\n this.ctx.scale(pixelRatio, pixelRatio);\n }\n\n initializeLoader() {\n this.setCanvasSize();\n\n this.height = this.props.size;\n this.width = this.props.size;\n\n this.particles = [];\n\n //Configuration\n this.baseSpeed = 1.0;\n this.colorIndex = 0;\n this.maxRadius = 10;\n this.minRadius = 6;\n this.colorChangeTick = 40;\n\n //State\n this.x = 0;\n this.y = 0;\n this.radius = 8;\n this.hSpeed = 1.5;\n this.vSpeed = 0.5;\n this.radiusSpeed = 0.05;\n this.tick = 0;\n\n this.prepareInitialState(INITIAL_TICKS);\n }\n\n prepareInitialState(ticks) {\n for (let i = 0; i < ticks; i++) {\n this.step();\n }\n }\n\n handleLimits(coord, radius, speed, limit) {\n const randomizedSpeedChange = Math.random(this.baseSpeed) - this.baseSpeed / 2;\n\n if (coord + (radius * 2) + this.baseSpeed >= limit) {\n return -(this.baseSpeed + randomizedSpeedChange);\n } else if (coord <= this.baseSpeed) {\n return this.baseSpeed + randomizedSpeedChange;\n }\n return speed;\n }\n\n calculateNextCoordinates() {\n this.x += this.hSpeed;\n this.y += this.vSpeed;\n\n this.hSpeed = this.handleLimits(this.x, this.radius, this.hSpeed, this.width);\n this.vSpeed = this.handleLimits(this.y, this.radius, this.vSpeed, this.height);\n }\n\n calculateNextRadius() {\n this.radius += this.radiusSpeed;\n\n if (this.radius > this.maxRadius || this.radius < this.minRadius) {\n this.radiusSpeed = -this.radiusSpeed;\n }\n }\n\n getNextColor() {\n const colors = this.props.colors;\n\n const currentColor = colors[this.colorIndex];\n const nextColor = colors[this.colorIndex + 1] || colors[0];\n\n return LoaderCore.calculateGradient(currentColor, nextColor, this.tick / this.colorChangeTick);\n }\n\n nextTick() {\n this.tick++;\n\n if (this.tick > this.colorChangeTick) {\n this.tick = 0;\n this.colorIndex++;\n if (this.colorIndex > this.props.colors.length - 1) {\n this.colorIndex = 0;\n }\n }\n }\n\n step() {\n this.nextTick();\n this.calculateNextCoordinates();\n this.calculateNextRadius();\n this.particles.forEach(particle => particle.step());\n\n this.particles.push(new Particle({\n x: this.x,\n y: this.y,\n radius: this.radius,\n color: this.getNextColor()\n }));\n }\n\n removeDeadParticles() {\n this.particles = this.particles.filter(it => it.isAlive());\n }\n\n draw() {\n this.ctx.clearRect(0, 0, this.width, this.height);\n this.removeDeadParticles();\n this.particles.forEach(particle => particle.draw(this.ctx));\n }\n\n loop() {\n this.step();\n this.draw();\n if (this.isRunning) {\n window.requestAnimationFrame(() => this.loop());\n }\n }\n\n updateMessage(text) {\n this.textNode.textContent = text || '';\n }\n\n stopAnimation() {\n this.isRunning = false;\n this.canvas.classList.remove(styles.animate);\n }\n\n startAnimation() {\n this.isRunning = true;\n this.canvas.classList.add(styles.animate);\n this.loop();\n }\n\n destroy() {\n this.isRunning = false;\n }\n\n renderInNode(node) {\n this.canvas = document.createElement('canvas');\n this.canvas.dataset.test = 'ring-loader';\n this.canvas.classList.add(styles.canvas);\n\n this.textNode = document.createElement('div');\n this.textNode.dataset.test = 'ring-loader-text';\n this.textNode.classList.add(styles.text);\n\n this.textNode.textContent = this.props.message ? this.props.message : '';\n\n node.appendChild(this.canvas);\n node.appendChild(this.textNode);\n\n return node;\n }\n}\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\n\nimport dataTests from '../global/data-tests';\n\nimport LoaderCore from './loader__core';\n\n/**\n * @name Loader\n */\n\nexport default class Loader extends PureComponent {\n static propTypes = {\n className: PropTypes.string,\n size: PropTypes.number,\n colors: PropTypes.array,\n message: PropTypes.string,\n 'data-test': PropTypes.string,\n stop: PropTypes.bool\n };\n\n componentDidUpdate(prevProps) {\n if (this.loader) {\n if (!prevProps.stop && this.props.stop) {\n this.loader.stopAnimation();\n } else if (prevProps.stop && !this.props.stop) {\n this.loader.startAnimation();\n }\n }\n }\n\n componentWillUnmount() {\n this.loader.destroy();\n }\n\n initLoader = el => {\n if (el) {\n this.loader = new LoaderCore(el, this.props);\n }\n };\n\n render() {\n const {message, size, colors, 'data-test': dataTest, stop, ...restProps} = this.props;\n return (\n \n );\n }\n}\n","import React, {Component} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport deprecate from 'util-deprecate';\n\nimport styles from './text.css';\n\n/**\n * @name Text\n */\n\nconst deprecateComment = deprecate(\n () => {},\n ' is deprecated, use instead'\n);\n\n\nexport default class Text extends Component {\n static propTypes = {\n children: PropTypes.node,\n comment: PropTypes.bool,\n info: PropTypes.bool,\n className: PropTypes.string\n };\n\n render() {\n const {children, className, comment, info, ...restProps} = this.props;\n if (comment) {\n deprecateComment();\n }\n const classes = classNames(styles.text, className, {\n [styles.info]: info || comment\n });\n\n return (\n {children}\n );\n }\n}\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport focusSensorHOC from '../global/focus-sensor-hoc';\nimport Checkbox from '../checkbox/checkbox';\n\nimport getUID from '../global/get-uid';\n\nimport styles from './data-list.css';\n\n\nclass Title extends PureComponent {\n static propTypes = {\n className: PropTypes.string,\n title: PropTypes.node,\n offset: PropTypes.number,\n selectable: PropTypes.bool,\n selected: PropTypes.bool,\n onSelect: PropTypes.func,\n showFocus: PropTypes.bool,\n collapserExpander: PropTypes.node,\n innerRef: PropTypes.oneOfType([PropTypes.object, PropTypes.string, PropTypes.func]),\n\n // focusSensorHOC\n onFocusRestore: PropTypes.func\n };\n\n static defaultProps = {\n selectable: false,\n selected: false,\n showFocus: false\n };\n\n id = getUID('data-list-title');\n\n onCheckboxFocus = () => {\n this.props.onFocusRestore();\n };\n\n onCheckboxChange = () => {\n this.toggleSelection();\n };\n\n toggleSelection() {\n const {selectable, selected, onSelect} = this.props;\n if (selectable) {\n onSelect(!selected);\n }\n }\n\n render() {\n const {\n className, title, offset, showFocus, innerRef,\n selectable, selected, collapserExpander\n } = this.props;\n\n const classes = classNames(className, {\n [styles.title]: true,\n [styles.titleFocused]: showFocus,\n [styles.titleSelected]: selected\n });\n\n return (\n \n
\n {selectable &&\n (\n
\n \n
\n )\n }\n\n {collapserExpander}\n
\n\n {title}\n \n );\n }\n}\n\nexport default focusSensorHOC(Title);\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport chevronRightIcon from '@jetbrains/icons/chevron-right.svg';\nimport chevronDownIcon from '@jetbrains/icons/chevron-down.svg';\n\nimport Link from '../link/link';\nimport Text from '../text/text';\nimport LoaderInline from '../loader-inline/loader-inline';\n\nimport Button from '../button/button';\n\nimport Title from './title';\n\nimport styles from './data-list.css';\n\nexport const moreLessButtonStates = {\n UNUSED: 0,\n MORE: 1,\n MORE_LOADING: 2,\n LESS: 3\n};\n\nconst ITEM_LEFT_OFFSET = 32;\nconst LIST_LEFT_OFFSET = 24;\n\n\nexport default class Item extends PureComponent {\n static propTypes = {\n item: PropTypes.object,\n title: PropTypes.node,\n items: PropTypes.array,\n className: PropTypes.string,\n level: PropTypes.number,\n parentShift: PropTypes.number,\n\n itemFormatter: PropTypes.func,\n\n collapsible: PropTypes.bool,\n collapsed: PropTypes.bool,\n onCollapse: PropTypes.func,\n onExpand: PropTypes.func,\n\n showFocus: PropTypes.bool,\n onFocus: PropTypes.func,\n\n selection: PropTypes.object,\n selectable: PropTypes.bool,\n selected: PropTypes.bool,\n onSelect: PropTypes.func,\n\n showMoreLessButton: PropTypes.number,\n onItemMoreLess: PropTypes.func\n };\n\n static defaultProps = {\n items: [],\n level: 0,\n parentShift: 0,\n showMoreLessButton: moreLessButtonStates.UNUSED,\n onItemMoreLess: () => {}\n };\n\n\n onShowMore = () => {\n const {onItemMoreLess, item} = this.props;\n onItemMoreLess(item, true);\n };\n\n onShowLess = () => {\n const {onItemMoreLess, item} = this.props;\n onItemMoreLess(item, false);\n };\n\n onFocus = () => {\n const {onFocus, item} = this.props;\n onFocus(item);\n };\n\n onSelect = selected => {\n const {onSelect, item} = this.props;\n onSelect(item, selected);\n };\n\n renderItem = (model, parentShift) => {\n const {\n onFocus, onSelect, selection, level,\n itemFormatter\n } = this.props;\n\n const item = itemFormatter(model);\n\n return (\n \n );\n };\n\n render() {\n const {\n title, items, showMoreLessButton,\n level, parentShift, showFocus,\n selectable, selected,\n collapsible, collapsed, onCollapse, onExpand\n } = this.props;\n\n let moreLessButton;\n if (showMoreLessButton === moreLessButtonStates.MORE ||\n showMoreLessButton === moreLessButtonStates.MORE_LOADING) {\n moreLessButton = (\n \n {'Show more'}\n {showMoreLessButton === moreLessButtonStates.MORE_LOADING &&\n \n }\n \n );\n } else if (showMoreLessButton === moreLessButtonStates.LESS) {\n moreLessButton = (\n \n {'Show less'}\n \n );\n }\n\n let collapserExpander = null;\n if (collapsible) {\n if (collapsed) {\n collapserExpander = (\n \n );\n } else {\n collapserExpander = (\n \n );\n }\n }\n\n const itemIsEmpty = !items.length || (collapsible && collapsed);\n const offset = level * LIST_LEFT_OFFSET + ITEM_LEFT_OFFSET + parentShift;\n\n return (\n
  • \n \n\n {!itemIsEmpty ? (\n
      \n {items.map(model => this.renderItem(model, parentShift))}\n\n {showMoreLessButton !== moreLessButtonStates.UNUSED\n ?
    • {moreLessButton}
    • \n : null\n }\n
    \n ) : null}\n
  • \n );\n }\n}\n","/**\n * @name Data List\n */\n\nimport React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport focusSensorHOC from '../global/focus-sensor-hoc';\nimport selectionShortcutsHOC from '../table/selection-shortcuts-hoc';\nimport disableHoverHOC from '../table/disable-hover-hoc';\nimport getUID from '../global/get-uid';\nimport Shortcuts from '../shortcuts/shortcuts';\nimport Loader from '../loader/loader';\n\nimport Item, {moreLessButtonStates} from './item';\n\nimport styles from './data-list.css';\n\n\nclass DataList extends PureComponent {\n static propTypes = {\n className: PropTypes.string,\n data: PropTypes.array.isRequired,\n loading: PropTypes.bool,\n focused: PropTypes.bool,\n disabledHover: PropTypes.bool,\n selection: PropTypes.object,\n selectable: PropTypes.bool,\n shortcutsMap: PropTypes.object,\n innerRef: PropTypes.oneOfType([PropTypes.object, PropTypes.string, PropTypes.func]),\n\n itemFormatter: PropTypes.func.isRequired,\n\n onItemMoreLess: PropTypes.func,\n itemMoreLessState: PropTypes.func,\n onSelect: PropTypes.func,\n\n remoteSelection: PropTypes.bool\n };\n\n static defaultProps = {\n loading: false,\n\n onItemMoreLess: () => {},\n itemMoreLessState: () => moreLessButtonStates.UNUSED,\n\n remoteSelection: false\n };\n\n componentDidUpdate(prevProps) {\n const {data, selection, onSelect, selectable} = this.props;\n\n if (data !== prevProps.data && !prevProps.remoteSelection) {\n onSelect(selection.cloneWith({data}));\n }\n\n if (!selectable && prevProps.selectable) {\n onSelect(selection.resetSelection());\n }\n }\n\n shortcutsScope = getUID('ring-data-list-');\n\n onItemFocus = item => {\n const {selection, onSelect} = this.props;\n onSelect(selection.focus(item));\n };\n\n onItemSelect = (item, selected) => {\n const {selection, onSelect} = this.props;\n if (selected) {\n onSelect(selection.select(item));\n } else {\n onSelect(selection.deselect(item));\n }\n };\n\n onEqualPress = () => {\n const {\n selection, itemFormatter\n } = this.props;\n\n const item = itemFormatter(selection.getFocused());\n\n if (item.collapsed) {\n item.onExpand();\n } else {\n item.onCollapse();\n }\n };\n\n shortcutsMap = {\n '=': this.onEqualPress\n };\n\n render() {\n const {\n data, className, loading,\n selection, disabledHover,\n itemFormatter, focused, innerRef\n } = this.props;\n\n const shortcutsMap = {...this.shortcutsMap, ...this.props.shortcutsMap};\n\n const classes = classNames(className, {\n [styles.dataList]: true,\n [styles.disabledHover]: disabledHover,\n [styles.multiSelection]: selection.getSelected().size > 0\n });\n\n return (\n
    \n {focused &&\n (\n \n )\n }\n\n
      \n {data.map(model => {\n const item = itemFormatter(model);\n const {id, key, title, items} = item;\n\n const showMoreLessButton = this.props.itemMoreLessState(item);\n\n return (\n \n );\n })}\n
    \n\n {loading && (\n
    0 ? styles.loadingOverlay : null}>\n \n
    \n )}\n
    \n );\n }\n}\n\nexport default disableHoverHOC(selectionShortcutsHOC(focusSensorHOC(DataList)));\n","/**\n * @name DataList Ng\n */\nimport angularComponentFactory from '../global/angular-component-factory';\nimport DataList from '../data-list/data-list';\n\nexport default angularComponentFactory(DataList, 'DataList').name;\n","import React, {createElement} from 'react';\nimport {findDOMNode, render} from 'react-dom';\n\n/**\n * Wraps a component to add a \"rerender\" method\n * @param ComposedComponent\n * @param captureNode, whether the wrapper should capture this.node itself. Set to false if the component already has \"node\" property captured\n * @returns {Rerenderer}\n */\nexport default function rerenderHOC(ComposedComponent, {captureNode} = {captureNode: true}) {\n return class Rerenderer extends ComposedComponent {\n _propsCache = {};\n\n onRefUpdate = component => {\n // eslint-disable-next-line react/no-find-dom-node\n this.node = findDOMNode(component);\n };\n\n rerender(props = {}, callback) {\n let container;\n\n try {\n container = this.node.parentNode;\n } finally {\n if (!container) {\n throw new Error(`${this.constructor.name} component isn't mounted`);\n }\n }\n\n this._propsCache = Object.assign({}, this.props, this._propsCache, props);\n\n return render(createElement(this.constructor, this._propsCache), container, callback);\n }\n\n render() {\n if (!captureNode) {\n return super.render();\n }\n\n return (\n \n );\n }\n };\n}\n","import React from 'react';\nimport PropTypes from 'prop-types';\nimport chevronDown from '@jetbrains/icons/chevron-10px.svg';\nimport classNames from 'classnames';\n\nimport Icon from '../icon';\n\nimport Button from '../button/button';\n\nimport styles from './dropdown.css';\n\nexport default function Anchor({children, className, ...restProps}) {\n return (\n \n {children}\n \n \n );\n}\n\nAnchor.propTypes = {\n children: PropTypes.node,\n className: PropTypes.string\n};\n","import React, {cloneElement, Component} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport dataTests from '../global/data-tests';\n\nimport Anchor from './anchor';\nimport styles from './dropdown.css';\n\n/**\n * @name Dropdown\n */\n\nexport default class Dropdown extends Component {\n static propTypes = {\n /**\n * Can be string, React element, or a function accepting an object with {active, pinned} properties and returning a React element\n * React element should render some interactive HTML element like `button` or `a`\n */\n anchor: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired,\n children: PropTypes.element.isRequired,\n initShown: PropTypes.bool,\n className: PropTypes.string,\n activeClassName: PropTypes.string,\n clickMode: PropTypes.bool,\n hoverMode: PropTypes.bool,\n hoverShowTimeOut: PropTypes.number,\n hoverHideTimeOut: PropTypes.number,\n onShow: PropTypes.func,\n onHide: PropTypes.func,\n onMouseEnter: PropTypes.func,\n onMouseLeave: PropTypes.func,\n 'data-test': PropTypes.string\n };\n\n static defaultProps = {\n initShown: false,\n clickMode: true,\n hoverMode: false,\n hoverShowTimeOut: 300,\n hoverHideTimeOut: 600,\n onShow: () => {},\n onHide: () => {},\n onMouseEnter: () => {},\n onMouseLeave: () => {}\n };\n\n state = {\n show: this.props.initShown,\n pinned: false\n };\n\n onClick = () => {\n const {show, pinned} = this.state;\n let nextPinned = pinned;\n\n if (this.props.hoverMode) {\n if (!pinned) {\n nextPinned = true;\n\n if (show) {\n this.setState({pinned: true});\n return;\n }\n } else {\n nextPinned = false;\n }\n }\n\n this._toggle(!show, nextPinned);\n };\n\n onChildCloseAttempt = () => {\n let nextPinned = this.state.pinned;\n if (this.props.hoverMode) {\n nextPinned = false;\n }\n\n this._toggle(false, nextPinned);\n };\n\n onMouseEnter = event => {\n this._clearTimer();\n this.props.onMouseEnter(event);\n\n this.hoverTimer = setTimeout(() => {\n if (!this.state.show) {\n this._toggle(true);\n }\n }, this.props.hoverShowTimeOut);\n };\n\n onMouseLeave = event => {\n this.props.onMouseLeave(event);\n if (this.state.pinned) {\n return;\n }\n\n this._clearTimer();\n\n this.hoverTimer = setTimeout(() => {\n if (this.state.show) {\n this._toggle(false);\n }\n }, this.props.hoverHideTimeOut);\n };\n\n handlePopupInteraction = () => {\n this.setState(({pinned}) => (pinned ? null : {pinned: true}));\n };\n\n toggle(show = !this.state.show) {\n this._toggle(show);\n }\n\n _toggle(show, pinned = this.state.pinned) {\n this.setState({show, pinned}, () => (show ? this.props.onShow() : this.props.onHide()));\n }\n\n _clearTimer() {\n if (this.hoverTimer) {\n clearTimeout(this.hoverTimer);\n this.hoverTimer = null;\n }\n }\n\n render() {\n const {show, pinned} = this.state;\n const {\n initShown, onShow, onHide, hoverShowTimeOut, hoverHideTimeOut,\n children, anchor, className, activeClassName, hoverMode, clickMode, 'data-test': dataTest,\n ...restProps\n } = this.props;\n\n const classes = classNames(styles.dropdown, className, {\n [activeClassName]: activeClassName != null && show\n });\n\n let anchorElement;\n\n switch (typeof anchor) {\n case 'string':\n anchorElement = ({anchor});\n break;\n case 'function':\n anchorElement = anchor({active: show, pinned});\n break;\n\n default:\n anchorElement = anchor;\n }\n\n return (\n \n {anchorElement}\n {cloneElement(children, {\n hidden: !show,\n onCloseAttempt: this.onChildCloseAttempt,\n onMouseDown: hoverMode ? this.handlePopupInteraction : undefined,\n onContextMenu: hoverMode ? this.handlePopupInteraction : undefined,\n dontCloseOnAnchorClick: true\n })}\n \n );\n }\n}\n\nexport {Anchor};\n","import React, {PureComponent} from 'react';\n\nimport sniffr from '../global/sniffer';\n\nfunction noop() {}\n\n/**\n * Workaround: IE11 loses symbols in onChange event\n * See RG-1361 and https://github.com/facebook/react/issues/7027\n */\nconst isIE11 = sniffr.browser.name === 'ie' && sniffr.browser.versionString === '11.0';\n\nexport default function ieCompatibleInputHOC(ComposedComponent) {\n return class IeCompatibleInput extends PureComponent {\n static propTypes = ComposedComponent.propTypes;\n\n render() {\n const {onChange, multiple, ...restProps} = this.props;\n\n const changeListenProps = (isIE11 && !multiple)\n ? {\n onInput: onChange,\n onChange: noop\n }\n : {onChange};\n\n return (\n \n );\n }\n };\n}\n","import React, {PureComponent} from 'react';\nimport {compose} from 'recompose';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport closeIcon from '@jetbrains/icons/close.svg';\n\nimport Theme, {withTheme} from '../global/theme';\nimport Button from '../button/button';\n\nimport getUID from '../global/get-uid';\n\nimport Icon from '../icon/icon';\n\nimport ieCompatibleInputHOC from './ie-compatible-hoc';\nimport styles from './input.css';\n\nfunction noop() {}\n\n/**\n * @name Input\n */\n\nconst Size = {\n AUTO: 'Auto',\n S: 'S',\n M: 'M',\n L: 'L',\n FULL: 'FULL'\n};\n\nexport class Input extends PureComponent {\n static propTypes = {\n value: PropTypes.string,\n theme: PropTypes.string,\n className: PropTypes.string,\n inputClassName: PropTypes.string,\n size: PropTypes.string,\n label: PropTypes.string,\n active: PropTypes.bool,\n error: PropTypes.string,\n multiline: PropTypes.bool,\n borderless: PropTypes.bool,\n compact: PropTypes.bool,\n onChange: PropTypes.func,\n onClear: PropTypes.func,\n inputRef: PropTypes.oneOfType([\n PropTypes.func,\n PropTypes.shape({current: PropTypes.instanceOf(HTMLInputElement)})\n ]),\n children: PropTypes.string,\n enableShortcuts: PropTypes.bool,\n disabled: PropTypes.bool,\n id: PropTypes.string,\n placeholder: PropTypes.string,\n icon: PropTypes.oneOfType([PropTypes.string, PropTypes.elementType])\n };\n\n static defaultProps = {\n size: Size.M,\n onChange: noop,\n inputRef: noop,\n enableShortcuts: false\n };\n\n state = {\n empty: true\n };\n\n componentDidMount() {\n this.adapt();\n }\n\n componentDidUpdate() {\n this.adapt();\n }\n\n id = getUID('ring-input-');\n getId() {\n return this.props.id || this.id;\n }\n\n checkValue() {\n this.setState({\n empty: !this.input.value\n });\n\n if (this.props.multiline && this.input.scrollHeight > this.input.clientHeight) {\n this.stretch(this.input);\n }\n }\n\n stretch(el) {\n if (!el) {\n return;\n }\n el.style.height = `${el.scrollHeight}px`;\n }\n\n adapt() {\n this.checkValue();\n this.stretch(this.error);\n }\n\n errorRef = el => {\n this.error = el;\n };\n\n inputRef = el => {\n const {inputRef} = this.props;\n\n this.input = el;\n if (typeof inputRef === 'function') {\n inputRef(el);\n } else {\n inputRef.current = el;\n }\n };\n\n clear = e => {\n this.props.onClear && this.props.onClear(e);\n };\n\n handleChange = e => {\n this.props.onChange(e);\n this.checkValue(e.target);\n };\n\n render() {\n const {\n // Modifiers\n theme,\n size,\n active,\n multiline,\n borderless,\n compact,\n\n // Props\n label,\n error,\n className,\n inputClassName,\n children,\n value,\n onClear,\n disabled,\n inputRef, onChange,\n enableShortcuts,\n id,\n placeholder,\n icon,\n ...restProps\n } = this.props;\n const minimizeMargins = compact || borderless;\n const {empty} = this.state;\n const clearable = !!onClear;\n const classes = classNames(\n styles.container,\n className,\n styles[theme],\n [styles[`size${size}`]],\n {\n 'ring-js-shortcuts': enableShortcuts,\n [styles.active]: active,\n [styles.error]: error != null,\n [styles.empty]: empty,\n [styles.noLabel]: !this.props.label,\n [styles.withIcon]: icon != null,\n [styles.clearable]: clearable,\n [styles.compact]: minimizeMargins\n }\n );\n\n const inputClasses = classNames(styles.input, inputClassName);\n\n const TagName = multiline ? 'textarea' : 'input';\n\n const text = value != null ? value : children;\n\n return (\n \n {icon && }\n \n {clearable && !disabled && (\n \n )}\n\n {!minimizeMargins && }\n {!borderless &&
    }\n {!borderless &&
    }\n {!minimizeMargins &&
    }\n {!minimizeMargins && (\n {error}
    \n )}\n
    \n );\n }\n}\n\nexport default compose(\n ieCompatibleInputHOC,\n withTheme(),\n)(Input);\n\nexport {Size, Theme};\n","export default ['D M', 'DD M', 'DD MM', 'D-M', 'DD-M', 'DD-MM', 'D.M', 'DD.M', 'DD.MM', 'D\\\\M', 'DD\\\\M', 'DD\\\\MM', 'D/M', 'DD/M', 'DD/MM', 'D M YY', 'DD M YY', 'DD MM YY', 'D M YYYY', 'DD M YYYY', 'DD MM YYYY', 'D-M-YY', 'DD-M-YY', 'DD-MM-YY', 'D-M-YYYY', 'DD-M-YYYY', 'DD-MM-YYYY', 'D.M.YY', 'DD.M.YY', 'DD.MM.YY', 'D.M.YYYY', 'DD.M.YYYY', 'DD.MM.YYYY', 'D\\\\M\\\\YY', 'DD\\\\M\\\\YY', 'DD\\\\MM\\\\YY', 'D\\\\M\\\\YYYY', 'DD\\\\M\\\\YYYY', 'DD\\\\MM\\\\YYYY', 'D/M/YY', 'DD/M/YY', 'DD/MM/YY', 'D/M/YYYY', 'DD/M/YYYY', 'DD/MM/YYYY', 'D M YY', 'DD M YY', 'DD MM YY', 'D M YYYY', 'DD M YYYY', 'DD MM YYYY', 'D-M-YY', 'DD-M-YY', 'DD-MM-YY', 'D-M-YYYY', 'DD-M-YYYY', 'DD-MM-YYYY', 'D.M.YY', 'DD.M.YY', 'DD.MM.YY', 'D.M.YYYY', 'DD.M.YYYY', 'DD.MM.YYYY', 'D\\\\M\\\\YY', 'DD\\\\M\\\\YY', 'DD\\\\MM\\\\YY', 'D\\\\M\\\\YYYY', 'DD\\\\M\\\\YYYY', 'DD\\\\MM\\\\YYYY', 'D/M/YY', 'DD/M/YY', 'DD/MM/YY', 'D/M/YYYY', 'DD/M/YYYY', 'DD/MM/YYYY', 'YY M D', 'YY M DD', 'YY MM DD', 'YYYY M D', 'YYYY M DD', 'YYYY MM DD', 'YY-M-D', 'YY-M-DD', 'YY-MM-DD', 'YYYY-M-D', 'YYYY-M-DD', 'YYYY-MM-DD', 'YY.M.D', 'YY.M.DD', 'YY.MM.DD', 'YYYY.M.D', 'YYYY.M.DD', 'YYYY.MM.DD', 'YY\\\\M\\\\D', 'YY\\\\M\\\\DD', 'YY\\\\MM\\\\DD', 'YYYY\\\\M\\\\D', 'YYYY\\\\M\\\\DD', 'YYYY\\\\MM\\\\DD', 'YY/M/D', 'YY/M/DD', 'YY/MM/DD', 'YYYY/M/D', 'YYYY/M/DD', 'YYYY/MM/DD', 'YY D M', 'YY DD M', 'YY DD MM', 'YYYY D M', 'YYYY DD MM', 'YYYY DD MM', 'YY-D-M', 'YY-DD-M', 'YY-DD-MM', 'YYYY-D-M', 'YYYY-DD-MM', 'YYYY-DD-MM', 'YY.D.M', 'YY.DD.M', 'YY.DD.MM', 'YYYY.D.M', 'YYYY.DD.MM', 'YYYY.DD.MM', 'YY\\\\D\\\\M', 'YY\\\\DD\\\\M', 'YY\\\\DD\\\\MM', 'YYYY\\\\D\\\\M', 'YYYY\\\\DD\\\\MM', 'YYYY\\\\DD\\\\MM', 'YY/D/M', 'YY/DD/M', 'YY/DD/MM', 'YYYY/D/M', 'YYYY/DD/MM', 'YYYY/DD/MM', 'D MMM', 'DD MMM', 'D M HH:mm', 'DD M HH:mm', 'DD MM HH:mm', 'D-M HH:mm', 'DD-M HH:mm', 'DD-MM HH:mm', 'D.M HH:mm', 'DD.M HH:mm', 'DD.MM HH:mm', 'D\\\\M HH:mm', 'DD\\\\M HH:mm', 'DD\\\\MM HH:mm', 'D/M HH:mm', 'DD/M HH:mm', 'DD/MM HH:mm', 'D M YY HH:mm', 'DD M YY HH:mm', 'DD MM YY HH:mm', 'D M YYYY HH:mm', 'DD M YYYY HH:mm', 'DD MM YYYY HH:mm', 'D-M-YY HH:mm', 'DD-M-YY HH:mm', 'DD-MM-YY HH:mm', 'D-M-YYYY HH:mm', 'DD-M-YYYY HH:mm', 'DD-MM-YYYY HH:mm', 'D.M.YY HH:mm', 'DD.M.YY HH:mm', 'DD.MM.YY HH:mm', 'D.M.YYYY HH:mm', 'DD.M.YYYY HH:mm', 'DD.MM.YYYY HH:mm', 'D\\\\M\\\\YY HH:mm', 'DD\\\\M\\\\YY HH:mm', 'DD\\\\MM\\\\YY HH:mm', 'D\\\\M\\\\YYYY HH:mm', 'DD\\\\M\\\\YYYY HH:mm', 'DD\\\\MM\\\\YYYY HH:mm', 'D/M/YY HH:mm', 'DD/M/YY HH:mm', 'DD/MM/YY HH:mm', 'D/M/YYYY HH:mm', 'DD/M/YYYY HH:mm', 'DD/MM/YYYY HH:mm', 'D M YY HH:mm', 'DD M YY HH:mm', 'DD MM YY HH:mm', 'D M YYYY HH:mm', 'DD M YYYY HH:mm', 'DD MM YYYY HH:mm', 'D-M-YY HH:mm', 'DD-M-YY HH:mm', 'DD-MM-YY HH:mm', 'D-M-YYYY HH:mm', 'DD-M-YYYY HH:mm', 'DD-MM-YYYY HH:mm', 'D.M.YY HH:mm', 'DD.M.YY HH:mm', 'DD.MM.YY HH:mm', 'D.M.YYYY HH:mm', 'DD.M.YYYY HH:mm', 'DD.MM.YYYY HH:mm', 'D\\\\M\\\\YY HH:mm', 'DD\\\\M\\\\YY HH:mm', 'DD\\\\MM\\\\YY HH:mm', 'D\\\\M\\\\YYYY HH:mm', 'DD\\\\M\\\\YYYY HH:mm', 'DD\\\\MM\\\\YYYY HH:mm', 'D/M/YY HH:mm', 'DD/M/YY HH:mm', 'DD/MM/YY HH:mm', 'D/M/YYYY HH:mm', 'DD/M/YYYY HH:mm', 'DD/MM/YYYY HH:mm', 'YY M D HH:mm', 'YY M DD HH:mm', 'YY MM DD HH:mm', 'YYYY M D HH:mm', 'YYYY M DD HH:mm', 'YYYY MM DD HH:mm', 'YY-M-D HH:mm', 'YY-M-DD HH:mm', 'YY-MM-DD HH:mm', 'YYYY-M-D HH:mm', 'YYYY-M-DD HH:mm', 'YYYY-MM-DD HH:mm', 'YY.M.D HH:mm', 'YY.M.DD HH:mm', 'YY.MM.DD HH:mm', 'YYYY.M.D HH:mm', 'YYYY.M.DD HH:mm', 'YYYY.MM.DD HH:mm', 'YY\\\\M\\\\D HH:mm', 'YY\\\\M\\\\DD HH:mm', 'YY\\\\MM\\\\DD HH:mm', 'YYYY\\\\M\\\\D HH:mm', 'YYYY\\\\M\\\\DD HH:mm', 'YYYY\\\\MM\\\\DD HH:mm', 'YY/M/D HH:mm', 'YY/M/DD HH:mm', 'YY/MM/DD HH:mm', 'YYYY/M/D HH:mm', 'YYYY/M/DD HH:mm', 'YYYY/MM/DD HH:mm', 'YY D M HH:mm', 'YY DD M HH:mm', 'YY DD MM HH:mm', 'YYYY D M HH:mm', 'YYYY DD MM HH:mm', 'YYYY DD MM HH:mm', 'YY-D-M HH:mm', 'YY-DD-M HH:mm', 'YY-DD-MM HH:mm', 'YYYY-D-M HH:mm', 'YYYY-DD-MM HH:mm', 'YYYY-DD-MM HH:mm', 'YY.D.M HH:mm', 'YY.DD.M HH:mm', 'YY.DD.MM HH:mm', 'YYYY.D.M HH:mm', 'YYYY.DD.MM HH:mm', 'YYYY.DD.MM HH:mm', 'YY\\\\D\\\\M HH:mm', 'YY\\\\DD\\\\M HH:mm', 'YY\\\\DD\\\\MM HH:mm', 'YYYY\\\\D\\\\M HH:mm', 'YYYY\\\\DD\\\\MM HH:mm', 'YYYY\\\\DD\\\\MM HH:mm', 'YY/D/M HH:mm', 'YY/DD/M HH:mm', 'YY/DD/MM HH:mm', 'YYYY/D/M HH:mm', 'YYYY/DD/MM HH:mm', 'YYYY/DD/MM HH:mm', 'D MMM HH:mm', 'DD MMM HH:mm', 'YYYY MMM D', 'YYYY MMM DD', 'YYYY D MMM', 'YYYY DD MMM', 'D MMM YY', 'DD MMM YY', 'D MMM YYYY', 'DD MMM YYYY', 'D MMM YY', 'DD MMM YY', 'D MMM YYYY', 'DD MMM YYYY', 'MMM D YYYY', 'MMM DD YYYY', 'YY MMM D', 'YY MMM DD', 'YY D MMM', 'YY DD MMM', 'D MMM', 'DD MMM', 'YYYY MMM D HH:mm', 'YYYY MMM DD HH:mm', 'YYYY D MMM HH:mm', 'YYYY DD MMM HH:mm', 'D MMM YY HH:mm', 'DD MMM YY HH:mm', 'D MMM YYYY HH:mm', 'DD MMM YYYY HH:mm', 'D MMM YY HH:mm', 'DD MMM YY HH:mm', 'D MMM YYYY HH:mm', 'DD MMM YYYY HH:mm', 'MMM D YYYY HH:mm', 'MMM DD YYYY HH:mm', 'YY MMM D HH:mm', 'YY MMM DD HH:mm', 'YY D MMM HH:mm', 'YY DD MMM HH:mm', 'D MMM HH:mm', 'DD MMM HH:mm', 'YYYY MMM D', 'YYYY MMM DD', 'YYYY D MMM', 'YYYY DD MMM', 'D MMM YY', 'DD MMM YY', 'D MMM YYYY', 'DD MMM YYYY', 'D MMM YY', 'DD MMM YY', 'D MMM YYYY', 'DD MMM YYYY', 'MMM D YYYY', 'MMM DD YYYY', 'YY MMM D', 'YY MMM DD', 'YY D MMM', 'YY DD MMM', 'YYYY MMM D HH:mm', 'YYYY MMM DD HH:mm', 'YYYY D MMM HH:mm', 'YYYY DD MMM HH:mm', 'D MMM YY HH:mm', 'DD MMM YY HH:mm', 'D MMM YYYY HH:mm', 'DD MMM YYYY HH:mm', 'D MMM YY HH:mm', 'DD MMM YY HH:mm', 'D MMM YYYY HH:mm', 'DD MMM YYYY HH:mm', 'MMM D YYYY HH:mm', 'MMM DD YYYY HH:mm', 'YY MMM D HH:mm', 'YY MMM DD HH:mm', 'YY D MMM HH:mm', 'YY DD MMM HH:mm'];\n","import PropTypes from 'prop-types';\nimport moment from 'moment';\n\nimport formats from './formats';\n\nconst unit = 8; // px;\nconst units = {\n unit,\n /* eslint-disable no-magic-numbers */\n cellSize: unit * 3,\n calHeight: unit * 36,\n yearHeight: unit * 4\n /* eslint-enable */\n};\n\nexport default units;\n\nexport const YEAR = 12;\nexport const WEEK = 7;\nexport const weekdays = {\n MO: 1,\n TU: 2,\n WE: 3,\n TH: 4,\n FR: 5,\n SA: 6,\n SU: 0\n};\nexport const MIDDLE_DAY = 15;\n\nexport const yearDuration = +moment.duration(1, 'year');\nexport const yearScrollSpeed = yearDuration / (YEAR * units.cellSize);\n\nexport const DOUBLE = 2;\nexport const HALF = 0.5;\n\nexport function linear(x0, y0, a) {\n return {\n y(x) {\n return +y0 + (x - x0) * a;\n },\n\n x(y) {\n return +x0 + (y - y0) / a;\n }\n };\n}\n\nexport const dateType = PropTypes.oneOfType([\n (props, propName) => {\n if (!moment.isMoment(props[propName])) {\n return new Error(\n `${propName} should be a string, number, Date object or Moment object`\n );\n }\n return undefined;\n },\n PropTypes.instanceOf(Date),\n PropTypes.string,\n PropTypes.number\n]);\n\nconst parsed = Object.create(null);\nexport function parseDate(text, ...addFormats) {\n let date;\n if (typeof text !== 'string') {\n date = moment(text);\n } else {\n\n const key = `${text}__${addFormats.join('__')}`;\n if (!(key in parsed)) {\n const extendedFormats = [\n ...addFormats,\n ...formats\n ];\n parsed[key] = moment(text, extendedFormats);\n }\n\n date = parsed[key];\n }\n return date.isValid() ? date : null;\n}\n\nexport function parseTime(time) {\n let result = null;\n if (/^([01][0-9]|2[0-3]):[0-5][0-9]$/.test(time)) {\n result = time;\n } else if (/^([0-9]|2[0-3]):[0-5][0-9]$/.test(time)) {\n result = `0${time}`;\n }\n\n return result;\n}\n","import React, {Component} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport moment from 'moment';\n\nimport {dateType, weekdays} from './consts';\nimport styles from './date-picker.css';\n\nlet hoverTO;\nexport default class Day extends Component {\n handleClick = () => this.props.onSelect(this.props.day);\n\n handleMouseOver = () => {\n if (hoverTO) {\n window.clearTimeout(hoverTO);\n hoverTO = null;\n }\n\n this.props.onHover(this.props.day);\n };\n\n handleMouseOut = () => {\n hoverTO = window.setTimeout(this.props.onHover, 0);\n };\n\n isDay = date => this.props.day.isSame(date, 'day');\n\n is = name => this.props[name] && this.isDay(this.props[name]);\n\n inRange = range => range && this.props.day.isBetween(...range, 'days');\n\n isDisabled = date => (this.props.minDate && date.isBefore(this.props.minDate, 'day')) ||\n (this.props.maxDate && date.isAfter(this.props.maxDate, 'day'));\n\n render() {\n const {\n day,\n from,\n currentRange,\n activeRange,\n empty\n } = this.props;\n\n const reverse = activeRange && activeRange[1] === from;\n\n function makeSpreadRange(range) {\n return range && [range[0], range[1].clone().add(1, 'days')];\n }\n\n const spreadRange = makeSpreadRange(currentRange);\n const disabled = this.isDisabled(day);\n const activeSpreadRange = makeSpreadRange(activeRange); return (\n // TODO make keyboard navigation actually work\n \n {empty || (\n \n {day.format('D')}\n )}\n \n );\n }\n}\n\nDay.propTypes = {\n day: dateType,\n from: dateType,\n currentRange: PropTypes.arrayOf(dateType),\n activeRange: PropTypes.arrayOf(dateType),\n empty: PropTypes.bool,\n onSelect: PropTypes.func,\n onHover: PropTypes.func,\n minDate: dateType,\n maxDate: dateType\n};\n","import React from 'react';\nimport classNames from 'classnames';\nimport PropTypes from 'prop-types';\n\nimport Input from '../input/input';\n\nimport {dateType} from './consts';\nimport styles from './date-picker.css';\n\nexport default class DateInput extends React.PureComponent {\n static propTypes = {\n active: PropTypes.bool,\n divider: PropTypes.bool,\n name: PropTypes.string,\n text: PropTypes.string,\n hoverDate: dateType,\n date: dateType,\n time: PropTypes.string,\n inputFormat: PropTypes.string,\n hidden: PropTypes.bool,\n onInput: PropTypes.func,\n onActivate: PropTypes.func,\n onConfirm: PropTypes.func,\n onClear: PropTypes.func\n };\n\n componentDidUpdate(prevProps) {\n const {hidden, text, active} = this.props;\n if (!hidden && prevProps.hidden || text !== prevProps.text || active !== prevProps.active) {\n this.updateInput({text, active});\n }\n }\n\n inputRef = el => {\n this.input = el;\n this.updateInput(this.props);\n };\n\n updateInput({text, active}) {\n const el = this.input;\n if (!el) {\n return;\n }\n\n if (active) {\n el.focus();\n if (!text) {\n el.select();\n }\n } else {\n el.blur();\n }\n }\n\n handleChange = e => this.props.onInput(e.target.value, e.target.dataset.name);\n\n handleKeyDown = e => e.key === 'Enter' && this.props.onConfirm();\n\n render() {\n const {\n active,\n divider,\n text,\n time,\n name,\n hoverDate,\n date,\n inputFormat,\n onActivate,\n onClear\n } = this.props;\n\n let displayText = '';\n if (active && hoverDate) {\n displayText = hoverDate.format(inputFormat);\n } else if (active && text != null) {\n displayText = text;\n } else if (date) {\n displayText = date.format(inputFormat);\n } else if (name === 'time') {\n displayText = time || '';\n }\n\n const placeholder = (() => {\n switch (name) {\n case 'from':\n return 'Add first date';\n case 'to':\n return 'Add second date';\n case 'time':\n return 'Add time';\n default:\n return `Select ${name}`;\n }\n })();\n\n const classes = classNames(\n styles.filter,\n styles[`${name}Input`],\n divider && styles[`${name}InputWithDivider`],\n 'ring-js-shortcuts'\n );\n\n return (\n \n );\n }\n}\n","import React from 'react';\n\nimport Day from './day';\nimport {dateType, WEEK, weekdays} from './consts';\nimport styles from './date-picker.css';\n\nexport default function Month(props) {\n const start = props.month;\n const end = start.\n clone().\n endOf('month');\n\n // pad with empty cells starting from last friday\n const weekday = start.day();\n let day = start.\n clone().\n weekday(weekday >= weekdays.FR ? weekdays.FR : weekdays.FR - WEEK);\n const days = [];\n while (day < end) {\n days.push(day);\n day = day.\n clone().\n add(1, 'day');\n }\n\n return (\n
    \n \n {props.month.format('MMMM')}\n \n {days.map(date => (\n \n ))}\n
    \n );\n}\n\nMonth.propTypes = {\n month: dateType\n};\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport moment from 'moment';\n\nimport linearFunction from '../global/linear-function';\n\n\nimport units, {dateType, yearScrollSpeed} from './consts';\nimport styles from './date-picker.css';\n\nconst COVERYEARS = 3;\n\nexport default class MonthSlider extends PureComponent {\n static propTypes = {\n scrollDate: dateType,\n onScroll: PropTypes.func,\n pxToDate: PropTypes.shape({\n x: PropTypes.func,\n y: PropTypes.func\n })\n };\n\n state = {\n dragging: false\n };\n\n componentDidUpdate(prevProps, prevState) {\n if (this.state.dragging && !prevState.dragging) {\n window.addEventListener('mousemove', this.onMouseMove);\n window.addEventListener('mouseup', this.onMouseUp);\n } else if (!this.state.dragging && prevState.dragging) {\n window.removeEventListener('mousemove', this.onMouseMove);\n window.removeEventListener('mouseup', this.onMouseUp);\n }\n }\n\n onMouseDown = () => {\n this.setState({dragging: true});\n };\n\n onMouseUp = () => {\n this.setState({dragging: false});\n };\n\n onMouseMove = e => {\n this.props.onScroll(\n linearFunction(0, this.props.scrollDate, yearScrollSpeed).y(e.movementY)\n );\n };\n\n render() {\n let year = moment(this.props.scrollDate).\n startOf('day').\n subtract(1, 'year');\n const years = [year];\n for (let i = 0; i <= COVERYEARS; i++) {\n year = year.\n clone().\n add(1, 'year');\n years.push(year);\n }\n\n const classes = classNames(\n styles.monthSlider,\n {[styles.dragging]: this.state.dragging}\n );\n\n return (\n
    \n {years.map(date => (\n \n ))}\n
    \n );\n }\n}\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport moment from 'moment';\n\nimport linearFunction from '../global/linear-function';\n\nimport MonthSlider from './month-slider';\nimport {dateType, HALF, YEAR, MIDDLE_DAY, yearScrollSpeed} from './consts';\nimport styles from './date-picker.css';\n\nclass MonthName extends PureComponent {\n handleClick = () => {\n const end = this.props.month.\n clone().\n endOf('month');\n this.props.onScrollChange((this.props.month + end) * HALF);\n };\n\n render() {\n const {month} = this.props;\n\n return (\n \n {month.format('MMM')}\n \n );\n }\n}\n\nMonthName.propTypes = {\n month: dateType,\n onScrollChange: PropTypes.func\n};\n\nexport default function MonthNames(props) {\n const scrollDate = moment(props.scrollDate);\n const months = [];\n for (let i = 0; i < YEAR; i++) {\n months.push(\n scrollDate.\n clone().\n month(i).\n date(MIDDLE_DAY).\n startOf('day')\n );\n }\n\n const pxToDate = linearFunction(\n 0,\n moment(props.scrollDate).startOf('year'),\n yearScrollSpeed\n );\n\n let top = 0;\n let bottom = 0;\n if (props.currentRange) {\n [top, bottom] = props.currentRange.\n map(date => Math.floor(pxToDate.x(date)));\n }\n\n return (\n
    \n {months.map(month => (\n \n ))}\n {props.currentRange &&\n (\n \n )\n }\n \n
    \n );\n}\n\nMonthNames.propTypes = {\n scrollDate: dateType,\n onScrollChange: PropTypes.func,\n currentRange: PropTypes.arrayOf(dateType)\n};\n","import React from 'react';\nimport PropTypes from 'prop-types';\nimport moment from 'moment';\n\nimport scheduleRAF from '../global/schedule-raf';\nimport linearFunction from '../global/linear-function';\n\nimport Month from './month';\nimport MonthNames from './month-names';\nimport styles from './date-picker.css';\nimport units, {dateType, DOUBLE, HALF, WEEK, weekdays} from './consts';\n\nconst {unit, cellSize, calHeight} = units;\n\nconst FridayToSunday = WEEK + weekdays.SU - weekdays.FR;\nconst FIVELINES = 31;\nconst TALLMONTH = 6;\nconst SHORTMONTH = 5;\nconst PADDING = 2;\n\nconst MONTHSBACK = 2;\n\nfunction monthHeight(date) {\n const monthStart = moment(date).startOf('month');\n const daysSinceLastFriday = (monthStart.day() + FridayToSunday) % WEEK;\n const monthLines =\n daysSinceLastFriday + monthStart.daysInMonth() > FIVELINES ? TALLMONTH : SHORTMONTH;\n return monthLines * cellSize + unit * PADDING;\n}\n\n// in milliseconds per pixel\nfunction scrollSpeed(date) {\n const monthStart = moment(date).startOf('month');\n const monthEnd = moment(date).endOf('month');\n return (monthEnd - monthStart) / monthHeight(monthStart);\n}\n\nconst scrollSchedule = scheduleRAF();\nlet dy = 0;\nexport default function Months(props) {\n const scrollDate = moment(props.scrollDate);\n const monthStart = scrollDate.\n clone().\n date(1).\n // prevent switching from april to march because of daylight saving time\n hours(1).\n startOf('hour');\n\n let month = monthStart.\n clone().\n subtract(MONTHSBACK, 'months');\n const months = [month];\n for (let i = 0; i < MONTHSBACK * DOUBLE; i++) {\n month = month.\n clone().\n add(1, 'month');\n months.push(month);\n }\n\n const currentSpeed = scrollSpeed(scrollDate);\n const pxToDate = linearFunction(0, scrollDate, currentSpeed);\n const offset = pxToDate.x(monthStart); // is a negative number\n const bottomOffset = monthHeight(scrollDate) + offset;\n\n return (\n {\n let date;\n\n // adjust scroll speed to prevent glitches\n if (dy < offset) {\n date = pxToDate.y(offset) + (dy - offset) * scrollSpeed(months[1]);\n } else if (dy > bottomOffset) {\n date =\n pxToDate.y(bottomOffset) +\n (dy - bottomOffset) *\n scrollSpeed(months[MONTHSBACK + 1]);\n } else {\n date = pxToDate.y(dy);\n }\n\n props.onScroll(date);\n dy = 0;\n });\n }}\n >\n \n {months.map(date => (\n \n ))}\n
    \n \n \n );\n}\n\nMonths.propTypes = {\n onScroll: PropTypes.func,\n scrollDate: dateType\n};\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport moment from 'moment';\n\nimport linearFunction from '../global/linear-function';\n\n\nimport styles from './date-picker.css';\nimport units, {dateType, DOUBLE, HALF, yearDuration} from './consts';\n\nconst {yearHeight, calHeight} = units;\n\nlet scrollTO;\n\nconst YEARSBACK = 5;\nconst scrollDelay = 100;\n\nexport default class Years extends PureComponent {\n static propTypes = {\n scrollDate: dateType,\n onScroll: PropTypes.func,\n onScrollChange: PropTypes.func\n };\n\n state = {scrollDate: null};\n\n componentDidUpdate(prevProps, prevState) {\n this.stoppedScrolling = prevState.scrollDate && !this.state.scrollDate;\n }\n\n setYear(date) {\n if (scrollTO) {\n window.clearTimeout(scrollTO);\n scrollTO = null;\n }\n\n this.setState({scrollDate: null});\n\n this.props.onScroll(\n moment(this.props.scrollDate).\n year(moment(date).year())\n );\n }\n\n render() {\n const {onScrollChange, scrollDate} = this.props;\n const date = moment(this.state.scrollDate || scrollDate);\n const yearStart = date.clone().startOf('year');\n let year = yearStart.\n clone().\n subtract(YEARSBACK, 'years');\n const years = [year];\n for (let i = 0; i < YEARSBACK * DOUBLE; i++) {\n year = year.\n clone().\n add(1, 'year');\n years.push(year);\n }\n\n const pxToDate = linearFunction(0, years[0], yearDuration / yearHeight);\n\n const handleWheel = e => {\n e.preventDefault();\n const newScrollDate = linearFunction(0, date, yearDuration / yearHeight).\n y(e.deltaY);\n this.setState({\n scrollDate: newScrollDate\n });\n if (scrollTO) {\n window.clearTimeout(scrollTO);\n }\n scrollTO = window.setTimeout(() => this.setYear(newScrollDate), scrollDelay);\n };\n\n return (\n \n {years.map(item => (\n \n {item.format('YYYY')}\n \n ))}\n \n );\n }\n}\n","import React from 'react';\nimport classNames from 'classnames';\nimport moment from 'moment';\n\nimport {weekdays} from './consts';\nimport styles from './date-picker.css';\n\nexport default function Weekdays() {\n const days = Object.keys(weekdays).\n map(key => moment().day(weekdays[key]).startOf('day'));\n\n return (\n
    \n {days.map(day => (\n \n {day.format('dd')}\n \n ))}\n
    \n );\n}\n","import React, {Component} from 'react';\nimport PropTypes from 'prop-types';\nimport moment from 'moment';\nimport calendarIcon from '@jetbrains/icons/calendar.svg';\n\nimport Icon from '../icon';\nimport memoize from '../global/memoize';\n\nimport DateInput from './date-input';\nimport Months from './months';\nimport Years from './years';\nimport Weekdays from './weekdays';\nimport {dateType, parseDate, parseTime} from './consts';\nimport styles from './date-picker.css';\n\nconst scrollExpDelay = 10;\n\nexport default class DatePopup extends Component {\n\n static sameDay(next, prev, inputFormat, displayFormat) {\n const nextMoment = parseDate(next, inputFormat, displayFormat);\n const prevMoment = parseDate(prev, inputFormat, displayFormat);\n if (nextMoment && prevMoment) {\n return nextMoment.isSame(prevMoment, 'day');\n }\n\n return next === prev;\n }\n\n static propTypes = {\n className: PropTypes.string,\n date: dateType,\n range: PropTypes.bool,\n withTime: PropTypes.bool,\n time: PropTypes.string,\n from: dateType,\n to: dateType,\n displayFormat: PropTypes.string,\n inputFormat: PropTypes.string,\n onChange: PropTypes.func,\n onComplete: PropTypes.func,\n onClear: PropTypes.func,\n minDate: dateType,\n maxDate: dateType,\n hidden: PropTypes.bool\n };\n\n static defaultProps = {\n onChange() {}\n };\n\n constructor(props) {\n super(props);\n const defaultState = {\n text: null,\n hoverDate: null,\n scrollDate: null\n };\n const {range, from, to, date, time, withTime} = props;\n\n if (!range) {\n const parsedTime = this.parse(time, 'time');\n const parsedDate = this.parse(date, 'date');\n const active = withTime && parsedDate && !parsedTime ? 'time' : 'date';\n\n this.state = {...defaultState, active};\n } else if (from && !to) {\n this.state = {...defaultState, active: 'to'};\n } else {\n this.state = {...defaultState, active: 'from'};\n }\n }\n\n componentDidMount() {\n if (this.componentRef.current) {\n this.componentRef.current.addEventListener('wheel', this.handleWheel);\n }\n }\n\n componentDidUpdate(prevProps, prevState) {\n if (this.state.active !== prevState.active) {\n if (this.state.text && prevState.active) {\n this.confirm(prevState.active);\n }\n // eslint-disable-next-line react/no-did-update-set-state\n this.setState({text: null});\n }\n }\n\n componentWillUnmount() {\n if (this.componentRef.current) {\n this.componentRef.current.removeEventListener('wheel', this.handleWheel);\n }\n }\n\n isInTimeMode = () => !this.props.range && this.props.withTime || false;\n\n componentRef = React.createRef();\n\n handleWheel = e => {\n e.preventDefault();\n };\n\n parse(text, type) {\n return (type === 'time')\n ? parseTime(text)\n : parseDate(text, this.props.inputFormat, this.props.displayFormat);\n }\n\n select(changes) {\n const {range, withTime} = this.props;\n const prevActive = this.state.active;\n const date = this.parse(this.props.date, 'date');\n const time = this.parse(this.props.time, 'time');\n\n if (!range && !withTime) {\n this.setState({\n text: null,\n scrollDate: null\n });\n this.props.onChange(changes.date);\n this.props.onComplete();\n } else if (!range && withTime) {\n const changeToSubmit = {\n date: changes.date || date,\n time: changes.time || time\n };\n\n this.setState({\n active: changes.date ? 'time' : 'date',\n text: null,\n scrollDate: null\n });\n\n this.props.onChange(changeToSubmit);\n if (\n !changes.date && prevActive === 'time' &&\n changeToSubmit.date && changeToSubmit.time\n ) {\n this.props.onComplete();\n }\n } else {\n let {from, to} = {\n ...this.props,\n ...changes\n };\n from = this.parse(from, 'from');\n to = this.parse(to, 'to');\n\n // proceed to setting the end by default\n let active = 'to';\n let complete = false;\n\n // end is before beginning\n if (from && to && from.isAfter(to, 'days')) {\n // ignore the old end when beginning is changed\n if (changes.from) {\n to = null;\n\n // treat range as reverse when end is changed\n } else if (changes.to) {\n to = from;\n from = changes.to;\n }\n } else if (changes.to) {\n active = 'from';\n complete = !!from;\n }\n\n this.setState({\n active,\n hoverDate: null,\n text: null\n });\n this.props.onChange({from, to});\n if (complete) {\n this.props.onComplete();\n }\n }\n }\n\n confirm(name) {\n const text = this.state.text;\n\n let result = this.parse(text, name);\n if (name === 'time') {\n const time = this.parse(this.props.time, 'time');\n\n const emptyCase = this.state.active === 'time' ? '00:00' : null;\n result = result || time || emptyCase;\n } else if (!this.isValidDate(result)) {\n result = this.parse(this.props[name], name);\n }\n\n this.select({\n [name]: result\n });\n }\n\n isValidDate = parsedText => {\n const minDate = this.parse(this.props.minDate, 'date');\n const maxDate = this.parse(this.props.maxDate, 'date');\n\n if (parsedText) {\n return (!(\n minDate && parsedText.isBefore(minDate) ||\n maxDate && parsedText.isAfter(maxDate)\n ));\n }\n return false;\n };\n\n scheduleScroll = () => {\n const current =\n this.state.scrollDate ||\n this.parse(this.props[this.state.active], 'date') ||\n moment();\n const goal = this._scrollDate;\n if (!current ||\n !goal ||\n DatePopup.sameDay(goal, current, this.props.inputFormat, this.props.displayFormat)\n ) {\n this._scrollDate = null;\n this._scrollTS = null;\n return;\n }\n\n if (this._scrollTS) {\n const diff = goal - current;\n const dt = moment() - this._scrollTS;\n const next = goal - diff * (Math.E ** (-dt / scrollExpDelay));\n this.setState({scrollDate: next});\n }\n\n this._scrollTS = moment();\n window.requestAnimationFrame(this.scheduleScroll);\n };\n\n scrollTo = scrollDate => {\n this._scrollDate = scrollDate;\n if (!this._scrollTS) {\n this.scheduleScroll();\n }\n };\n\n hoverHandler = hoverDate => this.setState({hoverDate});\n\n handleActivate = memoize(name => () => this.setState({active: name}));\n\n handleInput = (text, name) => {\n const parsed = this.parse(text, name);\n if (name !== 'time' && this.isValidDate(parsed)) {\n this.scrollTo(parsed);\n }\n this.setState({\n text,\n hoverDate: null\n });\n };\n\n handleConfirm = memoize(name => () => this.confirm(name));\n\n selectHandler = date => {\n if (this.isInTimeMode()) {\n this.setState({\n active: 'time'\n }, () => this.select({date}));\n } else {\n this.select({[this.state.active]: date});\n }\n };\n\n handleScroll = scrollDate => this.setState({scrollDate});\n\n render() {\n const {range, hidden, withTime} = this.props;\n const parsedTime = this.parse(this.props.time, 'time');\n const parsedDate = this.parse(this.props.date, 'date');\n const parsedTo = this.parse(this.props.to, 'to');\n\n const names = range ? ['from', 'to'] : ['date'];\n const dates = names.reduce((obj, key) => {\n const date = this.props[key];\n return {\n ...obj,\n [key]: this.parse(date, key)\n };\n }, {});\n\n const activeDate = this.state.active !== 'time'\n ? this.state.hoverDate || this.state.text && this.parse(this.state.text, 'date')\n : this.state.hoverDate || null;\n\n const currentRange = range && dates.from && dates.to && [dates.from, dates.to] || null;\n let activeRange = null;\n if (range && activeDate) {\n switch (this.state.active) {\n case 'from':\n if (dates.to && !activeDate.isAfter(dates.to, 'days')) {\n activeRange = [activeDate, dates.to];\n }\n\n break;\n case 'to':\n if (!dates.from) {\n break;\n }\n if (activeDate.isBefore(dates.from, 'days')) {\n activeRange = [activeDate, dates.from];\n } else {\n activeRange = [dates.from, activeDate];\n }\n\n break;\n default:\n break;\n }\n }\n\n const scrollDate = withTime && !range\n ? this.state.scrollDate || dates.date || moment()\n : this.state.scrollDate || dates[this.state.active] || moment();\n\n const calendarProps = {\n ...this.props,\n ...this.state,\n ...dates,\n scrollDate,\n activeDate,\n currentRange,\n activeRange,\n onScroll: this.handleScroll,\n onScrollChange: this.scrollTo\n };\n\n return (\n \n
    \n \n {names.map(name => (\n
    \n \n \n \n \n \n \n );\n }\n}\n","import React, {PureComponent} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport rerenderHOC from '../global/rerender-hoc';\n\nimport Popup from '../popup/popup';\nimport Dropdown, {Anchor} from '../dropdown/dropdown';\n\nimport DatePopup from './date-popup';\nimport {dateType, parseDate, parseTime} from './consts';\nimport styles from './date-picker.css';\n\nconst PopupComponent = ({\n hidden,\n className,\n popupRef,\n onClear,\n datePopupProps,\n onComplete,\n ...restProps\n}) => (\n