Compare commits

...

639 Commits

Author SHA1 Message Date
ccb65893bf docs(changelog): release notes for 4.0.0-beta.2 2017-01-05 17:18:21 -08:00
3e90ffd293 chore(release): cut the 4.0.0-beta.2 release 2017-01-05 16:58:31 -08:00
8063b0d9a2 fix(language-service): support TypeScript 2.1 (#13655)
@angular/language-service now supports using TypeScript 2.1 as the
the TypeScript host. TypeScript 2.1 is now also partially supported
in `ngc` but is not recommended as Tsickle does not yet support 2.1.
2017-01-05 11:34:42 -08:00
21030e9a1c fix(core): animations no longer silently exits if the element is not apart of the DOM (#13763) 2017-01-05 11:33:40 -08:00
889b48d85f fix(core): animations should blend in all previously transitioned styles into next animation if interrupted (#13148) 2017-01-05 11:32:52 -08:00
1bd04e95de refactor: remove unused imports 2017-01-05 11:18:34 -08:00
f88cd2f22e fix(Common): allow null/undefined values for NgForTrackBy
Reverts a breaking change introduced in 2.4.1 by #13420
fixes #13641
2017-01-05 11:18:34 -08:00
f822f9599c docs(common): add an example how to bind multiple classes based on a single parameter (#13779)
Closes #13778
2017-01-05 10:21:38 -08:00
9898d8f6d9 fix(forms): Validators.required properly validate arrays (#13362)
Closes #12274
2017-01-05 09:25:20 -08:00
2dd6280ab8 fix(common): do not override locale provided on bootstrap (#13654)
Closes #13607
2017-01-05 09:24:37 -08:00
35f9a1c2cb docs(developer): add linting section and correct command to verify API changes 2017-01-03 14:08:52 -08:00
465516b905 refactor(core): remove backwards compatibility of SimpleChange
BREAKING CHANGE:
`SimnpleChange` now takes an additional argument that defines
whether this is the first change or not.
2017-01-03 13:05:05 -08:00
db49d422f2 refactor(compiler): generate less code for bindings to DOM elements
Detailed changes:
- remove `UNINITIALIZED`, initialize change detection fields with `undefined`.
  * we use `view.numberOfChecks === 0` now everywhere
    as indicator whether we are in the first change detection cycle
    (previously we used this only in a couple of places).
  * we keep the initialization itself as change detection get slower without it.
- remove passing around `throwOnChange` in various generated calls,
  and store it on the view as property instead.
- change generated code for bindings to DOM elements as follows:
  Before:
  ```
  var currVal_10 = self.context.bgColor;
  if (jit_checkBinding15(self.throwOnChange,self._expr_10,currVal_10)) {
    self.renderer.setElementStyle(self._el_0,'backgroundColor',((self.viewUtils.sanitizer.sanitize(jit_21,currVal_10) == null)? null: self.viewUtils.sanitizer.sanitize(jit_21,currVal_10).toString()));
    self._expr_10 = currVal_10;
  }
  var currVal_11 = jit_inlineInterpolate16(1,' ',self.context.data.value,' ');
  if (jit_checkBinding15(self.throwOnChange,self._expr_11,currVal_11)) {
    self.renderer.setText(self._text_1,currVal_11);
    self._expr_11 = currVal_11;
  }
  ```,
  After:
  ```
  var currVal_10 = self.context.bgColor;
  jit_checkRenderStyle14(self,self._el_0,'backgroundColor',null,self._expr_10,self._expr_10=currVal_10,false,jit_21);
  var currVal_11 = jit_inlineInterpolate15(1,' ',self.context.data.value,' ');
  jit_checkRenderText16(self,self._text_1,self._expr_11,self._expr_11=currVal_11,false);
  ```

Performance impact:
- None seen (checked against internal latency lab)

Part of #13651
2017-01-03 13:05:05 -08:00
8ed92d75b0 refactor(benchmarks): make ftl benchmarks use their own version of checkBinding 2017-01-03 13:05:05 -08:00
50e5cb15dd feat(benchmarks): add detectChanges test for ng2 tree benchmark 2017-01-03 13:05:05 -08:00
c5c53f3666 fix(core): Remove reference to "Angular 2" in dev mode warning (#13751) 2017-01-03 10:03:58 -08:00
bb0d23f82b Typo (#13698) 2016-12-29 09:41:21 -08:00
1e6440e81b docs(Http): fix and extend samples for testing/MockBackend (#13689)
Fix samples for MockBackend and MockBackend.connections that were outdated. Also extend central sample for MockBackend to ease getting started.
2016-12-29 09:39:00 -08:00
6b02b80a03 fix(compiler): improve error message for undefined providers (#13546)
Closes #10835
2016-12-27 17:05:14 -08:00
2c0c86e3ce fix(compiler): improve the error when template is not a string
Closes #8708
Closes #13377
2016-12-27 17:04:16 -08:00
5b4bea24de refactor(compiler): clean up directive normalizer 2016-12-27 17:03:58 -08:00
7690d02133 fix(compiler): don’t throw when using ANALYZE_FOR_ENTRY_COMPONENTS with user classes (#13679)
Fixed #13565
2016-12-27 16:58:52 -08:00
b2ae7b607e docs(Core): fix API docs for ContentChild and ViewChildren (#13656)
Move the documentations of the ContentChild and ViewChildren decorators
so that they appear correctly on angular.io.

Closes #13625
2016-12-27 16:58:33 -08:00
7c210645a3 fix(compiler): query <template> elements before their children. (#13677)
Fixes #13118
Closes #13167
2016-12-27 16:28:54 -08:00
07e0fce8fc fix(router): update route snapshot before emit new values (#13558)
Closes #12912
2016-12-27 15:57:22 -08:00
0ac8e102de test(i18n): add extraction to integration specs
Closes #13648.
2016-12-27 15:32:54 -08:00
e74d8aaf92 fix(i18n): parse ICU messages while normalizing templates
Fixes:
- Inject the i18n specific HtmlParser into the directive normalizer,
- Parse ICU messages while normalizing templates,
- Normalize (visit) the content of ICU messages.

🎄🎁🎅
2016-12-27 15:32:43 -08:00
881eb894bc fix(Compiler): allow "." in attribute selectors (#13653)
fixes #13645
2016-12-27 15:23:49 -08:00
0eca960494 fix(router): fix lazy loaded module with wildcard route (#13649)
Closes #12955
2016-12-27 15:22:57 -08:00
eed83443b8 chore(tslint): update tslint to 4.x (#13603) 2016-12-27 14:55:58 -08:00
e5c4e5801f fix(upgrade): fix/improve support for lifecycle hooks (#13020)
With the exception of `$onChanges()`, all lifecycle hooks in ng1 are called on
the controller, regardless if it is the binding destination or not (i.e.
regardless of the value of `bindToController`).

This change makes `upgrade` mimic that behavior when calling lifecycle hooks.

Additionally, calling the `$onInit()` hook has been moved before calling the
linking functions, which also mimics the ng1 behavior.
2016-12-27 14:42:53 -08:00
69fa3bbc03 feat(router): add an extra argument to CanDeactivate interface (#13560)
Adds a `nextState` argument to access the future url from `CanDeactivate`.

BEFORE:

    canDeactivate(component: T, route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|Promise<boolean>|boolean;

AFTER:

    canDeactivate(component: T, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): Observable<boolean>|Promise<boolean>|boolean;

Closes #9853
2016-12-27 14:08:06 -08:00
445ed43b9a fix(compiler): throw an error for invalid provider (#13544)
Closes #8870
2016-12-27 14:02:28 -08:00
174334dec3 fix(router): routerLink support of null/undefined (#13380)
Closes #6971
2016-12-27 13:45:16 -08:00
9c697030e6 feat(compiler): generate proper reexports in .ngfactory.ts files to not need transitive deps for compiling .ngfactory.ts files. (#13524)
Note: This checks the constructors of `@Injectable` classes more strictly.
E.g this will fail now as the constructor argument has no `@Inject` nor is
the type of the argument a DI token.

```
@Injectable()
class MyService {
  constructor(dep: string) {}
}
```

Last part of #12787
Closes #12787
2016-12-27 09:36:47 -08:00
697690349f fix(common): add link to trackBy docs (#13634) 2016-12-22 13:25:51 -08:00
0448e80704 docs(examples): fix example path (#13635) 2016-12-22 13:25:21 -08:00
e85232afd2 docs(ngIf): fix typos (#13630) 2016-12-22 12:36:47 -08:00
e7ece6c8ce fixed minor typo (#13626) 2016-12-22 12:36:24 -08:00
67380d4b28 fix(testing): improve misleading error message when don't call compileComponents (#13543)
Closes #11301
2016-12-22 12:35:57 -08:00
f114e40212 docs(changelog): add changelog for 4.0.0-beta.1 2016-12-21 16:48:14 -08:00
952471e25d chore(release): cut the 4.0.0-beta.1 release 2016-12-21 16:44:56 -08:00
c65e428778 docs(changelog): add changelog for 2.4.1 2016-12-21 16:43:13 -08:00
842f52e841 fix(animations): always recover from a failed animation step (#13604) 2016-12-21 14:14:45 -08:00
eb2ceff4ba fix(router): should reset location if a navigation by location is successful (#13545)
Closes #13491
2016-12-21 12:47:58 -08:00
f49ab56160 fix(animations): always quote string map key values in AOT code (#13602) 2016-12-20 18:17:58 -08:00
c0f750af4e fix(compiler): ignore @import in comments (#13368)
* refactor(compiler): clean up style url resolver
* fix(compiler): ignore @import in css comments

Closes #12196
2016-12-20 17:51:02 -08:00
bcd37f52fb Include bower instructions in DEVELOPER.md (#13591) 2016-12-20 17:50:04 -08:00
e69c1fb36c refactor(platform-browser): resolver merge conflict for tslint (#13601) 2016-12-20 17:49:25 -08:00
9da4c259a5 feat(upgrade): support the $doCheck() lifecycle hook in UpgradeComponent (#13015) 2016-12-20 16:18:43 -08:00
fcd116fdc0 fix(common): throw an error if trackBy is not a function (#13420)
* fix(common): throw an error if trackBy is not a function

Closes #13388

* refactor(platform-browser): disable no-console rule in DomAdapter
2016-12-20 16:18:24 -08:00
383adc9ad9 fix(core): improve error message when component factory cannot be found (#13541)
Closes #12678
2016-12-20 16:17:22 -08:00
9b8488f007 build: fix publish-build-artifacts branch detection (#13599) 2016-12-20 15:59:15 -08:00
1817ddb57b build: publish build artifacts to branches (#13529)
Fix #13126
2016-12-20 14:52:50 -08:00
1ee574c51e docs(changelog): add changelog for 2.4.0 2016-12-20 11:14:28 -08:00
171a9bdc85 feat: update to rxjs@5.0.1 and unpin the rxjs peerDeps via ^5.0.1 (#13572)
Now that rxjs is stable and the rxjs team follows semver, we can update and unpin the dependency safely.

From now on the Angular application/library developers are in charge of controlling the rxjs version as long as it's newer than 5.0.1.

closes #13561
closes #13478
closes #13572
2016-12-19 16:24:53 -08:00
896916af29 build(npm): update angular version in shrinkwrap files 2016-12-19 16:23:54 -08:00
e49c7fae22 refactor(compiler-cli): support extracting the mesage bundle without writing a file (#13580) 2016-12-19 15:28:55 -08:00
6b65fc1286 feat(compiler-cli): private i18n API for the CLI (#13536)
Also change the Extractor API to align with the Codegen API (internal APIs)
2016-12-19 11:56:10 -08:00
0e3981afc1 fix(compiler-cli): produce metadata for .d.ts files without metadata (#13526)
Fixes #13307
Fixes #13473
Fixes #13521
2016-12-16 15:33:47 -08:00
e78508507d fix(compiler): do not lex }} when interpolation is disabled (#13531)
* doc(compiler): fix the ICU expander API docs

* test(compiler): add lexer and parser specs

* fix(compiler): do not lex `}}` when interpolation is disabled

fix #13525
2016-12-16 15:33:16 -08:00
a23fa94ca8 fix(common): capitalize first letter of all words in TitleCasePipe (#13511) 2016-12-16 15:24:26 -08:00
4568d5ddac refactor(core): fix typo (#13515)
Closes #13512
2016-12-16 15:21:58 -08:00
c6e893953f fix(upgrade): fix registerForNg1Tests (#13522)
Fix an issue in `registerForNg1Tests`, where it passes a `null` as
`ng1Injector` to `_bootstrapDone`. This causes a "TypeError: Cannot
read property 'get' of null" to be thrown from `_bootstrapDone`.
2016-12-16 15:14:16 -08:00
55dfa1b69d test(forms): refactor integration tests to improve speed (#13500) 2016-12-15 17:07:26 -08:00
0fe3cd9a4c fix(i18n): add a default example to xmb placeholders (#13507)
Otherwise the TC would not be able to load the message
2016-12-15 15:33:42 -08:00
0c19898694 fix(animations): allow players to be destroyed before initialized (#13346)
Closes #13293
Closes #13346
2016-12-15 14:18:57 -08:00
5b6e8ea3ec refactor(compiler): format update (#13506) 2016-12-15 13:54:38 -08:00
732f446ad2 docs(common): fix ngIf example (#13496) 2016-12-15 13:07:36 -08:00
f0e092515c refactor(compiler): don't print stack trace on template parse errors (#13390) 2016-12-15 13:07:12 -08:00
14e785f5b7 fix(build): use bash string comparison operator (#13502) 2016-12-15 12:05:29 -08:00
01d1624884 feature(DEVELOPER.md): add easy way to publish personal snapshot builds (#13469) 2016-12-15 11:19:21 -08:00
33910ddfc9 refactor(compiler): store metadata of top level symbols also in summaries (#13289)
This allows a build using summaries to not need .metadata.json files at all
any more.

Part of #12787
2016-12-15 09:12:40 -08:00
01ca2db6ae docs(changelog): add changelog for 4.0.0-beta.0 2016-12-14 21:54:31 -08:00
6cefccb314 build: bump angular to 4.0.0-beta.0 & tsc-wrapped to 0.5.0 2016-12-14 16:42:44 -08:00
fa9e21e83c fix(compiler): fix merge error in compiler_host 2016-12-14 15:36:49 -08:00
b6078f5887 fix(compiler): update to metadata version 3 (#13464)
This change retracts support for metadata version 2.

The collector used to produce version 2 metadata was incomplete
and can cause the AOT compiler to fail to resolve symbols or
produce other spurious errors.

All libraries compiled and published with 2.3.0 ngc will need
to be recompiled and updated with this change.
2016-12-14 15:28:51 -08:00
c65b4fa9dc refactor: format & lint 2016-12-14 15:10:43 -08:00
169ed82900 feat(testing): add overrideTemplate method (#13372)
Closes #10685
2016-12-14 15:05:17 -08:00
fd8e15b15d chore(animations/aot): always export NoOpAnimationDriver (#13480) 2016-12-14 14:51:29 -08:00
aa40366a92 fix(compiler): fix simplify a reference without a name
closes #13470
2016-12-14 14:33:10 -08:00
40d8d9c3e3 fix(tsc-wrapped): generate metadata for exports without module specifier
fixes #13327
2016-12-14 14:33:04 -08:00
ee2ac025ef fix(compiler): propagate exports when upgrading metadata to v2 2016-12-14 14:33:04 -08:00
aa3769ba69 fix(compiler): resolver should merge host bindings and listeners (#13474)
fixes #13327
2016-12-14 14:31:57 -08:00
d4ddb6004e refactor: format & lint 2016-12-14 13:05:04 -08:00
84400bcc86 docs(upgrade): fix UpgradeAdapter examples
closes #12675
2016-12-14 13:02:31 -08:00
42d9998cbb docs(upgrade/upgrade_adapter): fix up references to AngularJS and Angular 2 2016-12-14 13:02:27 -08:00
c18d2fe5e3 feat(upgrade): enable Angular 1 unit testing of upgrade module
- New method `UpgradeAdapter.registerForNg1Tests(modules)` declares the
  Angular 1 upgrade module and provides it to the `angular.mock.module()`
  helper.
  This prevents the need to bootstrap the entire hybrid for every test.

Closes #5462, #12675
2016-12-14 13:02:27 -08:00
d91a86aac6 fix(upgrade): fix downgrade content projection and injector inheritance
- Full support for content projection in downgraded Angular 2
  components. In particular, this enables multi-slot projection and
  other features on <ng-content>.
- Correctly wire up hierarchical injectors for downgraded Angular 2
  components: downgraded components inherit the injector of the first
  other downgraded Angular 2 component they find up the DOM tree.

Closes #6629, #7727, #8729, #9643, #9649, #12675
2016-12-14 13:02:27 -08:00
d6e5e9283c refactor(upgrade/upgrade_adapter): use Deferred helper
Making Angular 1's `$compile` asynchronous by chaining injector promises
in linking functions can cause flickering views in applications.
2016-12-14 13:02:27 -08:00
eab7e490c9 refactor(upgrade/util): remove unused stringify() method 2016-12-14 13:02:27 -08:00
3e90605db9 refactor(compiler/template_parser): export createElementCssSelector
This is needed in `ngUpgrade`.
2016-12-14 13:02:27 -08:00
79671a6f12 refactor(upgrade): add missing Angular 1 type info 2016-12-14 13:02:27 -08:00
a659259962 fix(core): detectChanges() doesn't work on detached instance
Closes #13426
Closes #13472
2016-12-14 13:01:06 -08:00
b56474d067 fix(animations): throw errors and normalize offset beyond the range of [0,1]
Closes #13348
Closes #13440
2016-12-14 12:59:47 -08:00
8395f0e138 perf(animations): always run the animation queue outside of zones
Related #12732
Closes #13440
2016-12-14 12:59:36 -08:00
dd0519abad fix(compiler): emit quoted object literal keys if the source is quoted
feat(tsc-wrapped): recored when to quote a object literal key

Collecting quoted literals is off by default as it introduces
a breaking change in the .metadata.json file. A follow-up commit
will address this.

Fixes #13249
Closes #13356
2016-12-14 12:58:41 -08:00
f238c8ac7a Revert "fix(compiler): xmb <ph> tags should not self close (#13413)"
This reverts commit 4b3d135193.
closes #13463
2016-12-14 12:54:58 -08:00
8c27c62fab Revert "test(i18n): fix a typo in the reference xmb (#13441)"
This reverts commit a8d237581d.
2016-12-14 12:54:50 -08:00
5031adc7a3 refactor(facade): don't expect super() to return a new Error object in BaseError (#12600)
Related to #12575
2016-12-14 11:54:57 -08:00
821b8f09d6 fix(forms): ensure select[multiple] retains selections
If you bound an array to select[multiple] via ngModel and subsequently
changed the options to select from, the UI would drop any selections
made since by the user. This was due to
SelectMultipleControlValueAccessor not keeping a reference to the new
model arrays it generated when users interacted with the select control.
Update code to keep the reference.

Closes #12527
Closes #12654
2016-12-14 08:52:07 -08:00
2bf1bbc071 fix(forms): introduce checkbox required validator
Closes #11459
Closes #13364
2016-12-14 08:44:24 -08:00
7b0a86718c fix (forms): clear selected options when model is not an array (#12519)
When an invalid model value (eg empty string) was preset ngModel on
select[multiple] would throw an error, which is inconsistent with how it
works on other user input elements. Setting the model value to null or
undefined would also have no effect on what was already selected in the
UI. Fix this by clearing selected options when model set to null,
undefined or a type other than Array.

Closes #11926
2016-12-14 08:34:19 -08:00
3edca4d37e fix(core): properly destroy embedded Views attatched to ApplicationRef (#13459)
Fixes #13062
2016-12-14 08:33:29 -08:00
a0a05041ac refactor: format & lint 2016-12-13 17:44:52 -08:00
7256d0ede5 chore(internal API): introduce an internal API for ngtools. (#13415) 2016-12-13 17:35:06 -08:00
d62d89319e fix(compiler): generated CSS files suffixed with ngstyle. (#13353)
Mirrors factories which ends in `ngfactory`.

Closes #13141.
2016-12-13 17:34:46 -08:00
f5f1d5f65c fix(compiler): make sure provider values with name property don’t break.
Fixes #13394
Closes #13445
2016-12-13 17:25:59 -08:00
a8d237581d test(i18n): fix a typo in the reference xmb (#13441) 2016-12-13 12:35:09 -08:00
d036165a19 refactor: remove intl from facades (#13404)
The existing intl.ts file is not a facade but
rather a set of utils used by i18n-related pipes only.
As such moving it back to common module so those utils
are not used accidently from other places.
2016-12-13 12:34:50 -08:00
d17e690eb4 test(upgrade): fix failing test in browsers which do not support RAF
closes #13399
2016-12-13 12:28:44 -08:00
714f2af0dd ci(browser providers): update browsers in SL and BS (#13431) 2016-12-13 11:32:31 -08:00
2b90cd532f fix(compiler): narrow the span reported for invalid pipes
fixes #13326
closes #13411
2016-12-13 11:23:47 -08:00
3a64ad895a fix(language-service): correctly type undefined
fixes #13412
closes #13414
2016-12-13 11:23:08 -08:00
9ec0a4e105 feat(language-service): warn when a method isn't called in an event (#13437)
Closes 13435
2016-12-13 11:20:45 -08:00
4b3d135193 fix(compiler): xmb <ph> tags should not self close (#13413) 2016-12-12 19:10:20 -08:00
1d0ed6f75f docs(core): update OnDestroy description (#13369)
Closes #11228
2016-12-12 16:45:56 -08:00
6f330a5fc9 fix(language-service): treat string unions as strings (#13406)
Fixes #13403
2016-12-12 16:42:20 -08:00
e23076f767 build: update the package list of the symlinks scripts for Windows (#13408) 2016-12-12 16:41:35 -08:00
7295a5e7f2 refactor: format and lint code 2016-12-12 11:30:25 -08:00
20bed46737 docs(Location): updating Location docs and adding example
closes #11500
2016-12-12 11:19:21 -08:00
2a5012d515 chore: Add @types/systemjs 2016-12-12 11:19:05 -08:00
fb38fba8f9 chore: convert hash_location_strategy example to a tested spec 2016-12-12 11:19:05 -08:00
4c35be3e07 feat(forms): add novalidate by default (#13092) 2016-12-12 11:17:42 -08:00
e9f307f948 fix(forms): fix Validators.min/maxLength with FormArray (#13095)
Fixes #13089
2016-12-12 11:17:12 -08:00
2e500cc85b fix(http): create a copy of headers when merge options (#13365)
Closes #11980
2016-12-12 11:16:34 -08:00
56dce0e26d feat(common): export NgLocaleLocalization (#13367)
Closes #11921
2016-12-12 11:16:12 -08:00
8a8c53250e fix(dom_adapter): remove logError from logGroup (#12925) 2016-12-09 15:40:26 -08:00
08ff2e5249 fix(http): check response body text against undefined (#13017) 2016-12-09 15:39:39 -08:00
a006c1418a feat(router): routerLink add tabindex attribute (#13094)
Fixes #10895
2016-12-09 15:38:50 -08:00
90c223591f feat(http): simplify URLSearchParams creation (#13338)
Closes #8858
2016-12-09 15:38:29 -08:00
aaf6e05f56 refactor(commonn): fix lint issues
closes #13352
2016-12-09 15:37:46 -08:00
3bee521aa4 fix(compiler): support dotted property binding
fixes angular/flex-layout#34
2016-12-09 15:37:41 -08:00
95f48292b1 test(Selector): add a test for dotted attribute names 2016-12-09 15:37:41 -08:00
04cfa1ebdf refactor(Compiler): cleanup 2016-12-09 15:37:41 -08:00
4022173d1e fix(compiler): fix PR 13322 (#13331) 2016-12-09 11:22:44 -08:00
c8baf51f4f style: clang-format the code 2016-12-09 11:19:55 -08:00
b4db73d0bf feat: ngIf now supports else; saves condition to local var
NgIf syntax has been extended to support else clause to display template
when the condition is false. In addition the condition value can now
be stored in local variable, for later reuse. This is especially useful
when used with the `async` pipe.

Example:

```
<div *ngIf="userObservable | async; else loading; let user">
  Hello {{user.last}}, {{user.first}}!
</div>
<template #loading>Waiting...</template>
```

closes #13061
closes #13297
2016-12-09 11:19:08 -08:00
e15a3f273f fix: Better instructions on running examples and their tests 2016-12-09 11:16:49 -08:00
213c713409 fix: Better error when directive not listed in NgModule.declarations 2016-12-09 11:16:28 -08:00
9a8423da36 fix(selector): SelectorMatcher match elements with :not selector (#12977) 2016-12-09 10:45:48 -08:00
f0b0762f4a fix(animations): always cleanup players after they have finished internally (#13334)
Closes #13333
Closes #13334
2016-12-09 10:45:10 -08:00
b5c4bf1c59 refactor(router): misc refactoring (#13330) 2016-12-09 10:44:46 -08:00
56c361ff6a test(compiler): test i18n explicit id
closes #13272
2016-12-09 10:43:57 -08:00
562f7a2f8b feat(compiler): digest methods return i18nMessage id if sets 2016-12-09 10:43:47 -08:00
6dd5201765 feat(compiler): add id property to i18nMessage 2016-12-09 10:43:47 -08:00
72361fb68f feat(platform browser): introduce Meta service (#12322) 2016-12-08 18:44:28 -08:00
5c6ec20c7e refactor(router): simplify regexp
closes #11373
closes #13329
2016-12-08 18:43:17 -08:00
440ef02f29 fix(router): add support for query params with mulitple values
closes #11373
2016-12-08 18:42:58 -08:00
4e3d58a792 Revert "fix(compiler): fix transpiled ES5 code (#13322)"
This reverts commit 4398056146.
2016-12-08 17:53:58 -08:00
61d7c1e0b3 feat(common): add a titlecase pipe (#13324)
closes #11436
2016-12-08 16:33:24 -08:00
bf93389615 doc: update triage owners for language service and router (#13325) 2016-12-08 15:42:34 -08:00
4398056146 fix(compiler): fix transpiled ES5 code (#13322)
fixes #13301

The inner class would transpile to a nested function declaration which is not
allowed in ES5.

See http://eslint.org/docs/rules/no-inner-declarations
2016-12-08 15:02:59 -08:00
1b547886d0 build(tslint): enable no-inner-declarations (#13316) 2016-12-08 13:46:08 -08:00
9591a08dfb fix(router): Use T type in Resolve interface (#13242) 2016-12-08 11:24:38 -08:00
65965c27a8 docs(changelog): fix a typo (#13298) 2016-12-08 11:23:57 -08:00
13b41bd631 chore(release): update version of tsc-wrapped to 0.4.2 2016-12-07 13:54:22 -08:00
f3524af68f docs(changelog): add changelog for 2.3.0 2016-12-07 11:21:13 -08:00
0a56f4ea82 chore(release): cut the 2.3.0 release 2016-12-07 10:58:29 -08:00
cf52284ac3 docs(changelog): fix typo AplicationRef => ApplicationRef (#13284)
docs(changelog): fix typo AplicationRef => ApplicationRef
2016-12-07 10:06:40 -08:00
4a09c81724 fix(language-service): do not throw for invalid metadata (#13261)
Fixes #13255
2016-12-06 17:11:09 -08:00
16efb13dd1 fix: display framework version on bootstrapped component (#13252) 2016-12-06 16:21:07 -08:00
986abbe0b2 fix(http): set the default Accept header (#12989)
Fixes #6354
2016-12-06 16:20:43 -08:00
25c2141991 fix(language-service): remove incompletely used parameter from createLanguageServiceFromTypescript() (#13278)
Fixes #13277
2016-12-06 16:19:39 -08:00
2893c2c0a2 fix(router): validate nested routes (#13224)
Fixes #12827
2016-12-06 10:41:01 -08:00
393c1007a8 fix(tsc-wrapped): have UserError display the actual error 2016-12-06 10:40:38 -08:00
66b6fc010d refactor(common): unify export structure 2016-12-06 10:40:38 -08:00
f31c9470fa fix(compiler): short-circut expressions with an index (#13263)
Fixes #13254
2016-12-06 10:40:15 -08:00
4bd8f58552 FIX typo (#13267) 2016-12-06 10:40:01 -08:00
93556a5720 fix(language-service): avoid throwing for invalid class declarations (#13257)
Fixes #13253
2016-12-06 09:56:30 -08:00
5614c4ff0f fix(compiler): serialize any StaticSymbol correctly, not matter in which context. 2016-12-05 14:20:01 -08:00
c3065aac7a refactor(compiler): replace isStaticSymbol with instanceof StaticSymbol 2016-12-05 14:20:01 -08:00
c767df0e4e fix(router): throw a better error message when angular 1 is not bootstraped 2016-12-05 10:57:24 -08:00
25e5b2fdf0 fix(router): make setUpLocationChangeListener idempotent 2016-12-05 10:57:24 -08:00
307c4693dc refactor(router): code cleanup 2016-12-05 10:54:10 -08:00
349ad75de3 fix(router): fix replaceUrl on RouterLink directives 2016-12-05 10:54:10 -08:00
f562cbf86c fix(router): fix skipLocationChanges on RouterLink directives
fixes #13156
2016-12-05 10:54:10 -08:00
804943c9b1 refactor(router): cleanup RouterLink 2016-12-05 10:54:10 -08:00
dea59165de docs(developer): add anchor to source code formatting (#13199)
In CONTRIBUTING.md#rules has reference to DEVELOPER.md#clang-format
but anchor to #clang-format is not present
2016-12-05 10:27:20 -08:00
a1322873c8 fix(facade): cache original format string (#12764) 2016-12-05 10:26:59 -08:00
b8c839bd51 docs(cheatsheet): correct HostBinding decorator example (#13206) 2016-12-05 10:25:40 -08:00
d2e5198b93 docs(contributing): fix styleguide link and typos (#13198) 2016-12-05 10:25:20 -08:00
6cf7a1bf84 refactor(build): fix build location of compiler-cli esm module (#13212) 2016-12-02 15:19:52 -08:00
d46b8deeea fix(router): runs guards every time when unsuccessfully navigating to the same url over and over again (#13209) 2016-12-02 15:19:00 -08:00
bbb7a39414 fix(router): allow specifying a matcher wihtout specifying a path
fixes #12972
2016-12-02 15:03:59 -08:00
d7d8fab211 refactor(router): cleanup config 2016-12-02 15:03:59 -08:00
51b06924bd docs(core): correct HostListener typo (#13203) 2016-12-02 14:45:47 -08:00
aa4bd14b3f docs(changelog): add instructions for people that depend on the cache operator (#13191) 2016-12-02 14:43:05 -08:00
3ff6554cbc fix(language-service): update to use CompilerHost from compiler-cli (#13189) 2016-12-02 14:34:16 -08:00
dfd8140084 Fix format 2016-12-02 14:31:55 -08:00
6ea3ab7e14 Fix exit code. Give a specific type. Add test cases. 2016-12-02 14:31:55 -08:00
9761db5ac2 refactor(compiler): change ngc error handling
Do not print stack trace for user errors
Print stack trace for compiler internal errors
2016-12-02 14:31:55 -08:00
75d1617b63 fix(compiler): include the summaries of reexported modules / directives / pipes (#13196)
Only if these are not part of the sources.
2016-12-02 10:08:46 -08:00
614a35d539 feat(compiler): read and write .ngsummary.json files
When compiling libraries, this feature extracts the minimal information
from the directives/pipes/modules of the library into `.ngsummary.json` files,
so that applications that use this library only need to be recompiled
if one of the summary files change, but not on every change
of the libraries (e.g. one of the templates).

Only works if individual codegen for libraries is enabled,
see the `generateCodeForLibraries: false` option.

Closes #12787
2016-12-01 14:49:52 -08:00
9ab401f4d3 refactor(compiler): simplify NgModuleSymmaryMetadata
- merge `NgModuleInjectorSummary` and `NgModuleDirectiveSummary`
- remove `directiveLoaders` from the summary
2016-12-01 14:49:52 -08:00
82c81cd0d2 fix(common): make sure the plural category exists (#13169)
fixes #12379
2016-12-01 13:26:24 -08:00
12959f444c refactor(router):remove unused parameter pathIndex (#13180) 2016-12-01 13:25:53 -08:00
25a6da244c refactor(compiler-cli): refactor compiler host parameters (#13147) 2016-12-01 13:24:51 -08:00
5908b66ae9 docs(changelog): move 2.2.2 to its place in the chronological order 2016-12-01 10:21:23 -08:00
480ef20eb1 docs(changelog): add changelog for 2.2.2 2016-12-01 09:59:23 -08:00
c066281bad docs(changelog): add changelog for 2.3.0-rc.0 2016-11-30 15:42:56 -08:00
1b9493f725 chore(release): cut the 2.3.0-rc.0 release 2016-11-30 15:42:56 -08:00
ae26504e84 fix(core): update peer dep on zone.js to ^0.7.2 2016-11-30 15:42:56 -08:00
d420080b3b docs(changelog): add changelog for 2.2.4 2016-11-30 15:19:09 -08:00
2975d8933c fix(language-service): harden against partial normalization of directives 2016-11-30 14:55:56 -08:00
43c0e9a6bb fix(compiler): fix performance regression caused by 5b0f9e2
Fixes #13146
2016-11-30 14:55:56 -08:00
f275f36081 fix(version): take all of version string after patch version 2016-11-30 14:25:11 -08:00
e628b66cca feat(build): record angular version in the dom (#13164) 2016-11-30 13:52:08 -08:00
3e73bea3e7 refactor(compiler): convert metadata classes used in summaries into interfaces (#13123)
Part of #12787
2016-11-30 10:52:51 -08:00
42cf06fa12 feat(router): add support for custom route reuse strategies 2016-11-29 23:21:41 -08:00
c4bbafc291 feat: upgrade zone.js to v0.7.1 2016-11-29 17:24:00 -08:00
2d6a003dba feat: update RxJS peer dependency to 5.0.0-rc.4
Closes #13125

RxJS from beta-12 to rc.4, has removed the `cache`
operator. (See https://github.com/ReactiveX/rxjs/blob/master/CHANGELOG.md#breaking-changes-1)
If your application relies on it, then we suggest 
that you use the one from this gist:
https://gist.github.com/robwormald/19dea0c70a6e01aadced6731aed4f9f7
2016-11-29 16:27:33 -08:00
e45b7ffcd9 fix: shrinkwrap was out of date with packages.
Rerun shrinkwrap on a clean workspace
2016-11-29 16:27:33 -08:00
627282d2c8 fix(compiler): correctly evaluate references to static functions (#13133) 2016-11-29 12:02:50 -08:00
2f7492c986 refactor(compiler): remove unneeded fields from metadata
Removes `CompileIdentifierMetadata.name` / `.moduleUrl`,
as well as `CompileTypeMetadata.name / moduleUrl` and
`CompileFactoryMetadata.name / moduleUrl`.
2016-11-28 15:19:23 -08:00
2452cd14e0 refactor(compiler): drop old codegen tests that run inside of test.sh
These tests were hard to maintain and only yielded little value,
now that we have the full integration with TypeScript.
2016-11-28 15:19:23 -08:00
bc69c74be0 fix(tsc-wrapped): still emit version 1 metadata to allow to use new components in old setups 2016-11-28 15:18:57 -08:00
897555ca78 fix(tsc-wrapped): set correct version number 2016-11-28 15:18:56 -08:00
966bcbad5a fix(compiler-cli): pin the version of tsc-wrapped 2016-11-28 15:18:56 -08:00
94b8612e4e Fix(http): invalidStateError response body
Check on null value failed with last version of mozilla.
Check on undefined type instead.
2016-11-28 14:36:32 -08:00
b2b72190f8 fix(common): update DatePipe to allow closure compilation
Quote the date formats to prevent closure renaming.  These are specified as strings in templates using DatePipes and also need to be quoted here.
2016-11-28 14:36:12 -08:00
f5c8e0989d feat(core): properly support inheritance
## Inheritance Semantics:

Decorators:
1) list the decorators of the class and its parents in the ancestor first order
2) only use the last decorator of each kind (e.g. @Component / ...)

Constructor parameters:
If a class inherits from a parent class and does not declare
a constructor, it inherits the parent class constructor,
and with it the parameter metadata of that parent class.

Lifecycle hooks:
Follow the normal class inheritance model,
i.e. lifecycle hooks of parent classes will be called
even if the method is not overwritten in the child class.

## Example

E.g. the following is a valid use of inheritance and it will
also inherit all metadata:

```
@Directive({selector: 'someDir'})
class ParentDirective {
  constructor(someDep: SomeDep) {}

  ngOnInit() {}
}

class ChildDirective extends ParentDirective {}
```

Closes #11606
Closes #12892
2016-11-28 14:12:12 -08:00
4a09251921 doc(common): fix a typo in async pipe 2016-11-28 14:11:45 -08:00
36caaaa8e4 refactor(core): remove unused import
APP_ID  was removed after 2.2.x
2016-11-28 14:11:25 -08:00
808275a9d5 feat(core): expose destroy() method on ViewRef 2016-11-28 14:10:42 -08:00
be3784c957 revert: fix(animations): blend in all previously transitioned styles into next animation if interrupted
This reverts commit ef96763fa4.
2016-11-28 13:23:52 -08:00
555301ce3a docs(changelog): add changelog for 2.2.3
original SHA: 380377139b
2016-11-27 22:11:04 -08:00
7194fc2b9e fix(language-service): make link check pass 2016-11-23 16:21:06 -08:00
2a3ca7bfcf fix(compiler-cli): fix paths in source maps to be relative
The change looks bigger than it really is because I reordered the properties to match other tsconfigs we have.

The only real change is removal of sourceRoot property.

Fixes #13040
2016-11-23 15:48:24 -08:00
4cbf8ccf05 Keep console.log that are not called during compilation. 2016-11-23 15:47:02 -08:00
a6c4490fce Check if console.error is defined 2016-11-23 15:47:02 -08:00
2c02d34c05 refactor(lint): Don't allow console.log
Enable tslint check for `console.log` as a follow-up to
https://github.com/angular/angular/issues/13018
2016-11-23 15:47:01 -08:00
6c2d931744 chore: make test.sh work again
Previously, `test.sh` relied on calling `build.sh` first
2016-11-23 14:23:05 -08:00
86ffa884b7 fix(build): update versions of umd bundles (#13038)
Fixes #13037
2016-11-22 13:39:41 -08:00
3e548de99d Revert "fix(router): guards restor an incorrect url when used with skipLocationChange"
This reverts commit ad20d7d260.
2016-11-22 13:31:33 -08:00
909268036b test(upgrade): remove setTimeout from lifecycle hook tests (#13027)
* test(upgrade): remove unnecessary NO_ERRORS_SCHEMA

* test(upgrade): remove `setTimeout` from lifecycle hook tests

Closes #13019
2016-11-22 09:21:03 -08:00
519a324454 feat(language-service): add services to support editors (#12987) 2016-11-22 09:10:23 -08:00
ef96763fa4 fix(animations): blend in all previously transitioned styles into next animation if interrupted (#13014)
Closes #13013
Closes #13014
2016-11-21 15:46:59 -08:00
7dcca307d9 fix(closure): quote date pattern aliases (#13012)
Quota the pattern aliases to prevent closure renaming. These are quoted in DatePipe and also need to be quoted here.
2016-11-21 11:45:48 -08:00
491d5a22a9 refactor(compiler): allow control of StaticSymbol lifetime (#12986) 2016-11-18 16:58:14 -08:00
44572f114f refactor(ngUpgrade): Small cleanup with Testability API and resumeBootstrap (#12926)
* With non-static ngUpgrade apps, callbacks to `whenStable` were being invoked with the wrong
  context
* With non-static ngUpgrade apps, `resumeBootstrap` was being run outside the NgZone
* Remove redundent `whenStableContext` variable

Neither of the first two problems were actually causing bugs (as far as I know), but they *might*
have caused problems in the future.

Inspired by https://github.com/angular/angular/pull/12910, but for non-static apps.
2016-11-18 14:30:47 -08:00
1ef4696cb7 fix(upgrade): call ng1 lifecycle hooks (#12875) 2016-11-18 13:46:49 -08:00
07a986d330 fix(changelog): replace beta.1 with beta.0 (#12961) 2016-11-18 12:37:26 -08:00
59d2b4c831 refactor(compiler): further minor fixes 2016-11-18 10:04:14 -08:00
2a5bd2f345 refactor(compiler): Reintroduce ReflectorHost and move Extractor into @angular/compiler 2016-11-18 10:04:14 -08:00
3c06a5dc25 refactor(comiler): various cleanups 2016-11-18 10:04:14 -08:00
adeea5d86a refactor(compiler): renames
- `NgHost` to `CompilerHost`
- `AotCompilerHost.resolveFileToImport` to `AotCompilerHost.fileNameToModuleName`
- `AotCompilerHoset.resolveImportToFile` to `AotCompilerHost.moduleNameToFileName`
2016-11-18 10:04:14 -08:00
dddbb1c1cb refactor(tsc-wrapped): collect all exported functions and classes and bump metadata version from 1 to 2
This is needed to resolve symbols without `.d.ts` files.
This bumps the version of the metadata from 1 to 2.
This adds logic into `ng_host.ts` to automatically upgrade
version 1 to version 2 metadata by adding the exported symbols
from the `.d.ts` file.
2016-11-18 10:04:14 -08:00
bccf0e69dc fix(compiler): fix versions of @angular/tsc-wrapped 2016-11-18 10:04:14 -08:00
b15039d228 refactor(compiler): move symbol extraction to AotCompiler 2016-11-18 10:04:14 -08:00
2235048432 refactor(compiler): add createAotCompiler factory
Also adds 2 more methods to the `AotCompilerHost`:
- `loadResource`
- `resolveFileToImport`
2016-11-18 10:04:14 -08:00
484119e59f refactor(compiler): remove asset: urls
These urls were just relicts from Dart.
2016-11-18 10:04:14 -08:00
24099bdbd2 refactor(compiler): move findDeclaration into the StaticReflector
Previously, this was part of the `AotCompilerHost`.
The `AotCompilerHost` is now also greatly simplified.
2016-11-18 10:04:14 -08:00
912ca44979 refactor(compiler): move static_reflector into @angular/compiler and rename files
- `src/runtime_compiler.ts` -> `src/jit/compiler.ts`
- `src/compiler.ts` -> `src/jit/compiler_factory.ts`
- `src/offline_compiler` -> `src/aot/compiler.ts`

Part of #12867
2016-11-18 10:04:14 -08:00
664a6273e1 feature(tsc-wrapped): add option for closure compiler JSDoc annotations 2016-11-18 09:37:40 -08:00
c1a62e2154 feat(tools): allow disabling annotation lowering 2016-11-18 09:37:40 -08:00
aac37bedc0 chore(build): update package.json versions during build (#12957) 2016-11-18 09:24:57 -08:00
a3884db87c fix(ci): pin version of npm on CircleCI (#12954) 2016-11-17 17:27:51 -08:00
fc5ac1ebc4 fix(benchmarks): use sanitized style values (#12943) 2016-11-17 15:18:10 -08:00
ad20d7d260 fix(router): guards restor an incorrect url when used with skipLocationChange
Closes #12825
2016-11-17 14:10:59 -08:00
602522beb2 fix(router): support redirects to named outlets
Closes #12740, #9921
2016-11-17 14:10:59 -08:00
4e047302f2 chore(release): cut the 2.3.0-beta.0 realse and add change log 2016-11-17 11:59:03 -08:00
419a812f04 chore(release): cut angular 2.2.1 2016-11-17 11:51:25 -08:00
f340e1a414 fix(tools): fix error when running test.sh (#12927) 2016-11-16 13:35:31 -08:00
481c9b3258 refactor(compiler): allows synchronous retrieving of metadata (#12908)
Allows non-normalized metadata to be retrieved synchronously.

Related to #7482
2016-11-16 10:22:11 -08:00
8b2dfb2eca fix(core): support ngTemplateOutlet in production mode (#12921)
Fixes #12911
2016-11-16 10:00:18 -08:00
824ea8406c docs(upgrade/static): improve API docs with examples
Closes #12717
2016-11-16 09:18:17 -08:00
1f96a93f59 chore(public_api): remove Angular 1 types from upgrade/static API 2016-11-16 09:18:10 -08:00
009d545787 chore(examples): add upgrade/static example 2016-11-16 09:18:10 -08:00
53c25210a6 chore(examples): support upgrade/static examples 2016-11-16 09:18:10 -08:00
927aa69726 fix(router): add a banner file for the router (#12919) 2016-11-16 09:17:19 -08:00
ce89039036 fix(platform_browser): fix disableDebugTools() (#12918) 2016-11-16 09:16:40 -08:00
42198cd7d5 fix(ngUpgrade): make AoT ngUpgrade work with the testability API and resumeBootstrap() (#12910) 2016-11-16 01:04:56 -08:00
d6ba092a27 build(build.sh): echo before building examples 2016-11-15 20:59:37 -08:00
773b31de8f fix(router): should not create a route state if navigation is canceled (#12868)
Closes #12776
2016-11-15 19:00:20 -08:00
f79b320fc4 refactor(forms): remove facade (#12558) 2016-11-15 18:48:34 -08:00
6a212fd561 fix(router): removes a peer dependency from router to upgrade 2016-11-15 18:37:08 -08:00
be010a292a fix(animations): only pass in same typed players as previous players into web-animations (#12907)
Closes #12907
2016-11-15 17:47:21 -08:00
7c36e7f956 chore(router): remove @angular/upgrade peer dep (#12896) 2016-11-15 14:00:11 -08:00
13ba2f90b9 refactor(http): remove all facade methods from http module (#12870) 2016-11-15 09:19:14 -08:00
75277cd94b fix(tsickle): support ctorParams in function closure (#12876)
See https://github.com/angular/tsickle/issues/261 for context.
2016-11-15 09:19:00 -08:00
46d150266b feat(router_link): add skipLocationChange and replaceUrl inputs (#12850) 2016-11-14 18:30:13 -08:00
1b5384ee54 feat(core): expose ViewRef as ChangeDetectorRef
closes #12722

This is helpful when manually dirty checking embedded views.
2016-11-14 17:01:41 -08:00
9f7d32a326 feat(core): add attachView / detachView to ApplicationRef
This feature is useful to allow components / embedded views
to be dirty checked if they are not placed in any `ViewContainer`.

Closes #9293
2016-11-14 17:01:35 -08:00
9de76ebfa5 fix(animations): retain styling when transition destinations are changed (#12208)
Closes #9661
Closes #12208
2016-11-14 16:59:06 -08:00
46023e4792 fix(select): allow for null values in HTML select options bound with ngValue
closes #12829
2016-11-14 16:47:14 -08:00
b55aaf094f fix: allow for null values in HTML select options bound with ngValue
This corrects the case of <option [ngValue]="null"> binding a string like "{0: null}" to the model instead of an actual null object.

Closes #10349
2016-11-14 16:47:09 -08:00
d90b622fa4 fix: allow for null values in HTML select options bound with ngValue
This corrects the case of <option [ngValue]="null"> binding a string like "{0: null}" to the model instead of an actual null object.

Closes #10349
2016-11-14 16:47:09 -08:00
79e2bb9291 refactor(core): remove dead code (#12871) 2016-11-14 16:44:25 -08:00
efbbefd353 fix(platform-browser): enable AOT
closes #12783
2016-11-14 12:57:11 -08:00
c2fae72bc6 feat(router): register router with ngprobe 2016-11-14 12:57:05 -08:00
7908679c4b fix(compiler): assert xliff messages have translations
fixes #12815
closes #12604
2016-11-14 12:55:56 -08:00
9ed9ff40b3 test(compiler): improve xliff tests 2016-11-14 12:55:48 -08:00
2f14415836 fix(compiler): updates hash algo for xmb/xtb files 2016-11-14 12:55:48 -08:00
76e4911e8b fix(core): fix placeholders handling in i18n.
Prior to this commit, translations were built in the serializers. This
could not work as a single translation can be used for different source
messages having different placeholder content.

Serializers do not try to replace the placeholders any more.
Placeholders are replaced by the translation bundle and the source
message is given as parameter so that the content of the placeholders is
taken into account.

Also XMB ids are now independent of the expression which is replaced by
a placeholder in the extracted file.
fixes #12512
2016-11-14 12:55:48 -08:00
ed5e98d0df fix(core): misc i18n fixes 2016-11-14 12:55:48 -08:00
146af1fed9 refactor(core): simplify i18n serializers code 2016-11-14 12:55:48 -08:00
c60ba7a72f refactor(core): remove ListWrapper from i18n 2016-11-14 12:55:48 -08:00
05beffe0d0 test(core): fix a typo in the i18n integration spec 2016-11-14 12:55:48 -08:00
08c038ebd9 fix(core): xmb serializer uses decimal messaged IDs
fixes #12511
2016-11-14 12:55:48 -08:00
582550a90d feat(core): implements a decimal fingerprint for i18n 2016-11-14 12:55:48 -08:00
1d53a870dd fix(http): return request url if it cannot be retrieved from response
closes #12837
2016-11-14 12:54:43 -08:00
a0c58a6b5c fix(http): correctly handle response body for 204 status code
closes #12830
fixes #12393
2016-11-14 12:36:22 -08:00
d3eff6c483 refactor(xhr_backend): remove facade 2016-11-14 12:36:16 -08:00
2524d510bc chore(release): cut the 2.2.0 upgrade-firebooster release 2016-11-14 11:26:03 -08:00
8f5dd1f11e chore(lint): enforce no var keyword rule 2016-11-12 16:40:17 -08:00
77ee27c59e refactor(): use const and let instead of var 2016-11-12 16:40:17 -08:00
73593d4bf3 perf(platform-browser): cache plugin resolution in the EventManager
closes #12824
2016-11-11 17:19:47 -08:00
a965d11cce fix(compiler): generate safe access strictNullChecks compatible code (#12800)
fixes #12795
2016-11-11 17:12:17 -08:00
52be848f94 fix(router): incorrect injector is used when instantiating components loaded lazily (#12817) 2016-11-11 17:12:00 -08:00
69dfcf7385 docs(forms): add inline docs why ngModel runs a 2nd change detection run (#12821)
Related to #11895
2016-11-11 15:24:11 -08:00
785b7b640e fix(router): Route.isActive also compares query params (#12321) 2016-11-11 13:23:47 -08:00
e5a753e111 fix(router): router should not swallow "unhandled" errors
closes #12802
2016-11-11 13:22:19 -08:00
768cddbe62 fix(events): provide the ability to register global hammer.js events
closes #12797
2016-11-11 11:15:49 -08:00
92f244aa26 refactor(events): remove facade and clean up 2016-11-11 11:15:43 -08:00
2a4bf9a0df fix(router): avoid router initialization for non root components
closes #12338
closes #12814
2016-11-11 11:15:17 -08:00
45ddd6ba78 cleanup(forms): remove facade (#12804) 2016-11-11 10:47:34 -08:00
7886561997 fix(router): check if windows.console exists before using it (#12348) 2016-11-11 10:46:53 -08:00
752edca81b test(core): ngOnDestroy called before output events are detached (#9946)
closes #6984
closes #5436
2016-11-11 10:27:32 -08:00
1bd858fb43 build(examples): upgrade to protractor 4.0.9 (#12803)
closes #12798
2016-11-10 18:13:11 -08:00
fcb4e66493 refactor(compiler): introduce summaries for metadata (#12799)
This does not yet introduce loading / serialization of summaries.

Part of #12787
2016-11-10 16:27:53 -08:00
ef881475e9 fix(forms): check if registerOnValidatorChange exists on validator before trying to invoke it (#12801)
closes #12593
2016-11-10 16:20:59 -08:00
458ca7112a build(publish): remove unneeded add-license-to-rx (#12734) 2016-11-10 15:56:14 -08:00
2aba8b0ff2 fix(common): no TZ Offset added by DatePipe for dates without time (#12380) 2016-11-10 14:57:04 -08:00
77dc1ab675 fix(router): throw an error when encounter undefined route (#12389) 2016-11-10 14:55:10 -08:00
3052fb234f fix(router): ignore null or undefined query parameters (#12333) 2016-11-10 14:41:19 -08:00
79383ce150 refactor(compiler): never create CompileDirectiveMetadata with not loaded resources (#12788)
Part of #12787
2016-11-10 14:07:30 -08:00
c3c0e2e2a2 refactor(compiler): add span to TemplateBinding (#12792)
fix(compiler): corrected error location for implicit templates expressions
2016-11-10 13:15:09 -08:00
44a142fc02 chore(playground): use base64-js from npm
closes #12471
2016-11-10 12:08:04 -08:00
3d9d839c6c refactor(playground): make playground great again 2016-11-10 12:07:51 -08:00
69f87ca075 fix(tools): harden colletor against invalid asts (#12793) 2016-11-10 11:58:55 -08:00
f224ca1461 ci(BrowserStack): increase timeout to avoid failures (#12786)
relates to #12578
2016-11-10 11:58:06 -08:00
19e869e7c9 fix(animations): ensure animations work with web-workers (#12656) 2016-11-10 11:53:50 -08:00
7cab30f85d refactor(compiler-cli): add position data to static reflector errors (#12782) 2016-11-09 16:29:22 -08:00
73407351e7 feat(router): add support for custom url matchers
Closes #12442
Closes #12772
2016-11-09 16:24:58 -08:00
2c110931f8 fix(router): do not require the creation of empty-path routes when no url left
Closes #12133
2016-11-09 16:24:49 -08:00
2ced2a8a5a refactor(compiler): misc updates (#12773) 2016-11-09 16:23:41 -08:00
634b3bb88b feat(core): map 'for' attribute to 'htmlFor' property (#10546)
This improves ergonomics a bit by allowing people to write:
`<label [for]="ctxProp"></label>`.
This is similar to the existing class -> className mapping.

Closes #7516
2016-11-09 15:21:27 -08:00
4595a61aeb refactor(compiler-cli): refactor imports in codegen to enable rollup (#12781) 2016-11-09 15:17:24 -08:00
f80a157b65 fix(animations): ensure web-animations are caught within the Angular zone
Closes #11881
Closes #11712
Closes #12355
Closes #11881
Closes #12546
Closes #12707
Closes #12774
2016-11-09 15:16:34 -08:00
6e35d13fbc feat(router): add a provider making angular1/angular2 integration easier (#12769) 2016-11-09 13:33:33 -08:00
fe35bc34f6 fix(animations): allow animations to be destroyed manually (#12719)
Closes #12456
Closes #12719
2016-11-08 16:21:28 -08:00
ad3bf6c54f fix(core): apply host attributes to root elements (#12761)
Fixes #12744
2016-11-08 15:46:55 -08:00
a0e9fde653 fix(animations): always normalize style properties and values during compilation (#12755)
Closes #11582
Closes #12481
Closes #12755
2016-11-08 15:45:30 -08:00
3dc61779f0 fix(DatePipe): handle empty string (#12374) 2016-11-08 15:45:12 -08:00
09092ac3c2 fix(forms): getRawValue returns any instead of Object (#12599) 2016-11-08 15:44:36 -08:00
778e6ad3b4 refactor: cleanup ICU message syntax 2016-11-08 15:44:18 -08:00
55dc0e4a5f fix(compiler): use the other case by default in ICU messages 2016-11-08 15:44:18 -08:00
4708b248d5 fix(common): I18nSelectPipe selects other case on default 2016-11-08 15:44:18 -08:00
7694f974af refactor: remove some facades (#12731) 2016-11-08 15:43:24 -08:00
acbf1d859c fix(core): fix pseudo-selector shimming (#12754)
fixes #12730
fixes #12354
2016-11-07 13:56:04 -08:00
f3793b5953 fix(NgClass): throw a descriptive error when CSS class is not a string (#12662)
Fixes #12586
2016-11-07 12:23:31 -08:00
22c021c57f fix(compiler): support more than 9 interpolations (#12710)
Fixes #10253
2016-11-07 12:23:03 -08:00
d8f23f4b7f fix(common): NgSwitch - don’t create the default case if another case matches (#12726)
This also simplifies the implementation of `NgSwitch`.

Closes #11297
Closes #9420
2016-11-07 12:22:36 -08:00
32fcec9fcb chore(npm): remove dependency on minimatch 2016-11-07 10:32:00 -08:00
78039b41d6 chore(build): remove unused build/util 2016-11-07 10:32:00 -08:00
89fd54e8e3 docs(url_tree):fix typo(UrlSegment path property's comment part -> path) (#12728) 2016-11-07 10:27:47 -08:00
77cbf7f2bb fix(closure): suppress two more closure compiler checks in codegen (#12698) 2016-11-04 15:18:05 -07:00
383f23b578 fix(animations): always trigger animations after the change detection check (#12713)
This patch ensures that animations are run outside of change detection
thus allowing for start and done callbacks to modify application data
without causing a cycle loop.

Closes #12713
2016-11-04 15:15:27 -07:00
2a3f4d7b17 refactor: kill MapWrapper 2016-11-04 13:27:38 -07:00
ec92f4b198 refactor: remove keys() and values() from MapWrapper 2016-11-04 13:27:38 -07:00
121e5080aa fix(http): preserve header case when copying headers (#12697) 2016-11-04 13:26:38 -07:00
fe1d0e29c5 feat(UpgradeComponent): add support for require
This commit also adds/improves/fixes some `UpgradeComponent` tests.
2016-11-04 11:16:28 -07:00
469010ea8e feat(UpgradeComponent): add/improve support for lifecycle hooks
Add support for the `$postDigest()` and `$onDestroy()` lifecycle hooks.
Better align the behavior of the `$onChanges()` and `$onInit()` lifecycle hooks
with Angular 1.x:

- Call `$onInit()` before pre-linking.
- Always instantiate the controller before calling `$onChanges()`.
2016-11-04 11:16:28 -07:00
f0cdb428f5 fix(compiler): don't convert undefined to null literals (#11503)
Fixes #11493
2016-11-04 10:55:21 -07:00
051d74802a fix(core): ensure that component views that have no bindings recurse into nested components / view containers. 2016-11-04 10:50:27 -07:00
f2bbef3e33 fix(core): allow to query content of templates that are stamped out at a different place
Previously, if a `TemplateRef` was created in a `ViewContainerRef`
at a different place, the content was not query able at all.

With this change, the content of the template can be queried
as if it was stamped out at the declaration place of the template.

E.g. in the following example, the `QueryList<ChildCmp>` will
be filled once the button is clicked.

```
@Component({
  selector: ‘my-comp’,
  template: ‘<button #vc (click)=“createView()”></button>’
})
class MyComp {
  @ContentChildren(ChildCmp)
  children: QueryList<ChildCmp>;

  @ContentChildren(TemplateRef)
  template: TemplateRef;

  @ViewChild(‘vc’, {read: ViewContainerRef})
  vc: ViewContainerRef;

  createView() {
    this.vc.createEmbeddedView(this.template);
  }
}

@Component({
  template: `
<my-comp>
  <template><child-cmp></child-cmp></template>
</my-comp>
`
})
class App {}
```

Closes #12283
Closes #12094
2016-11-04 10:50:27 -07:00
80d36b8db4 docs(CONTRIBUTING.md): fix stackoverflow broken link url (#12705) 2016-11-04 10:21:11 -07:00
e3687706c7 refactor(compiler): minor cleanup 2016-11-03 16:29:51 -07:00
648ce5981b perf(core): don’t use DomAdapter nor zone for regular events 2016-11-03 16:29:51 -07:00
9c23884da4 perf(compiler): introduce direct rendering
This allows to attach / detach embedded views and projected nodes
in a faster way.
2016-11-03 16:29:51 -07:00
d708a8859c perf(platform-browser): don’t use DomAdapter any more
But use the DOM apis directly.
This also creates a separate `ServerRenderer` implementation
for `platform-server` as it previously reused the `BrowserRenderer`.
2016-11-03 16:29:51 -07:00
9ddf9b3d3d fix(router): advance a route only after its children have been deactivated (#12676)
Closes #11715
2016-11-03 16:26:10 -07:00
69f006cd89 docs(change_detection): fix typo(ChangeDetectorStatus enum comment CheckedOnce -> CheckOnce) (#12683) 2016-11-03 11:23:20 -07:00
4aaae3eada docs(common): fix a typo in ngStyle API docs 2016-11-03 10:27:05 -07:00
2e78b76fcf fix(router): resolve guard observables on the first emit (#10412) 2016-11-02 21:56:04 -07:00
b2cf379d1c fix(enableDebugTools): create AngularTools by merging into context.ng (#12003)
When using `enableDebugTools` the tools are merged into `context.ng` to prevent `ng.probe` and `ng.coreTokens` from being clobbered.

Fixes #12002
2016-11-02 21:55:49 -07:00
e25baa08b3 fix(router): correctly export concatMap operator in es5 (#12430) 2016-11-02 21:55:02 -07:00
7103754178 fix(closure): suppress closure compiler suspiciousCode check in codegen (#12666) 2016-11-02 21:11:30 -07:00
1a069e8372 refactor(compiler): cleanups 2016-11-02 20:58:48 -07:00
0fc11a43f1 perf(core): use array.push / array.pop instead of splice if possible 2016-11-02 20:58:48 -07:00
0e3d655220 refactor(compiler): remove view factories, use view classes directly 2016-11-02 20:58:48 -07:00
7c5cc9bc41 refactor(compiler): initialize RenderComponentType eagerly
This moves the usage of `APP_ID` into the `DomRenderer`.
2016-11-02 20:58:48 -07:00
5f1dddc5d0 refactor(compiler): cleanups 2016-11-02 17:06:27 -07:00
20a4f9923f refactor(compiler): remove view.parentInjector 2016-11-02 17:06:27 -07:00
e7c00be19d refactor(compiler): rename AppElement into ViewContainer 2016-11-02 17:06:27 -07:00
74ede9aa9b refactor(core): don’t store view factory in TemplateRef
Instead, generate `createEmbeddedView`.
2016-11-02 17:06:27 -07:00
d1035da85c refactor(compiler): don’t use AppElements for creating component views 2016-11-02 17:06:27 -07:00
13533d2a30 refactor(compiler): remove AppElement.initComponent 2016-11-02 17:06:27 -07:00
953cb50fa5 chore(release): cut v2.2.0-rc.0 2016-11-03 00:28:29 +01:00
3fffcf6645 chore: update changelog 2016-11-02 12:34:21 -07:00
d509ee078b fix(router): reset URL to the stable state when a navigation gets canceled
Closes #10321
2016-11-02 12:25:23 -07:00
8e221b826f fix(router): routerLink should not prevent default on non-link elements 2016-11-02 12:25:23 -07:00
830a780cb3 fix(router): CanDeactivate receives a wrong component
Closes #12592
2016-11-02 12:25:23 -07:00
6fda97287e fix(compiler): support multiple components in a view container 2016-11-01 14:21:40 -07:00
234c5599f1 refactor(compiler): remove unused constructor query support 2016-11-01 11:29:15 -07:00
f6710fefeb refactor(compiler): make view.disposable array null if empty 2016-11-01 11:29:15 -07:00
bda1909ede refactor(compiler): remove view.rootNodes and view.projectableNodes
They are replaced by generated visitor functions `view.visitRootNodes` / `view.visitProjectableNodes`.
2016-11-01 11:29:15 -07:00
b3e3cd3add refactor(compiler): inline view.contentChildren 2016-11-01 11:29:14 -07:00
e5fdf4c70a refactor(compiler): inline view.viewChildren in generated code 2016-11-01 11:29:14 -07:00
97471d74b6 refactor(compiler): remove unused subscriptions in view 2016-11-01 11:29:14 -07:00
1de04b23b1 fix(router): call data observers when the path changes 2016-11-01 11:28:43 -07:00
a178bc6c83 fix(compiler): dedupe NgModule declarations, …
This is important so that we don’t generate things multiple times.
2016-10-31 14:43:50 -07:00
642c1db9ef fix(compiler): Don’t throw on empty property bindings
Closes #12583
2016-10-31 14:43:50 -07:00
579deeb9c5 style(platform-browser): clean up hammer gestures 2016-10-31 14:43:05 -07:00
bad58824a0 refactor(playground): update gestures playground to use latest hammer.js 2016-10-31 14:43:04 -07:00
5494169fb4 style: make internal members accessibility explicit 2016-10-31 14:25:53 -07:00
5a3d7a62a2 style: merge imports from the same modules 2016-10-31 14:25:53 -07:00
a382d6dd20 style: add missing semicolons 2016-10-31 14:25:53 -07:00
52bf188b8f style: add missing copyright headers 2016-10-31 14:25:53 -07:00
6f412bb449 chore(lint): extend linting to all modules and tools 2016-10-31 14:24:27 -07:00
e9fd8645ed fix(core): improve error when multiple components match the same element
Closes #7067
2016-10-31 11:28:03 -07:00
a0aecac0e5 chore(lint): replace enforce-copyright-header rule with the native equivalent 2016-10-31 11:27:35 -07:00
938ed1c76d chore(lint): deduplicate tslint dependency 2016-10-31 11:27:34 -07:00
eb8288f76c chore(package): remove unused lodash and sorted-object 2016-10-31 11:26:59 -07:00
0936ceeab4 chore(npm): clean up clean-shrinkwrap script 2016-10-31 11:26:59 -07:00
e0ad413a8e style(tests): clean up testing_public_spec (#11452) 2016-10-31 11:26:38 -07:00
3045d02b9a docs(pipes): minor fix and improvements 2016-10-31 12:39:21 +01:00
e86573bac8 chore(lint): replace gulp check-task with tslint no-jasmine-focus rule
fixes #11800
2016-10-28 15:53:15 -07:00
0a94845435 chore(lint): replace duplicate-module-import rule with no-duplicate-imports 2016-10-28 15:53:15 -07:00
262bd23b84 chore(lint): add vrsource tslint rules dependency 2016-10-28 15:53:15 -07:00
7b8dae19af refactor(facade): cleanup Intl facade 2016-10-28 15:52:52 -07:00
7c16ef942e feat(core): add the find method to QueryList 2016-10-28 15:34:47 -07:00
a318b57257 refactor(core): removed extraneous interface from QueryList test 2016-10-28 15:34:47 -07:00
fe47e6b783 fix(router): rerun resolvers when url changes
Closes #12603
2016-10-28 15:17:00 -07:00
091c390032 fix(router): run navigations serialy
Closes #11754
2016-10-28 14:56:08 -07:00
e391cacdf9 fix(compiler): don’t double bind functions
This fixes a performance regressions introduced by 178fb79b5c.

Also makes properties in the directive wrapper private
so that closure compiler can minify them better.
2016-10-28 11:17:12 -07:00
32feb8a532 refactor(compiler): generate host listeners in DirectiveWrappers
Part of #11683
2016-10-27 16:09:01 -07:00
a664aba2c9 build: ensure necessary symlinks created on windows
Bash scripts create and tear down symlinks on Windows. These use the
packages.txt file as input to identify the symlink locations. The
scripts ignored the last line in packages.txt if it didn't end with a
newline. Also, one location was missing. Resolve both issues.

Closes #12422
2016-10-27 12:13:39 -07:00
d520fae70e refactor(upgrade): spec cleanup 2016-10-27 12:12:55 -07:00
fa93fd672e fix(upgrade): silent bootstrap failures
fixes #12062
2016-10-27 12:12:54 -07:00
f4be2f907d docs(changelog): fix changelog title 2016-10-27 20:38:56 +02:00
2ea27a76d3 docs(changelog): update changelog with changes in v2.1.2 2016-10-27 20:30:48 +02:00
ec0acf9a1b chore(release): cut the 2.2.0-beta.0 release 2016-10-27 18:28:07 +02:00
a26dd28bdb refactor(upgrade): re-export the new static upgrade APIs on new entry
Add upgrade-static.umd.js bundles
This allows depending on it without getting a transitive dependency on compiler.

BREAKING CHANGE:

Four newly added APIs in 2.2.0-beta:
downgradeComponent, downgradeInjectable, UpgradeComponent, and UpgradeModule
are no longer exported by @angular/upgrade.
Import these from @angular/upgrade/static instead.
2016-10-26 15:14:22 -07:00
7742ec00e7 fix: remove double exports of template_ast 2016-10-26 15:14:00 -07:00
2b5c983c13 docs(reset): change semi-colon to colon in code example
The first code example for the reset function was invalid as it has a semi-colon instead of a colon for the last property in the json object.  Change the semi-colon to a colon.

Closes https://github.com/angular/angular/issues/12531
2016-10-26 14:56:57 -07:00
ef153649b3 fix(compiler-cli): fix types 2016-10-26 14:56:27 -07:00
d321b0ebf5 fix(selectors): use Maps instead of objects 2016-10-26 14:55:59 -07:00
b4265e0685 fix(xsrf): overwrite already set xsrf header 2016-10-26 14:55:24 -07:00
178fb79b5c refactor(compiler): move host properties into DirectiveWrapper
Part of #11683
2016-10-26 14:32:24 -07:00
5a7a58b1e0 refactor(compiler): make arguments in InlineArray optional. 2016-10-26 14:32:24 -07:00
f66ac821a2 refactor(compiler): extract createCheckBindingStmt into compiler_util
Part of #11683
2016-10-26 14:32:24 -07:00
fe299f4dfc refactor(compiler): minor cleanups 2016-10-26 14:32:24 -07:00
4cac650675 refactor(compiler): extract expression evaluation and writing to renderer from view_compiler
This is needed to that `DirectiveWrapper`s can also use them later on.

Part of #11683
2016-10-26 14:32:24 -07:00
cb7643ccea refactor(compiler): introduce ClassBuilder.
Part of #11683
2016-10-26 14:32:23 -07:00
faa3478514 refactor(compiler): set element attributes via one call
This makes the cost of using directives that have host attributes
smaller.

Part of #11683
2016-10-26 14:32:23 -07:00
bc3f4bc816 refactor(compiler): extract BindingParser
Needed so that we can parse directive host bindings independent of templates.

Part of #11683
2016-10-26 14:32:23 -07:00
c9f58cf78c feat(router): export routerLinkActive w/ isActive property 2016-10-26 14:08:22 -07:00
6ccbfd41dd fix(router): preserve resolve data
Closes #12306
2016-10-26 13:53:00 -07:00
7d2554baa1 tests(router): add a test showing how to handle resovle errors 2016-10-26 13:52:59 -07:00
52a853e257 fix(router): change router not to deactivate aux routes when navigating from a componentless routes 2016-10-26 13:52:59 -07:00
8f2fa0f766 fix(router): disallow component routes with named outlets
Closes #11208, #11082
2016-10-26 13:52:59 -07:00
fc60fa790c fix(router): add a test to make sure canDeactivate guards are called for aux routes
Closes #11345
2016-10-26 13:52:58 -07:00
b74185369f fix(router): canDeactivate guards are not triggered for componentless routes
Closes #12375
2016-10-26 13:52:58 -07:00
7221632228 fix(CompilerCli): assert that all pipes and directives are declared by a module 2016-10-25 18:17:18 -07:00
02f1222a8d docs(common): minor corrections/improvements for NgClass (#12327) 2016-10-25 00:12:09 +02:00
c27ce7318f doc(compiler-cli): align example with style guide (#12414)
See The Angular Style Guide, [Section 2.2 - Separate File Names with Dots and Dashes](https://angular.io/docs/ts/latest/guide/style-guide.html#!#02-02)
2016-10-25 00:10:03 +02:00
a838aba756 fix(compiler): walk third party modules (#12453)
fixes #11889
fixes #12428
2016-10-24 22:28:23 +02:00
bfc97ff2cd refactor(i18n): extract Extractor from extract_i18n (#12417)
I put an extractor into your extract so you can extract while you
extract.

This allows integrators to call Extractor as a library. Also refactors
Extractor a bit so that callers need fewer arguments or arguments that
are at the right semantic level.

The refactoring causes no function change.
2016-10-21 15:17:57 -07:00
57051f01ce refactor: remove most facades (#12399) 2016-10-21 15:14:44 -07:00
e319cfefc3 docs(changelog): fix minor typo (#12429) 2016-10-21 14:27:07 -07:00
444014ad96 docs(changelog): add 2.1.1 changelog 2016-10-20 15:49:59 -07:00
867494a060 fix(compiler): don't access view local variables nor pipes in host expressions (#12396)
Fixes #12004
Closes #12071
2016-10-20 15:24:58 -07:00
69ad99dca6 chore(release): cut the 2.2.0-beta.0 release and add changelog 2016-10-20 14:36:46 -07:00
da5fc696bb fix(router): do not update primary route if only secondary outlet is given (#11797) 2016-10-20 10:59:08 -07:00
b44b6ef8f5 fix(router): module loader should start compiling modules when stubbedModules are set (#11742) 2016-10-20 10:58:53 -07:00
0f21a5823b cleanup(router): add a test verifying than NavigationEnd is not emitted after NavigationCancel 2016-10-20 10:56:12 -07:00
5ae6915600 fix(router): fix lazy loading triggered by redirects from wildcard routes
Closes #12183
2016-10-20 10:56:12 -07:00
8b9ab44eee feat(router): add support for ng1/ng2 migration (#12160) 2016-10-20 10:44:44 -07:00
b0a03fcab3 refactor(compiler): introduce directive wrappers to generate less code
- for now only wraps the `@Input` properties and calls
  to `ngOnInit`, `ngDoCheck` and `ngOnChanges` of directives.
- also groups eval sources by NgModule.

Part of #11683
2016-10-20 10:41:43 -07:00
c951822c35 refactor(compiler): don’t use the OfflineCompiler in extract_i18n 2016-10-20 10:41:43 -07:00
acda82c1ed refactor(compiler): remove private exports
All of `@angular/compiler` is private, so we can export
everything we need directly.
2016-10-20 10:41:43 -07:00
a8815d6b08 chore(ci): re-enable browserstack tests in ci 2016-10-20 10:01:51 -07:00
d6791ff0e0 feat(ngUpgrade): add support for AoT compiled upgrade applications
This commit introduces a new API to the ngUpgrade module, which is compatible
with AoT compilation. Primarily, it removes the dependency on reflection
over the Angular 2 metadata by introducing an API where this information
is explicitly defined, in the source code, in a way that is not lost through
AoT compilation.

This commit is a collaboration between @mhevery (who provided the original
design of the API); @gkalpak & @petebacondarwin (who implemented the
API and migrated the specs from the original ngUpgrade tests) and @alexeagle
(who provided input and review).

This commit is an starting point, there is still work to be done:

* add more documentation
* validate the API via internal projects
* align the ngUpgrade compilation of A1 directives closer to the real A1
  compiler
* add more unit tests
* consider support for async `templateUrl` A1 upgraded components

Closes #12239
2016-10-19 15:27:49 -07:00
a2d35641e3 chore(tslint.json): semicolon rule expects an array 2016-10-19 22:38:14 +01:00
76dd026447 refactor: remove some facades (#12335) 2016-10-19 13:42:39 -07:00
0ecd9b2df0 chore(ci): make browserstack tests optional until they are fixed 2016-10-19 10:41:00 -07:00
0e9503b500 feat(forms) range values need to be numbers instead of strings (#11792) 2016-10-19 10:12:13 -07:00
f77ab6a2d2 feat(datePipe): support narrow forms for month and weekdays (#12297)
Closes #12294
2016-10-19 10:05:13 -07:00
97bc97153b feat(forms): add ng-pending CSS class during async validation (#11243)
Closes #10336
2016-10-19 09:56:31 -07:00
445e5922ec feat(forms): make 'parent' a public property of 'AbstractControl' (#11855) 2016-10-19 09:55:50 -07:00
b9fc090143 feat(forms): Added emitEvent to AbstractControl methods (#11949)
* feat(forms): Added emitEvent to AbstractControl methods

* style(forms): unified named parameter
2016-10-19 09:54:54 -07:00
592f40aa9c feat(forms): add hasError and getError to AbstractControlDirective (#11985)
Allows cleaner expressions in template-driven forms.

Before:

    <label>Username</label><input name="username" ngModel required #username="ngModel">
    <div *ngIf="username.dirty && username.control.hasError('required')">Username is required</div>

After:

    <label>Username</label><input name="username" ngModel required #username="ngModel">
    <div *ngIf="username.dirty && username.hasError('required')">Username is required</div>

Fixes #7255
2016-10-19 09:49:02 -07:00
24facdea2d feat(benchmark): add large form benchmark
This benchmark tracks the generated file size for large forms
as well as the time to create and destroy many form fields.
2016-10-19 09:39:16 -07:00
aa2d3372a5 fix(benchmarks): fix method name in targetable spec 2016-10-19 09:39:16 -07:00
bf60418fdc feat(forms): Validator.pattern accepts a RegExp (#12323) 2016-10-19 09:37:54 -07:00
cca4a5c519 fix(compiler): don't redeclare a var in the same scope (#12386)
This is not allowed by Closure Compiler.
2016-10-18 20:28:30 -07:00
6e5f8b59b3 fix(animations): generate aot code for animation trigger output events (#12291)
Closes #11707
Closes #12291
2016-10-18 17:16:51 -07:00
8409b65153 fix(http): make normalizeMethodName optimizer-compatible. (#12370)
`normalizeMethodName` reflectively accessed the RequestMethod enum. With a smart
optimizer, properties from the enum could be removed or renamed, and so user
code just passing in e.g. 'PATCH' might not work. This change fixes the code to
be more explicit and avoids the optimizer issue.
2016-10-18 11:21:54 -07:00
38e2203b24 refactor(core): delete unused reflector code 2016-10-17 23:17:34 -07:00
bd1dcb5f11 fix(core): fix decorator defalut values 2016-10-17 23:17:34 -07:00
3993279527 fix(core): fix property decorators
fixes #12224
2016-10-17 23:17:34 -07:00
bf1e2613b2 refactor(core): cleanup decorators 2016-10-17 23:17:34 -07:00
f7db0668d1 refactor(core): simplify & cleanup reflection 2016-10-17 23:17:34 -07:00
27d76776b8 fix(router): correctly export filter operator in es5 (#12286) 2016-10-17 23:06:19 -07:00
8603d9c269 refactor(http): use Http.request for all http shorthand methods (#12319) 2016-10-17 23:04:25 -07:00
d55f747858 docs(router): attribute notation for string paths (#12205)
Either bind an expression or use the attribute notation.
The mixed way `[routerLink]="/path"` won't work.
Prefer the attribute notation for string-only paths
2016-10-17 22:53:55 -07:00
52de0fa558 docs(CONTRIBUTING.md): fix typo (reproductions --> reproduction) (#12230) 2016-10-17 22:52:44 -07:00
d61ecf0663 docs(NgSwitch): fix mismatched tags in example (#12270) 2016-10-17 22:51:56 -07:00
5a9c5f28b8 docs(CHANGELOG.md): remove incorrect link (#12259) 2016-10-17 22:51:44 -07:00
15fc5dd7ee test(forms): added missing selfOnly tests (#12317) 2016-10-17 22:51:13 -07:00
a5419608e0 docs(ngIf): minor improvements 2016-10-17 22:50:12 -07:00
5f95bf1dd2 refactor(common): remove redundant type 2016-10-17 22:50:12 -07:00
33c8948fd3 refactor(animations): ensure animation data-structures are created only when used
Closes #12250
2016-10-14 15:43:41 -07:00
606e51881a perf(benchmarks): update ng2-switch to match ng2
- use the ~same template layout (text nodes),
- use trackBy

both benchmark now show about the same perfs.
2016-10-12 17:11:46 -07:00
fdf4309b50 perf(common): optimize NgSwitch default case
relates to #11297
2016-10-12 17:11:46 -07:00
af996ef0c4 docs(changelog): fix typo in code name, ouch! 2016-10-12 14:05:48 -07:00
68d2dfdd2a docs(changelog): tweak the change log and group all the 2.1 changes together 2016-10-12 13:54:21 -07:00
07bd4b0630 chore: bump version number and generate CHANGELOG (#12247) 2016-10-12 13:19:31 -07:00
df1718d624 fix(compiler): allow WS as <ng-content> content (#12225) 2016-10-12 07:58:06 -07:00
17e3410d98 Form submit event (#11989)
* feat(forms): ngSubmit event exposes $event from original submit event as local variable

Modify NgForm directive and FormGroup directive to expose the original submit event as $event in the ngSubmit event. Modify docs to reflect changes.

This resolves #10920.

* refactor: code cleanup
2016-10-11 15:49:36 -07:00
5effc330ed feat(upgrade): compilerOptions in bootstrap (#10575) 2016-10-11 15:48:08 -07:00
3df00828d7 docs(router): fix CanActivateChild API docs (#12128)
fixes #12127
2016-10-11 15:47:57 -07:00
8c477b2f45 fix(compiler-cli): don't clone static symbols when simplifying annotation metadata (#12158) 2016-10-11 15:47:44 -07:00
7787771aba refactor(core): cleanup decorators.ts (#12161) 2016-10-11 15:47:20 -07:00
7275e1beb3 refactor(compiler): add optional visit() to TemplateAstVisitor (#12209) 2016-10-11 15:46:11 -07:00
12ba62e5e2 refactor(compiler): expose template parser phases (#12210) 2016-10-11 15:45:27 -07:00
e6e007e2f1 refactor(core): cleanup SpyObject (#12221) 2016-10-11 15:44:48 -07:00
91dd138fa5 docs(animations): document :enter and :leave transition aliases (#12222) 2016-10-11 15:44:38 -07:00
d972d82354 refactor: simplify isPresent(x) ? x : y to x || y (#12166)
Closes #12166
2016-10-10 09:20:58 -07:00
bdcf46f82e refactor(compiler): improve types, misc 2016-10-10 09:20:58 -07:00
79e1c7b807 refactor(upgrade): unify spec code (#12190)
- replace all variable declarations using 'var' by 'const' or 'let'
- replace es5 function declaration by arrow function where applicable
2016-10-10 09:18:33 -07:00
d22eeb70b8 fix(forms): allow optional fields with pattern and minlength validators (#12147) 2016-10-10 09:17:45 -07:00
aa92512ac6 fix(compiler): properly shim :host:before and :host(:before) (#12171)
fixes #12165
2016-10-10 09:15:15 -07:00
f782b08f58 docs: Minor typo fix (#12151) 2016-10-10 09:14:35 -07:00
4202936bbf refactor(compiler): add optional visit() to html AST Visitor (#12135) 2016-10-10 09:13:50 -07:00
e1faca6386 refactor(compiler): template element ast has endSourceSpan (#12138) 2016-10-10 09:12:05 -07:00
f5b0e22d35 docs(public_api): fix missing backtick 2016-10-07 17:23:08 -07:00
00693d70a2 docs: add PUBLIC_API.md 2016-10-07 14:29:16 -07:00
bcef5efffe fix(platform-browser-dynamic): mark platformBrowserDynamic as stable API (#12154)
Everyone building Angular apps need to use this api to bootstrap or AoT compile, so it can't be experimental.
2016-10-07 13:54:06 -07:00
13ecc140e8 fix(compiler): validate @HostBinding name (#12139)
relates to #7500
2016-10-07 13:53:53 -07:00
709a6dea06 refactor(compiler): attribute ast records span of the value (#12132) 2016-10-07 13:53:29 -07:00
16cfb88c00 refactor(compiler): refactor analyzeModules() out of OfflineCompiler (#12137) 2016-10-07 13:52:53 -07:00
efee6f5199 docs(saved-replies): order the replies as shown in github (#12153)
github sorts the replies by reply name.
2016-10-07 13:52:18 -07:00
2aa8aae76d docs(saved-replies): add document with saved replies for our issue tracker 2016-10-07 09:21:20 -07:00
afb4bd9ef6 refactor(NgZone): merge NgZoneImpl and NgZone (#12104) 2016-10-06 15:23:37 -07:00
d641c36a45 fix(compiler): interpolation expressions report the correct offset (#12125) 2016-10-06 15:22:10 -07:00
f4566f8128 fix(http): fix Headers initialization from Headers and Object (#12106) 2016-10-06 15:21:27 -07:00
a67c06708d fix(http): Headers.append should append to the list 2016-10-06 15:21:03 -07:00
d9d57d71dd refactor(http): move one Headers test inside the main describe 2016-10-06 15:21:03 -07:00
e06303a987 fix(router): improve error message (#12102) 2016-10-06 15:19:22 -07:00
40b92ddf21 fix(router): wildcards routes should support lazy loading
Closes #12024
2016-10-06 15:19:09 -07:00
1681e4f57f fix(router): parent resolve should complete before merging resolved data
Closes #12032
2016-10-06 15:19:09 -07:00
71b7654660 fix(compiler-cli): remove peerDependency on @angular/platform-server (#12122)
There is no runtime dependency from the compiler-cli on @angular/platform-server - it was most likely added to package.json by mistake.
2016-10-06 15:16:41 -07:00
eaaec6979c fix(compiler-cli): remove unused parse5 dependency from package.json
This was added in error or is an obsolete dependency. We don't need parse5 for the compiler-cli's runtime.
2016-10-06 15:16:22 -07:00
c587c63591 docs(changelog): fix mentions, backticks and a misplaced line ending (#12109)
* docs(changelog): fix mentions and backticks

`@page` and `@document` were both incorrectly linking to GitHub repositories.
`:enter` and `:leave` in the *Features* section were missing backticks.

* Fix misplaced line ending.
2016-10-06 15:12:41 -07:00
f50c1da4e2 fix(forms): properly validate blank strings with minlength (#12091) 2016-10-06 15:12:09 -07:00
0254ce1f6c refactor(core): simplify Reflector code, add types (#12099) 2016-10-06 15:11:16 -07:00
c9b765f5c0 refactor(compiler): module collector is reusable (#12095) 2016-10-06 15:10:44 -07:00
8c975ed156 refactor(facade): inline StringWrapper (#12051) 2016-10-06 15:10:27 -07:00
bb35fcb562 docs(contributing): remove references to Angular 2
It's just Angular.
2016-10-06 15:07:46 -07:00
57230b70a9 docs(contributing): update the "Submitting an Issue" section 2016-10-06 15:06:37 -07:00
43dc60ce4f docs(contributing): update "got a question or a problem" section
Inspired by: https://github.com/ng-bootstrap/ng-bootstrap#getting-help
2016-10-06 13:58:14 -07:00
230b3b73d8 chore(benchpress): fix the license (#12090)
It's not Apache MIT 2.0, that's a mishmash of Apache 2.0 and MIT
2016-10-06 10:24:01 -07:00
0b7dc2f9ff docs(RouterTestingModule) change modules to imports in example (#12118) 2016-10-06 10:22:39 -07:00
de1f44f51f fix(benchmarks): allow ng2_switch benchmark to be used with AoT. (#12124) 2016-10-06 10:22:08 -07:00
f1cfddf6d6 refactor(benchmarks): add index_aot to support AoT bootstrap. (#12105)
Note: This only make sure it can compile the AoT version, but does not yet use it in e2e tests.
2016-10-06 08:37:37 -07:00
ef621a2f00 docs(changelog): tweak changelog 2016-10-06 06:43:17 -07:00
df9761951b docs(changelog): added changelog for 2.1.0-rc.0 2016-10-05 16:48:22 -07:00
f786c560f1 doc(triage): add info about user pain, frequency and severity labels 2016-10-05 15:58:45 -07:00
c5557de3e7 doc(triage): correct existing incorrect info 2016-10-05 15:58:45 -07:00
ec3a5b54de docs(readme): remove incorrect download count badge
npm doesn't currently support download counts for scoped packages, so there is no replacement right now.
2016-10-05 11:37:28 -07:00
cf269d9ff4 refactor: add license header to JS files & format files (#12081) 2016-10-04 20:39:20 -07:00
5fa5ffb82a refactor(benchmarks): refactor to support AOT bootstrap in G3 (#12075) 2016-10-04 16:27:45 -07:00
4a57dcfd8d fix(forms): properly validate empty strings with patterns (#11450) 2016-10-04 16:14:23 -07:00
43923ffcf5 docs(traige): update triaging doc 2016-10-04 16:13:32 -07:00
50c37d45dc refactor: simplify arrow functions (#12057) 2016-10-04 15:57:37 -07:00
a63359689f fix(ShadowCss): fix attribute selectors in :host and :host-context (#12056)
Fix a regression introduced in #11917 while fixing #6249
2016-10-04 15:40:31 -07:00
43d3a84df3 Revert "refactor: add license header to JS files & format files (#12035)"
This reverts commit 8310c91823.
2016-10-04 14:06:41 -07:00
8310c91823 refactor: add license header to JS files & format files (#12035) 2016-10-04 13:15:49 -07:00
b64b5ece65 refactor(facade): Remove most of StringMapWrapper facade. (#12022)
This change mostly automated by
12012b07a2
with some manual fixes.
2016-10-03 16:46:05 -07:00
ed9c2b6281 fix(Header): preserve case of the first init, set() or append() (#12023)
fixes #11624
2016-10-03 15:27:56 -07:00
1cf5f5fa38 docs(NgModule): Fixed docs for NgModule.entryComponents (#12006)
* docs(NgModule): Corrected the wording of the documentation of `entryComponents`, fixed some minor grammar issues

* docs(NgModule): Remove redundant ComponentFactory mentions

* docs(NgModule): Restore ComponentFactory/ComponentResolver links
2016-10-03 10:19:03 -07:00
a32078f85e docs(DEVELOPER.md): fix typos on "Tests" section (#12029) 2016-10-02 14:19:47 -07:00
decd129a4d refactor(facade): remove DateWrapper (#12027) 2016-10-02 14:12:14 -07:00
c3c9ecb302 text(offline compiler): fix expected output 2016-09-30 17:59:43 -07:00
af520947aa test(AstSerializer): fix serializing void tags 2016-09-30 17:59:43 -07:00
040bf57966 fix(xlif): fix <x> ctype names
fixes #12000
see http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#ctype
2016-09-30 17:59:43 -07:00
65a60b7456 style(I18N): Carriage returns in serialized files 2016-09-30 17:59:43 -07:00
756ef09d12 docs(gh): try to improve the issue template (#11891) 2016-09-30 16:40:56 -07:00
9316f95467 fix(ShadowCss): support @page and @document CSS rules (#11878)
fixes #11860
2016-09-30 16:26:24 -07:00
83d94b7504 fix(ShadowCss): support quoted attribute values
fixes #6085
2016-09-30 14:37:41 -07:00
a121136fae refactor(ShadowCss): add missing types 2016-09-30 14:37:41 -07:00
a6bb84e02b fix(ShadowCss): fix :host(tag) and :host-context(tag)
fixes #11972
2016-09-30 14:37:41 -07:00
3898dc488e fix(BrowserAdapter): correctly removes styles on IE
fixes #7916
2016-09-30 11:18:17 -07:00
ca3f9926f9 refactor(BrowserAdapter): cleanup 2016-09-30 11:18:17 -07:00
1c012a035f refactor(CssSelector): misc cleanup 2016-09-30 11:06:24 -07:00
38c5304b7f docs(CssSelector): [name*=value] is not supported
fixes #6042
2016-09-30 11:06:24 -07:00
9a049be67f feat(Parse5): update to the latest version 2.2.1
fixes #6237
2016-09-30 10:46:49 -07:00
2045c9e8ee docs: update docs for ng2_ftl benchmark 2016-09-30 10:42:21 -07:00
6c4ec05a4a fix(ShadowCss): support [attr="value with space"]
fixes #6249
2016-09-30 10:27:35 -07:00
f7bfda31ff refactor(ShadowCss): cleanup 2016-09-30 10:27:35 -07:00
a92b573309 test(DirectiveResolver): test that a prop can have both @Input and @HostBinding 2016-09-30 10:08:52 -07:00
4fd13d71c8 refactor(DirectiveResolver): cleanup 2016-09-30 10:08:52 -07:00
bf7b82b658 fix(UrlSearchParams): change a behavior when a param value is null or undefined (#11990) 2016-09-30 09:57:26 -07:00
c143fee849 refactor(routerLinkActive): optimised routerLinkActive active check code (#11968)
Modify routerLinkActive to optimise performance by removing unnecessary iteration. By replacing Array.reduce with Array.some, the loop will break when it finds an active link. Useful if used on the parent of a large group of routerLinks. Furthermore, if a RouterLink is active it will not check the RouterLinkWithHrefs.
2016-09-30 09:42:54 -07:00
0286956107 refactor(facade): Inline isBlank called with object-type argument (#11992) 2016-09-30 09:26:53 -07:00
e884f4854d feat(animations): provide aliases for :enter and :leave transitions (#11991) 2016-09-30 09:15:56 -07:00
df1822fc2a benchmarks: add ng2_ftl and ng2_switch_ftl benchmarks (#11963)
These benchmarks take the output of AoT
and manually tweaks it to explore possible
future changes to the compiler to produce
this output directly.
2016-09-30 09:09:31 -07:00
42b4b6d21b fix(upgrade): bind optional properties when upgrading from ng1 (#11411)
Previously, optional properties of a directive/component would be wrongly mapped and thus ignored.

Closes #10181
2016-09-29 09:45:28 -07:00
36bc2ff269 docs(forms): Added FormControl initialization information (#11948) 2016-09-28 13:59:08 -07:00
1564042fe8 fix(ngc): allow ReflectorHost passed as argument to CodeGenerator#create (#11951) 2016-09-27 17:12:57 -07:00
41c8c30973 chore(lint): remove unused imports (#11923)
This was done automatically by tslint, which can now fix issues it finds.
The fixer is still pending in PR https://github.com/palantir/tslint/pull/1568
Also I have a local bugfix for https://github.com/palantir/tslint/issues/1569
which causes too many imports to be deleted.
2016-09-27 17:12:25 -07:00
61129fa12d fix(compiler): move detection of unsafe properties for binding to ElementSchemaRegistry (#11378) 2016-09-27 17:10:02 -07:00
3a5b4882bc fix(compiler): Do not embed templateUrl in view factories in non-debug mode. (#11818)
Fixes #11117.
2016-09-27 17:09:44 -07:00
425c1e6042 refactor: remove dead code 2016-09-27 16:13:09 -07:00
58605cf350 refactor(facade): remove useless facades 2016-09-27 16:13:09 -07:00
34b31dea7c docs(upgrade): rename undeclared Ng2 to Ng2Component (#11950) 2016-09-27 16:11:41 -07:00
a241ab7c07 (docs): removing addProvider from UpgradeAdapter (#11934)
The `addProvider` function in the `UpgradeAdapter` was deprecated in this [commit](d21331e902 (diff-77163e956a7842149f583846c1c01651)) and has been removed in final. Given this, the documentation for downgrading ng2 providers for use in ng1 is invalid.
2016-09-27 10:10:45 -07:00
745e10e6d2 docs(router_config): add missing quote (#11925) 2016-09-27 10:10:12 -07:00
33340dbbd1 docs: remove outdated docs (#11875) 2016-09-24 08:23:28 +09:00
52812c08e2 chore(CHANGELOG): fix wrong issue link (#11871) 2016-09-24 07:13:24 +09:00
52f5ae1961 chore(compiler): followup fix for PR#11846 (#11870)
Original PR set [] to any, but any[], is a tighter type and still
works for SNC enabled consumers of the emit.
2016-09-24 07:13:05 +09:00
9be895b6da docs(ExceptionHandler): fix API docs (#11772)
fixes #11769
2016-09-24 07:05:43 +09:00
9f1c82537e ci(travis): increase node's heap size to prevent OOM on travis (#11869) 2016-09-24 06:04:29 +09:00
5ab5cc77bb Fix(http): invalidStateError if response body without content (#11786)
Fix(http): invalidStateError if response body without content
If the responseType has been specified and other than 'text', responseText throw an InvalidStateError exception

See XHR doc => https://xhr.spec.whatwg.org/#the-responsetext-attribute

Unit Test to prevent invalidStateError
2016-09-24 05:44:01 +09:00
f1b6c6efa1 refactor(animations): ensure animation input/outputs are managed within the template parser (#11782)
Closes #11782
Closes #11601
Related #11707
2016-09-24 05:37:04 +09:00
45ad13560b docs(changelog): remove info about an internal change 2016-09-23 12:02:56 -07:00
2045268cec chore(release): v2.1.0-beta.0 2016-09-23 11:41:35 -07:00
fb1076b44a docs(changelog): release notes for 2.1.0-beta.0 2016-09-23 11:37:28 -07:00
6fc46526ae fix(upgrade): allow attribute selectors for components in ng2 which are not part of upgrade (#11808)
fixes #11280
2016-09-24 02:47:16 +09:00
3ef5ede6d6 chore(compiler): emit ([] as any[]) instead of purely []. (#11846)
In SNC mode `[]` has type of never[], so we cast it to any[] to
typecheck correctly see
https://github.com/Microsoft/TypeScript/issues/10479.

This is temporary workaround, until we fully
migrate the framework to TS 2.0 and strictNullChecks.
2016-09-24 02:21:59 +09:00
136621ebc9 docs(Component): API docs for .encapsulation and .interpolation 2016-09-22 11:01:16 -07:00
f23b22a0f4 refactor: misc cleanup 2016-09-22 11:01:16 -07:00
0ca971c5bd refactor(common): cleanup (#11668) 2016-09-22 10:34:00 -07:00
3a6fcee0e6 docs(core): mark TestBed as stable api and add preliminary docs (#11767)
TestBed was accidentaly ommited from the 'stable' api list during the API sweep before final. We do consider it to be stable.
2016-09-22 10:32:17 -07:00
8972137c29 docs(contributing): remove preview references (#11795) 2016-09-22 10:31:56 -07:00
cc6481077f ci(BrowserStack): add Safari 10 (#11796) 2016-09-22 10:31:38 -07:00
c041b93418 refactor(TemplateParser): clearer error message for on* binding (#11802)
fixes #11756
2016-09-22 10:31:18 -07:00
bc33765913 chore(ISSUE_TEMPLATE): update Angular version field (#11821) 2016-09-22 10:29:12 -07:00
31dce72b7b fix(router): update the router not to reset router state when updating root component (#11799) 2016-09-21 11:37:43 -07:00
212f8dbde7 fix(forms): disable all radios with disable() 2016-09-20 15:00:12 -07:00
44da4984f9 fix(forms): support unbound disabled in ngModel (#11736) 2016-09-20 14:55:47 -07:00
d95344430c chore(zone.js): update to 0.6.25 (#11725) 2016-09-20 14:55:07 -07:00
131626fc61 fix(compiler): Safe property access expressions work in event bindings (#11724) 2016-09-20 14:54:53 -07:00
676bb0fa7d feat(router): update dts files 2016-09-20 14:53:52 -07:00
5a849829c4 feat(router): add router preloader to optimistically preload routes 2016-09-20 14:53:52 -07:00
671f73448c refactor: misc cleanup (#11654) 2016-09-19 17:15:57 -07:00
1138 changed files with 56584 additions and 26090 deletions

View File

@ -1,3 +1,7 @@
<!--
IF YOU DON'T FILL OUT THE FOLLOWING INFORMATION WE MIGHT CLOSE YOUR ISSUE WITHOUT INVESTIGATING
-->
**I'm submitting a ...** (check one with "x") **I'm submitting a ...** (check one with "x")
``` ```
[ ] bug report => search github for a similar issue or PR before submitting [ ] bug report => search github for a similar issue or PR before submitting
@ -5,14 +9,18 @@
[ ] support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question [ ] support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question
``` ```
**Current behavior** **Current behavior**
<!-- Describe how the bug manifests. --> <!-- Describe how the bug manifests. -->
**Expected behavior** **Expected behavior**
<!-- Describe what the behavior would be without the bug. --> <!-- Describe what the behavior would be without the bug. -->
**Reproduction of the problem** **Minimal reproduction of the problem with instructions**
<!-- If the current behavior is a bug or you can illustrate your feature request better with an example, please provide the steps to reproduce and if possible a minimal demo of the problem via https://plnkr.co or similar (you can use this template as a starting point: http://plnkr.co/edit/tpl:AvJOMERrnz94ekVua0u5). --> <!--
If the current behavior is a bug or you can illustrate your feature request better with an example,
please provide the *STEPS TO REPRODUCE* and if possible a *MINIMAL DEMO* of the problem via
https://plnkr.co or similar (you can use this template as a starting point: http://plnkr.co/edit/tpl:AvJOMERrnz94ekVua0u5).
-->
**What is the motivation / use case for changing the behavior?** **What is the motivation / use case for changing the behavior?**
<!-- Describe the motivation or the concrete use case --> <!-- Describe the motivation or the concrete use case -->
@ -20,12 +28,12 @@
**Please tell us about your environment:** **Please tell us about your environment:**
<!-- Operating system, IDE, package manager, HTTP server, ... --> <!-- Operating system, IDE, package manager, HTTP server, ... -->
* **Angular version:** 2.0.0-rc.X * **Angular version:** 2.0.X
<!-- Check whether this is still an issue in the most recent Angular version --> <!-- Check whether this is still an issue in the most recent Angular version -->
* **Browser:** [all | Chrome XX | Firefox XX | IE XX | Safari XX | Mobile Chrome XX | Android X.X Web Browser | iOS XX Safari | iOS XX UIWebView | iOS XX WKWebView ] * **Browser:** [all | Chrome XX | Firefox XX | IE XX | Safari XX | Mobile Chrome XX | Android X.X Web Browser | iOS XX Safari | iOS XX UIWebView | iOS XX WKWebView ]
<!-- All browsers where this could be reproduced --> <!-- All browsers where this could be reproduced -->
* **Language:** [all | TypeScript X.X | ES6/7 | ES5] * **Language:** [all | TypeScript X.X | ES6/7 | ES5]
* **Node (for AoT issues):** `node --version` = * **Node (for AoT issues):** `node --version` =

View File

@ -1,5 +1,601 @@
<a name="4.0.0-beta.2"></a>
# [4.0.0-beta.2](https://github.com/angular/angular/compare/4.0.0-beta.1...4.0.0-beta.2) (2017-01-06)
### Features
* **compiler:** generate less code for bindings to DOM elements ([db49d42](https://github.com/angular/angular/commit/db49d42))
* **compiler:** generate proper reexports in `.ngfactory.ts` files to not need transitive deps for compiling `.ngfactory.ts` files. ([#13524](https://github.com/angular/angular/issues/13524)) ([9c69703](https://github.com/angular/angular/commit/9c69703)), closes [#12787](https://github.com/angular/angular/issues/12787)
* **router:** add an extra argument to CanDeactivate interface ([#13560](https://github.com/angular/angular/issues/13560)) ([69fa3bb](https://github.com/angular/angular/commit/69fa3bb)), closes [#9853](https://github.com/angular/angular/issues/9853)
### Bug Fixes
* **common:** improve error message by adding a link to trackBy docs ([#13634](https://github.com/angular/angular/issues/13634)) ([6976903](https://github.com/angular/angular/commit/6976903))
* **common:** do not override locale provided on bootstrap ([#13654](https://github.com/angular/angular/issues/13654)) ([2dd6280](https://github.com/angular/angular/commit/2dd6280)), closes [#13607](https://github.com/angular/angular/issues/13607)
* **common:** allow null/undefined values for `NgForTrackBy` ([f88cd2f](https://github.com/angular/angular/commit/f88cd2f)), closes [#13641](https://github.com/angular/angular/issues/13641)
* **compiler:** dont throw when using `ANALYZE_FOR_ENTRY_COMPONENTS` with user classes ([#13679](https://github.com/angular/angular/issues/13679)) ([7690d02](https://github.com/angular/angular/commit/7690d02)), closes [#13565](https://github.com/angular/angular/issues/13565)
* **compiler:** improve error message for undefined providers ([#13546](https://github.com/angular/angular/issues/13546)) ([6b02b80](https://github.com/angular/angular/commit/6b02b80)), closes [#10835](https://github.com/angular/angular/issues/10835)
* **compiler:** improve the error when template is not a string ([2c0c86e](https://github.com/angular/angular/commit/2c0c86e)), closes [#8708](https://github.com/angular/angular/issues/8708) [#13377](https://github.com/angular/angular/issues/13377)
* **compiler:** query `<template>` elements before their children. ([#13677](https://github.com/angular/angular/issues/13677)) ([7c21064](https://github.com/angular/angular/commit/7c21064)), closes [#13118](https://github.com/angular/angular/issues/13118) [#13167](https://github.com/angular/angular/issues/13167)
* **compiler:** throw an error for invalid provider ([#13544](https://github.com/angular/angular/issues/13544)) ([445ed43](https://github.com/angular/angular/commit/445ed43)), closes [#8870](https://github.com/angular/angular/issues/8870)
* **compiler:** allow "." in attribute selectors ([#13653](https://github.com/angular/angular/issues/13653)) ([881eb89](https://github.com/angular/angular/commit/881eb89)), closes [#13645](https://github.com/angular/angular/issues/13645)
* **core:** animations no longer silently exits if the element is not apart of the DOM ([#13763](https://github.com/angular/angular/issues/13763)) ([21030e9](https://github.com/angular/angular/commit/21030e9))
* **core:** animations should blend in all previously transitioned styles into next animation if interrupted ([#13148](https://github.com/angular/angular/issues/13148)) ([889b48d](https://github.com/angular/angular/commit/889b48d))
* **core:** remove reference to "Angular 2" in dev mode warning ([#13751](https://github.com/angular/angular/issues/13751)) ([c5c53f3](https://github.com/angular/angular/commit/c5c53f3))
* **forms:** Validators.required properly validate arrays ([#13362](https://github.com/angular/angular/issues/13362)) ([9898d8f](https://github.com/angular/angular/commit/9898d8f)), closes [#12274](https://github.com/angular/angular/issues/12274)
* **i18n:** parse ICU messages while normalizing templates ([e74d8aa](https://github.com/angular/angular/commit/e74d8aa))
* **language-service:** support TypeScript 2.1 ([#13655](https://github.com/angular/angular/issues/13655)) ([8063b0d](https://github.com/angular/angular/commit/8063b0d))
* **router:** fix lazy loaded module with wildcard route ([#13649](https://github.com/angular/angular/issues/13649)) ([0eca960](https://github.com/angular/angular/commit/0eca960)), closes [#12955](https://github.com/angular/angular/issues/12955)
* **router:** routerLink support of null ([#13380](https://github.com/angular/angular/issues/13380)) ([174334d](https://github.com/angular/angular/commit/174334d)), closes [#6971](https://github.com/angular/angular/issues/6971)
* **router:** update route snapshot before emit new values ([#13558](https://github.com/angular/angular/issues/13558)) ([07e0fce](https://github.com/angular/angular/commit/07e0fce)), closes [#12912](https://github.com/angular/angular/issues/12912)
* **testing:** improve misleading error message when don't call compileComponents ([#13543](https://github.com/angular/angular/issues/13543)) ([67380d4](https://github.com/angular/angular/commit/67380d4)), closes [#11301](https://github.com/angular/angular/issues/11301)
* **upgrade:** fix/improve support for lifecycle hooks ([#13020](https://github.com/angular/angular/issues/13020)) ([e5c4e58](https://github.com/angular/angular/commit/e5c4e58))
### BREAKING CHANGES
* **core**: `SimpleChange` now takes an additional argument that defines whether this is the first
change or not. This is a low profile API and we don't expect anyone to be affected by this change.
If you are impacted by this change please file an issue. ([465516b](https://github.com/angular/angular/commit/465516b))
<a name="4.0.0-beta.1"></a>
# [4.0.0-beta.1](https://github.com/angular/angular/compare/2.4.0-marker...4.0.0-beta.1) (2016-12-22)
### Features
* **upgrade:** support the `$doCheck()` lifecycle hook in `UpgradeComponent` ([#13015](https://github.com/angular/angular/issues/13015)) ([9da4c25](https://github.com/angular/angular/commit/9da4c25))
Note: 4.0.0-beta.1 release also contains all the changes present in the 2.4.0 and the 2.4.1 releases.
<a name="2.4.1"></a>
## [2.4.1](https://github.com/angular/angular/compare/2.4.0...2.4.1) (2016-12-21)
### Bug Fixes
* **animations:** always quote string map key values in AOT code ([#13602](https://github.com/angular/angular/issues/13602)) ([6a5e46c](https://github.com/angular/angular/commit/6a5e46c))
* **animations:** always recover from a failed animation step ([#13604](https://github.com/angular/angular/issues/13604)) ([d788c67](https://github.com/angular/angular/commit/d788c67))
* **compiler:** ignore `@import` in comments ([#13368](https://github.com/angular/angular/issues/13368)) ([6316e5d](https://github.com/angular/angular/commit/6316e5d)), closes [#12196](https://github.com/angular/angular/issues/12196)
* **core:** improve error message when component factory cannot be found ([#13541](https://github.com/angular/angular/issues/13541)) ([b9e979e](https://github.com/angular/angular/commit/b9e979e)), closes [#12678](https://github.com/angular/angular/issues/12678)
* **router:** should reset location if a navigation by location is successful ([#13545](https://github.com/angular/angular/issues/13545)) ([a38f14b](https://github.com/angular/angular/commit/a38f14b)), closes [#13491](https://github.com/angular/angular/issues/13491)
<a name="2.4.0"></a>
# [2.4.0 stability-interjection](https://github.com/angular/angular/compare/2.3.1...2.4.0) (2016-12-20)
### Bug Fixes
* **animations:** allow players to be destroyed before initialized ([#13346](https://github.com/angular/angular/issues/13346)) ([b36f4bc](https://github.com/angular/angular/commit/b36f4bc)), closes [#13293](https://github.com/angular/angular/issues/13293)
* **build:** use bash string comparison operator ([#13502](https://github.com/angular/angular/issues/13502)) ([50afbe0](https://github.com/angular/angular/commit/50afbe0))
* **compiler:** do not lex `}}` when interpolation is disabled ([#13531](https://github.com/angular/angular/issues/13531)) ([9b87bb6](https://github.com/angular/angular/commit/9b87bb6)), closes [#13525](https://github.com/angular/angular/issues/13525)
* **compiler-cli:** produce metadata for .d.ts files without metadata ([#13526](https://github.com/angular/angular/issues/13526)) ([debb0c9](https://github.com/angular/angular/commit/debb0c9)), closes [#13307](https://github.com/angular/angular/issues/13307) [#13473](https://github.com/angular/angular/issues/13473) [#13521](https://github.com/angular/angular/issues/13521)
* **i18n:** add a default example to xmb placeholders ([#13507](https://github.com/angular/angular/issues/13507)) ([3f17841](https://github.com/angular/angular/commit/3f17841))
* **upgrade:** fix `registerForNg1Tests` ([#13522](https://github.com/angular/angular/issues/13522)) ([c26c24c](https://github.com/angular/angular/commit/c26c24c))
### Features
* update to `rxjs@5.0.1` and unpin the rxjs peerDeps via `^5.0.1` ([#13572](https://github.com/angular/angular/issues/13572)) ([8d5da1e](https://github.com/angular/angular/commit/8d5da1e)), closes [#13561](https://github.com/angular/angular/issues/13561) [#13478](https://github.com/angular/angular/issues/13478)
<a name="4.0.0-beta.0"></a>
# [4.0.0-beta.0](https://github.com/angular/angular/compare/2.3.0...4.0.0-beta.0) (2016-12-15)
### Features
* **common:** add a `titlecase` pipe ([#13324](https://github.com/angular/angular/issues/13324)) ([61d7c1e](https://github.com/angular/angular/commit/61d7c1e)), closes [#11436](https://github.com/angular/angular/issues/11436)
* **common:** export NgLocaleLocalization ([#13367](https://github.com/angular/angular/issues/13367)) ([56dce0e](https://github.com/angular/angular/commit/56dce0e)), closes [#11921](https://github.com/angular/angular/issues/11921)
* **compiler:** add id property to i18nMessage ([6dd5201](https://github.com/angular/angular/commit/6dd5201))
* **compiler:** digest methods return i18nMessage id if sets ([562f7a2](https://github.com/angular/angular/commit/562f7a2))
* **forms:** add novalidate by default ([#13092](https://github.com/angular/angular/issues/13092)) ([4c35be3](https://github.com/angular/angular/commit/4c35be3))
* **http:** simplify URLSearchParams creation ([#13338](https://github.com/angular/angular/issues/13338)) ([90c2235](https://github.com/angular/angular/commit/90c2235)), closes [#8858](https://github.com/angular/angular/issues/8858)
* **language-service:** warn when a method isn't called in an event ([#13437](https://github.com/angular/angular/issues/13437)) ([9ec0a4e](https://github.com/angular/angular/commit/9ec0a4e))
* **platform browser:** introduce Meta service ([#12322](https://github.com/angular/angular/issues/12322)) ([72361fb](https://github.com/angular/angular/commit/72361fb))
* **router:** routerLink add tabindex attribute ([#13094](https://github.com/angular/angular/issues/13094)) ([a006c14](https://github.com/angular/angular/commit/a006c14)), closes [#10895](https://github.com/angular/angular/issues/10895)
* **testing:** add overrideTemplate method ([#13372](https://github.com/angular/angular/issues/13372)) ([169ed82](https://github.com/angular/angular/commit/169ed82)), closes [#10685](https://github.com/angular/angular/issues/10685)
* **common** ngIf now supports else; saves condition to local var ([b4db73d](https://github.com/angular/angular/commit/b4db73d)), closes [#13061](https://github.com/angular/angular/issues/13061) [#13297](https://github.com/angular/angular/issues/13297)
Note: 4.0.0-beta.0 release also contains all the changes present in the 2.3.1 release.
<a name="2.3.1"></a>
## [2.3.1](https://github.com/angular/angular/compare/2.3.0...2.3.1) (2016-12-15)
### Bug Fixes
* **animations:** always cleanup players after they have finished internally ([#13334](https://github.com/angular/angular/issues/13334)) ([a26e054](https://github.com/angular/angular/commit/a26e054)), closes [#13333](https://github.com/angular/angular/issues/13333)
* **animations:** throw errors and normalize offset beyond the range of [0,1] ([6557bc3](https://github.com/angular/angular/commit/6557bc3)), closes [#13348](https://github.com/angular/angular/issues/13348) [#13440](https://github.com/angular/angular/issues/13440)
* **compiler:** emit quoted object literal keys if the source is quoted ([ecfad46](https://github.com/angular/angular/commit/ecfad46)), closes [#13249](https://github.com/angular/angular/issues/13249) [#13356](https://github.com/angular/angular/issues/13356)
* **compiler:** fix merge error in compiler_host ([69b52eb](https://github.com/angular/angular/commit/69b52eb))
* **compiler:** fix PR 13322 ([#13331](https://github.com/angular/angular/issues/13331)) ([79728b4](https://github.com/angular/angular/commit/79728b4))
* **compiler:** fix simplify a reference without a name ([1c279b3](https://github.com/angular/angular/commit/1c279b3)), closes [#13470](https://github.com/angular/angular/issues/13470)
* **compiler:** fix transpiled ES5 code ([#13322](https://github.com/angular/angular/issues/13322)) ([6c1d790](https://github.com/angular/angular/commit/6c1d790)), closes [#13301](https://github.com/angular/angular/issues/13301)
* **compiler:** generated CSS files suffixed with ngstyle. ([#13353](https://github.com/angular/angular/issues/13353)) ([c8a9b70](https://github.com/angular/angular/commit/c8a9b70)), closes [#13141](https://github.com/angular/angular/issues/13141)
* **compiler:** make sure provider values with `name` property dont break. ([efa2d80](https://github.com/angular/angular/commit/efa2d80)), closes [#13394](https://github.com/angular/angular/issues/13394) [#13445](https://github.com/angular/angular/issues/13445)
* **compiler:** narrow the span reported for invalid pipes ([307d305](https://github.com/angular/angular/commit/307d305)), closes [#13326](https://github.com/angular/angular/issues/13326) [#13411](https://github.com/angular/angular/issues/13411)
* **compiler:** propagate exports when upgrading metadata to v2 ([f6ef7d6](https://github.com/angular/angular/commit/f6ef7d6))
* **compiler:** resolver should merge host bindings and listeners ([#13474](https://github.com/angular/angular/issues/13474)) ([6aeaca3](https://github.com/angular/angular/commit/6aeaca3)), closes [#13327](https://github.com/angular/angular/issues/13327)
* **compiler:** support dotted property binding ([8db184d](https://github.com/angular/angular/commit/8db184d)), closes [angular/flex-layout#34](https://github.com/angular/flex-layout/issues/34)
* **compiler:** update to metadata version 3 ([#13464](https://github.com/angular/angular/issues/13464)) ([b9b557c](https://github.com/angular/angular/commit/b9b557c))
* **core:** detectChanges() doesn't work on detached instance ([4d6ac9d](https://github.com/angular/angular/commit/4d6ac9d)), closes [#13426](https://github.com/angular/angular/issues/13426) [#13472](https://github.com/angular/angular/issues/13472)
* **core:** properly destroy embedded Views attatched to ApplicationRef ([#13459](https://github.com/angular/angular/issues/13459)) ([d40bbf4](https://github.com/angular/angular/commit/d40bbf4)), closes [#13062](https://github.com/angular/angular/issues/13062)
* **core:** remove logError from logGroup ([#12925](https://github.com/angular/angular/issues/12925)) ([5fab871](https://github.com/angular/angular/commit/5fab871))
* **forms:** ensure `select[multiple]` retains selections ([b3dcff0](https://github.com/angular/angular/commit/b3dcff0)), closes [#12527](https://github.com/angular/angular/issues/12527) [#12654](https://github.com/angular/angular/issues/12654)
* **forms:** fix Validators.min/maxLength with FormArray ([#13095](https://github.com/angular/angular/issues/13095)) ([7383e4a](https://github.com/angular/angular/commit/7383e4a)), closes [#13089](https://github.com/angular/angular/issues/13089)
* **forms:** introduce checkbox required validator ([124267c](https://github.com/angular/angular/commit/124267c)), closes [#11459](https://github.com/angular/angular/issues/11459) [#13364](https://github.com/angular/angular/issues/13364)
* **http:** check response body text against undefined ([#13017](https://github.com/angular/angular/issues/13017)) ([f106a18](https://github.com/angular/angular/commit/f106a18))
* **http:** create a copy of headers when merge options ([#13365](https://github.com/angular/angular/issues/13365)) ([65c9b5b](https://github.com/angular/angular/commit/65c9b5b)), closes [#11980](https://github.com/angular/angular/issues/11980)
* **language-service:** correctly type `undefined` ([0a7364f](https://github.com/angular/angular/commit/0a7364f)), closes [#13412](https://github.com/angular/angular/issues/13412) [#13414](https://github.com/angular/angular/issues/13414)
* **compiler**: better error when directive not listed in NgModule.declarations ([b0cd514](https://github.com/angular/angular/commit/b0cd514))
* **language-service:** treat string unions as strings ([#13406](https://github.com/angular/angular/issues/13406)) ([14dd2b3](https://github.com/angular/angular/commit/14dd2b3)), closes [#13403](https://github.com/angular/angular/issues/13403)
* **router:** add support for query params with multiple values ([e4d5a5f](https://github.com/angular/angular/commit/e4d5a5f)), closes [#11373](https://github.com/angular/angular/issues/11373)
* **router:** Use T type in Resolve interface ([#13242](https://github.com/angular/angular/issues/13242)) ([5ee8155](https://github.com/angular/angular/commit/5ee8155))
* **selector:** SelectorMatcher match elements with :not selector ([#12977](https://github.com/angular/angular/issues/12977)) ([392c9ac](https://github.com/angular/angular/commit/392c9ac))
* **tsc-wrapped:** generate metadata for exports without module specifier ([cd03c77](https://github.com/angular/angular/commit/cd03c77)), closes [#13327](https://github.com/angular/angular/issues/13327)
* **upgrade:** fix downgrade content projection and injector inheritance ([86c5098](https://github.com/angular/angular/commit/86c5098)), closes [#6629](https://github.com/angular/angular/issues/6629) [#7727](https://github.com/angular/angular/issues/7727) [#8729](https://github.com/angular/angular/issues/8729) [#9643](https://github.com/angular/angular/issues/9643) [#9649](https://github.com/angular/angular/issues/9649) [#12675](https://github.com/angular/angular/issues/12675)
* **upgrade:** enable Angular 1 unit testing of upgrade module ([2fc0560](https://github.com/angular/angular/commit/2fc0560)), closes [#5462](https://github.com/angular/angular/issues/5462) [#12675](https://github.com/angular/angular/issues/12675)
### Performance Improvements
* **animations:** always run the animation queue outside of zones ([e2622ad](https://github.com/angular/angular/commit/e2622ad)), closes [#13440](https://github.com/angular/angular/issues/13440)
### Note ###
Due to regression in the 2.3.0 release that was fixed by [#13464](https://github.com/angular/angular/pull/13464),
components that have been compiled using 2.3.0 and published to npm will need to be recompiled and republished.
The >=2.3.1 compiler will issue is the following error if it encounters components compiled with 2.3.0:
`Unsupported metadata version 2 for module ${module}. This module should be compiled with a newer version of ngc`.
We are adding more tests to our test suite to catch these kinds of problems before we cut a release.
<a name="2.3.0"></a>
# [2.3.0](https://github.com/angular/angular/compare/2.3.0-rc.0...2.3.0) (2016-12-07)
### Bug Fixes
* **common:** make sure the plural category exists ([#13169](https://github.com/angular/angular/issues/13169)) ([82c81cd](https://github.com/angular/angular/commit/82c81cd)), closes [#12379](https://github.com/angular/angular/issues/12379)
* **compiler:** include the summaries of reexported modules / directives / pipes ([#13196](https://github.com/angular/angular/issues/13196)) ([75d1617](https://github.com/angular/angular/commit/75d1617))
* **compiler:** serialize any `StaticSymbol` correctly, not matter in which context ([5614c4f](https://github.com/angular/angular/commit/5614c4f))
* **compiler:** short-circut expressions with an index ([#13263](https://github.com/angular/angular/issues/13263)) ([f31c947](https://github.com/angular/angular/commit/f31c947)), closes [#13254](https://github.com/angular/angular/issues/13254)
* **core:** display framework version on bootstrapped component ([#13252](https://github.com/angular/angular/issues/13252)) ([16efb13](https://github.com/angular/angular/commit/16efb13))
* **facade:** cache original format string ([#12764](https://github.com/angular/angular/issues/12764)) ([a132287](https://github.com/angular/angular/commit/a132287))
* **http:** set the default Accept header ([#12989](https://github.com/angular/angular/issues/12989)) ([986abbe](https://github.com/angular/angular/commit/986abbe)), closes [#6354](https://github.com/angular/angular/issues/6354)
* **language-service:** avoid throwing for invalid class declarations ([#13257](https://github.com/angular/angular/issues/13257)) ([93556a5](https://github.com/angular/angular/commit/93556a5)), closes [#13253](https://github.com/angular/angular/issues/13253)
* **language-service:** do not throw for invalid metadata ([#13261](https://github.com/angular/angular/issues/13261)) ([4a09c81](https://github.com/angular/angular/commit/4a09c81)), closes [#13255](https://github.com/angular/angular/issues/13255)
* **language-service:** remove incompletely used parameter from `createLanguageServiceFromTypescript()` ([#13278](https://github.com/angular/angular/issues/13278)) ([25c2141](https://github.com/angular/angular/commit/25c2141)), closes [#13277](https://github.com/angular/angular/issues/13277)
* **language-service:** update to use `CompilerHost` from compiler-cli ([#13189](https://github.com/angular/angular/issues/13189)) ([3ff6554](https://github.com/angular/angular/commit/3ff6554))
* **router:** allow specifying a matcher without specifying a path ([bbb7a39](https://github.com/angular/angular/commit/bbb7a39)), closes [#12972](https://github.com/angular/angular/issues/12972)
* **router:** fix replaceUrl on RouterLink directives ([349ad75](https://github.com/angular/angular/commit/349ad75))
* **router:** fix skipLocationChanges on RouterLink directives ([f562cbf](https://github.com/angular/angular/commit/f562cbf)), closes [#13156](https://github.com/angular/angular/issues/13156)
* **router:** make setUpLocationChangeListener idempotent ([25e5b2f](https://github.com/angular/angular/commit/25e5b2f))
* **router:** runs guards every time when unsuccessfully navigating to the same url over and over again ([#13209](https://github.com/angular/angular/issues/13209)) ([d46b8de](https://github.com/angular/angular/commit/d46b8de))
* **router:** throw a better error message when angular 1 is not bootstraped ([c767df0](https://github.com/angular/angular/commit/c767df0))
* **router:** validate nested routes ([#13224](https://github.com/angular/angular/issues/13224)) ([2893c2c](https://github.com/angular/angular/commit/2893c2c)), closes [#12827](https://github.com/angular/angular/issues/12827)
* **tsc-wrapped:** have UserError display the actual error ([393c100](https://github.com/angular/angular/commit/393c100))
### Features
* **compiler:** read and write `.ngsummary.json` files ([614a35d](https://github.com/angular/angular/commit/614a35d)), closes [#12787](https://github.com/angular/angular/issues/12787)
<a name="2.3.0-rc.0"></a>
# [2.3.0-rc.0](https://github.com/angular/angular/compare/2.3.0-beta.0...2.3.0-rc.0) (2016-11-30)
### Bug Fixes
* **animations:** blend in all previously transitioned styles into next animation if interrupted ([#13014](https://github.com/angular/angular/issues/13014)) ([ef96763](https://github.com/angular/angular/commit/ef96763)), closes [#13013](https://github.com/angular/angular/issues/13013)
* **benchmarks:** use sanitized style values ([#12943](https://github.com/angular/angular/issues/12943)) ([fc5ac1e](https://github.com/angular/angular/commit/fc5ac1e))
* **build:** update versions of umd bundles ([#13038](https://github.com/angular/angular/issues/13038)) ([86ffa88](https://github.com/angular/angular/commit/86ffa88)), closes [#13037](https://github.com/angular/angular/issues/13037)
* **changelog:** replace beta.1 with beta.0 ([#12961](https://github.com/angular/angular/issues/12961)) ([07a986d](https://github.com/angular/angular/commit/07a986d))
* **ci:** pin version of npm on CircleCI ([#12954](https://github.com/angular/angular/issues/12954)) ([a3884db](https://github.com/angular/angular/commit/a3884db))
* **closure:** quote date pattern aliases ([#13012](https://github.com/angular/angular/issues/13012)) ([7dcca30](https://github.com/angular/angular/commit/7dcca30))
* **common:** update DatePipe to allow closure compilation ([b2b7219](https://github.com/angular/angular/commit/b2b7219))
* **compiler:** correctly evaluate references to static functions ([#13133](https://github.com/angular/angular/issues/13133)) ([627282d](https://github.com/angular/angular/commit/627282d))
* **compiler:** fix performance regression caused by 5b0f9e2 ([43c0e9a](https://github.com/angular/angular/commit/43c0e9a)), closes [#13146](https://github.com/angular/angular/issues/13146)
* **compiler:** fix versions of `@angular/tsc-wrapped` ([bccf0e6](https://github.com/angular/angular/commit/bccf0e6))
* **compiler-cli:** fix paths in source maps to be relative ([2a3ca7b](https://github.com/angular/angular/commit/2a3ca7b)), closes [#13040](https://github.com/angular/angular/issues/13040)
* **compiler-cli:** pin the version of `tsc-wrapped` ([966bcba](https://github.com/angular/angular/commit/966bcba))
* **language-service:** harden against partial normalization of directives ([2975d89](https://github.com/angular/angular/commit/2975d89))
* **core:** shrinkwrap was out of date with packages. ([e45b7ff](https://github.com/angular/angular/commit/e45b7ff))
* **language-service:** make link check pass ([7194fc2](https://github.com/angular/angular/commit/7194fc2))
* **router:** guards restore an incorrect url when used with skipLocationChange ([ad20d7d](https://github.com/angular/angular/commit/ad20d7d)), closes [#12825](https://github.com/angular/angular/issues/12825)
* **router:** support redirects to named outlets ([602522b](https://github.com/angular/angular/commit/602522b)), closes [#12740](https://github.com/angular/angular/issues/12740) [#9921](https://github.com/angular/angular/issues/9921)
* **tsc-wrapped:** set correct version number ([897555c](https://github.com/angular/angular/commit/897555c))
* **tsc-wrapped:** still emit version 1 metadata to allow use of new components in old setups ([bc69c74](https://github.com/angular/angular/commit/bc69c74))
* **upgrade:** call ng1 lifecycle hooks ([#12875](https://github.com/angular/angular/issues/12875)) ([1ef4696](https://github.com/angular/angular/commit/1ef4696))
* **version:** take all of version string after patch version ([f275f36](https://github.com/angular/angular/commit/f275f36))
### Features
* **core:** update RxJS peer dependency to 5.0.0-rc.4 Please see [this gist](https://gist.github.com/robwormald/19dea0c70a6e01aadced6731aed4f9f7) if you depend on the `cache` operator ([2d6a003](https://github.com/angular/angular/commit/2d6a003)), closes [#13125](https://github.com/angular/angular/issues/13125)
* **core:** upgrade zone.js to v0.7.1 ([c4bbafc](https://github.com/angular/angular/commit/c4bbafc))
* **build:** record angular version in the dom ([#13164](https://github.com/angular/angular/issues/13164)) ([e628b66](https://github.com/angular/angular/commit/e628b66))
* **core:** expose destroy() method on ViewRef ([808275a](https://github.com/angular/angular/commit/808275a))
* **core:** properly support inheritance ([f5c8e09](https://github.com/angular/angular/commit/f5c8e09)), closes [#11606](https://github.com/angular/angular/issues/11606) [#12892](https://github.com/angular/angular/issues/12892)
* **language-service:** add services to support editors ([#12987](https://github.com/angular/angular/issues/12987)) ([519a324](https://github.com/angular/angular/commit/519a324))
* **router:** add support for custom route reuse strategies ([42cf06f](https://github.com/angular/angular/commit/42cf06f))
* **tools:** allow disabling annotation lowering ([c1a62e2](https://github.com/angular/angular/commit/c1a62e2))
<a name="2.2.4"></a>
## [2.2.4](https://github.com/angular/angular/compare/2.2.3...2.2.4) (2016-11-30)
### Bug Fixes
* **common:** update DatePipe to allow closure compilation ([eba53fd](https://github.com/angular/angular/commit/eba53fd))
* **compiler:** fix performance regression caused by 5b0f9e2 ([ee2d6e5](https://github.com/angular/angular/commit/ee2d6e5)), closes [#13146](https://github.com/angular/angular/issues/13146)
* **compiler-cli:** fix paths in source maps to be relative ([eb173bc](https://github.com/angular/angular/commit/eb173bc)), closes [#13040](https://github.com/angular/angular/issues/13040)
<a name="2.2.3"></a>
## [2.2.3](https://github.com/angular/angular/compare/2.2.2...2.2.3) (2016-11-23)
### Bug Fixes
* **compiler:** Revert: fix versions of `@angular/tsc-wrapped` ([015ca47](https://github.com/angular/angular/commit/015ca47))
* **animations:** Revert: blend in all previously transitioned styles into next animation if interrupted ([c12e56e](https://github.com/angular/angular/commit/c12e56e))
<a name="2.2.2"></a>
## [2.2.2](https://github.com/angular/angular/compare/2.2.1...2.2.2) (2016-11-22)
### Bug Fixes
* **animations:** blend in all previously transitioned styles into next animation if interrupted ([#13014](https://github.com/angular/angular/issues/13014)) ([ea4fc9b](https://github.com/angular/angular/commit/ea4fc9b)), closes [#13013](https://github.com/angular/angular/issues/13013)
* **benchmarks:** use sanitized style values ([#12943](https://github.com/angular/angular/issues/12943)) ([33a7902](https://github.com/angular/angular/commit/33a7902))
* **closure:** quote date pattern aliases ([#13012](https://github.com/angular/angular/issues/13012)) ([0956ace](https://github.com/angular/angular/commit/0956ace))
* **compiler:** fix versions of `@angular/tsc-wrapped` ([2fe6fb1](https://github.com/angular/angular/commit/2fe6fb1))
* **router:** add a banner file for the router ([#12919](https://github.com/angular/angular/issues/12919)) ([8df328b](https://github.com/angular/angular/commit/8df328b))
* **router:** add a banner file for the router ([#12919](https://github.com/angular/angular/issues/12919)) ([511cd4d](https://github.com/angular/angular/commit/511cd4d))
* **router:** removes a peer dependency from router to upgrade ([115f18f](https://github.com/angular/angular/commit/115f18f))
* **router:** removes a peer dependency from router to upgrade ([87d5d49](https://github.com/angular/angular/commit/87d5d49))
* **router:** support redirects to named outlets ([09226d9](https://github.com/angular/angular/commit/09226d9)), closes [#12740](https://github.com/angular/angular/issues/12740) [#9921](https://github.com/angular/angular/issues/9921)
* **upgrade:** call ng1 lifecycle hooks ([#12875](https://github.com/angular/angular/issues/12875)) ([462316b](https://github.com/angular/angular/commit/462316b))
<a name="2.3.0-beta.0"></a>
# [2.3.0-beta.0](https://github.com/angular/angular/compare/2.2.0...2.3.0-beta.0) (2016-11-17)
### Bug Fixes
* **compiler:** assert xliff messages have translations ([7908679](https://github.com/angular/angular/commit/7908679)), closes [#12815](https://github.com/angular/angular/issues/12815) [#12604](https://github.com/angular/angular/issues/12604)
* **compiler:** updates hash algo for xmb/xtb files ([2f14415](https://github.com/angular/angular/commit/2f14415))
* **core:** fix placeholders handling in i18n. ([76e4911](https://github.com/angular/angular/commit/76e4911)), closes [#12512](https://github.com/angular/angular/issues/12512)
* **core:** misc i18n fixes ([ed5e98d](https://github.com/angular/angular/commit/ed5e98d))
* **core:** xmb serializer uses decimal messaged IDs ([08c038e](https://github.com/angular/angular/commit/08c038e)), closes [#12511](https://github.com/angular/angular/issues/12511)
* **platform-browser:** enable AOT ([efbbefd](https://github.com/angular/angular/commit/efbbefd)), closes [#12783](https://github.com/angular/angular/issues/12783)
### Features
* **core:** add `attachView` / `detachView` to ApplicationRef ([9f7d32a](https://github.com/angular/angular/commit/9f7d32a)), closes [#9293](https://github.com/angular/angular/issues/9293)
* **core:** expose `ViewRef` as `ChangeDetectorRef` ([1b5384e](https://github.com/angular/angular/commit/1b5384e)), closes [#12722](https://github.com/angular/angular/issues/12722)
* **core:** implements a decimal fingerprint for i18n ([582550a](https://github.com/angular/angular/commit/582550a))
* **router:** register router with ngprobe ([c2fae72](https://github.com/angular/angular/commit/c2fae72))
* **router_link:** add skipLocationChange and replaceUrl inputs ([#12850](https://github.com/angular/angular/issues/12850)) ([46d1502](https://github.com/angular/angular/commit/46d1502))
Note: The 2.3.0-beta.0 release also contains all the changes present in the 2.2.1 release.
<a name="2.2.1"></a>
## [2.2.1](https://github.com/angular/angular/compare/2.2.0...2.2.1) (2016-11-17)
### Bug Fixes
* **animations:** only pass in same typed players as previous players into web-animations ([#12907](https://github.com/angular/angular/issues/12907)) ([583d283](https://github.com/angular/angular/commit/583d283))
* **animations:** retain styling when transition destinations are changed ([#12208](https://github.com/angular/angular/issues/12208)) ([5c46c49](https://github.com/angular/angular/commit/5c46c49)), closes [#9661](https://github.com/angular/angular/issues/9661)
* **core:** support `ngTemplateOutlet` in production mode ([#12921](https://github.com/angular/angular/issues/12921)) ([4628798](https://github.com/angular/angular/commit/4628798)), closes [#12911](https://github.com/angular/angular/issues/12911)
* **http:** correctly handle response body for 204 status code ([21a4de9](https://github.com/angular/angular/commit/21a4de9)), closes [#12830](https://github.com/angular/angular/issues/12830) [#12393](https://github.com/angular/angular/issues/12393)
* **http:** return request url if it cannot be retrieved from response ([845ea23](https://github.com/angular/angular/commit/845ea23)), closes [#12837](https://github.com/angular/angular/issues/12837)
* **upgrade:** make AoT ngUpgrade work with the testability API and resumeBootstrap() ([#12910](https://github.com/angular/angular/issues/12910)) ([dc1662a](https://github.com/angular/angular/commit/dc1662a))
* **platform-browser:** fix disableDebugTools() ([#12918](https://github.com/angular/angular/issues/12918)) ([7b67bad](https://github.com/angular/angular/commit/7b67bad))
* **router:** add a banner file for the router ([#12919](https://github.com/angular/angular/issues/12919)) ([364642d](https://github.com/angular/angular/commit/364642d))
* **router:** removes a peer dependency from router to upgrade ([1dcf1f4](https://github.com/angular/angular/commit/1dcf1f4))
* **forms** allow for null values in HTML select options bound with ngValue ([e0ce545](https://github.com/angular/angular/commit/e0ce545)), closes [#10349](https://github.com/angular/angular/issues/10349)
* **router:** should not create a route state if navigation is canceled ([#12868](https://github.com/angular/angular/issues/12868)) ([dabaf85](https://github.com/angular/angular/commit/dabaf85)), closes [#12776](https://github.com/angular/angular/issues/12776)
* **common:** select should allow for null values in HTML select options bound with ngValue ([e02c180](https://github.com/angular/angular/commit/e02c180)), closes [#12829](https://github.com/angular/angular/issues/12829)
* **compiler-cli:** support ctorParams in function closure ([#12876](https://github.com/angular/angular/issues/12876)) ([6cdc3b5](https://github.com/angular/angular/commit/6cdc3b5))
<a name="2.2.0"></a>
# [2.2.0 upgrade-firebooster](https://github.com/angular/angular/compare/2.2.0-rc.0...2.2.0) (2016-11-14)
### Features (summary of all features from 2.2.0-beta.0 - 2.2.0-rc.0 releases)
* **common:** support narrow forms for month and weekdays in DatePipe ([#12297](https://github.com/angular/angular/issues/12297)) ([f77ab6a](https://github.com/angular/angular/commit/f77ab6a)), closes [#12294](https://github.com/angular/angular/issues/12294)
* **core:** map 'for' attribute to 'htmlFor' property ([#10546](https://github.com/angular/angular/issues/10546)) ([634b3bb](https://github.com/angular/angular/commit/634b3bb)), closes [#7516](https://github.com/angular/angular/issues/7516)
* **core:** add the find method to QueryList ([7c16ef9](https://github.com/angular/angular/commit/7c16ef9))
* **forms:** add hasError and getError to AbstractControlDirective ([#11985](https://github.com/angular/angular/issues/11985)) ([592f40a](https://github.com/angular/angular/commit/592f40a)), closes [#7255](https://github.com/angular/angular/issues/7255)
* **forms:** add ng-pending CSS class during async validation ([#11243](https://github.com/angular/angular/issues/11243)) ([97bc971](https://github.com/angular/angular/commit/97bc971)), closes [#10336](https://github.com/angular/angular/issues/10336)
* **forms:** add emitEvent to AbstractControl methods ([#11949](https://github.com/angular/angular/issues/11949)) ([b9fc090](https://github.com/angular/angular/commit/b9fc090))
* **forms:** make 'parent' a public property of 'AbstractControl' ([#11855](https://github.com/angular/angular/issues/11855)) ([445e592](https://github.com/angular/angular/commit/445e592))
* **forms:** Validator.pattern accepts a RegExp ([#12323](https://github.com/angular/angular/issues/12323)) ([bf60418](https://github.com/angular/angular/commit/bf60418))
* **router:** add a provider making angular1/angular2 integration easier ([#12769](https://github.com/angular/angular/issues/12769)) ([6e35d13](https://github.com/angular/angular/commit/6e35d13))
* **router:** add support for custom url matchers ([7340735](https://github.com/angular/angular/commit/7340735)), closes [#12442](https://github.com/angular/angular/issues/12442) [#12772](https://github.com/angular/angular/issues/12772)
* **router:** export routerLinkActive w/ isActive property ([c9f58cf](https://github.com/angular/angular/commit/c9f58cf))
* **router:** add support for ng1/ng2 migration ([#12160](https://github.com/angular/angular/issues/12160)) ([8b9ab44](https://github.com/angular/angular/commit/8b9ab44))
* **upgrade:** add support for AoT compiled upgrade applications ([d6791ff](https://github.com/angular/angular/commit/d6791ff)), closes [#12239](https://github.com/angular/angular/issues/12239)
* **upgrade:** add support for `require` in UpgradeComponent ([fe1d0e2](https://github.com/angular/angular/commit/fe1d0e2))
* **upgrade:** add/improve support for lifecycle hooks in UpgradeComponent ([469010e](https://github.com/angular/angular/commit/469010e))
### Performance Improvements
* **compiler:** introduce direct rendering ([9c23884](https://github.com/angular/angular/commit/9c23884))
* **core:** dont use `DomAdapter` nor zone for regular events ([648ce59](https://github.com/angular/angular/commit/648ce59))
* **core:** use `array.push` / `array.pop` instead of `splice` if possible ([0fc11a4](https://github.com/angular/angular/commit/0fc11a4))
* **platform-browser:** cache plugin resolution in the EventManager ([73593d4](https://github.com/angular/angular/commit/73593d4)), closes [#12824](https://github.com/angular/angular/issues/12824)
* **platform-browser:** dont use `DomAdapter` any more ([d708a88](https://github.com/angular/angular/commit/d708a88))
### Bug Fixes
* **animations:** allow animations to be destroyed manually ([#12719](https://github.com/angular/angular/issues/12719)) ([fe35bc3](https://github.com/angular/angular/commit/fe35bc3)), closes [#12456](https://github.com/angular/angular/issues/12456)
* **animations:** always normalize style properties and values during compilation ([#12755](https://github.com/angular/angular/issues/12755)) ([a0e9fde](https://github.com/angular/angular/commit/a0e9fde)), closes [#11582](https://github.com/angular/angular/issues/11582) [#12481](https://github.com/angular/angular/issues/12481)
* **animations:** always trigger animations after the change detection check ([#12713](https://github.com/angular/angular/issues/12713)) ([383f23b](https://github.com/angular/angular/commit/383f23b))
* **animations:** ensure animations work with web-workers ([#12656](https://github.com/angular/angular/issues/12656)) ([19e869e](https://github.com/angular/angular/commit/19e869e))
* **animations:** ensure web-animations are caught within the Angular zone ([f80a157](https://github.com/angular/angular/commit/f80a157)), closes [#11881](https://github.com/angular/angular/issues/11881) [#11712](https://github.com/angular/angular/issues/11712) [#12355](https://github.com/angular/angular/issues/12355) [#11881](https://github.com/angular/angular/issues/11881) [#12546](https://github.com/angular/angular/issues/12546) [#12707](https://github.com/angular/angular/issues/12707) [#12774](https://github.com/angular/angular/issues/12774)
* **common:** `NgSwitch` - dont create the default case if another case matches ([#12726](https://github.com/angular/angular/issues/12726)) ([d8f23f4](https://github.com/angular/angular/commit/d8f23f4)), closes [#11297](https://github.com/angular/angular/issues/11297) [#9420](https://github.com/angular/angular/issues/9420)
* **common:** I18nSelectPipe selects other case on default ([4708b24](https://github.com/angular/angular/commit/4708b24))
* **common:** no TZ Offset added by DatePipe for dates without time ([#12380](https://github.com/angular/angular/issues/12380)) ([2aba8b0](https://github.com/angular/angular/commit/2aba8b0))
* **common:** NgClass should throw a descriptive error when CSS class is not a string ([#12662](https://github.com/angular/angular/issues/12662)) ([f3793b5](https://github.com/angular/angular/commit/f3793b5)), closes [#12586](https://github.com/angular/angular/issues/12586)
* **common:** DatePipe should handle empty string ([#12374](https://github.com/angular/angular/issues/12374)) ([3dc6177](https://github.com/angular/angular/commit/3dc6177))
* **compiler:** don't convert undefined to null literals ([#11503](https://github.com/angular/angular/issues/11503)) ([f0cdb42](https://github.com/angular/angular/commit/f0cdb42)), closes [#11493](https://github.com/angular/angular/issues/11493)
* **compiler:** generate safe access strictNullChecks compatible code ([#12800](https://github.com/angular/angular/issues/12800)) ([a965d11](https://github.com/angular/angular/commit/a965d11)), closes [#12795](https://github.com/angular/angular/issues/12795)
* **compiler:** support more than 9 interpolations ([#12710](https://github.com/angular/angular/issues/12710)) ([22c021c](https://github.com/angular/angular/commit/22c021c)), closes [#10253](https://github.com/angular/angular/issues/10253)
* **compiler:** use the other case by default in ICU messages ([55dc0e4](https://github.com/angular/angular/commit/55dc0e4))
* **compiler-cli:** suppress closure compiler suspiciousCode check in codegen ([#12666](https://github.com/angular/angular/issues/12666)) ([7103754](https://github.com/angular/angular/commit/7103754))
* **compiler-cli:** suppress two more closure compiler checks in codegen ([#12698](https://github.com/angular/angular/issues/12698)) ([77cbf7f](https://github.com/angular/angular/commit/77cbf7f))
* **core:** allow to query content of templates that are stamped out at a different place ([f2bbef3](https://github.com/angular/angular/commit/f2bbef3)), closes [#12283](https://github.com/angular/angular/issues/12283) [#12094](https://github.com/angular/angular/issues/12094)
* **core:** apply host attributes to root elements ([#12761](https://github.com/angular/angular/issues/12761)) ([ad3bf6c](https://github.com/angular/angular/commit/ad3bf6c)), closes [#12744](https://github.com/angular/angular/issues/12744)
* **core:** ensure that component views that have no bindings recurse into nested components / view containers. ([051d748](https://github.com/angular/angular/commit/051d748))
* **core:** fix pseudo-selector shimming ([#12754](https://github.com/angular/angular/issues/12754)) ([acbf1d8](https://github.com/angular/angular/commit/acbf1d8)), closes [#12730](https://github.com/angular/angular/issues/12730) [#12354](https://github.com/angular/angular/issues/12354)
* **forms:** check if registerOnValidatorChange exists on validator before trying to invoke it ([#12801](https://github.com/angular/angular/issues/12801)) ([ef88147](https://github.com/angular/angular/commit/ef88147)), closes [#12593](https://github.com/angular/angular/issues/12593)
* **forms:** getRawValue returns any instead of Object ([#12599](https://github.com/angular/angular/issues/12599)) ([09092ac](https://github.com/angular/angular/commit/09092ac))
* **http:** preserve header case when copying headers ([#12697](https://github.com/angular/angular/issues/12697)) ([121e508](https://github.com/angular/angular/commit/121e508))
* **router:** advance a route only after its children have been deactivated ([#12676](https://github.com/angular/angular/issues/12676)) ([9ddf9b3](https://github.com/angular/angular/commit/9ddf9b3)), closes [#11715](https://github.com/angular/angular/issues/11715)
* **router:** avoid router initialization for non root components ([2a4bf9a](https://github.com/angular/angular/commit/2a4bf9a)), closes [#12338](https://github.com/angular/angular/issues/12338) [#12814](https://github.com/angular/angular/issues/12814)
* **router:** check if windows.console exists before using it ([#12348](https://github.com/angular/angular/issues/12348)) ([7886561](https://github.com/angular/angular/commit/7886561))
* **router:** correctly export concatMap operator in es5 ([#12430](https://github.com/angular/angular/issues/12430)) ([e25baa0](https://github.com/angular/angular/commit/e25baa0))
* **router:** do not require the creation of empty-path routes when no url left ([2c11093](https://github.com/angular/angular/commit/2c11093)), closes [#12133](https://github.com/angular/angular/issues/12133)
* **router:** ignore null or undefined query parameters ([#12333](https://github.com/angular/angular/issues/12333)) ([3052fb2](https://github.com/angular/angular/commit/3052fb2))
* **router:** incorrect injector is used when instantiating components loaded lazily ([#12817](https://github.com/angular/angular/issues/12817)) ([52be848](https://github.com/angular/angular/commit/52be848))
* **router:** resolve guard observables on the first emit ([#10412](https://github.com/angular/angular/issues/10412)) ([2e78b76](https://github.com/angular/angular/commit/2e78b76))
* **router:** Route.isActive also compares query params ([#12321](https://github.com/angular/angular/issues/12321)) ([785b7b6](https://github.com/angular/angular/commit/785b7b6))
* **router:** router should not swallow "unhandled" errors ([e5a753e](https://github.com/angular/angular/commit/e5a753e)), closes [#12802](https://github.com/angular/angular/issues/12802)
* **router:** throw an error when encounter undefined route ([#12389](https://github.com/angular/angular/issues/12389)) ([77dc1ab](https://github.com/angular/angular/commit/77dc1ab))
* **platform-browser:** enableDebugTools should create AngularTools by merging into context.ng ([#12003](https://github.com/angular/angular/issues/12003)) ([b2cf379](https://github.com/angular/angular/commit/b2cf379)), closes [#12002](https://github.com/angular/angular/issues/12002)
* **platform-browser:** provide the ability to register global hammer.js events ([768cddb](https://github.com/angular/angular/commit/768cddb)), closes [#12797](https://github.com/angular/angular/issues/12797)
* **tsc-wrapped:** harden collector against invalid asts ([#12793](https://github.com/angular/angular/issues/12793)) ([69f87ca](https://github.com/angular/angular/commit/69f87ca))
<a name="2.2.0-rc.0"></a>
# [2.2.0-rc.0](https://github.com/angular/angular/compare/2.2.0-beta.1...2.2.0-rc.0) (2016-11-02)
### Bug Fixes
* **compiler:** dedupe NgModule declarations, … ([a178bc6](https://github.com/angular/angular/commit/a178bc6))
* **compiler:** dont double bind functions ([e391cac](https://github.com/angular/angular/commit/e391cac))
* **compiler:** Dont throw on empty property bindings ([642c1db](https://github.com/angular/angular/commit/642c1db)), closes [#12583](https://github.com/angular/angular/issues/12583)
* **compiler:** support multiple components in a view container ([6fda972](https://github.com/angular/angular/commit/6fda972))
* **core:** improve error when multiple components match the same element ([e9fd864](https://github.com/angular/angular/commit/e9fd864)), closes [#7067](https://github.com/angular/angular/issues/7067)
* **router:** call data observers when the path changes ([1de04b2](https://github.com/angular/angular/commit/1de04b2))
* **router:** CanDeactivate receives a wrong component ([830a780](https://github.com/angular/angular/commit/830a780)), closes [#12592](https://github.com/angular/angular/issues/12592)
* **router:** rerun resolvers when url changes ([fe47e6b](https://github.com/angular/angular/commit/fe47e6b)), closes [#12603](https://github.com/angular/angular/issues/12603)
* **router:** reset URL to the stable state when a navigation gets canceled ([d509ee0](https://github.com/angular/angular/commit/d509ee0)), closes [#10321](https://github.com/angular/angular/issues/10321)
* **router:** routerLink should not prevent default on non-link elements ([8e221b8](https://github.com/angular/angular/commit/8e221b8))
* **router:** run navigations serially ([091c390](https://github.com/angular/angular/commit/091c390)), closes [#11754](https://github.com/angular/angular/issues/11754)
* **upgrade:** silent bootstrap failures ([fa93fd6](https://github.com/angular/angular/commit/fa93fd6)), closes [#12062](https://github.com/angular/angular/issues/12062)
### Features
* **core:** add the find method to QueryList ([7c16ef9](https://github.com/angular/angular/commit/7c16ef9))
<a name="2.1.2"></a>
# [2.1.2](https://github.com/angular/angular/compare/2.1.1...2.1.2) (2016-10-27)
### Bug Fixes
* **compiler:** don't access view local variables nor pipes in host expressions ([#12396](https://github.com/angular/angular/issues/12396)) ([867494a](https://github.com/angular/angular/commit/867494a)), closes [#12004](https://github.com/angular/angular/issues/12004) [#12071](https://github.com/angular/angular/issues/12071)
* **compiler:** walk third party modules ([#12453](https://github.com/angular/angular/issues/12453)) ([a838aba](https://github.com/angular/angular/commit/a838aba)), closes [#11889](https://github.com/angular/angular/issues/11889) [#12428](https://github.com/angular/angular/issues/12428)
* **compiler:** remove double exports of template_ast ([7742ec0](https://github.com/angular/angular/commit/7742ec0))
* **compiler:** use Maps instead of objects in selector implementation ([d321b0e](https://github.com/angular/angular/commit/d321b0e))
* **compiler-cli:** fix types ([ef15364](https://github.com/angular/angular/commit/ef15364))
* **compiler-cli:** assert that all pipes and directives are declared by a module ([7221632](https://github.com/angular/angular/commit/7221632))
* **http:** overwrite already set xsrf header ([b4265e0](https://github.com/angular/angular/commit/b4265e0))
* **router:** add a test to make sure canDeactivate guards are called for aux routes ([fc60fa7](https://github.com/angular/angular/commit/fc60fa7)), closes [#11345](https://github.com/angular/angular/issues/11345)
* **router:** canDeactivate guards are not triggered for componentless routes ([b741853](https://github.com/angular/angular/commit/b741853)), closes [#12375](https://github.com/angular/angular/issues/12375)
* **router:** change router not to deactivate aux routes when navigating from a componentless routes ([52a853e](https://github.com/angular/angular/commit/52a853e))
* **router:** disallow component routes with named outlets ([8f2fa0f](https://github.com/angular/angular/commit/8f2fa0f)), closes [#11208](https://github.com/angular/angular/issues/11208) [#11082](https://github.com/angular/angular/issues/11082)
* **router:** preserve resolve data ([6ccbfd4](https://github.com/angular/angular/commit/6ccbfd4)), closes [#12306](https://github.com/angular/angular/issues/12306)
<a name="2.2.0-beta.1"></a>
# [2.2.0-beta.1](https://github.com/angular/angular/compare/2.2.0-beta.0...2.2.0-beta.1) (2016-10-27)
### Code Refactoring
* **upgrade:** re-export the new static upgrade APIs on new entry ([a26dd28](https://github.com/angular/angular/commit/a26dd28))
### Features
* **router:** export routerLinkActive w/ isActive property ([c9f58cf](https://github.com/angular/angular/commit/c9f58cf))
### BREAKING CHANGES (only for beta version users)
* upgrade: Four newly added APIs in 2.2.0-beta:
downgradeComponent, downgradeInjectable, UpgradeComponent, and UpgradeModule are no longer exported by @angular/upgrade.
Import these from @angular/upgrade/static instead.
Note: The 2.2.0-beta.1 release also contains all the changes present in the 2.1.2 release.
# [2.1.1](https://github.com/angular/angular/compare/2.1.0...2.1.1) (2016-10-20)
### Bug Fixes
* **compiler:** generate aot code for animation trigger output events ([#12291](https://github.com/angular/angular/issues/12291)) ([6e5f8b5](https://github.com/angular/angular/commit/6e5f8b5)), closes [#11707](https://github.com/angular/angular/issues/11707)
* **compiler:** don't redeclare a var in the same scope ([#12386](https://github.com/angular/angular/issues/12386)) ([cca4a5c](https://github.com/angular/angular/commit/cca4a5c))
* **core:** fix decorator default values ([bd1dcb5](https://github.com/angular/angular/commit/bd1dcb5))
* **core:** fix property decorators ([3993279](https://github.com/angular/angular/commit/3993279)), closes [#12224](https://github.com/angular/angular/issues/12224)
* **http:** make normalizeMethodName optimizer-compatible. ([#12370](https://github.com/angular/angular/issues/12370)) ([8409b65](https://github.com/angular/angular/commit/8409b65))
* **router:** correctly export filter operator in es5 ([#12286](https://github.com/angular/angular/issues/12286)) ([27d7677](https://github.com/angular/angular/commit/27d7677))
* **router:** do not update primary route if only secondary outlet is given ([#11797](https://github.com/angular/angular/issues/11797)) ([da5fc69](https://github.com/angular/angular/commit/da5fc69))
* **router:** fix lazy loading triggered by redirects from wildcard routes ([5ae6915](https://github.com/angular/angular/commit/5ae6915)), closes [#12183](https://github.com/angular/angular/issues/12183)
* **router:** module loader should start compiling modules when stubbedModules are set ([#11742](https://github.com/angular/angular/issues/11742)) ([b44b6ef](https://github.com/angular/angular/commit/b44b6ef))
### Performance Improvements
* **common:** optimize NgSwitch default case ([fdf4309](https://github.com/angular/angular/commit/fdf4309))
<a name="2.2.0-beta.0"></a>
# [2.2.0-beta.0](https://github.com/angular/angular/compare/2.1.0...2.2.0-beta.0) (2016-10-20)
### Features
* **common:** support narrow forms for month and weekdays in DatePipe ([#12297](https://github.com/angular/angular/issues/12297)) ([f77ab6a](https://github.com/angular/angular/commit/f77ab6a)), closes [#12294](https://github.com/angular/angular/issues/12294)
* **forms:** add hasError and getError to AbstractControlDirective ([#11985](https://github.com/angular/angular/issues/11985)) ([592f40a](https://github.com/angular/angular/commit/592f40a)), closes [#7255](https://github.com/angular/angular/issues/7255)
* **forms:** add ng-pending CSS class during async validation ([#11243](https://github.com/angular/angular/issues/11243)) ([97bc971](https://github.com/angular/angular/commit/97bc971)), closes [#10336](https://github.com/angular/angular/issues/10336)
* **forms:** Added emitEvent to AbstractControl methods ([#11949](https://github.com/angular/angular/issues/11949)) ([b9fc090](https://github.com/angular/angular/commit/b9fc090))
* **forms:** make 'parent' a public property of 'AbstractControl' ([#11855](https://github.com/angular/angular/issues/11855)) ([445e592](https://github.com/angular/angular/commit/445e592))
* **forms:** Validator.pattern accepts a RegExp ([#12323](https://github.com/angular/angular/issues/12323)) ([bf60418](https://github.com/angular/angular/commit/bf60418))
* **upgrade:** add support for AoT compiled upgrade applications ([d6791ff](https://github.com/angular/angular/commit/d6791ff)), closes [#12239](https://github.com/angular/angular/issues/12239)
* **router:** add support for ng1/ng2 migration ([#12160](https://github.com/angular/angular/issues/12160)) ([8b9ab44](https://github.com/angular/angular/commit/8b9ab44))
Note: The 2.2.0-beta.0 release also contains all the changes present in the 2.1.1 release.
<a name="2.1.0"></a>
# [2.1.0 incremental-metamorphosis](https://github.com/angular/angular/compare/2.1.0-rc.0...2.1.0) (2016-10-12)
### Bug Fixes
* **compiler:** allow whitespace as `<ng-content>` content ([#12225](https://github.com/angular/angular/issues/12225)) ([df1718d](https://github.com/angular/angular/commit/df1718d))
* **compiler:** interpolation expressions report the correct offset ([#12125](https://github.com/angular/angular/issues/12125)) ([d641c36](https://github.com/angular/angular/commit/d641c36))
* **compiler:** properly shim `:host:before` and `:host(:before)` ([#12171](https://github.com/angular/angular/issues/12171)) ([aa92512](https://github.com/angular/angular/commit/aa92512)), closes [#12165](https://github.com/angular/angular/issues/12165)
* **compiler:** validate `@HostBinding` name ([#12139](https://github.com/angular/angular/issues/12139)) ([13ecc14](https://github.com/angular/angular/commit/13ecc14))
* **compiler-cli:** don't clone static symbols when simplifying annotation metadata ([#12158](https://github.com/angular/angular/issues/12158)) ([8c477b2](https://github.com/angular/angular/commit/8c477b2))
* **compiler-cli:** remove peerDependency on [@angular](https://github.com/angular)/platform-server ([#12122](https://github.com/angular/angular/issues/12122)) ([71b7654](https://github.com/angular/angular/commit/71b7654))
* **compiler-cli:** remove unused parse5 dependency from package.json ([eaaec69](https://github.com/angular/angular/commit/eaaec69))
* **forms:** allow optional fields with pattern and minlength validators ([#12147](https://github.com/angular/angular/issues/12147)) ([d22eeb7](https://github.com/angular/angular/commit/d22eeb7))
* **forms:** properly validate blank strings with minlength ([#12091](https://github.com/angular/angular/issues/12091)) ([f50c1da](https://github.com/angular/angular/commit/f50c1da))
* **http:** fix Headers initialization from Headers and Object ([#12106](https://github.com/angular/angular/issues/12106)) ([f4566f8](https://github.com/angular/angular/commit/f4566f8))
* **http:** Headers.append should append to the list ([a67c067](https://github.com/angular/angular/commit/a67c067))
* **platform-browser-dynamic:** mark platformBrowserDynamic as stable API ([#12154](https://github.com/angular/angular/issues/12154)) ([bcef5ef](https://github.com/angular/angular/commit/bcef5ef))
* **router:** improve error message ([#12102](https://github.com/angular/angular/issues/12102)) ([e06303a](https://github.com/angular/angular/commit/e06303a))
* **router:** parent resolve should complete before merging resolved data ([1681e4f](https://github.com/angular/angular/commit/1681e4f)), closes [#12032](https://github.com/angular/angular/issues/12032)
* **router:** wildcards routes should support lazy loading ([40b92dd](https://github.com/angular/angular/commit/40b92dd)), closes [#12024](https://github.com/angular/angular/issues/12024)
* **upgrade:** allow compilerOptions in bootstrap ([#10575](https://github.com/angular/angular/issues/10575)) ([5effc33](https://github.com/angular/angular/commit/5effc33))
<a name="2.1.0-rc.0"></a>
# [2.1.0-rc.0](https://github.com/angular/angular/compare/2.1.0-beta.0...2.1.0-rc.0) (2016-10-05)
### Features
* **animations:** provide aliases for `:enter` and `:leave` transitions ([#11991](https://github.com/angular/angular/issues/11991)) ([e884f48](https://github.com/angular/angular/commit/e884f48))
Note: 2.1.0-rc.0 release also contains all the changes present in the 2.0.2 release.
<a name="2.1.0-beta.0"></a>
# [2.1.0-beta.0](https://github.com/angular/angular/compare/2.0.0...2.1.0-beta.0) (2016-09-23)
### Features
* **router:** add router preloader to optimistically preload routes ([5a84982](https://github.com/angular/angular/commit/5a84982))
### Bug Fixes
* **router:** update the router not to reset router state when updating root component ([#11799](https://github.com/angular/angular/issues/11799)) ([31dce72](https://github.com/angular/angular/commit/31dce72))
Note: 2.1.0-beta.0 release also contains all the changes present in the 2.0.1 release.
<a name="2.0.2"></a>
## [2.0.2](https://github.com/angular/angular/compare/2.0.1...2.0.2) (2016-10-05)
### Bug Fixes
* **common:** correctly removes styles on IE ([#11953](https://github.com/angular/angular/pull/11953)), closes [#7916](https://github.com/angular/angular/issues/7916)
* **compiler:** do not embed templateUrl in view factories in non-debug mode. ([#11818](https://github.com/angular/angular/issues/11818)) ([51e1994](https://github.com/angular/angular/commit/51e1994)), closes [#11117](https://github.com/angular/angular/issues/11117)
* **compiler:** move detection of unsafe properties for binding to ElementSchemaRegistry ([#11378](https://github.com/angular/angular/issues/11378)) ([5911c3b](https://github.com/angular/angular/commit/5911c3b))
* **compiler:** fix `:host(tag)` and `:host-context(tag)` ([a6bb84e0](https://github.com/angular/angular/commit/a6bb84e02b7579f8d957ef6ba5b10d83482ed756)), closes [#11972](https://github.com/angular/angular/issues/11972)
* **compiler:** fix attribute selectors in :host and :host-context ([#12056](https://github.com/angular/angular/issues/12056)) ([6f7ed32](https://github.com/angular/angular/commit/6f7ed32)), closes [#11917](https://github.com/angular/angular/issues/11917)
* **compiler:** support `@page` and `@document` CSS rules ([#11878](https://github.com/angular/angular/issues/11878)) ([c99ef49](https://github.com/angular/angular/commit/c99ef49)), closes [#11860](https://github.com/angular/angular/issues/11860)
* **compiler:** support `[attr="value with space"]` ([bd012ef](https://github.com/angular/angular/commit/bd012ef)), closes [#6249](https://github.com/angular/angular/issues/6249)
* **compiler:** support quoted attribute values ([7395400](https://github.com/angular/angular/commit/7395400)), closes [#6085](https://github.com/angular/angular/issues/6085)
* **compiler:** fix `<x>` ctype names ([7578d85](https://github.com/angular/angular/commit/7578d85)), closes [#12000](https://github.com/angular/angular/issues/12000)
* **compiler-cli:** allow ReflectorHost passed as argument to CodeGenerator#create ([#11951](https://github.com/angular/angular/issues/11951)) ([826c98e](https://github.com/angular/angular/commit/826c98e))
* **forms:** properly validate empty strings with patterns ([#11450](https://github.com/angular/angular/issues/11450)) ([e00de0c](https://github.com/angular/angular/commit/e00de0c))
* **http:** preserve case of the first init, `set()` or `append()` ([#12023](https://github.com/angular/angular/issues/12023)) ([adb17fe](https://github.com/angular/angular/commit/adb17fe)), closes [#11624](https://github.com/angular/angular/issues/11624)
* **http:** remove url params if provided value is null or undefined ([#11990](https://github.com/angular/angular/issues/11990)) ([9cc0a4e](https://github.com/angular/angular/commit/9cc0a4e))
* **router:** do not reset the router state when updating the component ([#11867](https://github.com/angular/angular/issues/11867)) ([cf750e1](https://github.com/angular/angular/commit/cf750e1))
* **upgrade:** bind optional properties when upgrading from ng1 ([#11411](https://github.com/angular/angular/issues/11411)) ([0851238](https://github.com/angular/angular/commit/0851238)), closes [#10181](https://github.com/angular/angular/issues/10181)
<a name="2.0.1"></a>
## [2.0.1](https://github.com/angular/angular/compare/2.0.0...2.0.1) (2016-09-23)
### Bug Fixes
* **common:** fix ngOnChanges signature of NgTemplateOutlet directive ([14ee759](https://github.com/angular/angular/commit/14ee759))
* **compiler:** `[attribute~=value]` selector ([#11696](https://github.com/angular/angular/issues/11696)) ([734b8b8](https://github.com/angular/angular/commit/734b8b8)), closes [#9644](https://github.com/angular/angular/issues/9644)
* **compiler:** safe property access expressions work in event bindings ([#11724](https://github.com/angular/angular/issues/11724)) ([a95d652](https://github.com/angular/angular/commit/a95d652))
* **compiler:** throw when Component.moduleId is not a string ([bd4045b](https://github.com/angular/angular/commit/bd4045b)), closes [#11590](https://github.com/angular/angular/issues/11590)
* **compiler:** do not provide I18N values when they're not specified ([03aedbe](https://github.com/angular/angular/commit/03aedbe)), closes [#11643](https://github.com/angular/angular/issues/11643)
* **core:** ContentChild descendants should be queried by default ([0dc15eb](https://github.com/angular/angular/commit/0dc15eb)), closes [#11645](https://github.com/angular/angular/issues/11645)
* **forms:** disable all radios with disable() ([2860418](https://github.com/angular/angular/commit/2860418))
* **forms:** make setDisabledState optional for reactive form directives ([#11731](https://github.com/angular/angular/issues/11731)) ([51d73d3](https://github.com/angular/angular/commit/51d73d3)), closes [#11719](https://github.com/angular/angular/issues/11719)
* **forms:** support unbound disabled in ngModel ([#11736](https://github.com/angular/angular/issues/11736)) ([39e251e](https://github.com/angular/angular/commit/39e251e))
* **upgrade:** allow attribute selectors for components in ng2 which are not part of upgrade ([#11808](https://github.com/angular/angular/issues/11808)) ([b81e2e7](https://github.com/angular/angular/commit/b81e2e7)), closes [#11280](https://github.com/angular/angular/issues/11280)
<a name="2.0.0"></a> <a name="2.0.0"></a>
# [2.0.0](https://github.com/angular/angular/compare/2.0.0-rc.7...2.0.0) (2016-09-14) # [2.0.0 proprioception-reinforcement](https://github.com/angular/angular/compare/2.0.0-rc.7...2.0.0) (2016-09-14)
### Bug Fixes ### Bug Fixes
@ -212,7 +808,7 @@
use `Type<any>` in place of `Type`. use `Type<any>` in place of `Type`.
We don't expect that any user applications use the `Type` type directly. We don't expect that any user applications use the `Type` type directly.
* core: Previously inconsistently named APIs SanitizationService and DomSanitizationService were renamed to Sanitizer and DomSanitizer * core: Previously inconsistently named APIs SanitizationService and DomSanitizationService were renamed to Sanitizer and DomSanitizer
* core: previously deprecated @Component.directives and @Component.pipes support was removed. * core: previously deprecated @Component.directives and @Component.pipes support was removed.
@ -226,11 +822,11 @@ use `Type<any>` in place of `Type`.
* core: deprecated ComponentResolver was removed. Please use ComponentFactoryResolver instead. * core: deprecated ComponentResolver was removed. Please use ComponentFactoryResolver instead.
* core: animations defined using an at-symbol prefix that are not property bound are now invalid. * core: animations defined using an at-symbol prefix that are not property bound are now invalid.
```html ```html
<!-- this is now invalid --> <!-- this is now invalid -->
<div @flip="flipState"></div> <div @flip="flipState"></div>
<!-- change that to --> <!-- change that to -->
<div [@flip]="flipState"></div> <div [@flip]="flipState"></div>
``` ```
@ -256,7 +852,7 @@ prefix using `animate-` must now be preixed using `bind-animate-`.
``` ```
{provide: MyClass, useFactory: ...} {provide: MyClass, useFactory: ...}
``` ```
* core: previously deprecated NgZoneError has been removed * core: previously deprecated NgZoneError has been removed
* core: Exceptions are no longer part of the public API. We don't expect that anyone should be referring to the Exception types. * core: Exceptions are no longer part of the public API. We don't expect that anyone should be referring to the Exception types.
@ -268,7 +864,7 @@ prefix using `animate-` must now be preixed using `bind-animate-`.
``` ```
ErrorHandler.handleError(error: any): void; ErrorHandler.handleError(error: any): void;
``` ```
* core: deprecated DynamicComponentLoader was removed; see deprecation notice for migration instructions. * core: deprecated DynamicComponentLoader was removed; see deprecation notice for migration instructions.
* core: deprecated SystemJsComponentResolver and SystemJsCmpFactoryResolver have been removed. * core: deprecated SystemJsComponentResolver and SystemJsCmpFactoryResolver have been removed.
@ -302,13 +898,13 @@ prefix using `animate-` must now be preixed using `bind-animate-`.
* platform-browser-dynamic: `CACHED_TEMPLATE_PROVIDER` is now renamed to `RESOURCE_CACHE_PROVIDER` * platform-browser-dynamic: `CACHED_TEMPLATE_PROVIDER` is now renamed to `RESOURCE_CACHE_PROVIDER`
Before: Before:
```js ```js
import {CACHED_TEMPLATE_PROVIDER} from '@angular/platform-browser-dynamic'; import {CACHED_TEMPLATE_PROVIDER} from '@angular/platform-browser-dynamic';
``` ```
After: After:
```js ```js
import {RESOURCE_CACHE_PROVIDER} from '@angular/platform-browser-dynamic'; import {RESOURCE_CACHE_PROVIDER} from '@angular/platform-browser-dynamic';
``` ```
@ -326,7 +922,7 @@ prefix using `animate-` must now be preixed using `bind-animate-`.
* webworkers: web worker platform is now exported via separate packages. * webworkers: web worker platform is now exported via separate packages.
Please use @angular/platform-webworker and @angular/platform-webworker-dynamic Please use @angular/platform-webworker and @angular/platform-webworker-dynamic
<a name="2.0.0-rc.5"></a> <a name="2.0.0-rc.5"></a>
@ -520,7 +1116,7 @@ prefix using `animate-` must now be preixed using `bind-animate-`.
* core: * core:
- `ApplicationRef.dispose` is deprecated. Destroy the module that was - `ApplicationRef.dispose` is deprecated. Destroy the module that was
created during bootstrap instead by calling `NgModuleRef.destroy`. created during bootstrap instead by calling `NgModuleRef.destroy`.
- `AplicationRef.registerDisposeListener` is deprecated. - `ApplicationRef.registerDisposeListener` is deprecated.
Use the `ngOnDestroy` lifecycle hook for providers or Use the `ngOnDestroy` lifecycle hook for providers or
`NgModuleRef.onDestroy` instead. `NgModuleRef.onDestroy` instead.
- `disposePlatform` is deprecated. Use `destroyPlatform` instead. - `disposePlatform` is deprecated. Use `destroyPlatform` instead.

View File

@ -1,6 +1,6 @@
# Contributing to Angular 2 # Contributing to Angular
We would love for you to contribute to Angular 2 and help make it even better than it is We would love for you to contribute to Angular and help make it even better than it is
today! As a contributor, here are the guidelines we would like you to follow: today! As a contributor, here are the guidelines we would like you to follow:
- [Code of Conduct](#coc) - [Code of Conduct](#coc)
@ -17,19 +17,27 @@ Help us keep Angular open and inclusive. Please read and follow our [Code of Con
## <a name="question"></a> Got a Question or Problem? ## <a name="question"></a> Got a Question or Problem?
If you have questions about how to *use* Angular, please direct them to the [Google Group][angular-group] Please, do not open issues for the general support questions as we want to keep GitHub issues for bug reports and feature requests. You've got much better chances of getting your question answered on [StackOverflow](https://stackoverflow.com/questions/tagged/angular) where the questions should be tagged with tag `angular`.
discussion list or [StackOverflow][stackoverflow]. Please note that Angular 2 is still in early developer preview, and the core team's capacity to answer usage questions is limited. We are also available on [Gitter][gitter].
## <a name="issue"></a> Found an Issue? StackOverflow is a much better place to ask questions since:
- there are thousands of people willing to help on StackOverflow
- questions and answers stay available for public viewing so your question / answer might help someone else
- StackOverflow's voting system assures that the best answers are prominently visible.
To save your and our time we will be systematically closing all the issues that are requests for general support and redirecting people to StackOverflow.
If you would like to chat about the question in real-time, you can reach out via [our gitter channel][gitter].
## <a name="issue"></a> Found a Bug?
If you find a bug in the source code, you can help us by If you find a bug in the source code, you can help us by
[submitting an issue](#submit-issue) to our [GitHub Repository][github]. Even better, you can [submitting an issue](#submit-issue) to our [GitHub Repository][github]. Even better, you can
[submit a Pull Request](#submit-pr) with a fix. [submit a Pull Request](#submit-pr) with a fix.
## <a name="feature"></a> Want a Feature? ## <a name="feature"></a> Missing a Feature?
You can *request* a new feature by [submitting an issue](#submit-issue) to our [GitHub You can *request* a new feature by [submitting an issue](#submit-issue) to our GitHub
Repository][github]. If you would like to *implement* a new feature, please submit an issue with Repository. If you would like to *implement* a new feature, please submit an issue with
a proposal for your work first, to be sure that we can use it. Angular 2 is in developer preview a proposal for your work first, to be sure that we can use it.
and we are not ready to accept major contributions ahead of the full release.
Please consider what kind of change it is: Please consider what kind of change it is:
* For a **Major Feature**, first open an issue and outline your proposal so that it can be * For a **Major Feature**, first open an issue and outline your proposal so that it can be
@ -40,24 +48,22 @@ and help you to craft the change so that it is successfully accepted into the pr
## <a name="submit"></a> Submission Guidelines ## <a name="submit"></a> Submission Guidelines
### <a name="submit-issue"></a> Submitting an Issue ### <a name="submit-issue"></a> Submitting an Issue
Before you submit an issue, search the archive, maybe your question was already answered.
If your issue appears to be a bug, and hasn't been reported, open a new issue. Before you submit an issue, please search the issue tracker, maybe an issue for your problem already exists and the discussion might inform you of workarounds readily available.
Help us to maximize the effort we can spend fixing issues and adding new
features, by not reporting duplicate issues. Providing the following information will increase the
chances of your issue being dealt with quickly:
* **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps We want to fix all the issues as soon as possible, but before fixing a bug we need to reproduce and confirm it. In order to reproduce bugs we will systematically ask you to provide a minimal reproduction scenario using http://plnkr.co. Having a live, reproducible scenario gives us wealth of important information without going back & forth to you with additional questions like:
* **Angular Version** - what version of Angular is affected (e.g. 2.0.0-alpha.53)
* **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you
* **Browsers and Operating System** - is this a problem with all browsers?
* **Reproduce the Error** - provide a live example (using [Plunker][plunker],
[JSFiddle][jsfiddle] or [Runnable][runnable]) or a unambiguous set of steps
* **Related Issues** - has a similar issue been reported before?
* **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be
causing the problem (line of code or commit)
You can file new issues by providing the above information [here](https://github.com/angular/angular/issues/new). - version of Angular used
- 3rd-party libraries and their versions
- and most importantly - a use-case that fails
A minimal reproduce scenario using http://plnkr.co/ allows us to quickly confirm a bug (or point out coding problem) as well as confirm that we are fixing the right problem. If plunker is not a suitable way to demonstrate the problem (for example for issues related to our npm packaging), please create a standalone git repository demonstrating the problem.
We will be insisting on a minimal reproduce scenario in order to save maintainers time and ultimately be able to fix more bugs. Interestingly, from our experience users often find coding problems themselves while preparing a minimal plunk. We understand that sometimes it might be hard to extract essentials bits of code from a larger code-base but we really need to isolate the problem before we can fix it.
Unfortunately we are not able to investigate / fix bugs without a minimal reproduction, so if we don't hear back from you we are going to close an issue that don't have enough info to be reproduced.
You can file new issues by filling out our [new issue form](https://github.com/angular/angular/issues/new).
### <a name="submit-pr"></a> Submitting a Pull Request (PR) ### <a name="submit-pr"></a> Submitting a Pull Request (PR)
@ -95,7 +101,7 @@ Before you submit your Pull Request (PR) consider the following guidelines:
* In GitHub, send a pull request to `angular:master`. * In GitHub, send a pull request to `angular:master`.
* If we suggest changes then: * If we suggest changes then:
* Make the required updates. * Make the required updates.
* Re-run the Angular 2 test suites to ensure tests are still passing. * Re-run the Angular test suites to ensure tests are still passing.
* Rebase your branch and force push to your GitHub repository (this will update your Pull Request): * Rebase your branch and force push to your GitHub repository (this will update your Pull Request):
```shell ```shell
@ -238,7 +244,7 @@ changes to be accepted, the CLA must be signed. It's a quick process, we promise
[github]: https://github.com/angular/angular [github]: https://github.com/angular/angular
[gitter]: https://gitter.im/angular/angular [gitter]: https://gitter.im/angular/angular
[individual-cla]: http://code.google.com/legal/individual-cla-v1.0.html [individual-cla]: http://code.google.com/legal/individual-cla-v1.0.html
[js-style-guide]: https://google.github.io/styleguide/javascriptguide.xml [js-style-guide]: https://google.github.io/styleguide/jsguide.html
[jsfiddle]: http://jsfiddle.net [jsfiddle]: http://jsfiddle.net
[plunker]: http://plnkr.co/edit [plunker]: http://plnkr.co/edit
[runnable]: http://runnable.com [runnable]: http://runnable.com

View File

@ -1,6 +1,6 @@
# Building and Testing Angular 2 for JS # Building and Testing Angular
This document describes how to set up your development environment to build and test Angular 2 JS version. This document describes how to set up your development environment to build and test Angular.
It also explains the basic mechanics of using `git`, `node`, and `npm`. It also explains the basic mechanics of using `git`, `node`, and `npm`.
* [Prerequisite Software](#prerequisite-software) * [Prerequisite Software](#prerequisite-software)
@ -74,6 +74,15 @@ use in these instructions.
*Option 2*: defining a bash alias like `alias nbin='PATH=$(npm bin):$PATH'` as detailed in this *Option 2*: defining a bash alias like `alias nbin='PATH=$(npm bin):$PATH'` as detailed in this
[Stackoverflow answer](http://stackoverflow.com/questions/9679932/how-to-use-package-installed-locally-in-node-modules/15157360#15157360) and used like this: e.g., `nbin gulp build`. [Stackoverflow answer](http://stackoverflow.com/questions/9679932/how-to-use-package-installed-locally-in-node-modules/15157360#15157360) and used like this: e.g., `nbin gulp build`.
## Installing Bower Modules
Now run `bower` to install additional dependencies:
```shell
# Install other Angular project dependencies (bower.json)
bower install
```
## Windows only ## Windows only
In order to create the right symlinks, run **as administrator**: In order to create the right symlinks, run **as administrator**:
@ -114,7 +123,7 @@ You should execute the 3 test suites before submitting a PR to github.
All the tests are executed on our Continuous Integration infrastructure and a PR could only be merged once the tests pass. All the tests are executed on our Continuous Integration infrastructure and a PR could only be merged once the tests pass.
- CircleCI fails if your code is not formatted properly, - CircleCI fails if your code is not formatted properly,
- Travis CI fails if any of the test suite describe above fails. - Travis CI fails if any of the test suites described above fails.
## Update the public API tests ## Update the public API tests
@ -124,9 +133,10 @@ If you happen to modify the public API of Angular, API golden files must be upda
$ gulp public-api:update $ gulp public-api:update
``` ```
Note: The command `./test.sh tools` fails when the API doesn't match the golden files. Note: The command `gulp public-api:enforce` fails when the API doesn't match the golden files. Make sure to rebuild
the project before trying to verify after an API change.
## Formatting your source code ## <a name="clang-format"></a> Formatting your source code
Angular uses [clang-format](http://clang.llvm.org/docs/ClangFormat.html) to format the source code. If the source code Angular uses [clang-format](http://clang.llvm.org/docs/ClangFormat.html) to format the source code. If the source code
is not properly formatted, the CI will fail and the PR can not be merged. is not properly formatted, the CI will fail and the PR can not be merged.
@ -137,4 +147,32 @@ You can automatically format your code by running:
$ gulp format $ gulp format
``` ```
## Linting/verifying your source code
You can check that your code is properly formatted and adheres to coding style by running:
``` shell
$ gulp lint
```
## Publishing your own personal snapshot build
You may find that your un-merged change needs some validation from external participants.
Rather than requiring them to pull your Pull Request and build Angular locally, you can
publish the `*-builds` snapshots just like our Travis build does.
First time, you need to create the github repositories:
``` shell
$ export TOKEN=[get one from https://github.com/settings/tokens]
$ CREATE_REPOS=1 ./scripts/publish/publish-build-artifacts.sh [github username]
```
For subsequent snapshots, just run
``` shell
$ ./scripts/publish/publish-build-artifacts.sh [github username]
```
The script will publish the build snapshot to a branch with the same name as your current branch,
and create it if it doesn't exist.

View File

@ -4,7 +4,6 @@
[![Issue Stats](http://issuestats.com/github/angular/angular/badge/pr?style=flat)](http://issuestats.com/github/angular/angular) [![Issue Stats](http://issuestats.com/github/angular/angular/badge/pr?style=flat)](http://issuestats.com/github/angular/angular)
[![Issue Stats](http://issuestats.com/github/angular/angular/badge/issue?style=flat)](http://issuestats.com/github/angular/angular) [![Issue Stats](http://issuestats.com/github/angular/angular/badge/issue?style=flat)](http://issuestats.com/github/angular/angular)
[![npm version](https://badge.fury.io/js/%40angular%2Fcore.svg)](https://badge.fury.io/js/%40angular%2Fcore) [![npm version](https://badge.fury.io/js/%40angular%2Fcore.svg)](https://badge.fury.io/js/%40angular%2Fcore)
[![Downloads](http://img.shields.io/npm/dm/angular2.svg)](https://npmjs.org/package/angular2)
[![Sauce Test Status](https://saucelabs.com/browser-matrix/angular2-ci.svg)](https://saucelabs.com/u/angular2-ci) [![Sauce Test Status](https://saucelabs.com/browser-matrix/angular2-ci.svg)](https://saucelabs.com/u/angular2-ci)
*Safari (7+), iOS (7+), Edge (14) and IE mobile (11) are tested on [BrowserStack][browserstack].* *Safari (7+), iOS (7+), Edge (14) and IE mobile (11) are tested on [BrowserStack][browserstack].*

62
SAVED_REPLIES.md Normal file
View File

@ -0,0 +1,62 @@
# Saved Responses for Angular's Issue Tracker
The following are canned responses that the Angular team should use to close issues on our issue tracker that fall into the listed resolution categories.
Since GitHub currently doesn't allow us to have a repository-wide or organization-wide list of [saved replies](https://help.github.com/articles/working-with-saved-replies/), these replies need to be maintained by individual team members. Since the responses can be modified in the future, all responses are versioned to simplify the process of keeping the responses up to date.
## Angular: Already Fixed (v1)
```
Thanks for reporting this issue. Luckily it has already been fixed in one of the recent releases. Please update to the most recent version to resolve the problem.
If after upgrade the problem still exists in your application please open a new issue and provide a plunker reproducing the problem and describing the difference between the expected and current behavior. You can use this plunker template: http://plnkr.co/edit/tpl:AvJOMERrnz94ekVua0u5?p=catalogue
```
## Angular: Don't Understand (v1)
```
I'm sorry but we don't understand the problem you are reporting.
If the problem still exists please open a new issue and provide a plunker reproducing the problem and describing the difference between the expected and current behavior. You can use this plunker template: http://plnkr.co/edit/tpl:AvJOMERrnz94ekVua0u5?p=catalogue
```
## Angular: Duplicate (v1)
```
Thanks for reporting this issue. However this issue is a duplicate of an existing issue #<ISSUE_NUMBER>. Please subscribe to that issue for future updates.
```
## Angular: Insufficient Information Provided (v1)
```
Thanks for reporting this issue. However, you didn't provide sufficient information for us to understand and reproduce the problem. Please check out [our submission guidelines](https://github.com/angular/angular/blob/master/CONTRIBUTING.md#-submitting-an-issue) to understand why we can't act on issues that are lacking important information.
If the problem still persists, please file a new issue and ensure you provide all of the required information when filling out the issue template.
```
## Angular: Issue Outside of Angular (v1)
```
I'm sorry but this issue is not caused by Angular. Please contact the author(s) of project <PROJECT NAME> or file issue on their issue tracker.
```
## Angular: Non-reproducible (v1)
```
I'm sorry but we can't reproduce the problem following the instructions you provided.
If the problem still exists please open a new issue following [our submission guidelines](https://github.com/angular/angular/blob/master/CONTRIBUTING.md#-submitting-an-issue).
```
## Angular: Obsolete (v1)
```
Thanks for reporting this issue. This issue is now obsolete due to changes in the recent releases. Please update to the most recent Angular version.
If the problem still persists, please file a new issue and ensure you provide the version of Angular affected and include the steps to reproduce the problem when filling out the issue template.
```
## Angular: Support Request (v1)
```
Hello, we reviewed this issue and determined that it doesn't fall into the bug report or feature request category. This issue tracker is not suitable for support requests, please repost your issue on [StackOverflow](http://stackoverflow.com/) using tag `angular`.
If you are wondering why we don't resolve support issues via the issue tracker, please [check out this explanation](https://github.com/angular/angular/blob/master/CONTRIBUTING.md#-got-a-question-or-problem).
```

View File

@ -1,7 +1,7 @@
# Triage Process and Github Labels for Angular 2 # Triage Process and Github Labels for Angular 2
This document describes how the Angular team uses labels and milestones This document describes how the Angular team uses labels and milestones
to triage issues on github. The basic idea of the new process is that to triage issues on github. The basic idea of the process is that
caretaker only assigns a component and type (bug, feature) label. The caretaker only assigns a component and type (bug, feature) label. The
owner of the component than is in full control of how the issues should owner of the component than is in full control of how the issues should
be triaged further. be triaged further.
@ -17,26 +17,27 @@ with it.
* `comp: animations`: `@matsko` * `comp: animations`: `@matsko`
* `comp: benchpress`: `@tbosch` * `comp: benchpress`: `@tbosch`
* `comp: build/ci`: `@IgorMinar` -- All build and CI scripts * `comp: build & ci`: `@IgorMinar` -- All build and CI scripts
* `comp: common`: `@mhevery` -- This includes core components / pipes. * `comp: common`: `@mhevery` -- This includes core components / pipes.
* `comp: core/compiler`: `@tbosch` -- Because core and compiler are very * `comp: core & compiler`: `@tbosch` -- Because core and compiler are very
intertwined, we will be treating them as one. intertwined, we will be treating them as one.
* `comp: forms`: `@kara` * `comp: forms`: `@kara`
* `comp: http`: `@jeffbcross` * `comp: http`: `@jeffbcross`
* `comp: i18n`: `@vicb` * `comp: i18n`: `@vicb`
* `comp: language service`: `@chuckjaz`
* `comp: metadata-extractor`: `@chuckjaz` * `comp: metadata-extractor`: `@chuckjaz`
* `comp: router`: `@vsavkin` * `comp: router`: `@vicb`
* `comp: testing`: `@juliemr` * `comp: testing`: `@juliemr`
* `comp: upgrade`: `@mhevery` * `comp: upgrade`: `@mhevery`
* `comp: web-worker`: `@vicb` * `comp: web-worker`: `@vicb`
* `comp: zone`: `@mhevery` * `comp: zones`: `@mhevery`
There are few components which are cross-cutting. They don't have There are few components which are cross-cutting. They don't have
a clear location in the source tree. We will treat them as a component a clear location in the source tree. We will treat them as a component
even thought no specific source tree is associated with them. even thought no specific source tree is associated with them.
* `comp: documentation`: `@naomiblack` * `comp: docs`: `@naomiblack`
* `comp: packaging`: `@mhevery` * `comp: packaging`: `@IgorMinar`
* `comp: performance`: `@tbosch` * `comp: performance`: `@tbosch`
* `comp: security`: `@IgorMinar` * `comp: security`: `@IgorMinar`
@ -53,11 +54,11 @@ What kind of problem is this?
## Caretaker Triage Process ## Caretaker Triage Process
It is the caretaker's responsibility to assign `comp: *` and `type: *` It is the caretaker's responsibility to assign `comp: *` to each new
to each new issue as they come in. The reason why we limit the issue as they come in. The reason why we limit the responsibility of the
responsibility of the caretaker to these two labels is that it is caretaker to this one label is that it is likely that without domain
unlikely that without domain knowledge the caretaker could add any knowledge the caretaker could mislabel issues or lack knowledge of
additional labels of value. duplicate issues.
## Component's owner Triage Process ## Component's owner Triage Process
@ -68,11 +69,37 @@ process for their component.
It will be up to the component owner to determine the order in which the It will be up to the component owner to determine the order in which the
issues within the component will be resolved. issues within the component will be resolved.
Several owners have adopted the issue categorization based on
[user pain](http://www.lostgarden.com/2008/05/improving-bug-triage-with-user-pain.html)
used by Angular 1. In this system every issue is assigned frequency and
severity based on which the total user pain score is calculated.
Following is the definition of various frequency and severity levels:
1. `freq(score): *` How often does this issue come up? How many developers does this affect?
* low (1) - obscure issue affecting a handful of developers
* moderate (2) - impacts auxiliary usage patterns, only small number of applications are affected
* high (3) - impacts primary usage patterns, affecting most Angular apps
* critical (4) - impacts all Angular apps
1. `severity(score): *` - How bad is the issue?
* inconvenience (1) - causes ugly/boilerplate code in apps
* confusing (2) - unexpected or inconsistent behavior; hard-to-debug
* broken expected use (3) - it's hard or impossible for a developer using Angular to accomplish something that Angular should be able to do
* memory leak (4)
* regression (5) - functionality that used to work no longer works in a new release due to an unintentional change
* security issue (6)
These criteria are then used to calculate a "user pain" score as follows:
`pain = severity × frequency`
### Assigning Issues to Milestones ### Assigning Issues to Milestones
Any issue that is being worked on must have: Any issue that is being worked on must have:
* An `assignee`: The person doing the work. * An `Assignee`: The person doing the work.
* A `Milestone`: When we expect to complete this work. * A `Milestone`: When we expect to complete this work.
We aim to only have at most three milestones open at a time: We aim to only have at most three milestones open at a time:

View File

@ -1,220 +1,102 @@
// Unique place to configure the browsers which are used in the different CI jobs in Sauce Labs (SL) and BrowserStack (BS). /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// Unique place to configure the browsers which are used in the different CI jobs in Sauce Labs (SL)
// and BrowserStack (BS).
// If the target is set to null, then the browser is not run anywhere during CI. // If the target is set to null, then the browser is not run anywhere during CI.
// If a category becomes empty (e.g. BS and required), then the corresponding job must be commented out in Travis configuration. // If a category becomes empty (e.g. BS and required), then the corresponding job must be commented
// out in Travis configuration.
var CIconfiguration = { var CIconfiguration = {
'Chrome': { unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}}, 'Chrome': {unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}},
'Firefox': { unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}}, 'Firefox': {unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}},
// FirefoxBeta and ChromeBeta should be target:'BS' or target:'SL', and required:true // FirefoxBeta and ChromeBeta should be target:'BS' or target:'SL', and required:true
// Currently deactivated due to https://github.com/angular/angular/issues/7560 // Currently deactivated due to https://github.com/angular/angular/issues/7560
'ChromeBeta': { unitTest: {target: null, required: true}, e2e: {target: null, required: false}}, 'ChromeBeta': {unitTest: {target: null, required: true}, e2e: {target: null, required: false}},
'FirefoxBeta': { unitTest: {target: null, required: false}, e2e: {target: null, required: false}}, 'FirefoxBeta': {unitTest: {target: null, required: false}, e2e: {target: null, required: false}},
'ChromeDev': { unitTest: {target: null, required: true}, e2e: {target: null, required: true}}, 'ChromeDev': {unitTest: {target: null, required: true}, e2e: {target: null, required: true}},
'FirefoxDev': { unitTest: {target: null, required: true}, e2e: {target: null, required: true}}, 'FirefoxDev': {unitTest: {target: null, required: true}, e2e: {target: null, required: true}},
'IE9': { unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'IE9': {unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}},
'IE10': { unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}}, 'IE10': {unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}},
'IE11': { unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}}, 'IE11': {unitTest: {target: 'SL', required: true}, e2e: {target: null, required: true}},
'Edge': { unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'Edge': {unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}},
'Android4.1': { unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'Android4.1': {unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}},
'Android4.2': { unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'Android4.2': {unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}},
'Android4.3': { unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'Android4.3': {unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}},
'Android4.4': { unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'Android4.4': {unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}},
'Android5': { unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}}, 'Android5': {unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}},
'Safari7': { unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'Safari7': {unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}},
'Safari8': { unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'Safari8': {unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}},
'Safari9': { unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'Safari9': {unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}},
'iOS7': { unitTest: {target: 'BS', required: true}, e2e: {target: null, required: true}}, 'Safari10': {unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}},
'iOS8': { unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'iOS7': {unitTest: {target: 'BS', required: true}, e2e: {target: null, required: true}},
'iOS9': { unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}, 'iOS8': {unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}},
'WindowsPhone': { unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}} 'iOS9': {unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}},
'iOS10': {unitTest: {target: 'SL', required: false}, e2e: {target: null, required: true}},
'WindowsPhone': {unitTest: {target: 'BS', required: false}, e2e: {target: null, required: true}}
}; };
var customLaunchers = { var customLaunchers = {
'DartiumWithWebPlatform': { 'DartiumWithWebPlatform':
base: 'Dartium', {base: 'Dartium', flags: ['--enable-experimental-web-platform-features']},
flags: ['--enable-experimental-web-platform-features'] }, 'ChromeNoSandbox': {base: 'Chrome', flags: ['--no-sandbox']},
'ChromeNoSandbox': { 'SL_CHROME': {base: 'SauceLabs', browserName: 'chrome', version: '54'},
base: 'Chrome', 'SL_CHROMEBETA': {base: 'SauceLabs', browserName: 'chrome', version: 'beta'},
flags: ['--no-sandbox'] }, 'SL_CHROMEDEV': {base: 'SauceLabs', browserName: 'chrome', version: 'dev'},
'SL_CHROME': { 'SL_FIREFOX': {base: 'SauceLabs', browserName: 'firefox', version: '50'},
base: 'SauceLabs', 'SL_FIREFOXBETA': {base: 'SauceLabs', browserName: 'firefox', version: 'beta'},
browserName: 'chrome', 'SL_FIREFOXDEV': {base: 'SauceLabs', browserName: 'firefox', version: 'dev'},
version: '52' 'SL_SAFARI7': {base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.9', version: '7.0'},
}, 'SL_SAFARI8': {base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.10', version: '8.0'},
'SL_CHROMEBETA': { 'SL_SAFARI9': {base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.11', version: '9.0'},
base: 'SauceLabs', 'SL_SAFARI10':
browserName: 'chrome', {base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.12', version: '10.0'},
version: 'beta' 'SL_IOS7': {base: 'SauceLabs', browserName: 'iphone', platform: 'OS X 10.10', version: '7.1'},
}, 'SL_IOS8': {base: 'SauceLabs', browserName: 'iphone', platform: 'OS X 10.10', version: '8.4'},
'SL_CHROMEDEV': { 'SL_IOS9': {base: 'SauceLabs', browserName: 'iphone', platform: 'OS X 10.10', version: '9.3'},
base: 'SauceLabs', 'SL_IOS10': {base: 'SauceLabs', browserName: 'iphone', platform: 'OS X 10.10', version: '10.0'},
browserName: 'chrome', 'SL_IE9':
version: 'dev' {base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 2008', version: '9'},
},
'SL_FIREFOX': {
base: 'SauceLabs',
browserName: 'firefox',
version: '46'
},
'SL_FIREFOXBETA': {
base: 'SauceLabs',
browserName: 'firefox',
version: 'beta'
},
'SL_FIREFOXDEV': {
base: 'SauceLabs',
browserName: 'firefox',
version: 'dev'
},
'SL_SAFARI7': {
base: 'SauceLabs',
browserName: 'safari',
platform: 'OS X 10.9',
version: '7.0'
},
'SL_SAFARI8': {
base: 'SauceLabs',
browserName: 'safari',
platform: 'OS X 10.10',
version: '8.0'
},
'SL_SAFARI9': {
base: 'SauceLabs',
browserName: 'safari',
platform: 'OS X 10.11',
version: '9.0'
},
'SL_IOS7': {
base: 'SauceLabs',
browserName: 'iphone',
platform: 'OS X 10.10',
version: '7.1'
},
'SL_IOS8': {
base: 'SauceLabs',
browserName: 'iphone',
platform: 'OS X 10.10',
version: '8.4'
},
'SL_IOS9': {
base: 'SauceLabs',
browserName: 'iphone',
platform: 'OS X 10.10',
version: '9.3'
},
'SL_IE9': {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 2008',
version: '9'
},
'SL_IE10': { 'SL_IE10': {
base: 'SauceLabs', base: 'SauceLabs',
browserName: 'internet explorer', browserName: 'internet explorer',
platform: 'Windows 2012', platform: 'Windows 2012',
version: '10' version: '10'
}, },
'SL_IE11': { 'SL_IE11':
base: 'SauceLabs', {base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 8.1', version: '11'},
browserName: 'internet explorer',
platform: 'Windows 8.1',
version: '11'
},
'SL_EDGE': { 'SL_EDGE': {
base: 'SauceLabs', base: 'SauceLabs',
browserName: 'MicrosoftEdge', browserName: 'MicrosoftEdge',
platform: 'Windows 10', platform: 'Windows 10',
version: '13.10586' version: '13.10586'
}, },
'SL_ANDROID4.1': { 'SL_ANDROID4.1': {base: 'SauceLabs', browserName: 'android', platform: 'Linux', version: '4.1'},
base: 'SauceLabs', 'SL_ANDROID4.2': {base: 'SauceLabs', browserName: 'android', platform: 'Linux', version: '4.2'},
browserName: 'android', 'SL_ANDROID4.3': {base: 'SauceLabs', browserName: 'android', platform: 'Linux', version: '4.3'},
platform: 'Linux', 'SL_ANDROID4.4': {base: 'SauceLabs', browserName: 'android', platform: 'Linux', version: '4.4'},
version: '4.1' 'SL_ANDROID5': {base: 'SauceLabs', browserName: 'android', platform: 'Linux', version: '5.1'},
},
'SL_ANDROID4.2': {
base: 'SauceLabs',
browserName: 'android',
platform: 'Linux',
version: '4.2'
},
'SL_ANDROID4.3': {
base: 'SauceLabs',
browserName: 'android',
platform: 'Linux',
version: '4.3'
},
'SL_ANDROID4.4': {
base: 'SauceLabs',
browserName: 'android',
platform: 'Linux',
version: '4.4'
},
'SL_ANDROID5': {
base: 'SauceLabs',
browserName: 'android',
platform: 'Linux',
version: '5.1'
},
'BS_CHROME': { 'BS_CHROME': {base: 'BrowserStack', browser: 'chrome', os: 'OS X', os_version: 'Yosemite'},
base: 'BrowserStack', 'BS_FIREFOX': {base: 'BrowserStack', browser: 'firefox', os: 'Windows', os_version: '10'},
browser: 'chrome', 'BS_SAFARI7': {base: 'BrowserStack', browser: 'safari', os: 'OS X', os_version: 'Mavericks'},
os: 'OS X', 'BS_SAFARI8': {base: 'BrowserStack', browser: 'safari', os: 'OS X', os_version: 'Yosemite'},
os_version: 'Yosemite' 'BS_SAFARI9': {base: 'BrowserStack', browser: 'safari', os: 'OS X', os_version: 'El Capitan'},
}, 'BS_SAFARI10': {base: 'BrowserStack', browser: 'safari', os: 'OS X', os_version: 'Sierra'},
'BS_FIREFOX': { 'BS_IOS7': {base: 'BrowserStack', device: 'iPhone 5S', os: 'ios', os_version: '7.0'},
base: 'BrowserStack', 'BS_IOS8': {base: 'BrowserStack', device: 'iPhone 6', os: 'ios', os_version: '8.3'},
browser: 'firefox', 'BS_IOS9': {base: 'BrowserStack', device: 'iPhone 6S', os: 'ios', os_version: '9.1'},
os: 'Windows', 'BS_IOS10': {base: 'BrowserStack', device: 'iPhone SE', os: 'ios', os_version: '10.0'},
os_version: '10' 'BS_IE9':
}, {base: 'BrowserStack', browser: 'ie', browser_version: '9.0', os: 'Windows', os_version: '7'},
'BS_SAFARI7': {
base: 'BrowserStack',
browser: 'safari',
os: 'OS X',
os_version: 'Mavericks'
},
'BS_SAFARI8': {
base: 'BrowserStack',
browser: 'safari',
os: 'OS X',
os_version: 'Yosemite'
},
'BS_SAFARI9': {
base: 'BrowserStack',
browser: 'safari',
os: 'OS X',
os_version: 'El Capitan'
},
'BS_IOS7': {
base: 'BrowserStack',
device: 'iPhone 5S',
os: 'ios',
os_version: '7.0'
},
'BS_IOS8': {
base: 'BrowserStack',
device: 'iPhone 6',
os: 'ios',
os_version: '8.3'
},
'BS_IOS9': {
base: 'BrowserStack',
device: 'iPhone 6S',
os: 'ios',
os_version: '9.1'
},
'BS_IE9': {
base: 'BrowserStack',
browser: 'ie',
browser_version: '9.0',
os: 'Windows',
os_version: '7'
},
'BS_IE10': { 'BS_IE10': {
base: 'BrowserStack', base: 'BrowserStack',
browser: 'ie', browser: 'ie',
browser_version: '10.0', browser_version: '10.1',
os: 'Windows', os: 'Windows',
os_version: '8' os_version: '8'
}, },
@ -225,58 +107,35 @@ var customLaunchers = {
os: 'Windows', os: 'Windows',
os_version: '10' os_version: '10'
}, },
'BS_EDGE': { 'BS_EDGE': {base: 'BrowserStack', browser: 'edge', os: 'Windows', os_version: '10'},
base: 'BrowserStack', 'BS_WINDOWSPHONE':
browser: 'edge', {base: 'BrowserStack', device: 'Nokia Lumia 930', os: 'winphone', os_version: '8.1'},
os: 'Windows', 'BS_ANDROID5': {base: 'BrowserStack', device: 'Google Nexus 5', os: 'android', os_version: '5.0'},
os_version: '10' 'BS_ANDROID4.4': {base: 'BrowserStack', device: 'HTC One M8', os: 'android', os_version: '4.4'},
}, 'BS_ANDROID4.3':
'BS_WINDOWSPHONE' : { {base: 'BrowserStack', device: 'Samsung Galaxy S4', os: 'android', os_version: '4.3'},
base: 'BrowserStack', 'BS_ANDROID4.2':
device: 'Nokia Lumia 930', {base: 'BrowserStack', device: 'Google Nexus 4', os: 'android', os_version: '4.2'},
os: 'winphone', 'BS_ANDROID4.1':
os_version: '8.1' {base: 'BrowserStack', device: 'Google Nexus 7', os: 'android', os_version: '4.1'}
},
'BS_ANDROID5': {
base: 'BrowserStack',
device: 'Google Nexus 5',
os: 'android',
os_version: '5.0'
},
'BS_ANDROID4.4': {
base: 'BrowserStack',
device: 'HTC One M8',
os: 'android',
os_version: '4.4'
},
'BS_ANDROID4.3': {
base: 'BrowserStack',
device: 'Samsung Galaxy S4',
os: 'android',
os_version: '4.3'
},
'BS_ANDROID4.2': {
base: 'BrowserStack',
device: 'Google Nexus 4',
os: 'android',
os_version: '4.2'
},
'BS_ANDROID4.1': {
base: 'BrowserStack',
device: 'Google Nexus 7',
os: 'android',
os_version: '4.1'
}
}; };
var sauceAliases = { var sauceAliases = {
'ALL': Object.keys(customLaunchers).filter(function(item) {return customLaunchers[item].base == 'SauceLabs';}), 'ALL': Object.keys(customLaunchers).filter(function(item) {
'DESKTOP': ['SL_CHROME', 'SL_FIREFOX', 'SL_IE9', 'SL_IE10', 'SL_IE11', 'SL_EDGE', 'SL_SAFARI7', 'SL_SAFARI8', 'SL_SAFARI9'], return customLaunchers[item].base == 'SauceLabs';
'MOBILE': ['SL_ANDROID4.1', 'SL_ANDROID4.2', 'SL_ANDROID4.3', 'SL_ANDROID4.4', 'SL_ANDROID5', 'SL_IOS7', 'SL_IOS8', 'SL_IOS9'], }),
'DESKTOP': [
'SL_CHROME', 'SL_FIREFOX', 'SL_IE9', 'SL_IE10', 'SL_IE11', 'SL_EDGE', 'SL_SAFARI7',
'SL_SAFARI8', 'SL_SAFARI9', 'SL_SAFARI10'
],
'MOBILE': [
'SL_ANDROID4.1', 'SL_ANDROID4.2', 'SL_ANDROID4.3', 'SL_ANDROID4.4', 'SL_ANDROID5', 'SL_IOS7',
'SL_IOS8', 'SL_IOS9', 'SL_IOS10'
],
'ANDROID': ['SL_ANDROID4.1', 'SL_ANDROID4.2', 'SL_ANDROID4.3', 'SL_ANDROID4.4', 'SL_ANDROID5'], 'ANDROID': ['SL_ANDROID4.1', 'SL_ANDROID4.2', 'SL_ANDROID4.3', 'SL_ANDROID4.4', 'SL_ANDROID5'],
'IE': ['SL_IE9', 'SL_IE10', 'SL_IE11'], 'IE': ['SL_IE9', 'SL_IE10', 'SL_IE11'],
'IOS': ['SL_IOS7', 'SL_IOS8', 'SL_IOS9'], 'IOS': ['SL_IOS7', 'SL_IOS8', 'SL_IOS9', 'SL_IOS10'],
'SAFARI': ['SL_SAFARI7', 'SL_SAFARI8', 'SL_SAFARI9'], 'SAFARI': ['SL_SAFARI7', 'SL_SAFARI8', 'SL_SAFARI9', 'SL_SAFARI10'],
'BETA': ['SL_CHROMEBETA', 'SL_FIREFOXBETA'], 'BETA': ['SL_CHROMEBETA', 'SL_FIREFOXBETA'],
'DEV': ['SL_CHROMEDEV', 'SL_FIREFOXDEV'], 'DEV': ['SL_CHROMEDEV', 'SL_FIREFOXDEV'],
'CI_REQUIRED': buildConfiguration('unitTest', 'SL', true), 'CI_REQUIRED': buildConfiguration('unitTest', 'SL', true),
@ -284,13 +143,20 @@ var sauceAliases = {
}; };
var browserstackAliases = { var browserstackAliases = {
'ALL': Object.keys(customLaunchers).filter(function(item) {return customLaunchers[item].base == 'BrowserStack';}), 'ALL': Object.keys(customLaunchers).filter(function(item) {
'DESKTOP': ['BS_CHROME', 'BS_FIREFOX', 'BS_IE9', 'BS_IE10', 'BS_IE11', 'BS_EDGE', 'BS_SAFARI7', 'BS_SAFARI8', 'BS_SAFARI9'], return customLaunchers[item].base == 'BrowserStack';
'MOBILE': ['BS_ANDROID4.3', 'BS_ANDROID4.4', 'BS_IOS7', 'BS_IOS8', 'BS_IOS9', 'BS_WINDOWSPHONE'], }),
'DESKTOP': [
'BS_CHROME', 'BS_FIREFOX', 'BS_IE9', 'BS_IE10', 'BS_IE11', 'BS_EDGE', 'BS_SAFARI7',
'BS_SAFARI8', 'BS_SAFARI9', 'BS_SAFARI10'
],
'MOBILE': [
'BS_ANDROID4.3', 'BS_ANDROID4.4', 'BS_IOS7', 'BS_IOS8', 'BS_IOS9', 'BS_IOS10', 'BS_WINDOWSPHONE'
],
'ANDROID': ['BS_ANDROID4.3', 'BS_ANDROID4.4'], 'ANDROID': ['BS_ANDROID4.3', 'BS_ANDROID4.4'],
'IE': ['BS_IE9', 'BS_IE10', 'BS_IE11'], 'IE': ['BS_IE9', 'BS_IE10', 'BS_IE11'],
'IOS': ['BS_IOS7', 'BS_IOS8', 'BS_IOS9'], 'IOS': ['BS_IOS7', 'BS_IOS8', 'BS_IOS9', 'BS_IOS10'],
'SAFARI': ['BS_SAFARI7', 'BS_SAFARI8', 'BS_SAFARI9'], 'SAFARI': ['BS_SAFARI7', 'BS_SAFARI8', 'BS_SAFARI9', 'BS_SAFARI10'],
'CI_REQUIRED': buildConfiguration('unitTest', 'BS', true), 'CI_REQUIRED': buildConfiguration('unitTest', 'BS', true),
'CI_OPTIONAL': buildConfiguration('unitTest', 'BS', false) 'CI_OPTIONAL': buildConfiguration('unitTest', 'BS', false)
}; };
@ -303,11 +169,9 @@ module.exports = {
function buildConfiguration(type, target, required) { function buildConfiguration(type, target, required) {
return Object.keys(CIconfiguration) return Object.keys(CIconfiguration)
.filter((item) => { .filter((item) => {
var conf = CIconfiguration[item][type]; var conf = CIconfiguration[item][type];
return conf.required === required && conf.target === target; return conf.required === required && conf.target === target;
}) })
.map((item) => { .map((item) => target + '_' + item.toUpperCase());
return target + '_' + item.toUpperCase();
});
} }

View File

@ -14,12 +14,17 @@ PACKAGES=(core
platform-webworker platform-webworker
platform-webworker-dynamic platform-webworker-dynamic
http http
router
upgrade upgrade
router
compiler-cli compiler-cli
language-service
benchpress) benchpress)
BUILD_ALL=true BUILD_ALL=true
BUNDLE=true BUNDLE=true
VERSION_PREFIX=$(node -p "require('./package.json').version")
VERSION_SUFFIX="-$(git log --oneline -1 | awk '{print $1}')"
ROUTER_VERSION_PREFIX=$(node -p "require('./package.json').version.replace(/^2/, '3')")
REMOVE_BENCHPRESS=false
for ARG in "$@"; do for ARG in "$@"; do
case "$ARG" in case "$ARG" in
@ -31,6 +36,10 @@ for ARG in "$@"; do
--bundle=*) --bundle=*)
BUNDLE=( "${ARG#--bundle=}" ) BUNDLE=( "${ARG#--bundle=}" )
;; ;;
--publish)
VERSION_SUFFIX=""
REMOVE_BENCHPRESS=true
;;
*) *)
echo "Unknown option $ARG." echo "Unknown option $ARG."
exit 1 exit 1
@ -38,6 +47,10 @@ for ARG in "$@"; do
esac esac
done done
VERSION="${VERSION_PREFIX}${VERSION_SUFFIX}"
ROUTER_VERSION="${ROUTER_VERSION_PREFIX}${VERSION_SUFFIX}"
echo "====== BUILDING: Version ${VERSION} (Router ${ROUTER_VERSION})"
export NODE_PATH=${NODE_PATH}:$(pwd)/dist/all:$(pwd)/dist/tools export NODE_PATH=${NODE_PATH}:$(pwd)/dist/all:$(pwd)/dist/tools
TSC="node --max-old-space-size=3000 dist/tools/@angular/tsc-wrapped/src/main" TSC="node --max-old-space-size=3000 dist/tools/@angular/tsc-wrapped/src/main"
UGLIFYJS=`pwd`/node_modules/.bin/uglifyjs UGLIFYJS=`pwd`/node_modules/.bin/uglifyjs
@ -63,10 +76,11 @@ if [[ ${BUILD_ALL} == true ]]; then
ln -s ../../../../node_modules/zone.js/dist/zone.js . ln -s ../../../../node_modules/zone.js/dist/zone.js .
ln -s ../../../../node_modules/zone.js/dist/long-stack-trace-zone.js . ln -s ../../../../node_modules/zone.js/dist/long-stack-trace-zone.js .
ln -s ../../../../node_modules/systemjs/dist/system.src.js . ln -s ../../../../node_modules/systemjs/dist/system.src.js .
ln -s ../../../../node_modules/base64-js/lib/b64.js . ln -s ../../../../node_modules/base64-js .
ln -s ../../../../node_modules/reflect-metadata/Reflect.js . ln -s ../../../../node_modules/reflect-metadata/Reflect.js .
ln -s ../../../../node_modules/rxjs . ln -s ../../../../node_modules/rxjs .
ln -s ../../../../node_modules/angular/angular.js . ln -s ../../../../node_modules/angular/angular.js .
ln -s ../../../../node_modules/hammerjs/hammer.js .
cd - cd -
echo "====== Copying files needed for benchmarks =====" echo "====== Copying files needed for benchmarks ====="
@ -78,7 +92,6 @@ if [[ ${BUILD_ALL} == true ]]; then
ln -s ../../../../node_modules/zone.js/dist/zone.js . ln -s ../../../../node_modules/zone.js/dist/zone.js .
ln -s ../../../../node_modules/zone.js/dist/long-stack-trace-zone.js . ln -s ../../../../node_modules/zone.js/dist/long-stack-trace-zone.js .
ln -s ../../../../node_modules/systemjs/dist/system.src.js . ln -s ../../../../node_modules/systemjs/dist/system.src.js .
ln -s ../../../../node_modules/base64-js/lib/b64.js .
ln -s ../../../../node_modules/reflect-metadata/Reflect.js . ln -s ../../../../node_modules/reflect-metadata/Reflect.js .
ln -s ../../../../node_modules/rxjs . ln -s ../../../../node_modules/rxjs .
ln -s ../../../../node_modules/angular/angular.js . ln -s ../../../../node_modules/angular/angular.js .
@ -101,14 +114,29 @@ do
DESTDIR=${PWD}/dist/packages-dist/${PACKAGE} DESTDIR=${PWD}/dist/packages-dist/${PACKAGE}
UMD_ES5_PATH=${DESTDIR}/bundles/${PACKAGE}.umd.js UMD_ES5_PATH=${DESTDIR}/bundles/${PACKAGE}.umd.js
UMD_TESTING_ES5_PATH=${DESTDIR}/bundles/${PACKAGE}-testing.umd.js UMD_TESTING_ES5_PATH=${DESTDIR}/bundles/${PACKAGE}-testing.umd.js
UMD_STATIC_ES5_PATH=${DESTDIR}/bundles/${PACKAGE}-static.umd.js
UMD_UPGRADE_ES5_PATH=${DESTDIR}/bundles/${PACKAGE}-upgrade.umd.js
UMD_ES5_MIN_PATH=${DESTDIR}/bundles/${PACKAGE}.umd.min.js UMD_ES5_MIN_PATH=${DESTDIR}/bundles/${PACKAGE}.umd.min.js
LICENSE_BANNER=${PWD}/modules/@angular/license-banner.txt UMD_STATIC_ES5_MIN_PATH=${DESTDIR}/bundles/${PACKAGE}-static.umd.min.js
UMD_UPGRADE_ES5_MIN_PATH=${DESTDIR}/bundles/${PACKAGE}-upgrade.umd.min.js
if [[ ${PACKAGE} != router ]]; then
LICENSE_BANNER=${PWD}/modules/@angular/license-banner.txt
fi
if [[ ${PACKAGE} == router ]]; then
LICENSE_BANNER=${PWD}/modules/@angular/router-license-banner.txt
fi
rm -rf ${DESTDIR} rm -rf ${DESTDIR}
echo "====== COMPILING: ${TSC} -p ${SRCDIR}/tsconfig-build.json =====" echo "====== COMPILING: ${TSC} -p ${SRCDIR}/tsconfig-build.json ====="
$TSC -p ${SRCDIR}/tsconfig-build.json $TSC -p ${SRCDIR}/tsconfig-build.json
if [[ -e ${SRCDIR}/tsconfig-upgrade.json ]]; then
echo "====== COMPILING: ${TSC} -p ${SRCDIR}/tsconfig-upgrade.json ====="
$TSC -p ${SRCDIR}/tsconfig-upgrade.json
fi
cp ${SRCDIR}/package.json ${DESTDIR}/ cp ${SRCDIR}/package.json ${DESTDIR}/
cp ${PWD}/modules/@angular/README.md ${DESTDIR}/ cp ${PWD}/modules/@angular/README.md ${DESTDIR}/
@ -117,6 +145,11 @@ do
$TSC -p ${SRCDIR}/tsconfig-testing.json $TSC -p ${SRCDIR}/tsconfig-testing.json
fi fi
if [[ -e ${SRCDIR}/tsconfig-2015.json ]]; then
echo "====== COMPILING ESM: ${TSC} -p ${SRCDIR}/tsconfig-2015.json"
${TSC} -p ${SRCDIR}/tsconfig-2015.json
fi
echo "====== TSC 1.8 d.ts compat for ${DESTDIR} =====" echo "====== TSC 1.8 d.ts compat for ${DESTDIR} ====="
# safely strips 'readonly' specifier from d.ts files to make them compatible with tsc 1.8 # safely strips 'readonly' specifier from d.ts files to make them compatible with tsc 1.8
if [ "$(uname)" == "Darwin" ]; then if [ "$(uname)" == "Darwin" ]; then
@ -148,7 +181,6 @@ do
mv ${UMD_ES5_PATH}.tmp ${UMD_ES5_PATH} mv ${UMD_ES5_PATH}.tmp ${UMD_ES5_PATH}
$UGLIFYJS -c --screw-ie8 --comments -o ${UMD_ES5_MIN_PATH} ${UMD_ES5_PATH} $UGLIFYJS -c --screw-ie8 --comments -o ${UMD_ES5_MIN_PATH} ${UMD_ES5_PATH}
if [[ -e rollup-testing.config.js ]]; then if [[ -e rollup-testing.config.js ]]; then
echo "====== Rollup ${PACKAGE} testing" echo "====== Rollup ${PACKAGE} testing"
../../../node_modules/.bin/rollup -c rollup-testing.config.js ../../../node_modules/.bin/rollup -c rollup-testing.config.js
@ -157,9 +189,49 @@ do
cat ${UMD_TESTING_ES5_PATH} >> ${UMD_TESTING_ES5_PATH}.tmp cat ${UMD_TESTING_ES5_PATH} >> ${UMD_TESTING_ES5_PATH}.tmp
mv ${UMD_TESTING_ES5_PATH}.tmp ${UMD_TESTING_ES5_PATH} mv ${UMD_TESTING_ES5_PATH}.tmp ${UMD_TESTING_ES5_PATH}
fi fi
) 2>&1 | grep -v "as external dependency"
if [[ -e rollup-static.config.js ]]; then
echo "====== Rollup ${PACKAGE} static"
../../../node_modules/.bin/rollup -c rollup-static.config.js
# create dir because it doesn't exist yet, we should move the src code here and remove this line
mkdir ${DESTDIR}/static
echo "{\"main\": \"../bundles/${PACKAGE}-static.umd.js\"}" > ${DESTDIR}/static/package.json
cat ${LICENSE_BANNER} > ${UMD_STATIC_ES5_PATH}.tmp
cat ${UMD_STATIC_ES5_PATH} >> ${UMD_STATIC_ES5_PATH}.tmp
mv ${UMD_STATIC_ES5_PATH}.tmp ${UMD_STATIC_ES5_PATH}
$UGLIFYJS -c --screw-ie8 --comments -o ${UMD_STATIC_ES5_MIN_PATH} ${UMD_STATIC_ES5_PATH}
fi
if [[ -e rollup-upgrade.config.js ]]; then
echo "====== Rollup ${PACKAGE} upgrade"
../../../node_modules/.bin/rollup -c rollup-upgrade.config.js
# create dir because it doesn't exist yet, we should move the src code here and remove this line
mkdir ${DESTDIR}/upgrade
echo "{\"main\": \"../bundles/${PACKAGE}-upgrade.umd.js\"}" > ${DESTDIR}/upgrade/package.json
cat ${LICENSE_BANNER} > ${UMD_UPGRADE_ES5_PATH}.tmp
cat ${UMD_UPGRADE_ES5_PATH} >> ${UMD_UPGRADE_ES5_PATH}.tmp
mv ${UMD_UPGRADE_ES5_PATH}.tmp ${UMD_UPGRADE_ES5_PATH}
$UGLIFYJS -c --screw-ie8 --comments -o ${UMD_UPGRADE_ES5_MIN_PATH} ${UMD_UPGRADE_ES5_PATH}
fi
) 2>&1 | grep -v "as external dependency"
fi fi
(
echo "====== VERSION: Updating version references"
cd ${DESTDIR}
echo "====== EXECUTE: perl -p -i -e \"s/0\.0\.0\-PLACEHOLDER/${VERSION}/g\" $""(grep -ril 0\.0\.0\-PLACEHOLDER .)"
perl -p -i -e "s/0\.0\.0\-PLACEHOLDER/${VERSION}/g" $(grep -ril 0\.0\.0\-PLACEHOLDER .) < /dev/null 2> /dev/null
echo "====== EXECUTE: perl -p -i -e \"s/0\.0\.0\-ROUTERPLACEHOLDER/${ROUTER_VERSION}/g\" $""(grep -ril 0\.0\.0\-ROUTERPLACEHOLDER .)"
perl -p -i -e "s/0\.0\.0\-ROUTERPLACEHOLDER/${ROUTER_VERSION}/g" $(grep -ril 0\.0\.0\-ROUTERPLACEHOLDER .) < /dev/null 2> /dev/null
)
done done
echo ""
echo "====== Building examples: ./modules/@angular/examples/build.sh ====="
./modules/@angular/examples/build.sh ./modules/@angular/examples/build.sh
if [[ ${REMOVE_BENCHPRESS} == true ]]; then
echo ""
echo "==== Removing benchpress from publication"
rm -r dist/packages-dist/benchpress
fi

View File

@ -4,7 +4,7 @@ machine:
dependencies: dependencies:
pre: pre:
- npm install -g npm - npm install -g npm@3.6.0
test: test:
override: override:

40
docs/PUBLIC_API.md Normal file
View File

@ -0,0 +1,40 @@
# Supported Public API Surface of Angular
Our SemVer, timed-release cycle and deprecation policy currently applies to these npm packages:
- `@angular/core`
- `@angular/common`
- `@angular/platform-browser`
- `@angular/platform-browser-dynamic`
- `@angular/platform-server`
- `@angular/platform-webworker`
- `@angular/platform-webworker-dynamic`
- `@angular/upgrade`
- `@angular/router`
- `@angular/forms`
- `@angular/http`
One intentional omission from this list is `@angular/compiler`, which is currently considered a low level api and is subject to internal changes. These changes will not affect any applications or libraries using the higher-level apis (the command line interface or JIT compilation via `@angular/platform-browser-dynamic`). Only very specific use-cases require direct access to the compiler API (mostly tooling integration for IDEs, linters, etc). If you are working on this kind of integration, please reach out to us first.
Additionally only the command line usage (not direct use of APIs) of `@angular/compiler-cli` is covered.
Other projects developed by the Angular team like angular-cli, Angular Material, benchpress, will be covered by these or similar guarantees in the future as they mature.
Within the supported packages, we provide guarantees for:
- symbols exported via the main entry point (e.g. `@angular/core`) and testing entry point (e.g. `@angular/core/testing`). This applies to both runtime/JavaScript values and TypeScript types.
- symbols exported via global namespace `ng` (e.g. `ng.core`)
- bundles located in the `bundles/` directory of our npm packages (e.g. `@angular/core/bundles/core.umd.js`)
We explicitly don't consider the following to be our public API surface:
- any file/import paths within our package except for the `/`, `/testing` and `/bundles/*`
- constructors of injectable classes (services and directives) - please use DI to obtain instances of these classes
- any class members or symbols marked as `private` or prefixed with underscore
- extending any of our classes unless the support for this is specifically documented in the API docs
- the contents and API surface of the code generated by Angular's compiler (with one notable exception: the existence and name of `NgModuleFactory` instances exported from generated code is guaranteed)
Our peer dependencies (e.g. typescript, zone.js, or rxjs) are not considered part of our API surface, but they are included in our SemVer policies. We might update the required version of any of these dependencies in minor releases if the update doesn't cause breaking changes for Angular applications. Peer dependency updates that result in non-trivial breaking changes must be deferred to major Angular releases.

View File

@ -1,3 +1,11 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
'use strict'; 'use strict';
// THIS CHECK SHOULD BE THE FIRST THING IN THIS FILE // THIS CHECK SHOULD BE THE FIRST THING IN THIS FILE
@ -13,12 +21,14 @@ const os = require('os');
// clang-format entry points // clang-format entry points
const srcsToFmt = [ const srcsToFmt = [
'modules/@angular/**/*.ts', 'modules/@angular/**/*.{js,ts}',
'modules/benchmarks/**/*.ts', 'modules/benchmarks/**/*.{js,ts}',
'modules/e2e_util/**/*.ts', 'modules/e2e_util/**/*.{js,ts}',
'modules/playground/**/*.ts', 'modules/playground/**/*.{js,ts}',
'tools/**/*.ts', 'tools/**/*.{js,ts}',
'!tools/public_api_guard/**/*.d.ts', '!tools/public_api_guard/**/*.d.ts',
'./*.{js,ts}',
'!shims_for_IE.js',
]; ];
// Check source code for formatting errors (clang-format) // Check source code for formatting errors (clang-format)
@ -26,15 +36,16 @@ gulp.task('format:enforce', () => {
const format = require('gulp-clang-format'); const format = require('gulp-clang-format');
const clangFormat = require('clang-format'); const clangFormat = require('clang-format');
return gulp.src(srcsToFmt).pipe( return gulp.src(srcsToFmt).pipe(
format.checkFormat('file', clangFormat, {verbose: true, fail: true})); format.checkFormat('file', clangFormat, {verbose: true, fail: true}));
}); });
// Format the source code with clang-format (see .clang-format) // Format the source code with clang-format (see .clang-format)
gulp.task('format', () => { gulp.task('format', () => {
const format = require('gulp-clang-format'); const format = require('gulp-clang-format');
const clangFormat = require('clang-format'); const clangFormat = require('clang-format');
return gulp.src(srcsToFmt, { base: '.' }).pipe( return gulp.src(srcsToFmt, {base: '.'})
format.format('file', clangFormat)).pipe(gulp.dest('.')); .pipe(format.format('file', clangFormat))
.pipe(gulp.dest('.'));
}); });
const entrypoints = [ const entrypoints = [
@ -47,6 +58,7 @@ const entrypoints = [
//'dist/packages-dist/compiler/index.d.ts', //'dist/packages-dist/compiler/index.d.ts',
//'dist/packages-dist/compiler/testing.d.ts', //'dist/packages-dist/compiler/testing.d.ts',
'dist/packages-dist/upgrade/index.d.ts', 'dist/packages-dist/upgrade/index.d.ts',
'dist/packages-dist/upgrade/static.d.ts',
'dist/packages-dist/platform-browser/index.d.ts', 'dist/packages-dist/platform-browser/index.d.ts',
'dist/packages-dist/platform-browser/testing/index.d.ts', 'dist/packages-dist/platform-browser/testing/index.d.ts',
'dist/packages-dist/platform-browser-dynamic/index.d.ts', 'dist/packages-dist/platform-browser-dynamic/index.d.ts',
@ -62,12 +74,18 @@ const entrypoints = [
]; ];
const publicApiDir = path.normalize('tools/public_api_guard'); const publicApiDir = path.normalize('tools/public_api_guard');
const publicApiArgs = [ const publicApiArgs = [
'--rootDir', 'dist/packages-dist', '--rootDir',
'--stripExportPattern', '^__', 'dist/packages-dist',
'--allowModuleIdentifiers', 'jasmine', '--stripExportPattern',
'--allowModuleIdentifiers', 'protractor', '^__',
'--allowModuleIdentifiers', 'angular', '--allowModuleIdentifiers',
'--onStabilityMissing', 'error', 'jasmine',
'--allowModuleIdentifiers',
'protractor',
'--allowModuleIdentifiers',
'angular',
'--onStabilityMissing',
'error',
].concat(entrypoints); ].concat(entrypoints);
// Build angular // Build angular
@ -83,17 +101,17 @@ gulp.task('public-api:enforce', (done) => {
const childProcess = require('child_process'); const childProcess = require('child_process');
childProcess childProcess
.spawn( .spawn(
path.join(__dirname, platformScriptPath(`/node_modules/.bin/ts-api-guardian`)), path.join(__dirname, platformScriptPath(`/node_modules/.bin/ts-api-guardian`)),
['--verifyDir', publicApiDir].concat(publicApiArgs), {stdio: 'inherit'}) ['--verifyDir', publicApiDir].concat(publicApiArgs), {stdio: 'inherit'})
.on('close', (errorCode) => { .on('close', (errorCode) => {
if (errorCode !== 0) { if (errorCode !== 0) {
done(new Error( done(new Error(
'Public API differs from golden file. Please run `gulp public-api:update`.')); 'Public API differs from golden file. Please run `gulp public-api:update`.'));
} else { } else {
done(); done();
} }
}); });
}); });
// Generate the public API golden files // Generate the public API golden files
@ -101,36 +119,40 @@ gulp.task('public-api:update', ['build.sh'], (done) => {
const childProcess = require('child_process'); const childProcess = require('child_process');
childProcess childProcess
.spawn( .spawn(
path.join(__dirname, platformScriptPath(`/node_modules/.bin/ts-api-guardian`)), path.join(__dirname, platformScriptPath(`/node_modules/.bin/ts-api-guardian`)),
['--outDir', publicApiDir].concat(publicApiArgs), {stdio: 'inherit'}) ['--outDir', publicApiDir].concat(publicApiArgs), {stdio: 'inherit'})
.on('close', done); .on('close', done);
});
// Checks tests for presence of ddescribe, fdescribe, fit, iit and fails the build if one of the focused tests is found.
// Currently xdescribe and xit are _not_ reported as errors since there are a couple of excluded tests in our code base.
gulp.task('check-tests', function() {
const ddescribeIit = require('gulp-ddescribe-iit');
return gulp.src([
'modules/**/*.spec.ts',
'modules/**/*_spec.ts',
]).pipe(ddescribeIit({allowDisabledTests: true}));
}); });
// Check the coding standards and programming errors // Check the coding standards and programming errors
gulp.task('lint', ['check-tests', 'format:enforce', 'tools:build'], () => { gulp.task('lint', ['format:enforce', 'tools:build'], () => {
const tslint = require('gulp-tslint'); const tslint = require('gulp-tslint');
// Built-in rules are at // Built-in rules are at
// https://github.com/palantir/tslint#supported-rules // https://palantir.github.io/tslint/rules/
const tslintConfig = require('./tslint.json'); const tslintConfig = require('./tslint.json');
return gulp.src(['modules/@angular/**/*.ts', 'modules/benchpress/**/*.ts']) return gulp
.pipe(tslint({ .src([
tslint: require('tslint').default, // todo(vicb): add .js files when supported
configuration: tslintConfig, // see https://github.com/palantir/tslint/pull/1515
rulesDirectory: 'dist/tools/tslint', './modules/**/*.ts',
formatter: 'prose', './tools/**/*.ts',
})) './*.ts',
.pipe(tslint.report({emitError: true}));
// Ignore TypeScript mocks because it's not managed by us
'!./tools/@angular/tsc-wrapped/test/typescript.mocks.ts',
// Ignore generated files due to lack of copyright header
// todo(alfaproject): make generated files lintable
'!**/*.d.ts',
'!**/*.ngfactory.ts',
])
.pipe(tslint({
tslint: require('tslint').default,
configuration: tslintConfig,
formatter: 'prose',
}))
.pipe(tslint.report({emitError: true}));
}); });
gulp.task('tools:build', (done) => { tsc('tools/', done); }); gulp.task('tools:build', (done) => { tsc('tools/', done); });
@ -142,7 +164,7 @@ gulp.task('check-cycle', (done) => {
const dependencyObject = madge(['dist/all/'], { const dependencyObject = madge(['dist/all/'], {
format: 'cjs', format: 'cjs',
extensions: ['.js'], extensions: ['.js'],
onParseFile: function(data) { data.src = data.src.replace(/\/\* circular \*\//g, "//"); } onParseFile: function(data) { data.src = data.src.replace(/\/\* circular \*\//g, '//'); }
}); });
const circularDependencies = dependencyObject.circular().getArray(); const circularDependencies = dependencyObject.circular().getArray();
if (circularDependencies.length > 0) { if (circularDependencies.length > 0) {
@ -173,11 +195,11 @@ gulp.task('serve-examples', () => {
const cors = require('cors'); const cors = require('cors');
connect.server({ connect.server({
root: `${__dirname}/dist/examples`, root: `${__dirname}/dist/examples`,
port: 8001, port: 8001,
livereload: false, livereload: false,
open: false, open: false,
middleware: (connect, opt) => [cors()], middleware: (connect, opt) => [cors()],
}); });
}); });
@ -187,16 +209,13 @@ gulp.task('changelog', () => {
const conventionalChangelog = require('gulp-conventional-changelog'); const conventionalChangelog = require('gulp-conventional-changelog');
return gulp.src('CHANGELOG.md') return gulp.src('CHANGELOG.md')
.pipe(conventionalChangelog({ .pipe(conventionalChangelog({preset: 'angular', releaseCount: 1}, {
preset: 'angular', // Conventional Changelog Context
releaseCount: 1 // We have to manually set version number so it doesn't get prefixed with `v`
}, { // See https://github.com/conventional-changelog/conventional-changelog-core/issues/10
// Conventional Changelog Context currentTag: require('./package.json').version
// We have to manually set version number so it doesn't get prefixed with `v` }))
// See https://github.com/conventional-changelog/conventional-changelog-core/issues/10 .pipe(gulp.dest('./'));
currentTag: require('./package.json').version
}))
.pipe(gulp.dest('./'));
}); });
function tsc(projectPath, done) { function tsc(projectPath, done) {
@ -205,8 +224,7 @@ function tsc(projectPath, done) {
childProcess childProcess
.spawn( .spawn(
path.normalize(platformScriptPath(`${__dirname}/node_modules/.bin/tsc`)), path.normalize(platformScriptPath(`${__dirname}/node_modules/.bin/tsc`)),
['-p', path.join(__dirname, projectPath)], ['-p', path.join(__dirname, projectPath)], {stdio: 'inherit'})
{stdio: 'inherit'})
.on('close', done); .on('close', done);
} }

View File

@ -1,3 +1,11 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var browserProvidersConf = require('./browser-providers.conf.js'); var browserProvidersConf = require('./browser-providers.conf.js');
var internalAngularReporter = require('./tools/karma/reporter.js'); var internalAngularReporter = require('./tools/karma/reporter.js');
@ -15,7 +23,8 @@ module.exports = function(config) {
'node_modules/core-js/client/core.js', 'node_modules/core-js/client/core.js',
// include Angular v1 for upgrade module testing // include Angular v1 for upgrade module testing
'node_modules/angular/angular.min.js', 'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'node_modules/zone.js/dist/zone.js', 'node_modules/zone.js/dist/zone.js',
'node_modules/zone.js/dist/long-stack-trace-zone.js', 'node_modules/zone.js/dist/long-stack-trace-zone.js',
@ -33,18 +42,30 @@ module.exports = function(config) {
'tools/build/file2modulename.js', 'tools/build/file2modulename.js',
'test-main.js', 'test-main.js',
{pattern: 'dist/all/empty.*', included: false, watched: false}, {pattern: 'dist/all/empty.*', included: false, watched: false},
{pattern: 'modules/@angular/platform-browser/test/static_assets/**', included: false, watched: false}, {
{pattern: 'modules/@angular/platform-browser/test/browser/static_assets/**', included: false, watched: false} pattern: 'modules/@angular/platform-browser/test/static_assets/**',
included: false,
watched: false
},
{
pattern: 'modules/@angular/platform-browser/test/browser/static_assets/**',
included: false,
watched: false,
}
], ],
exclude: [ exclude: [
'dist/all/@angular/**/e2e_test/**', 'dist/all/@angular/**/e2e_test/**',
'dist/all/@angular/router/**', 'dist/all/@angular/**/*node_only_spec.js',
'dist/all/@angular/compiler-cli/**',
'dist/all/@angular/benchpress/**', 'dist/all/@angular/benchpress/**',
'dist/all/angular1_router.js', 'dist/all/@angular/compiler-cli/**',
'dist/all/@angular/compiler/test/aot/**',
'dist/all/@angular/examples/**/e2e_test/*',
'dist/all/@angular/language-service/**',
'dist/all/@angular/router/**',
'dist/all/@angular/platform-browser/testing/e2e_util.js', 'dist/all/@angular/platform-browser/testing/e2e_util.js',
'dist/examples/**/e2e_test/**' 'dist/all/angular1_router.js',
'dist/examples/**/e2e_test/**',
], ],
customLaunchers: browserProvidersConf.customLaunchers, customLaunchers: browserProvidersConf.customLaunchers,
@ -55,11 +76,11 @@ module.exports = function(config) {
'karma-sauce-launcher', 'karma-sauce-launcher',
'karma-chrome-launcher', 'karma-chrome-launcher',
'karma-sourcemap-loader', 'karma-sourcemap-loader',
internalAngularReporter internalAngularReporter,
], ],
preprocessors: { preprocessors: {
'**/*.js': ['sourcemap'] '**/*.js': ['sourcemap'],
}, },
reporters: ['internal-angular'], reporters: ['internal-angular'],
@ -73,7 +94,7 @@ module.exports = function(config) {
'selenium-version': '2.53.0', 'selenium-version': '2.53.0',
'command-timeout': 600, 'command-timeout': 600,
'idle-timeout': 600, 'idle-timeout': 600,
'max-duration': 5400 'max-duration': 5400,
} }
}, },
@ -81,21 +102,22 @@ module.exports = function(config) {
project: 'Angular2', project: 'Angular2',
startTunnel: false, startTunnel: false,
retryLimit: 3, retryLimit: 3,
timeout: 600, timeout: 1800,
pollingTimeout: 10000 pollingTimeout: 10000,
}, },
browsers: ['Chrome'], browsers: ['Chrome'],
port: 9876, port: 9876,
captureTimeout: 60000, captureTimeout: 180000,
browserDisconnectTimeout : 60000, browserDisconnectTimeout: 180000,
browserDisconnectTolerance : 3, browserDisconnectTolerance: 3,
browserNoActivityTimeout : 60000, browserNoActivityTimeout: 300000,
}); });
if (process.env.TRAVIS) { if (process.env.TRAVIS) {
var buildId = 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')'; var buildId =
'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')';
if (process.env.CI_MODE.startsWith('saucelabs')) { if (process.env.CI_MODE.startsWith('saucelabs')) {
config.sauceLabs.build = buildId; config.sauceLabs.build = buildId;
config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER; config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER;

View File

@ -5,7 +5,7 @@ See [here for an example project](https://github.com/angular/benchpress-tree).
The sources for this package are in the main [Angular2](https://github.com/angular/angular) repo. Please file issues and pull requests against that repo. The sources for this package are in the main [Angular2](https://github.com/angular/angular) repo. Please file issues and pull requests against that repo.
License: Apache MIT 2.0 License: MIT
# Why? # Why?

View File

@ -7,7 +7,7 @@
"dependencies": { "dependencies": {
"@angular/core": "^2.0.0-rc.7", "@angular/core": "^2.0.0-rc.7",
"reflect-metadata": "^0.1.2", "reflect-metadata": "^0.1.2",
"rxjs": "5.0.0-beta.12", "rxjs": "^5.0.1",
"jpm": "1.1.4", "jpm": "1.1.4",
"firefox-profile": "0.4.0", "firefox-profile": "0.4.0",
"selenium-webdriver": "^2.53.3" "selenium-webdriver": "^2.53.3"

View File

@ -9,8 +9,6 @@
import {OpaqueToken} from '@angular/core'; import {OpaqueToken} from '@angular/core';
import * as fs from 'fs'; import * as fs from 'fs';
import {DateWrapper} from './facade/lang';
export class Options { export class Options {
static SAMPLE_ID = new OpaqueToken('Options.sampleId'); static SAMPLE_ID = new OpaqueToken('Options.sampleId');
static DEFAULT_DESCRIPTION = new OpaqueToken('Options.defaultDescription'); static DEFAULT_DESCRIPTION = new OpaqueToken('Options.defaultDescription');
@ -34,7 +32,7 @@ export class Options {
{provide: Options.FORCE_GC, useValue: false}, {provide: Options.FORCE_GC, useValue: false},
{provide: Options.PREPARE, useValue: Options.NO_PREPARE}, {provide: Options.PREPARE, useValue: Options.NO_PREPARE},
{provide: Options.MICRO_METRICS, useValue: {}}, {provide: Options.USER_METRICS, useValue: {}}, {provide: Options.MICRO_METRICS, useValue: {}}, {provide: Options.USER_METRICS, useValue: {}},
{provide: Options.NOW, useValue: () => DateWrapper.now()}, {provide: Options.NOW, useValue: () => new Date()},
{provide: Options.RECEIVED_DATA, useValue: false}, {provide: Options.RECEIVED_DATA, useValue: false},
{provide: Options.REQUEST_COUNT, useValue: false}, {provide: Options.REQUEST_COUNT, useValue: false},
{provide: Options.CAPTURE_FRAMES, useValue: false}, {provide: Options.CAPTURE_FRAMES, useValue: false},

View File

@ -10,7 +10,7 @@ declare var exportFunction: any;
declare var unsafeWindow: any; declare var unsafeWindow: any;
exportFunction(function() { exportFunction(function() {
var curTime = unsafeWindow.performance.now(); const curTime = unsafeWindow.performance.now();
(<any>self).port.emit('startProfiler', curTime); (<any>self).port.emit('startProfiler', curTime);
}, unsafeWindow, {defineAs: 'startProfiler'}); }, unsafeWindow, {defineAs: 'startProfiler'});
@ -28,11 +28,11 @@ exportFunction(function() {
}, unsafeWindow, {defineAs: 'forceGC'}); }, unsafeWindow, {defineAs: 'forceGC'});
exportFunction(function(name: string) { exportFunction(function(name: string) {
var curTime = unsafeWindow.performance.now(); const curTime = unsafeWindow.performance.now();
(<any>self).port.emit('markStart', name, curTime); (<any>self).port.emit('markStart', name, curTime);
}, unsafeWindow, {defineAs: 'markStart'}); }, unsafeWindow, {defineAs: 'markStart'});
exportFunction(function(name: string) { exportFunction(function(name: string) {
var curTime = unsafeWindow.performance.now(); const curTime = unsafeWindow.performance.now();
(<any>self).port.emit('markEnd', name, curTime); (<any>self).port.emit('markEnd', name, curTime);
}, unsafeWindow, {defineAs: 'markEnd'}); }, unsafeWindow, {defineAs: 'markEnd'});

View File

@ -6,9 +6,9 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
var {Cc, Ci, Cu} = require('chrome'); const {Cc, Ci, Cu} = require('chrome');
var os = Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService); const os = Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
var ParserUtil = require('./parser_util'); const ParserUtil = require('./parser_util');
class Profiler { class Profiler {
private _profiler: any; private _profiler: any;
@ -26,8 +26,8 @@ class Profiler {
stop() { this._profiler.StopProfiler(); } stop() { this._profiler.StopProfiler(); }
getProfilePerfEvents() { getProfilePerfEvents() {
var profileData = this._profiler.getProfileData(); const profileData = this._profiler.getProfileData();
var perfEvents = ParserUtil.convertPerfProfileToEvents(profileData); let perfEvents = ParserUtil.convertPerfProfileToEvents(profileData);
perfEvents = this._mergeMarkerEvents(perfEvents); perfEvents = this._mergeMarkerEvents(perfEvents);
perfEvents.sort(function(event1: any, event2: any) { perfEvents.sort(function(event1: any, event2: any) {
return event1.ts - event2.ts; return event1.ts - event2.ts;
@ -55,9 +55,9 @@ function forceGC() {
os.notifyObservers(null, 'child-gc-request', null); os.notifyObservers(null, 'child-gc-request', null);
}; };
var mod = require('sdk/page-mod'); const mod = require('sdk/page-mod');
var data = require('sdk/self').data; const data = require('sdk/self').data;
var profiler = new Profiler(); const profiler = new Profiler();
mod.PageMod({ mod.PageMod({
include: ['*'], include: ['*'],
contentScriptFile: data.url('installed_script.js'), contentScriptFile: data.url('installed_script.js'),

View File

@ -12,11 +12,11 @@
* within the perf profile. * within the perf profile.
*/ */
export function convertPerfProfileToEvents(perfProfile: any): any[] { export function convertPerfProfileToEvents(perfProfile: any): any[] {
var inProgressEvents = new Map(); // map from event name to start time const inProgressEvents = new Map(); // map from event name to start time
var finishedEvents: {[key: string]: any}[] = []; // Event[] finished events const finishedEvents: {[key: string]: any}[] = []; // Event[] finished events
var addFinishedEvent = function(eventName: string, startTime: number, endTime: number) { const addFinishedEvent = function(eventName: string, startTime: number, endTime: number) {
var categorizedEventName = categorizeEvent(eventName); const categorizedEventName = categorizeEvent(eventName);
var args: {[key: string]: any} = undefined; let args: {[key: string]: any} = undefined;
if (categorizedEventName == 'gc') { if (categorizedEventName == 'gc') {
// TODO: We cannot measure heap size at the moment // TODO: We cannot measure heap size at the moment
args = {usedHeapSize: 0}; args = {usedHeapSize: 0};
@ -31,17 +31,17 @@ export function convertPerfProfileToEvents(perfProfile: any): any[] {
} }
}; };
var samples = perfProfile.threads[0].samples; const samples = perfProfile.threads[0].samples;
// In perf profile, firefox samples all the frames in set time intervals. Here // In perf profile, firefox samples all the frames in set time intervals. Here
// we go through all the samples and construct the start and end time for each // we go through all the samples and construct the start and end time for each
// event. // event.
for (var i = 0; i < samples.length; ++i) { for (let i = 0; i < samples.length; ++i) {
var sample = samples[i]; const sample = samples[i];
var sampleTime = sample.time; const sampleTime = sample.time;
// Add all the frames into a set so it's easier/faster to find the set // Add all the frames into a set so it's easier/faster to find the set
// differences // differences
var sampleFrames = new Set(); const sampleFrames = new Set();
sample.frames.forEach(function(frame: {[key: string]: any}) { sample.frames.forEach(function(frame: {[key: string]: any}) {
sampleFrames.add(frame['location']); sampleFrames.add(frame['location']);
}); });
@ -49,7 +49,7 @@ export function convertPerfProfileToEvents(perfProfile: any): any[] {
// If an event is in the inProgressEvents map, but not in the current sample, // If an event is in the inProgressEvents map, but not in the current sample,
// then it must have just finished. We add this event to the finishedEvents // then it must have just finished. We add this event to the finishedEvents
// array and remove it from the inProgressEvents map. // array and remove it from the inProgressEvents map.
var previousSampleTime = (i == 0 ? /* not used */ -1 : samples[i - 1].time); const previousSampleTime = (i == 0 ? /* not used */ -1 : samples[i - 1].time);
inProgressEvents.forEach(function(startTime, eventName) { inProgressEvents.forEach(function(startTime, eventName) {
if (!(sampleFrames.has(eventName))) { if (!(sampleFrames.has(eventName))) {
addFinishedEvent(eventName, startTime, previousSampleTime); addFinishedEvent(eventName, startTime, previousSampleTime);
@ -69,7 +69,7 @@ export function convertPerfProfileToEvents(perfProfile: any): any[] {
// If anything is still in progress, we need to included it as a finished event // If anything is still in progress, we need to included it as a finished event
// since recording ended. // since recording ended.
var lastSampleTime = samples[samples.length - 1].time; const lastSampleTime = samples[samples.length - 1].time;
inProgressEvents.forEach(function(startTime, eventName) { inProgressEvents.forEach(function(startTime, eventName) {
addFinishedEvent(eventName, startTime, lastSampleTime); addFinishedEvent(eventName, startTime, lastSampleTime);
}); });

View File

@ -6,15 +6,15 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
var q = require('q'); const q = require('q');
var FirefoxProfile = require('firefox-profile'); const FirefoxProfile = require('firefox-profile');
var jpm = require('jpm/lib/xpi'); const jpm = require('jpm/lib/xpi');
var pathUtil = require('path'); const pathUtil = require('path');
var PERF_ADDON_PACKAGE_JSON_DIR = '..'; const PERF_ADDON_PACKAGE_JSON_DIR = '..';
exports.getAbsolutePath = function(path: string) { exports.getAbsolutePath = function(path: string) {
var normalizedPath = pathUtil.normalize(path); const normalizedPath = pathUtil.normalize(path);
if (pathUtil.resolve(normalizedPath) == normalizedPath) { if (pathUtil.resolve(normalizedPath) == normalizedPath) {
// Already absolute path // Already absolute path
return normalizedPath; return normalizedPath;
@ -24,12 +24,12 @@ exports.getAbsolutePath = function(path: string) {
}; };
exports.getFirefoxProfile = function(extensionPath: string) { exports.getFirefoxProfile = function(extensionPath: string) {
var deferred = q.defer(); const deferred = q.defer();
var firefoxProfile = new FirefoxProfile(); const firefoxProfile = new FirefoxProfile();
firefoxProfile.addExtensions([extensionPath], () => { firefoxProfile.addExtensions([extensionPath], () => {
firefoxProfile.encoded((encodedProfile: any) => { firefoxProfile.encoded((encodedProfile: any) => {
var multiCapabilities = [{browserName: 'firefox', firefox_profile: encodedProfile}]; const multiCapabilities = [{browserName: 'firefox', firefox_profile: encodedProfile}];
deferred.resolve(multiCapabilities); deferred.resolve(multiCapabilities);
}); });
}); });
@ -38,10 +38,10 @@ exports.getFirefoxProfile = function(extensionPath: string) {
}; };
exports.getFirefoxProfileWithExtension = function() { exports.getFirefoxProfileWithExtension = function() {
var absPackageJsonDir = pathUtil.join(__dirname, PERF_ADDON_PACKAGE_JSON_DIR); const absPackageJsonDir = pathUtil.join(__dirname, PERF_ADDON_PACKAGE_JSON_DIR);
var packageJson = require(pathUtil.join(absPackageJsonDir, 'package.json')); const packageJson = require(pathUtil.join(absPackageJsonDir, 'package.json'));
var savedCwd = process.cwd(); const savedCwd = process.cwd();
process.chdir(absPackageJsonDir); process.chdir(absPackageJsonDir);
return jpm(packageJson).then((xpiPath: string) => { return jpm(packageJson).then((xpiPath: string) => {

View File

@ -6,18 +6,15 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {Map} from './facade/collection';
import {Date, DateWrapper} from './facade/lang';
export class MeasureValues { export class MeasureValues {
constructor( constructor(
public runIndex: number, public timeStamp: Date, public values: {[key: string]: any}) {} public runIndex: number, public timeStamp: Date, public values: {[key: string]: any}) {}
toJson() { toJson() {
return { return {
'timeStamp': DateWrapper.toJson(this.timeStamp), 'timeStamp': this.timeStamp.toJSON(),
'runIndex': this.runIndex, 'runIndex': this.runIndex,
'values': this.values 'values': this.values,
}; };
} }
} }

View File

@ -7,7 +7,6 @@
*/ */
import {Injector, OpaqueToken} from '@angular/core'; import {Injector, OpaqueToken} from '@angular/core';
import {StringMapWrapper} from '../facade/collection';
import {Metric} from '../metric'; import {Metric} from '../metric';
@ -56,10 +55,9 @@ export class MultiMetric extends Metric {
} }
function mergeStringMaps(maps: {[key: string]: string}[]): {[key: string]: string} { function mergeStringMaps(maps: {[key: string]: string}[]): {[key: string]: string} {
var result: {[key: string]: string} = {}; const result: {[key: string]: string} = {};
maps.forEach( maps.forEach(map => { Object.keys(map).forEach(prop => { result[prop] = map[prop]; }); });
map => { StringMapWrapper.forEach(map, (value, prop) => { result[prop] = value; }); });
return result; return result;
} }
var _CHILDREN = new OpaqueToken('MultiMetric.children'); const _CHILDREN = new OpaqueToken('MultiMetric.children');

View File

@ -56,7 +56,7 @@ export class PerflogMetric extends Metric {
} }
describe(): {[key: string]: string} { describe(): {[key: string]: string} {
var res: {[key: string]: any} = { const res: {[key: string]: any} = {
'scriptTime': 'script execution time in ms, including gc and render', 'scriptTime': 'script execution time in ms, including gc and render',
'pureScriptTime': 'script execution time in ms, without gc nor render' 'pureScriptTime': 'script execution time in ms, without gc nor render'
}; };
@ -80,7 +80,7 @@ export class PerflogMetric extends Metric {
} }
if (this._captureFrames) { if (this._captureFrames) {
if (!this._perfLogFeatures.frameCapture) { if (!this._perfLogFeatures.frameCapture) {
var warningMsg = 'WARNING: Metric requested, but not supported by driver'; const warningMsg = 'WARNING: Metric requested, but not supported by driver';
// using dot syntax for metric name to keep them grouped together in console reporter // using dot syntax for metric name to keep them grouped together in console reporter
res['frameTime.mean'] = warningMsg; res['frameTime.mean'] = warningMsg;
res['frameTime.worst'] = warningMsg; res['frameTime.worst'] = warningMsg;
@ -93,14 +93,14 @@ export class PerflogMetric extends Metric {
res['frameTime.smooth'] = 'percentage of frames that hit 60fps'; res['frameTime.smooth'] = 'percentage of frames that hit 60fps';
} }
} }
for (let name in this._microMetrics) { for (const name in this._microMetrics) {
res[name] = this._microMetrics[name]; res[name] = this._microMetrics[name];
} }
return res; return res;
} }
beginMeasure(): Promise<any> { beginMeasure(): Promise<any> {
var resultPromise = Promise.resolve(null); let resultPromise = Promise.resolve(null);
if (this._forceGc) { if (this._forceGc) {
resultPromise = resultPromise.then((_) => this._driverExtension.gc()); resultPromise = resultPromise.then((_) => this._driverExtension.gc());
} }
@ -119,7 +119,7 @@ export class PerflogMetric extends Metric {
private _endPlainMeasureAndMeasureForceGc(restartMeasure: boolean) { private _endPlainMeasureAndMeasureForceGc(restartMeasure: boolean) {
return this._endMeasure(true).then((measureValues) => { return this._endMeasure(true).then((measureValues) => {
// disable frame capture for measurements during forced gc // disable frame capture for measurements during forced gc
var originalFrameCaptureValue = this._captureFrames; const originalFrameCaptureValue = this._captureFrames;
this._captureFrames = false; this._captureFrames = false;
return this._driverExtension.gc() return this._driverExtension.gc()
.then((_) => this._endMeasure(restartMeasure)) .then((_) => this._endMeasure(restartMeasure))
@ -137,8 +137,8 @@ export class PerflogMetric extends Metric {
} }
private _endMeasure(restart: boolean): Promise<{[key: string]: number}> { private _endMeasure(restart: boolean): Promise<{[key: string]: number}> {
var markName = this._markName(this._measureCount - 1); const markName = this._markName(this._measureCount - 1);
var nextMarkName = restart ? this._markName(this._measureCount++) : null; const nextMarkName = restart ? this._markName(this._measureCount++) : null;
return this._driverExtension.timeEnd(markName, nextMarkName) return this._driverExtension.timeEnd(markName, nextMarkName)
.then((_) => this._readUntilEndMark(markName)); .then((_) => this._readUntilEndMark(markName));
} }
@ -150,26 +150,26 @@ export class PerflogMetric extends Metric {
} }
return this._driverExtension.readPerfLog().then((events) => { return this._driverExtension.readPerfLog().then((events) => {
this._addEvents(events); this._addEvents(events);
var result = this._aggregateEvents(this._remainingEvents, markName); const result = this._aggregateEvents(this._remainingEvents, markName);
if (result) { if (result) {
this._remainingEvents = events; this._remainingEvents = events;
return result; return result;
} }
var resolve: (result: any) => void; let resolve: (result: any) => void;
var promise = new Promise(res => { resolve = res; }); const promise = new Promise(res => { resolve = res; });
this._setTimeout(() => resolve(this._readUntilEndMark(markName, loopCount + 1)), 100); this._setTimeout(() => resolve(this._readUntilEndMark(markName, loopCount + 1)), 100);
return promise; return promise;
}); });
} }
private _addEvents(events: PerfLogEvent[]) { private _addEvents(events: PerfLogEvent[]) {
var needSort = false; let needSort = false;
events.forEach(event => { events.forEach(event => {
if (event['ph'] === 'X') { if (event['ph'] === 'X') {
needSort = true; needSort = true;
var startEvent: PerfLogEvent = {}; const startEvent: PerfLogEvent = {};
var endEvent: PerfLogEvent = {}; const endEvent: PerfLogEvent = {};
for (let prop in event) { for (const prop in event) {
startEvent[prop] = event[prop]; startEvent[prop] = event[prop];
endEvent[prop] = event[prop]; endEvent[prop] = event[prop];
} }
@ -185,14 +185,14 @@ export class PerflogMetric extends Metric {
if (needSort) { if (needSort) {
// Need to sort because of the ph==='X' events // Need to sort because of the ph==='X' events
this._remainingEvents.sort((a, b) => { this._remainingEvents.sort((a, b) => {
var diff = a['ts'] - b['ts']; const diff = a['ts'] - b['ts'];
return diff > 0 ? 1 : diff < 0 ? -1 : 0; return diff > 0 ? 1 : diff < 0 ? -1 : 0;
}); });
} }
} }
private _aggregateEvents(events: PerfLogEvent[], markName: string): {[key: string]: number} { private _aggregateEvents(events: PerfLogEvent[], markName: string): {[key: string]: number} {
var result: {[key: string]: number} = {'scriptTime': 0, 'pureScriptTime': 0}; const result: {[key: string]: number} = {'scriptTime': 0, 'pureScriptTime': 0};
if (this._perfLogFeatures.gc) { if (this._perfLogFeatures.gc) {
result['gcTime'] = 0; result['gcTime'] = 0;
result['majorGcTime'] = 0; result['majorGcTime'] = 0;
@ -207,7 +207,7 @@ export class PerflogMetric extends Metric {
result['frameTime.worst'] = 0; result['frameTime.worst'] = 0;
result['frameTime.smooth'] = 0; result['frameTime.smooth'] = 0;
} }
for (let name in this._microMetrics) { for (const name in this._microMetrics) {
result[name] = 0; result[name] = 0;
} }
if (this._receivedData) { if (this._receivedData) {
@ -217,11 +217,11 @@ export class PerflogMetric extends Metric {
result['requestCount'] = 0; result['requestCount'] = 0;
} }
var markStartEvent: PerfLogEvent = null; let markStartEvent: PerfLogEvent = null;
var markEndEvent: PerfLogEvent = null; let markEndEvent: PerfLogEvent = null;
events.forEach((event) => { events.forEach((event) => {
var ph = event['ph']; const ph = event['ph'];
var name = event['name']; const name = event['name'];
if (ph === 'B' && name === markName) { if (ph === 'B' && name === markName) {
markStartEvent = event; markStartEvent = event;
} else if (ph === 'I' && name === 'navigationStart') { } else if (ph === 'I' && name === 'navigationStart') {
@ -237,23 +237,23 @@ export class PerflogMetric extends Metric {
return null; return null;
} }
var gcTimeInScript = 0; let gcTimeInScript = 0;
var renderTimeInScript = 0; let renderTimeInScript = 0;
var frameTimestamps: number[] = []; const frameTimestamps: number[] = [];
var frameTimes: number[] = []; const frameTimes: number[] = [];
var frameCaptureStartEvent: PerfLogEvent = null; let frameCaptureStartEvent: PerfLogEvent = null;
var frameCaptureEndEvent: PerfLogEvent = null; let frameCaptureEndEvent: PerfLogEvent = null;
var intervalStarts: {[key: string]: PerfLogEvent} = {}; const intervalStarts: {[key: string]: PerfLogEvent} = {};
var intervalStartCount: {[key: string]: number} = {}; const intervalStartCount: {[key: string]: number} = {};
var inMeasureRange = false; let inMeasureRange = false;
events.forEach((event) => { events.forEach((event) => {
var ph = event['ph']; const ph = event['ph'];
var name = event['name']; let name = event['name'];
var microIterations = 1; let microIterations = 1;
var microIterationsMatch = name.match(_MICRO_ITERATIONS_REGEX); const microIterationsMatch = name.match(_MICRO_ITERATIONS_REGEX);
if (microIterationsMatch) { if (microIterationsMatch) {
name = microIterationsMatch[1]; name = microIterationsMatch[1];
microIterations = parseInt(microIterationsMatch[2], 10); microIterations = parseInt(microIterationsMatch[2], 10);
@ -307,15 +307,15 @@ export class PerflogMetric extends Metric {
} else if ((ph === 'E') && intervalStarts[name]) { } else if ((ph === 'E') && intervalStarts[name]) {
intervalStartCount[name]--; intervalStartCount[name]--;
if (intervalStartCount[name] === 0) { if (intervalStartCount[name] === 0) {
var startEvent = intervalStarts[name]; const startEvent = intervalStarts[name];
var duration = (event['ts'] - startEvent['ts']); const duration = (event['ts'] - startEvent['ts']);
intervalStarts[name] = null; intervalStarts[name] = null;
if (name === 'gc') { if (name === 'gc') {
result['gcTime'] += duration; result['gcTime'] += duration;
var amount = const amount =
(startEvent['args']['usedHeapSize'] - event['args']['usedHeapSize']) / 1000; (startEvent['args']['usedHeapSize'] - event['args']['usedHeapSize']) / 1000;
result['gcAmount'] += amount; result['gcAmount'] += amount;
var majorGc = event['args']['majorGc']; const majorGc = event['args']['majorGc'];
if (majorGc && majorGc) { if (majorGc && majorGc) {
result['majorGcTime'] += duration; result['majorGcTime'] += duration;
} }
@ -351,7 +351,7 @@ export class PerflogMetric extends Metric {
private _addFrameMetrics(result: {[key: string]: number}, frameTimes: any[]) { private _addFrameMetrics(result: {[key: string]: number}, frameTimes: any[]) {
result['frameTime.mean'] = frameTimes.reduce((a, b) => a + b, 0) / frameTimes.length; result['frameTime.mean'] = frameTimes.reduce((a, b) => a + b, 0) / frameTimes.length;
var firstFrame = frameTimes[0]; const firstFrame = frameTimes[0];
result['frameTime.worst'] = frameTimes.reduce((a, b) => a > b ? a : b, firstFrame); result['frameTime.worst'] = frameTimes.reduce((a, b) => a > b ? a : b, firstFrame);
result['frameTime.best'] = frameTimes.reduce((a, b) => a < b ? a : b, firstFrame); result['frameTime.best'] = frameTimes.reduce((a, b) => a < b ? a : b, firstFrame);
result['frameTime.smooth'] = result['frameTime.smooth'] =
@ -361,11 +361,11 @@ export class PerflogMetric extends Metric {
private _markName(index: number) { return `${_MARK_NAME_PREFIX}${index}`; } private _markName(index: number) { return `${_MARK_NAME_PREFIX}${index}`; }
} }
var _MICRO_ITERATIONS_REGEX = /(.+)\*(\d+)$/; const _MICRO_ITERATIONS_REGEX = /(.+)\*(\d+)$/;
var _MAX_RETRY_COUNT = 20; const _MAX_RETRY_COUNT = 20;
var _MARK_NAME_PREFIX = 'benchpress'; const _MARK_NAME_PREFIX = 'benchpress';
var _MARK_NAME_FRAME_CAPUTRE = 'frameCapture'; const _MARK_NAME_FRAME_CAPUTRE = 'frameCapture';
// using 17ms as a somewhat looser threshold, instead of 16.6666ms // using 17ms as a somewhat looser threshold, instead of 16.6666ms
var _FRAME_TIME_SMOOTH_THRESHOLD = 17; const _FRAME_TIME_SMOOTH_THRESHOLD = 17;

View File

@ -6,11 +6,9 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {Inject, Injectable, OpaqueToken, Provider} from '@angular/core'; import {Inject, Injectable} from '@angular/core';
import {Options} from '../common_options'; import {Options} from '../common_options';
import {StringMapWrapper} from '../facade/collection';
import {isNumber} from '../facade/lang';
import {Metric} from '../metric'; import {Metric} from '../metric';
import {WebDriverAdapter} from '../web_driver_adapter'; import {WebDriverAdapter} from '../web_driver_adapter';
@ -35,22 +33,22 @@ export class UserMetric extends Metric {
endMeasure(restart: boolean): Promise<{[key: string]: any}> { endMeasure(restart: boolean): Promise<{[key: string]: any}> {
let resolve: (result: any) => void; let resolve: (result: any) => void;
let reject: (error: any) => void; let reject: (error: any) => void;
let promise = new Promise((res, rej) => { const promise = new Promise((res, rej) => {
resolve = res; resolve = res;
reject = rej; reject = rej;
}); });
let adapter = this._wdAdapter; const adapter = this._wdAdapter;
let names = StringMapWrapper.keys(this._userMetrics); const names = Object.keys(this._userMetrics);
function getAndClearValues() { function getAndClearValues() {
Promise.all(names.map(name => adapter.executeScript(`return window.${name}`))) Promise.all(names.map(name => adapter.executeScript(`return window.${name}`)))
.then((values: any[]) => { .then((values: any[]) => {
if (values.every(isNumber)) { if (values.every(v => typeof v === 'number')) {
Promise.all(names.map(name => adapter.executeScript(`delete window.${name}`))) Promise.all(names.map(name => adapter.executeScript(`delete window.${name}`)))
.then((_: any[]) => { .then((_: any[]) => {
let map = StringMapWrapper.create(); const map: {[k: string]: any} = {};
for (let i = 0, n = names.length; i < n; i++) { for (let i = 0, n = names.length; i < n; i++) {
StringMapWrapper.set(map, names[i], values[i]); map[names[i]] = values[i];
} }
resolve(map); resolve(map);
}, reject); }, reject);

View File

@ -7,10 +7,7 @@
*/ */
import {Inject, Injectable, OpaqueToken} from '@angular/core'; import {Inject, Injectable, OpaqueToken} from '@angular/core';
import {print} from '../facade/lang';
import {ListWrapper, StringMapWrapper} from '../facade/collection';
import {NumberWrapper, isBlank, isPresent, print} from '../facade/lang';
import {Math} from '../facade/math';
import {MeasureValues} from '../measure_values'; import {MeasureValues} from '../measure_values';
import {Reporter} from '../reporter'; import {Reporter} from '../reporter';
import {SampleDescription} from '../sample_description'; import {SampleDescription} from '../sample_description';
@ -31,8 +28,8 @@ export class ConsoleReporter extends Reporter {
]; ];
private static _lpad(value: string, columnWidth: number, fill = ' ') { private static _lpad(value: string, columnWidth: number, fill = ' ') {
var result = ''; let result = '';
for (var i = 0; i < columnWidth - value.length; i++) { for (let i = 0; i < columnWidth - value.length; i++) {
result += fill; result += fill;
} }
return result + value; return result + value;
@ -52,7 +49,7 @@ export class ConsoleReporter extends Reporter {
private _printDescription(sampleDescription: SampleDescription) { private _printDescription(sampleDescription: SampleDescription) {
this._print(`BENCHMARK ${sampleDescription.id}`); this._print(`BENCHMARK ${sampleDescription.id}`);
this._print('Description:'); this._print('Description:');
var props = sortedProps(sampleDescription.description); const props = sortedProps(sampleDescription.description);
props.forEach((prop) => { this._print(`- ${prop}: ${sampleDescription.description[prop]}`); }); props.forEach((prop) => { this._print(`- ${prop}: ${sampleDescription.description[prop]}`); });
this._print('Metrics:'); this._print('Metrics:');
this._metricNames.forEach((metricName) => { this._metricNames.forEach((metricName) => {
@ -64,8 +61,8 @@ export class ConsoleReporter extends Reporter {
} }
reportMeasureValues(measureValues: MeasureValues): Promise<any> { reportMeasureValues(measureValues: MeasureValues): Promise<any> {
var formattedValues = this._metricNames.map(metricName => { const formattedValues = this._metricNames.map(metricName => {
var value = measureValues.values[metricName]; const value = measureValues.values[metricName];
return formatNum(value); return formatNum(value);
}); });
this._printStringRow(formattedValues); this._printStringRow(formattedValues);

View File

@ -9,7 +9,6 @@
import {Inject, Injectable, OpaqueToken} from '@angular/core'; import {Inject, Injectable, OpaqueToken} from '@angular/core';
import {Options} from '../common_options'; import {Options} from '../common_options';
import {DateWrapper, Json, isBlank, isPresent} from '../facade/lang';
import {MeasureValues} from '../measure_values'; import {MeasureValues} from '../measure_values';
import {Reporter} from '../reporter'; import {Reporter} from '../reporter';
import {SampleDescription} from '../sample_description'; import {SampleDescription} from '../sample_description';
@ -39,14 +38,15 @@ export class JsonFileReporter extends Reporter {
sortedProps(this._description.metrics).forEach((metricName) => { sortedProps(this._description.metrics).forEach((metricName) => {
stats[metricName] = formatStats(validSample, metricName); stats[metricName] = formatStats(validSample, metricName);
}); });
var content = Json.stringify({ const content = JSON.stringify(
'description': this._description, {
'stats': stats, 'description': this._description,
'completeSample': completeSample, 'stats': stats,
'validSample': validSample, 'completeSample': completeSample,
}); 'validSample': validSample,
var filePath = },
`${this._path}/${this._description.id}_${DateWrapper.toMillis(this._now())}.json`; null, 2);
const filePath = `${this._path}/${this._description.id}_${this._now().getTime()}.json`;
return this._writeFile(filePath, content); return this._writeFile(filePath, content);
} }
} }

View File

@ -39,4 +39,4 @@ export class MultiReporter extends Reporter {
} }
} }
var _CHILDREN = new OpaqueToken('MultiReporter.children'); const _CHILDREN = new OpaqueToken('MultiReporter.children');

View File

@ -6,28 +6,23 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {StringMapWrapper} from '../facade/collection';
import {NumberWrapper} from '../facade/lang';
import {MeasureValues} from '../measure_values'; import {MeasureValues} from '../measure_values';
import {Statistic} from '../statistic'; import {Statistic} from '../statistic';
export function formatNum(n: number) { export function formatNum(n: number) {
return NumberWrapper.toFixed(n, 2); return n.toFixed(2);
} }
export function sortedProps(obj: {[key: string]: any}) { export function sortedProps(obj: {[key: string]: any}) {
var props: string[] = []; return Object.keys(obj).sort();
StringMapWrapper.forEach(obj, (value, prop) => props.push(prop));
props.sort();
return props;
} }
export function formatStats(validSamples: MeasureValues[], metricName: string): string { export function formatStats(validSamples: MeasureValues[], metricName: string): string {
var samples = validSamples.map(measureValues => measureValues.values[metricName]); const samples = validSamples.map(measureValues => measureValues.values[metricName]);
var mean = Statistic.calculateMean(samples); const mean = Statistic.calculateMean(samples);
var cv = Statistic.calculateCoefficientOfVariation(samples, mean); const cv = Statistic.calculateCoefficientOfVariation(samples, mean);
var formattedMean = formatNum(mean); const formattedMean = formatNum(mean);
// Note: Don't use the unicode character for +- as it might cause // Note: Don't use the unicode character for +- as it might cause
// hickups for consoles... // hickups for consoles...
return NumberWrapper.isNaN(cv) ? formattedMean : `${formattedMean}+-${Math.floor(cv)}%`; return isNaN(cv) ? formattedMean : `${formattedMean}+-${Math.floor(cv)}%`;
} }

View File

@ -9,7 +9,7 @@
import {Provider, ReflectiveInjector} from '@angular/core'; import {Provider, ReflectiveInjector} from '@angular/core';
import {Options} from './common_options'; import {Options} from './common_options';
import {isBlank, isPresent} from './facade/lang'; import {isPresent} from './facade/lang';
import {Metric} from './metric'; import {Metric} from './metric';
import {MultiMetric} from './metric/multi_metric'; import {MultiMetric} from './metric/multi_metric';
import {PerflogMetric} from './metric/perflog_metric'; import {PerflogMetric} from './metric/perflog_metric';
@ -45,7 +45,7 @@ export class Runner {
providers?: Provider[], providers?: Provider[],
userMetrics?: {[key: string]: string} userMetrics?: {[key: string]: string}
}): Promise<SampleState> { }): Promise<SampleState> {
var sampleProviders: Provider[] = [ const sampleProviders: Provider[] = [
_DEFAULT_PROVIDERS, this._defaultProviders, {provide: Options.SAMPLE_ID, useValue: id}, _DEFAULT_PROVIDERS, this._defaultProviders, {provide: Options.SAMPLE_ID, useValue: id},
{provide: Options.EXECUTE, useValue: execute} {provide: Options.EXECUTE, useValue: execute}
]; ];
@ -62,33 +62,33 @@ export class Runner {
sampleProviders.push(providers); sampleProviders.push(providers);
} }
var inj = ReflectiveInjector.resolveAndCreate(sampleProviders); const inj = ReflectiveInjector.resolveAndCreate(sampleProviders);
var adapter: WebDriverAdapter = inj.get(WebDriverAdapter); const adapter: WebDriverAdapter = inj.get(WebDriverAdapter);
return Promise return Promise
.all([adapter.capabilities(), adapter.executeScript('return window.navigator.userAgent;')]) .all([adapter.capabilities(), adapter.executeScript('return window.navigator.userAgent;')])
.then((args) => { .then((args) => {
var capabilities = args[0]; const capabilities = args[0];
var userAgent = args[1]; const userAgent = args[1];
// This might still create instances twice. We are creating a new injector with all the // This might still create instances twice. We are creating a new injector with all the
// providers. // providers.
// Only WebDriverAdapter is reused. // Only WebDriverAdapter is reused.
// TODO vsavkin consider changing it when toAsyncFactory is added back or when child // TODO vsavkin consider changing it when toAsyncFactory is added back or when child
// injectors are handled better. // injectors are handled better.
var injector = ReflectiveInjector.resolveAndCreate([ const injector = ReflectiveInjector.resolveAndCreate([
sampleProviders, {provide: Options.CAPABILITIES, useValue: capabilities}, sampleProviders, {provide: Options.CAPABILITIES, useValue: capabilities},
{provide: Options.USER_AGENT, useValue: userAgent}, {provide: Options.USER_AGENT, useValue: userAgent},
{provide: WebDriverAdapter, useValue: adapter} {provide: WebDriverAdapter, useValue: adapter}
]); ]);
var sampler = injector.get(Sampler); const sampler = injector.get(Sampler);
return sampler.sample(); return sampler.sample();
}); });
} }
} }
var _DEFAULT_PROVIDERS = [ const _DEFAULT_PROVIDERS = [
Options.DEFAULT_PROVIDERS, Options.DEFAULT_PROVIDERS,
Sampler.PROVIDERS, Sampler.PROVIDERS,
ConsoleReporter.PROVIDERS, ConsoleReporter.PROVIDERS,

View File

@ -9,7 +9,6 @@
import {OpaqueToken} from '@angular/core'; import {OpaqueToken} from '@angular/core';
import {Options} from './common_options'; import {Options} from './common_options';
import {StringMapWrapper} from './facade/collection';
import {Metric} from './metric'; import {Metric} from './metric';
import {Validator} from './validator'; import {Validator} from './validator';
@ -42,7 +41,7 @@ export class SampleDescription {
public metrics: {[key: string]: any}) { public metrics: {[key: string]: any}) {
this.description = {}; this.description = {};
descriptions.forEach(description => { descriptions.forEach(description => {
StringMapWrapper.forEach(description, (value, prop) => this.description[prop] = value); Object.keys(description).forEach(prop => { this.description[prop] = description[prop]; });
}); });
} }

View File

@ -6,10 +6,10 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {Inject, Injectable, OpaqueToken} from '@angular/core'; import {Inject, Injectable} from '@angular/core';
import {Options} from './common_options'; import {Options} from './common_options';
import {Date, DateWrapper, isBlank, isPresent} from './facade/lang'; import {isPresent} from './facade/lang';
import {MeasureValues} from './measure_values'; import {MeasureValues} from './measure_values';
import {Metric} from './metric'; import {Metric} from './metric';
import {Reporter} from './reporter'; import {Reporter} from './reporter';
@ -49,7 +49,7 @@ export class Sampler {
} }
private _iterate(lastState: SampleState): Promise<SampleState> { private _iterate(lastState: SampleState): Promise<SampleState> {
var resultPromise: Promise<SampleState>; let resultPromise: Promise<SampleState>;
if (this._prepare !== Options.NO_PREPARE) { if (this._prepare !== Options.NO_PREPARE) {
resultPromise = this._driver.waitFor(this._prepare); resultPromise = this._driver.waitFor(this._prepare);
} else { } else {
@ -64,10 +64,10 @@ export class Sampler {
} }
private _report(state: SampleState, metricValues: {[key: string]: any}): Promise<SampleState> { private _report(state: SampleState, metricValues: {[key: string]: any}): Promise<SampleState> {
var measureValues = new MeasureValues(state.completeSample.length, this._now(), metricValues); const measureValues = new MeasureValues(state.completeSample.length, this._now(), metricValues);
var completeSample = state.completeSample.concat([measureValues]); const completeSample = state.completeSample.concat([measureValues]);
var validSample = this._validator.validate(completeSample); const validSample = this._validator.validate(completeSample);
var resultPromise = this._reporter.reportMeasureValues(measureValues); let resultPromise = this._reporter.reportMeasureValues(measureValues);
if (isPresent(validSample)) { if (isPresent(validSample)) {
resultPromise = resultPromise =
resultPromise.then((_) => this._reporter.reportSample(completeSample, validSample)); resultPromise.then((_) => this._reporter.reportSample(completeSample, validSample));

View File

@ -6,22 +6,20 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {Math} from './facade/math';
export class Statistic { export class Statistic {
static calculateCoefficientOfVariation(sample: number[], mean: number) { static calculateCoefficientOfVariation(sample: number[], mean: number) {
return Statistic.calculateStandardDeviation(sample, mean) / mean * 100; return Statistic.calculateStandardDeviation(sample, mean) / mean * 100;
} }
static calculateMean(samples: number[]) { static calculateMean(samples: number[]) {
var total = 0; let total = 0;
// TODO: use reduce // TODO: use reduce
samples.forEach(x => total += x); samples.forEach(x => total += x);
return total / samples.length; return total / samples.length;
} }
static calculateStandardDeviation(samples: number[], mean: number) { static calculateStandardDeviation(samples: number[], mean: number) {
var deviation = 0; let deviation = 0;
// TODO: use reduce // TODO: use reduce
samples.forEach(x => deviation += Math.pow(x - mean, 2)); samples.forEach(x => deviation += Math.pow(x - mean, 2));
deviation = deviation / (samples.length); deviation = deviation / (samples.length);
@ -32,9 +30,9 @@ export class Statistic {
static calculateRegressionSlope( static calculateRegressionSlope(
xValues: number[], xMean: number, yValues: number[], yMean: number) { xValues: number[], xMean: number, yValues: number[], yMean: number) {
// See http://en.wikipedia.org/wiki/Simple_linear_regression // See http://en.wikipedia.org/wiki/Simple_linear_regression
var dividendSum = 0; let dividendSum = 0;
var divisorSum = 0; let divisorSum = 0;
for (var i = 0; i < xValues.length; i++) { for (let i = 0; i < xValues.length; i++) {
dividendSum += (xValues[i] - xMean) * (yValues[i] - yMean); dividendSum += (xValues[i] - xMean) * (yValues[i] - yMean);
divisorSum += Math.pow(xValues[i] - xMean, 2); divisorSum += Math.pow(xValues[i] - xMean, 2);
} }

View File

@ -8,13 +8,10 @@
import {Inject, Injectable, OpaqueToken} from '@angular/core'; import {Inject, Injectable, OpaqueToken} from '@angular/core';
import {ListWrapper} from '../facade/collection';
import {MeasureValues} from '../measure_values'; import {MeasureValues} from '../measure_values';
import {Statistic} from '../statistic'; import {Statistic} from '../statistic';
import {Validator} from '../validator'; import {Validator} from '../validator';
/** /**
* A validator that checks the regression slope of a specific metric. * A validator that checks the regression slope of a specific metric.
* Waits for the regression slope to be >=0. * Waits for the regression slope to be >=0.
@ -40,17 +37,17 @@ export class RegressionSlopeValidator extends Validator {
validate(completeSample: MeasureValues[]): MeasureValues[] { validate(completeSample: MeasureValues[]): MeasureValues[] {
if (completeSample.length >= this._sampleSize) { if (completeSample.length >= this._sampleSize) {
var latestSample = ListWrapper.slice( const latestSample =
completeSample, completeSample.length - this._sampleSize, completeSample.length); completeSample.slice(completeSample.length - this._sampleSize, completeSample.length);
var xValues: number[] = []; const xValues: number[] = [];
var yValues: number[] = []; const yValues: number[] = [];
for (var i = 0; i < latestSample.length; i++) { for (let i = 0; i < latestSample.length; i++) {
// For now, we only use the array index as x value. // For now, we only use the array index as x value.
// TODO(tbosch): think about whether we should use time here instead // TODO(tbosch): think about whether we should use time here instead
xValues.push(i); xValues.push(i);
yValues.push(latestSample[i].values[this._metric]); yValues.push(latestSample[i].values[this._metric]);
} }
var regressionSlope = Statistic.calculateRegressionSlope( const regressionSlope = Statistic.calculateRegressionSlope(
xValues, Statistic.calculateMean(xValues), yValues, Statistic.calculateMean(yValues)); xValues, Statistic.calculateMean(xValues), yValues, Statistic.calculateMean(yValues));
return regressionSlope >= 0 ? latestSample : null; return regressionSlope >= 0 ? latestSample : null;
} else { } else {

View File

@ -8,12 +8,9 @@
import {Inject, Injectable, OpaqueToken} from '@angular/core'; import {Inject, Injectable, OpaqueToken} from '@angular/core';
import {ListWrapper} from '../facade/collection';
import {MeasureValues} from '../measure_values'; import {MeasureValues} from '../measure_values';
import {Validator} from '../validator'; import {Validator} from '../validator';
/** /**
* A validator that waits for the sample to have a certain size. * A validator that waits for the sample to have a certain size.
*/ */
@ -28,8 +25,7 @@ export class SizeValidator extends Validator {
validate(completeSample: MeasureValues[]): MeasureValues[] { validate(completeSample: MeasureValues[]): MeasureValues[] {
if (completeSample.length >= this._sampleSize) { if (completeSample.length >= this._sampleSize) {
return ListWrapper.slice( return completeSample.slice(completeSample.length - this._sampleSize, completeSample.length);
completeSample, completeSample.length - this._sampleSize, completeSample.length);
} else { } else {
return null; return null;
} }

View File

@ -9,7 +9,6 @@
import {Injector, OpaqueToken} from '@angular/core'; import {Injector, OpaqueToken} from '@angular/core';
import {Options} from './common_options'; import {Options} from './common_options';
import {isBlank, isPresent} from './facade/lang';
export type PerfLogEvent = { export type PerfLogEvent = {
[key: string]: any [key: string]: any
@ -35,7 +34,7 @@ export type PerfLogEvent = {
*/ */
export abstract class WebDriverExtension { export abstract class WebDriverExtension {
static provideFirstSupported(childTokens: any[]): any[] { static provideFirstSupported(childTokens: any[]): any[] {
var res = [ const res = [
{ {
provide: _CHILDREN, provide: _CHILDREN,
useFactory: (injector: Injector) => childTokens.map(token => injector.get(token)), useFactory: (injector: Injector) => childTokens.map(token => injector.get(token)),
@ -44,13 +43,13 @@ export abstract class WebDriverExtension {
{ {
provide: WebDriverExtension, provide: WebDriverExtension,
useFactory: (children: WebDriverExtension[], capabilities: {[key: string]: any}) => { useFactory: (children: WebDriverExtension[], capabilities: {[key: string]: any}) => {
var delegate: WebDriverExtension; let delegate: WebDriverExtension;
children.forEach(extension => { children.forEach(extension => {
if (extension.supports(capabilities)) { if (extension.supports(capabilities)) {
delegate = extension; delegate = extension;
} }
}); });
if (isBlank(delegate)) { if (!delegate) {
throw new Error('Could not find a delegate for given capabilities!'); throw new Error('Could not find a delegate for given capabilities!');
} }
return delegate; return delegate;
@ -102,4 +101,4 @@ export class PerfLogFeatures {
} }
} }
var _CHILDREN = new OpaqueToken('WebDriverExtension.children'); const _CHILDREN = new OpaqueToken('WebDriverExtension.children');

View File

@ -34,7 +34,7 @@ export class ChromeDriverExtension extends WebDriverExtension {
if (!userAgent) { if (!userAgent) {
return -1; return -1;
} }
var v = userAgent.split(/Chrom(e|ium)\//g)[2]; let v = userAgent.split(/Chrom(e|ium)\//g)[2];
if (!v) { if (!v) {
return -1; return -1;
} }
@ -52,7 +52,7 @@ export class ChromeDriverExtension extends WebDriverExtension {
} }
timeEnd(name: string, restartName: string = null): Promise<any> { timeEnd(name: string, restartName: string = null): Promise<any> {
var script = `console.timeEnd('${name}');`; let script = `console.timeEnd('${name}');`;
if (restartName) { if (restartName) {
script += `console.time('${restartName}');`; script += `console.time('${restartName}');`;
} }
@ -67,9 +67,9 @@ export class ChromeDriverExtension extends WebDriverExtension {
return this._driver.executeScript('1+1') return this._driver.executeScript('1+1')
.then((_) => this._driver.logs('performance')) .then((_) => this._driver.logs('performance'))
.then((entries) => { .then((entries) => {
var events: PerfLogEvent[] = []; const events: PerfLogEvent[] = [];
entries.forEach(entry => { entries.forEach(entry => {
var message = JSON.parse(entry['message'])['message']; const message = JSON.parse(entry['message'])['message'];
if (message['method'] === 'Tracing.dataCollected') { if (message['method'] === 'Tracing.dataCollected') {
events.push(message['params']); events.push(message['params']);
} }
@ -95,8 +95,8 @@ export class ChromeDriverExtension extends WebDriverExtension {
} }
private _convertEvent(event: {[key: string]: any}, categories: string[]) { private _convertEvent(event: {[key: string]: any}, categories: string[]) {
var name = event['name']; const name = event['name'];
var args = event['args']; const args = event['args'];
if (this._isEvent(categories, name, ['blink.console'])) { if (this._isEvent(categories, name, ['blink.console'])) {
return normalizeEvent(event, {'name': name}); return normalizeEvent(event, {'name': name});
} else if (this._isEvent( } else if (this._isEvent(
@ -109,7 +109,7 @@ export class ChromeDriverExtension extends WebDriverExtension {
// new surfaces framework (not broadly enabled yet) // new surfaces framework (not broadly enabled yet)
// 3rd choice: BenchmarkInstrumentation::ImplThreadRenderingStats - fallback event that is // 3rd choice: BenchmarkInstrumentation::ImplThreadRenderingStats - fallback event that is
// always available if something is rendered // always available if something is rendered
var frameCount = event['args']['data']['frame_count']; const frameCount = event['args']['data']['frame_count'];
if (frameCount > 1) { if (frameCount > 1) {
throw new Error('multi-frame render stats not supported'); throw new Error('multi-frame render stats not supported');
} }
@ -122,14 +122,14 @@ export class ChromeDriverExtension extends WebDriverExtension {
categories, name, ['disabled-by-default-devtools.timeline'], 'CompositeLayers')) { categories, name, ['disabled-by-default-devtools.timeline'], 'CompositeLayers')) {
return normalizeEvent(event, {'name': 'render'}); return normalizeEvent(event, {'name': 'render'});
} else if (this._isEvent(categories, name, ['devtools.timeline', 'v8'], 'MajorGC')) { } else if (this._isEvent(categories, name, ['devtools.timeline', 'v8'], 'MajorGC')) {
var normArgs = { const normArgs = {
'majorGc': true, 'majorGc': true,
'usedHeapSize': args['usedHeapSizeAfter'] !== undefined ? args['usedHeapSizeAfter'] : 'usedHeapSize': args['usedHeapSizeAfter'] !== undefined ? args['usedHeapSizeAfter'] :
args['usedHeapSizeBefore'] args['usedHeapSizeBefore']
}; };
return normalizeEvent(event, {'name': 'gc', 'args': normArgs}); return normalizeEvent(event, {'name': 'gc', 'args': normArgs});
} else if (this._isEvent(categories, name, ['devtools.timeline', 'v8'], 'MinorGC')) { } else if (this._isEvent(categories, name, ['devtools.timeline', 'v8'], 'MinorGC')) {
var normArgs = { const normArgs = {
'majorGc': false, 'majorGc': false,
'usedHeapSize': args['usedHeapSizeAfter'] !== undefined ? args['usedHeapSizeAfter'] : 'usedHeapSize': args['usedHeapSizeAfter'] !== undefined ? args['usedHeapSizeAfter'] :
args['usedHeapSizeBefore'] args['usedHeapSizeBefore']
@ -151,11 +151,11 @@ export class ChromeDriverExtension extends WebDriverExtension {
this._isEvent(categories, name, ['devtools.timeline'], 'Paint')) { this._isEvent(categories, name, ['devtools.timeline'], 'Paint')) {
return normalizeEvent(event, {'name': 'render'}); return normalizeEvent(event, {'name': 'render'});
} else if (this._isEvent(categories, name, ['devtools.timeline'], 'ResourceReceivedData')) { } else if (this._isEvent(categories, name, ['devtools.timeline'], 'ResourceReceivedData')) {
let normArgs = {'encodedDataLength': args['data']['encodedDataLength']}; const normArgs = {'encodedDataLength': args['data']['encodedDataLength']};
return normalizeEvent(event, {'name': 'receivedData', 'args': normArgs}); return normalizeEvent(event, {'name': 'receivedData', 'args': normArgs});
} else if (this._isEvent(categories, name, ['devtools.timeline'], 'ResourceSendRequest')) { } else if (this._isEvent(categories, name, ['devtools.timeline'], 'ResourceSendRequest')) {
let data = args['data']; const data = args['data'];
let normArgs = {'url': data['url'], 'method': data['requestMethod']}; const normArgs = {'url': data['url'], 'method': data['requestMethod']};
return normalizeEvent(event, {'name': 'sendRequest', 'args': normArgs}); return normalizeEvent(event, {'name': 'sendRequest', 'args': normArgs});
} else if (this._isEvent(categories, name, ['blink.user_timing'], 'navigationStart')) { } else if (this._isEvent(categories, name, ['blink.user_timing'], 'navigationStart')) {
return normalizeEvent(event, {'name': 'navigationStart'}); return normalizeEvent(event, {'name': 'navigationStart'});
@ -168,8 +168,8 @@ export class ChromeDriverExtension extends WebDriverExtension {
private _isEvent( private _isEvent(
eventCategories: string[], eventName: string, expectedCategories: string[], eventCategories: string[], eventName: string, expectedCategories: string[],
expectedName: string = null): boolean { expectedName: string = null): boolean {
var hasCategories = expectedCategories.reduce( const hasCategories = expectedCategories.reduce(
(value, cat) => { return value && eventCategories.indexOf(cat) !== -1; }, true); (value, cat) => value && eventCategories.indexOf(cat) !== -1, true);
return !expectedName ? hasCategories : hasCategories && eventName === expectedName; return !expectedName ? hasCategories : hasCategories && eventName === expectedName;
} }
@ -183,7 +183,7 @@ export class ChromeDriverExtension extends WebDriverExtension {
} }
function normalizeEvent(chromeEvent: {[key: string]: any}, data: PerfLogEvent): PerfLogEvent { function normalizeEvent(chromeEvent: {[key: string]: any}, data: PerfLogEvent): PerfLogEvent {
var ph = chromeEvent['ph'].toUpperCase(); let ph = chromeEvent['ph'].toUpperCase();
if (ph === 'S') { if (ph === 'S') {
ph = 'B'; ph = 'B';
} else if (ph === 'F') { } else if (ph === 'F') {
@ -192,16 +192,16 @@ function normalizeEvent(chromeEvent: {[key: string]: any}, data: PerfLogEvent):
// mark events from navigation timing // mark events from navigation timing
ph = 'I'; ph = 'I';
} }
var result: {[key: string]: any} = const result: {[key: string]: any} =
{'pid': chromeEvent['pid'], 'ph': ph, 'cat': 'timeline', 'ts': chromeEvent['ts'] / 1000}; {'pid': chromeEvent['pid'], 'ph': ph, 'cat': 'timeline', 'ts': chromeEvent['ts'] / 1000};
if (ph === 'X') { if (ph === 'X') {
var dur = chromeEvent['dur']; let dur = chromeEvent['dur'];
if (dur === undefined) { if (dur === undefined) {
dur = chromeEvent['tdur']; dur = chromeEvent['tdur'];
} }
result['dur'] = !dur ? 0.0 : dur / 1000; result['dur'] = !dur ? 0.0 : dur / 1000;
} }
for (let prop in data) { for (const prop in data) {
result[prop] = data[prop]; result[prop] = data[prop];
} }
return result; return result;

View File

@ -8,7 +8,7 @@
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {StringWrapper, isPresent} from '../facade/lang'; import {isPresent} from '../facade/lang';
import {WebDriverAdapter} from '../web_driver_adapter'; import {WebDriverAdapter} from '../web_driver_adapter';
import {PerfLogEvent, PerfLogFeatures, WebDriverExtension} from '../web_driver_extension'; import {PerfLogEvent, PerfLogFeatures, WebDriverExtension} from '../web_driver_extension';
@ -34,7 +34,7 @@ export class FirefoxDriverExtension extends WebDriverExtension {
} }
timeEnd(name: string, restartName: string = null): Promise<any> { timeEnd(name: string, restartName: string = null): Promise<any> {
var script = 'window.markEnd("' + name + '");'; let script = 'window.markEnd("' + name + '");';
if (isPresent(restartName)) { if (isPresent(restartName)) {
script += 'window.markStart("' + restartName + '");'; script += 'window.markStart("' + restartName + '");';
} }
@ -48,6 +48,6 @@ export class FirefoxDriverExtension extends WebDriverExtension {
perfLogFeatures(): PerfLogFeatures { return new PerfLogFeatures({render: true, gc: true}); } perfLogFeatures(): PerfLogFeatures { return new PerfLogFeatures({render: true, gc: true}); }
supports(capabilities: {[key: string]: any}): boolean { supports(capabilities: {[key: string]: any}): boolean {
return StringWrapper.equals(capabilities['browserName'].toLowerCase(), 'firefox'); return capabilities['browserName'].toLowerCase() === 'firefox';
} }
} }

View File

@ -8,7 +8,7 @@
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {StringWrapper, isBlank, isPresent} from '../facade/lang'; import {isBlank, isPresent} from '../facade/lang';
import {WebDriverAdapter} from '../web_driver_adapter'; import {WebDriverAdapter} from '../web_driver_adapter';
import {PerfLogEvent, PerfLogFeatures, WebDriverExtension} from '../web_driver_extension'; import {PerfLogEvent, PerfLogFeatures, WebDriverExtension} from '../web_driver_extension';
@ -25,7 +25,7 @@ export class IOsDriverExtension extends WebDriverExtension {
} }
timeEnd(name: string, restartName: string = null): Promise<any> { timeEnd(name: string, restartName: string = null): Promise<any> {
var script = `console.timeEnd('${name}');`; let script = `console.timeEnd('${name}');`;
if (isPresent(restartName)) { if (isPresent(restartName)) {
script += `console.time('${restartName}');`; script += `console.time('${restartName}');`;
} }
@ -39,10 +39,10 @@ export class IOsDriverExtension extends WebDriverExtension {
return this._driver.executeScript('1+1') return this._driver.executeScript('1+1')
.then((_) => this._driver.logs('performance')) .then((_) => this._driver.logs('performance'))
.then((entries) => { .then((entries) => {
var records: any[] = []; const records: any[] = [];
entries.forEach(entry => { entries.forEach(entry => {
var message = JSON.parse(entry['message'])['message']; const message = JSON.parse(entry['message'])['message'];
if (StringWrapper.equals(message['method'], 'Timeline.eventRecorded')) { if (message['method'] === 'Timeline.eventRecorded') {
records.push(message['params']['record']); records.push(message['params']['record']);
} }
}); });
@ -52,29 +52,26 @@ export class IOsDriverExtension extends WebDriverExtension {
/** @internal */ /** @internal */
private _convertPerfRecordsToEvents(records: any[], events: PerfLogEvent[] = null) { private _convertPerfRecordsToEvents(records: any[], events: PerfLogEvent[] = null) {
if (isBlank(events)) { if (!events) {
events = []; events = [];
} }
records.forEach((record) => { records.forEach((record) => {
var endEvent: PerfLogEvent = null; let endEvent: PerfLogEvent = null;
var type = record['type']; const type = record['type'];
var data = record['data']; const data = record['data'];
var startTime = record['startTime']; const startTime = record['startTime'];
var endTime = record['endTime']; const endTime = record['endTime'];
if (StringWrapper.equals(type, 'FunctionCall') && if (type === 'FunctionCall' && (data == null || data['scriptName'] !== 'InjectedScript')) {
(isBlank(data) || !StringWrapper.equals(data['scriptName'], 'InjectedScript'))) {
events.push(createStartEvent('script', startTime)); events.push(createStartEvent('script', startTime));
endEvent = createEndEvent('script', endTime); endEvent = createEndEvent('script', endTime);
} else if (StringWrapper.equals(type, 'Time')) { } else if (type === 'Time') {
events.push(createMarkStartEvent(data['message'], startTime)); events.push(createMarkStartEvent(data['message'], startTime));
} else if (StringWrapper.equals(type, 'TimeEnd')) { } else if (type === 'TimeEnd') {
events.push(createMarkEndEvent(data['message'], startTime)); events.push(createMarkEndEvent(data['message'], startTime));
} else if ( } else if (
StringWrapper.equals(type, 'RecalculateStyles') || StringWrapper.equals(type, 'Layout') || type === 'RecalculateStyles' || type === 'Layout' || type === 'UpdateLayerTree' ||
StringWrapper.equals(type, 'UpdateLayerTree') || StringWrapper.equals(type, 'Paint') || type === 'Paint' || type === 'Rasterize' || type === 'CompositeLayers') {
StringWrapper.equals(type, 'Rasterize') ||
StringWrapper.equals(type, 'CompositeLayers')) {
events.push(createStartEvent('render', startTime)); events.push(createStartEvent('render', startTime));
endEvent = createEndEvent('render', endTime); endEvent = createEndEvent('render', endTime);
} }
@ -92,13 +89,13 @@ export class IOsDriverExtension extends WebDriverExtension {
perfLogFeatures(): PerfLogFeatures { return new PerfLogFeatures({render: true}); } perfLogFeatures(): PerfLogFeatures { return new PerfLogFeatures({render: true}); }
supports(capabilities: {[key: string]: any}): boolean { supports(capabilities: {[key: string]: any}): boolean {
return StringWrapper.equals(capabilities['browserName'].toLowerCase(), 'safari'); return capabilities['browserName'].toLowerCase() === 'safari';
} }
} }
function createEvent( function createEvent(
ph: 'X' | 'B' | 'E' | 'B' | 'E', name: string, time: number, args: any = null) { ph: 'X' | 'B' | 'E' | 'B' | 'E', name: string, time: number, args: any = null) {
var result: PerfLogEvent = { const result: PerfLogEvent = {
'cat': 'timeline', 'cat': 'timeline',
'name': name, 'name': name,
'ts': time, 'ts': time,

View File

@ -8,7 +8,7 @@
require('core-js'); require('core-js');
require('reflect-metadata'); require('reflect-metadata');
var testHelper = require('../../src/firefox_extension/lib/test_helper.js'); const testHelper = require('../../src/firefox_extension/lib/test_helper.js');
exports.config = { exports.config = {
specs: ['spec.js', 'sample_benchmark.js'], specs: ['spec.js', 'sample_benchmark.js'],

View File

@ -10,10 +10,10 @@ import {convertPerfProfileToEvents} from '../../src/firefox_extension/lib/parser
function assertEventsEqual(actualEvents: any[], expectedEvents: any[]) { function assertEventsEqual(actualEvents: any[], expectedEvents: any[]) {
expect(actualEvents.length == expectedEvents.length); expect(actualEvents.length == expectedEvents.length);
for (var i = 0; i < actualEvents.length; ++i) { for (let i = 0; i < actualEvents.length; ++i) {
var actualEvent = actualEvents[i]; const actualEvent = actualEvents[i];
var expectedEvent = expectedEvents[i]; const expectedEvent = expectedEvents[i];
for (var key in actualEvent) { for (const key in actualEvent) {
expect(actualEvent[key]).toEqual(expectedEvent[key]); expect(actualEvent[key]).toEqual(expectedEvent[key]);
} }
} }
@ -22,17 +22,17 @@ function assertEventsEqual(actualEvents: any[], expectedEvents: any[]) {
export function main() { export function main() {
describe('convertPerfProfileToEvents', function() { describe('convertPerfProfileToEvents', function() {
it('should convert single instantaneous event', function() { it('should convert single instantaneous event', function() {
var profileData = { const profileData = {
threads: [ threads: [
{samples: [{time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}]} {samples: [{time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}]}
] ]
}; };
var perfEvents = convertPerfProfileToEvents(profileData); const perfEvents = convertPerfProfileToEvents(profileData);
assertEventsEqual(perfEvents, [{ph: 'X', ts: 1, name: 'script'}]); assertEventsEqual(perfEvents, [{ph: 'X', ts: 1, name: 'script'}]);
}); });
it('should convert single non-instantaneous event', function() { it('should convert single non-instantaneous event', function() {
var profileData = { const profileData = {
threads: [{ threads: [{
samples: [ samples: [
{time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]},
@ -41,13 +41,13 @@ export function main() {
] ]
}] }]
}; };
var perfEvents = convertPerfProfileToEvents(profileData); const perfEvents = convertPerfProfileToEvents(profileData);
assertEventsEqual( assertEventsEqual(
perfEvents, [{ph: 'B', ts: 1, name: 'script'}, {ph: 'E', ts: 100, name: 'script'}]); perfEvents, [{ph: 'B', ts: 1, name: 'script'}, {ph: 'E', ts: 100, name: 'script'}]);
}); });
it('should convert multiple instantaneous events', function() { it('should convert multiple instantaneous events', function() {
var profileData = { const profileData = {
threads: [{ threads: [{
samples: [ samples: [
{time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]},
@ -55,13 +55,13 @@ export function main() {
] ]
}] }]
}; };
var perfEvents = convertPerfProfileToEvents(profileData); const perfEvents = convertPerfProfileToEvents(profileData);
assertEventsEqual( assertEventsEqual(
perfEvents, [{ph: 'X', ts: 1, name: 'script'}, {ph: 'X', ts: 2, name: 'render'}]); perfEvents, [{ph: 'X', ts: 1, name: 'script'}, {ph: 'X', ts: 2, name: 'render'}]);
}); });
it('should convert multiple mixed events', function() { it('should convert multiple mixed events', function() {
var profileData = { const profileData = {
threads: [{ threads: [{
samples: [ samples: [
{time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]},
@ -71,7 +71,7 @@ export function main() {
] ]
}] }]
}; };
var perfEvents = convertPerfProfileToEvents(profileData); const perfEvents = convertPerfProfileToEvents(profileData);
assertEventsEqual(perfEvents, [ assertEventsEqual(perfEvents, [
{ph: 'X', ts: 1, name: 'script'}, {ph: 'X', ts: 2, name: 'render'}, {ph: 'X', ts: 1, name: 'script'}, {ph: 'X', ts: 2, name: 'render'},
{ph: 'B', ts: 5, name: 'script'}, {ph: 'E', ts: 10, name: 'script'} {ph: 'B', ts: 5, name: 'script'}, {ph: 'E', ts: 10, name: 'script'}
@ -79,13 +79,13 @@ export function main() {
}); });
it('should add args to gc events', function() { it('should add args to gc events', function() {
var profileData = {threads: [{samples: [{time: 1, frames: [{location: 'forceGC'}]}]}]}; const profileData = {threads: [{samples: [{time: 1, frames: [{location: 'forceGC'}]}]}]};
var perfEvents = convertPerfProfileToEvents(profileData); const perfEvents = convertPerfProfileToEvents(profileData);
assertEventsEqual(perfEvents, [{ph: 'X', ts: 1, name: 'gc', args: {usedHeapSize: 0}}]); assertEventsEqual(perfEvents, [{ph: 'X', ts: 1, name: 'gc', args: {usedHeapSize: 0}}]);
}); });
it('should skip unknown events', function() { it('should skip unknown events', function() {
var profileData = { const profileData = {
threads: [{ threads: [{
samples: [ samples: [
{time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]},
@ -93,7 +93,7 @@ export function main() {
] ]
}] }]
}; };
var perfEvents = convertPerfProfileToEvents(profileData); const perfEvents = convertPerfProfileToEvents(profileData);
assertEventsEqual(perfEvents, [{ph: 'X', ts: 1, name: 'script'}]); assertEventsEqual(perfEvents, [{ph: 'X', ts: 1, name: 'script'}]);
}); });
}); });

View File

@ -6,8 +6,10 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
var benchpress = require('../../index.js'); import {$, browser} from 'protractor';
var runner = new benchpress.Runner([
const benchpress = require('../../index.js');
const runner = new benchpress.Runner([
// use protractor as Webdriver client // use protractor as Webdriver client
benchpress.SeleniumWebDriverAdapter.PROTRACTOR_PROVIDERS, benchpress.SeleniumWebDriverAdapter.PROTRACTOR_PROVIDERS,
// use RegressionSlopeValidator to validate samples // use RegressionSlopeValidator to validate samples

View File

@ -6,9 +6,12 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
var assertEventsContainsName = function(events: any[], eventName: string) { /* tslint:disable:no-console */
var found = false; import {browser} from 'protractor';
for (var i = 0; i < events.length; ++i) {
const assertEventsContainsName = function(events: any[], eventName: string) {
let found = false;
for (let i = 0; i < events.length; ++i) {
if (events[i].name == eventName) { if (events[i].name == eventName) {
found = true; found = true;
break; break;
@ -18,7 +21,7 @@ var assertEventsContainsName = function(events: any[], eventName: string) {
}; };
describe('firefox extension', function() { describe('firefox extension', function() {
var TEST_URL = 'http://localhost:8001/playground/src/hello_world/index.html'; const TEST_URL = 'http://localhost:8001/playground/src/hello_world/index.html';
it('should measure performance', function() { it('should measure performance', function() {
browser.sleep(3000); // wait for extension to load browser.sleep(3000); // wait for extension to load

View File

@ -6,17 +6,17 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {Metric, MultiMetric, ReflectiveInjector} from '../../index'; import {Metric, MultiMetric, ReflectiveInjector} from '../../index';
export function main() { export function main() {
function createMetric(ids: any[]) { function createMetric(ids: any[]) {
var m = ReflectiveInjector const m = ReflectiveInjector
.resolveAndCreate([ .resolveAndCreate([
ids.map(id => { return {provide: id, useValue: new MockMetric(id)}; }), ids.map(id => ({provide: id, useValue: new MockMetric(id)})),
MultiMetric.provideWith(ids) MultiMetric.provideWith(ids)
]) ])
.get(MultiMetric); .get(MultiMetric);
return Promise.resolve(m); return Promise.resolve(m);
} }
@ -56,13 +56,13 @@ class MockMetric extends Metric {
beginMeasure(): Promise<string> { return Promise.resolve(`${this._id}_beginMeasure`); } beginMeasure(): Promise<string> { return Promise.resolve(`${this._id}_beginMeasure`); }
endMeasure(restart: boolean): Promise<{[key: string]: any}> { endMeasure(restart: boolean): Promise<{[key: string]: any}> {
var result: {[key: string]: any} = {}; const result: {[key: string]: any} = {};
result[this._id] = {'restart': restart}; result[this._id] = {'restart': restart};
return Promise.resolve(result); return Promise.resolve(result);
} }
describe(): {[key: string]: string} { describe(): {[key: string]: string} {
var result: {[key: string]: string} = {}; const result: {[key: string]: string} = {};
result[this._id] = 'describe'; result[this._id] = 'describe';
return result; return result;
} }

View File

@ -7,16 +7,15 @@
*/ */
import {Provider} from '@angular/core'; import {Provider} from '@angular/core';
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, beforeEach, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {Metric, Options, PerfLogEvent, PerfLogFeatures, PerflogMetric, ReflectiveInjector, WebDriverExtension} from '../../index'; import {Metric, Options, PerfLogEvent, PerfLogFeatures, PerflogMetric, ReflectiveInjector, WebDriverExtension} from '../../index';
import {StringMapWrapper} from '../../src/facade/collection'; import {isPresent} from '../../src/facade/lang';
import {isBlank, isPresent} from '../../src/facade/lang';
import {TraceEventFactory} from '../trace_event_factory'; import {TraceEventFactory} from '../trace_event_factory';
export function main() { export function main() {
var commandLog: any[]; let commandLog: any[];
var eventFactory = new TraceEventFactory('timeline', 'pid0'); const eventFactory = new TraceEventFactory('timeline', 'pid0');
function createMetric( function createMetric(
perfLogs: PerfLogEvent[], perfLogFeatures: PerfLogFeatures, perfLogs: PerfLogEvent[], perfLogFeatures: PerfLogFeatures,
@ -28,14 +27,14 @@ export function main() {
requestCount?: boolean requestCount?: boolean
} = {}): Metric { } = {}): Metric {
commandLog = []; commandLog = [];
if (isBlank(perfLogFeatures)) { if (!perfLogFeatures) {
perfLogFeatures = perfLogFeatures =
new PerfLogFeatures({render: true, gc: true, frameCapture: true, userTiming: true}); new PerfLogFeatures({render: true, gc: true, frameCapture: true, userTiming: true});
} }
if (isBlank(microMetrics)) { if (!microMetrics) {
microMetrics = StringMapWrapper.create(); microMetrics = {};
} }
var providers: Provider[] = [ const providers: Provider[] = [
Options.DEFAULT_PROVIDERS, PerflogMetric.PROVIDERS, Options.DEFAULT_PROVIDERS, PerflogMetric.PROVIDERS,
{provide: Options.MICRO_METRICS, useValue: microMetrics}, { {provide: Options.MICRO_METRICS, useValue: microMetrics}, {
provide: PerflogMetric.SET_TIMEOUT, provide: PerflogMetric.SET_TIMEOUT,
@ -67,8 +66,8 @@ export function main() {
describe('perflog metric', () => { describe('perflog metric', () => {
function sortedKeys(stringMap: {[key: string]: any}) { function sortedKeys(stringMap: {[key: string]: any}) {
var res: string[] = []; const res: string[] = [];
StringMapWrapper.forEach(stringMap, (_, key) => { res.push(key); }); res.push(...Object.keys(stringMap));
res.sort(); res.sort();
return res; return res;
} }
@ -103,15 +102,15 @@ export function main() {
}); });
it('should describe itself based on micro metrics', () => { it('should describe itself based on micro metrics', () => {
var description = const description =
createMetric([[]], null, {microMetrics: {'myMicroMetric': 'someDesc'}}).describe(); createMetric([[]], null, {microMetrics: {'myMicroMetric': 'someDesc'}}).describe();
expect(description['myMicroMetric']).toEqual('someDesc'); expect(description['myMicroMetric']).toEqual('someDesc');
}); });
it('should describe itself if frame capture is requested and available', () => { it('should describe itself if frame capture is requested and available', () => {
var description = createMetric([[]], new PerfLogFeatures({frameCapture: true}), { const description = createMetric([[]], new PerfLogFeatures({frameCapture: true}), {
captureFrames: true captureFrames: true
}).describe(); }).describe();
expect(description['frameTime.mean']).not.toContain('WARNING'); expect(description['frameTime.mean']).not.toContain('WARNING');
expect(description['frameTime.best']).not.toContain('WARNING'); expect(description['frameTime.best']).not.toContain('WARNING');
expect(description['frameTime.worst']).not.toContain('WARNING'); expect(description['frameTime.worst']).not.toContain('WARNING');
@ -119,9 +118,9 @@ export function main() {
}); });
it('should describe itself if frame capture is requested and not available', () => { it('should describe itself if frame capture is requested and not available', () => {
var description = createMetric([[]], new PerfLogFeatures({frameCapture: false}), { const description = createMetric([[]], new PerfLogFeatures({frameCapture: false}), {
captureFrames: true captureFrames: true
}).describe(); }).describe();
expect(description['frameTime.mean']).toContain('WARNING'); expect(description['frameTime.mean']).toContain('WARNING');
expect(description['frameTime.best']).toContain('WARNING'); expect(description['frameTime.best']).toContain('WARNING');
expect(description['frameTime.worst']).toContain('WARNING'); expect(description['frameTime.worst']).toContain('WARNING');
@ -132,7 +131,7 @@ export function main() {
it('should not force gc and mark the timeline', it('should not force gc and mark the timeline',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var metric = createMetric([[]], null); const metric = createMetric([[]], null);
metric.beginMeasure().then((_) => { metric.beginMeasure().then((_) => {
expect(commandLog).toEqual([['timeBegin', 'benchpress0']]); expect(commandLog).toEqual([['timeBegin', 'benchpress0']]);
@ -142,7 +141,7 @@ export function main() {
it('should force gc and mark the timeline', it('should force gc and mark the timeline',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var metric = createMetric([[]], null, {forceGc: true}); const metric = createMetric([[]], null, {forceGc: true});
metric.beginMeasure().then((_) => { metric.beginMeasure().then((_) => {
expect(commandLog).toEqual([['gc'], ['timeBegin', 'benchpress0']]); expect(commandLog).toEqual([['gc'], ['timeBegin', 'benchpress0']]);
@ -156,11 +155,11 @@ export function main() {
it('should mark and aggregate events in between the marks', it('should mark and aggregate events in between the marks',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var events = [[ const events = [[
eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4),
eventFactory.end('script', 6), eventFactory.markEnd('benchpress0', 10) eventFactory.end('script', 6), eventFactory.markEnd('benchpress0', 10)
]]; ]];
var metric = createMetric(events, null); const metric = createMetric(events, null);
metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => {
expect(commandLog).toEqual([ expect(commandLog).toEqual([
['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', null], 'readPerfLog' ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', null], 'readPerfLog'
@ -173,13 +172,13 @@ export function main() {
it('should mark and aggregate events since navigationStart', it('should mark and aggregate events since navigationStart',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var events = [[ const events = [[
eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4),
eventFactory.end('script', 6), eventFactory.instant('navigationStart', 7), eventFactory.end('script', 6), eventFactory.instant('navigationStart', 7),
eventFactory.start('script', 8), eventFactory.end('script', 9), eventFactory.start('script', 8), eventFactory.end('script', 9),
eventFactory.markEnd('benchpress0', 10) eventFactory.markEnd('benchpress0', 10)
]]; ]];
var metric = createMetric(events, null); const metric = createMetric(events, null);
metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => {
expect(data['scriptTime']).toBe(1); expect(data['scriptTime']).toBe(1);
@ -188,7 +187,7 @@ export function main() {
})); }));
it('should restart timing', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { it('should restart timing', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var events = [ const events = [
[ [
eventFactory.markStart('benchpress0', 0), eventFactory.markStart('benchpress0', 0),
eventFactory.markEnd('benchpress0', 1), eventFactory.markEnd('benchpress0', 1),
@ -196,7 +195,7 @@ export function main() {
], ],
[eventFactory.markEnd('benchpress1', 3)] [eventFactory.markEnd('benchpress1', 3)]
]; ];
var metric = createMetric(events, null); const metric = createMetric(events, null);
metric.beginMeasure() metric.beginMeasure()
.then((_) => metric.endMeasure(true)) .then((_) => metric.endMeasure(true))
.then((_) => metric.endMeasure(true)) .then((_) => metric.endMeasure(true))
@ -212,7 +211,7 @@ export function main() {
it('should loop and aggregate until the end mark is present', it('should loop and aggregate until the end mark is present',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var events = [ const events = [
[eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 1)], [eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 1)],
[eventFactory.end('script', 2)], [eventFactory.end('script', 2)],
[ [
@ -220,7 +219,7 @@ export function main() {
eventFactory.markEnd('benchpress0', 10) eventFactory.markEnd('benchpress0', 10)
] ]
]; ];
var metric = createMetric(events, null); const metric = createMetric(events, null);
metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => {
expect(commandLog).toEqual([ expect(commandLog).toEqual([
['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', null], 'readPerfLog', ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', null], 'readPerfLog',
@ -234,7 +233,7 @@ export function main() {
it('should store events after the end mark for the next call', it('should store events after the end mark for the next call',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var events = [ const events = [
[ [
eventFactory.markStart('benchpress0', 0), eventFactory.markEnd('benchpress0', 1), eventFactory.markStart('benchpress0', 0), eventFactory.markEnd('benchpress0', 1),
eventFactory.markStart('benchpress1', 1), eventFactory.start('script', 1), eventFactory.markStart('benchpress1', 1), eventFactory.start('script', 1),
@ -245,7 +244,7 @@ export function main() {
eventFactory.markEnd('benchpress1', 6) eventFactory.markEnd('benchpress1', 6)
] ]
]; ];
var metric = createMetric(events, null); const metric = createMetric(events, null);
metric.beginMeasure() metric.beginMeasure()
.then((_) => metric.endMeasure(true)) .then((_) => metric.endMeasure(true))
.then((data) => { .then((data) => {
@ -264,7 +263,7 @@ export function main() {
})); }));
describe('with forced gc', () => { describe('with forced gc', () => {
var events: PerfLogEvent[][]; let events: PerfLogEvent[][];
beforeEach(() => { beforeEach(() => {
events = [[ events = [[
eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4),
@ -277,7 +276,7 @@ export function main() {
}); });
it('should measure forced gc', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { it('should measure forced gc', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var metric = createMetric(events, null, {forceGc: true}); const metric = createMetric(events, null, {forceGc: true});
metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => {
expect(commandLog).toEqual([ expect(commandLog).toEqual([
['gc'], ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', 'benchpress1'], ['gc'], ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', 'benchpress1'],
@ -292,7 +291,7 @@ export function main() {
it('should restart after the forced gc if needed', it('should restart after the forced gc if needed',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var metric = createMetric(events, null, {forceGc: true}); const metric = createMetric(events, null, {forceGc: true});
metric.beginMeasure().then((_) => metric.endMeasure(true)).then((data) => { metric.beginMeasure().then((_) => metric.endMeasure(true)).then((data) => {
expect(commandLog[5]).toEqual(['timeEnd', 'benchpress1', 'benchpress2']); expect(commandLog[5]).toEqual(['timeEnd', 'benchpress1', 'benchpress2']);
@ -314,7 +313,7 @@ export function main() {
} = {}) { } = {}) {
events.unshift(eventFactory.markStart('benchpress0', 0)); events.unshift(eventFactory.markStart('benchpress0', 0));
events.push(eventFactory.markEnd('benchpress0', 10)); events.push(eventFactory.markEnd('benchpress0', 10));
var metric = createMetric([events], null, { const metric = createMetric([events], null, {
microMetrics: microMetrics, microMetrics: microMetrics,
captureFrames: captureFrames, captureFrames: captureFrames,
receivedData: receivedData, receivedData: receivedData,
@ -503,8 +502,8 @@ export function main() {
it('should ignore events from different processed as the start mark', it('should ignore events from different processed as the start mark',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var otherProcessEventFactory = new TraceEventFactory('timeline', 'pid1'); const otherProcessEventFactory = new TraceEventFactory('timeline', 'pid1');
var metric = createMetric( const metric = createMetric(
[[ [[
eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 0, null), eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 0, null),
eventFactory.end('script', 5, null), eventFactory.end('script', 5, null),
@ -686,7 +685,7 @@ class MockDriverExtension extends WebDriverExtension {
readPerfLog(): Promise<any> { readPerfLog(): Promise<any> {
this._commandLog.push('readPerfLog'); this._commandLog.push('readPerfLog');
if (this._perfLogs.length > 0) { if (this._perfLogs.length > 0) {
var next = this._perfLogs[0]; const next = this._perfLogs[0];
this._perfLogs.shift(); this._perfLogs.shift();
return Promise.resolve(next); return Promise.resolve(next);
} else { } else {

View File

@ -7,27 +7,25 @@
*/ */
import {Provider, ReflectiveInjector} from '@angular/core'; import {Provider, ReflectiveInjector} from '@angular/core';
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {Injector, Metric, MultiMetric, Options, PerfLogEvent, PerfLogFeatures, PerflogMetric, UserMetric, WebDriverAdapter, WebDriverExtension} from '../../index'; import {Options, PerfLogEvent, PerfLogFeatures, UserMetric, WebDriverAdapter} from '../../index';
import {StringMapWrapper} from '../../src/facade/collection';
import {Json, isBlank, isPresent} from '../../src/facade/lang';
export function main() { export function main() {
var wdAdapter: MockDriverAdapter; let wdAdapter: MockDriverAdapter;
function createMetric( function createMetric(
perfLogs: PerfLogEvent[], perfLogFeatures: PerfLogFeatures, perfLogs: PerfLogEvent[], perfLogFeatures: PerfLogFeatures,
{userMetrics}: {userMetrics?: {[key: string]: string}} = {}): UserMetric { {userMetrics}: {userMetrics?: {[key: string]: string}} = {}): UserMetric {
if (isBlank(perfLogFeatures)) { if (!perfLogFeatures) {
perfLogFeatures = perfLogFeatures =
new PerfLogFeatures({render: true, gc: true, frameCapture: true, userTiming: true}); new PerfLogFeatures({render: true, gc: true, frameCapture: true, userTiming: true});
} }
if (isBlank(userMetrics)) { if (!userMetrics) {
userMetrics = StringMapWrapper.create(); userMetrics = {};
} }
wdAdapter = new MockDriverAdapter(); wdAdapter = new MockDriverAdapter();
var providers: Provider[] = [ const providers: Provider[] = [
Options.DEFAULT_PROVIDERS, UserMetric.PROVIDERS, Options.DEFAULT_PROVIDERS, UserMetric.PROVIDERS,
{provide: Options.USER_METRICS, useValue: userMetrics}, {provide: Options.USER_METRICS, useValue: userMetrics},
{provide: WebDriverAdapter, useValue: wdAdapter} {provide: WebDriverAdapter, useValue: wdAdapter}
@ -47,7 +45,7 @@ export function main() {
describe('endMeasure', () => { describe('endMeasure', () => {
it('should stop measuring when all properties have numeric values', it('should stop measuring when all properties have numeric values',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let metric = createMetric( const metric = createMetric(
[[]], new PerfLogFeatures(), [[]], new PerfLogFeatures(),
{userMetrics: {'loadTime': 'time to load', 'content': 'time to see content'}}); {userMetrics: {'loadTime': 'time to load', 'content': 'time to see content'}});
metric.beginMeasure() metric.beginMeasure()
@ -73,7 +71,7 @@ class MockDriverAdapter extends WebDriverAdapter {
executeScript(script: string): any { executeScript(script: string): any {
// Just handles `return window.propName` ignores `delete window.propName`. // Just handles `return window.propName` ignores `delete window.propName`.
if (script.indexOf('return window.') == 0) { if (script.indexOf('return window.') == 0) {
let metricName = script.substring('return window.'.length); const metricName = script.substring('return window.'.length);
return Promise.resolve(this.data[metricName]); return Promise.resolve(this.data[metricName]);
} else if (script.indexOf('delete window.') == 0) { } else if (script.indexOf('delete window.') == 0) {
return Promise.resolve(null); return Promise.resolve(null);

View File

@ -7,15 +7,15 @@
*/ */
import {Provider} from '@angular/core'; import {Provider} from '@angular/core';
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {describe, expect, it} from '@angular/core/testing/testing_internal';
import {ConsoleReporter, MeasureValues, ReflectiveInjector, Reporter, SampleDescription, SampleState} from '../../index'; import {ConsoleReporter, MeasureValues, ReflectiveInjector, SampleDescription} from '../../index';
import {Date, DateWrapper, isBlank, isPresent} from '../../src/facade/lang'; import {isBlank, isPresent} from '../../src/facade/lang';
export function main() { export function main() {
describe('console reporter', () => { describe('console reporter', () => {
var reporter: ConsoleReporter; let reporter: ConsoleReporter;
var log: string[]; let log: string[];
function createReporter( function createReporter(
{columnWidth = null, sampleId = null, descriptions = null, metrics = null}: { {columnWidth = null, sampleId = null, descriptions = null, metrics = null}: {
@ -25,13 +25,13 @@ export function main() {
metrics?: {[key: string]: any} metrics?: {[key: string]: any}
}) { }) {
log = []; log = [];
if (isBlank(descriptions)) { if (!descriptions) {
descriptions = []; descriptions = [];
} }
if (isBlank(sampleId)) { if (sampleId == null) {
sampleId = 'null'; sampleId = 'null';
} }
var providers: Provider[] = [ const providers: Provider[] = [
ConsoleReporter.PROVIDERS, { ConsoleReporter.PROVIDERS, {
provide: SampleDescription, provide: SampleDescription,
useValue: new SampleDescription(sampleId, descriptions, metrics) useValue: new SampleDescription(sampleId, descriptions, metrics)
@ -90,5 +90,5 @@ export function main() {
} }
function mv(runIndex: number, time: number, values: {[key: string]: number}) { function mv(runIndex: number, time: number, values: {[key: string]: number}) {
return new MeasureValues(runIndex, DateWrapper.fromMillis(time), values); return new MeasureValues(runIndex, new Date(time), values);
} }

View File

@ -6,14 +6,14 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {JsonFileReporter, MeasureValues, Options, ReflectiveInjector, SampleDescription} from '../../index'; import {JsonFileReporter, MeasureValues, Options, ReflectiveInjector, SampleDescription} from '../../index';
import {DateWrapper, Json, isPresent} from '../../src/facade/lang'; import {isPresent} from '../../src/facade/lang';
export function main() { export function main() {
describe('file reporter', () => { describe('file reporter', () => {
var loggedFile: any; let loggedFile: any;
function createReporter({sampleId, descriptions, metrics, path}: { function createReporter({sampleId, descriptions, metrics, path}: {
sampleId: string, sampleId: string,
@ -21,13 +21,13 @@ export function main() {
metrics: {[key: string]: string}, metrics: {[key: string]: string},
path: string path: string
}) { }) {
var providers = [ const providers = [
JsonFileReporter.PROVIDERS, { JsonFileReporter.PROVIDERS, {
provide: SampleDescription, provide: SampleDescription,
useValue: new SampleDescription(sampleId, descriptions, metrics) useValue: new SampleDescription(sampleId, descriptions, metrics)
}, },
{provide: JsonFileReporter.PATH, useValue: path}, {provide: JsonFileReporter.PATH, useValue: path},
{provide: Options.NOW, useValue: () => DateWrapper.fromMillis(1234)}, { {provide: Options.NOW, useValue: () => new Date(1234)}, {
provide: Options.WRITE_FILE, provide: Options.WRITE_FILE,
useValue: (filename: string, content: string) => { useValue: (filename: string, content: string) => {
loggedFile = {'filename': filename, 'content': content}; loggedFile = {'filename': filename, 'content': content};
@ -49,9 +49,9 @@ export function main() {
.reportSample( .reportSample(
[mv(0, 0, {'a': 3, 'b': 6})], [mv(0, 0, {'a': 3, 'b': 6})],
[mv(0, 0, {'a': 3, 'b': 6}), mv(1, 1, {'a': 5, 'b': 9})]); [mv(0, 0, {'a': 3, 'b': 6}), mv(1, 1, {'a': 5, 'b': 9})]);
var regExp = /somePath\/someId_\d+\.json/; const regExp = /somePath\/someId_\d+\.json/;
expect(isPresent(loggedFile['filename'].match(regExp))).toBe(true); expect(isPresent(loggedFile['filename'].match(regExp))).toBe(true);
var parsedContent = Json.parse(loggedFile['content']); const parsedContent = JSON.parse(loggedFile['content']);
expect(parsedContent).toEqual({ expect(parsedContent).toEqual({
'description': { 'description': {
'id': 'someId', 'id': 'someId',
@ -77,5 +77,5 @@ export function main() {
} }
function mv(runIndex: number, time: number, values: {[key: string]: number}) { function mv(runIndex: number, time: number, values: {[key: string]: number}) {
return new MeasureValues(runIndex, DateWrapper.fromMillis(time), values); return new MeasureValues(runIndex, new Date(time), values);
} }

View File

@ -6,19 +6,18 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {MeasureValues, MultiReporter, ReflectiveInjector, Reporter} from '../../index'; import {MeasureValues, MultiReporter, ReflectiveInjector, Reporter} from '../../index';
import {DateWrapper} from '../../src/facade/lang';
export function main() { export function main() {
function createReporters(ids: any[]) { function createReporters(ids: any[]) {
var r = ReflectiveInjector const r = ReflectiveInjector
.resolveAndCreate([ .resolveAndCreate([
ids.map(id => { return {provide: id, useValue: new MockReporter(id)}; }), ids.map(id => ({provide: id, useValue: new MockReporter(id)})),
MultiReporter.provideWith(ids) MultiReporter.provideWith(ids)
]) ])
.get(MultiReporter); .get(MultiReporter);
return Promise.resolve(r); return Promise.resolve(r);
} }
@ -26,7 +25,7 @@ export function main() {
it('should reportMeasureValues to all', it('should reportMeasureValues to all',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var mv = new MeasureValues(0, DateWrapper.now(), {}); const mv = new MeasureValues(0, new Date(), {});
createReporters(['m1', 'm2']).then((r) => r.reportMeasureValues(mv)).then((values) => { createReporters(['m1', 'm2']).then((r) => r.reportMeasureValues(mv)).then((values) => {
expect(values).toEqual([{'id': 'm1', 'values': mv}, {'id': 'm2', 'values': mv}]); expect(values).toEqual([{'id': 'm1', 'values': mv}, {'id': 'm2', 'values': mv}]);
@ -35,10 +34,9 @@ export function main() {
})); }));
it('should reportSample to call', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { it('should reportSample to call', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var completeSample = [ const completeSample =
new MeasureValues(0, DateWrapper.now(), {}), new MeasureValues(1, DateWrapper.now(), {}) [new MeasureValues(0, new Date(), {}), new MeasureValues(1, new Date(), {})];
]; const validSample = [completeSample[1]];
var validSample = [completeSample[1]];
createReporters(['m1', 'm2']) createReporters(['m1', 'm2'])
.then((r) => r.reportSample(completeSample, validSample)) .then((r) => r.reportSample(completeSample, validSample))

View File

@ -6,18 +6,17 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {Injector, Metric, Options, ReflectiveInjector, Runner, SampleDescription, SampleState, Sampler, Validator, WebDriverAdapter} from '../index'; import {Injector, Metric, Options, ReflectiveInjector, Runner, SampleDescription, SampleState, Sampler, Validator, WebDriverAdapter} from '../index';
import {isBlank} from '../src/facade/lang';
export function main() { export function main() {
describe('runner', () => { describe('runner', () => {
var injector: ReflectiveInjector; let injector: ReflectiveInjector;
var runner: Runner; let runner: Runner;
function createRunner(defaultProviders: any[] = null): Runner { function createRunner(defaultProviders: any[] = null): Runner {
if (isBlank(defaultProviders)) { if (!defaultProviders) {
defaultProviders = []; defaultProviders = [];
} }
runner = new Runner([ runner = new Runner([
@ -77,7 +76,7 @@ export function main() {
it('should provide Options.EXECUTE', it('should provide Options.EXECUTE',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var execute = () => {}; const execute = () => {};
createRunner().sample({id: 'someId', execute: execute}).then((_) => { createRunner().sample({id: 'someId', execute: execute}).then((_) => {
expect(injector.get(Options.EXECUTE)).toEqual(execute); expect(injector.get(Options.EXECUTE)).toEqual(execute);
async.done(); async.done();
@ -86,7 +85,7 @@ export function main() {
it('should provide Options.PREPARE', it('should provide Options.PREPARE',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var prepare = () => {}; const prepare = () => {};
createRunner().sample({id: 'someId', prepare: prepare}).then((_) => { createRunner().sample({id: 'someId', prepare: prepare}).then((_) => {
expect(injector.get(Options.PREPARE)).toEqual(prepare); expect(injector.get(Options.PREPARE)).toEqual(prepare);
async.done(); async.done();

View File

@ -6,16 +6,16 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {MeasureValues, Metric, Options, ReflectiveInjector, Reporter, Sampler, Validator, WebDriverAdapter} from '../index'; import {MeasureValues, Metric, Options, ReflectiveInjector, Reporter, Sampler, Validator, WebDriverAdapter} from '../index';
import {Date, DateWrapper, isBlank, isPresent, stringify} from '../src/facade/lang'; import {isBlank, isPresent} from '../src/facade/lang';
export function main() { export function main() {
var EMPTY_EXECUTE = () => {}; const EMPTY_EXECUTE = () => {};
describe('sampler', () => { describe('sampler', () => {
var sampler: Sampler; let sampler: Sampler;
function createSampler({driver, metric, reporter, validator, prepare, execute}: { function createSampler({driver, metric, reporter, validator, prepare, execute}: {
driver?: any, driver?: any,
@ -25,21 +25,21 @@ export function main() {
prepare?: any, prepare?: any,
execute?: any execute?: any
} = {}) { } = {}) {
var time = 1000; let time = 1000;
if (isBlank(metric)) { if (!metric) {
metric = new MockMetric([]); metric = new MockMetric([]);
} }
if (isBlank(reporter)) { if (!reporter) {
reporter = new MockReporter([]); reporter = new MockReporter([]);
} }
if (isBlank(driver)) { if (isBlank(driver)) {
driver = new MockDriverAdapter([]); driver = new MockDriverAdapter([]);
} }
var providers = [ const providers = [
Options.DEFAULT_PROVIDERS, Sampler.PROVIDERS, {provide: Metric, useValue: metric}, Options.DEFAULT_PROVIDERS, Sampler.PROVIDERS, {provide: Metric, useValue: metric},
{provide: Reporter, useValue: reporter}, {provide: WebDriverAdapter, useValue: driver}, {provide: Reporter, useValue: reporter}, {provide: WebDriverAdapter, useValue: driver},
{provide: Options.EXECUTE, useValue: execute}, {provide: Validator, useValue: validator}, {provide: Options.EXECUTE, useValue: execute}, {provide: Validator, useValue: validator},
{provide: Options.NOW, useValue: () => DateWrapper.fromMillis(time++)} {provide: Options.NOW, useValue: () => new Date(time++)}
]; ];
if (isPresent(prepare)) { if (isPresent(prepare)) {
providers.push({provide: Options.PREPARE, useValue: prepare}); providers.push({provide: Options.PREPARE, useValue: prepare});
@ -50,18 +50,18 @@ export function main() {
it('should call the prepare and execute callbacks using WebDriverAdapter.waitFor', it('should call the prepare and execute callbacks using WebDriverAdapter.waitFor',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var log: any[] = []; const log: any[] = [];
var count = 0; let count = 0;
var driver = new MockDriverAdapter([], (callback: Function) => { const driver = new MockDriverAdapter([], (callback: Function) => {
var result = callback(); const result = callback();
log.push(result); log.push(result);
return Promise.resolve(result); return Promise.resolve(result);
}); });
createSampler({ createSampler({
driver: driver, driver: driver,
validator: createCountingValidator(2), validator: createCountingValidator(2),
prepare: () => { return count++; }, prepare: () => count++,
execute: () => { return count++; } execute: () => count++,
}); });
sampler.sample().then((_) => { sampler.sample().then((_) => {
expect(count).toBe(4); expect(count).toBe(4);
@ -73,8 +73,8 @@ export function main() {
it('should call prepare, beginMeasure, execute, endMeasure for every iteration', it('should call prepare, beginMeasure, execute, endMeasure for every iteration',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var workCount = 0; let workCount = 0;
var log: any[] = []; const log: any[] = [];
createSampler({ createSampler({
metric: createCountingMetric(log), metric: createCountingMetric(log),
validator: createCountingValidator(2), validator: createCountingValidator(2),
@ -98,8 +98,8 @@ export function main() {
it('should call execute, endMeasure for every iteration if there is no prepare callback', it('should call execute, endMeasure for every iteration if there is no prepare callback',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var log: any[] = []; const log: any[] = [];
var workCount = 0; let workCount = 0;
createSampler({ createSampler({
metric: createCountingMetric(log), metric: createCountingMetric(log),
validator: createCountingValidator(2), validator: createCountingValidator(2),
@ -120,14 +120,14 @@ export function main() {
it('should only collect metrics for execute and ignore metrics from prepare', it('should only collect metrics for execute and ignore metrics from prepare',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var scriptTime = 0; let scriptTime = 0;
var iterationCount = 1; let iterationCount = 1;
createSampler({ createSampler({
validator: createCountingValidator(2), validator: createCountingValidator(2),
metric: new MockMetric( metric: new MockMetric(
[], [],
() => { () => {
var result = Promise.resolve({'script': scriptTime}); const result = Promise.resolve({'script': scriptTime});
scriptTime = 0; scriptTime = 0;
return result; return result;
}), }),
@ -147,8 +147,8 @@ export function main() {
it('should call the validator for every execution and store the valid sample', it('should call the validator for every execution and store the valid sample',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var log: any[] = []; const log: any[] = [];
var validSample = [mv(null, null, {})]; const validSample = [mv(null, null, {})];
createSampler({ createSampler({
metric: createCountingMetric(), metric: createCountingMetric(),
@ -174,8 +174,8 @@ export function main() {
it('should report the metric values', it('should report the metric values',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var log: any[] = []; const log: any[] = [];
var validSample = [mv(null, null, {})]; const validSample = [mv(null, null, {})];
createSampler({ createSampler({
validator: createCountingValidator(2, validSample), validator: createCountingValidator(2, validSample),
metric: createCountingMetric(), metric: createCountingMetric(),
@ -204,7 +204,7 @@ export function main() {
} }
function mv(runIndex: number, time: number, values: {[key: string]: number}) { function mv(runIndex: number, time: number, values: {[key: string]: number}) {
return new MeasureValues(runIndex, DateWrapper.fromMillis(time), values); return new MeasureValues(runIndex, new Date(time), values);
} }
function createCountingValidator( function createCountingValidator(
@ -212,7 +212,7 @@ function createCountingValidator(
return new MockValidator(log, (completeSample: MeasureValues[]) => { return new MockValidator(log, (completeSample: MeasureValues[]) => {
count--; count--;
if (count === 0) { if (count === 0) {
return isPresent(validSample) ? validSample : completeSample; return validSample || completeSample;
} else { } else {
return null; return null;
} }
@ -220,8 +220,8 @@ function createCountingValidator(
} }
function createCountingMetric(log: any[] = []) { function createCountingMetric(log: any[] = []) {
var scriptTime = 0; let scriptTime = 0;
return new MockMetric(log, () => { return {'script': scriptTime++}; }); return new MockMetric(log, () => ({'script': scriptTime++}));
} }
class MockDriverAdapter extends WebDriverAdapter { class MockDriverAdapter extends WebDriverAdapter {
@ -239,7 +239,8 @@ class MockDriverAdapter extends WebDriverAdapter {
class MockValidator extends Validator { class MockValidator extends Validator {
constructor(private _log: any[] = [], private _validate: Function = null) { super(); } constructor(private _log: any[] = [], private _validate: Function = null) { super(); }
validate(completeSample: MeasureValues[]): MeasureValues[] { validate(completeSample: MeasureValues[]): MeasureValues[] {
var stableSample = isPresent(this._validate) ? this._validate(completeSample) : completeSample; const stableSample =
isPresent(this._validate) ? this._validate(completeSample) : completeSample;
this._log.push(['validate', completeSample, stableSample]); this._log.push(['validate', completeSample, stableSample]);
return stableSample; return stableSample;
} }
@ -252,7 +253,7 @@ class MockMetric extends Metric {
return Promise.resolve(null); return Promise.resolve(null);
} }
endMeasure(restart: boolean) { endMeasure(restart: boolean) {
var measureValues = isPresent(this._endMeasure) ? this._endMeasure() : {}; const measureValues = isPresent(this._endMeasure) ? this._endMeasure() : {};
this._log.push(['endMeasure', restart, measureValues]); this._log.push(['endMeasure', restart, measureValues]);
return Promise.resolve(measureValues); return Promise.resolve(measureValues);
} }

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {describe, expect, it} from '@angular/core/testing/testing_internal';
import {Statistic} from '../src/statistic'; import {Statistic} from '../src/statistic';
export function main() { export function main() {

View File

@ -13,7 +13,7 @@ export class TraceEventFactory {
constructor(private _cat: string, private _pid: string) {} constructor(private _cat: string, private _pid: string) {}
create(ph: any, name: string, time: number, args: any = null) { create(ph: any, name: string, time: number, args: any = null) {
var res: const res:
PerfLogEvent = {'name': name, 'cat': this._cat, 'ph': ph, 'ts': time, 'pid': this._pid}; PerfLogEvent = {'name': name, 'cat': this._cat, 'ph': ph, 'ts': time, 'pid': this._pid};
if (isPresent(args)) { if (isPresent(args)) {
res['args'] = args; res['args'] = args;
@ -34,7 +34,7 @@ export class TraceEventFactory {
} }
complete(name: string, time: number, duration: number, args: any = null) { complete(name: string, time: number, duration: number, args: any = null) {
var res = this.create('X', name, time, args); const res = this.create('X', name, time, args);
res['dur'] = duration; res['dur'] = duration;
return res; return res;
} }

View File

@ -6,15 +6,13 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {describe, expect, it} from '@angular/core/testing/testing_internal';
import {MeasureValues, ReflectiveInjector, RegressionSlopeValidator} from '../../index'; import {MeasureValues, ReflectiveInjector, RegressionSlopeValidator} from '../../index';
import {ListWrapper} from '../../src/facade/collection';
import {Date, DateWrapper} from '../../src/facade/lang';
export function main() { export function main() {
describe('regression slope validator', () => { describe('regression slope validator', () => {
var validator: RegressionSlopeValidator; let validator: RegressionSlopeValidator;
function createValidator({size, metric}: {size: number, metric: string}) { function createValidator({size, metric}: {size: number, metric: string}) {
validator = ReflectiveInjector validator = ReflectiveInjector
@ -44,23 +42,21 @@ export function main() {
it('should return the last sampleSize runs when the regression slope is ==0', () => { it('should return the last sampleSize runs when the regression slope is ==0', () => {
createValidator({size: 2, metric: 'script'}); createValidator({size: 2, metric: 'script'});
var sample = [mv(0, 0, {'script': 1}), mv(1, 1, {'script': 1}), mv(2, 2, {'script': 1})]; const sample = [mv(0, 0, {'script': 1}), mv(1, 1, {'script': 1}), mv(2, 2, {'script': 1})];
expect(validator.validate(ListWrapper.slice(sample, 0, 2))) expect(validator.validate(sample.slice(0, 2))).toEqual(sample.slice(0, 2));
.toEqual(ListWrapper.slice(sample, 0, 2)); expect(validator.validate(sample)).toEqual(sample.slice(1, 3));
expect(validator.validate(sample)).toEqual(ListWrapper.slice(sample, 1, 3));
}); });
it('should return the last sampleSize runs when the regression slope is >0', () => { it('should return the last sampleSize runs when the regression slope is >0', () => {
createValidator({size: 2, metric: 'script'}); createValidator({size: 2, metric: 'script'});
var sample = [mv(0, 0, {'script': 1}), mv(1, 1, {'script': 2}), mv(2, 2, {'script': 3})]; const sample = [mv(0, 0, {'script': 1}), mv(1, 1, {'script': 2}), mv(2, 2, {'script': 3})];
expect(validator.validate(ListWrapper.slice(sample, 0, 2))) expect(validator.validate(sample.slice(0, 2))).toEqual(sample.slice(0, 2));
.toEqual(ListWrapper.slice(sample, 0, 2)); expect(validator.validate(sample)).toEqual(sample.slice(1, 3));
expect(validator.validate(sample)).toEqual(ListWrapper.slice(sample, 1, 3));
}); });
}); });
} }
function mv(runIndex: number, time: number, values: {[key: string]: number}) { function mv(runIndex: number, time: number, values: {[key: string]: number}) {
return new MeasureValues(runIndex, DateWrapper.fromMillis(time), values); return new MeasureValues(runIndex, new Date(time), values);
} }

View File

@ -6,15 +6,13 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {describe, expect, it} from '@angular/core/testing/testing_internal';
import {MeasureValues, ReflectiveInjector, SizeValidator, Validator} from '../../index'; import {MeasureValues, ReflectiveInjector, SizeValidator} from '../../index';
import {ListWrapper} from '../../src/facade/collection';
import {Date, DateWrapper} from '../../src/facade/lang';
export function main() { export function main() {
describe('size validator', () => { describe('size validator', () => {
var validator: SizeValidator; let validator: SizeValidator;
function createValidator(size: number) { function createValidator(size: number) {
validator = validator =
@ -37,15 +35,14 @@ export function main() {
it('should return the last sampleSize runs when it has at least the given size', () => { it('should return the last sampleSize runs when it has at least the given size', () => {
createValidator(2); createValidator(2);
var sample = [mv(0, 0, {'a': 1}), mv(1, 1, {'b': 2}), mv(2, 2, {'c': 3})]; const sample = [mv(0, 0, {'a': 1}), mv(1, 1, {'b': 2}), mv(2, 2, {'c': 3})];
expect(validator.validate(ListWrapper.slice(sample, 0, 2))) expect(validator.validate(sample.slice(0, 2))).toEqual(sample.slice(0, 2));
.toEqual(ListWrapper.slice(sample, 0, 2)); expect(validator.validate(sample)).toEqual(sample.slice(1, 3));
expect(validator.validate(sample)).toEqual(ListWrapper.slice(sample, 1, 3));
}); });
}); });
} }
function mv(runIndex: number, time: number, values: {[key: string]: number}) { function mv(runIndex: number, time: number, values: {[key: string]: number}) {
return new MeasureValues(runIndex, DateWrapper.fromMillis(time), values); return new MeasureValues(runIndex, new Date(time), values);
} }

View File

@ -6,10 +6,10 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {Options, ReflectiveInjector, WebDriverExtension} from '../index'; import {Options, ReflectiveInjector, WebDriverExtension} from '../index';
import {StringWrapper, isPresent} from '../src/facade/lang'; import {isPresent} from '../src/facade/lang';
export function main() { export function main() {
function createExtension(ids: any[], caps: any) { function createExtension(ids: any[], caps: any) {
@ -17,7 +17,7 @@ export function main() {
try { try {
res(ReflectiveInjector res(ReflectiveInjector
.resolveAndCreate([ .resolveAndCreate([
ids.map((id) => { return {provide: id, useValue: new MockExtension(id)}; }), ids.map((id) => ({provide: id, useValue: new MockExtension(id)})),
{provide: Options.CAPABILITIES, useValue: caps}, {provide: Options.CAPABILITIES, useValue: caps},
WebDriverExtension.provideFirstSupported(ids) WebDriverExtension.provideFirstSupported(ids)
]) ])
@ -52,6 +52,6 @@ class MockExtension extends WebDriverExtension {
constructor(public id: string) { super(); } constructor(public id: string) { super(); }
supports(capabilities: {[key: string]: any}): boolean { supports(capabilities: {[key: string]: any}): boolean {
return StringWrapper.equals(capabilities['browser'], this.id); return capabilities['browser'] === this.id;
} }
} }

View File

@ -6,36 +6,36 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {ChromeDriverExtension, Options, ReflectiveInjector, WebDriverAdapter, WebDriverExtension} from '../../index'; import {ChromeDriverExtension, Options, ReflectiveInjector, WebDriverAdapter, WebDriverExtension} from '../../index';
import {Json, isBlank} from '../../src/facade/lang'; import {isBlank} from '../../src/facade/lang';
import {TraceEventFactory} from '../trace_event_factory'; import {TraceEventFactory} from '../trace_event_factory';
export function main() { export function main() {
describe('chrome driver extension', () => { describe('chrome driver extension', () => {
var CHROME45_USER_AGENT = const CHROME45_USER_AGENT =
'"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2499.0 Safari/537.36"'; '"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2499.0 Safari/537.36"';
var log: any[]; let log: any[];
var extension: ChromeDriverExtension; let extension: ChromeDriverExtension;
var blinkEvents = new TraceEventFactory('blink.console', 'pid0'); const blinkEvents = new TraceEventFactory('blink.console', 'pid0');
var v8Events = new TraceEventFactory('v8', 'pid0'); const v8Events = new TraceEventFactory('v8', 'pid0');
var v8EventsOtherProcess = new TraceEventFactory('v8', 'pid1'); const v8EventsOtherProcess = new TraceEventFactory('v8', 'pid1');
var chromeTimelineEvents = const chromeTimelineEvents =
new TraceEventFactory('disabled-by-default-devtools.timeline', 'pid0'); new TraceEventFactory('disabled-by-default-devtools.timeline', 'pid0');
var chrome45TimelineEvents = new TraceEventFactory('devtools.timeline', 'pid0'); const chrome45TimelineEvents = new TraceEventFactory('devtools.timeline', 'pid0');
var chromeTimelineV8Events = new TraceEventFactory('devtools.timeline,v8', 'pid0'); const chromeTimelineV8Events = new TraceEventFactory('devtools.timeline,v8', 'pid0');
var chromeBlinkTimelineEvents = new TraceEventFactory('blink,devtools.timeline', 'pid0'); const chromeBlinkTimelineEvents = new TraceEventFactory('blink,devtools.timeline', 'pid0');
var chromeBlinkUserTimingEvents = new TraceEventFactory('blink.user_timing', 'pid0'); const chromeBlinkUserTimingEvents = new TraceEventFactory('blink.user_timing', 'pid0');
var benchmarkEvents = new TraceEventFactory('benchmark', 'pid0'); const benchmarkEvents = new TraceEventFactory('benchmark', 'pid0');
var normEvents = new TraceEventFactory('timeline', 'pid0'); const normEvents = new TraceEventFactory('timeline', 'pid0');
function createExtension( function createExtension(
perfRecords: any[] = null, userAgent: string = null, perfRecords: any[] = null, userAgent: string = null,
messageMethod = 'Tracing.dataCollected'): WebDriverExtension { messageMethod = 'Tracing.dataCollected'): WebDriverExtension {
if (isBlank(perfRecords)) { if (!perfRecords) {
perfRecords = []; perfRecords = [];
} }
if (isBlank(userAgent)) { if (isBlank(userAgent)) {
@ -101,7 +101,7 @@ export function main() {
it('should normalize "tdur" to "dur"', it('should normalize "tdur" to "dur"',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var event: any = chromeTimelineV8Events.create('X', 'FunctionCall', 1100, null); const event: any = chromeTimelineV8Events.create('X', 'FunctionCall', 1100, null);
event['tdur'] = 5500; event['tdur'] = 5500;
createExtension([event]).readPerfLog().then((events) => { createExtension([event]).readPerfLog().then((events) => {
expect(events).toEqual([ expect(events).toEqual([
@ -396,11 +396,11 @@ class MockDriverAdapter extends WebDriverAdapter {
logs(type: string) { logs(type: string) {
this._log.push(['logs', type]); this._log.push(['logs', type]);
if (type === 'performance') { if (type === 'performance') {
return Promise.resolve(this._events.map((event) => { return Promise.resolve(this._events.map(
return { (event) => ({
'message': Json.stringify({'message': {'method': this._messageMethod, 'params': event}}) 'message': JSON.stringify(
}; {'message': {'method': this._messageMethod, 'params': event}}, null, 2)
})); })));
} else { } else {
return null; return null;
} }

View File

@ -6,21 +6,20 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {IOsDriverExtension, ReflectiveInjector, WebDriverAdapter, WebDriverExtension} from '../../index'; import {IOsDriverExtension, ReflectiveInjector, WebDriverAdapter, WebDriverExtension} from '../../index';
import {Json, isBlank, isPresent} from '../../src/facade/lang';
import {TraceEventFactory} from '../trace_event_factory'; import {TraceEventFactory} from '../trace_event_factory';
export function main() { export function main() {
describe('ios driver extension', () => { describe('ios driver extension', () => {
var log: any[]; let log: any[];
var extension: IOsDriverExtension; let extension: IOsDriverExtension;
var normEvents = new TraceEventFactory('timeline', 'pid0'); const normEvents = new TraceEventFactory('timeline', 'pid0');
function createExtension(perfRecords: any[] = null): WebDriverExtension { function createExtension(perfRecords: any[] = null): WebDriverExtension {
if (isBlank(perfRecords)) { if (!perfRecords) {
perfRecords = []; perfRecords = [];
} }
log = []; log = [];
@ -156,7 +155,7 @@ function timeEndRecord(name: string, time: number) {
} }
function durationRecord(type: string, startTime: number, endTime: number, children: any[] = null) { function durationRecord(type: string, startTime: number, endTime: number, children: any[] = null) {
if (isBlank(children)) { if (!children) {
children = []; children = [];
} }
return {'type': type, 'startTime': startTime, 'endTime': endTime, 'children': children}; return {'type': type, 'startTime': startTime, 'endTime': endTime, 'children': children};
@ -184,8 +183,9 @@ class MockDriverAdapter extends WebDriverAdapter {
if (type === 'performance') { if (type === 'performance') {
return Promise.resolve(this._perfRecords.map(function(record) { return Promise.resolve(this._perfRecords.map(function(record) {
return { return {
'message': Json.stringify( 'message': JSON.stringify(
{'message': {'method': 'Timeline.eventRecorded', 'params': {'record': record}}}) {'message': {'method': 'Timeline.eventRecorded', 'params': {'record': record}}}, null,
2)
}; };
})); }));
} else { } else {

View File

@ -11,9 +11,6 @@
* @description * @description
* Entry point for all public APIs of the common package. * Entry point for all public APIs of the common package.
*/ */
export * from './src/location'; export * from './src/common';
export {NgLocalization} from './src/localization';
export {CommonModule} from './src/common_module';
export {NgClass, NgFor, NgIf, NgPlural, NgPluralCase, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgTemplateOutlet} from './src/directives/index'; // This file only reexports content of the `src` folder. Keep it that way.
export {AsyncPipe, DatePipe, I18nPluralPipe, I18nSelectPipe, JsonPipe, LowerCasePipe, CurrencyPipe, DecimalPipe, PercentPipe, SlicePipe, UpperCasePipe} from './src/pipes/index';

View File

@ -1,3 +1,10 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export default { export default {
entry: '../../../dist/packages-dist/common/testing/index.js', entry: '../../../dist/packages-dist/common/testing/index.js',
@ -10,4 +17,4 @@ export default {
'rxjs/Observable': 'Rx', 'rxjs/Observable': 'Rx',
'rxjs/Subject': 'Rx' 'rxjs/Subject': 'Rx'
} }
} };

View File

@ -1,3 +1,10 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export default { export default {
entry: '../../../dist/packages-dist/common/index.js', entry: '../../../dist/packages-dist/common/index.js',
@ -7,6 +14,6 @@ export default {
globals: { globals: {
'@angular/core': 'ng.core', '@angular/core': 'ng.core',
'rxjs/Observable': 'Rx', 'rxjs/Observable': 'Rx',
'rxjs/Subject': 'Rx' 'rxjs/Subject': 'Rx',
} }
} };

View File

@ -0,0 +1,20 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
export * from './location/index';
export {NgLocaleLocalization, NgLocalization} from './localization';
export {CommonModule} from './common_module';
export {NgClass, NgFor, NgIf, NgPlural, NgPluralCase, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgTemplateOutlet} from './directives/index';
export {AsyncPipe, DatePipe, I18nPluralPipe, I18nSelectPipe, JsonPipe, LowerCasePipe, CurrencyPipe, DecimalPipe, PercentPipe, SlicePipe, UpperCasePipe, TitleCasePipe} from './pipes/index';
export {VERSION} from './version';
export {Version} from '@angular/core';

View File

@ -9,9 +9,7 @@
import {CollectionChangeRecord, Directive, DoCheck, ElementRef, Input, IterableDiffer, IterableDiffers, KeyValueChangeRecord, KeyValueDiffer, KeyValueDiffers, Renderer} from '@angular/core'; import {CollectionChangeRecord, Directive, DoCheck, ElementRef, Input, IterableDiffer, IterableDiffers, KeyValueChangeRecord, KeyValueDiffer, KeyValueDiffers, Renderer} from '@angular/core';
import {isListLikeIterable} from '../facade/collection'; import {isListLikeIterable} from '../facade/collection';
import {isPresent} from '../facade/lang'; import {isPresent, stringify} from '../facade/lang';
/** /**
* @ngModule CommonModule * @ngModule CommonModule
@ -27,15 +25,17 @@ import {isPresent} from '../facade/lang';
* <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element> * <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
* *
* <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element> * <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
*
* <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
* ``` * ```
* *
* @description * @description
* *
* The CSS classes are updated as follow depending on the type of the expression evaluation: * The CSS classes are updated as follows, depending on the type of the expression evaluation:
* - `string` - the CSS classes listed in a string (space delimited) are added, * - `string` - the CSS classes listed in the string (space delimited) are added,
* - `Array` - the CSS classes (Array elements) are added, * - `Array` - the CSS classes declared as Array elements are added,
* - `Object` - keys are CSS class names that get added when the expression given in the value * - `Object` - keys are CSS classes that get added when the expression given in the value
* evaluates to a truthy value, otherwise class are removed. * evaluates to a truthy value, otherwise they are removed.
* *
* @stable * @stable
*/ */
@ -50,7 +50,6 @@ export class NgClass implements DoCheck {
private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers, private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers,
private _ngEl: ElementRef, private _renderer: Renderer) {} private _ngEl: ElementRef, private _renderer: Renderer) {}
@Input('class') @Input('class')
set klass(v: string) { set klass(v: string) {
this._applyInitialClasses(true); this._applyInitialClasses(true);
@ -111,8 +110,14 @@ export class NgClass implements DoCheck {
} }
private _applyIterableChanges(changes: any): void { private _applyIterableChanges(changes: any): void {
changes.forEachAddedItem( changes.forEachAddedItem((record: CollectionChangeRecord) => {
(record: CollectionChangeRecord) => this._toggleClass(record.item, true)); if (typeof record.item === 'string') {
this._toggleClass(record.item, true);
} else {
throw new Error(
`NgClass can only toggle CSS classes expressed as strings, got ${stringify(record.item)}`);
}
});
changes.forEachRemovedItem( changes.forEachRemovedItem(
(record: CollectionChangeRecord) => this._toggleClass(record.item, false)); (record: CollectionChangeRecord) => this._toggleClass(record.item, false));

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {ChangeDetectorRef, CollectionChangeRecord, DefaultIterableDiffer, Directive, DoCheck, EmbeddedViewRef, Input, IterableDiffer, IterableDiffers, OnChanges, SimpleChanges, TemplateRef, TrackByFn, ViewContainerRef} from '@angular/core'; import {ChangeDetectorRef, CollectionChangeRecord, DefaultIterableDiffer, Directive, DoCheck, EmbeddedViewRef, Input, IterableDiffer, IterableDiffers, OnChanges, SimpleChanges, TemplateRef, TrackByFn, ViewContainerRef, isDevMode} from '@angular/core';
import {getTypeNameForDebugging} from '../facade/lang'; import {getTypeNameForDebugging} from '../facade/lang';
@ -89,9 +89,23 @@ export class NgForRow {
@Directive({selector: '[ngFor][ngForOf]'}) @Directive({selector: '[ngFor][ngForOf]'})
export class NgFor implements DoCheck, OnChanges { export class NgFor implements DoCheck, OnChanges {
@Input() ngForOf: any; @Input() ngForOf: any;
@Input() ngForTrackBy: TrackByFn; @Input()
set ngForTrackBy(fn: TrackByFn) {
if (isDevMode() && fn != null && typeof fn !== 'function') {
// TODO(vicb): use a log service once there is a public one available
if (<any>console && <any>console.warn) {
console.warn(
`trackBy must be a function, but received ${JSON.stringify(fn)}. ` +
`See https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html#!#change-propagation for more information.`);
}
}
this._trackByFn = fn;
}
get ngForTrackBy(): TrackByFn { return this._trackByFn; }
private _differ: IterableDiffer = null; private _differ: IterableDiffer = null;
private _trackByFn: TrackByFn;
constructor( constructor(
private _viewContainer: ViewContainerRef, private _template: TemplateRef<NgForRow>, private _viewContainer: ViewContainerRef, private _template: TemplateRef<NgForRow>,
@ -119,7 +133,7 @@ export class NgFor implements DoCheck, OnChanges {
} }
} }
ngDoCheck() { ngDoCheck(): void {
if (this._differ) { if (this._differ) {
const changes = this._differ.diff(this.ngForOf); const changes = this._differ.diff(this.ngForOf);
if (changes) this._applyChanges(changes); if (changes) this._applyChanges(changes);
@ -150,13 +164,13 @@ export class NgFor implements DoCheck, OnChanges {
} }
for (let i = 0, ilen = this._viewContainer.length; i < ilen; i++) { for (let i = 0, ilen = this._viewContainer.length; i < ilen; i++) {
let viewRef = <EmbeddedViewRef<NgForRow>>this._viewContainer.get(i); const viewRef = <EmbeddedViewRef<NgForRow>>this._viewContainer.get(i);
viewRef.context.index = i; viewRef.context.index = i;
viewRef.context.count = ilen; viewRef.context.count = ilen;
} }
changes.forEachIdentityChange((record: any) => { changes.forEachIdentityChange((record: any) => {
let viewRef = <EmbeddedViewRef<NgForRow>>this._viewContainer.get(record.currentIndex); const viewRef = <EmbeddedViewRef<NgForRow>>this._viewContainer.get(record.currentIndex);
viewRef.context.$implicit = record.item; viewRef.context.$implicit = record.item;
}); });
} }

View File

@ -6,46 +6,152 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core'; import {Directive, EmbeddedViewRef, Input, TemplateRef, ViewContainerRef} from '@angular/core';
/** /**
* Removes or recreates a portion of the DOM tree based on an {expression}. * Conditionally includes a template based on the value of an `expression`.
* *
* If the expression assigned to `ngIf` evaluates to a false value then the element * `ngIf` evaluates the `expression` and then renders the `then` or `else` template in its place
* is removed from the DOM, otherwise a clone of the element is reinserted into the DOM. * when expression is truthy or falsy respectively. Typically the:
* - `then` template is the inline template of `ngIf` unless bound to a different value.
* - `else` template is blank unless it is bound.
* *
* ### Example ([live demo](http://plnkr.co/edit/fe0kgemFBtmQOY31b4tw?p=preview)): * # Most common usage
*
* The most common usage of the `ngIf` directive is to conditionally show the inline template as
* seen in this example:
* {@example common/ngIf/ts/module.ts region='NgIfSimple'}
*
* # Showing an alternative template using `else`
*
* If it is necessary to display a template when the `expression` is falsy use the `else` template
* binding as shown. Note that the `else` binding points to a `<template>` labeled `#elseBlock`.
* The template can be defined anywhere in the component view but is typically placed right after
* `ngIf` for readability.
*
* {@example common/ngIf/ts/module.ts region='NgIfElse'}
*
* # Using non-inlined `then` template
*
* Usually the `then` template is the inlined template of the `ngIf`, but it can be changed using
* a binding (just like `else`). Because `then` and `else` are bindings, the template references can
* change at runtime as shown in this example.
*
* {@example common/ngIf/ts/module.ts region='NgIfThenElse'}
*
* # Storing conditional result in a variable
*
* A common pattern is that we need to show a set of properties from the same object. If the
* object is undefined, then we have to use the safe-traversal-operator `?.` to guard against
* dereferencing a `null` value. This is especially the case when waiting on async data such as
* when using the `async` pipe as shown in folowing example:
* *
* ``` * ```
* <div *ngIf="errorCount > 0" class="error"> * Hello {{ (userStream|async)?.last }}, {{ (userStream|async)?.first }}!
* <!-- Error message displayed when the errorCount property on the current context is greater
* than 0. -->
* {{errorCount}} errors detected
* </div>
* ``` * ```
* *
* There are several inefficiencies in the above example:
* - We create multiple subscriptions on `userStream`. One for each `async` pipe, or two in the
* example above.
* - We cannot display an alternative screen while waiting for the data to arrive asynchronously.
* - We have to use the safe-traversal-operator `?.` to access properties, which is cumbersome.
* - We have to place the `async` pipe in parenthesis.
*
* A better way to do this is to use `ngIf` and store the result of the condition in a local
* variable as shown in the the example below:
*
* {@example common/ngIf/ts/module.ts region='NgIfLet'}
*
* Notice that:
* - We use only one `async` pipe and hence only one subscription gets created.
* - `ngIf` stores the result of the `userStream|async` in the local variable `user`.
* - The local `user` can then be bound repeatedly in a more efficient way.
* - No need to use the safe-traversal-operator `?.` to access properties as `ngIf` will only
* display the data if `userStream` returns a value.
* - We can display an alternative template while waiting for the data.
*
* ### Syntax * ### Syntax
* *
* Simple form:
* - `<div *ngIf="condition">...</div>` * - `<div *ngIf="condition">...</div>`
* - `<div template="ngIf condition">...</div>` * - `<div template="ngIf condition">...</div>`
* - `<template [ngIf]="condition"><div>...</div></template>` * - `<template [ngIf]="condition"><div>...</div></template>`
* *
* Form with an else block:
* ```
* <div *ngIf="condition; else elseBlock">...</div>
* <template #elseBlock>...</template>
* ```
*
* Form with a `then` and `else` block:
* ```
* <div *ngIf="condition; then thenBlock else elseBlock"></div>
* <template #thenBlock>...</template>
* <template #elseBlock>...</template>
* ```
*
* Form with storing the value locally:
* ```
* <div *ngIf="condition; else elseBlock; let value">{{value}}</div>
* <template #elseBlock>...</template>
* ```
*
* @stable * @stable
*/ */
@Directive({selector: '[ngIf]'}) @Directive({selector: '[ngIf]'})
export class NgIf { export class NgIf {
private _hasView: boolean = false; private _context: NgIfContext = new NgIfContext();
private _thenTemplateRef: TemplateRef<NgIfContext> = null;
private _elseTemplateRef: TemplateRef<NgIfContext> = null;
private _thenViewRef: EmbeddedViewRef<NgIfContext> = null;
private _elseViewRef: EmbeddedViewRef<NgIfContext> = null;
constructor(private _viewContainer: ViewContainerRef, private _template: TemplateRef<Object>) {} constructor(private _viewContainer: ViewContainerRef, templateRef: TemplateRef<NgIfContext>) {
this._thenTemplateRef = templateRef;
}
@Input() @Input()
set ngIf(condition: any) { set ngIf(condition: any) {
if (condition && !this._hasView) { this._context.$implicit = condition;
this._hasView = true; this._updateView();
this._viewContainer.createEmbeddedView(this._template); }
} else if (!condition && this._hasView) {
this._hasView = false; @Input()
this._viewContainer.clear(); set ngIfThen(templateRef: TemplateRef<NgIfContext>) {
this._thenTemplateRef = templateRef;
this._thenViewRef = null; // clear previous view if any.
this._updateView();
}
@Input()
set ngIfElse(templateRef: TemplateRef<NgIfContext>) {
this._elseTemplateRef = templateRef;
this._elseViewRef = null; // clear previous view if any.
this._updateView();
}
private _updateView() {
if (this._context.$implicit) {
if (!this._thenViewRef) {
this._viewContainer.clear();
this._elseViewRef = null;
if (this._thenTemplateRef) {
this._thenViewRef =
this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);
}
}
} else {
if (!this._elseViewRef) {
this._viewContainer.clear();
this._thenViewRef = null;
if (this._elseTemplateRef) {
this._elseViewRef =
this._viewContainer.createEmbeddedView(this._elseTemplateRef, this._context);
}
}
} }
} }
} }
export class NgIfContext { public $implicit: any = null; }

View File

@ -61,8 +61,7 @@ export class NgPlural {
addCase(value: string, switchView: SwitchView): void { this._caseViews[value] = switchView; } addCase(value: string, switchView: SwitchView): void { this._caseViews[value] = switchView; }
/** @internal */ private _updateView(): void {
_updateView(): void {
this._clearViews(); this._clearViews();
const cases = Object.keys(this._caseViews); const cases = Object.keys(this._caseViews);
@ -70,13 +69,11 @@ export class NgPlural {
this._activateView(this._caseViews[key]); this._activateView(this._caseViews[key]);
} }
/** @internal */ private _clearViews() {
_clearViews() {
if (this._activeView) this._activeView.destroy(); if (this._activeView) this._activeView.destroy();
} }
/** @internal */ private _activateView(view: SwitchView) {
_activateView(view: SwitchView) {
if (view) { if (view) {
this._activeView = view; this._activeView = view;
this._activeView.create(); this._activeView.create();

View File

@ -25,17 +25,15 @@ import {Directive, DoCheck, ElementRef, Input, KeyValueChangeRecord, KeyValueDif
* @description * @description
* *
* The styles are updated according to the value of the expression evaluation: * The styles are updated according to the value of the expression evaluation:
* - keys are style names with an option `.<unit>` suffix (ie 'top.px', 'font-style.em'), * - keys are style names with an optional `.<unit>` suffix (ie 'top.px', 'font-style.em'),
* - values are the values assigned to those properties (expressed in the given unit). * - values are the values assigned to those properties (expressed in the given unit).
* *
* @stable * @stable
*/ */
@Directive({selector: '[ngStyle]'}) @Directive({selector: '[ngStyle]'})
export class NgStyle implements DoCheck { export class NgStyle implements DoCheck {
/** @internal */ private _ngStyle: {[key: string]: string};
_ngStyle: {[key: string]: string}; private _differ: KeyValueDiffer;
/** @internal */
_differ: KeyValueDiffer;
constructor( constructor(
private _differs: KeyValueDiffers, private _ngEl: ElementRef, private _renderer: Renderer) {} private _differs: KeyValueDiffers, private _ngEl: ElementRef, private _renderer: Renderer) {}
@ -69,7 +67,7 @@ export class NgStyle implements DoCheck {
private _setStyle(nameAndUnit: string, value: string): void { private _setStyle(nameAndUnit: string, value: string): void {
const [name, unit] = nameAndUnit.split('.'); const [name, unit] = nameAndUnit.split('.');
value = value !== null && value !== void(0) && unit ? `${value}${unit}` : value; value = value && unit ? `${value}${unit}` : value;
this._renderer.setElementStyle(this._ngEl.nativeElement, name, value); this._renderer.setElementStyle(this._ngEl.nativeElement, name, value);
} }

View File

@ -6,19 +6,31 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {Directive, Host, Input, TemplateRef, ViewContainerRef} from '@angular/core'; import {Directive, DoCheck, Host, Input, TemplateRef, ViewContainerRef} from '@angular/core';
import {ListWrapper} from '../facade/collection';
const _CASE_DEFAULT = new Object();
export class SwitchView { export class SwitchView {
private _created = false;
constructor( constructor(
private _viewContainerRef: ViewContainerRef, private _templateRef: TemplateRef<Object>) {} private _viewContainerRef: ViewContainerRef, private _templateRef: TemplateRef<Object>) {}
create(): void { this._viewContainerRef.createEmbeddedView(this._templateRef); } create(): void {
this._created = true;
this._viewContainerRef.createEmbeddedView(this._templateRef);
}
destroy(): void { this._viewContainerRef.clear(); } destroy(): void {
this._created = false;
this._viewContainerRef.clear();
}
enforceState(created: boolean) {
if (created && !this._created) {
this.create();
} else if (!created && this._created) {
this.destroy();
}
}
} }
/** /**
@ -38,7 +50,7 @@ export class SwitchView {
* <inner-element></inner-element> * <inner-element></inner-element>
* <inner-other-element></inner-other-element> * <inner-other-element></inner-other-element>
* </ng-container> * </ng-container>
* <some-element *ngSwitchDefault>...</p> * <some-element *ngSwitchDefault>...</some-element>
* </container-element> * </container-element>
* ``` * ```
* @description * @description
@ -53,8 +65,7 @@ export class SwitchView {
* root elements. * root elements.
* *
* Elements within `NgSwitch` but outside of a `NgSwitchCase` or `NgSwitchDefault` directives will * Elements within `NgSwitch` but outside of a `NgSwitchCase` or `NgSwitchDefault` directives will
* be * be preserved at the location.
* preserved at the location.
* *
* The `ngSwitchCase` directive informs the parent `NgSwitch` of which view to display when the * The `ngSwitchCase` directive informs the parent `NgSwitch` of which view to display when the
* expression is evaluated. * expression is evaluated.
@ -65,91 +76,52 @@ export class SwitchView {
*/ */
@Directive({selector: '[ngSwitch]'}) @Directive({selector: '[ngSwitch]'})
export class NgSwitch { export class NgSwitch {
private _switchValue: any; private _defaultViews: SwitchView[];
private _useDefault: boolean = false; private _defaultUsed = false;
private _valueViews = new Map<any, SwitchView[]>(); private _caseCount = 0;
private _activeViews: SwitchView[] = []; private _lastCaseCheckIndex = 0;
private _lastCasesMatched = false;
private _ngSwitch: any;
@Input() @Input()
set ngSwitch(value: any) { set ngSwitch(newValue: any) {
// Empty the currently active ViewContainers this._ngSwitch = newValue;
this._emptyAllActiveViews(); if (this._caseCount === 0) {
this._updateDefaultCases(true);
// Add the ViewContainers matching the value (with a fallback to default)
this._useDefault = false;
let views = this._valueViews.get(value);
if (!views) {
this._useDefault = true;
views = this._valueViews.get(_CASE_DEFAULT) || null;
} }
this._activateViews(views);
this._switchValue = value;
} }
/** @internal */ /** @internal */
_onCaseValueChanged(oldCase: any, newCase: any, view: SwitchView): void { _addCase(): number { return this._caseCount++; }
this._deregisterView(oldCase, view);
this._registerView(newCase, view);
if (oldCase === this._switchValue) { /** @internal */
view.destroy(); _addDefault(view: SwitchView) {
ListWrapper.remove(this._activeViews, view); if (!this._defaultViews) {
} else if (newCase === this._switchValue) { this._defaultViews = [];
if (this._useDefault) { }
this._useDefault = false; this._defaultViews.push(view);
this._emptyAllActiveViews(); }
/** @internal */
_matchCase(value: any): boolean {
const matched = value == this._ngSwitch;
this._lastCasesMatched = this._lastCasesMatched || matched;
this._lastCaseCheckIndex++;
if (this._lastCaseCheckIndex === this._caseCount) {
this._updateDefaultCases(!this._lastCasesMatched);
this._lastCaseCheckIndex = 0;
this._lastCasesMatched = false;
}
return matched;
}
private _updateDefaultCases(useDefault: boolean) {
if (this._defaultViews && useDefault !== this._defaultUsed) {
this._defaultUsed = useDefault;
for (let i = 0; i < this._defaultViews.length; i++) {
const defaultView = this._defaultViews[i];
defaultView.enforceState(useDefault);
} }
view.create();
this._activeViews.push(view);
}
// Switch to default when there is no more active ViewContainers
if (this._activeViews.length === 0 && !this._useDefault) {
this._useDefault = true;
this._activateViews(this._valueViews.get(_CASE_DEFAULT));
}
}
/** @internal */
_emptyAllActiveViews(): void {
const activeContainers = this._activeViews;
for (var i = 0; i < activeContainers.length; i++) {
activeContainers[i].destroy();
}
this._activeViews = [];
}
/** @internal */
_activateViews(views: SwitchView[]): void {
// TODO(vicb): assert(this._activeViews.length === 0);
if (views) {
for (var i = 0; i < views.length; i++) {
views[i].create();
}
this._activeViews = views;
}
}
/** @internal */
_registerView(value: any, view: SwitchView): void {
let views = this._valueViews.get(value);
if (!views) {
views = [];
this._valueViews.set(value, views);
}
views.push(view);
}
/** @internal */
_deregisterView(value: any, view: SwitchView): void {
// `_CASE_DEFAULT` is used a marker for non-registered cases
if (value === _CASE_DEFAULT) return;
const views = this._valueViews.get(value);
if (views.length == 1) {
this._valueViews.delete(value);
} else {
ListWrapper.remove(views, view);
} }
} }
} }
@ -179,26 +151,20 @@ export class NgSwitch {
* @stable * @stable
*/ */
@Directive({selector: '[ngSwitchCase]'}) @Directive({selector: '[ngSwitchCase]'})
export class NgSwitchCase { export class NgSwitchCase implements DoCheck {
// `_CASE_DEFAULT` is used as a marker for a not yet initialized value private _view: SwitchView;
/** @internal */
_value: any = _CASE_DEFAULT; @Input()
/** @internal */ ngSwitchCase: any;
_view: SwitchView;
private _switch: NgSwitch;
constructor( constructor(
viewContainer: ViewContainerRef, templateRef: TemplateRef<Object>, viewContainer: ViewContainerRef, templateRef: TemplateRef<Object>,
@Host() ngSwitch: NgSwitch) { @Host() private ngSwitch: NgSwitch) {
this._switch = ngSwitch; ngSwitch._addCase();
this._view = new SwitchView(viewContainer, templateRef); this._view = new SwitchView(viewContainer, templateRef);
} }
@Input() ngDoCheck() { this._view.enforceState(this.ngSwitch._matchCase(this.ngSwitchCase)); }
set ngSwitchCase(value: any) {
this._switch._onCaseValueChanged(this._value, value, this._view);
this._value = value;
}
} }
/** /**
@ -228,7 +194,7 @@ export class NgSwitchCase {
export class NgSwitchDefault { export class NgSwitchDefault {
constructor( constructor(
viewContainer: ViewContainerRef, templateRef: TemplateRef<Object>, viewContainer: ViewContainerRef, templateRef: TemplateRef<Object>,
@Host() sswitch: NgSwitch) { @Host() ngSwitch: NgSwitch) {
sswitch._registerView(_CASE_DEFAULT, new SwitchView(viewContainer, templateRef)); ngSwitch._addDefault(new SwitchView(viewContainer, templateRef));
} }
} }

View File

@ -23,9 +23,23 @@ export abstract class NgLocalization { abstract getPluralCategory(value: any): s
*/ */
export function getPluralCategory( export function getPluralCategory(
value: number, cases: string[], ngLocalization: NgLocalization): string { value: number, cases: string[], ngLocalization: NgLocalization): string {
const nbCase = `=${value}`; let key = `=${value}`;
return cases.indexOf(nbCase) > -1 ? nbCase : ngLocalization.getPluralCategory(value); if (cases.indexOf(key) > -1) {
return key;
}
key = ngLocalization.getPluralCategory(value);
if (cases.indexOf(key) > -1) {
return key;
}
if (cases.indexOf('other') > -1) {
return 'other';
}
throw new Error(`No plural message found for value "${value}"`);
} }
/** /**
@ -35,10 +49,10 @@ export function getPluralCategory(
*/ */
@Injectable() @Injectable()
export class NgLocaleLocalization extends NgLocalization { export class NgLocaleLocalization extends NgLocalization {
constructor(@Inject(LOCALE_ID) private _locale: string) { super(); } constructor(@Inject(LOCALE_ID) protected locale: string) { super(); }
getPluralCategory(value: any): string { getPluralCategory(value: any): string {
const plural = getPluralCase(this._locale, value); const plural = getPluralCase(this.locale, value);
switch (plural) { switch (plural) {
case Plural.Zero: case Plural.Zero:
@ -67,7 +81,7 @@ export enum Plural {
Two, Two,
Few, Few,
Many, Many,
Other Other,
} }
/** /**
@ -417,4 +431,4 @@ export function getPluralCase(locale: string, nLike: number | string): Plural {
default: default:
return Plural.Other; return Plural.Other;
} }
} }

View File

@ -1,13 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export * from './location/platform_location';
export * from './location/location_strategy';
export * from './location/hash_location_strategy';
export * from './location/path_location_strategy';
export * from './location/location';

View File

@ -17,6 +17,8 @@ import {LocationChangeListener, PlatformLocation} from './platform_location';
/** /**
* @whatItDoes Use URL hash for storing application location data.
* @description
* `HashLocationStrategy` is a {@link LocationStrategy} used to configure the * `HashLocationStrategy` is a {@link LocationStrategy} used to configure the
* {@link Location} service to represent its state in the * {@link Location} service to represent its state in the
* [hash fragment](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) * [hash fragment](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax)
@ -27,18 +29,7 @@ import {LocationChangeListener, PlatformLocation} from './platform_location';
* *
* ### Example * ### Example
* *
* ``` * {@example common/location/ts/hash_location_component.ts region='LocationComponent'}
* import {Component, NgModule} from '@angular/core';
* import {
* LocationStrategy,
* HashLocationStrategy
* } from '@angular/common';
*
* @NgModule({
* providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}]
* })
* class AppModule {}
* ```
* *
* @stable * @stable
*/ */
@ -64,19 +55,19 @@ export class HashLocationStrategy extends LocationStrategy {
path(includeHash: boolean = false): string { path(includeHash: boolean = false): string {
// the hash value is always prefixed with a `#` // the hash value is always prefixed with a `#`
// and if it is empty then it will stay empty // and if it is empty then it will stay empty
var path = this._platformLocation.hash; let path = this._platformLocation.hash;
if (!isPresent(path)) path = '#'; if (!isPresent(path)) path = '#';
return path.length > 0 ? path.substring(1) : path; return path.length > 0 ? path.substring(1) : path;
} }
prepareExternalUrl(internal: string): string { prepareExternalUrl(internal: string): string {
var url = Location.joinWithSlash(this._baseHref, internal); const url = Location.joinWithSlash(this._baseHref, internal);
return url.length > 0 ? ('#' + url) : url; return url.length > 0 ? ('#' + url) : url;
} }
pushState(state: any, title: string, path: string, queryParams: string) { pushState(state: any, title: string, path: string, queryParams: string) {
var url = this.prepareExternalUrl(path + Location.normalizeQueryParams(queryParams)); let url = this.prepareExternalUrl(path + Location.normalizeQueryParams(queryParams));
if (url.length == 0) { if (url.length == 0) {
url = this._platformLocation.pathname; url = this._platformLocation.pathname;
} }
@ -84,7 +75,7 @@ export class HashLocationStrategy extends LocationStrategy {
} }
replaceState(state: any, title: string, path: string, queryParams: string) { replaceState(state: any, title: string, path: string, queryParams: string) {
var url = this.prepareExternalUrl(path + Location.normalizeQueryParams(queryParams)); let url = this.prepareExternalUrl(path + Location.normalizeQueryParams(queryParams));
if (url.length == 0) { if (url.length == 0) {
url = this._platformLocation.pathname; url = this._platformLocation.pathname;
} }

View File

@ -0,0 +1,13 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export * from './platform_location';
export * from './location_strategy';
export * from './hash_location_strategy';
export * from './path_location_strategy';
export * from './location';

View File

@ -12,7 +12,8 @@ import {LocationStrategy} from './location_strategy';
/** /**
* `Location` is a service that applications can use to interact with a browser's URL. * @whatItDoes `Location` is a service that applications can use to interact with a browser's URL.
* @description
* Depending on which {@link LocationStrategy} is used, `Location` will either persist * Depending on which {@link LocationStrategy} is used, `Location` will either persist
* to the URL's path or the URL's hash segment. * to the URL's path or the URL's hash segment.
* *
@ -28,19 +29,7 @@ import {LocationStrategy} from './location_strategy';
* - `/my/app/user/123/` **is not** normalized * - `/my/app/user/123/` **is not** normalized
* *
* ### Example * ### Example
* * {@example common/location/ts/path_location_component.ts region='LocationComponent'}
* ```
* import {Component} from '@angular/core';
* import {Location} from '@angular/common';
*
* @Component({selector: 'app-component'})
* class AppCmp {
* constructor(location: Location) {
* location.go('/foo');
* }
* }
* ```
*
* @stable * @stable
*/ */
@Injectable() @Injectable()
@ -49,16 +38,20 @@ export class Location {
_subject: EventEmitter<any> = new EventEmitter(); _subject: EventEmitter<any> = new EventEmitter();
/** @internal */ /** @internal */
_baseHref: string; _baseHref: string;
/** @internal */ /** @internal */
_platformStrategy: LocationStrategy; _platformStrategy: LocationStrategy;
constructor(platformStrategy: LocationStrategy) { constructor(platformStrategy: LocationStrategy) {
this._platformStrategy = platformStrategy; this._platformStrategy = platformStrategy;
var browserBaseHref = this._platformStrategy.getBaseHref(); const browserBaseHref = this._platformStrategy.getBaseHref();
this._baseHref = Location.stripTrailingSlash(_stripIndexHtml(browserBaseHref)); this._baseHref = Location.stripTrailingSlash(_stripIndexHtml(browserBaseHref));
this._platformStrategy.onPopState( this._platformStrategy.onPopState((ev) => {
(ev) => { this._subject.emit({'url': this.path(true), 'pop': true, 'type': ev.type}); }); this._subject.emit({
'url': this.path(true),
'pop': true,
'type': ev.type,
});
});
} }
/** /**
@ -92,7 +85,7 @@ export class Location {
* used, or the `APP_BASE_HREF` if the `PathLocationStrategy` is in use. * used, or the `APP_BASE_HREF` if the `PathLocationStrategy` is in use.
*/ */
prepareExternalUrl(url: string): string { prepareExternalUrl(url: string): string {
if (url.length > 0 && !url.startsWith('/')) { if (url && url[0] !== '/') {
url = '/' + url; url = '/' + url;
} }
return this._platformStrategy.prepareExternalUrl(url); return this._platformStrategy.prepareExternalUrl(url);
@ -139,7 +132,7 @@ export class Location {
* is. * is.
*/ */
public static normalizeQueryParams(params: string): string { public static normalizeQueryParams(params: string): string {
return (params.length > 0 && params.substring(0, 1) != '?') ? ('?' + params) : params; return params && params[0] !== '?' ? '?' + params : params;
} }
/** /**
@ -152,7 +145,7 @@ export class Location {
if (end.length == 0) { if (end.length == 0) {
return start; return start;
} }
var slashes = 0; let slashes = 0;
if (start.endsWith('/')) { if (start.endsWith('/')) {
slashes++; slashes++;
} }
@ -171,25 +164,13 @@ export class Location {
/** /**
* If url has a trailing slash, remove it, otherwise return url as is. * If url has a trailing slash, remove it, otherwise return url as is.
*/ */
public static stripTrailingSlash(url: string): string { public static stripTrailingSlash(url: string): string { return url.replace(/\/$/, ''); }
if (/\/$/g.test(url)) {
url = url.substring(0, url.length - 1);
}
return url;
}
} }
function _stripBaseHref(baseHref: string, url: string): string { function _stripBaseHref(baseHref: string, url: string): string {
if (baseHref.length > 0 && url.startsWith(baseHref)) { return baseHref && url.startsWith(baseHref) ? url.substring(baseHref.length) : url;
return url.substring(baseHref.length);
}
return url;
} }
function _stripIndexHtml(url: string): string { function _stripIndexHtml(url: string): string {
if (/\/index.html$/g.test(url)) { return url.replace(/\/index.html$/, '');
// '/index.html'.length == 11
return url.substring(0, url.length - 11);
}
return url;
} }

View File

@ -12,7 +12,7 @@ import {LocationChangeListener} from './platform_location';
/** /**
* `LocationStrategy` is responsible for representing and reading route state * `LocationStrategy` is responsible for representing and reading route state
* from the browser's URL. Angular provides two strategies: * from the browser's URL. Angular provides two strategies:
* {@link HashLocationStrategy} and {@link PathLocationStrategy} (default). * {@link HashLocationStrategy} and {@link PathLocationStrategy}.
* *
* This is used under the hood of the {@link Location} service. * This is used under the hood of the {@link Location} service.
* *

View File

@ -17,14 +17,13 @@ import {LocationChangeListener, PlatformLocation} from './platform_location';
/** /**
* @whatItDoes Use URL for storing application location data.
* @description
* `PathLocationStrategy` is a {@link LocationStrategy} used to configure the * `PathLocationStrategy` is a {@link LocationStrategy} used to configure the
* {@link Location} service to represent its state in the * {@link Location} service to represent its state in the
* [path](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) of the * [path](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) of the
* browser's URL. * browser's URL.
* *
* `PathLocationStrategy` is the default binding for {@link LocationStrategy}
* provided in {@link ROUTER_PROVIDERS}.
*
* If you're using `PathLocationStrategy`, you must provide a {@link APP_BASE_HREF} * If you're using `PathLocationStrategy`, you must provide a {@link APP_BASE_HREF}
* or add a base element to the document. This URL prefix that will be preserved * or add a base element to the document. This URL prefix that will be preserved
* when generating and recognizing URLs. * when generating and recognizing URLs.
@ -37,6 +36,10 @@ import {LocationChangeListener, PlatformLocation} from './platform_location';
* `location.go('/foo')`, the browser's URL will become * `location.go('/foo')`, the browser's URL will become
* `example.com/my/app/foo`. * `example.com/my/app/foo`.
* *
* ### Example
*
* {@example common/location/ts/path_location_component.ts region='LocationComponent'}
*
* @stable * @stable
*/ */
@Injectable() @Injectable()
@ -79,12 +82,12 @@ export class PathLocationStrategy extends LocationStrategy {
} }
pushState(state: any, title: string, url: string, queryParams: string) { pushState(state: any, title: string, url: string, queryParams: string) {
var externalUrl = this.prepareExternalUrl(url + Location.normalizeQueryParams(queryParams)); const externalUrl = this.prepareExternalUrl(url + Location.normalizeQueryParams(queryParams));
this._platformLocation.pushState(state, title, externalUrl); this._platformLocation.pushState(state, title, externalUrl);
} }
replaceState(state: any, title: string, url: string, queryParams: string) { replaceState(state: any, title: string, url: string, queryParams: string) {
var externalUrl = this.prepareExternalUrl(url + Location.normalizeQueryParams(queryParams)); const externalUrl = this.prepareExternalUrl(url + Location.normalizeQueryParams(queryParams));
this._platformLocation.replaceState(state, title, externalUrl); this._platformLocation.replaceState(state, title, externalUrl);
} }

View File

@ -59,7 +59,7 @@ const _observableStrategy = new ObservableStrategy();
* {@example common/pipes/ts/async_pipe.ts region='AsyncPipePromise'} * {@example common/pipes/ts/async_pipe.ts region='AsyncPipePromise'}
* *
* It's also possible to use `async` with Observables. The example below binds the `time` Observable * It's also possible to use `async` with Observables. The example below binds the `time` Observable
* to the view. The Observable continuesly updates the view with the current time. * to the view. The Observable continuously updates the view with the current time.
* *
* {@example common/pipes/ts/async_pipe.ts region='AsyncPipeObservable'} * {@example common/pipes/ts/async_pipe.ts region='AsyncPipeObservable'}
* *

View File

@ -0,0 +1,72 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Pipe, PipeTransform} from '@angular/core';
import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
/**
* Transforms text to lowercase.
*
* {@example common/pipes/ts/lowerupper_pipe.ts region='LowerUpperPipe' }
*
* @stable
*/
@Pipe({name: 'lowercase'})
export class LowerCasePipe implements PipeTransform {
transform(value: string): string {
if (!value) return value;
if (typeof value !== 'string') {
throw new InvalidPipeArgumentError(LowerCasePipe, value);
}
return value.toLowerCase();
}
}
/**
* Helper method to transform a single word to titlecase.
*
* @stable
*/
function titleCaseWord(word: string) {
if (!word) return word;
return word[0].toUpperCase() + word.substr(1).toLowerCase();
}
/**
* Transforms text to titlecase.
*
* @stable
*/
@Pipe({name: 'titlecase'})
export class TitleCasePipe implements PipeTransform {
transform(value: string): string {
if (!value) return value;
if (typeof value !== 'string') {
throw new InvalidPipeArgumentError(TitleCasePipe, value);
}
return value.split(/\b/g).map(word => titleCaseWord(word)).join('');
}
}
/**
* Transforms text to uppercase.
*
* @stable
*/
@Pipe({name: 'uppercase'})
export class UpperCasePipe implements PipeTransform {
transform(value: string): string {
if (!value) return value;
if (typeof value !== 'string') {
throw new InvalidPipeArgumentError(UpperCasePipe, value);
}
return value.toUpperCase();
}
}

View File

@ -7,11 +7,14 @@
*/ */
import {Inject, LOCALE_ID, Pipe, PipeTransform} from '@angular/core'; import {Inject, LOCALE_ID, Pipe, PipeTransform} from '@angular/core';
import {DateFormatter} from '../facade/intl';
import {NumberWrapper, isBlank, isDate} from '../facade/lang'; import {NumberWrapper, isDate} from '../facade/lang';
import {DateFormatter} from './intl';
import {InvalidPipeArgumentError} from './invalid_pipe_argument_error'; import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
/** /**
* @ngModule CommonModule * @ngModule CommonModule
* @whatItDoes Formats a date according to locale rules. * @whatItDoes Formats a date according to locale rules.
@ -33,27 +36,30 @@ import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
* - `'shortTime'`: equivalent to `'jm'` (e.g. `12:05 PM` for `en-US`) * - `'shortTime'`: equivalent to `'jm'` (e.g. `12:05 PM` for `en-US`)
* *
* *
* | Component | Symbol | Short Form | Long Form | Numeric | 2-digit | * | Component | Symbol | Narrow | Short Form | Long Form | Numeric | 2-digit |
* |-----------|:------:|--------------|-------------------|-----------|-----------| * |-----------|:------:|--------|--------------|-------------------|-----------|-----------|
* | era | G | G (AD) | GGGG (Anno Domini)| - | - | * | era | G | G (A) | GGG (AD) | GGGG (Anno Domini)| - | - |
* | year | y | - | - | y (2015) | yy (15) | * | year | y | - | - | - | y (2015) | yy (15) |
* | month | M | MMM (Sep) | MMMM (September) | M (9) | MM (09) | * | month | M | L (S) | MMM (Sep) | MMMM (September) | M (9) | MM (09) |
* | day | d | - | - | d (3) | dd (03) | * | day | d | - | - | - | d (3) | dd (03) |
* | weekday | E | EEE (Sun) | EEEE (Sunday) | - | - | * | weekday | E | E (S) | EEE (Sun) | EEEE (Sunday) | - | - |
* | hour | j | - | - | j (13) | jj (13) | * | hour | j | - | - | - | j (13) | jj (13) |
* | hour12 | h | - | - | h (1 PM) | hh (01 PM)| * | hour12 | h | - | - | - | h (1 PM) | hh (01 PM)|
* | hour24 | H | - | - | H (13) | HH (13) | * | hour24 | H | - | - | - | H (13) | HH (13) |
* | minute | m | - | - | m (5) | mm (05) | * | minute | m | - | - | - | m (5) | mm (05) |
* | second | s | - | - | s (9) | ss (09) | * | second | s | - | - | - | s (9) | ss (09) |
* | timezone | z | - | z (Pacific Standard Time)| - | - | * | timezone | z | - | - | z (Pacific Standard Time)| - | - |
* | timezone | Z | Z (GMT-8:00) | - | - | - | * | timezone | Z | - | Z (GMT-8:00) | - | - | - |
* | timezone | a | a (PM) | - | - | - | * | timezone | a | - | a (PM) | - | - | - |
* *
* In javascript, only the components specified will be respected (not the ordering, * In javascript, only the components specified will be respected (not the ordering,
* punctuations, ...) and details of the formatting will be dependent on the locale. * punctuations, ...) and details of the formatting will be dependent on the locale.
* *
* Timezone of the formatted text will be the local system timezone of the end-user's machine. * Timezone of the formatted text will be the local system timezone of the end-user's machine.
* *
* When the expression is a ISO string without time (e.g. 2016-09-19) the time zone offset is not
* applied and the formatted text will have the same day, month and year of the expression.
*
* WARNINGS: * WARNINGS:
* - this pipe is marked as pure hence it will not be re-evaluated when the input is mutated. * - this pipe is marked as pure hence it will not be re-evaluated when the input is mutated.
* Instead users should treat the date as an immutable object and change the reference when the * Instead users should treat the date as an immutable object and change the reference when the
@ -95,22 +101,42 @@ export class DatePipe implements PipeTransform {
constructor(@Inject(LOCALE_ID) private _locale: string) {} constructor(@Inject(LOCALE_ID) private _locale: string) {}
transform(value: any, pattern: string = 'mediumDate'): string { transform(value: any, pattern: string = 'mediumDate'): string {
let date: Date;
if (isBlank(value)) return null; if (isBlank(value)) return null;
if (!this.supports(value)) { if (typeof value === 'string') {
value = value.trim();
}
if (isDate(value)) {
date = value;
} else if (NumberWrapper.isNumeric(value)) {
date = new Date(parseFloat(value));
} else if (typeof value === 'string' && /^(\d{4}-\d{1,2}-\d{1,2})$/.test(value)) {
/**
* For ISO Strings without time the day, month and year must be extracted from the ISO String
* before Date creation to avoid time offset and errors in the new Date.
* If we only replace '-' with ',' in the ISO String ("2015,01,01"), and try to create a new
* date, some browsers (e.g. IE 9) will throw an invalid Date error
* If we leave the '-' ("2015-01-01") and try to create a new Date("2015-01-01") the timeoffset
* is applied
* Note: ISO months are 0 for January, 1 for February, ...
*/
const [y, m, d] = value.split('-').map((val: string) => parseInt(val, 10));
date = new Date(y, m - 1, d);
} else {
date = new Date(value);
}
if (!isDate(date)) {
throw new InvalidPipeArgumentError(DatePipe, value); throw new InvalidPipeArgumentError(DatePipe, value);
} }
if (NumberWrapper.isNumeric(value)) { return DateFormatter.format(date, this._locale, DatePipe._ALIASES[pattern] || pattern);
value = parseFloat(value);
}
return DateFormatter.format(
new Date(value), this._locale, DatePipe._ALIASES[pattern] || pattern);
}
private supports(obj: any): boolean {
return isDate(obj) || NumberWrapper.isNumeric(obj) ||
(typeof obj === 'string' && isDate(new Date(obj)));
} }
} }
function isBlank(obj: any): boolean {
return obj == null || obj === '';
}

View File

@ -7,7 +7,7 @@
*/ */
import {Pipe, PipeTransform} from '@angular/core'; import {Pipe, PipeTransform} from '@angular/core';
import {isBlank, isStringMap} from '../facade/lang'; import {isBlank} from '../facade/lang';
import {NgLocalization, getPluralCategory} from '../localization'; import {NgLocalization, getPluralCategory} from '../localization';
import {InvalidPipeArgumentError} from './invalid_pipe_argument_error'; import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
@ -37,7 +37,7 @@ export class I18nPluralPipe implements PipeTransform {
transform(value: number, pluralMap: {[count: string]: string}): string { transform(value: number, pluralMap: {[count: string]: string}): string {
if (isBlank(value)) return ''; if (isBlank(value)) return '';
if (!isStringMap(pluralMap)) { if (typeof pluralMap !== 'object' || pluralMap === null) {
throw new InvalidPipeArgumentError(I18nPluralPipe, pluralMap); throw new InvalidPipeArgumentError(I18nPluralPipe, pluralMap);
} }

View File

@ -7,7 +7,6 @@
*/ */
import {Pipe, PipeTransform} from '@angular/core'; import {Pipe, PipeTransform} from '@angular/core';
import {isBlank, isStringMap} from '../facade/lang';
import {InvalidPipeArgumentError} from './invalid_pipe_argument_error'; import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
/** /**
@ -16,9 +15,10 @@ import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
* @howToUse `expression | i18nSelect:mapping` * @howToUse `expression | i18nSelect:mapping`
* @description * @description
* *
* Where: * Where `mapping` is an object that indicates the text that should be displayed
* - `mapping`: is an object that indicates the text that should be displayed
* for different values of the provided `expression`. * for different values of the provided `expression`.
* If none of the keys of the mapping match the value of the `expression`, then the content
* of the `other` key is returned when present, otherwise an empty string is returned.
* *
* ## Example * ## Example
* *
@ -29,12 +29,20 @@ import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
@Pipe({name: 'i18nSelect', pure: true}) @Pipe({name: 'i18nSelect', pure: true})
export class I18nSelectPipe implements PipeTransform { export class I18nSelectPipe implements PipeTransform {
transform(value: string, mapping: {[key: string]: string}): string { transform(value: string, mapping: {[key: string]: string}): string {
if (isBlank(value)) return ''; if (value == null) return '';
if (!isStringMap(mapping)) { if (typeof mapping !== 'object' || typeof value !== 'string') {
throw new InvalidPipeArgumentError(I18nSelectPipe, mapping); throw new InvalidPipeArgumentError(I18nSelectPipe, mapping);
} }
return mapping.hasOwnProperty(value) ? mapping[value] : ''; if (mapping.hasOwnProperty(value)) {
return mapping[value];
}
if (mapping.hasOwnProperty('other')) {
return mapping['other'];
}
return '';
} }
} }

View File

@ -12,14 +12,13 @@
* This module provides a set of common Pipes. * This module provides a set of common Pipes.
*/ */
import {AsyncPipe} from './async_pipe'; import {AsyncPipe} from './async_pipe';
import {LowerCasePipe, TitleCasePipe, UpperCasePipe} from './case_conversion_pipes';
import {DatePipe} from './date_pipe'; import {DatePipe} from './date_pipe';
import {I18nPluralPipe} from './i18n_plural_pipe'; import {I18nPluralPipe} from './i18n_plural_pipe';
import {I18nSelectPipe} from './i18n_select_pipe'; import {I18nSelectPipe} from './i18n_select_pipe';
import {JsonPipe} from './json_pipe'; import {JsonPipe} from './json_pipe';
import {LowerCasePipe} from './lowercase_pipe';
import {CurrencyPipe, DecimalPipe, PercentPipe} from './number_pipe'; import {CurrencyPipe, DecimalPipe, PercentPipe} from './number_pipe';
import {SlicePipe} from './slice_pipe'; import {SlicePipe} from './slice_pipe';
import {UpperCasePipe} from './uppercase_pipe';
export { export {
AsyncPipe, AsyncPipe,
@ -32,9 +31,11 @@ export {
LowerCasePipe, LowerCasePipe,
PercentPipe, PercentPipe,
SlicePipe, SlicePipe,
TitleCasePipe,
UpperCasePipe UpperCasePipe
}; };
/** /**
* A collection of Angular pipes that are likely to be used in each and every application. * A collection of Angular pipes that are likely to be used in each and every application.
*/ */
@ -46,6 +47,7 @@ export const COMMON_PIPES = [
SlicePipe, SlicePipe,
DecimalPipe, DecimalPipe,
PercentPipe, PercentPipe,
TitleCasePipe,
CurrencyPipe, CurrencyPipe,
DatePipe, DatePipe,
I18nPluralPipe, I18nPluralPipe,

View File

@ -0,0 +1,226 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export enum NumberFormatStyle {
Decimal,
Percent,
Currency,
}
export class NumberFormatter {
static format(
num: number, locale: string, style: NumberFormatStyle,
{minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, currency,
currencyAsSymbol = false}: {
minimumIntegerDigits?: number,
minimumFractionDigits?: number,
maximumFractionDigits?: number,
currency?: string,
currencyAsSymbol?: boolean
} = {}): string {
const options: Intl.NumberFormatOptions = {
minimumIntegerDigits,
minimumFractionDigits,
maximumFractionDigits,
style: NumberFormatStyle[style].toLowerCase()
};
if (style == NumberFormatStyle.Currency) {
options.currency = currency;
options.currencyDisplay = currencyAsSymbol ? 'symbol' : 'code';
}
return new Intl.NumberFormat(locale, options).format(num);
}
}
type DateFormatterFn = (date: Date, locale: string) => string;
const DATE_FORMATS_SPLIT =
/((?:[^yMLdHhmsazZEwGjJ']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|J+|j+|m+|s+|a|z|Z|G+|w+))(.*)/;
const PATTERN_ALIASES: {[format: string]: DateFormatterFn} = {
// Keys are quoted so they do not get renamed during closure compilation.
'yMMMdjms': datePartGetterFactory(combine([
digitCondition('year', 1),
nameCondition('month', 3),
digitCondition('day', 1),
digitCondition('hour', 1),
digitCondition('minute', 1),
digitCondition('second', 1),
])),
'yMdjm': datePartGetterFactory(combine([
digitCondition('year', 1), digitCondition('month', 1), digitCondition('day', 1),
digitCondition('hour', 1), digitCondition('minute', 1)
])),
'yMMMMEEEEd': datePartGetterFactory(combine([
digitCondition('year', 1), nameCondition('month', 4), nameCondition('weekday', 4),
digitCondition('day', 1)
])),
'yMMMMd': datePartGetterFactory(
combine([digitCondition('year', 1), nameCondition('month', 4), digitCondition('day', 1)])),
'yMMMd': datePartGetterFactory(
combine([digitCondition('year', 1), nameCondition('month', 3), digitCondition('day', 1)])),
'yMd': datePartGetterFactory(
combine([digitCondition('year', 1), digitCondition('month', 1), digitCondition('day', 1)])),
'jms': datePartGetterFactory(combine(
[digitCondition('hour', 1), digitCondition('second', 1), digitCondition('minute', 1)])),
'jm': datePartGetterFactory(combine([digitCondition('hour', 1), digitCondition('minute', 1)]))
};
const DATE_FORMATS: {[format: string]: DateFormatterFn} = {
// Keys are quoted so they do not get renamed.
'yyyy': datePartGetterFactory(digitCondition('year', 4)),
'yy': datePartGetterFactory(digitCondition('year', 2)),
'y': datePartGetterFactory(digitCondition('year', 1)),
'MMMM': datePartGetterFactory(nameCondition('month', 4)),
'MMM': datePartGetterFactory(nameCondition('month', 3)),
'MM': datePartGetterFactory(digitCondition('month', 2)),
'M': datePartGetterFactory(digitCondition('month', 1)),
'LLLL': datePartGetterFactory(nameCondition('month', 4)),
'L': datePartGetterFactory(nameCondition('month', 1)),
'dd': datePartGetterFactory(digitCondition('day', 2)),
'd': datePartGetterFactory(digitCondition('day', 1)),
'HH': digitModifier(
hourExtractor(datePartGetterFactory(hour12Modify(digitCondition('hour', 2), false)))),
'H': hourExtractor(datePartGetterFactory(hour12Modify(digitCondition('hour', 1), false))),
'hh': digitModifier(
hourExtractor(datePartGetterFactory(hour12Modify(digitCondition('hour', 2), true)))),
'h': hourExtractor(datePartGetterFactory(hour12Modify(digitCondition('hour', 1), true))),
'jj': datePartGetterFactory(digitCondition('hour', 2)),
'j': datePartGetterFactory(digitCondition('hour', 1)),
'mm': digitModifier(datePartGetterFactory(digitCondition('minute', 2))),
'm': datePartGetterFactory(digitCondition('minute', 1)),
'ss': digitModifier(datePartGetterFactory(digitCondition('second', 2))),
's': datePartGetterFactory(digitCondition('second', 1)),
// while ISO 8601 requires fractions to be prefixed with `.` or `,`
// we can be just safely rely on using `sss` since we currently don't support single or two digit
// fractions
'sss': datePartGetterFactory(digitCondition('second', 3)),
'EEEE': datePartGetterFactory(nameCondition('weekday', 4)),
'EEE': datePartGetterFactory(nameCondition('weekday', 3)),
'EE': datePartGetterFactory(nameCondition('weekday', 2)),
'E': datePartGetterFactory(nameCondition('weekday', 1)),
'a': hourClockExtractor(datePartGetterFactory(hour12Modify(digitCondition('hour', 1), true))),
'Z': timeZoneGetter('short'),
'z': timeZoneGetter('long'),
'ww': datePartGetterFactory({}), // Week of year, padded (00-53). Week 01 is the week with the
// first Thursday of the year. not support ?
'w':
datePartGetterFactory({}), // Week of year (0-53). Week 1 is the week with the first Thursday
// of the year not support ?
'G': datePartGetterFactory(nameCondition('era', 1)),
'GG': datePartGetterFactory(nameCondition('era', 2)),
'GGG': datePartGetterFactory(nameCondition('era', 3)),
'GGGG': datePartGetterFactory(nameCondition('era', 4))
};
function digitModifier(inner: DateFormatterFn): DateFormatterFn {
return function(date: Date, locale: string): string {
const result = inner(date, locale);
return result.length == 1 ? '0' + result : result;
};
}
function hourClockExtractor(inner: DateFormatterFn): DateFormatterFn {
return function(date: Date, locale: string): string { return inner(date, locale).split(' ')[1]; };
}
function hourExtractor(inner: DateFormatterFn): DateFormatterFn {
return function(date: Date, locale: string): string { return inner(date, locale).split(' ')[0]; };
}
function intlDateFormat(date: Date, locale: string, options: Intl.DateTimeFormatOptions): string {
return new Intl.DateTimeFormat(locale, options).format(date).replace(/[\u200e\u200f]/g, '');
}
function timeZoneGetter(timezone: string): DateFormatterFn {
// To workaround `Intl` API restriction for single timezone let format with 24 hours
const options = {hour: '2-digit', hour12: false, timeZoneName: timezone};
return function(date: Date, locale: string): string {
const result = intlDateFormat(date, locale, options);
// Then extract first 3 letters that related to hours
return result ? result.substring(3) : '';
};
}
function hour12Modify(
options: Intl.DateTimeFormatOptions, value: boolean): Intl.DateTimeFormatOptions {
options.hour12 = value;
return options;
}
function digitCondition(prop: string, len: number): Intl.DateTimeFormatOptions {
const result: {[k: string]: string} = {};
result[prop] = len === 2 ? '2-digit' : 'numeric';
return result;
}
function nameCondition(prop: string, len: number): Intl.DateTimeFormatOptions {
const result: {[k: string]: string} = {};
if (len < 4) {
result[prop] = len > 1 ? 'short' : 'narrow';
} else {
result[prop] = 'long';
}
return result;
}
function combine(options: Intl.DateTimeFormatOptions[]): Intl.DateTimeFormatOptions {
return (<any>Object).assign({}, ...options);
}
function datePartGetterFactory(ret: Intl.DateTimeFormatOptions): DateFormatterFn {
return (date: Date, locale: string): string => intlDateFormat(date, locale, ret);
}
const DATE_FORMATTER_CACHE = new Map<string, string[]>();
function dateFormatter(format: string, date: Date, locale: string): string {
const fn = PATTERN_ALIASES[format];
if (fn) return fn(date, locale);
const cacheKey = format;
let parts = DATE_FORMATTER_CACHE.get(cacheKey);
if (!parts) {
parts = [];
let match: RegExpExecArray;
DATE_FORMATS_SPLIT.exec(format);
while (format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = parts.concat(match.slice(1));
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
DATE_FORMATTER_CACHE.set(cacheKey, parts);
}
return parts.reduce((text, part) => {
const fn = DATE_FORMATS[part];
return text + (fn ? fn(date, locale) : partToTime(part));
}, '');
}
function partToTime(part: string): string {
return part === '\'\'' ? '\'' : part.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
}
export class DateFormatter {
static format(date: Date, locale: string, pattern: string): string {
return dateFormatter(pattern, date, locale);
}
}

View File

@ -8,10 +8,6 @@
import {Pipe, PipeTransform} from '@angular/core'; import {Pipe, PipeTransform} from '@angular/core';
import {Json} from '../facade/lang';
/** /**
* @ngModule CommonModule * @ngModule CommonModule
* @whatItDoes Converts value into JSON string. * @whatItDoes Converts value into JSON string.
@ -27,5 +23,5 @@ import {Json} from '../facade/lang';
*/ */
@Pipe({name: 'json', pure: false}) @Pipe({name: 'json', pure: false})
export class JsonPipe implements PipeTransform { export class JsonPipe implements PipeTransform {
transform(value: any): string { return Json.stringify(value); } transform(value: any): string { return JSON.stringify(value, null, 2); }
} }

View File

@ -1,37 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Pipe, PipeTransform} from '@angular/core';
import {isBlank} from '../facade/lang';
import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
/**
* @ngModule CommonModule
* @whatItDoes Transforms string to lowercase.
* @howToUse `expression | lowercase`
* @description
*
* Converts value into lowercase string using `String.prototype.toLowerCase()`.
*
* ### Example
*
* {@example common/pipes/ts/lowerupper_pipe.ts region='LowerUpperPipe'}
*
* @stable
*/
@Pipe({name: 'lowercase'})
export class LowerCasePipe implements PipeTransform {
transform(value: string): string {
if (isBlank(value)) return value;
if (typeof value !== 'string') {
throw new InvalidPipeArgumentError(LowerCasePipe, value);
}
return value.toLowerCase();
}
}

View File

@ -8,9 +8,9 @@
import {Inject, LOCALE_ID, Pipe, PipeTransform, Type} from '@angular/core'; import {Inject, LOCALE_ID, Pipe, PipeTransform, Type} from '@angular/core';
import {NumberFormatStyle, NumberFormatter} from '../facade/intl';
import {NumberWrapper, isBlank, isPresent} from '../facade/lang'; import {NumberWrapper, isBlank, isPresent} from '../facade/lang';
import {NumberFormatStyle, NumberFormatter} from './intl';
import {InvalidPipeArgumentError} from './invalid_pipe_argument_error'; import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/; const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;
@ -37,7 +37,7 @@ function formatNumber(
} }
if (digits) { if (digits) {
let parts = digits.match(_NUMBER_FORMAT_REGEXP); const parts = digits.match(_NUMBER_FORMAT_REGEXP);
if (parts === null) { if (parts === null) {
throw new Error(`${digits} is not a valid digit info for number pipes`); throw new Error(`${digits} is not a valid digit info for number pipes`);
} }

View File

@ -1,36 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Pipe, PipeTransform} from '@angular/core';
import {isBlank} from '../facade/lang';
import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
/**
* @ngModule CommonModule
* @whatItDoes Transforms string to uppercase.
* @howToUse `expression | uppercase`
* @description
*
* Converts value into lowercase string using `String.prototype.toUpperCase()`.
*
* ### Example
*
* {@example common/pipes/ts/lowerupper_pipe.ts region='LowerUpperPipe'}
*
* @stable
*/
@Pipe({name: 'uppercase'})
export class UpperCasePipe implements PipeTransform {
transform(value: string): string {
if (isBlank(value)) return value;
if (typeof value !== 'string') {
throw new InvalidPipeArgumentError(UpperCasePipe, value);
}
return value.toUpperCase();
}
}

View File

@ -0,0 +1,19 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
import {Version} from '@angular/core';
/**
* @stable
*/
export const VERSION = new Version('0.0.0-PLACEHOLDER');

View File

@ -8,7 +8,6 @@
import {Component} from '@angular/core'; import {Component} from '@angular/core';
import {ComponentFixture, TestBed, async} from '@angular/core/testing'; import {ComponentFixture, TestBed, async} from '@angular/core/testing';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
export function main() { export function main() {
describe('binding to CSS class list', () => { describe('binding to CSS class list', () => {
@ -66,7 +65,7 @@ export function main() {
it('should add and remove classes based on changes to the expression object', async(() => { it('should add and remove classes based on changes to the expression object', async(() => {
fixture = createTestComponent('<div [ngClass]="objExpr"></div>'); fixture = createTestComponent('<div [ngClass]="objExpr"></div>');
let objExpr = getComponent().objExpr; const objExpr = getComponent().objExpr;
detectChangesAndExpectClassName('foo'); detectChangesAndExpectClassName('foo');
@ -135,7 +134,7 @@ export function main() {
it('should add and remove classes based on changes to the expression', async(() => { it('should add and remove classes based on changes to the expression', async(() => {
fixture = createTestComponent('<div [ngClass]="arrExpr"></div>'); fixture = createTestComponent('<div [ngClass]="arrExpr"></div>');
let arrExpr = getComponent().arrExpr; const arrExpr = getComponent().arrExpr;
detectChangesAndExpectClassName('foo'); detectChangesAndExpectClassName('foo');
arrExpr.push('bar'); arrExpr.push('bar');
@ -187,6 +186,13 @@ export function main() {
getComponent().arrExpr = ['foo bar baz foobar']; getComponent().arrExpr = ['foo bar baz foobar'];
detectChangesAndExpectClassName('foo bar baz foobar'); detectChangesAndExpectClassName('foo bar baz foobar');
})); }));
it('should throw with descriptive error message when CSS class is not a string', () => {
fixture = createTestComponent(`<div [ngClass]="['foo', {}]"></div>`);
expect(() => fixture.detectChanges())
.toThrowError(
/NgClass can only toggle CSS classes expressed as strings, got \[object Object\]/);
});
}); });
describe('expressions evaluating to sets', () => { describe('expressions evaluating to sets', () => {
@ -253,7 +259,7 @@ export function main() {
it('should co-operate with the class attribute', async(() => { it('should co-operate with the class attribute', async(() => {
fixture = createTestComponent('<div [ngClass]="objExpr" class="init foo"></div>'); fixture = createTestComponent('<div [ngClass]="objExpr" class="init foo"></div>');
let objExpr = getComponent().objExpr; const objExpr = getComponent().objExpr;
objExpr['bar'] = true; objExpr['bar'] = true;
detectChangesAndExpectClassName('init foo bar'); detectChangesAndExpectClassName('init foo bar');
@ -267,7 +273,7 @@ export function main() {
it('should co-operate with the interpolated class attribute', async(() => { it('should co-operate with the interpolated class attribute', async(() => {
fixture = createTestComponent(`<div [ngClass]="objExpr" class="{{'init foo'}}"></div>`); fixture = createTestComponent(`<div [ngClass]="objExpr" class="{{'init foo'}}"></div>`);
let objExpr = getComponent().objExpr; const objExpr = getComponent().objExpr;
objExpr['bar'] = true; objExpr['bar'] = true;
detectChangesAndExpectClassName(`init foo bar`); detectChangesAndExpectClassName(`init foo bar`);
@ -282,7 +288,7 @@ export function main() {
it('should co-operate with the class attribute and binding to it', async(() => { it('should co-operate with the class attribute and binding to it', async(() => {
fixture = fixture =
createTestComponent(`<div [ngClass]="objExpr" class="init" [class]="'foo'"></div>`); createTestComponent(`<div [ngClass]="objExpr" class="init" [class]="'foo'"></div>`);
let objExpr = getComponent().objExpr; const objExpr = getComponent().objExpr;
objExpr['bar'] = true; objExpr['bar'] = true;
detectChangesAndExpectClassName(`init foo bar`); detectChangesAndExpectClassName(`init foo bar`);
@ -298,7 +304,7 @@ export function main() {
const template = const template =
'<div class="init foo" [ngClass]="objExpr" [class.baz]="condition"></div>'; '<div class="init foo" [ngClass]="objExpr" [class.baz]="condition"></div>';
fixture = createTestComponent(template); fixture = createTestComponent(template);
let objExpr = getComponent().objExpr; const objExpr = getComponent().objExpr;
detectChangesAndExpectClassName('init foo baz'); detectChangesAndExpectClassName('init foo baz');
@ -316,7 +322,7 @@ export function main() {
async(() => { async(() => {
const template = '<div class="init" [ngClass]="objExpr" [class]="strExpr"></div>'; const template = '<div class="init" [ngClass]="objExpr" [class]="strExpr"></div>';
fixture = createTestComponent(template); fixture = createTestComponent(template);
let cmp = getComponent(); const cmp = getComponent();
detectChangesAndExpectClassName('init foo'); detectChangesAndExpectClassName('init foo');
@ -348,4 +354,4 @@ class TestComponent {
function createTestComponent(template: string): ComponentFixture<TestComponent> { function createTestComponent(template: string): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template}}) return TestBed.overrideComponent(TestComponent, {set: {template: template}})
.createComponent(TestComponent); .createComponent(TestComponent);
} }

View File

@ -264,7 +264,7 @@ export function main() {
})); }));
it('should use a default template if a custom one is null', async(() => { it('should use a default template if a custom one is null', async(() => {
const testTemplate = `<ul><template ngFor let-item [ngForOf]="items" const testTemplate = `<ul><template ngFor let-item [ngForOf]="items"
[ngForTemplate]="contentTpl" let-i="index">{{i}}: {{item}};</template></ul>`; [ngForTemplate]="contentTpl" let-i="index">{{i}}: {{item}};</template></ul>`;
TestBed.overrideComponent(TestComponent, {set: {template: testTemplate}}); TestBed.overrideComponent(TestComponent, {set: {template: testTemplate}});
const cutTemplate = const cutTemplate =
@ -294,6 +294,27 @@ export function main() {
})); }));
describe('track by', () => { describe('track by', () => {
it('should console.warn if trackBy is not a function', async(() => {
// TODO(vicb): expect a warning message when we have a proper log service
const template =
`<template ngFor let-item [ngForOf]="items" [ngForTrackBy]="value"></template>`;
fixture = createTestComponent(template);
fixture.componentInstance.value = 0;
fixture.detectChanges();
}));
it('should track by identity when trackBy is to `null` or `undefined`', async(() => {
// TODO(vicb): expect no warning message when we have a proper log service
const template =
`<template ngFor let-item [ngForOf]="items" [ngForTrackBy]="value">{{ item }}</template>`;
fixture = createTestComponent(template);
fixture.componentInstance.items = ['a', 'b', 'c'];
fixture.componentInstance.value = null;
detectChangesAndExpectText('abc');
fixture.componentInstance.value = undefined;
detectChangesAndExpectText('abc');
}));
it('should set the context to the component instance', async(() => { it('should set the context to the component instance', async(() => {
const template = const template =
`<template ngFor let-item [ngForOf]="items" [ngForTrackBy]="trackByContext.bind(this)"></template>`; `<template ngFor let-item [ngForOf]="items" [ngForTrackBy]="trackByContext.bind(this)"></template>`;
@ -333,6 +354,7 @@ export function main() {
getComponent().items = [{'id': 'a', 'color': 'red'}]; getComponent().items = [{'id': 'a', 'color': 'red'}];
detectChangesAndExpectText('red'); detectChangesAndExpectText('red');
})); }));
it('should move items around and keep them updated ', async(() => { it('should move items around and keep them updated ', async(() => {
const template = const template =
`<div><template ngFor let-item [ngForOf]="items" [ngForTrackBy]="trackById">{{item['color']}}</template></div>`; `<div><template ngFor let-item [ngForOf]="items" [ngForTrackBy]="trackById">{{item['color']}}</template></div>`;
@ -368,6 +390,7 @@ class Foo {
@Component({selector: 'test-cmp', template: ''}) @Component({selector: 'test-cmp', template: ''})
class TestComponent { class TestComponent {
@ContentChild(TemplateRef) contentTpl: TemplateRef<Object>; @ContentChild(TemplateRef) contentTpl: TemplateRef<Object>;
value: any;
items: any[] = [1, 2]; items: any[] = [1, 2];
trackById(index: number, item: any): string { return item['id']; } trackById(index: number, item: any): string { return item['id']; }
trackByIndex(index: number, item: any): number { return index; } trackByIndex(index: number, item: any): number { return index; }
@ -384,4 +407,4 @@ const TEMPLATE = '<div><span template="ngFor let item of items">{{item.toString(
function createTestComponent(template: string = TEMPLATE): ComponentFixture<TestComponent> { function createTestComponent(template: string = TEMPLATE): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template}}) return TestBed.overrideComponent(TestComponent, {set: {template: template}})
.createComponent(TestComponent); .createComponent(TestComponent);
} }

View File

@ -153,6 +153,78 @@ export function main() {
expect(getDOM().hasClass(getDOM().querySelector(fixture.nativeElement, 'span'), 'foo')) expect(getDOM().hasClass(getDOM().querySelector(fixture.nativeElement, 'span'), 'foo'))
.toBe(true); .toBe(true);
})); }));
describe('else', () => {
it('should support else', async(() => {
const template = '<div>' +
'<span *ngIf="booleanCondition; else elseBlock">TRUE</span>' +
'<template #elseBlock>FALSE</template>' +
'</div>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('TRUE');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('FALSE');
}));
it('should support then and else', async(() => {
const template = '<div>' +
'<span *ngIf="booleanCondition; then thenBlock; else elseBlock">IGNORE</span>' +
'<template #thenBlock>THEN</template>' +
'<template #elseBlock>ELSE</template>' +
'</div>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('THEN');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('ELSE');
}));
it('should support dynamic else', async(() => {
const template = '<div>' +
'<span *ngIf="booleanCondition; else nestedBooleanCondition ? b1 : b2">TRUE</span>' +
'<template #b1>FALSE1</template>' +
'<template #b2>FALSE2</template>' +
'</div>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('TRUE');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('FALSE1');
getComponent().nestedBooleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('FALSE2');
}));
it('should support binding to variable', async(() => {
const template = '<div>' +
'<span *ngIf="booleanCondition; else elseBlock; let v">{{v}}</span>' +
'<template #elseBlock let-v>{{v}}</template>' +
'</div>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('true');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('false');
}));
});
}); });
} }

View File

@ -7,8 +7,8 @@
*/ */
import {CommonModule} from '@angular/common'; import {CommonModule} from '@angular/common';
import {Component} from '@angular/core'; import {Attribute, Component, Directive} from '@angular/core';
import {ComponentFixture, TestBed, async} from '@angular/core/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/matchers'; import {expect} from '@angular/platform-browser/testing/matchers';
export function main() { export function main() {
@ -32,109 +32,153 @@ export function main() {
}); });
describe('switch value changes', () => { describe('switch value changes', () => {
it('should switch amongst when values', async(() => { it('should switch amongst when values', () => {
const template = '<div>' + const template = '<div>' +
'<ul [ngSwitch]="switchValue">' + '<ul [ngSwitch]="switchValue">' +
'<template ngSwitchCase="a"><li>when a</li></template>' + '<template ngSwitchCase="a"><li>when a</li></template>' +
'<template ngSwitchCase="b"><li>when b</li></template>' + '<template ngSwitchCase="b"><li>when b</li></template>' +
'</ul></div>'; '</ul></div>';
fixture = createTestComponent(template); fixture = createTestComponent(template);
detectChangesAndExpectText(''); detectChangesAndExpectText('');
getComponent().switchValue = 'a'; getComponent().switchValue = 'a';
detectChangesAndExpectText('when a'); detectChangesAndExpectText('when a');
getComponent().switchValue = 'b'; getComponent().switchValue = 'b';
detectChangesAndExpectText('when b'); detectChangesAndExpectText('when b');
})); });
// TODO(robwormald): deprecate and remove it('should switch amongst when values with fallback to default', () => {
it('should switch amongst when values using switchCase', async(() => { const template = '<div>' +
const template = '<div>' + '<ul [ngSwitch]="switchValue">' +
'<ul [ngSwitch]="switchValue">' + '<li template="ngSwitchCase \'a\'">when a</li>' +
'<template ngSwitchCase="a"><li>when a</li></template>' + '<li template="ngSwitchDefault">when default</li>' +
'<template ngSwitchCase="b"><li>when b</li></template>' + '</ul></div>';
'</ul></div>';
fixture = createTestComponent(template); fixture = createTestComponent(template);
detectChangesAndExpectText('when default');
detectChangesAndExpectText(''); getComponent().switchValue = 'a';
detectChangesAndExpectText('when a');
getComponent().switchValue = 'a'; getComponent().switchValue = 'b';
detectChangesAndExpectText('when a'); detectChangesAndExpectText('when default');
getComponent().switchValue = 'b'; getComponent().switchValue = 'c';
detectChangesAndExpectText('when b'); detectChangesAndExpectText('when default');
})); });
it('should switch amongst when values with fallback to default', async(() => { it('should support multiple whens with the same value', () => {
const template = '<div>' + const template = '<div>' +
'<ul [ngSwitch]="switchValue">' + '<ul [ngSwitch]="switchValue">' +
'<li template="ngSwitchCase \'a\'">when a</li>' + '<template ngSwitchCase="a"><li>when a1;</li></template>' +
'<li template="ngSwitchDefault">when default</li>' + '<template ngSwitchCase="b"><li>when b1;</li></template>' +
'</ul></div>'; '<template ngSwitchCase="a"><li>when a2;</li></template>' +
'<template ngSwitchCase="b"><li>when b2;</li></template>' +
'<template ngSwitchDefault><li>when default1;</li></template>' +
'<template ngSwitchDefault><li>when default2;</li></template>' +
'</ul></div>';
fixture = createTestComponent(template); fixture = createTestComponent(template);
detectChangesAndExpectText('when default'); detectChangesAndExpectText('when default1;when default2;');
getComponent().switchValue = 'a'; getComponent().switchValue = 'a';
detectChangesAndExpectText('when a'); detectChangesAndExpectText('when a1;when a2;');
getComponent().switchValue = 'b'; getComponent().switchValue = 'b';
detectChangesAndExpectText('when default'); detectChangesAndExpectText('when b1;when b2;');
})); });
it('should support multiple whens with the same value', async(() => {
const template = '<div>' +
'<ul [ngSwitch]="switchValue">' +
'<template ngSwitchCase="a"><li>when a1;</li></template>' +
'<template ngSwitchCase="b"><li>when b1;</li></template>' +
'<template ngSwitchCase="a"><li>when a2;</li></template>' +
'<template ngSwitchCase="b"><li>when b2;</li></template>' +
'<template ngSwitchDefault><li>when default1;</li></template>' +
'<template ngSwitchDefault><li>when default2;</li></template>' +
'</ul></div>';
fixture = createTestComponent(template);
detectChangesAndExpectText('when default1;when default2;');
getComponent().switchValue = 'a';
detectChangesAndExpectText('when a1;when a2;');
getComponent().switchValue = 'b';
detectChangesAndExpectText('when b1;when b2;');
}));
}); });
describe('when values changes', () => { describe('when values changes', () => {
it('should switch amongst when values', async(() => { it('should switch amongst when values', () => {
const template = '<div>' + const template = '<div>' +
'<ul [ngSwitch]="switchValue">' + '<ul [ngSwitch]="switchValue">' +
'<template [ngSwitchCase]="when1"><li>when 1;</li></template>' + '<template [ngSwitchCase]="when1"><li>when 1;</li></template>' +
'<template [ngSwitchCase]="when2"><li>when 2;</li></template>' + '<template [ngSwitchCase]="when2"><li>when 2;</li></template>' +
'<template ngSwitchDefault><li>when default;</li></template>' + '<template ngSwitchDefault><li>when default;</li></template>' +
'</ul></div>'; '</ul></div>';
fixture = createTestComponent(template); fixture = createTestComponent(template);
getComponent().when1 = 'a'; getComponent().when1 = 'a';
getComponent().when2 = 'b'; getComponent().when2 = 'b';
getComponent().switchValue = 'a'; getComponent().switchValue = 'a';
detectChangesAndExpectText('when 1;'); detectChangesAndExpectText('when 1;');
getComponent().switchValue = 'b'; getComponent().switchValue = 'b';
detectChangesAndExpectText('when 2;'); detectChangesAndExpectText('when 2;');
getComponent().switchValue = 'c'; getComponent().switchValue = 'c';
detectChangesAndExpectText('when default;'); detectChangesAndExpectText('when default;');
getComponent().when1 = 'c'; getComponent().when1 = 'c';
detectChangesAndExpectText('when 1;'); detectChangesAndExpectText('when 1;');
getComponent().when1 = 'd'; getComponent().when1 = 'd';
detectChangesAndExpectText('when default;'); detectChangesAndExpectText('when default;');
})); });
});
describe('corner cases', () => {
it('should not create the default case if another case matches', () => {
const log: string[] = [];
@Directive({selector: '[test]'})
class TestDirective {
constructor(@Attribute('test') test: string) { log.push(test); }
}
const template = '<div [ngSwitch]="switchValue">' +
'<div *ngSwitchCase="\'a\'" test="aCase"></div>' +
'<div *ngSwitchDefault test="defaultCase"></div>' +
'</div>';
TestBed.configureTestingModule({declarations: [TestDirective]});
TestBed.overrideComponent(TestComponent, {set: {template: template}})
.createComponent(TestComponent);
const fixture = TestBed.createComponent(TestComponent);
fixture.componentInstance.switchValue = 'a';
fixture.detectChanges();
expect(log).toEqual(['aCase']);
});
it('should create the default case if there is no other case', () => {
const template = '<div>' +
'<ul [ngSwitch]="switchValue">' +
'<template ngSwitchDefault><li>when default1;</li></template>' +
'<template ngSwitchDefault><li>when default2;</li></template>' +
'</ul></div>';
fixture = createTestComponent(template);
detectChangesAndExpectText('when default1;when default2;');
});
it('should allow defaults before cases', () => {
const template = '<div>' +
'<ul [ngSwitch]="switchValue">' +
'<template ngSwitchDefault><li>when default1;</li></template>' +
'<template ngSwitchDefault><li>when default2;</li></template>' +
'<template ngSwitchCase="a"><li>when a1;</li></template>' +
'<template ngSwitchCase="b"><li>when b1;</li></template>' +
'<template ngSwitchCase="a"><li>when a2;</li></template>' +
'<template ngSwitchCase="b"><li>when b2;</li></template>' +
'</ul></div>';
fixture = createTestComponent(template);
detectChangesAndExpectText('when default1;when default2;');
getComponent().switchValue = 'a';
detectChangesAndExpectText('when a1;when a2;');
getComponent().switchValue = 'b';
detectChangesAndExpectText('when b1;when b2;');
});
}); });
}); });
} }

View File

@ -7,13 +7,10 @@
*/ */
import {LOCALE_ID} from '@angular/core'; import {LOCALE_ID} from '@angular/core';
import {TestBed} from '@angular/core/testing'; import {TestBed, inject} from '@angular/core/testing';
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing/matchers';
import {NgLocaleLocalization, NgLocalization, getPluralCategory} from '../src/localization'; import {NgLocaleLocalization, NgLocalization, getPluralCategory} from '../src/localization';
export function main() { export function main() {
describe('l10n', () => { describe('l10n', () => {
@ -141,6 +138,23 @@ export function main() {
expect(getPluralCategory(5, ['one', 'other', '=5'], l10n)).toEqual('=5'); expect(getPluralCategory(5, ['one', 'other', '=5'], l10n)).toEqual('=5');
expect(getPluralCategory(6, ['one', 'other', '=5'], l10n)).toEqual('other'); expect(getPluralCategory(6, ['one', 'other', '=5'], l10n)).toEqual('other');
}); });
it('should fallback to other when the case is not present', () => {
const l10n = new NgLocaleLocalization('ro');
expect(getPluralCategory(1, ['one', 'other'], l10n)).toEqual('one');
// 2 -> 'few'
expect(getPluralCategory(2, ['one', 'other'], l10n)).toEqual('other');
});
describe('errors', () => {
it('should report an error when the "other" category is not present', () => {
expect(() => {
const l10n = new NgLocaleLocalization('ro');
// 2 -> 'few'
getPluralCategory(2, ['one'], l10n);
}).toThrowError('No plural message found for value "2"');
});
});
}); });
}); });
} }

View File

@ -8,22 +8,21 @@
import {AsyncPipe} from '@angular/common'; import {AsyncPipe} from '@angular/common';
import {WrappedValue} from '@angular/core'; import {WrappedValue} from '@angular/core';
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, beforeEach, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {browserDetection} from '@angular/platform-browser/testing/browser_util'; import {browserDetection} from '@angular/platform-browser/testing/browser_util';
import {EventEmitter} from '../../src/facade/async'; import {EventEmitter} from '../../src/facade/async';
import {isBlank} from '../../src/facade/lang';
import {SpyChangeDetectorRef} from '../spies'; import {SpyChangeDetectorRef} from '../spies';
export function main() { export function main() {
describe('AsyncPipe', () => { describe('AsyncPipe', () => {
describe('Observable', () => { describe('Observable', () => {
var emitter: EventEmitter<any>; let emitter: EventEmitter<any>;
var pipe: AsyncPipe; let pipe: AsyncPipe;
var ref: any; let ref: any;
var message = {}; const message = {};
beforeEach(() => { beforeEach(() => {
emitter = new EventEmitter(); emitter = new EventEmitter();
@ -63,7 +62,7 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(emitter); pipe.transform(emitter);
var newEmitter = new EventEmitter(); const newEmitter = new EventEmitter();
expect(pipe.transform(newEmitter)).toBe(null); expect(pipe.transform(newEmitter)).toBe(null);
emitter.emit(message); emitter.emit(message);
@ -105,14 +104,14 @@ export function main() {
}); });
describe('Promise', () => { describe('Promise', () => {
var message = new Object(); const message = new Object();
var pipe: AsyncPipe; let pipe: AsyncPipe;
var resolve: (result: any) => void; let resolve: (result: any) => void;
var reject: (error: any) => void; let reject: (error: any) => void;
var promise: Promise<any>; let promise: Promise<any>;
var ref: SpyChangeDetectorRef; let ref: SpyChangeDetectorRef;
// adds longer timers for passing tests in IE // adds longer timers for passing tests in IE
var timer = (!isBlank(getDOM()) && browserDetection.isIE) ? 50 : 10; const timer = (getDOM() && browserDetection.isIE) ? 50 : 10;
beforeEach(() => { beforeEach(() => {
promise = new Promise((res, rej) => { promise = new Promise((res, rej) => {
@ -155,7 +154,7 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(promise); pipe.transform(promise);
var promise = new Promise<any>(() => {}); promise = new Promise<any>(() => {});
expect(pipe.transform(promise)).toBe(null); expect(pipe.transform(promise)).toBe(null);
// this should not affect the pipe, so it should return WrappedValue // this should not affect the pipe, so it should return WrappedValue
@ -169,7 +168,7 @@ export function main() {
it('should request a change detection check upon receiving a new value', it('should request a change detection check upon receiving a new value',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var markForCheck = ref.spy('markForCheck'); const markForCheck = ref.spy('markForCheck');
pipe.transform(promise); pipe.transform(promise);
resolve(message); resolve(message);
@ -203,14 +202,14 @@ export function main() {
describe('null', () => { describe('null', () => {
it('should return null when given null', () => { it('should return null when given null', () => {
var pipe = new AsyncPipe(null); const pipe = new AsyncPipe(null);
expect(pipe.transform(null)).toEqual(null); expect(pipe.transform(null)).toEqual(null);
}); });
}); });
describe('other types', () => { describe('other types', () => {
it('should throw when given an invalid object', () => { it('should throw when given an invalid object', () => {
var pipe = new AsyncPipe(null); const pipe = new AsyncPipe(null);
expect(() => pipe.transform(<any>'some bogus object')).toThrowError(); expect(() => pipe.transform(<any>'some bogus object')).toThrowError();
}); });
}); });

View File

@ -0,0 +1,67 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {LowerCasePipe, TitleCasePipe, UpperCasePipe} from '@angular/common';
export function main() {
describe('LowerCasePipe', () => {
let pipe: LowerCasePipe;
beforeEach(() => { pipe = new LowerCasePipe(); });
it('should return lowercase', () => { expect(pipe.transform('FOO')).toEqual('foo'); });
it('should lowercase when there is a new value', () => {
expect(pipe.transform('FOO')).toEqual('foo');
expect(pipe.transform('BAr')).toEqual('bar');
});
it('should not support other objects',
() => { expect(() => pipe.transform(<any>{})).toThrowError(); });
});
describe('TitleCasePipe', () => {
let pipe: TitleCasePipe;
beforeEach(() => { pipe = new TitleCasePipe(); });
it('should return titlecase', () => { expect(pipe.transform('foo')).toEqual('Foo'); });
it('should return titlecase for subsequent words',
() => { expect(pipe.transform('one TWO Three fouR')).toEqual('One Two Three Four'); });
it('should support empty strings', () => { expect(pipe.transform('')).toEqual(''); });
it('should persist whitespace',
() => { expect(pipe.transform('one two')).toEqual('One Two'); });
it('should titlecase when there is a new value', () => {
expect(pipe.transform('bar')).toEqual('Bar');
expect(pipe.transform('foo')).toEqual('Foo');
});
it('should not support other objects',
() => { expect(() => pipe.transform(<any>{})).toThrowError(); });
});
describe('UpperCasePipe', () => {
let pipe: UpperCasePipe;
beforeEach(() => { pipe = new UpperCasePipe(); });
it('should return uppercase', () => { expect(pipe.transform('foo')).toEqual('FOO'); });
it('should uppercase when there is a new value', () => {
expect(pipe.transform('foo')).toEqual('FOO');
expect(pipe.transform('bar')).toEqual('BAR');
});
it('should not support other objects',
() => { expect(() => pipe.transform(<any>{})).toThrowError(); });
});
}

View File

@ -8,15 +8,18 @@
import {DatePipe} from '@angular/common'; import {DatePipe} from '@angular/common';
import {PipeResolver} from '@angular/compiler/src/pipe_resolver'; import {PipeResolver} from '@angular/compiler/src/pipe_resolver';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {browserDetection} from '@angular/platform-browser/testing/browser_util'; import {browserDetection} from '@angular/platform-browser/testing/browser_util';
import {DateWrapper} from '../../src/facade/lang';
export function main() { export function main() {
describe('DatePipe', () => { describe('DatePipe', () => {
var date: Date; let date: Date;
var pipe: DatePipe; const isoStringWithoutTime = '2015-01-01';
let pipe: DatePipe;
// Check the transformation of a date into a pattern
function expectDateFormatAs(date: Date | string, pattern: any, output: string): void {
expect(pipe.transform(date, pattern)).toEqual(output);
}
// TODO: reactivate the disabled expectations once emulators are fixed in SauceLabs // TODO: reactivate the disabled expectations once emulators are fixed in SauceLabs
// In some old versions of Chrome in Android emulators, time formatting returns dates in the // In some old versions of Chrome in Android emulators, time formatting returns dates in the
@ -27,7 +30,7 @@ export function main() {
// Tracking issue: https://github.com/angular/angular/issues/11187 // Tracking issue: https://github.com/angular/angular/issues/11187
beforeEach(() => { beforeEach(() => {
date = DateWrapper.create(2015, 6, 15, 9, 3, 1); date = new Date(2015, 5, 15, 9, 3, 1);
pipe = new DatePipe('en-US'); pipe = new DatePipe('en-US');
}); });
@ -36,7 +39,9 @@ export function main() {
describe('supports', () => { describe('supports', () => {
it('should support date', () => { expect(() => pipe.transform(date)).not.toThrow(); }); it('should support date', () => { expect(() => pipe.transform(date)).not.toThrow(); });
it('should support int', () => { expect(() => pipe.transform(123456789)).not.toThrow(); }); it('should support int', () => { expect(() => pipe.transform(123456789)).not.toThrow(); });
it('should support numeric strings', it('should support numeric strings',
() => { expect(() => pipe.transform('123456789')).not.toThrow(); }); () => { expect(() => pipe.transform('123456789')).not.toThrow(); });
@ -44,85 +49,143 @@ export function main() {
() => { expect(() => pipe.transform('123456789.11')).not.toThrow(); }); () => { expect(() => pipe.transform('123456789.11')).not.toThrow(); });
it('should support ISO string', it('should support ISO string',
() => { expect(() => pipe.transform('2015-06-15T21:43:11Z')).not.toThrow(); }); () => expect(() => pipe.transform('2015-06-15T21:43:11Z')).not.toThrow());
it('should not support other objects', () => { it('should return null for empty string', () => expect(pipe.transform('')).toEqual(null));
expect(() => pipe.transform({})).toThrow();
expect(() => pipe.transform('')).toThrow(); it('should support ISO string without time',
}); () => { expect(() => pipe.transform(isoStringWithoutTime)).not.toThrow(); });
it('should not support other objects',
() => { expect(() => pipe.transform({})).toThrowError(); });
}); });
describe('transform', () => { describe('transform', () => {
it('should format each component correctly', () => { it('should format each component correctly', () => {
expect(pipe.transform(date, 'y')).toEqual('2015'); const dateFixtures: any = {
expect(pipe.transform(date, 'yy')).toEqual('15'); 'y': '2015',
expect(pipe.transform(date, 'M')).toEqual('6'); 'yy': '15',
expect(pipe.transform(date, 'MM')).toEqual('06'); 'M': '6',
expect(pipe.transform(date, 'MMM')).toEqual('Jun'); 'MM': '06',
expect(pipe.transform(date, 'MMMM')).toEqual('June'); 'MMM': 'Jun',
expect(pipe.transform(date, 'd')).toEqual('15'); 'MMMM': 'June',
expect(pipe.transform(date, 'E')).toEqual('Mon'); 'd': '15',
expect(pipe.transform(date, 'EEEE')).toEqual('Monday'); 'dd': '15',
'EEE': 'Mon',
'EEEE': 'Monday'
};
const isoStringWithoutTimeFixtures: any = {
'y': '2015',
'yy': '15',
'M': '1',
'MM': '01',
'MMM': 'Jan',
'MMMM': 'January',
'd': '1',
'dd': '01',
'EEE': 'Thu',
'EEEE': 'Thursday'
};
if (!browserDetection.isOldChrome) { if (!browserDetection.isOldChrome) {
expect(pipe.transform(date, 'h')).toEqual('9'); dateFixtures['h'] = '9';
expect(pipe.transform(date, 'hh')).toEqual('09'); dateFixtures['hh'] = '09';
expect(pipe.transform(date, 'j')).toEqual('9 AM'); dateFixtures['j'] = '9 AM';
isoStringWithoutTimeFixtures['h'] = '12';
isoStringWithoutTimeFixtures['hh'] = '12';
isoStringWithoutTimeFixtures['j'] = '12 AM';
} }
// IE and Edge can't format a date to minutes and seconds without hours // IE and Edge can't format a date to minutes and seconds without hours
if (!browserDetection.isEdge && !browserDetection.isIE || if (!browserDetection.isEdge && !browserDetection.isIE ||
!browserDetection.supportsNativeIntlApi) { !browserDetection.supportsNativeIntlApi) {
if (!browserDetection.isOldChrome) { if (!browserDetection.isOldChrome) {
expect(pipe.transform(date, 'HH')).toEqual('09'); dateFixtures['HH'] = '09';
isoStringWithoutTimeFixtures['HH'] = '00';
} }
expect(pipe.transform(date, 'm')).toEqual('3'); dateFixtures['E'] = 'M';
expect(pipe.transform(date, 's')).toEqual('1'); dateFixtures['L'] = 'J';
expect(pipe.transform(date, 'mm')).toEqual('03'); dateFixtures['m'] = '3';
expect(pipe.transform(date, 'ss')).toEqual('01'); dateFixtures['s'] = '1';
dateFixtures['mm'] = '03';
dateFixtures['ss'] = '01';
isoStringWithoutTimeFixtures['m'] = '0';
isoStringWithoutTimeFixtures['s'] = '0';
isoStringWithoutTimeFixtures['mm'] = '00';
isoStringWithoutTimeFixtures['ss'] = '00';
} }
Object.keys(dateFixtures).forEach((pattern: string) => {
expectDateFormatAs(date, pattern, dateFixtures[pattern]);
});
Object.keys(isoStringWithoutTimeFixtures).forEach((pattern: string) => {
expectDateFormatAs(isoStringWithoutTime, pattern, isoStringWithoutTimeFixtures[pattern]);
});
expect(pipe.transform(date, 'Z')).toBeDefined(); expect(pipe.transform(date, 'Z')).toBeDefined();
}); });
it('should format common multi component patterns', () => { it('should format common multi component patterns', () => {
expect(pipe.transform(date, 'E, M/d/y')).toEqual('Mon, 6/15/2015'); const dateFixtures: any = {
expect(pipe.transform(date, 'E, M/d')).toEqual('Mon, 6/15'); 'EEE, M/d/y': 'Mon, 6/15/2015',
expect(pipe.transform(date, 'MMM d')).toEqual('Jun 15'); 'EEE, M/d': 'Mon, 6/15',
expect(pipe.transform(date, 'dd/MM/yyyy')).toEqual('15/06/2015'); 'MMM d': 'Jun 15',
expect(pipe.transform(date, 'MM/dd/yyyy')).toEqual('06/15/2015'); 'dd/MM/yyyy': '15/06/2015',
expect(pipe.transform(date, 'yMEd')).toEqual('20156Mon15'); 'MM/dd/yyyy': '06/15/2015',
expect(pipe.transform(date, 'MEd')).toEqual('6Mon15'); 'yMEEEd': '20156Mon15',
expect(pipe.transform(date, 'MMMd')).toEqual('Jun15'); 'MEEEd': '6Mon15',
expect(pipe.transform(date, 'yMMMMEEEEd')).toEqual('Monday, June 15, 2015'); 'MMMd': 'Jun15',
'yMMMMEEEEd': 'Monday, June 15, 2015'
};
// IE and Edge can't format a date to minutes and seconds without hours // IE and Edge can't format a date to minutes and seconds without hours
if (!browserDetection.isEdge && !browserDetection.isIE || if (!browserDetection.isEdge && !browserDetection.isIE ||
!browserDetection.supportsNativeIntlApi) { !browserDetection.supportsNativeIntlApi) {
expect(pipe.transform(date, 'ms')).toEqual('31'); dateFixtures['ms'] = '31';
} }
if (!browserDetection.isOldChrome) { if (!browserDetection.isOldChrome) {
expect(pipe.transform(date, 'jm')).toEqual('9:03 AM'); dateFixtures['jm'] = '9:03 AM';
} }
Object.keys(dateFixtures).forEach((pattern: string) => {
expectDateFormatAs(date, pattern, dateFixtures[pattern]);
});
}); });
it('should format with pattern aliases', () => { it('should format with pattern aliases', () => {
const dateFixtures: any = {
'MM/dd/yyyy': '06/15/2015',
'fullDate': 'Monday, June 15, 2015',
'longDate': 'June 15, 2015',
'mediumDate': 'Jun 15, 2015',
'shortDate': '6/15/2015'
};
if (!browserDetection.isOldChrome) { if (!browserDetection.isOldChrome) {
// IE and Edge do not add a coma after the year in these 2 cases // IE and Edge do not add a coma after the year in these 2 cases
if ((browserDetection.isEdge || browserDetection.isIE) && if ((browserDetection.isEdge || browserDetection.isIE) &&
browserDetection.supportsNativeIntlApi) { browserDetection.supportsNativeIntlApi) {
expect(pipe.transform(date, 'medium')).toEqual('Jun 15, 2015 9:03:01 AM'); dateFixtures['medium'] = 'Jun 15, 2015 9:03:01 AM';
expect(pipe.transform(date, 'short')).toEqual('6/15/2015 9:03 AM'); dateFixtures['short'] = '6/15/2015 9:03 AM';
} else { } else {
expect(pipe.transform(date, 'medium')).toEqual('Jun 15, 2015, 9:03:01 AM'); dateFixtures['medium'] = 'Jun 15, 2015, 9:03:01 AM';
expect(pipe.transform(date, 'short')).toEqual('6/15/2015, 9:03 AM'); dateFixtures['short'] = '6/15/2015, 9:03 AM';
} }
} }
expect(pipe.transform(date, 'MM/dd/yyyy')).toEqual('06/15/2015');
expect(pipe.transform(date, 'fullDate')).toEqual('Monday, June 15, 2015');
expect(pipe.transform(date, 'longDate')).toEqual('June 15, 2015');
expect(pipe.transform(date, 'mediumDate')).toEqual('Jun 15, 2015');
expect(pipe.transform(date, 'shortDate')).toEqual('6/15/2015');
if (!browserDetection.isOldChrome) { if (!browserDetection.isOldChrome) {
expect(pipe.transform(date, 'mediumTime')).toEqual('9:03:01 AM'); dateFixtures['mediumTime'] = '9:03:01 AM';
expect(pipe.transform(date, 'shortTime')).toEqual('9:03 AM'); dateFixtures['shortTime'] = '9:03 AM';
} }
Object.keys(dateFixtures).forEach((pattern: string) => {
expectDateFormatAs(date, pattern, dateFixtures[pattern]);
});
}); });
it('should remove bidi control characters', it('should remove bidi control characters',

View File

@ -8,14 +8,14 @@
import {I18nPluralPipe, NgLocalization} from '@angular/common'; import {I18nPluralPipe, NgLocalization} from '@angular/common';
import {PipeResolver} from '@angular/compiler/src/pipe_resolver'; import {PipeResolver} from '@angular/compiler/src/pipe_resolver';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; import {beforeEach, describe, expect, it} from '@angular/core/testing/testing_internal';
export function main() { export function main() {
describe('I18nPluralPipe', () => { describe('I18nPluralPipe', () => {
var localization: NgLocalization; let localization: NgLocalization;
var pipe: I18nPluralPipe; let pipe: I18nPluralPipe;
var mapping = { const mapping = {
'=0': 'No messages.', '=0': 'No messages.',
'=1': 'One message.', '=1': 'One message.',
'many': 'Many messages.', 'many': 'Many messages.',
@ -32,27 +32,27 @@ export function main() {
describe('transform', () => { describe('transform', () => {
it('should return 0 text if value is 0', () => { it('should return 0 text if value is 0', () => {
var val = pipe.transform(0, mapping); const val = pipe.transform(0, mapping);
expect(val).toEqual('No messages.'); expect(val).toEqual('No messages.');
}); });
it('should return 1 text if value is 1', () => { it('should return 1 text if value is 1', () => {
var val = pipe.transform(1, mapping); const val = pipe.transform(1, mapping);
expect(val).toEqual('One message.'); expect(val).toEqual('One message.');
}); });
it('should return category messages', () => { it('should return category messages', () => {
var val = pipe.transform(4, mapping); const val = pipe.transform(4, mapping);
expect(val).toEqual('Many messages.'); expect(val).toEqual('Many messages.');
}); });
it('should interpolate the value into the text where indicated', () => { it('should interpolate the value into the text where indicated', () => {
var val = pipe.transform(6, mapping); const val = pipe.transform(6, mapping);
expect(val).toEqual('There are 6 messages, that is 6.'); expect(val).toEqual('There are 6 messages, that is 6.');
}); });
it('should use "" if value is undefined', () => { it('should use "" if value is undefined', () => {
var val = pipe.transform(void(0), mapping); const val = pipe.transform(void(0), mapping);
expect(val).toEqual(''); expect(val).toEqual('');
}); });

View File

@ -8,40 +8,35 @@
import {I18nSelectPipe} from '@angular/common'; import {I18nSelectPipe} from '@angular/common';
import {PipeResolver} from '@angular/compiler/src/pipe_resolver'; import {PipeResolver} from '@angular/compiler/src/pipe_resolver';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
export function main() { export function main() {
describe('I18nSelectPipe', () => { describe('I18nSelectPipe', () => {
var pipe: I18nSelectPipe; const pipe: I18nSelectPipe = new I18nSelectPipe();
var mapping = {'male': 'Invite him.', 'female': 'Invite her.', 'other': 'Invite them.'}; const mapping = {'male': 'Invite him.', 'female': 'Invite her.', 'other': 'Invite them.'};
beforeEach(() => { pipe = new I18nSelectPipe(); });
it('should be marked as pure', it('should be marked as pure',
() => { expect(new PipeResolver().resolve(I18nSelectPipe).pure).toEqual(true); }); () => { expect(new PipeResolver().resolve(I18nSelectPipe).pure).toEqual(true); });
describe('transform', () => { describe('transform', () => {
it('should return male text if value is male', () => { it('should return the "male" text if value is "male"', () => {
var val = pipe.transform('male', mapping); const val = pipe.transform('male', mapping);
expect(val).toEqual('Invite him.'); expect(val).toEqual('Invite him.');
}); });
it('should return female text if value is female', () => { it('should return the "female" text if value is "female"', () => {
var val = pipe.transform('female', mapping); const val = pipe.transform('female', mapping);
expect(val).toEqual('Invite her.'); expect(val).toEqual('Invite her.');
}); });
it('should return "" if value is anything other than male or female', () => { it('should return the "other" text if value is neither "male" nor "female"',
var val = pipe.transform('Anything else', mapping); () => { expect(pipe.transform('Anything else', mapping)).toEqual('Invite them.'); });
expect(val).toEqual('');
it('should return an empty text if value is null or undefined', () => {
expect(pipe.transform(null, mapping)).toEqual('');
expect(pipe.transform(void 0, mapping)).toEqual('');
}); });
it('should use "" if value is undefined', () => { it('should throw on bad arguments',
var val = pipe.transform(void(0), mapping);
expect(val).toEqual('');
});
it('should not support bad arguments',
() => { expect(() => pipe.transform('male', <any>'hey')).toThrowError(); }); () => { expect(() => pipe.transform('male', <any>'hey')).toThrowError(); });
}); });

View File

@ -11,16 +11,14 @@ import {Component} from '@angular/core';
import {TestBed, async} from '@angular/core/testing'; import {TestBed, async} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/matchers'; import {expect} from '@angular/platform-browser/testing/matchers';
import {Json, StringWrapper} from '../../src/facade/lang';
export function main() { export function main() {
describe('JsonPipe', () => { describe('JsonPipe', () => {
var regNewLine = '\n'; const regNewLine = '\n';
var inceptionObj: any; let inceptionObj: any;
var inceptionObjString: string; let inceptionObjString: string;
var pipe: JsonPipe; let pipe: JsonPipe;
function normalize(obj: string): string { return StringWrapper.replace(obj, regNewLine, ''); } function normalize(obj: string): string { return obj.replace(regNewLine, ''); }
beforeEach(() => { beforeEach(() => {
inceptionObj = {dream: {dream: {dream: 'Limbo'}}}; inceptionObj = {dream: {dream: {dream: 'Limbo'}}};
@ -41,14 +39,14 @@ export function main() {
() => { expect(pipe.transform(inceptionObj)).toEqual(inceptionObjString); }); () => { expect(pipe.transform(inceptionObj)).toEqual(inceptionObjString); });
it('should return JSON-formatted string even when normalized', () => { it('should return JSON-formatted string even when normalized', () => {
var dream1 = normalize(pipe.transform(inceptionObj)); const dream1 = normalize(pipe.transform(inceptionObj));
var dream2 = normalize(inceptionObjString); const dream2 = normalize(inceptionObjString);
expect(dream1).toEqual(dream2); expect(dream1).toEqual(dream2);
}); });
it('should return JSON-formatted string similar to Json.stringify', () => { it('should return JSON-formatted string similar to Json.stringify', () => {
var dream1 = normalize(pipe.transform(inceptionObj)); const dream1 = normalize(pipe.transform(inceptionObj));
var dream2 = normalize(Json.stringify(inceptionObj)); const dream2 = normalize(JSON.stringify(inceptionObj, null, 2));
expect(dream1).toEqual(dream2); expect(dream1).toEqual(dream2);
}); });
}); });
@ -65,8 +63,8 @@ export function main() {
}); });
it('should work with mutable objects', async(() => { it('should work with mutable objects', async(() => {
let fixture = TestBed.createComponent(TestComp); const fixture = TestBed.createComponent(TestComp);
let mutable: number[] = [1]; const mutable: number[] = [1];
fixture.componentInstance.data = mutable; fixture.componentInstance.data = mutable;
fixture.detectChanges(); fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('[\n 1\n]'); expect(fixture.nativeElement).toHaveText('[\n 1\n]');
@ -74,7 +72,6 @@ export function main() {
mutable.push(2); mutable.push(2);
fixture.detectChanges(); fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('[\n 1,\n 2\n]'); expect(fixture.nativeElement).toHaveText('[\n 1,\n 2\n]');
})); }));
}); });
}); });

View File

@ -1,42 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {LowerCasePipe} from '@angular/common';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
export function main() {
describe('LowerCasePipe', () => {
var upper: string;
var lower: string;
var pipe: LowerCasePipe;
beforeEach(() => {
lower = 'something';
upper = 'SOMETHING';
pipe = new LowerCasePipe();
});
describe('transform', () => {
it('should return lowercase', () => {
var val = pipe.transform(upper);
expect(val).toEqual(lower);
});
it('should lowercase when there is a new value', () => {
var val = pipe.transform(upper);
expect(val).toEqual(lower);
var val2 = pipe.transform('WAT');
expect(val2).toEqual('wat');
});
it('should not support other objects',
() => { expect(() => pipe.transform(<any>{})).toThrowError(); });
});
});
}

View File

@ -7,13 +7,13 @@
*/ */
import {CurrencyPipe, DecimalPipe, PercentPipe} from '@angular/common'; import {CurrencyPipe, DecimalPipe, PercentPipe} from '@angular/common';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; import {beforeEach, describe, expect, it} from '@angular/core/testing/testing_internal';
import {browserDetection} from '@angular/platform-browser/testing/browser_util'; import {browserDetection} from '@angular/platform-browser/testing/browser_util';
export function main() { export function main() {
describe('Number pipes', () => { describe('Number pipes', () => {
describe('DecimalPipe', () => { describe('DecimalPipe', () => {
var pipe: DecimalPipe; let pipe: DecimalPipe;
beforeEach(() => { pipe = new DecimalPipe('en-US'); }); beforeEach(() => { pipe = new DecimalPipe('en-US'); });
@ -44,7 +44,7 @@ export function main() {
}); });
describe('PercentPipe', () => { describe('PercentPipe', () => {
var pipe: PercentPipe; let pipe: PercentPipe;
beforeEach(() => { pipe = new PercentPipe('en-US'); }); beforeEach(() => { pipe = new PercentPipe('en-US'); });
@ -60,7 +60,7 @@ export function main() {
}); });
describe('CurrencyPipe', () => { describe('CurrencyPipe', () => {
var pipe: CurrencyPipe; let pipe: CurrencyPipe;
beforeEach(() => { pipe = new CurrencyPipe('en-US'); }); beforeEach(() => { pipe = new CurrencyPipe('en-US'); });

View File

@ -9,14 +9,13 @@
import {CommonModule, SlicePipe} from '@angular/common'; import {CommonModule, SlicePipe} from '@angular/common';
import {Component} from '@angular/core'; import {Component} from '@angular/core';
import {TestBed, async} from '@angular/core/testing'; import {TestBed, async} from '@angular/core/testing';
import {browserDetection} from '@angular/platform-browser/testing/browser_util';
import {expect} from '@angular/platform-browser/testing/matchers'; import {expect} from '@angular/platform-browser/testing/matchers';
export function main() { export function main() {
describe('SlicePipe', () => { describe('SlicePipe', () => {
var list: number[]; let list: number[];
var str: string; let str: string;
var pipe: SlicePipe; let pipe: SlicePipe;
beforeEach(() => { beforeEach(() => {
list = [1, 2, 3, 4, 5]; list = [1, 2, 3, 4, 5];
@ -94,8 +93,8 @@ export function main() {
}); });
it('should work with mutable arrays', async(() => { it('should work with mutable arrays', async(() => {
let fixture = TestBed.createComponent(TestComp); const fixture = TestBed.createComponent(TestComp);
let mutable: number[] = [1, 2]; const mutable: number[] = [1, 2];
fixture.componentInstance.data = mutable; fixture.componentInstance.data = mutable;
fixture.detectChanges(); fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('2'); expect(fixture.nativeElement).toHaveText('2');

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