Compare commits
468 Commits
Author | SHA1 | Date | |
---|---|---|---|
04dd9713f0 | |||
48d579b2ae | |||
3db91ffd96 | |||
229b76cfde | |||
80a5b91575 | |||
9728dce048 | |||
463e2872a6 | |||
fa03ae14b0 | |||
27196b676b | |||
6040ee39eb | |||
74dbf7bad5 | |||
7269fe5203 | |||
8e80db4982 | |||
e99475260f | |||
b15d50af9b | |||
db55e86e91 | |||
a2f3f4550d | |||
d2cfc6a719 | |||
fecf768f43 | |||
2fc4cf67be | |||
f9436f7a5b | |||
e726d81822 | |||
6cd4b1b41c | |||
24df08efc7 | |||
4f1a571ba6 | |||
c8d2e0a3bc | |||
b5934fc582 | |||
2402224b4e | |||
03d16fcd24 | |||
dcc3eba962 | |||
6588ca8a6c | |||
81823e89cd | |||
ef78538a06 | |||
ccea37256e | |||
cdc66f6164 | |||
5bceb89a7f | |||
2582eca265 | |||
3e47ea27f5 | |||
d365077dfa | |||
bc7a6d7b00 | |||
9f538a6cac | |||
3750ea9dff | |||
afd89ed8d9 | |||
a62371c0eb | |||
c516bc3b35 | |||
8bf1305490 | |||
d8abf70f1f | |||
efd9c09456 | |||
a66cd526c3 | |||
a0ffdf1ef2 | |||
83d207d0a7 | |||
83c1383701 | |||
c66283ad66 | |||
ae97920fe2 | |||
533a010b28 | |||
6b81d1c9b9 | |||
fefc081e1b | |||
bdee1f4a25 | |||
40dfe39e64 | |||
3d50fd7cac | |||
cc1058f6e1 | |||
47e251a80a | |||
47bcb5bc35 | |||
f3fc74ab67 | |||
86a36eaadd | |||
5ba1cf1063 | |||
07b81ae741 | |||
5a7bf36723 | |||
66528a21f6 | |||
a77757277b | |||
4f05d022c1 | |||
5df343169e | |||
764fea1344 | |||
bbdea96a66 | |||
d1de587ce0 | |||
147aec43bd | |||
1f5049f30c | |||
09e3839994 | |||
19eeba2281 | |||
6cc8f2298e | |||
83b27bac17 | |||
b462f49ce7 | |||
1a9064ba2b | |||
5bc869cb24 | |||
8fdb1e09c1 | |||
f3d38ce053 | |||
05953b3b83 | |||
f75296e04e | |||
0867e85163 | |||
93b00cceb6 | |||
0fa818b318 | |||
bc66d27938 | |||
6a5818454f | |||
27fc458ef6 | |||
0487a9f140 | |||
871ece6123 | |||
abca7c0243 | |||
1f5256e745 | |||
6990354047 | |||
135ead6c97 | |||
33c0ee3441 | |||
5efea2f6a0 | |||
5f23a1223f | |||
30208759cd | |||
e4c53f8529 | |||
b61e3e9d20 | |||
f593552cfe | |||
8458647232 | |||
a693c5614c | |||
8ceffd8b48 | |||
2986e25abb | |||
f8fe53aeb0 | |||
74e3115686 | |||
3846f19f22 | |||
057513536b | |||
82bcd83566 | |||
e48f477477 | |||
20e1cc049f | |||
0b2d636b75 | |||
f5bb999319 | |||
a4742763b9 | |||
05ff6c09ca | |||
d91ff17adc | |||
d213a20dfc | |||
2e7e935b02 | |||
b89e7c2cb7 | |||
b4db2e25d6 | |||
a33eaf6e07 | |||
0d47c39609 | |||
cbe7e39bbe | |||
6d57cb04f6 | |||
6e2a8a2ba4 | |||
7874697b6c | |||
767141761a | |||
b3eb1db6dd | |||
ee0dab025b | |||
b7738e1fe5 | |||
634d33f5dd | |||
3401283399 | |||
981947d104 | |||
8c52088346 | |||
add3589451 | |||
81d497ce1f | |||
70cd124ede | |||
7363b3d4b5 | |||
f05937db4d | |||
d684f55423 | |||
db06cb170f | |||
77a1f9f2e8 | |||
13e663c232 | |||
d098cf5a8b | |||
3ce3b4d2af | |||
e7d9cb3e4c | |||
e544742156 | |||
c9ad529afc | |||
75e468494c | |||
ddada6e2be | |||
22ae17bb0b | |||
d546be48e1 | |||
753a130aaa | |||
94e2ea7361 | |||
1539cd8819 | |||
131c8ab6be | |||
7d81309e11 | |||
225baf4686 | |||
70b061be2e | |||
46aa0a1cf6 | |||
661fdcd3e2 | |||
590d93b30d | |||
c26e1bba1d | |||
10771d0bd8 | |||
d8cc09b76c | |||
d41d2c460a | |||
4efc32dabf | |||
ef534c0cc1 | |||
073f485c72 | |||
c2dbc55f11 | |||
9ee2703824 | |||
b78ada198a | |||
6790e02a13 | |||
7cabaa0ae7 | |||
da3563ce19 | |||
9bbec42a6c | |||
be994496cd | |||
77ef527993 | |||
f092a7c824 | |||
5e25d3986d | |||
35977e3830 | |||
f7328c69b3 | |||
25f2211726 | |||
18793c896b | |||
e7cdb9f660 | |||
6911a250ef | |||
7e7ff2e0aa | |||
d34f0bf573 | |||
1f5fa25583 | |||
d507057476 | |||
f582620d5b | |||
3fbcde9048 | |||
f841fbe60f | |||
b9a91a5e74 | |||
65f4fad801 | |||
60a30818ef | |||
b967cbfc66 | |||
8826a8235b | |||
47addd169d | |||
ba6af2a6dd | |||
b9e4d62d5a | |||
71e5de646b | |||
3def2cc552 | |||
4ec4a99f16 | |||
3203069d6c | |||
54bfe14313 | |||
ba850b36de | |||
f3c5481181 | |||
48300067fb | |||
b841e0d530 | |||
65a2cb8307 | |||
0bef021321 | |||
aafa75da84 | |||
503be69af6 | |||
eb01ad583f | |||
15a54df7d3 | |||
eaaae2edf4 | |||
c2b3792a3b | |||
b2a586cee1 | |||
8bb42df47e | |||
add5953aa1 | |||
6b4c24020d | |||
24bf3e2a25 | |||
8ecda94899 | |||
1366762d12 | |||
dd6237ecd9 | |||
6e83204238 | |||
a53a040071 | |||
5bef070e16 | |||
89de98b25e | |||
de78307928 | |||
6293ca23c3 | |||
330bb2a360 | |||
59455ea8d1 | |||
e9e4ffd6e1 | |||
0444e13efb | |||
ffb6dbeefe | |||
0e012c9669 | |||
a0819d3af1 | |||
ffd8c361eb | |||
1594f8c09e | |||
d7a727cc07 | |||
437a0446e2 | |||
ac93f1235e | |||
e2b76bb386 | |||
ae0275e2dd | |||
ecce90718b | |||
c2cb475a2c | |||
7cf5e95ac9 | |||
a740e4f00a | |||
2a9d2bacd5 | |||
4ed04392d3 | |||
23ab83b504 | |||
9332161e01 | |||
816d5ba3fd | |||
69c53c3e03 | |||
365712e2f0 | |||
997336b790 | |||
1861e416a1 | |||
7c44637fbf | |||
68b53c07fd | |||
368cb5ad4e | |||
949836d003 | |||
697fb76960 | |||
0fedb57cb0 | |||
717ac5ac4d | |||
4064cbe945 | |||
a88306d671 | |||
c702ffc471 | |||
dcfffbf828 | |||
336041aac9 | |||
7e38f4fd1f | |||
c28b52187a | |||
5ec1717c58 | |||
c2a24b4241 | |||
a9f3e2bd95 | |||
f8658cdc38 | |||
043e408805 | |||
c004d483ab | |||
2586846ee2 | |||
d47b2a6f70 | |||
1adbcda12e | |||
12af6d356e | |||
20aafff092 | |||
a622e19df6 | |||
1db7c0d139 | |||
b9bd3204f2 | |||
bf651a504f | |||
e5c4371d72 | |||
3caae94261 | |||
e7a2b31472 | |||
c03186013c | |||
5a2531ee45 | |||
6ca780178c | |||
9608b0636d | |||
89187d9b6b | |||
335b72f301 | |||
74071210eb | |||
fde966832b | |||
75d474e1d3 | |||
24cf8b3269 | |||
743651f5e8 | |||
161f88fe6f | |||
c33a57666b | |||
cf618c564c | |||
401ead07b8 | |||
b55c2ba342 | |||
d8db0f12a2 | |||
eb8013e853 | |||
fb4b90a564 | |||
7830d74615 | |||
8e24c0fff4 | |||
cf0444b731 | |||
a7bbe9a1ff | |||
ffe323036e | |||
b4a39f9c30 | |||
3257fcdcee | |||
9bcd7097d0 | |||
c32f5fd393 | |||
78ba39bfe2 | |||
119034c642 | |||
6e8e3bd248 | |||
a460066972 | |||
05d96dc507 | |||
b489259a34 | |||
6b748835be | |||
d30ea61f0d | |||
0c47ea704e | |||
049c89645b | |||
bf22f2df88 | |||
880201681f | |||
63d26a1777 | |||
8b50ed083c | |||
3997d97806 | |||
200d92d030 | |||
dbec3ca716 | |||
f7c9b941cb | |||
f0764016f9 | |||
a99eb16320 | |||
e36bac9e90 | |||
196ce6d475 | |||
faa621218e | |||
169cedd43b | |||
567cc26b8e | |||
1d19d61970 | |||
03f080b7da | |||
26f82995f6 | |||
f1da1419fa | |||
5079d2d37c | |||
c7fd172ba7 | |||
dcf8840831 | |||
60c0b178af | |||
0899f4f8fc | |||
aed4a11d01 | |||
75cf70ae04 | |||
6b30fbf94e | |||
24f17f913a | |||
ebfa204af0 | |||
a28d616e10 | |||
613a9e3672 | |||
65d57a07e0 | |||
22946cfd40 | |||
9975486954 | |||
068348e9b1 | |||
1beab0da6a | |||
3a03ff6b2d | |||
feae55b264 | |||
0355142737 | |||
5b16ce9302 | |||
17ed14faea | |||
d156e72ad7 | |||
7186c9c839 | |||
a41558eb30 | |||
a91252a90c | |||
132c0719dc | |||
3db7112b89 | |||
2ea76cce31 | |||
b8bb2dd0f5 | |||
27ae0f9475 | |||
171dceb010 | |||
1ebc0d1e33 | |||
1d8e0758fa | |||
cd55643f85 | |||
486b8e6f69 | |||
215d373ebd | |||
4038b42396 | |||
9ab1f4a9c9 | |||
e9afc59a81 | |||
83c826c3f9 | |||
abfc41d661 | |||
11fd7eaf63 | |||
54eba606cb | |||
3337865913 | |||
f24397c5d0 | |||
9d52bf27de | |||
19fbfbc371 | |||
6578b30b77 | |||
10c1c2ba5a | |||
e18bfd1f3d | |||
3c2ddbe9ab | |||
a149605c9f | |||
b396029d39 | |||
040b376052 | |||
175c872514 | |||
71291aa2c0 | |||
415e75716a | |||
3216abee2e | |||
327ad02a28 | |||
1df0c9e1b0 | |||
280dadaaad | |||
c30eff898a | |||
ca129ba549 | |||
171ae154c2 | |||
4426c0f14e | |||
901436e46f | |||
6fbc2b3be0 | |||
93d23ddcc8 | |||
548a809a05 | |||
a161b4ab6d | |||
60b91656cd | |||
1858d99559 | |||
3a8665409d | |||
005a78bd83 | |||
7553ce9dfe | |||
42bfe4477f | |||
3bdbb18c8b | |||
13f8648a00 | |||
b6abcb2500 | |||
f1a9e1e361 | |||
54480f7dfc | |||
951bd33b09 | |||
bf57df3e04 | |||
420852e2f5 | |||
04eb80cc2b | |||
308fc8e328 | |||
9bb2939d68 | |||
2f63899be2 | |||
22c66f0e02 | |||
00bc80bb37 | |||
394d951883 | |||
98b26381f6 | |||
31797d3b50 | |||
957be960d2 | |||
18e9d86a3b | |||
a869aeecd2 | |||
eca822b756 | |||
17142a778a | |||
5adb7c9669 | |||
703fcda590 | |||
f16a7cd7e3 | |||
fde5f2fa14 | |||
d56724659f | |||
56b18ff063 | |||
7bfeac746e | |||
c92efc15fb | |||
b51d57deb8 | |||
c357b40dca | |||
a0ae120093 | |||
d3211a2468 | |||
adab4f3e49 | |||
82fed62af2 |
18
.bazelrc
18
.bazelrc
@ -1,18 +0,0 @@
|
||||
# Make compilation fast, by keeping a few copies of the compilers
|
||||
# running as daemons, and cache SourceFile AST's to reduce parse time.
|
||||
build --strategy=TypeScriptCompile=worker
|
||||
build --strategy=AngularTemplateCompile=worker
|
||||
|
||||
# Don't create bazel-* symlinks in the WORKSPACE directory.
|
||||
# These require .gitignore and may scare users.
|
||||
# Also, it's a workaround for https://github.com/bazelbuild/rules_typescript/issues/12
|
||||
# which affects the common case of having `tsconfig.json` in the WORKSPACE directory.
|
||||
#
|
||||
# Instead, you should run `bazel info bazel-bin` to find out where the outputs went.
|
||||
build --symlink_prefix=/
|
||||
|
||||
# Performance: avoid stat'ing input files
|
||||
build --watchfs
|
||||
|
||||
# Don't print all the .d.ts output locations after builds
|
||||
build --show_result=0
|
@ -7,17 +7,25 @@
|
||||
# To validate changes, use an online parser, eg.
|
||||
# http://yaml-online-parser.appspot.com/
|
||||
|
||||
# Variables
|
||||
|
||||
## IMPORTANT
|
||||
# If you change the `docker_image` version, also change the `cache_key` suffix and the version of
|
||||
# `com_github_bazelbuild_buildtools` in the `/WORKSPACE` file.
|
||||
var_1: &docker_image angular/ngcontainer:0.1.0
|
||||
var_2: &cache_key angular-{{ .Branch }}-{{ checksum "yarn.lock" }}-0.1.0
|
||||
|
||||
# Settings common to each job
|
||||
anchor_1: &job_defaults
|
||||
working_directory: ~/ng
|
||||
docker:
|
||||
- image: angular/ngcontainer:0.0.2
|
||||
- image: *docker_image
|
||||
|
||||
# After checkout, rebase on top of master.
|
||||
# Similar to travis behavior, but not quite the same.
|
||||
# See https://discuss.circleci.com/t/1662
|
||||
anchor_2: &post_checkout
|
||||
post: git pull --ff-only origin "refs/pull/${CI_PULL_REQUEST//*pull\//}/merge"
|
||||
post: git pull --ff-only origin "refs/pull/${CIRCLE_PULL_REQUEST//*pull\//}/merge"
|
||||
|
||||
version: 2
|
||||
jobs:
|
||||
@ -26,25 +34,38 @@ jobs:
|
||||
steps:
|
||||
- checkout:
|
||||
<<: *post_checkout
|
||||
# Check BUILD.bazel formatting before we have a node_modules directory
|
||||
# Then we don't need any exclude pattern to avoid checking those files
|
||||
- run: 'buildifier -mode=check $(find . -type f \( -name BUILD.bazel -or -name BUILD \)) ||
|
||||
(echo "BUILD files not formatted. Please run ''yarn buildifier''" ; exit 1)'
|
||||
# Run the skylark linter to check our Bazel rules
|
||||
- run: 'find . -type f -name "*.bzl" |
|
||||
xargs java -jar /usr/local/bin/Skylint_deploy.jar ||
|
||||
(echo -e "\n.bzl files have lint errors. Please run ''yarn skylint''"; exit 1)'
|
||||
- restore_cache:
|
||||
key: angular-{{ .Branch }}-{{ checksum "yarn.lock" }}
|
||||
key: *cache_key
|
||||
|
||||
- run: yarn install --frozen-lockfile --non-interactive
|
||||
- run: ./node_modules/.bin/gulp lint
|
||||
|
||||
build:
|
||||
<<: *job_defaults
|
||||
resource_class: large
|
||||
steps:
|
||||
- checkout:
|
||||
<<: *post_checkout
|
||||
- restore_cache:
|
||||
key: angular-{{ .Branch }}-{{ checksum "yarn.lock" }}
|
||||
key: *cache_key
|
||||
|
||||
- run: bazel info release
|
||||
- run: bazel run @yarn//:yarn
|
||||
- run: bazel build packages/...
|
||||
- run: bazel test @angular//...
|
||||
# Use bazel query so that we explicitly ask for all buildable targets to be built as well
|
||||
# This avoids waiting for a build command to finish before running the first test
|
||||
# See https://github.com/bazelbuild/bazel/issues/4257
|
||||
- run: bazel query --output=label '//packages/... union @angular//...' | xargs bazel test --config=ci
|
||||
|
||||
- save_cache:
|
||||
key: angular-{{ .Branch }}-{{ checksum "yarn.lock" }}
|
||||
key: *cache_key
|
||||
paths:
|
||||
- "node_modules"
|
||||
|
||||
|
@ -15,7 +15,6 @@
|
||||
# hansl - Hans Larsen
|
||||
# IgorMinar - Igor Minar
|
||||
# jasonaden - Jason Aden
|
||||
# juleskremer - Jules Kremer
|
||||
# kara - Kara Erickson
|
||||
# matsko - Matias Niemelä
|
||||
# mhevery - Misko Hevery
|
||||
@ -25,7 +24,6 @@
|
||||
# tinayuangao - Tina Gao
|
||||
# vicb - Victor Berchet
|
||||
# vikerman - Vikram Subramanian
|
||||
# wardbell - Ward Bell
|
||||
|
||||
|
||||
version: 2
|
||||
@ -36,14 +34,33 @@ group_defaults:
|
||||
enabled: true
|
||||
approve_by_comment:
|
||||
enabled: false
|
||||
# see http://docs.pullapprove.com/groups/author_approval/
|
||||
author_approval:
|
||||
# If the author is a reviewer on the PR, they will automatically have an "approved" status.
|
||||
auto: true
|
||||
|
||||
groups:
|
||||
# Require all PRs to have at least one approval from *someone*
|
||||
all:
|
||||
users: all
|
||||
required: 1
|
||||
# In this group, your self-approval does not count
|
||||
author_approval:
|
||||
auto: false
|
||||
ignored: true
|
||||
files:
|
||||
include:
|
||||
- "*"
|
||||
|
||||
root:
|
||||
conditions:
|
||||
files:
|
||||
include:
|
||||
- "*"
|
||||
exclude:
|
||||
- "WORKSPACE"
|
||||
- "BUILD.bazel"
|
||||
- ".circleci/*"
|
||||
- "aio/*"
|
||||
- "integration/*"
|
||||
- "modules/*"
|
||||
@ -70,9 +87,11 @@ groups:
|
||||
- "*.bazel"
|
||||
- "*.bzl"
|
||||
- "packages/bazel/*"
|
||||
- "tools/bazel.rc"
|
||||
users:
|
||||
- alexeagle #primary
|
||||
- chuckjaz
|
||||
- IgorMinar
|
||||
- vikerman #fallback
|
||||
|
||||
build-and-ci:
|
||||
@ -84,6 +103,7 @@ groups:
|
||||
- "*.lock"
|
||||
- "tools/*"
|
||||
exclude:
|
||||
- "tools/bazel.rc"
|
||||
- "tools/public_api_guard/*"
|
||||
- "aio/*"
|
||||
users:
|
||||
@ -279,7 +299,7 @@ groups:
|
||||
files:
|
||||
- "packages/benchpress/*"
|
||||
users:
|
||||
- alxhub #primary
|
||||
- alxhub # primary
|
||||
# needs secondary
|
||||
- IgorMinar #fallback
|
||||
- mhevery #fallback
|
||||
@ -307,10 +327,8 @@ groups:
|
||||
- "aio/content/navigation.json"
|
||||
- "aio/content/license.md"
|
||||
users:
|
||||
- juleskremer #primary
|
||||
- Foxandxss
|
||||
- stephenfluin
|
||||
- wardbell
|
||||
- Foxandxss
|
||||
- petebacondarwin
|
||||
- gkalpak
|
||||
- IgorMinar #fallback
|
||||
@ -324,7 +342,6 @@ groups:
|
||||
- "aio/content/navigation.json"
|
||||
- "aio/content/license.md"
|
||||
users:
|
||||
- juleskremer #primary
|
||||
- stephenfluin
|
||||
- petebacondarwin
|
||||
- gkalpak
|
||||
|
@ -1,8 +1,10 @@
|
||||
language: node_js
|
||||
sudo: false
|
||||
# Work-around for https://github.com/travis-ci/travis-ci/issues/8836#issuecomment-356362524.
|
||||
# (Restore `sudo: false` once that is resolved.)
|
||||
sudo: required
|
||||
dist: trusty
|
||||
node_js:
|
||||
- '6.9.5'
|
||||
- '8.9.1'
|
||||
|
||||
addons:
|
||||
# firefox: "38.0"
|
||||
@ -54,7 +56,6 @@ env:
|
||||
- CI_MODE=browserstack_optional
|
||||
- CI_MODE=aio_tools_test
|
||||
- CI_MODE=aio
|
||||
- CI_MODE=aio_optional
|
||||
- CI_MODE=aio_e2e AIO_SHARD=0
|
||||
- CI_MODE=aio_e2e AIO_SHARD=1
|
||||
- CI_MODE=bazel
|
||||
@ -64,7 +65,6 @@ matrix:
|
||||
allow_failures:
|
||||
- env: "CI_MODE=saucelabs_optional"
|
||||
- env: "CI_MODE=browserstack_optional"
|
||||
- env: "CI_MODE=aio_optional"
|
||||
|
||||
before_install:
|
||||
# source the env.sh script so that the exported variables are available to other scripts later on
|
||||
|
42
BUILD.bazel
42
BUILD.bazel
@ -1,5 +1,8 @@
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
exports_files(["tsconfig.json"])
|
||||
|
||||
exports_files([
|
||||
"tsconfig.json",
|
||||
])
|
||||
|
||||
# This rule belongs in node_modules/BUILD
|
||||
# It's here as a workaround for
|
||||
@ -11,17 +14,25 @@ filegroup(
|
||||
# bazel query "deps(:node_modules)" | wc -l
|
||||
# This won't scale in the general case.
|
||||
# TODO(alexeagle): figure out what to do
|
||||
srcs = glob(["/".join(["node_modules", pkg, "**", ext]) for pkg in [
|
||||
srcs = glob(["/".join([
|
||||
"node_modules",
|
||||
pkg,
|
||||
"**",
|
||||
ext,
|
||||
]) for pkg in [
|
||||
"jasmine",
|
||||
"typescript",
|
||||
"zone.js",
|
||||
"rxjs",
|
||||
"@types",
|
||||
"tsutils",
|
||||
"@types/jasmine",
|
||||
"@types/node",
|
||||
"@types/source-map",
|
||||
"tsickle",
|
||||
"hammerjs",
|
||||
"protobufjs",
|
||||
"bytebuffer",
|
||||
"reflect-metadata",
|
||||
"source-map-support",
|
||||
"minimist",
|
||||
] for ext in [
|
||||
"*.js",
|
||||
@ -29,3 +40,26 @@ filegroup(
|
||||
"*.d.ts",
|
||||
]]),
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "web_test_bootstrap_scripts",
|
||||
# do not sort
|
||||
srcs = [
|
||||
"//:node_modules/reflect-metadata/Reflect.js",
|
||||
"//:node_modules/zone.js/dist/zone.js",
|
||||
"//:node_modules/zone.js/dist/async-test.js",
|
||||
"//:node_modules/zone.js/dist/sync-test.js",
|
||||
"//:node_modules/zone.js/dist/fake-async-test.js",
|
||||
"//:node_modules/zone.js/dist/proxy.js",
|
||||
"//:node_modules/zone.js/dist/jasmine-patch.js",
|
||||
],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "angularjs",
|
||||
# do not sort
|
||||
srcs = [
|
||||
"//:node_modules/angular/angular.js",
|
||||
"//:node_modules/angular-mocks/angular-mocks.js",
|
||||
],
|
||||
)
|
||||
|
237
CHANGELOG.md
237
CHANGELOG.md
@ -1,3 +1,178 @@
|
||||
<a name="5.2.0"></a>
|
||||
# [5.2.0](https://github.com/angular/angular/compare/5.2.0-rc.0...5.2.0) (2018-01-10)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **bazel:** Give correct module names for ES6 output ([#21320](https://github.com/angular/angular/issues/21320)) ([9728dce](https://github.com/angular/angular/commit/9728dce)), closes [#21022](https://github.com/angular/angular/issues/21022)
|
||||
* **benchpress:** forward compat with selenium_webdriver 3.6.0 ([#21399](https://github.com/angular/angular/issues/21399)) ([6040ee3](https://github.com/angular/angular/commit/6040ee3))
|
||||
* **benchpress:** work around missing events from Chrome 63 ([#21396](https://github.com/angular/angular/issues/21396)) ([fa03ae1](https://github.com/angular/angular/commit/fa03ae1))
|
||||
* **common:** export currencies via `getCurrencySymbol` ([#20983](https://github.com/angular/angular/issues/20983)) ([fecf768](https://github.com/angular/angular/commit/fecf768))
|
||||
|
||||
|
||||
<a name="5.2.0-rc.0"></a>
|
||||
# [5.2.0-rc.0](https://github.com/angular/angular/compare/5.2.0-beta.1...5.2.0-rc.0) (2018-01-04)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **animations:** avoid infinite loop with multiple blocked sub triggers ([#21119](https://github.com/angular/angular/issues/21119)) ([86a36ea](https://github.com/angular/angular/commit/86a36ea))
|
||||
* **animations:** renaming issue with DOMAnimation. ([#21125](https://github.com/angular/angular/issues/21125)) ([871ece6](https://github.com/angular/angular/commit/871ece6))
|
||||
* **common:** handle JS floating point errors in percent pipe ([#20329](https://github.com/angular/angular/issues/20329)) ([07b81ae](https://github.com/angular/angular/commit/07b81ae)), closes [#20136](https://github.com/angular/angular/issues/20136)
|
||||
* **language-service:** ignore null metadatas ([#20557](https://github.com/angular/angular/issues/20557)) ([3e47ea2](https://github.com/angular/angular/commit/3e47ea2)), closes [#20260](https://github.com/angular/angular/issues/20260)
|
||||
* **router:** fix wildcard route with lazy loaded module (again) ([#18139](https://github.com/angular/angular/issues/18139)) ([5ba1cf1](https://github.com/angular/angular/commit/5ba1cf1)), closes [#13848](https://github.com/angular/angular/issues/13848)
|
||||
|
||||
|
||||
|
||||
<a name="5.1.3"></a>
|
||||
## [5.1.3](https://github.com/angular/angular/compare/5.1.2...5.1.3) (2018-01-03)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **animations:** avoid infinite loop with multiple blocked sub triggers ([#21119](https://github.com/angular/angular/issues/21119)) ([3e34fa8](https://github.com/angular/angular/commit/3e34fa8))
|
||||
* **animations:** renaming issue with DOMAnimation. ([#21125](https://github.com/angular/angular/issues/21125)) ([d1f4500](https://github.com/angular/angular/commit/d1f4500))
|
||||
* **common:** handle JS floating point errors in percent pipe ([#20329](https://github.com/angular/angular/issues/20329)) ([fa0e8ef](https://github.com/angular/angular/commit/fa0e8ef)), closes [#20136](https://github.com/angular/angular/issues/20136)
|
||||
* **language-service:** ignore null metadatas ([#20557](https://github.com/angular/angular/issues/20557)) ([48a1f32](https://github.com/angular/angular/commit/48a1f32)), closes [#20260](https://github.com/angular/angular/issues/20260)
|
||||
* **router:** fix wildcard route with lazy loaded module (again) ([#18139](https://github.com/angular/angular/issues/18139)) ([8c99175](https://github.com/angular/angular/commit/8c99175)), closes [#13848](https://github.com/angular/angular/issues/13848)
|
||||
|
||||
|
||||
<a name="5.2.0-beta.1"></a>
|
||||
# [5.2.0-beta.1](https://github.com/angular/angular/compare/5.2.0-beta.0...5.2.0-beta.1) (2017-12-20)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **compiler:** generate the correct imports for summary type-check ([d91ff17](https://github.com/angular/angular/commit/d91ff17))
|
||||
* **forms:** avoid producing an error with hostBindingTypeCheck ([d213a20](https://github.com/angular/angular/commit/d213a20))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **compiler:** allow ngIf to use the ngIf expression directly as a guard ([82bcd83](https://github.com/angular/angular/commit/82bcd83))
|
||||
* **router:** add "paramsInheritanceStrategy" router configuration option ([5efea2f](https://github.com/angular/angular/commit/5efea2f)), closes [#20572](https://github.com/angular/angular/issues/20572)
|
||||
|
||||
|
||||
|
||||
<a name="5.1.2"></a>
|
||||
## [5.1.2](https://github.com/angular/angular/compare/5.1.1...5.1.2) (2017-12-20)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **common:** fix a Closure compilation issue. ([267ebf3](https://github.com/angular/angular/commit/267ebf3))
|
||||
* **compiler:** make tsx file aot compatible ([756dd34](https://github.com/angular/angular/commit/756dd34)), closes [#20555](https://github.com/angular/angular/issues/20555)
|
||||
* **compiler:** report an error for recursive module references ([ced575f](https://github.com/angular/angular/commit/ced575f))
|
||||
* **compiler-cli:** do not emit invalid .metadata.json files ([a1d4c2d](https://github.com/angular/angular/commit/a1d4c2d))
|
||||
* **compiler-cli:** do not force type checking on .js files ([3b63e16](https://github.com/angular/angular/commit/3b63e16))
|
||||
* **service-worker:** check for updates on navigation ([a33182c](https://github.com/angular/angular/commit/a33182c)), closes [#20877](https://github.com/angular/angular/issues/20877)
|
||||
* **upgrade:** replaces get/setAngularLib with get/setAngularJSGlobal ([66cc2fa](https://github.com/angular/angular/commit/66cc2fa))
|
||||
|
||||
|
||||
|
||||
<a name="5.2.0-beta.0"></a>
|
||||
# [5.2.0-beta.0](https://github.com/angular/angular/compare/5.1.0...5.2.0-beta.0) (2017-12-13)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **animations:** re-introduce support for transition matching functions ([#20723](https://github.com/angular/angular/issues/20723)) ([590d93b](https://github.com/angular/angular/commit/590d93b)), closes [#18959](https://github.com/angular/angular/issues/18959)
|
||||
* **compiler:** add a pseudo $any() function to disable type checking ([#20876](https://github.com/angular/angular/issues/20876)) ([70cd124](https://github.com/angular/angular/commit/70cd124))
|
||||
* **compiler:** narrow types of expressions used in *ngIf ([#20702](https://github.com/angular/angular/issues/20702)) ([e7d9cb3](https://github.com/angular/angular/commit/e7d9cb3))
|
||||
* **core:** add source to `StaticInjectorError` message ([#20817](https://github.com/angular/angular/issues/20817)) ([b7738e1](https://github.com/angular/angular/commit/b7738e1)), closes [#19302](https://github.com/angular/angular/issues/19302)
|
||||
* **forms:** allow nulls on setAsyncValidators ([#20327](https://github.com/angular/angular/issues/20327)) ([d41d2c4](https://github.com/angular/angular/commit/d41d2c4)), closes [#20296](https://github.com/angular/angular/issues/20296)
|
||||
|
||||
|
||||
|
||||
<a name="5.1.1"></a>
|
||||
## [5.1.1](https://github.com/angular/angular/compare/5.1.0...5.1.1) (2017-12-13)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **animations:** ensure multi-level route leave animations are queryable ([#20787](https://github.com/angular/angular/issues/20787)) ([d09d497](https://github.com/angular/angular/commit/d09d497)), closes [#19807](https://github.com/angular/angular/issues/19807)
|
||||
* **animations:** ensure the web-animations driver properly handles empty keyframes ([#20648](https://github.com/angular/angular/issues/20648)) ([c3e8731](https://github.com/angular/angular/commit/c3e8731)), closes [#15858](https://github.com/angular/angular/issues/15858)
|
||||
* **animations:** properly recover and cleanup DOM when CD failures occur ([#20719](https://github.com/angular/angular/issues/20719)) ([e6a2805](https://github.com/angular/angular/commit/e6a2805)), closes [#19093](https://github.com/angular/angular/issues/19093)
|
||||
* **animations:** support webkit-based vendor prefixes for prop validations ([#19055](https://github.com/angular/angular/issues/19055)) ([501f01e](https://github.com/angular/angular/commit/501f01e)), closes [#18921](https://github.com/angular/angular/issues/18921)
|
||||
* **bazel:** don't equate moduleName with fileName ([#20895](https://github.com/angular/angular/issues/20895)) ([0c9f7b0](https://github.com/angular/angular/commit/0c9f7b0))
|
||||
* **compiler:** support referencing enums in namespaces ([#20947](https://github.com/angular/angular/issues/20947)) ([d6da798](https://github.com/angular/angular/commit/d6da798)), closes [#18170](https://github.com/angular/angular/issues/18170)
|
||||
* **compiler-cli:** disable checkTypes in emit. ([#20828](https://github.com/angular/angular/issues/20828)) ([160a154](https://github.com/angular/angular/commit/160a154))
|
||||
* **compiler-cli:** fix swallowed Error messages ([#20846](https://github.com/angular/angular/issues/20846)) ([6727336](https://github.com/angular/angular/commit/6727336))
|
||||
* **compiler-cli:** merge [@fileoverview](https://github.com/fileoverview) comments. ([#20870](https://github.com/angular/angular/issues/20870)) ([be9a737](https://github.com/angular/angular/commit/be9a737))
|
||||
* **router:** NavigationError and NavigationCancel should be emitted after resetting the URL ([#20803](https://github.com/angular/angular/issues/20803)) ([baeec4d](https://github.com/angular/angular/commit/baeec4d))
|
||||
|
||||
|
||||
|
||||
<a name="5.1.0"></a>
|
||||
# [5.1.0](https://github.com/angular/angular/compare/5.1.0-rc.1...5.1.0) (2017-12-06)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **animations:** ensure DOM is cleaned up after multiple [@trigger](https://github.com/trigger) leave animations finish ([#20740](https://github.com/angular/angular/issues/20740)) ([b78ada1](https://github.com/angular/angular/commit/b78ada1)), closes [#20541](https://github.com/angular/angular/issues/20541)
|
||||
* **service-worker:** initialize in browser only ([#20782](https://github.com/angular/angular/issues/20782)) ([7cabaa0](https://github.com/angular/angular/commit/7cabaa0)), closes [#20360](https://github.com/angular/angular/issues/20360)
|
||||
* **service-worker:** esm2015 points to wrong path ([#20800](https://github.com/angular/angular/issues/20800)) ([da3563c](https://github.com/angular/angular/commit/da3563c))
|
||||
|
||||
|
||||
|
||||
<a name="5.1.0-rc.1"></a>
|
||||
# [5.1.0-rc.1](https://github.com/angular/angular/compare/5.1.0-rc.0...5.1.0-rc.1) (2017-12-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **compiler-cli:** propagate ts.SourceFile moduleName into metadata ([f841fbe](https://github.com/angular/angular/commit/f841fbe))
|
||||
* **service-worker:** allow disabling SW while still using services ([65f4fad](https://github.com/angular/angular/commit/65f4fad))
|
||||
* **service-worker:** don't crash if SW not supported ([b9a91a5](https://github.com/angular/angular/commit/b9a91a5))
|
||||
* **service-worker:** send initialization signal from the application ([3fbcde9](https://github.com/angular/angular/commit/3fbcde9))
|
||||
* **service-worker:** use relative path for ngsw.json ([f582620](https://github.com/angular/angular/commit/f582620))
|
||||
|
||||
|
||||
|
||||
<a name="5.0.5"></a>
|
||||
## [5.0.5](https://github.com/angular/angular/compare/5.0.4...5.0.5) (2017-12-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **compiler-cli:** propagate ts.SourceFile moduleName into metadata ([a2ff4ab](https://github.com/angular/angular/commit/a2ff4ab))
|
||||
* **service-worker:** allow disabling SW while still using services ([f99335b](https://github.com/angular/angular/commit/f99335b))
|
||||
* **service-worker:** don't crash if SW not supported ([ee37d4b](https://github.com/angular/angular/commit/ee37d4b))
|
||||
* **service-worker:** send initialization signal from the application ([6bf07b4](https://github.com/angular/angular/commit/6bf07b4))
|
||||
* **service-worker:** use relative path for ngsw.json ([56c98f7](https://github.com/angular/angular/commit/56c98f7))
|
||||
|
||||
|
||||
|
||||
<a name="5.1.0-rc.0"></a>
|
||||
# [5.1.0-rc.0](https://github.com/angular/angular/compare/5.1.0-beta.2...5.1.0-rc.0) (2017-12-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **animations:** ensure multi-level enter animations work ([#19455](https://github.com/angular/angular/issues/19455)) ([dd6237e](https://github.com/angular/angular/commit/dd6237e))
|
||||
* **animations:** ensure multi-level enter animations work ([#19455](https://github.com/angular/angular/issues/19455)) ([b2a586c](https://github.com/angular/angular/commit/b2a586c))
|
||||
* **animations:** ensure multi-level leave animations work ([#19455](https://github.com/angular/angular/issues/19455)) ([1366762](https://github.com/angular/angular/commit/1366762))
|
||||
* **animations:** ensure multi-level leave animations work ([#19455](https://github.com/angular/angular/issues/19455)) ([c2b3792](https://github.com/angular/angular/commit/c2b3792))
|
||||
* **bazel:** produce named AMD modules for codegen ([#20547](https://github.com/angular/angular/issues/20547)) ([6e83204](https://github.com/angular/angular/commit/6e83204)), closes [#19422](https://github.com/angular/angular/issues/19422)
|
||||
* **common:** accept falsy values as HTTP bodies ([#19958](https://github.com/angular/angular/issues/19958)) ([15a54df](https://github.com/angular/angular/commit/15a54df)), closes [#19825](https://github.com/angular/angular/issues/19825) [#19195](https://github.com/angular/angular/issues/19195)
|
||||
* **common:** don't strip XSSI prefix for if error isn't JSON ([#19958](https://github.com/angular/angular/issues/19958)) ([aafa75d](https://github.com/angular/angular/commit/aafa75d))
|
||||
* **common:** remove useless guard in HttpClient ([#19958](https://github.com/angular/angular/issues/19958)) ([eb01ad5](https://github.com/angular/angular/commit/eb01ad5)), closes [#19223](https://github.com/angular/angular/issues/19223)
|
||||
* **common:** treat an empty body as null when parsing JSON in HttpClient ([#19958](https://github.com/angular/angular/issues/19958)) ([503be69](https://github.com/angular/angular/commit/503be69)), closes [#18680](https://github.com/angular/angular/issues/18680) [#19413](https://github.com/angular/angular/issues/19413) [#19502](https://github.com/angular/angular/issues/19502) [#19555](https://github.com/angular/angular/issues/19555)
|
||||
* **compiler:** correctly detect when to serialze summary metadata ([#20668](https://github.com/angular/angular/issues/20668)) ([8bb42df](https://github.com/angular/angular/commit/8bb42df))
|
||||
* **compiler-cli:** fix memory leak in program creation ([#20692](https://github.com/angular/angular/issues/20692)) ([71e5de6](https://github.com/angular/angular/commit/71e5de6)), closes [#20691](https://github.com/angular/angular/issues/20691)
|
||||
* **compiler-cli:** normalize sourcepaths for i18n extracted files ([#20417](https://github.com/angular/angular/issues/20417)) ([de78307](https://github.com/angular/angular/commit/de78307)), closes [#20416](https://github.com/angular/angular/issues/20416)
|
||||
* **core:** should use native addEventListener in ngZone ([#20672](https://github.com/angular/angular/issues/20672)) ([65a2cb8](https://github.com/angular/angular/commit/65a2cb8))
|
||||
* **language-service:** Allow empty templates ([#20651](https://github.com/angular/angular/issues/20651)) ([3203069](https://github.com/angular/angular/commit/3203069)), closes [#19406](https://github.com/angular/angular/issues/19406)
|
||||
* **language-service:** Fix crash when no script files are found ([#20550](https://github.com/angular/angular/issues/20550)) ([54bfe14](https://github.com/angular/angular/commit/54bfe14)), closes [#19325](https://github.com/angular/angular/issues/19325)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **common:** add locale id parameter to `registerLocaleData` ([#20623](https://github.com/angular/angular/issues/20623)) ([24bf3e2](https://github.com/angular/angular/commit/24bf3e2))
|
||||
* **compiler-cli:** improve error messages produced during structural errors ([#20459](https://github.com/angular/angular/issues/20459)) ([8ecda94](https://github.com/angular/angular/commit/8ecda94))
|
||||
|
||||
|
||||
|
||||
<a name="5.0.4"></a>
|
||||
## [5.0.4](https://github.com/angular/angular/compare/5.0.3...5.0.4) (2017-12-01)
|
||||
|
||||
@ -15,6 +190,30 @@
|
||||
|
||||
|
||||
|
||||
<a name="5.1.0-beta.2"></a>
|
||||
# [5.1.0-beta.2](https://github.com/angular/angular/compare/5.1.0-beta.1...5.1.0-beta.2) (2017-11-22)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **animations:** always fire inner trigger callbacks even if blocked by parent animations ([#19753](https://github.com/angular/angular/issues/19753)) ([0e012c9](https://github.com/angular/angular/commit/0e012c9)), closes [#19100](https://github.com/angular/angular/issues/19100)
|
||||
* **animations:** always fire start and done callbacks in order for noop animations ([#20570](https://github.com/angular/angular/issues/20570)) ([ffb6dbe](https://github.com/angular/angular/commit/ffb6dbe))
|
||||
* **animations:** validate against trigger() names that use @ symbols ([#20326](https://github.com/angular/angular/issues/20326)) ([1861e41](https://github.com/angular/angular/commit/1861e41))
|
||||
* **benchpress:** Allow ignoring navigationStart events in perflog metric. ([#20312](https://github.com/angular/angular/issues/20312)) ([717ac5a](https://github.com/angular/angular/commit/717ac5a))
|
||||
* **common:** return ISubscription from Location.subscribe() ([#20429](https://github.com/angular/angular/issues/20429)) ([437a044](https://github.com/angular/angular/commit/437a044)), closes [#20406](https://github.com/angular/angular/issues/20406)
|
||||
* **compiler:** emit correct type-check-blocks with TemplateRef's ([#20463](https://github.com/angular/angular/issues/20463)) ([68b53c0](https://github.com/angular/angular/commit/68b53c0))
|
||||
* **compiler:** support event bindings in `fullTemplateTypeCheck` ([#20490](https://github.com/angular/angular/issues/20490)) ([4ed0439](https://github.com/angular/angular/commit/4ed0439))
|
||||
* **core:** fix [#20532](https://github.com/angular/angular/issues/20532), should be able to cancel listener from mixed zone ([#20538](https://github.com/angular/angular/issues/20538)) ([a740e4f](https://github.com/angular/angular/commit/a740e4f))
|
||||
* **core:** should support event.stopImmediatePropagation ([#20469](https://github.com/angular/angular/issues/20469)) ([997336b](https://github.com/angular/angular/commit/997336b))
|
||||
* **forms:** updateOn should check if change occurred ([#20358](https://github.com/angular/angular/issues/20358)) ([69c53c3](https://github.com/angular/angular/commit/69c53c3)), closes [#20259](https://github.com/angular/angular/issues/20259)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **platform-browser-dynamic:** export `JitCompilerFactory` ([#20478](https://github.com/angular/angular/issues/20478)) ([d7a727c](https://github.com/angular/angular/commit/d7a727c)), closes [#20125](https://github.com/angular/angular/issues/20125)
|
||||
|
||||
|
||||
|
||||
<a name="5.0.3"></a>
|
||||
## [5.0.3](https://github.com/angular/angular/compare/5.0.2...5.0.3) (2017-11-22)
|
||||
|
||||
@ -32,6 +231,28 @@
|
||||
* **forms:** updateOn should check if change occurred ([#20358](https://github.com/angular/angular/issues/20358)) ([f9f2c20](https://github.com/angular/angular/commit/f9f2c20)), closes [#20259](https://github.com/angular/angular/issues/20259)
|
||||
|
||||
|
||||
<a name="5.1.0-beta.1"></a>
|
||||
# [5.1.0-beta.1](https://github.com/angular/angular/compare/5.1.0-beta.0...5.1.0-beta.1) (2017-11-16)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **animations:** always fire inner trigger callbacks even if blocked by parent animations ([#19753](https://github.com/angular/angular/issues/19753)) ([d47b2a6](https://github.com/angular/angular/commit/d47b2a6)), closes [#19100](https://github.com/angular/angular/issues/19100)
|
||||
* **animations:** ensure final state() styles are applied within @.disabled animations ([#20267](https://github.com/angular/angular/issues/20267)) ([20aafff](https://github.com/angular/angular/commit/20aafff)), closes [#20266](https://github.com/angular/angular/issues/20266)
|
||||
* **bazel:** adjust mock of tsconfig for ng_module rule unit test ([#20175](https://github.com/angular/angular/issues/20175)) ([c2a24b4](https://github.com/angular/angular/commit/c2a24b4))
|
||||
* **compiler:** fix corner cases in shadow CSS ([c32f5fd](https://github.com/angular/angular/commit/c32f5fd))
|
||||
* **compiler:** recognize @NgModule with a redundant @Injectable ([#20320](https://github.com/angular/angular/issues/20320)) ([c33a576](https://github.com/angular/angular/commit/c33a576))
|
||||
* **compiler:** show explanatory text in template errors ([#20313](https://github.com/angular/angular/issues/20313)) ([3257fcd](https://github.com/angular/angular/commit/3257fcd))
|
||||
* **core:** ensure init lifecycle events are called ([#20258](https://github.com/angular/angular/issues/20258)) ([24cf8b3](https://github.com/angular/angular/commit/24cf8b3))
|
||||
* **language-service:** pass compilerOptions.paths to ReflectorHost ([#20222](https://github.com/angular/angular/issues/20222)) ([eb8013e](https://github.com/angular/angular/commit/eb8013e))
|
||||
* **router:** 'merge' queryParamHandling strategy should be able to remove query params ([#19733](https://github.com/angular/angular/issues/19733)) ([a622e19](https://github.com/angular/angular/commit/a622e19)), closes [#18463](https://github.com/angular/angular/issues/18463) [#17202](https://github.com/angular/angular/issues/17202)
|
||||
* Update test code to type-check under TS 2.5 ([#20175](https://github.com/angular/angular/issues/20175)) ([5ec1717](https://github.com/angular/angular/commit/5ec1717))
|
||||
|
||||
### Features
|
||||
|
||||
* **typescript:** support TypeScript 2.5 ([a9f3e2b](https://github.com/angular/angular/commit/a9f3e2b)), closes [#20175](https://github.com/angular/angular/issues/20175)
|
||||
|
||||
> Note, if you do `Injector.get(Token)` where `Token` has static members, you'll run into https://github.com/Microsoft/TypeScript/issues/20102 where the returned type is `{}` rather than `Token`. Use `Injector.get<Token>(Token)` to work around.
|
||||
|
||||
<a name="5.0.2"></a>
|
||||
## [5.0.2](https://github.com/angular/angular/compare/5.0.1...5.0.2) (2017-11-16)
|
||||
@ -46,6 +267,22 @@
|
||||
* **router:** 'merge' queryParamHandling strategy should be able to remove query params ([#19733](https://github.com/angular/angular/issues/19733)) ([b732fb9](https://github.com/angular/angular/commit/b732fb9)), closes [#18463](https://github.com/angular/angular/issues/18463) [#17202](https://github.com/angular/angular/issues/17202)
|
||||
|
||||
|
||||
<a name="5.1.0-beta.0"></a>
|
||||
# [5.1.0-beta.0](https://github.com/angular/angular/compare/5.0.0-rc.4...5.1.0-beta.0) (2017-11-08)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **compiler:** don't overwrite missingTranslation's value in JIT ([#19952](https://github.com/angular/angular/issues/19952)) ([799cbb9](https://github.com/angular/angular/commit/799cbb9))
|
||||
* **compiler:** report a reasonable error with invalid metadata ([#20062](https://github.com/angular/angular/issues/20062)) ([da22c48](https://github.com/angular/angular/commit/da22c48))
|
||||
* **compiler-cli:** don't report emit diagnostics when `--noEmitOnError` is off ([#20063](https://github.com/angular/angular/issues/20063)) ([8639995](https://github.com/angular/angular/commit/8639995))
|
||||
* **core:** `__symbol__` should return `__zone_symbol__` without zone.js loaded ([#19541](https://github.com/angular/angular/issues/19541)) ([678d1cf](https://github.com/angular/angular/commit/678d1cf))
|
||||
* **core:** should support event.stopImmediatePropagation ([#19222](https://github.com/angular/angular/issues/19222)) ([7083791](https://github.com/angular/angular/commit/7083791))
|
||||
* **platform-browser:** support Symbols in custom `jasmineToString()` method ([#19794](https://github.com/angular/angular/issues/19794)) ([5a6efa7](https://github.com/angular/angular/commit/5a6efa7))
|
||||
|
||||
### Features
|
||||
|
||||
* **compiler:** introduce `TestBed.overrideTemplateUsingTestingModule` ([a460066](https://github.com/angular/angular/commit/a460066)), closes [#19815](https://github.com/angular/angular/issues/19815)
|
||||
|
||||
|
||||
<a name="5.0.1"></a>
|
||||
## [5.0.1](https://github.com/angular/angular/compare/5.0.0...5.0.1) (2017-11-08)
|
||||
|
@ -69,36 +69,37 @@ You can file new issues by filling out our [new issue form](https://github.com/a
|
||||
### <a name="submit-pr"></a> Submitting a Pull Request (PR)
|
||||
Before you submit your Pull Request (PR) consider the following guidelines:
|
||||
|
||||
* Search [GitHub](https://github.com/angular/angular/pulls) for an open or closed PR
|
||||
1. Search [GitHub](https://github.com/angular/angular/pulls) for an open or closed PR
|
||||
that relates to your submission. You don't want to duplicate effort.
|
||||
* Please sign our [Contributor License Agreement (CLA)](#cla) before sending PRs.
|
||||
1. Please sign our [Contributor License Agreement (CLA)](#cla) before sending PRs.
|
||||
We cannot accept code without this.
|
||||
* Make your changes in a new git branch:
|
||||
1. Fork the angular/angular repo.
|
||||
1. Make your changes in a new git branch:
|
||||
|
||||
```shell
|
||||
git checkout -b my-fix-branch master
|
||||
```
|
||||
|
||||
* Create your patch, **including appropriate test cases**.
|
||||
* Follow our [Coding Rules](#rules).
|
||||
* Run the full Angular test suite, as described in the [developer documentation][dev-doc],
|
||||
1. Create your patch, **including appropriate test cases**.
|
||||
1. Follow our [Coding Rules](#rules).
|
||||
1. Run the full Angular test suite, as described in the [developer documentation][dev-doc],
|
||||
and ensure that all tests pass.
|
||||
* Commit your changes using a descriptive commit message that follows our
|
||||
1. Commit your changes using a descriptive commit message that follows our
|
||||
[commit message conventions](#commit). Adherence to these conventions
|
||||
is necessary because release notes are automatically generated from these messages.
|
||||
|
||||
```shell
|
||||
git commit -a
|
||||
```
|
||||
Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files.
|
||||
Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files.
|
||||
|
||||
* Push your branch to GitHub:
|
||||
1. Push your branch to GitHub:
|
||||
|
||||
```shell
|
||||
git push origin my-fix-branch
|
||||
```
|
||||
|
||||
* In GitHub, send a pull request to `angular:master`.
|
||||
1. In GitHub, send a pull request to `angular:master`.
|
||||
* If we suggest changes then:
|
||||
* Make the required updates.
|
||||
* Re-run the Angular test suites to ensure tests are still passing.
|
||||
|
2
LICENSE
2
LICENSE
@ -1,6 +1,6 @@
|
||||
The MIT License
|
||||
|
||||
Copyright (c) 2014-2017 Google, Inc. http://angular.io
|
||||
Copyright (c) 2014-2018 Google, Inc. http://angular.io
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
@ -2,8 +2,6 @@
|
||||
[](https://circleci.com/gh/angular/angular/tree/master)
|
||||
[](https://www.browserstack.com/automate/public-build/LzF3RzBVVGt6VWE2S0hHaC9uYllOZz09LS1BVjNTclBKV0x4eVRlcjA4QVY1M0N3PT0=--eb4ce8c8dc2c1c5b2b5352d473ee12a73ac20e06)
|
||||
[](https://gitter.im/angular/angular?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
[](http://issuestats.com/github/angular/angular)
|
||||
[](http://issuestats.com/github/angular/angular)
|
||||
[](https://www.npmjs.com/@angular/core)
|
||||
|
||||
|
||||
|
50
WORKSPACE
50
WORKSPACE
@ -5,20 +5,60 @@ load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
|
||||
git_repository(
|
||||
name = "build_bazel_rules_nodejs",
|
||||
remote = "https://github.com/bazelbuild/rules_nodejs.git",
|
||||
# TODO(alexeagle): use the correct tag here.
|
||||
commit = "2c6243df53fd33fdab283ebdd01582e4eb815db8",
|
||||
tag = "0.3.1",
|
||||
)
|
||||
|
||||
load("@build_bazel_rules_nodejs//:defs.bzl", "node_repositories")
|
||||
load("@build_bazel_rules_nodejs//:defs.bzl", "check_bazel_version", "node_repositories")
|
||||
|
||||
check_bazel_version("0.9.0")
|
||||
node_repositories(package_json = ["//:package.json"])
|
||||
|
||||
local_repository(
|
||||
git_repository(
|
||||
name = "build_bazel_rules_typescript",
|
||||
path = "node_modules/@bazel/typescript",
|
||||
remote = "https://github.com/bazelbuild/rules_typescript.git",
|
||||
# tag = "0.7.1+",
|
||||
commit = "89d2c75066bea3d9c942f29dd1d2ea543c58d6d5"
|
||||
)
|
||||
|
||||
load("@build_bazel_rules_typescript//:setup.bzl", "ts_setup_workspace")
|
||||
|
||||
ts_setup_workspace()
|
||||
|
||||
local_repository(
|
||||
name = "angular",
|
||||
path = "packages/bazel",
|
||||
)
|
||||
|
||||
local_repository(
|
||||
name = "rxjs",
|
||||
path = "node_modules/rxjs/src",
|
||||
)
|
||||
|
||||
git_repository(
|
||||
name = "com_github_bazelbuild_buildtools",
|
||||
remote = "https://github.com/bazelbuild/buildtools.git",
|
||||
# Note, this commit matches the version of buildifier in angular/ngcontainer
|
||||
# If you change this, also check if it matches the version in the angular/ngcontainer
|
||||
# version in /.circleci/config.yml
|
||||
commit = "b3b620e8bcff18ed3378cd3f35ebeb7016d71f71",
|
||||
)
|
||||
|
||||
http_archive(
|
||||
name = "io_bazel_rules_go",
|
||||
url = "https://github.com/bazelbuild/rules_go/releases/download/0.7.1/rules_go-0.7.1.tar.gz",
|
||||
sha256 = "341d5eacef704415386974bc82a1783a8b7ffbff2ab6ba02375e1ca20d9b031c",
|
||||
)
|
||||
|
||||
load("@io_bazel_rules_go//go:def.bzl", "go_rules_dependencies", "go_register_toolchains")
|
||||
|
||||
go_rules_dependencies()
|
||||
|
||||
go_register_toolchains()
|
||||
|
||||
# Fetching the Bazel source code allows us to compile the Skylark linter
|
||||
http_archive(
|
||||
name = "io_bazel",
|
||||
url = "https://github.com/bazelbuild/bazel/archive/9755c72b48866ed034bd28aa033e9abd27431b1e.zip",
|
||||
strip_prefix = "bazel-9755c72b48866ed034bd28aa033e9abd27431b1e",
|
||||
sha256 = "5b8443fc3481b5fcd9e7f348e1dd93c1397f78b223623c39eb56494c55f41962",
|
||||
)
|
||||
|
@ -1,9 +1,10 @@
|
||||
<hr>
|
||||
<h4>{{hero.name}} Detail</h4>
|
||||
<div>Id: {{hero.id}}</div>
|
||||
<div>Name:
|
||||
<label>Name:
|
||||
<!-- #docregion ngModel -->
|
||||
<input [(ngModel)]="hero.name">
|
||||
<!-- #enddocregion ngModel -->
|
||||
</div>
|
||||
<div>Power:<input [(ngModel)]="hero.power"></div>
|
||||
</label>
|
||||
<br />
|
||||
<label>Power: <input [(ngModel)]="hero.power"></label>
|
||||
|
@ -7,7 +7,7 @@ import { TaxRateService } from './tax-rate.service';
|
||||
selector: 'app-sales-tax',
|
||||
template: `
|
||||
<h2>Sales Tax Calculator</h2>
|
||||
Amount: <input #amountBox (change)="0">
|
||||
<label>Amount: <input #amountBox (change)="0"></label>
|
||||
|
||||
<div *ngIf="amountBox.value">
|
||||
The sales tax is
|
||||
|
@ -5,7 +5,7 @@
|
||||
"!**/*.d.ts",
|
||||
"!**/*.js",
|
||||
"!**/*.[0,1,2].*",
|
||||
"**/dummy.module.ts"
|
||||
"!**/dummy.module.ts"
|
||||
],
|
||||
"tags": ["dependency", "di"]
|
||||
}
|
||||
|
@ -2,5 +2,6 @@
|
||||
import { registerLocaleData } from '@angular/common';
|
||||
import localeFr from '@angular/common/locales/fr';
|
||||
|
||||
registerLocaleData(localeFr);
|
||||
// the second parameter 'fr' is optional
|
||||
registerLocaleData(localeFr, 'fr');
|
||||
// #enddocregion import-locale
|
||||
|
@ -1,7 +1,7 @@
|
||||
// #docregion import-locale-extra
|
||||
import { registerLocaleData } from '@angular/common';
|
||||
import localeFrCa from '@angular/common/locales/fr-CA';
|
||||
import localeFrCaExtra from '@angular/common/locales/extra/fr-CA';
|
||||
import localeFr from '@angular/common/locales/fr';
|
||||
import localeFrExtra from '@angular/common/locales/extra/fr';
|
||||
|
||||
registerLocaleData(localeFrCa, localeFrCaExtra);
|
||||
registerLocaleData(localeFr, 'fr-FR', localeFrExtra);
|
||||
// #enddocregion import-locale-extra
|
||||
|
@ -5,17 +5,6 @@
|
||||
<title>NgModule Minimal</title>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
|
||||
<!-- Polyfills -->
|
||||
<script src="node_modules/core-js/client/shim.min.js"></script>
|
||||
|
||||
<script src="node_modules/zone.js/dist/zone.js"></script>
|
||||
<script src="node_modules/systemjs/dist/system.src.js"></script>
|
||||
<script src="systemjs.config.js"></script>
|
||||
<script>
|
||||
System.import('main.0.js').catch(function(err){ console.error(err); });
|
||||
</script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
@ -5,17 +5,6 @@
|
||||
<title>NgModule Minimal</title>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
|
||||
<!-- Polyfills -->
|
||||
<script src="node_modules/core-js/client/shim.min.js"></script>
|
||||
|
||||
<script src="node_modules/zone.js/dist/zone.js"></script>
|
||||
<script src="node_modules/systemjs/dist/system.src.js"></script>
|
||||
<script src="systemjs.config.js"></script>
|
||||
<script>
|
||||
System.import('main.1.js').catch(function(err){ console.error(err); });
|
||||
</script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
@ -5,17 +5,6 @@
|
||||
<title>NgModule Minimal</title>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
|
||||
<!-- Polyfills -->
|
||||
<script src="node_modules/core-js/client/shim.min.js"></script>
|
||||
|
||||
<script src="node_modules/zone.js/dist/zone.js"></script>
|
||||
<script src="node_modules/systemjs/dist/system.src.js"></script>
|
||||
<script src="systemjs.config.js"></script>
|
||||
<script>
|
||||
System.import('main.1b.js').catch(function(err){ console.error(err); });
|
||||
</script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
@ -5,17 +5,6 @@
|
||||
<title>NgModule Minimal</title>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
|
||||
<!-- Polyfills -->
|
||||
<script src="node_modules/core-js/client/shim.min.js"></script>
|
||||
|
||||
<script src="node_modules/zone.js/dist/zone.js"></script>
|
||||
<script src="node_modules/systemjs/dist/system.src.js"></script>
|
||||
<script src="systemjs.config.js"></script>
|
||||
<script>
|
||||
System.import('main.2.js').catch(function(err){ console.error(err); });
|
||||
</script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
@ -5,17 +5,6 @@
|
||||
<title>NgModule Minimal</title>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
|
||||
<!-- Polyfills -->
|
||||
<script src="node_modules/core-js/client/shim.min.js"></script>
|
||||
|
||||
<script src="node_modules/zone.js/dist/zone.js"></script>
|
||||
<script src="node_modules/systemjs/dist/system.src.js"></script>
|
||||
<script src="systemjs.config.js"></script>
|
||||
<script>
|
||||
System.import('main.3.js').catch(function(err){ console.error(err); });
|
||||
</script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
@ -5,13 +5,17 @@
|
||||
"styles.css",
|
||||
|
||||
"app/app.component.ts",
|
||||
"app/app.component.html",
|
||||
"app/app.component.css",
|
||||
"app/app.module.ts",
|
||||
"app/data-model.ts",
|
||||
"app/hero.service.ts",
|
||||
"app/hero-detail.component.html",
|
||||
"app/hero-detail.component.ts",
|
||||
"app/hero-list.component.html",
|
||||
"app/hero-list.component.ts",
|
||||
"app/hero-detail/hero-detail.component.html",
|
||||
"app/hero-detail/hero-detail.component.ts",
|
||||
"app/hero-detail/hero-detail.component.css",
|
||||
"app/hero-list/hero-list.component.html",
|
||||
"app/hero-list/hero-list.component.ts",
|
||||
"app/hero-list/hero-list.component.css",
|
||||
|
||||
"main-final.ts",
|
||||
"index-final.html"
|
||||
|
@ -6,18 +6,6 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
|
||||
<script src="node_modules/core-js/client/shim.min.js"></script>
|
||||
|
||||
<script src="node_modules/zone.js/dist/zone.js"></script>
|
||||
<script src="node_modules/reflect-metadata/Reflect.js"></script>
|
||||
<script src="node_modules/systemjs/dist/system.src.js"></script>
|
||||
|
||||
<script src="systemjs.config.js"></script>
|
||||
<script>
|
||||
System.import('main-final.js').catch(function(err){ console.error(err); });
|
||||
</script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
44
aio/content/examples/service-worker-getting-started/e2e/app.e2e-spec.ts
Executable file
44
aio/content/examples/service-worker-getting-started/e2e/app.e2e-spec.ts
Executable file
@ -0,0 +1,44 @@
|
||||
import { AppPage } from './app.po';
|
||||
import { browser, element, by } from 'protractor';
|
||||
|
||||
|
||||
describe('sw-example App', () => {
|
||||
let page: AppPage;
|
||||
|
||||
beforeEach(() => {
|
||||
page = new AppPage();
|
||||
});
|
||||
|
||||
it('should display welcome message', () => {
|
||||
page.navigateTo();
|
||||
expect(page.getParagraphText()).toEqual('Welcome to Service Workers!');
|
||||
});
|
||||
|
||||
it('should display the Angular logo', () => {
|
||||
let logo = element(by.css('img'));
|
||||
page.navigateTo();
|
||||
expect(logo.isPresent()).toBe(true);
|
||||
});
|
||||
|
||||
it('should show a header for the list of links', () => {
|
||||
const listHeader = element(by.css('app-root > h2'));
|
||||
expect(listHeader.getText()).toEqual('Here are some links to help you start:');
|
||||
});
|
||||
|
||||
it('should show a list of links', function () {
|
||||
element.all(by.css('ul > li > h2 > a')).then((items) => {
|
||||
expect(items.length).toBe(4);
|
||||
expect(items[0].getText()).toBe('Angular Service Worker Intro');
|
||||
expect(items[1].getText()).toBe('Tour of Heroes');
|
||||
expect(items[2].getText()).toBe('CLI Documentation');
|
||||
expect(items[3].getText()).toBe('Angular blog');
|
||||
});
|
||||
});
|
||||
// Check for a rejected promise as the service worker is not enabled
|
||||
it('SwUpdate.checkForUpdate() should return a rejected promise', () => {
|
||||
const button = element(by.css('button'));
|
||||
const rejectMessage = element(by.css('p'));
|
||||
button.click();
|
||||
expect(rejectMessage.getText()).toContain('rejected: ');
|
||||
});
|
||||
});
|
@ -0,0 +1,50 @@
|
||||
{
|
||||
"name": "angular.io-example",
|
||||
"version": "0.0.0",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve",
|
||||
"build": "ng build",
|
||||
"test": "ng test",
|
||||
"lint": "ng lint",
|
||||
"e2e": "ng e2e"
|
||||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@angular/animations": "^5.0.0",
|
||||
"@angular/common": "^5.0.0",
|
||||
"@angular/compiler": "^5.0.0",
|
||||
"@angular/core": "^5.0.0",
|
||||
"@angular/forms": "^5.0.0",
|
||||
"@angular/http": "^5.0.0",
|
||||
"@angular/service-worker": "^5.0.0",
|
||||
"@angular/platform-browser": "^5.0.0",
|
||||
"@angular/platform-browser-dynamic": "^5.0.0",
|
||||
"@angular/router": "^5.0.0",
|
||||
"core-js": "^2.4.1",
|
||||
"rxjs": "^5.5.2",
|
||||
"zone.js": "^0.8.14"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/cli": "1.5.4",
|
||||
"@angular/compiler-cli": "^5.0.0",
|
||||
"@angular/language-service": "^5.0.0",
|
||||
"@types/jasmine": "~2.5.53",
|
||||
"@types/jasminewd2": "~2.0.2",
|
||||
"@types/node": "~6.0.60",
|
||||
"codelyzer": "^4.0.1",
|
||||
"jasmine-core": "~2.6.2",
|
||||
"jasmine-spec-reporter": "~4.1.0",
|
||||
"karma": "~1.7.0",
|
||||
"karma-chrome-launcher": "~2.1.1",
|
||||
"karma-cli": "~1.0.1",
|
||||
"karma-coverage-istanbul-reporter": "^1.2.1",
|
||||
"karma-jasmine": "~1.1.0",
|
||||
"karma-jasmine-html-reporter": "^0.2.2",
|
||||
"protractor": "~5.1.2",
|
||||
"ts-node": "~3.2.0",
|
||||
"tslint": "~5.7.0",
|
||||
"typescript": "~2.4.2"
|
||||
}
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
{
|
||||
"description": "Service Worker",
|
||||
"basePath": "src/",
|
||||
"tags": ["service worker"]
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
<!--The content below is only a placeholder and can be replaced.-->
|
||||
<div style="text-align:center">
|
||||
<h1>
|
||||
Welcome to {{title}}!
|
||||
</h1>
|
||||
<img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
|
||||
</div>
|
||||
|
||||
<button id="check" (click)="updateCheck()">Check for Update</button>
|
||||
<p id="checkResult">{{updateCheckText}}</p>
|
||||
|
||||
<h2>Here are some links to help you start: </h2>
|
||||
<ul>
|
||||
<li>
|
||||
<h2><a target="_blank" rel="noopener" href="https://angular.io/service-worker-intro">Angular Service Worker Intro</a></h2>
|
||||
</li>
|
||||
<li>
|
||||
<h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
|
||||
</li>
|
||||
<li>
|
||||
<h2><a target="_blank" rel="noopener" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2>
|
||||
</li>
|
||||
<li>
|
||||
<h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular blog</a></h2>
|
||||
</li>
|
||||
</ul>
|
||||
|
@ -0,0 +1,27 @@
|
||||
import { TestBed, async } from '@angular/core/testing';
|
||||
import { AppComponent } from './app.component';
|
||||
describe('AppComponent', () => {
|
||||
beforeEach(async(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [
|
||||
AppComponent
|
||||
],
|
||||
}).compileComponents();
|
||||
}));
|
||||
it('should create the app', async(() => {
|
||||
const fixture = TestBed.createComponent(AppComponent);
|
||||
const app = fixture.debugElement.componentInstance;
|
||||
expect(app).toBeTruthy();
|
||||
}));
|
||||
it(`should have as title 'app'`, async(() => {
|
||||
const fixture = TestBed.createComponent(AppComponent);
|
||||
const app = fixture.debugElement.componentInstance;
|
||||
expect(app.title).toEqual('Service Workers');
|
||||
}));
|
||||
it('should render title in a h1 tag', async(() => {
|
||||
const fixture = TestBed.createComponent(AppComponent);
|
||||
fixture.detectChanges();
|
||||
const compiled = fixture.debugElement.nativeElement;
|
||||
expect(compiled.querySelector('h1').textContent).toContain('Welcome to Service Workers!');
|
||||
}));
|
||||
});
|
20
aio/content/examples/service-worker-getting-started/src/app/app.component.ts
Executable file
20
aio/content/examples/service-worker-getting-started/src/app/app.component.ts
Executable file
@ -0,0 +1,20 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { SwUpdate } from '@angular/service-worker';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
templateUrl: './app.component.html'
|
||||
})
|
||||
export class AppComponent {
|
||||
title = 'Service Workers';
|
||||
updateCheckText = '';
|
||||
|
||||
constructor(private update: SwUpdate) {}
|
||||
|
||||
updateCheck(): void {
|
||||
this.update
|
||||
.checkForUpdate()
|
||||
.then(() => this.updateCheckText = 'resolved')
|
||||
.catch(err => this.updateCheckText = `rejected: ${err.message}`);
|
||||
}
|
||||
}
|
31
aio/content/examples/service-worker-getting-started/src/app/app.module.ts
Executable file
31
aio/content/examples/service-worker-getting-started/src/app/app.module.ts
Executable file
@ -0,0 +1,31 @@
|
||||
import { BrowserModule } from '@angular/platform-browser';
|
||||
import { NgModule } from '@angular/core';
|
||||
import { AppComponent } from './app.component';
|
||||
|
||||
// #docregion sw-import
|
||||
import { ServiceWorkerModule } from '@angular/service-worker';
|
||||
import { environment } from '../environments/environment';
|
||||
// #enddocregion sw-import
|
||||
|
||||
import { CheckForUpdateService } from './check-for-update.service';
|
||||
import { LogUpdateService } from './log-update.service';
|
||||
import { PromptUpdateService } from './prompt-update.service';
|
||||
|
||||
// #docregion sw-module
|
||||
@NgModule({
|
||||
declarations: [
|
||||
AppComponent
|
||||
],
|
||||
imports: [
|
||||
BrowserModule,
|
||||
ServiceWorkerModule.register('/ngsw-worker.js', {enabled: environment.production})
|
||||
],
|
||||
providers: [
|
||||
CheckForUpdateService,
|
||||
LogUpdateService,
|
||||
PromptUpdateService,
|
||||
],
|
||||
bootstrap: [AppComponent]
|
||||
})
|
||||
export class AppModule { }
|
||||
// #enddocregion sw-module
|
@ -0,0 +1,15 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { SwUpdate } from '@angular/service-worker';
|
||||
|
||||
|
||||
// #docregion sw-check-update
|
||||
import { interval } from 'rxjs/observable/interval';
|
||||
|
||||
@Injectable()
|
||||
export class CheckForUpdateService {
|
||||
|
||||
constructor(updates: SwUpdate) {
|
||||
interval(6 * 60 * 60).subscribe(() => updates.checkForUpdate());
|
||||
}
|
||||
}
|
||||
// #enddocregion sw-check-update
|
@ -0,0 +1,19 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { SwUpdate } from '@angular/service-worker';
|
||||
|
||||
// #docregion sw-update
|
||||
@Injectable()
|
||||
export class LogUpdateService {
|
||||
|
||||
constructor(updates: SwUpdate) {
|
||||
updates.available.subscribe(event => {
|
||||
console.log('current version is', event.current);
|
||||
console.log('available version is', event.available);
|
||||
});
|
||||
updates.activated.subscribe(event => {
|
||||
console.log('old version was', event.previous);
|
||||
console.log('new version is', event.current);
|
||||
});
|
||||
}
|
||||
}
|
||||
// #enddocregion sw-update
|
@ -0,0 +1,20 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { SwUpdate } from '@angular/service-worker';
|
||||
|
||||
function promptUser(event): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
// #docregion sw-activate
|
||||
@Injectable()
|
||||
export class PromptUpdateService {
|
||||
|
||||
constructor(updates: SwUpdate) {
|
||||
updates.available.subscribe(event => {
|
||||
if (promptUser(event)) {
|
||||
updates.activateUpdate().then(() => document.location.reload());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
// #enddocregion sw-activate
|
12
aio/content/examples/service-worker-getting-started/src/index.html
Executable file
12
aio/content/examples/service-worker-getting-started/src/index.html
Executable file
@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>SwExample</title>
|
||||
<base href="/">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<app-root></app-root>
|
||||
</body>
|
||||
</html>
|
12
aio/content/examples/service-worker-getting-started/src/main.ts
Executable file
12
aio/content/examples/service-worker-getting-started/src/main.ts
Executable file
@ -0,0 +1,12 @@
|
||||
import { enableProdMode } from '@angular/core';
|
||||
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
|
||||
|
||||
import { AppModule } from './app/app.module';
|
||||
import { environment } from './environments/environment';
|
||||
|
||||
if (environment.production) {
|
||||
enableProdMode();
|
||||
}
|
||||
|
||||
platformBrowserDynamic().bootstrapModule(AppModule)
|
||||
.catch(err => console.log(err));
|
28
aio/content/examples/service-worker-getting-started/src/ngsw-config.json
Executable file
28
aio/content/examples/service-worker-getting-started/src/ngsw-config.json
Executable file
@ -0,0 +1,28 @@
|
||||
|
||||
{
|
||||
"index": "/index.html",
|
||||
"assetGroups": [{
|
||||
"name": "app",
|
||||
"installMode": "prefetch",
|
||||
"resources": {
|
||||
"files": [
|
||||
"/favicon.ico",
|
||||
"/index.html"
|
||||
],
|
||||
"versionedFiles": [
|
||||
"/*.bundle.css",
|
||||
"/*.bundle.js",
|
||||
"/*.chunk.js"
|
||||
]
|
||||
}
|
||||
}, {
|
||||
"name": "assets",
|
||||
"installMode": "lazy",
|
||||
"updateMode": "prefetch",
|
||||
"resources": {
|
||||
"files": [
|
||||
"/assets/**"
|
||||
]
|
||||
}
|
||||
}]
|
||||
}
|
@ -37,7 +37,7 @@ describe('Structural Directives', function () {
|
||||
expect(paragraph.count()).toEqual(1);
|
||||
});
|
||||
|
||||
it('myUnless should show 3 paragraph (A)s and (B)s at the start', function () {
|
||||
it('appUnless should show 3 paragraph (A)s and (B)s at the start', function () {
|
||||
const paragraph = element.all(by.css('p.unless'));
|
||||
expect(paragraph.count()).toEqual(3);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
@ -45,7 +45,7 @@ describe('Structural Directives', function () {
|
||||
}
|
||||
});
|
||||
|
||||
it('myUnless should show 1 paragraph (B) after toggling condition', function () {
|
||||
it('appUnless should show 1 paragraph (B) after toggling condition', function () {
|
||||
const toggleConditionButton = element.all(by.cssContainingText('button', 'Toggle condition')).get(0);
|
||||
const paragraph = element.all(by.css('p.unless'));
|
||||
|
||||
|
@ -188,7 +188,7 @@
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="myUnless">UnlessDirective</h2>
|
||||
<h2 id="appUnless">UnlessDirective</h2>
|
||||
<p>
|
||||
The condition is currently
|
||||
<span [ngClass]="{ 'a': !condition, 'b': condition, 'unless': true }">{{condition}}</span>.
|
||||
@ -198,31 +198,31 @@
|
||||
Toggle condition to {{condition ? 'false' : 'true'}}
|
||||
</button>
|
||||
</p>
|
||||
<!-- #docregion myUnless-->
|
||||
<!-- #docregion appUnless-->
|
||||
<p *appUnless="condition" class="unless a">
|
||||
(A) This paragraph is displayed because the condition is false.
|
||||
</p>
|
||||
|
||||
<p *appUnless="!condition" class="unless b">
|
||||
(B) Although the condition is true,
|
||||
this paragraph is displayed because myUnless is set to false.
|
||||
this paragraph is displayed because appUnless is set to false.
|
||||
</p>
|
||||
<!-- #enddocregion myUnless-->
|
||||
<!-- #enddocregion appUnless-->
|
||||
|
||||
|
||||
<h4>UnlessDirective with template</h4>
|
||||
|
||||
<!-- #docregion myUnless-1 -->
|
||||
<!-- #docregion appUnless-1 -->
|
||||
<p *appUnless="condition">Show this sentence unless the condition is true.</p>
|
||||
<!-- #enddocregion myUnless-1 -->
|
||||
<!-- #enddocregion appUnless-1 -->
|
||||
|
||||
<p *appUnless="condition" class="code unless">
|
||||
(A) <p *myUnless="condition" class="code unless">
|
||||
(A) <p *appUnless="condition" class="code unless">
|
||||
</p>
|
||||
|
||||
<ng-template [appUnless]="condition">
|
||||
<p class="code unless">
|
||||
(A) <ng-template [myUnless]="condition">
|
||||
(A) <ng-template [appUnless]="condition">
|
||||
</p>
|
||||
</ng-template>
|
||||
|
||||
|
@ -8,7 +8,7 @@ import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
|
||||
* Add the template content to the DOM unless the condition is true.
|
||||
// #enddocregion no-docs
|
||||
*
|
||||
* If the expression assigned to `myUnless` evaluates to a truthy value
|
||||
* If the expression assigned to `appUnless` evaluates to a truthy value
|
||||
* then the templated elements are removed removed from the DOM,
|
||||
* the templated elements are (re)inserted into the DOM.
|
||||
*
|
||||
@ -18,8 +18,8 @@ import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
|
||||
*
|
||||
* ### Syntax
|
||||
*
|
||||
* - `<div *myUnless="condition">...</div>`
|
||||
* - `<ng-template [myUnless]="condition"><div>...</div></ng-template>`
|
||||
* - `<div *appUnless="condition">...</div>`
|
||||
* - `<ng-template [appUnless]="condition"><div>...</div></ng-template>`
|
||||
*
|
||||
// #docregion no-docs
|
||||
*/
|
||||
|
@ -130,7 +130,7 @@ function tests() {
|
||||
it('can get RouterLinks from template', () => {
|
||||
expect(links.length).toBe(3, 'should have 3 links');
|
||||
expect(links[0].linkParams).toBe('/dashboard', '1st link should go to Dashboard');
|
||||
expect(links[1].linkParams).toBe('/heroes', '1st link should go to Heroes');
|
||||
expect(links[1].linkParams).toBe('/heroes', '2nd link should go to Heroes');
|
||||
});
|
||||
|
||||
it('can click Heroes link in template', () => {
|
||||
|
@ -2,7 +2,7 @@
|
||||
|
||||
The Angular Ahead-of-Time (AOT) compiler converts your Angular HTML and TypeScript code into efficient JavaScript code during the build phase _before_ the browser downloads and runs that code.
|
||||
|
||||
This guide explains how to to build with the AOT compiler and how to write Angular metadata that AOT can compile.
|
||||
This guide explains how to build with the AOT compiler using different compiler options and how to write Angular metadata that AOT can compile.
|
||||
|
||||
<div class="l-sub-section">
|
||||
|
||||
@ -77,6 +77,174 @@ AOT compiles HTML templates and components into JavaScript files long before the
|
||||
With no templates to read and no risky client-side HTML or JavaScript evaluation,
|
||||
there are fewer opportunities for injection attacks.
|
||||
|
||||
{@a compiler-options}
|
||||
|
||||
## Angular Compiler Options
|
||||
|
||||
You can control your app compilation by providing template compiler options in the `tsconfig.json` file along with the options supplied to the TypeScript compiler. The template compiler options are specified as members of
|
||||
`"angularCompilerOptions"` object as shown below:
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
...
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"fullTemplateTypeCheck": true,
|
||||
"preserveWhiteSpace": false,
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### *skipMetadataEmit*
|
||||
|
||||
This option tells the compiler not to produce `.metadata.json` files.
|
||||
The option is `false` by default.
|
||||
|
||||
`.metadata.json` files contain infomration needed by the template compiler from a `.ts`
|
||||
file that is not included in the `.d.ts` file produced by the TypeScript compiler. This information contains,
|
||||
for example, the content of annotations (such as a component's template) which TypeScript
|
||||
emits to the `.js` file but not to the `.d.ts` file.
|
||||
|
||||
This option should be set to `true` if using TypeScript's `--outFile` option, as the metadata files
|
||||
are not valid for this style of TypeScript output. It is not recommeded to use `--outFile` with
|
||||
Angular. Use a bundler, such as [webpack](https://webpack.js.org/), instead.
|
||||
|
||||
This option can also be set to `true` when using factory summaries as the factory summaries
|
||||
include a copy of the information that is in the `.metadata.json` file.
|
||||
|
||||
### *strictMetadataEmit*
|
||||
|
||||
This option tells the template compiler to report an error to the `.metadata.json`
|
||||
file if `"skipMetadataEmit"` is `false` . This option is `false` by default. This should only be used when `"skipMetadataEmit"` is `false` and `"skipTemplateCodeGen"` is `true`.
|
||||
|
||||
It is intended to validate the `.metadata.json` files emitted for bundling with an `npm` package. The validation is overly strict and can emit errors for metadata that would never produce an error when used by the template compiler. You can choose to suppress the error emitted by this option for an exported symbol by including `@dynamic` in the comment documenting the symbol.
|
||||
|
||||
It is valid for `.metadata.json` files to contain errors. The template compiler reports these errors
|
||||
if the metadata is used to determine the contents of an annotation. The metadata
|
||||
collector cannot predict the symbols that are designed to use in an annotation, so it will preemptively
|
||||
include error nodes in the metadata for the exported symbols. The template compiler can then use the error
|
||||
nodes to report an error if these symbols are used. If the client of a library intends to use a symbol in an annotation, the template compiler will not normally report
|
||||
this until the client uses the symbol. This option allows detecting these errors during the build phase of
|
||||
the library and is used, for example, in producing Angular libraries themselves.
|
||||
|
||||
### *skipTemplateCodegen*
|
||||
|
||||
This option tells the compiler to suppress emitting `.ngfactory.js` and `.ngstyle.js` files. When set,
|
||||
this turns off most of the template compiler and disables reporting template diagnostics.
|
||||
This option can be used to instruct the
|
||||
template compiler to produce `.metadata.json` files for distribution with an `npm` package while
|
||||
avoiding the production of `.ngfactory.js` and `.ngstyle.js` files that cannot be distributed to
|
||||
`npm`.
|
||||
|
||||
### *strictInjectionParameters*
|
||||
|
||||
When set to `true`, this options tells the compiler to report an error for a parameter supplied
|
||||
whose injection type cannot be determined. When this value option is not provided or is `false`, constructor parameters of classes marked with `@Injectable` whose type cannot be resolved will
|
||||
produce a warning.
|
||||
|
||||
*Note*: It is recommended to change this option explicitly to `true` as this option will default to `true` in the future.
|
||||
|
||||
### *flatModuleOutFile*
|
||||
|
||||
When set to `true`, this option tells the template compiler to generate a flat module
|
||||
index of the given file name and the corresponding flat module metadata. Use this option when creating
|
||||
flat modules that are packaged similarly to `@angular/core` and `@angular/common`. When this option
|
||||
is used, the `package.json` for the library should refer
|
||||
to the generated flat module index instead of the library index file. With this
|
||||
option only one `.metadata.json` file is produced that contains all the metadata necessary
|
||||
for symbols exported from the library index. In the generated `.ngfactory.js` files, the flat
|
||||
module index is used to import symbols that includes both the public API from the library index
|
||||
as well as shrowded internal symbols.
|
||||
|
||||
By default the `.ts` file supplied in the `files` field is assumed to be library index.
|
||||
If more than one `.ts` file is specified, `libraryIndex` is used to select the file to use.
|
||||
If more than one `.ts` file is supplied without a `libraryIndex`, an error is produced. A flat module
|
||||
index `.d.ts` and `.js` will be created with the given `flatModuleOutFile` name in the same
|
||||
location as the library index `.d.ts` file. For example, if a library uses
|
||||
`public_api.ts` file as the library index of the module, the `tsconfig.json` `files` field
|
||||
would be `["public_api.ts"]`. The `flatModuleOutFile` options could then be set to, for
|
||||
example `"index.js"`, which produces `index.d.ts` and `index.metadata.json` files. The
|
||||
library's `package.json`'s `module` field would be `"index.js"` and the `typings` field
|
||||
would be `"index.d.ts"`.
|
||||
|
||||
### *flatModuleId*
|
||||
|
||||
This option specifies the preferred module id to use for importing a flat module.
|
||||
References generated by the template compiler will use this module name when importing symbols
|
||||
from the flat module.
|
||||
This is only meaningful when `flatModuleOutFile` is also supplied. Otherwise the compiler ignores
|
||||
this option.
|
||||
|
||||
### *generateCodeForLibraries*
|
||||
|
||||
This option tells the template compiler to generate factory files (`.ngfactory.js` and `.ngstyle.js`)
|
||||
for `.d.ts` files with a corresponding `.metadata.json` file. This option defaults to
|
||||
`true`. When this option is `false`, factory files are generated only for `.ts` files.
|
||||
|
||||
This option should be set to `false` when using factory summaries.
|
||||
|
||||
### *fullTemplateTypeCheck*
|
||||
|
||||
This option tells the compiler to enable the [binding expression validation](#binding-expresion-validation)
|
||||
phase of the template compiler which uses TypeScript to validate binding expressions.
|
||||
|
||||
This option is `false` by default.
|
||||
|
||||
*Note*: It is recommended to set this to `true` as this option will default to `true` in the future.
|
||||
|
||||
### *annotateForClosureCompiler*
|
||||
|
||||
This option tells the compiler to use [Tsickle](https://github.com/angular/tsickle) to annotate the emitted
|
||||
JavaScript with [JsDoc](http://usejsdoc.org/) comments needed by the
|
||||
[Closure Compiler](https://github.com/google/closure-compiler). This option defaults to `false`.
|
||||
|
||||
### *annotationsAs*
|
||||
|
||||
Use this option to modify how the Angular specific annotations are emitted to improve tree-shaking. Non-Angular
|
||||
annotations and decorators are unnaffected. Default is `static fields`.
|
||||
|
||||
value | description
|
||||
----------------|-------------------------------------------------------------
|
||||
`decorators` | Leave the Decorators in-place. This makes compilation faster. TypeScript will emit calls to the __decorate helper. Use `--emitDecoratorMetadata` for runtime reflection. However, the resulting code will not properly tree-shake.
|
||||
`static fields` | Replace decorators with a static field in the class. Allows advanced tree-shakers like [Closure Compiler](https://github.com/google/closure-compiler) to remove unused classes.
|
||||
|
||||
### *trace*
|
||||
|
||||
This tells the compiler to print extra information while compiling templates.
|
||||
|
||||
### *enableLegacyTemplate*
|
||||
|
||||
The use of `<template>` element was deprecated starting in Angular 4.0 in favor of using
|
||||
`<ng-template>` to avoid colliding with the DOM's element of the same name. Setting this option to
|
||||
`true` enables the use of the deprecated `<template>` element . This option
|
||||
is `false` by default. This option might be required by some third-party Angular libraries.
|
||||
|
||||
### *disableExpressionLowering*
|
||||
|
||||
The Angular template compiler transforms code that is used, or could be used, in an annotation
|
||||
to allow it to be imported from template factory modules. See
|
||||
[metadata rewriting](#metadata-rewriting) for more information.
|
||||
|
||||
Setting this option to `false` disables this rewriting, requiring the rewriting to be
|
||||
done manually.
|
||||
|
||||
### *preserveWhitespaces*
|
||||
|
||||
This option tells the compiler whether to remove blank text nodes from compiled templates.
|
||||
This option is `true` by default.
|
||||
|
||||
*Note*: It is recommended to set this explicitly to `false` as it emits smaller template factory modules and might be set to `false` by default in the future.
|
||||
|
||||
### *allowEmptyCodegenFiles*
|
||||
|
||||
Tells the compiler to generate all the possible generated files even if they are empty. This option is
|
||||
`false` by default. This is an option used by `bazel` build rules and is needed to simplify
|
||||
how `bazel` rules track file dependencies. It is not recommended to use this option outside of the `bazel`
|
||||
rules.
|
||||
|
||||
## Angular Metadata and AOT
|
||||
|
||||
The Angular **AOT compiler** extracts and interprets **metadata** about the parts of the application that Angular is supposed to manage.
|
||||
@ -212,6 +380,7 @@ export function serverFactory() {
|
||||
|
||||
Beginning in version 5, the compiler automatically performs this rewritting while emitting the `.js` file.
|
||||
|
||||
{@a function-calls}
|
||||
### Limited function calls
|
||||
|
||||
The _collector_ can represent a function call or object creation with `new` as long as the syntax is valid. The _collector_ only cares about proper syntax.
|
||||
@ -411,6 +580,7 @@ The Angular [`RouterModule`](api/router/RouterModule) exports two macro static m
|
||||
Review the [source code](https://github.com/angular/angular/blob/master/packages/router/src/router_module.ts#L139 "RouterModule.forRoot source code")
|
||||
for these methods to see how macros can simplify configuration of complex [NgModules](guide/ngmodule).
|
||||
|
||||
{@ metadata-rewriting}
|
||||
### Metadata rewriting
|
||||
|
||||
The compiler treats object literals containing the fields `useClass`, `useValue`, `useFactory`, and `data` specially. The compiler converts the expression initializing one of these fields into an exported variable, which replaces the expression. This process of rewriting these expressions removes all the restrictions on what can be in them because
|
||||
@ -961,7 +1131,155 @@ This error can occur if you use an expression in the `extends` clause of a class
|
||||
Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](https://github.com/angular/angular/pull/17712#discussion_r132025495).
|
||||
|
||||
-->
|
||||
{@a binding-expresion-validation}
|
||||
|
||||
## Phase 3: binding expression validation
|
||||
|
||||
In the validation phase, the Angular template compiler uses the TypeScript compiler to validate the
|
||||
binding expressions in templates. Enable this phase explicity by adding the compiler
|
||||
option `"fullTemplateTypeCheck"` in the `"angularCompilerOptions"` of the project's `tsconfig.json` (see
|
||||
[Angular Compiler Options](#compiler-options)).
|
||||
|
||||
Template validation produces error messages when a type error is detected in a template binding
|
||||
expression, similar to how type errors are reported by the TypeScript compiler against code in a `.ts`
|
||||
file.
|
||||
|
||||
For example, consider the following component:
|
||||
|
||||
```ts
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: '{{person.addresss.street}}'
|
||||
})
|
||||
class MyComponent {
|
||||
person?: Person;
|
||||
}
|
||||
```
|
||||
|
||||
This will produce the following error:
|
||||
|
||||
```
|
||||
my.component.ts.MyComponent.html(1,1): : Property 'addresss' does not exist on type 'Person'. Did you mean 'address'?
|
||||
```
|
||||
|
||||
The file name reported in the error message, `my.component.ts.MyComponent.html`, is a synthetic file
|
||||
generated by the template compiler that holds contents of the `MyComponent` class template.
|
||||
Compiler never writes this file to disk. The line and column numbers are relative to the template string
|
||||
in the `@Component` annotation of the class, `MyComponent` in this case. If a component uses
|
||||
`templateUrl` instead of `template`, the errors are reported in the HTML file refereneced by the
|
||||
`templateUrl` instead of a synthetic file.
|
||||
|
||||
The error location is the beginning of the text node that contains the interpolation expression with
|
||||
the error. If the error is in an attribute binding such as `[value]="person.address.street"`, the error
|
||||
location is the location of the attribute that contains the error.
|
||||
|
||||
The validation uses the TypeScript type checker and the options supplied to the TypeScript compiler to control
|
||||
how detailed the type validation is. For example, if the `strictTypeChecks` is specified, the error ```my.component.ts.MyComponent.html(1,1): : Object is possibly 'undefined'``` is reported as well as the above error message.
|
||||
|
||||
### Type narrowing
|
||||
|
||||
The expression used in an `ngIf` directive is used to narrow type unions in the Angular
|
||||
template compiler, the same way the `if` expression does in TypeScript. For example, to avoid
|
||||
`Object is possibly 'undefined'` error in the template above, modify it to only emit the
|
||||
interpolation if the value of `person` is initialized as shown below:
|
||||
|
||||
```ts
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: '<span *ngIf="person"> {{person.addresss.street}} </span>'
|
||||
})
|
||||
class MyComponent {
|
||||
person?: Person;
|
||||
}
|
||||
```
|
||||
|
||||
Using `*ngIf` allows the TypeScript compiler to infer that the `person` used in the
|
||||
binding expression will never be `undefined`.
|
||||
|
||||
#### Custom `ngIf` like directives
|
||||
|
||||
Directives that behave like `*ngIf` can declare that they want the same treatment by including
|
||||
a static member marker that is a signal to the template compiler to treat them
|
||||
like `*ngIf`. This static member for `*ngIf` is:
|
||||
|
||||
```ts
|
||||
public static ngIfUseIfTypeGuard: void;
|
||||
```
|
||||
|
||||
This declares that the input property `ngIf` of the `NgIf` directive should be treated as a
|
||||
guard to the use of its template, implying that the template will only be instantiated if
|
||||
the `ngIf` input property is true.
|
||||
|
||||
|
||||
### Non-null type assertion operator
|
||||
|
||||
Use the [non-null type assertion operator](guide/template-syntax#non-null-assertion-operator)
|
||||
to suppress the `Object is possibly 'undefined'` error when it is incovienent to use
|
||||
`*ngIf` or when some constraint in the component ensures that the expression is always
|
||||
non-null when the binding expression is interpolated.
|
||||
|
||||
In the following example, the `person` and `address` properties are always set together,
|
||||
implying that `address` is always non-null if `person` is non-null. There is no convenient
|
||||
way to describe this constraint to TypeScript and the template compiler, but the error
|
||||
is suppressed in the example by using `address!.street`.
|
||||
|
||||
```ts
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: '<span *ngIf="person"> {{person.name}} lives on {{address!.street}} </span>'
|
||||
})
|
||||
class MyComponent {
|
||||
person?: Person;
|
||||
address?: Address;
|
||||
|
||||
setData(person: Person, address: Address) {
|
||||
this.person = person;
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The non-null assertion operator should be used sparingly as refactoring of the component
|
||||
might break this constraint.
|
||||
|
||||
In this example it is recommended to include the checking of `address`
|
||||
in the `*ngIf`as shown below:
|
||||
|
||||
```ts
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: '<span *ngIf="person && address"> {{person.name}} lives on {{address.street}} </span>'
|
||||
})
|
||||
class MyComponent {
|
||||
person?: Person;
|
||||
address?: Address;
|
||||
|
||||
setData(person: Person, address: Address) {
|
||||
this.person = person;
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Disabling type checking using `$any()`
|
||||
|
||||
Disable checking of a binding expression by surrounding the expression
|
||||
in a call to the [`$any()` cast pseudo-function](guide/template-syntax).
|
||||
The compiler treats it as a cast to the `any` type just like in TypeScript when a `<any>`
|
||||
or `as any` cast is used.
|
||||
|
||||
In the following example, the error `Property addresss does not exist` is suppressed
|
||||
by casting `person` to the `any` type.
|
||||
|
||||
```ts
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: '{{$any(person).addresss.street}}'
|
||||
})
|
||||
class MyComponent {
|
||||
person?: Person;
|
||||
}
|
||||
```
|
||||
## Summary
|
||||
|
||||
* What the AOT compiler does and why it is important.
|
||||
@ -970,3 +1288,5 @@ Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](
|
||||
* Other restrictions on metadata definition.
|
||||
* Macro-functions and macro-static methods.
|
||||
* Compiler errors related to metadata.
|
||||
* Validation of binding expressions
|
||||
|
||||
|
@ -179,7 +179,7 @@ to a component's `@Component` decorator:
|
||||
<code-tabs>
|
||||
<code-pane title="src/app/hero-app.component.ts (CSS in file)" path="component-styles/src/app/hero-app.component.1.ts"></code-pane>
|
||||
<code-pane title="src/app/hero-app.component.css" path="component-styles/src/app/hero-app.component.1.css"></code-pane>
|
||||
</code-tabs>
|
||||
</code-tabs>
|
||||
|
||||
<div class="alert is-critical">
|
||||
|
||||
@ -245,7 +245,8 @@ See the [CLI documentation](https://github.com/angular/angular-cli/wiki/stories-
|
||||
|
||||
### Non-CSS style files
|
||||
|
||||
You can write style files in [sass](http://sass-lang.com/), [less](http://lesscss.org/), or [stylus](http://stylus-lang.com/) and specify those files in the `styleUrls` metadata, e.g.,
|
||||
If you're building with the CLI,
|
||||
you can write style files in [sass](http://sass-lang.com/), [less](http://lesscss.org/), or [stylus](http://stylus-lang.com/) and specify those files in the `@Component.styleUrls` metadata with the appropriate extensions (`.scss`, `.less`, `.styl`) as in the following example:
|
||||
|
||||
<code-example>
|
||||
@Component({
|
||||
@ -256,10 +257,18 @@ You can write style files in [sass](http://sass-lang.com/), [less](http://lesscs
|
||||
...
|
||||
</code-example>
|
||||
|
||||
The CLI build process runs the corresponding CSS pre-processors.
|
||||
The CLI build process runs the pertinent CSS preprocessor.
|
||||
|
||||
You can also configure the CLI to default to your preferred CSS pre-processer
|
||||
as explained in the [CLI documentation](https://github.com/angular/angular-cli/wiki/stories-css-preprocessors).
|
||||
When generating a component file with `ng generate component`, the CLI emits an empty CSS styles file (`.css`) by default.
|
||||
You can configure the CLI to default to your preferred CSS preprocessor
|
||||
as explained in the [CLI documentation](https://github.com/angular/angular-cli/wiki/stories-css-preprocessors
|
||||
"CSS Preprocessor integration").
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
Style strings added to the `@Component.styles` array _must be written in CSS_ because the CLI cannot apply a preprocessor to inline styles.
|
||||
|
||||
</div>
|
||||
|
||||
{@a view-encapsulation}
|
||||
|
||||
|
@ -371,7 +371,7 @@ and to
|
||||
|
||||
Angular developers may encounter a
|
||||
<a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing" title="Cross-origin resource sharing">
|
||||
<i>cross-origin resource sharing</i></a> error when making a service request (typically a data service request).
|
||||
<i>cross-origin resource sharing</i></a> error when making a service request (typically a data service request)
|
||||
to a server other than the application's own host server.
|
||||
Browsers forbid such requests unless the server permits them explicitly.
|
||||
|
||||
|
@ -273,6 +273,8 @@ has a single `intercept()` method. Here is a simple interceptor which does nothi
|
||||
import {Injectable} from '@angular/core';
|
||||
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
|
||||
|
||||
import {Observable} from 'rxjs/Observable';
|
||||
|
||||
@Injectable()
|
||||
export class NoopInterceptor implements HttpInterceptor {
|
||||
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
||||
@ -297,6 +299,8 @@ Simply declaring the `NoopInterceptor` above doesn't cause your app to use it. Y
|
||||
import {NgModule} from '@angular/core';
|
||||
import {HTTP_INTERCEPTORS} from '@angular/common/http';
|
||||
|
||||
import {NoopInterceptor} from 'noop.interceptor.ts';
|
||||
|
||||
@NgModule({
|
||||
providers: [{
|
||||
provide: HTTP_INTERCEPTORS,
|
||||
@ -547,12 +551,12 @@ In order to prevent collisions in environments where multiple Angular apps share
|
||||
|
||||
### Configuring custom cookie/header names
|
||||
|
||||
If your backend service uses different names for the XSRF token cookie or header, use `HttpClientXsrfModule.withConfig()` to override the defaults.
|
||||
If your backend service uses different names for the XSRF token cookie or header, use `HttpClientXsrfModule.withOptions()` to override the defaults.
|
||||
|
||||
```javascript
|
||||
imports: [
|
||||
HttpClientModule,
|
||||
HttpClientXsrfModule.withConfig({
|
||||
HttpClientXsrfModule.withOptions({
|
||||
cookieName: 'My-Xsrf-Cookie',
|
||||
headerName: 'My-Xsrf-Header',
|
||||
}),
|
||||
|
@ -8,7 +8,6 @@ See the <live-example downloadOnly name="i18n">i18n Example</live-example> for a
|
||||
an AOT-compiled app, translated into French.
|
||||
|
||||
{@a angular-i18n}
|
||||
|
||||
## Angular and i18n
|
||||
|
||||
Angular simplifies the following aspects of internationalization:
|
||||
@ -62,6 +61,23 @@ For more information about Unicode locale identifiers, see the
|
||||
For a complete list of locales supported by Angular, see
|
||||
[the Angular repository](https://github.com/angular/angular/tree/master/packages/common/locales).
|
||||
|
||||
The locale identifiers used by CLDR and Angular are based on [BCP47](http://www.rfc-editor.org/rfc/bcp/bcp47.txt).
|
||||
These specifications change over time; the following table maps previous identifiers to current ones at
|
||||
time of writing:
|
||||
|
||||
| Locale name | Old locale id | New locale id |
|
||||
|-------------------------------|-------------------|---------------|
|
||||
| Indonesian | in | id |
|
||||
| Hebrew | iw | he |
|
||||
| Romanian Moldova | mo | ro-MD |
|
||||
| Norwegian Bokmål | no, no-NO | nb |
|
||||
| Serbian Latin | sh | sr-Latn |
|
||||
| Filipino | tl | fil |
|
||||
| Portuguese Brazil | pt-BR | pt |
|
||||
| Chinese Simplified | zh-cn, zh-Hans-CN | zh-Hans |
|
||||
| Chinese Traditional | zh-tw, zh-Hant-TW | zh-Hant |
|
||||
| Chinese Traditional Hong Kong | zh-hk | zh-Hant-HK |
|
||||
|
||||
|
||||
## i18n pipes
|
||||
|
||||
@ -78,6 +94,14 @@ If you want to import locale data for other languages, you can do it manually:
|
||||
<code-example path="i18n/doc-files/app.locale_data.ts" region="import-locale" title="src/app/app.module.ts" linenums="false">
|
||||
</code-example>
|
||||
|
||||
The first parameter is an object containing the locale data imported from `@angular/common/locales`.
|
||||
By default, the imported locale data is registered with the locale id that is defined in the Angular
|
||||
locale data itself.
|
||||
If you want to register the imported locale data with another locale id, use the second parameter to
|
||||
specify a custom locale id. For example, Angular's locale data defines the locale id for French as
|
||||
"fr". You can use the second parameter to associate the imported French locale data with the custom
|
||||
locale id "fr-FR" instead of "fr".
|
||||
|
||||
The files in `@angular/common/locales` contain most of the locale data that you
|
||||
need, but some advanced formatting options might only be available in the extra dataset that you can
|
||||
import from `@angular/common/locales/extra`. An error message informs you when this is the case.
|
||||
@ -118,7 +142,6 @@ in the target language.
|
||||
You need to build and deploy a separate version of the app for each supported language.
|
||||
|
||||
{@a i18n-attribute}
|
||||
|
||||
### Mark text with the i18n attribute
|
||||
|
||||
The Angular `i18n` attribute marks translatable content. Place it on every element tag whose fixed
|
||||
@ -144,7 +167,6 @@ To mark the greeting for translation, add the `i18n` attribute to the `<h1>` tag
|
||||
|
||||
|
||||
{@a help-translator}
|
||||
|
||||
### Help the translator with a description and meaning
|
||||
|
||||
To translate a text message accurately, the translator may need additional information or context.
|
||||
@ -175,7 +197,6 @@ text messages with different descriptions (not different meanings), then they ar
|
||||
|
||||
|
||||
{@a custom-id}
|
||||
|
||||
### Set a custom id for persistence and maintenance
|
||||
|
||||
The angular i18n extractor tool generates a file with a translation unit entry for each `i18n`
|
||||
@ -250,7 +271,6 @@ the same text, `Bonjour`:
|
||||
|
||||
|
||||
{@a no-element}
|
||||
|
||||
### Translate text without creating an element
|
||||
|
||||
If there is a section of text that you would like to translate, you can wrap it in a `<span>` tag.
|
||||
@ -262,7 +282,6 @@ The `<ng-container>` is transformed into an html comment:
|
||||
</code-example>
|
||||
|
||||
{@a translate-attributes}
|
||||
|
||||
## Add i18n translation attributes
|
||||
|
||||
You also can translate attributes.
|
||||
@ -286,7 +305,6 @@ You also can assign a meaning, description, and id with the `i18n-x="<meaning>|<
|
||||
syntax.
|
||||
|
||||
{@a plural-ICU}
|
||||
|
||||
## Translate singular and plural
|
||||
|
||||
Different languages have different pluralization rules.
|
||||
@ -342,7 +360,6 @@ for two, three, or any other number if the pluralization rules were different. F
|
||||
</div>
|
||||
|
||||
{@a select-ICU}
|
||||
|
||||
## Select among alternative text messages
|
||||
|
||||
If your template needs to display different text messages depending on the value of a variable, you
|
||||
@ -360,7 +377,6 @@ The message maps those values to the appropriate translations:
|
||||
</code-example>
|
||||
|
||||
{@a nesting-ICUS}
|
||||
|
||||
## Nesting plural and select ICU expressions
|
||||
|
||||
You can also nest different ICU expressions together, as shown in this example:
|
||||
@ -369,7 +385,6 @@ You can also nest different ICU expressions together, as shown in this example:
|
||||
</code-example>
|
||||
|
||||
{@a ng-xi18n}
|
||||
|
||||
## Create a translation source file with _ng xi18n_
|
||||
|
||||
Use the `ng xi18n` command provided by the CLI to extract the text messages marked with `i18n` into
|
||||
@ -394,7 +409,6 @@ package, or you can manually use the CLI Webpack plugin `ExtractI18nPlugin` from
|
||||
</div>
|
||||
|
||||
{@a other-formats}
|
||||
|
||||
### Other translation formats
|
||||
|
||||
Angular i18n tooling supports three translation formats:
|
||||
@ -422,7 +436,6 @@ The sample in this guide uses the default XLIFF 1.2 format.
|
||||
</div>
|
||||
|
||||
{@a ng-xi18n-options}
|
||||
|
||||
### Other options
|
||||
|
||||
You can specify the output path used by the CLI to extract your translation source file with
|
||||
@ -456,7 +469,6 @@ file. This information is not used by Angular, but external translation tools ma
|
||||
|
||||
|
||||
{@a translate}
|
||||
|
||||
## Translate text messages
|
||||
|
||||
The `ng xi18n` command generates a translation source file named `messages.xlf` in the project `src`
|
||||
@ -466,7 +478,6 @@ The next step is to translate this source file into the specific language
|
||||
translation files. The example in this guide creates a French translation file.
|
||||
|
||||
{@a localization-folder}
|
||||
|
||||
### Create a localization folder
|
||||
|
||||
Most apps are translated into more than one other language. For this reason, it is standard practice
|
||||
@ -500,7 +511,6 @@ For this example:
|
||||
If you were translating to other languages, you would repeat these steps for each target language.
|
||||
|
||||
{@a translate-text-nodes}
|
||||
|
||||
### Translate text nodes
|
||||
|
||||
In a large translation project, you would send the `messages.fr.xlf` file to a French translator who
|
||||
@ -544,7 +554,6 @@ This sample file is easy to translate without a special editor or knowledge of F
|
||||
</div>
|
||||
|
||||
{@a translate-plural-select}
|
||||
|
||||
## Translate plural and select expressions
|
||||
|
||||
_Plural_ and _select_ ICU expressions are extracted separately, so they require special attention
|
||||
@ -555,7 +564,6 @@ elsewhere in the source template. In this example, you know the translation unit
|
||||
must be just below the translation unit for the logo.
|
||||
|
||||
{@a translate-plural}
|
||||
|
||||
### Translate _plural_
|
||||
|
||||
To translate a `plural`, translate its ICU format match values:
|
||||
@ -567,7 +575,6 @@ You can add or remove plural cases, with each language having its own cardinalit
|
||||
[CLDR plural rules](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html).)
|
||||
|
||||
{@a translate-select}
|
||||
|
||||
### Translate _select_
|
||||
|
||||
Below is the content of our example `select` ICU expression in the component template:
|
||||
@ -598,7 +605,6 @@ Here they are together, after translation:
|
||||
</code-example>
|
||||
|
||||
{@a translate-nested}
|
||||
|
||||
### Translate a nested expression
|
||||
|
||||
A nested expression is similar to the previous examples. As in the previous example, there are
|
||||
@ -621,7 +627,6 @@ The entire template translation is complete. The next section describes how to l
|
||||
into the app.
|
||||
|
||||
{@a app-pre-translation}
|
||||
|
||||
### The app and its translation file
|
||||
|
||||
The sample app and its translation file are now as follows:
|
||||
@ -640,7 +645,6 @@ The sample app and its translation file are now as follows:
|
||||
</code-tabs>
|
||||
|
||||
{@a merge}
|
||||
|
||||
## Merge the completed translation file into the app
|
||||
|
||||
To merge the translated text into component templates, compile the app with the completed
|
||||
@ -656,12 +660,11 @@ format that Angular understands, such as `.xtb`.
|
||||
How you provide this information depends upon whether you compile with
|
||||
the JIT compiler or the AOT compiler.
|
||||
|
||||
* With [AOT](guide/i18n#aot), you pass the information as a CLI parameter.
|
||||
* With [JIT](guide/i18n#jit), you provide the information at bootstrap time.
|
||||
* With [AOT](guide/i18n#merge-aot), you pass the information as a CLI parameter.
|
||||
* With [JIT](guide/i18n#merge-jit), you provide the information at bootstrap time.
|
||||
|
||||
|
||||
{@a aot}
|
||||
|
||||
{@a merge-aot}
|
||||
### Merge with the AOT compiler
|
||||
|
||||
The AOT (_Ahead-of-Time_) compiler is part of a build process that produces a small, fast,
|
||||
@ -685,8 +688,7 @@ guide:
|
||||
ng serve --aot --i18nFile=src/locale/messages.fr.xlf --i18nFormat=xlf --locale=fr
|
||||
</code-example>
|
||||
|
||||
{@a jit}
|
||||
|
||||
{@a merge-jit}
|
||||
### Merge with the JIT compiler
|
||||
|
||||
The JIT compiler compiles the app in the browser as the app loads.
|
||||
@ -713,3 +715,29 @@ Then provide the `LOCALE_ID` in the main module:
|
||||
|
||||
<code-example path="i18n/doc-files/app.module.ts" title="src/app/app.module.ts" linenums="false">
|
||||
</code-example>
|
||||
|
||||
|
||||
{@a missing-translation}
|
||||
### Report missing translations
|
||||
By default, when a translation is missing, the build succeeds but generates a warning such as
|
||||
`Missing translation for message "foo"`. You can configure the level of warning that is generated by
|
||||
the Angular compiler:
|
||||
|
||||
* Error: throw an error. If you are using AOT compilation, the build will fail. If you are using JIT
|
||||
compilation, the app will fail to load.
|
||||
* Warning (default): show a 'Missing translation' warning in the console or shell.
|
||||
* Ignore: do nothing.
|
||||
|
||||
If you use the AOT compiler, specify the warning level by using the CLI parameter
|
||||
`--missingTranslation`. The example below shows how to set the warning level to error:
|
||||
|
||||
<code-example language="sh" class="code-shell">
|
||||
ng serve --aot --missingTranslation=error
|
||||
</code-example>
|
||||
|
||||
If you use the JIT compiler, specify the warning level in the compiler config at bootstrap by adding
|
||||
the 'MissingTranslationStrategy' property. The example below shows how to set the warning level to
|
||||
error:
|
||||
|
||||
<code-example path="i18n/doc-files/main.3.ts" title="src/main.ts">
|
||||
</code-example>
|
||||
|
@ -140,7 +140,7 @@ calls the lifecycle hook methods in the following sequence at specific moments:
|
||||
</tr>
|
||||
<tr style='vertical-align:top'>
|
||||
<td>
|
||||
<code>ngOnDestroy</code>
|
||||
<code>ngOnDestroy()</code>
|
||||
</td>
|
||||
<td>
|
||||
|
||||
|
54
aio/content/guide/service-worker-communications.md
Normal file
54
aio/content/guide/service-worker-communications.md
Normal file
@ -0,0 +1,54 @@
|
||||
# Service Worker Communication
|
||||
|
||||
Importing `ServiceWorkerModule` into your `AppModule` doesn't just register the service worker, it also provides a few services you can use to interact with the service worker and control the caching of your app.
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
A basic understanding of the following:
|
||||
* [Getting Started with Service Workers](guide/service-worker-getting-started).
|
||||
|
||||
<hr />
|
||||
|
||||
|
||||
## `SwUpdate` service
|
||||
|
||||
The `SwUpdate` service gives you access to events that indicate when the service worker has discovered an available update for your app or when it has activated such an update—meaning it is now serving content from that update to your app.
|
||||
|
||||
The `SwUpdate` service supports four separate operations:
|
||||
* Getting notified of *available* updates. These are new versions of the app to be loaded if the page is refreshed.
|
||||
* Getting notified of update *activation*. This is when the service worker starts serving a new version of the app immediately.
|
||||
* Asking the service worker to check the server for new updates.
|
||||
* Asking the service worker to activate the latest version of the app for the current tab.
|
||||
|
||||
### Available and activated updates
|
||||
|
||||
The two update events, `available` and `activated`, are `Observable` properties of `SwUpdate`:
|
||||
|
||||
<code-example path="service-worker-getting-started/src/app/log-update.service.ts" linenums="false" title="log-update.service.ts" region="sw-update"> </code-example>
|
||||
|
||||
|
||||
You can use these events to notify the user of a pending update or to refresh their pages when the code they are running is out of date.
|
||||
|
||||
### Checking for updates
|
||||
|
||||
It's possible to ask the service worker to check if any updates have been deployed to the server. You might choose to do this if you have a site that changes frequently or want updates to happen on a schedule.
|
||||
|
||||
Do this with the `checkForUpdate()` method:
|
||||
|
||||
<code-example path="service-worker-getting-started/src/app/check-for-update.service.ts" linenums="false" title="check-for-update.service.ts" region="sw-check-update"> </code-example>
|
||||
|
||||
|
||||
This method returns a `Promise` which indicates that the update check has completed successfully, though it does not indicate whether an update was discovered as a result of the check. Even if one is found, the service worker must still successfully download the changed files, which can fail. If successful, the `available` event will indicate availability of a new version of the app.
|
||||
|
||||
### Forcing update activation
|
||||
|
||||
If the current tab needs to be updated to the latest app version immediately, it can ask to do so with the `activateUpdate()` method:
|
||||
|
||||
<code-example path="service-worker-getting-started/src/app/prompt-update.service.ts" linenums="false" title="prompt-update.service.ts" region="sw-activate"> </code-example>
|
||||
|
||||
Doing this could break lazy-loading into currently running apps, especially if the lazy-loaded chunks use filenames with hashes, which change every version.
|
||||
|
||||
## More on Angular service workers
|
||||
|
||||
You may also be interested in the following:
|
||||
* [Service Worker in Production](guide/service-worker-devops).
|
169
aio/content/guide/service-worker-config.md
Normal file
169
aio/content/guide/service-worker-config.md
Normal file
@ -0,0 +1,169 @@
|
||||
{@a glob}
|
||||
|
||||
# Service Worker Configuration
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
A basic understanding of the following:
|
||||
* [Service Worker in Production](guide/service-worker-devops).
|
||||
|
||||
<hr />
|
||||
|
||||
The `src/ngsw-config.json` configuration file specifies which files and data URLs the Angular
|
||||
service worker should cache and how it should update the cached files and data. The
|
||||
CLI processes the configuration file during `ng build --prod`. Manually, you can process
|
||||
it with the `ngsw-config` tool:
|
||||
|
||||
```sh
|
||||
ngsw-config dist src/ngsw-config.json /base/href
|
||||
```
|
||||
|
||||
The configuration file uses the JSON format. All file paths must begin with `/`, which is the deployment directory—usually `dist` in CLI projects.
|
||||
|
||||
Patterns use a limited glob format:
|
||||
|
||||
* `**` matches 0 or more path segments.
|
||||
* `*` matches exactly one path segment or filename segment.
|
||||
* The `!` prefix marks the pattern as being negative, meaning that only files that don't match the pattern will be included.
|
||||
|
||||
Example patterns:
|
||||
|
||||
* `/**/*.html` specifies all HTML files.
|
||||
* `/*.html` specifies only HTML files in the root.
|
||||
* `!/**/*.map` exclude all sourcemaps.
|
||||
|
||||
Each section of the configuration file is described below.
|
||||
|
||||
## `appData`
|
||||
|
||||
This section enables you to pass any data you want that describes this particular version of the app.
|
||||
The `SwUpdate` service includes that data in the update notifications. Many apps use this section to provide additional information for the display of UI popups, notifying users of the available update.
|
||||
|
||||
## `index`
|
||||
|
||||
Specifies the file that serves as the index page to satisfy navigation requests. Usually this is `/index.html`.
|
||||
|
||||
## `assetGroups`
|
||||
|
||||
*Assets* are resources that are part of the app version that update along with the app. They can include resources loaded from the page's origin as well as third-party resources loaded from CDNs and other external URLs. As not all such external URLs may be known at build time, URL patterns can be matched.
|
||||
|
||||
This field contains an array of asset groups, each of which defines a set of asset resources and the policy by which they are cached.
|
||||
|
||||
```json
|
||||
{
|
||||
"assetGroups": [{
|
||||
...
|
||||
}, {
|
||||
...
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
Each asset group specifies both a group of resources and a policy that governs them. This policy determines when the resources are fetched and what happens when changes are detected.
|
||||
|
||||
Asset groups follow the Typescript interface shown here:
|
||||
|
||||
```typescript
|
||||
interface AssetGroup {
|
||||
name: string;
|
||||
installMode?: 'prefetch' | 'lazy';
|
||||
updateMode?: 'prefetch' | 'lazy';
|
||||
resources: {
|
||||
files?: string[];
|
||||
versionedFiles?: string[];
|
||||
urls?: string[];
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### `name`
|
||||
|
||||
A `name` is mandatory. It identifies this particular group of assets between versions of the configuration.
|
||||
|
||||
### `installMode`
|
||||
|
||||
The `installMode` determines how these resources are initially cached. The `installMode` can be either of two values:
|
||||
|
||||
* `prefetch` tells the Angular service worker to fetch every single listed resource while it's caching the current version of the app. This is bandwidth-intensive but ensures resources are available whenever they're requested, even if the browser is currently offline.
|
||||
|
||||
* `lazy` does not cache any of the resources up front. Instead, the Angular service worker only caches resources for which it receives requests. This is an on-demand caching mode. Resources that are never requested will not be cached. This is useful for things like images at different resolutions, so the service worker only caches the correct assets for the particular screen and orientation.
|
||||
|
||||
### `updateMode`
|
||||
|
||||
For resources already in the cache, the `updateMode` determines the caching behavior when a new version of the app is discovered. Any resources in the group that have changed since the previous version are updated in accordance with `updateMode`.
|
||||
|
||||
* `prefetch` tells the service worker to download and cache the changed resources immediately.
|
||||
|
||||
* `lazy` tells the service worker to not cache those resources. Instead, it treats them as unrequested and waits until they're requested again before updating them. An `updateMode` of `lazy` is only valid if the `installMode` is also `lazy`.
|
||||
|
||||
### `resources`
|
||||
|
||||
This section describes the resources to cache, broken up into three groups.
|
||||
|
||||
* `files` lists patterns that match files in the distribution directory. These can be single files or glob-like patterns that match a number of files.
|
||||
|
||||
* `versionedFiles` is like `files` but should be used for build artifacts that already include a hash in the filename, which is used for cache busting. The Angular service worker can optimize some aspects of its operation if it can assume file contents are immutable.
|
||||
|
||||
* `urls` includes both URLs and URL patterns that will be matched at runtime. These resources are not fetched directly and do not have content hashes, but they will be cached according to their HTTP headers. This is most useful for CDNs such as the Google Fonts service.
|
||||
|
||||
## `dataGroups`
|
||||
|
||||
Unlike asset resources, data requests are not versioned along with the app. They're cached according to manually-configured policies that are more useful for situations such as API requests and other data dependencies.
|
||||
|
||||
Data groups follow this Typescript interface:
|
||||
|
||||
```typescript
|
||||
export interface DataGroup {
|
||||
name: string;
|
||||
urls: string[];
|
||||
version?: number;
|
||||
cacheConfig: {
|
||||
maxSize: number;
|
||||
maxAge: string;
|
||||
timeout?: string;
|
||||
strategy?: 'freshness' | 'performance';
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### `name`
|
||||
Similar to `assetGroups`, every data group has a `name` which uniquely identifies it.
|
||||
|
||||
### `urls`
|
||||
A list of URL patterns. URLs that match these patterns will be cached according to this data group's policy.
|
||||
|
||||
### `version`
|
||||
Occasionally APIs change formats in a way that is not backward-compatible. A new version of the app may not be compatible with the old API format and thus may not be compatible with existing cached resources from that API.
|
||||
|
||||
`version` provides a mechanism to indicate that the resources being cached have been updated in a backwards-incompatible way, and that the old cache entries—those from previous versions—should be discarded.
|
||||
|
||||
`version` is an integer field and defaults to `0`.
|
||||
|
||||
### `cacheConfig`
|
||||
This section defines the policy by which matching requests will be cached.
|
||||
|
||||
#### `maxSize`
|
||||
(required) The maximum number of entries, or responses, in the cache. Open-ended caches can grow in unbounded ways and eventually exceed storage quotas, calling for eviction.
|
||||
|
||||
#### `maxAge`
|
||||
(required) The `maxAge` parameter indicates how long responses are allowed to remain in the cache before being considered invalid and evicted. `maxAge` is a duration string, using the following unit suffixes:
|
||||
|
||||
* `d`: days
|
||||
* `h`: hours
|
||||
* `m`: minutes
|
||||
* `s`: seconds
|
||||
* `u`: milliseconds
|
||||
|
||||
For example, the string `3d12h` will cache content for up to three and a half days.
|
||||
|
||||
#### `timeout`
|
||||
This duration string specifies the network timeout. The network timeout is how long the Angular service worker will wait for the network to respond before using a cached response, if configured to do so.
|
||||
|
||||
#### `strategy`
|
||||
|
||||
The Angular service worker can use either of two caching strategies for data resources.
|
||||
|
||||
* `performance`, the default, optimizes for responses that are as fast as possible. If a resource exists in the cache, the cached version is used. This allows for some staleness, depending on the `maxAge`, in exchange for better performance. This is suitable for resources that don't change often; for example, user avatar images.
|
||||
|
||||
* `freshness` optimizes for currency of data, preferentially fetching requested data from the network. Only if the network times out, according to `timeout`, does the request fall back to the cache. This is useful for resources that change frequently; for example, account balances.
|
||||
|
311
aio/content/guide/service-worker-devops.md
Normal file
311
aio/content/guide/service-worker-devops.md
Normal file
@ -0,0 +1,311 @@
|
||||
# Service Worker in Production
|
||||
|
||||
This page is a reference for deploying and supporting production apps that use the Angular service worker. It explains how the Angular service worker fits into the larger production environment, the service worker's behavior under various conditions, and available recourses and fail-safes.
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
A basic understanding of the following:
|
||||
* [Service Worker Communication](guide/service-worker-communications).
|
||||
|
||||
<hr />
|
||||
|
||||
## Service worker and caching of app resources
|
||||
|
||||
Conceptually, you can imagine the Angular service worker as a forward cache or a CDN edge that is installed in the end user's web browser. The service worker's job is to satisfy requests made by the Angular app for resources or data from a local cache, without needing to wait for the network. Like any cache, it has rules for how content is expired and updated.
|
||||
|
||||
{@a versions}
|
||||
|
||||
### App versions
|
||||
|
||||
In the context of an Angular service worker, a "version" is a collection of resources that represent a specific build of the Angular app. Whenever a new build of the app is deployed, the service worker treats that build as a new version of the app. This is true even if only a single file is updated. At any given time, the service worker may have multiple versions of the app in its cache and it may be serving them simultaneously. For more information, see the [App tabs](guide/service-worker-devops#tabs) section below.
|
||||
|
||||
To preserve app integrity, the Angular service worker groups all files into a version together. The files grouped into a version usually include HTML, JS, and CSS files. Grouping of these files is essential for integrity because HTML, JS, and CSS files frequently refer to each other and depend on specific content. For example, an `index.html` file might have a `<script>` tag that references `bundle.js` and it might attempt to call a function `startApp()` from within that script. Any time this version of `index.html` is served, the corresponding `bundle.js` must be served with it. For example, assume that the `startApp()` function is renamed to `runApp()` in both files. In this scenario, it is not valid to serve the old `index.html`, which calls `startApp()`, along with the new bundle, which defines `runApp()`.
|
||||
|
||||
This file integrity is especially important when lazy loading modules.
|
||||
A JS bundle may reference many lazy chunks, and the filenames of the
|
||||
lazy chunks are unique to the particular build of the app. If a running
|
||||
app at version `X` attempts to load a lazy chunk, but the server has
|
||||
updated to version `X + 1` already, the lazy loading operation will fail.
|
||||
|
||||
The version identifier of the app is determined by the contents of all
|
||||
resources, and it changes if any of them change. In practice, the version
|
||||
is determined by the contents of the `ngsw.json` file, which includes
|
||||
hashes for all known content. If any of the cached files change, the file's
|
||||
hash will change in `ngsw.json`, causing the Angular service worker to
|
||||
treat the active set of files as a new version.
|
||||
|
||||
With the versioning behavior of the Angular service worker, an application
|
||||
server can ensure that the Angular app always has a consistent set of files.
|
||||
|
||||
#### Update checks
|
||||
|
||||
Every time the user opens or refreshes the application, the Angular service worker
|
||||
checks for updates to the app by looking for updates to the `ngsw.json` manifest. If
|
||||
an update is found, it is downloaded and cached automatically, and will be served
|
||||
the next time the application is loaded.
|
||||
|
||||
### Resource integrity
|
||||
|
||||
One of the potential side effects of long caching is inadvertently
|
||||
caching an invalid resource. In a normal HTTP cache, a hard refresh
|
||||
or cache expiration limits the negative effects of caching an invalid
|
||||
file. A service worker ignores such constraints and effectively long
|
||||
caches the entire app. Consequently, it is essential that the service worker
|
||||
get the correct content.
|
||||
|
||||
To ensure resource integrity, the Angular service worker validates
|
||||
the hashes of all resources for which it has a hash. Typically for
|
||||
a CLI app, this is everything in the `dist` directory covered by
|
||||
the user's `src/ngsw-config.json` configuration.
|
||||
|
||||
If a particular file fails validation, the Angular service worker
|
||||
attempts to re-fetch the content using a "cache-busting" URL
|
||||
parameter to eliminate the effects of browser or intermediate
|
||||
caching. If that content also fails validation, the service worker
|
||||
considers the entire version of the app to be invalid and it stops
|
||||
serving the app. If necessary, the service worker enters a safe mode
|
||||
where requests fall back on the network, opting not to use its cache
|
||||
if the risk of serving invalid, broken, or outdated content is high.
|
||||
|
||||
Hash mismatches can occur for a variety of reasons:
|
||||
|
||||
* Caching layers in between the origin server and the end user could serve stale content.
|
||||
* A non-atomic deployment could result in the Angular service worker having visibility of partially updated content.
|
||||
* Errors during the build process could result in updated resources without `ngsw.json` being updated. The reverse could also happen resulting in an updated `ngsw.json` without updated resources.
|
||||
|
||||
#### Unhashed content
|
||||
|
||||
The only resources that have hashes in the `ngsw.json`
|
||||
manifest are resources that were present in the `dist`
|
||||
directory at the time the manifest was built. Other
|
||||
resources, especially those loaded from CDNs, have
|
||||
content that is unknown at build time or are updated
|
||||
more frequently than the app is deployed.
|
||||
|
||||
If the Angular service worker does not have a hash to validate
|
||||
a given resource, it still caches its contents but it honors
|
||||
the HTTP caching headers by using a policy of "stale while
|
||||
revalidate." That is, when HTTP caching headers for a cached
|
||||
resource indicate that the resource has expired, the Angular
|
||||
service worker continues to serve the content and it attempts
|
||||
to refresh the resource in the background. This way, broken
|
||||
unhashed resources do not remain in the cache beyond their
|
||||
configured lifetimes.
|
||||
|
||||
{@a tabs}
|
||||
|
||||
### App tabs
|
||||
|
||||
It can be problematic for an app if the version of resources
|
||||
it's receiving changes suddenly or without warning. See the
|
||||
[Versions](guide/service-worker-devops#versions) section above
|
||||
for a description of such issues.
|
||||
|
||||
The Angular service worker provides a guarantee: a running app
|
||||
will continue to run the same version of the app. If another
|
||||
instance of the app is opened in a new web browser tab, then
|
||||
the most current version of the app is served. As a result,
|
||||
that new tab can be running a different version of the app
|
||||
than the original tab.
|
||||
|
||||
It's important to note that this guarantee is **stronger**
|
||||
than that provided by the normal web deployment model. Without
|
||||
a service worker, there is no guarantee that code lazily loaded
|
||||
later in a running app is from the same version as the initial
|
||||
code for the app.
|
||||
|
||||
There are a few limited reasons why the Angular service worker
|
||||
might change the version of a running app. Some of them are
|
||||
error conditions:
|
||||
|
||||
* The current version becomes invalid due to a failed hash.
|
||||
* An unrelated error causes the service worker to enter safe mode; that is, temporary deactivation.
|
||||
|
||||
The Angular service worker is aware of which versions are in
|
||||
use at any given moment and it cleans up versions when
|
||||
no tab is using them.
|
||||
|
||||
Other reasons the Angular service worker might change the version
|
||||
of a running app are normal events:
|
||||
|
||||
* The page is reloaded/refreshed.
|
||||
* The page requests an update be immediately activated via the `SwUpdate` service.
|
||||
|
||||
### Service worker updates
|
||||
|
||||
The Angular service worker is a small script that runs in web browsers.
|
||||
From time to time, the service worker will be updated with bug
|
||||
fixes and feature improvements.
|
||||
|
||||
The Angular service worker is downloaded when the app is first opened
|
||||
and when the app is accessed after a period of inactivity. If the
|
||||
service worker has changed, the service worker will be updated in the background.
|
||||
|
||||
Most updates to the Angular service worker are transparent to the
|
||||
app—the old caches are still valid and content is still served
|
||||
normally. However, occasionally a bugfix or feature in the Angular
|
||||
service worker requires the invalidation of old caches. In this case,
|
||||
the app will be refreshed transparently from the network.
|
||||
|
||||
|
||||
## Debugging the Angular service worker
|
||||
|
||||
Occasionally, it may be necessary to examine the Angular service
|
||||
worker in a running state to investigate issues or to ensure that
|
||||
it is operating as designed. Browsers provide built-in tools for
|
||||
debugging service workers and the Angular service worker itself
|
||||
includes useful debugging features.
|
||||
|
||||
### Locating and analyzing debugging information
|
||||
|
||||
The Angular service worker exposes debugging information under
|
||||
the `ngsw/` virtual directory. Currently, the single exposed URL
|
||||
is `ngsw/state`. Here is an example of this debug page's contents:
|
||||
|
||||
```
|
||||
NGSW Debug Info:
|
||||
|
||||
Driver state: NORMAL ((nominal))
|
||||
Latest manifest hash: eea7f5f464f90789b621170af5a569d6be077e5c
|
||||
Last update check: never
|
||||
|
||||
=== Version eea7f5f464f90789b621170af5a569d6be077e5c ===
|
||||
|
||||
Clients: 7b79a015-69af-4d3d-9ae6-95ba90c79486, 5bc08295-aaf2-42f3-a4cc-9e4ef9100f65
|
||||
|
||||
=== Idle Task Queue ===
|
||||
Last update tick: 1s496u
|
||||
Last update run: never
|
||||
Task queue:
|
||||
* init post-load (update, cleanup)
|
||||
|
||||
Debug log:
|
||||
```
|
||||
|
||||
#### Driver state
|
||||
|
||||
The first line indicates the driver state:
|
||||
|
||||
```
|
||||
Driver state: NORMAL ((nominal))
|
||||
```
|
||||
|
||||
`NORMAL` indicates that the service worker is operating normally and is not in a degraded state.
|
||||
|
||||
There are two possible degraded states:
|
||||
|
||||
* `EXISTING_CLIENTS_ONLY`: the service worker does not have a
|
||||
clean copy of the latest known version of the app. Older cached
|
||||
versions are safe to use, so existing tabs continue to run from
|
||||
cache, but new loads of the app will be served from the network.
|
||||
|
||||
* `SAFE_MODE`: the service worker cannot guarantee the safety of
|
||||
using cached data. Either an unexpected error occurred or all
|
||||
cached versions are invalid. All traffic will be served from the
|
||||
network, running as little service worker code as possible.
|
||||
|
||||
In both cases, the parenthetical annotation provides the
|
||||
error that caused the service worker to enter the degraded state.
|
||||
|
||||
|
||||
#### Latest manifest hash
|
||||
|
||||
```
|
||||
Latest manifest hash: eea7f5f464f90789b621170af5a569d6be077e5c
|
||||
```
|
||||
|
||||
This is the SHA1 hash of the most up-to-date version of the app that the service worker knows about.
|
||||
|
||||
|
||||
#### Last update check
|
||||
|
||||
```
|
||||
Last update check: never
|
||||
```
|
||||
|
||||
This indicates the last time the service worker checked for a new version, or update, of the app. `never` indicates that the service worker has never checked for an update.
|
||||
|
||||
In this example debug file, the update check is currently scheduled, as explained the next section.
|
||||
|
||||
#### Version
|
||||
|
||||
```
|
||||
=== Version eea7f5f464f90789b621170af5a569d6be077e5c ===
|
||||
|
||||
Clients: 7b79a015-69af-4d3d-9ae6-95ba90c79486, 5bc08295-aaf2-42f3-a4cc-9e4ef9100f65
|
||||
```
|
||||
|
||||
In this example, the service worker has one version of the app cached and
|
||||
being used to serve two different tabs. Note that this version hash
|
||||
is the "latest manifest hash" listed above. Both clients are on the
|
||||
latest version. Each client is listed by its ID from the `Clients`
|
||||
API in the browser.
|
||||
|
||||
|
||||
#### Idle task queue
|
||||
|
||||
```
|
||||
=== Idle Task Queue ===
|
||||
Last update tick: 1s496u
|
||||
Last update run: never
|
||||
Task queue:
|
||||
* init post-load (update, cleanup)
|
||||
```
|
||||
|
||||
The Idle Task Queue is the queue of all pending tasks that happen
|
||||
in the background in the service worker. If there are any tasks
|
||||
in the queue, they are listed with a description. In this example,
|
||||
the service worker has one such task scheduled, a post-initialization
|
||||
operation involving an update check and cleanup of stale caches.
|
||||
|
||||
The last update tick/run counters give the time since specific
|
||||
events happened related to the idle queue. The "Last update run"
|
||||
counter shows the last time idle tasks were actually executed.
|
||||
"Last update tick" shows the time since the last event after
|
||||
which the queue might be processed.
|
||||
|
||||
|
||||
#### Debug log
|
||||
|
||||
```
|
||||
Debug log:
|
||||
```
|
||||
|
||||
Errors that occur within the service worker will be logged here.
|
||||
|
||||
|
||||
### Developer Tools
|
||||
|
||||
Browsers such as Chrome provide developer tools for interacting
|
||||
with service workers. Such tools can be powerful when used properly,
|
||||
but there are a few things to keep in mind.
|
||||
|
||||
* When using developer tools, the service worker is kept running
|
||||
in the background and never restarts. This can cause behavior with Dev
|
||||
Tools open to differ from behavior a user might experience.
|
||||
|
||||
* If you look in the Cache Storage viewer, the cache is frequently
|
||||
out of date. Right click the Cache Storage title and refresh the caches.
|
||||
|
||||
Stopping and starting the service worker in the Service Worker
|
||||
pane triggers a check for updates.
|
||||
|
||||
## Fail-safe
|
||||
|
||||
Like any complex system, bugs or broken configurations can cause
|
||||
the Angular service worker to act in unforeseen ways. While its
|
||||
design attempts to minimize the impact of such problems, the
|
||||
Angular service worker contains a failsafe mechanism in case
|
||||
an administrator ever needs to deactivate the service worker quickly.
|
||||
|
||||
To deactivate the service worker, remove or rename the
|
||||
`ngsw-config.json` file. When the service worker's request
|
||||
for `ngsw.json` returns a `404`, then the service worker
|
||||
removes all of its caches and de-registers itself,
|
||||
essentially self-destructing.
|
||||
|
||||
## More on Angular service workers
|
||||
|
||||
You may also be interested in the following:
|
||||
* [Service Worker Configuration](guide/service-worker-config).
|
||||
|
203
aio/content/guide/service-worker-getting-started.md
Normal file
203
aio/content/guide/service-worker-getting-started.md
Normal file
@ -0,0 +1,203 @@
|
||||
# Getting Started with Service Workers
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
A basic understanding of the following:
|
||||
* [Introduction to Angular service workers](guide/service-worker-intro).
|
||||
|
||||
<hr />
|
||||
|
||||
|
||||
Beginning in Angular 5.0.0, you can easily enable Angular service worker support in any CLI project. This document explains how to enable Angular service worker support in new and existing projects. It then uses a simple example to show you a service worker in action, demonstrating loading and basic caching.
|
||||
|
||||
## Adding a service worker to a new application
|
||||
|
||||
If you're generating a new CLI project, you can use the CLI to set up the Angular service worker as part of creating the project. To do so, add the `--service-worker` flag to the `ng new` command:
|
||||
|
||||
```sh
|
||||
ng new my-project --service-worker
|
||||
```
|
||||
|
||||
The `--service-worker` flag takes care of configuring your app to
|
||||
use service workers by adding the `service-worker` package along
|
||||
with setting up the necessary files to support service workers.
|
||||
For information on the details, see the following section
|
||||
which covers the process in detail as it shows you how to add a
|
||||
service worker manually to an existing app.
|
||||
|
||||
|
||||
|
||||
## Adding a service worker to an existing app
|
||||
|
||||
To add a service worker to an existing app:
|
||||
|
||||
1. Add the service worker package.
|
||||
2. Enable service worker build support in the CLI.
|
||||
3. Import and register the service worker.
|
||||
4. Create the service worker configuration file, which specifies the caching behaviors and other settings.
|
||||
5. Build the project.
|
||||
|
||||
### Step 1: Add the service worker package
|
||||
|
||||
Add the package `@angular/service-worker`, using the yarn utility as shown here:
|
||||
|
||||
```sh
|
||||
yarn add @angular/service-worker
|
||||
```
|
||||
|
||||
### Step 2: Enable service worker build support in the CLI
|
||||
|
||||
To enable the Angular service worker, the CLI must generate an Angular service worker manifest at build time. To cause the CLI to generate the manifest for an existing project, set the `serviceWorker` flag to `true` in the project's `.angular-cli.json` file as shown here:
|
||||
|
||||
```sh
|
||||
ng set apps.0.serviceWorker=true
|
||||
```
|
||||
|
||||
### Step 3: Import and register the service worker
|
||||
|
||||
To import and register the Angular service worker:
|
||||
|
||||
At the top of the root module, `src/app/app.module.ts`, import `ServiceWorkerModule` and `environment`.
|
||||
|
||||
<code-example path="service-worker-getting-started/src/app/app.module.ts" linenums="false" title="src/app/app.module.ts" region="sw-import"> </code-example>
|
||||
|
||||
|
||||
Add `ServiceWorkerModule` to the `@NgModule` `imports` array. Use the `register()` helper to take care of registering the service worker, taking care to disable the service worker when not running in production mode.
|
||||
|
||||
<code-example path="service-worker-getting-started/src/app/app.module.ts" linenums="false" title="src/app/app.module.ts" region="sw-module"> </code-example>
|
||||
|
||||
The file `ngsw-worker.js` is the name of the prebuilt service worker script, which the CLI copies into `dist/` to deploy along with your server.
|
||||
|
||||
### Step 4: Create the configuration file, `ngsw-config.json`
|
||||
|
||||
The Angular CLI needs a service worker configuration file, called `ngsw-config.json`. The configuration file controls how the service worker caches files and data
|
||||
resources.
|
||||
|
||||
You can begin with the boilerplate version from the CLI, which configures sensible defaults for most applications.
|
||||
|
||||
Alternately, save the following as `src/ngsw-config.json`:
|
||||
|
||||
<code-example path="service-worker-getting-started/src/ngsw-config.json" linenums="false" title="src/ngsw-config.json"> </code-example>
|
||||
|
||||
### Step 5: Build the project
|
||||
|
||||
Finally, build the project:
|
||||
|
||||
```sh
|
||||
ng build --prod
|
||||
```
|
||||
|
||||
The CLI project is now set up to use the Angular service worker.
|
||||
|
||||
|
||||
## Service worker in action: a tour
|
||||
|
||||
This section demonstrates a service worker in action,
|
||||
using an example application.
|
||||
|
||||
### Serving with `http-server`
|
||||
|
||||
Because `ng serve` does not work with service workers, you must use a seperate HTTP server to test your project locally. You can use any HTTP server. The example below uses the [http-server](https://www.npmjs.com/package/http-server) package from npm. To reduce the possibility of conflicts, test on a dedicated port.
|
||||
|
||||
To serve with `http-server`, change to the directory containing your web files and start the web server:
|
||||
|
||||
```sh
|
||||
cd dist
|
||||
http-server -p 8080
|
||||
```
|
||||
|
||||
### Initial load
|
||||
|
||||
With the server running, you can point your browser at http://localhost:8080/. Your application should load normally.
|
||||
|
||||
**Tip:** When testing Angular service workers, it's a good idea to use an incognito or private window in your browser to ensure the service worker doesn't end up reading from a previous leftover state, which can cause unexpected behavior.
|
||||
|
||||
### Simulating a network issue
|
||||
|
||||
To simulate a network issue, disable network interaction for your application. In Chrome:
|
||||
|
||||
1. Select **Tools** > **Developer Tools** (from the Chrome menu located at the top right corner).
|
||||
2. Go to the **Network tab**.
|
||||
3. Check the **Offline box**.
|
||||
|
||||
<figure>
|
||||
<img src="generated/images/guide/service-worker/offline-checkbox.png" alt="The offline checkbox in the Network tab is checked">
|
||||
</figure>
|
||||
|
||||
Now the app has no access to network interaction.
|
||||
|
||||
For applications that do not use the Angular service worker, refreshing now would display Chrome's Internet disconnected page that says "There is no Internet connection".
|
||||
|
||||
With the addition of an Angular service worker, the application behavior changes. On a refresh, the page loads normally.
|
||||
|
||||
If you look at the Network tab, you can verify that the service worker is active.
|
||||
|
||||
<figure>
|
||||
<img src="generated/images/guide/service-worker/sw-active.png" alt="Requests are marked as from ServiceWorker">
|
||||
</figure>
|
||||
|
||||
Notice that under the "Size" column, the requests state is `(from ServiceWorker)`. This means that the resources are not being loaded from the network. Instead, they are being loaded from the service worker's cache.
|
||||
|
||||
|
||||
### What's being cached?
|
||||
|
||||
Notice that all of the files the browser needs to render this application are cached. The `ngsw-config.json` boilerplate configuration is set up to cache the specific resources used by the CLI:
|
||||
|
||||
* `index.html`.
|
||||
* `favicon.ico`.
|
||||
* Build artifacts (JS and CSS bundles).
|
||||
* Anything under `assets`.
|
||||
|
||||
### Making changes to your application
|
||||
|
||||
Now that you've seen how service workers cache your application, the
|
||||
next step is understanding how updates work.
|
||||
|
||||
1. If you're testing in an incognito window, open a second blank tab. This will keep the incognito and the cache state alive during your test.
|
||||
|
||||
2. Close the application tab, but not the window. This should also close the Developer Tools.
|
||||
|
||||
3. Shut down `http-server`.
|
||||
|
||||
4. Next, make a change to the application, and watch the service worker install the update.
|
||||
|
||||
5. Open `src/app/app.component.html` for editing.
|
||||
|
||||
6. Change the text `Welcome to {{title}}!` to `Bienvenue à {{title}}!`.
|
||||
|
||||
7. Build and run the server again:
|
||||
|
||||
```sh
|
||||
ng build --prod
|
||||
cd dist
|
||||
http-server -p 8080
|
||||
```
|
||||
|
||||
### Updating your application in the browser
|
||||
|
||||
Now look at how the browser and service worker handle the updated application.
|
||||
|
||||
1. Open http://localhost:8080 again in the same window. What happens?
|
||||
|
||||
<figure>
|
||||
<img src="generated/images/guide/service-worker/welcome-msg-en.png" alt="It still says Welcome to Service Workers!">
|
||||
</figure>
|
||||
|
||||
What went wrong? Nothing, actually. The Angular service worker is doing its job and serving the version of the application that it has **installed**, even though there is an update available. In the interest of speed, the service worker doesn't wait to check for updates before it serves the application that it has cached.
|
||||
|
||||
If you look at the `http-server` logs, you can see the service worker requesting `/ngsw.json`. This is how the service worker checks for updates.
|
||||
|
||||
2. Refresh the page.
|
||||
|
||||
<figure>
|
||||
<img src="generated/images/guide/service-worker/welcome-msg-fr.png" alt="The text has changed to say Bienvenue à app!">
|
||||
</figure>
|
||||
|
||||
The service worker installed the updated version of your app *in the background*, and the next time the page is loaded or reloaded, the service worker switches to the latest version.
|
||||
|
||||
<hr />
|
||||
|
||||
## More on Angular service workers
|
||||
|
||||
You may also be interested in the following:
|
||||
* [Communicating with service workers](guide/service-worker-communications).
|
53
aio/content/guide/service-worker-intro.md
Normal file
53
aio/content/guide/service-worker-intro.md
Normal file
@ -0,0 +1,53 @@
|
||||
# Angular Service Worker Introduction
|
||||
|
||||
Service workers augment the traditional web deployment model and empower applications to deliver a user experience with the reliability and performance on par with natively-installed code.
|
||||
|
||||
At its simplest, a service worker is a script that runs in the web browser and manages caching for an application.
|
||||
|
||||
Service workers function as a network proxy. They intercept all outgoing HTTP requests made by the application and can choose how to respond to them. For example, they can query a local cache and deliver a cached response if one is available. Proxying isn't limited to requests made through programmatic APIs, such as `fetch`; it also includes resources referenced in HTML and even the initial request to `index.html`. Service worker-based caching is thus completely programmable and doesn't rely on server-specified caching headers.
|
||||
|
||||
Unlike the other scripts that make up an application, such as the Angular app bundle, the service worker is preserved after the user closes the tab. The next time that browser loads the application, the service worker loads first, and can intercept every request for resources to load the application. If the service worker is designed to do so, it can *completely satisfy the loading of the application, without the need for the network*.
|
||||
|
||||
Even across a fast reliable network, round-trip delays can introduce significant latency when loading the application. Using a service worker to reduce dependency on the network can significantly improve the user experience.
|
||||
|
||||
|
||||
## Service workers in Angular
|
||||
|
||||
Angular applications, as single-page applications, are in a prime position to benefit from the advantages of service workers. Starting with version 5.0.0, Angular ships with a service worker implementation. Angular developers can take advantage of this service worker and benefit from the increased reliability and performance it provides, without needing to code against low-level APIs.
|
||||
|
||||
Angular's service worker is designed to optimize the end user experience of using an application over a slow or unreliable network connection, while also minimizing the risks of serving outdated content.
|
||||
|
||||
The Angular service worker's behavior follows that design goal:
|
||||
|
||||
* Caching an application is like installing a native application. The application is cached as one unit, and all files update together.
|
||||
* A running application continues to run with the same version of all files. It does not suddenly start receiving cached files from a newer version, which are likely incompatible.
|
||||
* When users refresh the application, they see the latest fully cached version. New tabs load the latest cached code.
|
||||
* Updates happen in the background, relatively quickly after changes are published. The previous version of the application is served until an update is installed and ready.
|
||||
* The service worker conserves bandwidth when possible. Resources are only downloaded if they've changed.
|
||||
|
||||
To support these behaviors, the Angular service worker loads a *manifest* file from the server. The manifest describes the resources to cache and includes hashes of every file's contents. When an update to the application is deployed, the contents of the manifest change, informing the service worker that a new version of the application should be downloaded and cached. This manifest is generated from a user-provided configuration file called `ngsw-config.json`, by using a build tool such as the Angular CLI.
|
||||
|
||||
Installing the Angular service worker is as simple as including an `NgModule`. In addition to registering the Angular service worker with the browser, this also makes a few services available for injection which interact with the service worker and can be used to control it. For example, an application can ask to be notified when a new update becomes available, or an application can ask the service worker to check the server for available updates.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
To use Angular service workers, you must have the following Angular and CLI versions:
|
||||
|
||||
* Angular 5.0.0 or later.
|
||||
* Angular CLI 1.6.0 or later.
|
||||
|
||||
Your application must run in a web browser that supports service workers. Currently, the latest versions of Chrome and Firefox are supported. To learn about other browsers that are service worker ready, see the [Can I Use](http://caniuse.com/#feat=serviceworkers) page.
|
||||
|
||||
## Related resources
|
||||
|
||||
For more information about service workers in general, see [Service Workers: an Introduction](https://developers.google.com/web/fundamentals/primers/service-workers/).
|
||||
|
||||
For more information about browser support, see the [browser support](https://developers.google.com/web/fundamentals/primers/service-workers/#browser_support) section of [Service Workers: an Introduction](https://developers.google.com/web/fundamentals/primers/service-workers/), Jake Archibald's [Is Serviceworker ready?](https://jakearchibald.github.io/isserviceworkerready/), and
|
||||
[Can I Use](http://caniuse.com/#feat=serviceworkers).
|
||||
|
||||
The remainder of this Angular documentation specifically addresses the Angular implementation of service workers.
|
||||
|
||||
## More on Angular service workers
|
||||
|
||||
You may also be interested in the following:
|
||||
* [Getting Started with service workers](guide/service-worker-getting-started).
|
@ -625,7 +625,7 @@ that does the opposite of `NgIf`.
|
||||
`UnlessDirective` displays the content when the condition is ***false***.
|
||||
|
||||
|
||||
<code-example path="structural-directives/src/app/app.component.html" linenums="false" title="src/app/app.component.html (myUnless-1)" region="myUnless-1">
|
||||
<code-example path="structural-directives/src/app/app.component.html" linenums="false" title="src/app/app.component.html (appUnless-1)" region="appUnless-1">
|
||||
|
||||
</code-example>
|
||||
|
||||
@ -650,14 +650,14 @@ Here's how you might begin:
|
||||
|
||||
|
||||
|
||||
The directive's _selector_ is typically the directive's **attribute name** in square brackets, `[myUnless]`.
|
||||
The directive's _selector_ is typically the directive's **attribute name** in square brackets, `[appUnless]`.
|
||||
The brackets define a CSS
|
||||
<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors" title="MDN: Attribute selectors">attribute selector</a>.
|
||||
|
||||
The directive _attribute name_ should be spelled in _lowerCamelCase_ and begin with a prefix.
|
||||
Don't use `ng`. That prefix belongs to Angular.
|
||||
Pick something short that fits you or your company.
|
||||
In this example, the prefix is `my`.
|
||||
In this example, the prefix is `app`.
|
||||
|
||||
|
||||
The directive _class_ name ends in `Directive` per the [style guide](guide/styleguide#02-03 "Angular Style Guide").
|
||||
@ -685,10 +685,10 @@ You inject both in the directive constructor as private variables of the class.
|
||||
|
||||
|
||||
|
||||
### The _myUnless_ property
|
||||
### The _appUnless_ property
|
||||
|
||||
The directive consumer expects to bind a true/false condition to `[myUnless]`.
|
||||
That means the directive needs a `myUnless` property, decorated with `@Input`
|
||||
The directive consumer expects to bind a true/false condition to `[appUnless]`.
|
||||
That means the directive needs an `appUnless` property, decorated with `@Input`
|
||||
|
||||
|
||||
<div class="l-sub-section">
|
||||
@ -708,8 +708,8 @@ Read about `@Input` in the [_Template Syntax_](guide/template-syntax#inputs-outp
|
||||
|
||||
|
||||
|
||||
Angular sets the `myUnless` property whenever the value of the condition changes.
|
||||
Because the `myUnless` property does work, it needs a setter.
|
||||
Angular sets the `appUnless` property whenever the value of the condition changes.
|
||||
Because the `appUnless` property does work, it needs a setter.
|
||||
|
||||
* If the condition is falsy and the view hasn't been created previously,
|
||||
tell the _view container_ to create the _embedded view_ from the template.
|
||||
@ -717,7 +717,7 @@ tell the _view container_ to create the _embedded view_ from the template.
|
||||
* If the condition is truthy and the view is currently displayed,
|
||||
clear the container which also destroys the view.
|
||||
|
||||
Nobody reads the `myUnless` property so it doesn't need a getter.
|
||||
Nobody reads the `appUnless` property so it doesn't need a getter.
|
||||
|
||||
The completed directive code looks like this:
|
||||
|
||||
@ -733,7 +733,7 @@ Add this directive to the `declarations` array of the AppModule.
|
||||
Then create some HTML to try it.
|
||||
|
||||
|
||||
<code-example path="structural-directives/src/app/app.component.html" linenums="false" title="src/app/app.component.html (myUnless)" region="myUnless">
|
||||
<code-example path="structural-directives/src/app/app.component.html" linenums="false" title="src/app/app.component.html (appUnless)" region="appUnless">
|
||||
|
||||
</code-example>
|
||||
|
||||
|
BIN
aio/content/images/guide/service-worker/offline-checkbox.png
Normal file
BIN
aio/content/images/guide/service-worker/offline-checkbox.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 31 KiB |
BIN
aio/content/images/guide/service-worker/sw-active.png
Normal file
BIN
aio/content/images/guide/service-worker/sw-active.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 44 KiB |
BIN
aio/content/images/guide/service-worker/welcome-msg-en.png
Normal file
BIN
aio/content/images/guide/service-worker/welcome-msg-en.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 30 KiB |
BIN
aio/content/images/guide/service-worker/welcome-msg-fr.png
Normal file
BIN
aio/content/images/guide/service-worker/welcome-msg-fr.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 28 KiB |
@ -2,7 +2,7 @@
|
||||
@description
|
||||
The MIT License
|
||||
|
||||
Copyright (c) 2014-2017 Google, Inc.
|
||||
Copyright (c) 2014-2018 Google, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
@ -639,6 +639,13 @@
|
||||
"rev": true,
|
||||
"title": "Formation JavaScript (French)",
|
||||
"url": "https://formationjavascript.com/formation-angular/"
|
||||
},
|
||||
"wao": {
|
||||
"desc": "Onsite Angular Training delivered by We Are One Sàrl in Switzerland",
|
||||
"logo": "https://weareone.ch/wordpress/wao-content/uploads/2014/12/logo_200_2x.png",
|
||||
"rev": true,
|
||||
"title": "We Are One Sàrl",
|
||||
"url": "https://weareone.ch/courses/angular/"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -350,6 +350,37 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "Service Workers",
|
||||
"tooltip": "Angular service workers: Controlling caching of application resources.",
|
||||
"children": [
|
||||
{
|
||||
"url": "guide/service-worker-intro",
|
||||
"title": "Introduction",
|
||||
"tooltip": "Angular's implementation of service workers improves user experience with slow or unreliable network connectivity."
|
||||
},
|
||||
{
|
||||
"url": "guide/service-worker-getting-started",
|
||||
"title": "Getting Started",
|
||||
"tooltip": "Enabling the service worker in a CLI project and observing behavior in the browser."
|
||||
},
|
||||
{
|
||||
"url": "guide/service-worker-communications",
|
||||
"title": "Service Worker Communication",
|
||||
"tooltip": "Services that enable you to interact with an Angular service worker."
|
||||
},
|
||||
{
|
||||
"url": "guide/service-worker-devops",
|
||||
"title": "Service Worker in Production",
|
||||
"tooltip": "Running applications with service workers, managing application update, debugging, and killing applications."
|
||||
},
|
||||
{
|
||||
"url": "guide/service-worker-config",
|
||||
"title": "Service Worker Configuration",
|
||||
"tooltip": "Configuring service worker caching behavior."
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
"title": "Upgrading",
|
||||
|
@ -121,7 +121,7 @@ Import the `HeroService` instead.
|
||||
<code-example path="toh-pt4/src/app/heroes/heroes.component.ts" title="src/app/heroes/heroes.component.ts (import HeroService)" region="hero-service-import">
|
||||
</code-example>
|
||||
|
||||
Replace the the definition of the `heroes` property with a simple declaration.
|
||||
Replace the definition of the `heroes` property with a simple declaration.
|
||||
|
||||
<code-example path="toh-pt4/src/app/heroes/heroes.component.ts" region="heroes">
|
||||
</code-example>
|
||||
|
@ -275,6 +275,7 @@ The `HeroDetailsComponent` displays details of a selected hero.
|
||||
At the moment the `HeroDetailsComponent` is only visible at the bottom of the `HeroesComponent`
|
||||
|
||||
The user should be able to get to these details in three ways.
|
||||
|
||||
1. By clicking a hero in the dashboard.
|
||||
1. By clicking a hero in the heroes list.
|
||||
1. By pasting a "deep link" URL into the browser address bar that identifies the hero to display.
|
||||
|
@ -7,15 +7,16 @@ describe('site App', function() {
|
||||
beforeEach(() => {
|
||||
SitePage.setWindowWidth(1050); // Make the window wide enough to show the SideNav side-by-side.
|
||||
page = new SitePage();
|
||||
page.navigateTo();
|
||||
});
|
||||
|
||||
it('should show features text after clicking "Features"', () => {
|
||||
page.navigateTo('');
|
||||
page.getTopMenuLink('features').click();
|
||||
expect(page.getDocViewerText()).toMatch(/Progressive web apps/i);
|
||||
});
|
||||
|
||||
it('should set appropriate window titles', () => {
|
||||
page.navigateTo('');
|
||||
expect(browser.getTitle()).toBe('Angular');
|
||||
|
||||
page.getTopMenuLink('features').click();
|
||||
@ -25,9 +26,9 @@ describe('site App', function() {
|
||||
expect(browser.getTitle()).toBe('Angular');
|
||||
});
|
||||
|
||||
it('should show the tutorial index page at `/tutorial/` after jitterbugging through features', () => {
|
||||
it('should show the tutorial index page at `/tutorial` after jitterbugging through features', () => {
|
||||
// check that we can navigate directly to the tutorial page
|
||||
page.navigateTo('tutorial/');
|
||||
page.navigateTo('tutorial');
|
||||
expect(page.getDocViewerText()).toMatch(/Tutorial: Tour of Heroes/i);
|
||||
|
||||
// navigate to a different page
|
||||
@ -52,24 +53,26 @@ describe('site App', function() {
|
||||
describe('scrolling to the top', () => {
|
||||
it('should scroll to the top when navigating to another page', () => {
|
||||
page.navigateTo('guide/security');
|
||||
browser.sleep(1000); // Wait for initial async scroll-to-top after `onDocRendered`.
|
||||
|
||||
page.scrollToBottom();
|
||||
page.getScrollTop().then(scrollTop => expect(scrollTop).toBeGreaterThan(0));
|
||||
expect(page.getScrollTop()).toBeGreaterThan(0);
|
||||
|
||||
page.navigateTo('api');
|
||||
page.getScrollTop().then(scrollTop => expect(scrollTop).toBe(0));
|
||||
page.getNavItem(/api/i).click();
|
||||
browser.waitForAngular();
|
||||
expect(page.locationPath()).toBe('/api');
|
||||
expect(page.getScrollTop()).toBe(0);
|
||||
});
|
||||
|
||||
it('should scroll to the top when navigating to the same page', () => {
|
||||
page.navigateTo('guide/security');
|
||||
browser.sleep(1000); // Wait for initial async scroll-to-top after `onDocRendered`.
|
||||
|
||||
page.scrollToBottom();
|
||||
page.getScrollTop().then(scrollTop => expect(scrollTop).toBeGreaterThan(0));
|
||||
expect(page.getScrollTop()).toBeGreaterThan(0);
|
||||
|
||||
page.navigateTo('guide/security');
|
||||
page.getScrollTop().then(scrollTop => expect(scrollTop).toBe(0));
|
||||
page.getNavItem(/security/i).click();
|
||||
browser.waitForAngular();
|
||||
expect(page.locationPath()).toBe('/guide/security');
|
||||
expect(page.getScrollTop()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@ -87,42 +90,50 @@ describe('site App', function() {
|
||||
page.navigateTo('api');
|
||||
page.locationPath()
|
||||
.then(p => path = p)
|
||||
.then(() => page.ga().then(calls => {
|
||||
.then(() => page.ga())
|
||||
.then(calls => {
|
||||
// The last call (length-1) will be the `send` command
|
||||
// The second to last call (length-2) will be the command to `set` the page url
|
||||
expect(calls[calls.length - 2]).toEqual(['set', 'page', path]);
|
||||
done();
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
it('should call ga with new URL on navigation', done => {
|
||||
let path: string;
|
||||
page.navigateTo('');
|
||||
page.getTopMenuLink('features').click();
|
||||
page.locationPath()
|
||||
.then(p => path = p)
|
||||
.then(() => page.ga().then(calls => {
|
||||
.then(() => page.ga())
|
||||
.then(calls => {
|
||||
// The last call (length-1) will be the `send` command
|
||||
// The second to last call (length-2) will be the command to `set` the page url
|
||||
expect(calls[calls.length - 2]).toEqual(['set', 'page', path]);
|
||||
done();
|
||||
}));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('search', () => {
|
||||
it('should find pages when searching by a partial word in the title', () => {
|
||||
page.navigateTo('');
|
||||
|
||||
page.enterSearch('ngCont');
|
||||
expect(page.getSearchResults().map(link => link.getText())).toContain('NgControl');
|
||||
expect(page.getSearchResults()).toContain('NgControl');
|
||||
|
||||
page.enterSearch('accessor');
|
||||
expect(page.getSearchResults().map(link => link.getText())).toContain('ControlValueAccessor');
|
||||
expect(page.getSearchResults()).toContain('ControlValueAccessor');
|
||||
});
|
||||
});
|
||||
|
||||
describe('404 page', () => {
|
||||
it('should search the index for words found in the url', () => {
|
||||
page.navigateTo('http/router');
|
||||
expect(page.getSearchResults().map(link => link.getText())).toContain('Http');
|
||||
expect(page.getSearchResults().map(link => link.getText())).toContain('Router');
|
||||
const results = page.getSearchResults();
|
||||
|
||||
expect(results).toContain('Http');
|
||||
expect(results).toContain('Router');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@ -28,8 +28,11 @@ export class SitePage {
|
||||
ga() { return browser.executeScript('return window["ga"].q') as promise.Promise<any[][]>; }
|
||||
locationPath() { return browser.executeScript('return document.location.pathname') as promise.Promise<string>; }
|
||||
|
||||
navigateTo(pageUrl = '') {
|
||||
return browser.get('/' + pageUrl);
|
||||
navigateTo(pageUrl) {
|
||||
// Navigate to the page, disable animations, and wait for Angular.
|
||||
return browser.get('/' + pageUrl)
|
||||
.then(() => browser.executeScript('document.body.classList.add(\'no-animations\')'))
|
||||
.then(() => browser.waitForAngular());
|
||||
}
|
||||
|
||||
getDocViewerText() {
|
||||
@ -59,6 +62,6 @@ export class SitePage {
|
||||
getSearchResults() {
|
||||
const results = element.all(by.css('.search-results li'));
|
||||
browser.wait(ExpectedConditions.presenceOf(results.first()), 8000);
|
||||
return results;
|
||||
return results.map(link => link.getText());
|
||||
}
|
||||
}
|
||||
|
@ -40,7 +40,12 @@
|
||||
{"type": 301, "source": "/docs/ts/latest/:any*", "destination": "/:any*"},
|
||||
|
||||
// aot-compiler.md and metadata.md combined into aot-compiler.md - issue #19510
|
||||
{"type": 301, "source": "/guide/metadata", "destination": "/guide/aot-compiler"}
|
||||
{"type": 301, "source": "/guide/metadata", "destination": "/guide/aot-compiler"},
|
||||
|
||||
// service-worker-getstart.md, service-worker-comm.md, service-worker-configref.md
|
||||
{"type": 301, "source": "/guide/service-worker-getstart", "destination": "/guide/service-worker-getting-started"},
|
||||
{"type": 301, "source": "/guide/service-worker-comm", "destination": "/guide/service-worker-communications"},
|
||||
{"type": 301, "source": "/guide/service-worker-configref", "destination": "/guide/service-worker-config"}
|
||||
],
|
||||
"rewrites": [
|
||||
{
|
||||
|
@ -56,39 +56,39 @@
|
||||
"~~check-env": "node scripts/check-environment",
|
||||
"~~build": "ng build --target=production --environment=stable -sm",
|
||||
"post~~build": "yarn sw-manifest && yarn sw-copy",
|
||||
"~~update-webdriver": "webdriver-manager update --standalone false --gecko false"
|
||||
"~~update-webdriver": "webdriver-manager update --standalone false --gecko false $CHROMEDRIVER_VERSION_ARG"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.9.5 <7.0.0",
|
||||
"node": ">=8.9.1 <9.0.0",
|
||||
"yarn": ">=1.0.2 <2.0.0"
|
||||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@angular/animations": "^5.0.0",
|
||||
"@angular/cdk": "^2.0.0-beta.12",
|
||||
"@angular/common": "^5.0.0",
|
||||
"@angular/compiler": "^5.0.0",
|
||||
"@angular/core": "^5.0.0-rc.9",
|
||||
"@angular/forms": "^5.0.0",
|
||||
"@angular/http": "^5.0.0",
|
||||
"@angular/material": "^2.0.0-beta.12",
|
||||
"@angular/platform-browser": "^5.0.0",
|
||||
"@angular/platform-browser-dynamic": "^5.0.0",
|
||||
"@angular/platform-server": "^5.0.0",
|
||||
"@angular/router": "^5.0.0",
|
||||
"@angular/animations": "^5.1.0-beta.2",
|
||||
"@angular/cdk": "^5.0.0-rc.1",
|
||||
"@angular/common": "^5.1.0-beta.2",
|
||||
"@angular/compiler": "^5.1.0-beta.2",
|
||||
"@angular/core": "^5.1.0-beta.2",
|
||||
"@angular/forms": "^5.1.0-beta.2",
|
||||
"@angular/http": "^5.1.0-beta.2",
|
||||
"@angular/material": "^5.0.0-rc.1",
|
||||
"@angular/platform-browser": "^5.1.0-beta.2",
|
||||
"@angular/platform-browser-dynamic": "^5.1.0-beta.2",
|
||||
"@angular/platform-server": "^5.1.0-beta.2",
|
||||
"@angular/router": "^5.1.0-beta.2",
|
||||
"@angular/service-worker": "^1.0.0-beta.16",
|
||||
"classlist.js": "^1.1.20150312",
|
||||
"core-js": "^2.4.1",
|
||||
"jasmine": "^2.6.0",
|
||||
"ng-pwa-tools": "^0.0.10",
|
||||
"rxjs": "^5.5.0",
|
||||
"rxjs": "^5.5.2",
|
||||
"tslib": "^1.7.1",
|
||||
"web-animations-js": "^2.2.5",
|
||||
"zone.js": "0.8.16"
|
||||
"zone.js": "^0.8.19"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/cli": "^1.5.0",
|
||||
"@angular/compiler-cli": "^5.0.0",
|
||||
"@angular/cli": "^1.6.0-rc.0",
|
||||
"@angular/compiler-cli": "^5.1.0-beta.2",
|
||||
"@types/jasmine": "^2.5.52",
|
||||
"@types/jasminewd2": "^2.0.3",
|
||||
"@types/node": "~6.0.60",
|
||||
@ -113,7 +113,7 @@
|
||||
"http-server": "^0.9.0",
|
||||
"ignore": "^3.3.3",
|
||||
"image-size": "^0.5.1",
|
||||
"jasmine-core": "^2.6.4",
|
||||
"jasmine-core": "^2.8.0",
|
||||
"jasmine-spec-reporter": "^4.1.0",
|
||||
"jsdom": "^9.12.0",
|
||||
"karma": "^1.7.0",
|
||||
|
@ -1,3 +1,21 @@
|
||||
{
|
||||
"aio":{"master":{"change":"application","gzip7":{"inline":925,"main":119519,"polyfills":11863},"gzip9":{"inline":925,"main":119301,"polyfills":11861},"uncompressed":{"inline":1533,"main":486493,"polyfills":37068}}}
|
||||
}
|
||||
"aio": {
|
||||
"master": {
|
||||
"gzip7": {
|
||||
"inline": 941,
|
||||
"main": 116124,
|
||||
"polyfills": 13102
|
||||
},
|
||||
"gzip9": {
|
||||
"inline": 941,
|
||||
"main": 115954,
|
||||
"polyfills": 13104
|
||||
},
|
||||
"uncompressed": {
|
||||
"inline": 1558,
|
||||
"main": 456432,
|
||||
"polyfills": 40684
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
#!/bin/bash
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -eu -o pipefail
|
||||
|
||||
|
@ -4,12 +4,14 @@
|
||||
<mat-progress-bar mode="indeterminate" color="warn"></mat-progress-bar>
|
||||
</div>
|
||||
|
||||
<mat-toolbar color="primary" class="app-toolbar">
|
||||
<button class="hamburger" [class.starting]="isStarting" mat-button
|
||||
(click)="sidenav.toggle()" title="Docs menu">
|
||||
<mat-icon [ngClass]="{'sidenav-open': !isSideBySide }" svgIcon="menu"></mat-icon>
|
||||
<mat-toolbar color="primary" class="app-toolbar" [class.transitioning]="isTransitioning">
|
||||
<button mat-button class="hamburger" (click)="sidenav.toggle()" title="Docs menu">
|
||||
<mat-icon svgIcon="menu"></mat-icon>
|
||||
</button>
|
||||
<a class="nav-link home" href="/"><img src="{{ homeImageUrl }}" title="Home" alt="Home"></a>
|
||||
<a class="nav-link home" href="/" [ngSwitch]="isSideBySide">
|
||||
<img *ngSwitchCase="true" src="assets/images/logos/angular/logo-nav@2x.png" width="150" height="40" title="Home" alt="Home">
|
||||
<img *ngSwitchDefault src="assets/images/logos/angular/shield-large.svg" width="37" height="40" title="Home" alt="Home">
|
||||
</a>
|
||||
<aio-top-menu *ngIf="isSideBySide" [nodes]="topMenuNodes"></aio-top-menu>
|
||||
<aio-search-box class="search-container" #searchBox (onSearch)="doSearch($event)" (onFocus)="doSearch($event)"></aio-search-box>
|
||||
</mat-toolbar>
|
||||
@ -17,7 +19,7 @@
|
||||
|
||||
<mat-sidenav-container class="sidenav-container" [class.starting]="isStarting" [class.has-floating-toc]="hasFloatingToc" role="main">
|
||||
|
||||
<mat-sidenav [ngClass]="{'collapsed': !isSideBySide }" #sidenav class="sidenav" [opened]="isOpened" [mode]="mode" (open)="updateHostClasses()" (close)="updateHostClasses()">
|
||||
<mat-sidenav [ngClass]="{'collapsed': !isSideBySide}" #sidenav class="sidenav" [opened]="isOpened" [mode]="mode" (open)="updateHostClasses()" (close)="updateHostClasses()">
|
||||
<aio-nav-menu *ngIf="!isSideBySide" [nodes]="topMenuNarrowNodes" [currentNode]="currentNodes?.TopBarNarrow" [isWide]="false"></aio-nav-menu>
|
||||
<aio-nav-menu [nodes]="sideNavNodes" [currentNode]="currentNodes?.SideNav" [isWide]="isSideBySide"></aio-nav-menu>
|
||||
|
||||
@ -28,7 +30,13 @@
|
||||
|
||||
<section class="sidenav-content" [id]="pageId" role="content">
|
||||
<aio-mode-banner [mode]="deployment.mode" [version]="versionInfo"></aio-mode-banner>
|
||||
<aio-doc-viewer [doc]="currentDocument" (docRendered)="onDocRendered()"></aio-doc-viewer>
|
||||
<aio-doc-viewer [class.no-animations]="isStarting"
|
||||
[doc]="currentDocument"
|
||||
(docReady)="onDocReady()"
|
||||
(docRemoved)="onDocRemoved()"
|
||||
(docInserted)="onDocInserted()"
|
||||
(docRendered)="onDocRendered()">
|
||||
</aio-doc-viewer>
|
||||
<aio-dt [on]="dtOn" [(doc)]="currentDocument"></aio-dt>
|
||||
</section>
|
||||
|
||||
|
@ -6,12 +6,14 @@ import { HttpClient } from '@angular/common/http';
|
||||
import { MatProgressBar, MatSidenav } from '@angular/material';
|
||||
import { By } from '@angular/platform-browser';
|
||||
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
import { of } from 'rxjs/observable/of';
|
||||
|
||||
import { AppComponent } from './app.component';
|
||||
import { AppModule } from './app.module';
|
||||
import { DocViewerComponent } from 'app/layout/doc-viewer/doc-viewer.component';
|
||||
import { Deployment } from 'app/shared/deployment.service';
|
||||
import { EmbedComponentsService } from 'app/embed-components/embed-components.service';
|
||||
import { GaService } from 'app/shared/ga.service';
|
||||
import { LocationService } from 'app/shared/location.service';
|
||||
import { Logger } from 'app/shared/logger.service';
|
||||
@ -24,7 +26,7 @@ import { SearchBoxComponent } from 'app/search/search-box/search-box.component';
|
||||
import { SearchResultsComponent } from 'app/shared/search-results/search-results.component';
|
||||
import { SearchService } from 'app/search/search.service';
|
||||
import { SelectComponent } from 'app/shared/select/select.component';
|
||||
import { TocComponent } from 'app/embedded/toc/toc.component';
|
||||
import { TocComponent } from 'app/layout/toc/toc.component';
|
||||
import { TocItem, TocService } from 'app/shared/toc.service';
|
||||
|
||||
const sideBySideBreakPoint = 992;
|
||||
@ -55,13 +57,18 @@ describe('AppComponent', () => {
|
||||
tocService = de.injector.get(TocService);
|
||||
};
|
||||
|
||||
|
||||
describe('with proper DocViewer', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
DocViewerComponent.animationsEnabled = false;
|
||||
|
||||
createTestingModule('a/b');
|
||||
initializeTest();
|
||||
});
|
||||
|
||||
afterEach(() => DocViewerComponent.animationsEnabled = true);
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeDefined();
|
||||
});
|
||||
@ -147,34 +154,35 @@ describe('AppComponent', () => {
|
||||
});
|
||||
|
||||
describe('SideNav when side-by-side (wide)', () => {
|
||||
const navigateTo = (path: string) => {
|
||||
locationService.go(path);
|
||||
component.updateSideNav();
|
||||
fixture.detectChanges();
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
component.onResize(sideBySideBreakPoint + 1); // side-by-side
|
||||
});
|
||||
|
||||
it('should open when nav to a guide page (guide/pipes)', () => {
|
||||
locationService.go('guide/pipes');
|
||||
fixture.detectChanges();
|
||||
navigateTo('guide/pipes');
|
||||
expect(sidenav.opened).toBe(true);
|
||||
});
|
||||
|
||||
it('should open when nav to an api page', () => {
|
||||
locationService.go('api/a/b/c/d');
|
||||
fixture.detectChanges();
|
||||
navigateTo('api/a/b/c/d');
|
||||
expect(sidenav.opened).toBe(true);
|
||||
});
|
||||
|
||||
it('should be closed when nav to a marketing page (features)', () => {
|
||||
locationService.go('features');
|
||||
fixture.detectChanges();
|
||||
navigateTo('features');
|
||||
expect(sidenav.opened).toBe(false);
|
||||
});
|
||||
|
||||
describe('when manually closed', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
locationService.go('guide/pipes');
|
||||
fixture.detectChanges();
|
||||
navigateTo('guide/pipes');
|
||||
hamburger.click();
|
||||
fixture.detectChanges();
|
||||
});
|
||||
@ -184,56 +192,53 @@ describe('AppComponent', () => {
|
||||
});
|
||||
|
||||
it('should stay closed when nav from one guide page to another', () => {
|
||||
locationService.go('guide/bags');
|
||||
fixture.detectChanges();
|
||||
navigateTo('guide/bags');
|
||||
expect(sidenav.opened).toBe(false);
|
||||
});
|
||||
|
||||
it('should stay closed when nav from a guide page to api page', () => {
|
||||
locationService.go('api');
|
||||
fixture.detectChanges();
|
||||
navigateTo('api');
|
||||
expect(sidenav.opened).toBe(false);
|
||||
});
|
||||
|
||||
it('should reopen when nav to market page and back to guide page', () => {
|
||||
locationService.go('features');
|
||||
fixture.detectChanges();
|
||||
locationService.go('guide/bags');
|
||||
fixture.detectChanges();
|
||||
navigateTo('features');
|
||||
navigateTo('guide/bags');
|
||||
expect(sidenav.opened).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('SideNav when NOT side-by-side (narrow)', () => {
|
||||
const navigateTo = (path: string) => {
|
||||
locationService.go(path);
|
||||
component.updateSideNav();
|
||||
fixture.detectChanges();
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
component.onResize(sideBySideBreakPoint - 1); // NOT side-by-side
|
||||
});
|
||||
|
||||
it('should be closed when nav to a guide page (guide/pipes)', () => {
|
||||
locationService.go('guide/pipes');
|
||||
fixture.detectChanges();
|
||||
navigateTo('guide/pipes');
|
||||
expect(sidenav.opened).toBe(false);
|
||||
});
|
||||
|
||||
it('should be closed when nav to an api page', () => {
|
||||
locationService.go('api/a/b/c/d');
|
||||
fixture.detectChanges();
|
||||
navigateTo('api/a/b/c/d');
|
||||
expect(sidenav.opened).toBe(false);
|
||||
});
|
||||
|
||||
it('should be closed when nav to a marketing page (features)', () => {
|
||||
locationService.go('features');
|
||||
fixture.detectChanges();
|
||||
navigateTo('features');
|
||||
expect(sidenav.opened).toBe(false);
|
||||
});
|
||||
|
||||
describe('when manually opened', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
locationService.go('guide/pipes');
|
||||
fixture.detectChanges();
|
||||
navigateTo('guide/pipes');
|
||||
hamburger.click();
|
||||
fixture.detectChanges();
|
||||
});
|
||||
@ -246,25 +251,22 @@ describe('AppComponent', () => {
|
||||
const sidenavBackdrop = fixture.debugElement.query(By.css('.mat-drawer-backdrop')).nativeElement;
|
||||
sidenavBackdrop.click();
|
||||
fixture.detectChanges();
|
||||
expect(sidenav.opened).toBe(false);
|
||||
expect(sidenav.opened).toBe(false);
|
||||
});
|
||||
|
||||
it('should close when nav to another guide page', () => {
|
||||
locationService.go('guide/bags');
|
||||
fixture.detectChanges();
|
||||
expect(sidenav.opened).toBe(false);
|
||||
navigateTo('guide/bags');
|
||||
expect(sidenav.opened).toBe(false);
|
||||
});
|
||||
|
||||
it('should close when nav to api page', () => {
|
||||
locationService.go('api');
|
||||
fixture.detectChanges();
|
||||
expect(sidenav.opened).toBe(false);
|
||||
navigateTo('api');
|
||||
expect(sidenav.opened).toBe(false);
|
||||
});
|
||||
|
||||
it('should close again when nav to market page', () => {
|
||||
locationService.go('features');
|
||||
fixture.detectChanges();
|
||||
expect(sidenav.opened).toBe(false);
|
||||
navigateTo('features');
|
||||
expect(sidenav.opened).toBe(false);
|
||||
});
|
||||
|
||||
});
|
||||
@ -318,96 +320,7 @@ describe('AppComponent', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('pageId', () => {
|
||||
|
||||
it('should set the id of the doc viewer container based on the current doc', () => {
|
||||
const container = fixture.debugElement.query(By.css('section.sidenav-content'));
|
||||
|
||||
locationService.go('guide/pipes');
|
||||
fixture.detectChanges();
|
||||
expect(component.pageId).toEqual('guide-pipes');
|
||||
expect(container.properties['id']).toEqual('guide-pipes');
|
||||
|
||||
locationService.go('news');
|
||||
fixture.detectChanges();
|
||||
expect(component.pageId).toEqual('news');
|
||||
expect(container.properties['id']).toEqual('news');
|
||||
|
||||
locationService.go('');
|
||||
fixture.detectChanges();
|
||||
expect(component.pageId).toEqual('home');
|
||||
expect(container.properties['id']).toEqual('home');
|
||||
});
|
||||
|
||||
it('should not be affected by changes to the query', () => {
|
||||
const container = fixture.debugElement.query(By.css('section.sidenav-content'));
|
||||
|
||||
locationService.go('guide/pipes');
|
||||
fixture.detectChanges();
|
||||
|
||||
locationService.go('guide/other?search=http');
|
||||
fixture.detectChanges();
|
||||
expect(component.pageId).toEqual('guide-other');
|
||||
expect(container.properties['id']).toEqual('guide-other');
|
||||
});
|
||||
});
|
||||
|
||||
describe('hostClasses', () => {
|
||||
|
||||
it('should set the css classes of the host container based on the current doc and navigation view', () => {
|
||||
locationService.go('guide/pipes');
|
||||
fixture.detectChanges();
|
||||
|
||||
checkHostClass('page', 'guide-pipes');
|
||||
checkHostClass('folder', 'guide');
|
||||
checkHostClass('view', 'SideNav');
|
||||
|
||||
locationService.go('features');
|
||||
fixture.detectChanges();
|
||||
checkHostClass('page', 'features');
|
||||
checkHostClass('folder', 'features');
|
||||
checkHostClass('view', 'TopBar');
|
||||
|
||||
locationService.go('');
|
||||
fixture.detectChanges();
|
||||
checkHostClass('page', 'home');
|
||||
checkHostClass('folder', 'home');
|
||||
checkHostClass('view', '');
|
||||
});
|
||||
|
||||
it('should set the css class of the host container based on the open/closed state of the side nav', () => {
|
||||
locationService.go('guide/pipes');
|
||||
fixture.detectChanges();
|
||||
checkHostClass('sidenav', 'open');
|
||||
|
||||
sidenav.close();
|
||||
sidenav.onClose.next();
|
||||
fixture.detectChanges();
|
||||
checkHostClass('sidenav', 'closed');
|
||||
|
||||
sidenav.open();
|
||||
sidenav.onOpen.next();
|
||||
fixture.detectChanges();
|
||||
checkHostClass('sidenav', 'open');
|
||||
});
|
||||
|
||||
it('should set the css class of the host container based on the initial deployment mode', () => {
|
||||
createTestingModule('a/b', 'archive');
|
||||
initializeTest();
|
||||
checkHostClass('mode', 'archive');
|
||||
});
|
||||
|
||||
function checkHostClass(type, value) {
|
||||
const host = fixture.debugElement;
|
||||
const classes = host.properties['className'];
|
||||
const classArray = classes.split(' ').filter(c => c.indexOf(`${type}-`) === 0);
|
||||
expect(classArray.length).toBeLessThanOrEqual(1, `"${classes}" should have only one class matching ${type}-*`);
|
||||
expect(classArray).toEqual([`${type}-${value}`], `"${classes}" should contain ${type}-${value}`);
|
||||
}
|
||||
});
|
||||
|
||||
describe('currentDocument', () => {
|
||||
|
||||
it('should display a guide page (guide/pipes)', () => {
|
||||
locationService.go('guide/pipes');
|
||||
fixture.detectChanges();
|
||||
@ -447,16 +360,19 @@ describe('AppComponent', () => {
|
||||
const scrollDelay = 500;
|
||||
let scrollService: ScrollService;
|
||||
let scrollSpy: jasmine.Spy;
|
||||
let scrollToTopSpy: jasmine.Spy;
|
||||
|
||||
beforeEach(() => {
|
||||
scrollService = fixture.debugElement.injector.get(ScrollService);
|
||||
scrollSpy = spyOn(scrollService, 'scroll');
|
||||
scrollToTopSpy = spyOn(scrollService, 'scrollToTop');
|
||||
});
|
||||
|
||||
it('should not scroll immediately when the docId (path) changes', () => {
|
||||
locationService.go('guide/pipes');
|
||||
// deliberately not calling `fixture.detectChanges` because don't want `onDocRendered`
|
||||
// deliberately not calling `fixture.detectChanges` because don't want `onDocInserted`
|
||||
expect(scrollSpy).not.toHaveBeenCalled();
|
||||
expect(scrollToTopSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should scroll when just the hash changes (# alone)', () => {
|
||||
@ -486,7 +402,7 @@ describe('AppComponent', () => {
|
||||
expect(scrollSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should scroll when e-nav to the empty path', () => {
|
||||
it('should scroll when re-nav to the empty path', () => {
|
||||
locationService.go('');
|
||||
scrollSpy.calls.reset();
|
||||
|
||||
@ -494,17 +410,29 @@ describe('AppComponent', () => {
|
||||
expect(scrollSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should scroll after a delay when call onDocRendered directly', fakeAsync(() => {
|
||||
component.onDocRendered();
|
||||
it('should scroll to top when call `onDocRemoved` directly', () => {
|
||||
scrollToTopSpy.calls.reset();
|
||||
|
||||
component.onDocRemoved();
|
||||
expect(scrollToTopSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should scroll after a delay when call `onDocInserted` directly', fakeAsync(() => {
|
||||
component.onDocInserted();
|
||||
expect(scrollSpy).not.toHaveBeenCalled();
|
||||
|
||||
tick(scrollDelay);
|
||||
expect(scrollSpy).toHaveBeenCalled();
|
||||
}));
|
||||
|
||||
it('should scroll (via onDocRendered) when finish navigating to a new doc', fakeAsync(() => {
|
||||
it('should scroll (via `onDocInserted`) when finish navigating to a new doc', fakeAsync(() => {
|
||||
expect(scrollToTopSpy).not.toHaveBeenCalled();
|
||||
|
||||
locationService.go('guide/pipes');
|
||||
fixture.detectChanges(); // triggers the event that calls onDocRendered
|
||||
fixture.detectChanges(); // triggers the event that calls `onDocInserted`
|
||||
expect(scrollToTopSpy).toHaveBeenCalled();
|
||||
expect(scrollSpy).not.toHaveBeenCalled();
|
||||
|
||||
tick(scrollDelay);
|
||||
expect(scrollSpy).toHaveBeenCalled();
|
||||
}));
|
||||
@ -795,14 +723,14 @@ describe('AppComponent', () => {
|
||||
expect(TestBed.get(LocationService).replace).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should redirect to `docs` if deployment mode is `next` and not at a docs page', () => {
|
||||
it('should not redirect if deployment mode is `next`', () => {
|
||||
createTestingModule('', 'next');
|
||||
initializeTest();
|
||||
expect(TestBed.get(LocationService).replace).toHaveBeenCalledWith('docs');
|
||||
expect(TestBed.get(LocationService).replace).not.toHaveBeenCalled();
|
||||
|
||||
createTestingModule('resources', 'next');
|
||||
initializeTest();
|
||||
expect(TestBed.get(LocationService).replace).toHaveBeenCalledWith('docs');
|
||||
expect(TestBed.get(LocationService).replace).not.toHaveBeenCalled();
|
||||
|
||||
createTestingModule('guide/aot-compiler', 'next');
|
||||
initializeTest();
|
||||
@ -829,7 +757,7 @@ describe('AppComponent', () => {
|
||||
expect(TestBed.get(LocationService).replace).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not redirect to `docs` if deployment mode is `stable` and not at a docs page', () => {
|
||||
it('should not redirect to `docs` if deployment mode is `stable`', () => {
|
||||
createTestingModule('', 'stable');
|
||||
initializeTest();
|
||||
expect(TestBed.get(LocationService).replace).not.toHaveBeenCalled();
|
||||
@ -867,7 +795,9 @@ describe('AppComponent', () => {
|
||||
|
||||
describe('with mocked DocViewer', () => {
|
||||
const getDocViewer = () => fixture.debugElement.query(By.css('aio-doc-viewer'));
|
||||
const triggerDocRendered = () => getDocViewer().triggerEventHandler('docRendered', {});
|
||||
const triggerDocViewerEvent =
|
||||
(evt: 'docReady' | 'docRemoved' | 'docInserted' | 'docRendered') =>
|
||||
getDocViewer().triggerEventHandler(evt, undefined);
|
||||
|
||||
beforeEach(() => {
|
||||
createTestingModule('a/b');
|
||||
@ -879,7 +809,7 @@ describe('AppComponent', () => {
|
||||
});
|
||||
|
||||
describe('initial rendering', () => {
|
||||
it('should initially add the starting class until the first document is rendered', fakeAsync(() => {
|
||||
it('should initially add the starting class until a document is rendered', () => {
|
||||
const getSidenavContainer = () => fixture.debugElement.query(By.css('mat-sidenav-container'));
|
||||
|
||||
initializeTest();
|
||||
@ -887,21 +817,181 @@ describe('AppComponent', () => {
|
||||
expect(component.isStarting).toBe(true);
|
||||
expect(getSidenavContainer().classes['starting']).toBe(true);
|
||||
|
||||
triggerDocRendered();
|
||||
fixture.detectChanges();
|
||||
expect(component.isStarting).toBe(true);
|
||||
expect(getSidenavContainer().classes['starting']).toBe(true);
|
||||
|
||||
tick(499);
|
||||
fixture.detectChanges();
|
||||
expect(component.isStarting).toBe(true);
|
||||
expect(getSidenavContainer().classes['starting']).toBe(true);
|
||||
|
||||
tick(2);
|
||||
triggerDocViewerEvent('docRendered');
|
||||
fixture.detectChanges();
|
||||
expect(component.isStarting).toBe(false);
|
||||
expect(getSidenavContainer().classes['starting']).toBe(false);
|
||||
}));
|
||||
});
|
||||
|
||||
it('should initially disable animations on the DocViewer for the first rendering', () => {
|
||||
initializeTest();
|
||||
|
||||
expect(component.isStarting).toBe(true);
|
||||
expect(docViewer.classList.contains('no-animations')).toBe(true);
|
||||
|
||||
triggerDocViewerEvent('docRendered');
|
||||
fixture.detectChanges();
|
||||
expect(component.isStarting).toBe(false);
|
||||
expect(docViewer.classList.contains('no-animations')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('subsequent rendering', () => {
|
||||
beforeEach(jasmine.clock().install);
|
||||
afterEach(jasmine.clock().uninstall);
|
||||
|
||||
it('should set the transitioning class on `.app-toolbar` while a document is being rendered', () => {
|
||||
const getToolbar = () => fixture.debugElement.query(By.css('.app-toolbar'));
|
||||
|
||||
initializeTest();
|
||||
|
||||
// Initially, `isTransitoning` is true.
|
||||
expect(component.isTransitioning).toBe(true);
|
||||
expect(getToolbar().classes['transitioning']).toBe(true);
|
||||
|
||||
triggerDocViewerEvent('docRendered');
|
||||
fixture.detectChanges();
|
||||
expect(component.isTransitioning).toBe(false);
|
||||
expect(getToolbar().classes['transitioning']).toBe(false);
|
||||
|
||||
// While a document is being rendered, `isTransitoning` is set to true.
|
||||
triggerDocViewerEvent('docReady');
|
||||
fixture.detectChanges();
|
||||
expect(component.isTransitioning).toBe(true);
|
||||
expect(getToolbar().classes['transitioning']).toBe(true);
|
||||
|
||||
triggerDocViewerEvent('docRendered');
|
||||
fixture.detectChanges();
|
||||
expect(component.isTransitioning).toBe(false);
|
||||
expect(getToolbar().classes['transitioning']).toBe(false);
|
||||
});
|
||||
|
||||
it('should update the sidenav state as soon as a new document is inserted', () => {
|
||||
initializeTest();
|
||||
const updateSideNavSpy = spyOn(component, 'updateSideNav');
|
||||
|
||||
triggerDocViewerEvent('docInserted');
|
||||
jasmine.clock().tick(0);
|
||||
expect(updateSideNavSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
triggerDocViewerEvent('docInserted');
|
||||
jasmine.clock().tick(0);
|
||||
expect(updateSideNavSpy).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('pageId', () => {
|
||||
const navigateTo = (path: string) => {
|
||||
locationService.go(path);
|
||||
triggerDocViewerEvent('docInserted');
|
||||
jasmine.clock().tick(0);
|
||||
fixture.detectChanges();
|
||||
};
|
||||
|
||||
beforeEach(jasmine.clock().install);
|
||||
afterEach(jasmine.clock().uninstall);
|
||||
|
||||
it('should set the id of the doc viewer container based on the current doc', () => {
|
||||
initializeTest();
|
||||
const container = fixture.debugElement.query(By.css('section.sidenav-content'));
|
||||
|
||||
navigateTo('guide/pipes');
|
||||
expect(component.pageId).toEqual('guide-pipes');
|
||||
expect(container.properties['id']).toEqual('guide-pipes');
|
||||
|
||||
navigateTo('news');
|
||||
expect(component.pageId).toEqual('news');
|
||||
expect(container.properties['id']).toEqual('news');
|
||||
|
||||
navigateTo('');
|
||||
expect(component.pageId).toEqual('home');
|
||||
expect(container.properties['id']).toEqual('home');
|
||||
});
|
||||
|
||||
it('should not be affected by changes to the query', () => {
|
||||
initializeTest();
|
||||
const container = fixture.debugElement.query(By.css('section.sidenav-content'));
|
||||
|
||||
navigateTo('guide/pipes');
|
||||
navigateTo('guide/other?search=http');
|
||||
|
||||
expect(component.pageId).toEqual('guide-other');
|
||||
expect(container.properties['id']).toEqual('guide-other');
|
||||
});
|
||||
});
|
||||
|
||||
describe('hostClasses', () => {
|
||||
const triggerUpdateHostClasses = () => {
|
||||
triggerDocViewerEvent('docInserted');
|
||||
jasmine.clock().tick(0);
|
||||
fixture.detectChanges();
|
||||
};
|
||||
const navigateTo = (path: string) => {
|
||||
locationService.go(path);
|
||||
triggerUpdateHostClasses();
|
||||
};
|
||||
|
||||
beforeEach(jasmine.clock().install);
|
||||
afterEach(jasmine.clock().uninstall);
|
||||
|
||||
it('should set the css classes of the host container based on the current doc and navigation view', () => {
|
||||
initializeTest();
|
||||
|
||||
navigateTo('guide/pipes');
|
||||
checkHostClass('page', 'guide-pipes');
|
||||
checkHostClass('folder', 'guide');
|
||||
checkHostClass('view', 'SideNav');
|
||||
|
||||
navigateTo('features');
|
||||
checkHostClass('page', 'features');
|
||||
checkHostClass('folder', 'features');
|
||||
checkHostClass('view', 'TopBar');
|
||||
|
||||
navigateTo('');
|
||||
checkHostClass('page', 'home');
|
||||
checkHostClass('folder', 'home');
|
||||
checkHostClass('view', '');
|
||||
});
|
||||
|
||||
it('should set the css class of the host container based on the open/closed state of the side nav', async () => {
|
||||
initializeTest();
|
||||
|
||||
navigateTo('guide/pipes');
|
||||
checkHostClass('sidenav', 'open');
|
||||
|
||||
sidenav.close();
|
||||
await waitForEmit(sidenav.onClose);
|
||||
fixture.detectChanges();
|
||||
checkHostClass('sidenav', 'closed');
|
||||
|
||||
sidenav.open();
|
||||
await waitForEmit(sidenav.onOpen);
|
||||
fixture.detectChanges();
|
||||
checkHostClass('sidenav', 'open');
|
||||
|
||||
function waitForEmit(emitter: Observable<void>): Promise<void> {
|
||||
return new Promise(resolve => {
|
||||
emitter.subscribe(resolve);
|
||||
fixture.detectChanges();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('should set the css class of the host container based on the initial deployment mode', () => {
|
||||
createTestingModule('a/b', 'archive');
|
||||
initializeTest();
|
||||
|
||||
triggerUpdateHostClasses();
|
||||
checkHostClass('mode', 'archive');
|
||||
});
|
||||
|
||||
function checkHostClass(type, value) {
|
||||
const host = fixture.debugElement;
|
||||
const classes = host.properties['className'];
|
||||
const classArray = classes.split(' ').filter(c => c.indexOf(`${type}-`) === 0);
|
||||
expect(classArray.length).toBeLessThanOrEqual(1, `"${classes}" should have only one class matching ${type}-*`);
|
||||
expect(classArray).toEqual([`${type}-${value}`], `"${classes}" should contain ${type}-${value}`);
|
||||
}
|
||||
});
|
||||
|
||||
describe('progress bar', () => {
|
||||
@ -910,7 +1000,7 @@ describe('AppComponent', () => {
|
||||
const getProgressBar = () => fixture.debugElement.query(By.directive(MatProgressBar));
|
||||
const initializeAndCompleteNavigation = () => {
|
||||
initializeTest();
|
||||
triggerDocRendered();
|
||||
triggerDocViewerEvent('docReady');
|
||||
tick(HIDE_DELAY);
|
||||
};
|
||||
|
||||
@ -947,7 +1037,7 @@ describe('AppComponent', () => {
|
||||
it('should not be shown when re-navigating to the empty path', fakeAsync(() => {
|
||||
initializeAndCompleteNavigation();
|
||||
locationService.urlSubject.next('');
|
||||
triggerDocRendered();
|
||||
triggerDocViewerEvent('docReady');
|
||||
|
||||
locationService.urlSubject.next('');
|
||||
|
||||
@ -958,12 +1048,12 @@ describe('AppComponent', () => {
|
||||
tick(HIDE_DELAY); // Fire the remaining timer or `fakeAsync()` complains.
|
||||
}));
|
||||
|
||||
it('should not be shown if the doc is rendered quickly', fakeAsync(() => {
|
||||
it('should not be shown if the doc is prepared quickly', fakeAsync(() => {
|
||||
initializeAndCompleteNavigation();
|
||||
locationService.urlSubject.next('c/d');
|
||||
|
||||
tick(SHOW_DELAY - 1);
|
||||
triggerDocRendered();
|
||||
triggerDocViewerEvent('docReady');
|
||||
|
||||
tick(1);
|
||||
fixture.detectChanges();
|
||||
@ -972,12 +1062,12 @@ describe('AppComponent', () => {
|
||||
tick(HIDE_DELAY); // Fire the remaining timer or `fakeAsync()` complains.
|
||||
}));
|
||||
|
||||
it('should be shown if rendering the doc takes too long', fakeAsync(() => {
|
||||
it('should be shown if preparing the doc takes too long', fakeAsync(() => {
|
||||
initializeAndCompleteNavigation();
|
||||
locationService.urlSubject.next('c/d');
|
||||
|
||||
tick(SHOW_DELAY);
|
||||
triggerDocRendered();
|
||||
triggerDocViewerEvent('docReady');
|
||||
|
||||
fixture.detectChanges();
|
||||
expect(getProgressBar()).toBeTruthy();
|
||||
@ -985,12 +1075,12 @@ describe('AppComponent', () => {
|
||||
tick(HIDE_DELAY); // Fire the remaining timer or `fakeAsync()` complains.
|
||||
}));
|
||||
|
||||
it('should be hidden (after a delay) once the doc is rendered', fakeAsync(() => {
|
||||
it('should be hidden (after a delay) once the doc has been prepared', fakeAsync(() => {
|
||||
initializeAndCompleteNavigation();
|
||||
locationService.urlSubject.next('c/d');
|
||||
|
||||
tick(SHOW_DELAY);
|
||||
triggerDocRendered();
|
||||
triggerDocViewerEvent('docReady');
|
||||
|
||||
fixture.detectChanges();
|
||||
expect(getProgressBar()).toBeTruthy();
|
||||
@ -1007,10 +1097,10 @@ describe('AppComponent', () => {
|
||||
it('should only take the latest request into account', fakeAsync(() => {
|
||||
initializeAndCompleteNavigation();
|
||||
locationService.urlSubject.next('c/d'); // The URL changes.
|
||||
locationService.urlSubject.next('e/f'); // The URL changes again before `onDocRendered()`.
|
||||
locationService.urlSubject.next('e/f'); // The URL changes again before `onDocReady()`.
|
||||
|
||||
tick(SHOW_DELAY - 1); // `onDocRendered()` is triggered (for the last doc),
|
||||
triggerDocRendered(); // before the progress bar is shown.
|
||||
tick(SHOW_DELAY - 1); // `onDocReady()` is triggered (for the last doc),
|
||||
triggerDocViewerEvent('docReady'); // before the progress bar is shown.
|
||||
|
||||
tick(1);
|
||||
fixture.detectChanges();
|
||||
@ -1033,6 +1123,7 @@ function createTestingModule(initialUrl: string, mode: string = 'stable') {
|
||||
imports: [ AppModule ],
|
||||
providers: [
|
||||
{ provide: APP_BASE_HREF, useValue: '/' },
|
||||
{ provide: EmbedComponentsService, useClass: TestEmbedComponentsService },
|
||||
{ provide: GaService, useClass: TestGaService },
|
||||
{ provide: HttpClient, useClass: TestHttpClient },
|
||||
{ provide: LocationService, useFactory: () => mockLocationService },
|
||||
@ -1047,6 +1138,10 @@ function createTestingModule(initialUrl: string, mode: string = 'stable') {
|
||||
});
|
||||
}
|
||||
|
||||
class TestEmbedComponentsService {
|
||||
embedInto = jasmine.createSpy('embedInto').and.returnValue(of([]));
|
||||
}
|
||||
|
||||
class TestGaService {
|
||||
locationChanged = jasmine.createSpy('locationChanged');
|
||||
}
|
||||
|
@ -1,10 +1,9 @@
|
||||
import { Component, ElementRef, HostBinding, HostListener, OnInit,
|
||||
QueryList, ViewChild, ViewChildren } from '@angular/core';
|
||||
import { MatSidenav } from '@angular/material';
|
||||
import { MatSidenav } from '@angular/material/sidenav';
|
||||
|
||||
import { CurrentNodes, NavigationService, NavigationNode, VersionInfo } from 'app/navigation/navigation.service';
|
||||
import { DocumentService, DocumentContents } from 'app/documents/document.service';
|
||||
import { DocViewerComponent } from 'app/layout/doc-viewer/doc-viewer.component';
|
||||
import { Deployment } from 'app/shared/deployment.service';
|
||||
import { LocationService } from 'app/shared/location.service';
|
||||
import { ScrollService } from 'app/shared/scroll.service';
|
||||
@ -16,6 +15,7 @@ import { TocService } from 'app/shared/toc.service';
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
|
||||
import { combineLatest } from 'rxjs/observable/combineLatest';
|
||||
import 'rxjs/add/operator/first';
|
||||
|
||||
const sideNavView = 'SideNav';
|
||||
|
||||
@ -58,6 +58,7 @@ export class AppComponent implements OnInit {
|
||||
|
||||
isFetching = false;
|
||||
isStarting = true;
|
||||
isTransitioning = true;
|
||||
isSideBySide = false;
|
||||
private isFetchingTimeout: any;
|
||||
private isSideNavDoc = false;
|
||||
@ -75,18 +76,9 @@ export class AppComponent implements OnInit {
|
||||
|
||||
versionInfo: VersionInfo;
|
||||
|
||||
get homeImageUrl() {
|
||||
return this.isSideBySide ?
|
||||
'assets/images/logos/angular/logo-nav@2x.png' :
|
||||
'assets/images/logos/angular/shield-large.svg';
|
||||
}
|
||||
get isOpened() { return this.isSideBySide && this.isSideNavDoc; }
|
||||
get mode() { return this.isSideBySide ? 'side' : 'over'; }
|
||||
|
||||
// Need the doc-viewer element for scrolling the contents
|
||||
@ViewChild(DocViewerComponent, { read: ElementRef })
|
||||
docViewer: ElementRef;
|
||||
|
||||
// Search related properties
|
||||
showSearchResults = false;
|
||||
searchResults: Observable<SearchResults>;
|
||||
@ -120,17 +112,18 @@ export class AppComponent implements OnInit {
|
||||
|
||||
/* No need to unsubscribe because this root component never dies */
|
||||
|
||||
this.documentService.currentDocument.subscribe(doc => {
|
||||
this.currentDocument = doc;
|
||||
this.setPageId(doc.id);
|
||||
this.setFolderId(doc.id);
|
||||
this.updateHostClasses();
|
||||
});
|
||||
this.documentService.currentDocument.subscribe(doc => this.currentDocument = doc);
|
||||
// Generally, we want to delay updating the host classes for the new document, until after the
|
||||
// leaving document has been removed (to avoid having the styles for the new document applied
|
||||
// prematurely).
|
||||
// On the first document, though, (when we know there is no previous document), we want to
|
||||
// ensure the styles are applied as soon as possible to avoid flicker.
|
||||
this.documentService.currentDocument.first().subscribe(doc => this.updateHostClassesForDoc(doc));
|
||||
|
||||
this.locationService.currentPath.subscribe(path => {
|
||||
// Redirect to docs if we are in not in stable mode and are not hitting a docs page
|
||||
// Redirect to docs if we are in archive mode and are not hitting a docs page
|
||||
// (i.e. we have arrived at a marketing page)
|
||||
if (this.deployment.mode !== 'stable' && !/^(docs$|api|guide|tutorial)/.test(path)) {
|
||||
if (this.deployment.mode === 'archive' && !/^(docs$|api|guide|tutorial)/.test(path)) {
|
||||
this.locationService.replace('docs');
|
||||
}
|
||||
if (path === this.currentPath) {
|
||||
@ -146,21 +139,7 @@ export class AppComponent implements OnInit {
|
||||
}
|
||||
});
|
||||
|
||||
this.navigationService.currentNodes.subscribe(currentNodes => {
|
||||
this.currentNodes = currentNodes;
|
||||
|
||||
// Preserve current sidenav open state by default
|
||||
let openSideNav = this.sidenav.opened;
|
||||
const isSideNavDoc = !!currentNodes[sideNavView];
|
||||
|
||||
if (this.isSideNavDoc !== isSideNavDoc) {
|
||||
// View type changed. Is it now a sidenav view (e.g, guide or tutorial)?
|
||||
// Open if changed to a sidenav doc; close if changed to a marketing doc.
|
||||
openSideNav = this.isSideNavDoc = isSideNavDoc;
|
||||
}
|
||||
// May be open or closed when wide; always closed when narrow
|
||||
this.sideNavToggle(this.isSideBySide ? openSideNav : false);
|
||||
});
|
||||
this.navigationService.currentNodes.subscribe(currentNodes => this.currentNodes = currentNodes);
|
||||
|
||||
// Compute the version picker list from the current version and the versions in the navigation map
|
||||
combineLatest(
|
||||
@ -203,20 +182,41 @@ export class AppComponent implements OnInit {
|
||||
this.scrollService.scroll();
|
||||
}
|
||||
|
||||
onDocRendered() {
|
||||
onDocReady() {
|
||||
// About to transition to new view.
|
||||
this.isTransitioning = true;
|
||||
|
||||
// Stop fetching timeout (which, when render is fast, means progress bar never shown)
|
||||
clearTimeout(this.isFetchingTimeout);
|
||||
|
||||
// Put page in a clean visual state
|
||||
this.scrollService.scrollToTop();
|
||||
// If progress bar has been shown, keep it for at least 500ms (to avoid flashing).
|
||||
setTimeout(() => this.isFetching = false, 500);
|
||||
}
|
||||
|
||||
// Scroll 500ms after the doc-viewer has finished rendering the new doc
|
||||
// The delay is to allow time for async layout to complete
|
||||
onDocRemoved() {
|
||||
// The previous document has been removed.
|
||||
// Scroll to top to restore a clean visual state for the new document.
|
||||
this.scrollService.scrollToTop();
|
||||
}
|
||||
|
||||
onDocInserted() {
|
||||
// TODO: Find a better way to avoid `ExpressionChangedAfterItHasBeenChecked` error.
|
||||
setTimeout(() => {
|
||||
this.autoScroll();
|
||||
this.isStarting = false;
|
||||
this.isFetching = false;
|
||||
}, 500);
|
||||
// Update the SideNav state (if necessary).
|
||||
this.updateSideNav();
|
||||
|
||||
// Update the host classes to match the new document.
|
||||
this.updateHostClassesForDoc(this.currentDocument);
|
||||
});
|
||||
|
||||
// Scroll 500ms after the new document has been inserted into the doc-viewer.
|
||||
// The delay is to allow time for async layout to complete.
|
||||
setTimeout(() => this.autoScroll(), 500);
|
||||
}
|
||||
|
||||
onDocRendered() {
|
||||
this.isStarting = false;
|
||||
this.isTransitioning = false;
|
||||
}
|
||||
|
||||
onDocVersionChange(versionIndex: number) {
|
||||
@ -283,6 +283,27 @@ export class AppComponent implements OnInit {
|
||||
this.hostClasses = `${mode} ${sideNavOpen} ${pageClass} ${folderClass} ${viewClasses}`;
|
||||
}
|
||||
|
||||
updateHostClassesForDoc(doc: DocumentContents) {
|
||||
this.setPageId(doc.id);
|
||||
this.setFolderId(doc.id);
|
||||
this.updateHostClasses();
|
||||
}
|
||||
|
||||
updateSideNav() {
|
||||
// Preserve current sidenav open state by default.
|
||||
let openSideNav = this.sidenav.opened;
|
||||
const isSideNavDoc = !!this.currentNodes[sideNavView];
|
||||
|
||||
if (this.isSideNavDoc !== isSideNavDoc) {
|
||||
// View type changed. Is it now a sidenav view (e.g, guide or tutorial)?
|
||||
// Open if changed to a sidenav doc; close if changed to a marketing doc.
|
||||
openSideNav = this.isSideNavDoc = isSideNavDoc;
|
||||
}
|
||||
|
||||
// May be open or closed when wide; always closed when narrow.
|
||||
this.sideNavToggle(this.isSideBySide && openSideNav);
|
||||
}
|
||||
|
||||
// Dynamically change height of table of contents container
|
||||
@HostListener('window:scroll')
|
||||
onScroll() {
|
||||
@ -291,7 +312,7 @@ export class AppComponent implements OnInit {
|
||||
const el = this.hostElement.nativeElement as Element;
|
||||
this.tocMaxHeightOffset =
|
||||
el.querySelector('footer').clientHeight +
|
||||
el.querySelector('mat-toolbar.app-toolbar').clientHeight +
|
||||
el.querySelector('.app-toolbar').clientHeight +
|
||||
24; // fudge margin
|
||||
}
|
||||
|
||||
|
48
aio/src/app/app.module.spec.ts
Normal file
48
aio/src/app/app.module.spec.ts
Normal file
@ -0,0 +1,48 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { AppModule } from 'app/app.module';
|
||||
import { ComponentsOrModulePath, EMBEDDED_COMPONENTS } from 'app/embed-components/embed-components.service';
|
||||
import { embeddedComponents } from 'app/embedded/embedded.module';
|
||||
|
||||
describe('AppModule', () => {
|
||||
let componentsMap: {[multiSelectorstring: string]: ComponentsOrModulePath};
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({imports: [AppModule]});
|
||||
componentsMap = TestBed.get(EMBEDDED_COMPONENTS);
|
||||
});
|
||||
|
||||
it('should provide a map of selectors to embedded components (or module)', () => {
|
||||
const allSelectors = Object.keys(componentsMap);
|
||||
|
||||
expect(allSelectors.length).toBeGreaterThan(1);
|
||||
allSelectors.forEach(selector => {
|
||||
const value = componentsMap[selector];
|
||||
const isArrayOrString = Array.isArray(value) || (typeof value === 'string');
|
||||
expect(isArrayOrString).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('should provide a list of eagerly-loaded embedded components', () => {
|
||||
const eagerSelector = Object.keys(componentsMap).find(selector => Array.isArray(componentsMap[selector]));
|
||||
const selectorCount = eagerSelector.split(',').length;
|
||||
|
||||
expect(eagerSelector).not.toBeNull();
|
||||
expect(selectorCount).toBe(componentsMap[eagerSelector].length);
|
||||
|
||||
// For example...
|
||||
expect(eagerSelector).toContain('aio-toc');
|
||||
});
|
||||
|
||||
it('should provide a list of lazy-loaded embedded components', () => {
|
||||
const lazySelector = Object.keys(componentsMap).find(selector => selector.includes('code-example'));
|
||||
const selectorCount = lazySelector.split(',').length;
|
||||
|
||||
expect(lazySelector).not.toBeNull();
|
||||
expect(selectorCount).toBe(embeddedComponents.length);
|
||||
|
||||
// For example...
|
||||
expect(lazySelector).toContain('code-example');
|
||||
expect(lazySelector).toContain('code-tabs');
|
||||
expect(lazySelector).toContain('live-example');
|
||||
});
|
||||
});
|
@ -5,36 +5,22 @@ import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
|
||||
|
||||
import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';
|
||||
|
||||
import {
|
||||
MatButtonModule,
|
||||
MatIconModule,
|
||||
MatIconRegistry,
|
||||
MatInputModule,
|
||||
MatProgressBarModule,
|
||||
MatSidenavModule,
|
||||
MatTabsModule,
|
||||
MatToolbarModule
|
||||
} from '@angular/material';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule, MatIconRegistry } from '@angular/material/icon';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatSidenavModule } from '@angular/material/sidenav';
|
||||
import { MatToolbarModule } from '@angular/material/toolbar';
|
||||
|
||||
import {
|
||||
Platform
|
||||
} from '@angular/cdk/platform';
|
||||
import { ROUTES } from '@angular/router';
|
||||
|
||||
|
||||
// Temporary fix for MatSidenavModule issue:
|
||||
// crashes with "missing first" operator when SideNav.mode is "over"
|
||||
import 'rxjs/add/operator/first';
|
||||
|
||||
import { SwUpdatesModule } from 'app/sw-updates/sw-updates.module';
|
||||
|
||||
import { AppComponent } from 'app/app.component';
|
||||
import { ApiService } from 'app/embedded/api/api.service';
|
||||
import { EMBEDDED_COMPONENTS, EmbeddedComponentsMap } from 'app/embed-components/embed-components.service';
|
||||
import { CustomIconRegistry, SVG_ICONS } from 'app/shared/custom-icon-registry';
|
||||
import { Deployment } from 'app/shared/deployment.service';
|
||||
import { DocViewerComponent } from 'app/layout/doc-viewer/doc-viewer.component';
|
||||
import { DtComponent } from 'app/layout/doc-viewer/dt.component';
|
||||
import { ModeBannerComponent } from 'app/layout/mode-banner/mode-banner.component';
|
||||
import { EmbeddedModule } from 'app/embedded/embedded.module';
|
||||
import { GaService } from 'app/shared/ga.service';
|
||||
import { Logger } from 'app/shared/logger.service';
|
||||
import { LocationService } from 'app/shared/location.service';
|
||||
@ -47,11 +33,18 @@ import { NavMenuComponent } from 'app/layout/nav-menu/nav-menu.component';
|
||||
import { NavItemComponent } from 'app/layout/nav-item/nav-item.component';
|
||||
import { ScrollService } from 'app/shared/scroll.service';
|
||||
import { ScrollSpyService } from 'app/shared/scroll-spy.service';
|
||||
import { SearchBoxComponent } from './search/search-box/search-box.component';
|
||||
import { SearchBoxComponent } from 'app/search/search-box/search-box.component';
|
||||
import { TocComponent } from 'app/layout/toc/toc.component';
|
||||
import { TocService } from 'app/shared/toc.service';
|
||||
import { WindowToken, windowProvider } from 'app/shared/window';
|
||||
|
||||
import { EmbedComponentsModule } from 'app/embed-components/embed-components.module';
|
||||
import { SharedModule } from 'app/shared/shared.module';
|
||||
import { SwUpdatesModule } from 'app/sw-updates/sw-updates.module';
|
||||
|
||||
|
||||
// The path to the `EmbeddedModule`.
|
||||
const embeddedModulePath = 'app/embedded/embedded.module#EmbeddedModule';
|
||||
|
||||
// These are the hardcoded inline svg sources to be used by the `<mat-icon>` component
|
||||
export const svgIconProviders = [
|
||||
@ -78,15 +71,13 @@ export const svgIconProviders = [
|
||||
@NgModule({
|
||||
imports: [
|
||||
BrowserModule,
|
||||
EmbeddedModule,
|
||||
HttpClientModule,
|
||||
BrowserAnimationsModule,
|
||||
EmbedComponentsModule,
|
||||
HttpClientModule,
|
||||
MatButtonModule,
|
||||
MatIconModule,
|
||||
MatInputModule,
|
||||
MatProgressBarModule,
|
||||
MatSidenavModule,
|
||||
MatTabsModule,
|
||||
MatToolbarModule,
|
||||
SwUpdatesModule,
|
||||
SharedModule
|
||||
@ -100,10 +91,10 @@ export const svgIconProviders = [
|
||||
NavMenuComponent,
|
||||
NavItemComponent,
|
||||
SearchBoxComponent,
|
||||
TocComponent,
|
||||
TopMenuComponent,
|
||||
],
|
||||
providers: [
|
||||
ApiService,
|
||||
Deployment,
|
||||
DocumentService,
|
||||
GaService,
|
||||
@ -113,15 +104,32 @@ export const svgIconProviders = [
|
||||
LocationService,
|
||||
{ provide: MatIconRegistry, useClass: CustomIconRegistry },
|
||||
NavigationService,
|
||||
Platform,
|
||||
ScrollService,
|
||||
ScrollSpyService,
|
||||
SearchService,
|
||||
svgIconProviders,
|
||||
TocService,
|
||||
{ provide: WindowToken, useFactory: windowProvider },
|
||||
|
||||
{
|
||||
provide: EMBEDDED_COMPONENTS,
|
||||
useValue: {
|
||||
/* tslint:disable: max-line-length */
|
||||
'aio-toc': [TocComponent],
|
||||
'aio-api-list, aio-contributor-list, aio-file-not-found-search, aio-resource-list, code-example, code-tabs, current-location, live-example': embeddedModulePath,
|
||||
/* tslint:enable: max-line-length */
|
||||
} as EmbeddedComponentsMap,
|
||||
},
|
||||
{
|
||||
// This is currently the only way to get `@angular/cli`
|
||||
// to split `EmbeddedModule` into a separate chunk :(
|
||||
provide: ROUTES,
|
||||
useValue: [{ path: '/embedded', loadChildren: embeddedModulePath }],
|
||||
multi: true,
|
||||
},
|
||||
],
|
||||
bootstrap: [AppComponent]
|
||||
entryComponents: [ TocComponent ],
|
||||
bootstrap: [ AppComponent ]
|
||||
})
|
||||
export class AppModule {
|
||||
}
|
||||
|
13
aio/src/app/embed-components/embed-components.module.ts
Normal file
13
aio/src/app/embed-components/embed-components.module.ts
Normal file
@ -0,0 +1,13 @@
|
||||
import { NgModule, NgModuleFactoryLoader, SystemJsNgModuleLoader } from '@angular/core';
|
||||
|
||||
import { EmbedComponentsService } from './embed-components.service';
|
||||
|
||||
|
||||
@NgModule({
|
||||
providers: [
|
||||
EmbedComponentsService,
|
||||
{ provide: NgModuleFactoryLoader, useClass: SystemJsNgModuleLoader },
|
||||
],
|
||||
})
|
||||
export class EmbedComponentsModule {
|
||||
}
|
378
aio/src/app/embed-components/embed-components.service.spec.ts
Normal file
378
aio/src/app/embed-components/embed-components.service.spec.ts
Normal file
@ -0,0 +1,378 @@
|
||||
import { ComponentFactory, ComponentFactoryResolver, ComponentRef, NgModuleFactoryLoader } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import {
|
||||
MockNgModuleFactoryLoader, TestEmbedComponentsService, TestModule, mockEmbeddedModulePath,
|
||||
testEagerEmbeddedComponents, testEagerEmbeddedSelectors, testLazyEmbeddedComponents
|
||||
} from 'testing/embed-components-utils';
|
||||
import { EmbedComponentsService, ComponentsOrModulePath } from './embed-components.service';
|
||||
|
||||
|
||||
describe('EmbedComponentsService', () => {
|
||||
let service: TestEmbedComponentsService;
|
||||
let host: HTMLElement;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({imports: [TestModule]});
|
||||
|
||||
service = TestBed.get(EmbedComponentsService);
|
||||
host = document.createElement('div');
|
||||
});
|
||||
|
||||
it('should be instantiated', () => {
|
||||
expect(service).toEqual(jasmine.any(EmbedComponentsService));
|
||||
});
|
||||
|
||||
describe('#createComponentFactories()', () => {
|
||||
let factories: typeof service.componentFactories;
|
||||
let resolver: ComponentFactoryResolver;
|
||||
|
||||
const doCreateComponentFactories = () =>
|
||||
service.createComponentFactories(testEagerEmbeddedComponents, resolver);
|
||||
|
||||
beforeEach(() => {
|
||||
factories = service.componentFactories;
|
||||
resolver = TestBed.get(ComponentFactoryResolver) as ComponentFactoryResolver;
|
||||
});
|
||||
|
||||
it('should create a factory entry for each component', () => {
|
||||
expect(factories.size).toBe(0);
|
||||
|
||||
doCreateComponentFactories();
|
||||
expect(factories.size).toBe(testEagerEmbeddedComponents.length);
|
||||
});
|
||||
|
||||
it('should key the factory entries by selector', () => {
|
||||
doCreateComponentFactories();
|
||||
|
||||
const actualSelectors = Array.from(factories.keys());
|
||||
const expectedSelectors = testEagerEmbeddedSelectors;
|
||||
|
||||
expect(actualSelectors).toEqual(expectedSelectors);
|
||||
});
|
||||
|
||||
it('should store the projected content property name', () => {
|
||||
doCreateComponentFactories();
|
||||
|
||||
const actualContentPropNames = Array.from(factories.values()).map(x => x.contentPropertyName);
|
||||
const expectedContentPropNames = testEagerEmbeddedSelectors.map(x => service.selectorToContentPropertyName(x));
|
||||
|
||||
expect(actualContentPropNames).toEqual(expectedContentPropNames);
|
||||
});
|
||||
|
||||
it('should store the factory for each component', () => {
|
||||
doCreateComponentFactories();
|
||||
|
||||
const actualFactories = Array.from(factories.values()).map(x => x.factory);
|
||||
const expectedComponentTypes = testEagerEmbeddedComponents;
|
||||
|
||||
actualFactories.forEach((factory, i) => {
|
||||
expect(factory).toEqual(jasmine.any(ComponentFactory));
|
||||
expect(factory.componentType).toBe(expectedComponentTypes[i]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#createComponents()', () => {
|
||||
const FooComponent = testEagerEmbeddedComponents[0];
|
||||
const BarComponent = testEagerEmbeddedComponents[1];
|
||||
|
||||
beforeEach(() => service.prepareComponentFactories(testEagerEmbeddedComponents));
|
||||
|
||||
it('should apply all embedded components (and return the `ComponentRef`s)', () => {
|
||||
host.innerHTML = `
|
||||
<p>Header</p>
|
||||
<p><aio-eager-foo></aio-eager-foo></p>
|
||||
<p><aio-eager-bar></aio-eager-bar></p>
|
||||
<p>Footer</p>
|
||||
`;
|
||||
|
||||
const componentRefs = service.createComponents(host);
|
||||
|
||||
expect(host.innerHTML).toContain('Foo Component');
|
||||
expect(host.innerHTML).toContain('Bar Component');
|
||||
|
||||
expect(componentRefs.length).toBe(2);
|
||||
expect(componentRefs[0].instance).toEqual(jasmine.any(FooComponent));
|
||||
expect(componentRefs[1].instance).toEqual(jasmine.any(BarComponent));
|
||||
});
|
||||
|
||||
it('should apply embedded components to all matching elements', () => {
|
||||
host.innerHTML = `
|
||||
<p>Header</p>
|
||||
<p><aio-eager-foo></aio-eager-foo></p>
|
||||
<p><aio-eager-bar></aio-eager-bar></p>
|
||||
<p><aio-eager-foo></aio-eager-foo></p>
|
||||
<p><aio-eager-bar></aio-eager-bar></p>
|
||||
<p>Footer</p>
|
||||
`;
|
||||
|
||||
const componentRefs = service.createComponents(host);
|
||||
|
||||
expect(componentRefs.length).toBe(4);
|
||||
expect(componentRefs[0].instance).toEqual(jasmine.any(FooComponent));
|
||||
expect(componentRefs[1].instance).toEqual(jasmine.any(FooComponent));
|
||||
expect(componentRefs[2].instance).toEqual(jasmine.any(BarComponent));
|
||||
expect(componentRefs[3].instance).toEqual(jasmine.any(BarComponent));
|
||||
});
|
||||
|
||||
it('should allow projecting content by assigning it on the element', () => {
|
||||
const projectedContent = 'Projected content';
|
||||
host.innerHTML = `
|
||||
<p>Header</p>
|
||||
<p><aio-eager-bar>${projectedContent}</aio-eager-bar></p>
|
||||
<p>Footer</p>
|
||||
`;
|
||||
|
||||
const componentRefs = service.createComponents(host);
|
||||
componentRefs[0].changeDetectorRef.detectChanges();
|
||||
|
||||
const barEl = host.querySelector('aio-eager-bar');
|
||||
|
||||
expect(barEl['aioEagerBarContent']).toBe(projectedContent);
|
||||
expect(barEl.innerHTML).toContain(projectedContent);
|
||||
});
|
||||
|
||||
// Because `FooComponent` is processed before `BarComponent`...
|
||||
it('should apply `FooComponent` within `BarComponent`', () => {
|
||||
host.innerHTML = `
|
||||
<aio-eager-bar>
|
||||
<aio-eager-foo></aio-eager-foo>
|
||||
</aio-eager-bar>
|
||||
`;
|
||||
|
||||
const componentRefs = service.createComponents(host);
|
||||
componentRefs.forEach(ref => ref.changeDetectorRef.detectChanges());
|
||||
|
||||
expect(host.innerHTML).toContain('Foo Component');
|
||||
expect(host.innerHTML).toContain('Bar Component');
|
||||
|
||||
expect(componentRefs.length).toBe(2);
|
||||
expect(componentRefs[0].instance).toEqual(jasmine.any(FooComponent));
|
||||
expect(componentRefs[1].instance).toEqual(jasmine.any(BarComponent));
|
||||
});
|
||||
|
||||
// Because `BarComponent` is processed after `FooComponent`...
|
||||
it('should not apply `BarComponent` within `FooComponent`', () => {
|
||||
host.innerHTML = `
|
||||
<aio-eager-foo>
|
||||
<aio-eager-bar></aio-eager-bar>
|
||||
</aio-eager-foo>
|
||||
`;
|
||||
|
||||
const componentRefs = service.createComponents(host);
|
||||
componentRefs.forEach(ref => ref.changeDetectorRef.detectChanges());
|
||||
|
||||
expect(host.innerHTML).toContain('Foo Component');
|
||||
expect(host.innerHTML).not.toContain('Bar Component');
|
||||
|
||||
expect(componentRefs.length).toBe(1);
|
||||
expect(componentRefs[0].instance).toEqual(jasmine.any(FooComponent));
|
||||
});
|
||||
});
|
||||
|
||||
describe('#embedInto()', () => {
|
||||
let mockComponentRefs: ComponentRef<any>[];
|
||||
let createComponentsSpy: jasmine.Spy;
|
||||
let prepareComponentFactoriesSpy: jasmine.Spy;
|
||||
|
||||
const doEmbed = (contents: string) =>
|
||||
new Promise<ComponentRef<any>[]>((resolve, reject) => {
|
||||
host.innerHTML = contents;
|
||||
service.embedInto(host).subscribe(resolve, reject);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
mockComponentRefs = [{foo: true}, {bar: true}] as any as ComponentRef<any>[];
|
||||
|
||||
createComponentsSpy = spyOn(service, 'createComponents').and.returnValue(mockComponentRefs);
|
||||
prepareComponentFactoriesSpy = spyOn(service, 'prepareComponentFactories')
|
||||
.and.returnValue(Promise.resolve());
|
||||
});
|
||||
|
||||
it('should return an observable', done => {
|
||||
service.embedInto(host).subscribe(done, done.fail);
|
||||
});
|
||||
|
||||
describe('(preparing component factories)', () => {
|
||||
it('should return an array of `ComponentRef`s', async () => {
|
||||
// When there are embedded components.
|
||||
expect(await doEmbed('<aio-eager-foo></aio-eager-foo>')).toEqual(mockComponentRefs);
|
||||
expect(await doEmbed('<aio-lazy-bar></aio-lazy-bar>')).toEqual(mockComponentRefs);
|
||||
|
||||
// When there are no embedded components.
|
||||
expect(await doEmbed('<div>Test</div>')).toEqual([]);
|
||||
expect(await doEmbed('')).toEqual([]);
|
||||
});
|
||||
|
||||
it('should prepare all component factories if there are embedded components', async () => {
|
||||
await doEmbed(`
|
||||
<div><aio-eager-foo><b>foo</b></aio-eager-foo></div>
|
||||
<span><aio-lazy-foo><i>bar</i></aio-lazy-foo></span>
|
||||
`);
|
||||
|
||||
expect(prepareComponentFactoriesSpy).toHaveBeenCalledTimes(2);
|
||||
expect(prepareComponentFactoriesSpy).toHaveBeenCalledWith(testEagerEmbeddedComponents);
|
||||
expect(prepareComponentFactoriesSpy).toHaveBeenCalledWith(mockEmbeddedModulePath);
|
||||
});
|
||||
|
||||
it('should only prepare the necessary factories', async () => {
|
||||
await doEmbed('<aio-eager-foo>Eager only</aio-eager-foo>');
|
||||
expect(prepareComponentFactoriesSpy).toHaveBeenCalledTimes(1);
|
||||
expect(prepareComponentFactoriesSpy).toHaveBeenCalledWith(testEagerEmbeddedComponents);
|
||||
|
||||
await doEmbed('<aio-lazy-foo>Lazy only</aio-lazy-foo>');
|
||||
expect(prepareComponentFactoriesSpy).toHaveBeenCalledTimes(2);
|
||||
expect(prepareComponentFactoriesSpy).toHaveBeenCalledWith(mockEmbeddedModulePath);
|
||||
});
|
||||
|
||||
it('should not load embedded components if the document does not contain any', async () => {
|
||||
await doEmbed('');
|
||||
await doEmbed('<no-aio-eager-foo></no-aio-eager-foo>');
|
||||
await doEmbed('<no-aio-lazy-foo></no-aio-lazy-foo>');
|
||||
|
||||
expect(prepareComponentFactoriesSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('(creating embedded components)', () => {
|
||||
it('should create embedded components if the element contains any', async () => {
|
||||
await doEmbed('<div><aio-eager-foo><i>blah</i></aio-eager-foo></div>');
|
||||
|
||||
expect(createComponentsSpy).toHaveBeenCalledTimes(1);
|
||||
expect(prepareComponentFactoriesSpy).toHaveBeenCalledBefore(createComponentsSpy);
|
||||
|
||||
prepareComponentFactoriesSpy.calls.reset();
|
||||
createComponentsSpy.calls.reset();
|
||||
|
||||
await doEmbed('<aio-lazy-bar><i>blah</i></aio-lazy-bar>');
|
||||
expect(createComponentsSpy).toHaveBeenCalledTimes(1);
|
||||
expect(prepareComponentFactoriesSpy).toHaveBeenCalledBefore(createComponentsSpy);
|
||||
});
|
||||
|
||||
it('should emit the created embedded components', async () => {
|
||||
const componentRefs = await doEmbed('<aio-eager-foo></aio-eager-foo>');
|
||||
expect(componentRefs).toBe(mockComponentRefs);
|
||||
});
|
||||
|
||||
it('should not create embedded components if the element does not contain any', async () => {
|
||||
await doEmbed(`
|
||||
<aio-eager-foo-not></aio-eager-foo-not>
|
||||
<aio-lazy-bar></aio-lazy-bar>
|
||||
`);
|
||||
expect(createComponentsSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not create embedded components if the document is empty', async () => {
|
||||
await doEmbed('');
|
||||
expect(createComponentsSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not create embedded components if unsubscribed from', async () => {
|
||||
const preparePromise = Promise.resolve();
|
||||
prepareComponentFactoriesSpy.and.returnValue(preparePromise);
|
||||
|
||||
// When not unsubscribed from...
|
||||
host.innerHTML = '<aio-eager-foo></aio-eager-foo>';
|
||||
service.embedInto(host).subscribe();
|
||||
await new Promise(resolve => setTimeout(resolve));
|
||||
expect(createComponentsSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
createComponentsSpy.calls.reset();
|
||||
|
||||
// When unsubscribed from...
|
||||
host.innerHTML = '<aio-eager-foo></aio-eager-foo>';
|
||||
service.embedInto(host).subscribe().unsubscribe();
|
||||
await new Promise(resolve => setTimeout(resolve));
|
||||
expect(createComponentsSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#prepareComponentFactories()', () => {
|
||||
let loader: MockNgModuleFactoryLoader;
|
||||
let resolver: ComponentFactoryResolver;
|
||||
let createComponentFactoriesSpy: jasmine.Spy;
|
||||
|
||||
beforeEach(() => {
|
||||
loader = TestBed.get(NgModuleFactoryLoader);
|
||||
resolver = TestBed.get(ComponentFactoryResolver);
|
||||
|
||||
createComponentFactoriesSpy = spyOn(service, 'createComponentFactories');
|
||||
});
|
||||
|
||||
[testLazyEmbeddedComponents, mockEmbeddedModulePath].forEach((compsOrPath: ComponentsOrModulePath) => {
|
||||
const useComponents = Array.isArray(compsOrPath);
|
||||
|
||||
describe(`(using ${useComponents ? 'component types' : 'module path'})`, () => {
|
||||
const doPrepareComponentFactories = () =>
|
||||
service.prepareComponentFactories(compsOrPath);
|
||||
|
||||
it('should return a promise', done => {
|
||||
doPrepareComponentFactories().then(done, done.fail);
|
||||
});
|
||||
|
||||
it('should create the component factories', async () => {
|
||||
expect(createComponentFactoriesSpy).not.toHaveBeenCalled();
|
||||
|
||||
await doPrepareComponentFactories();
|
||||
expect(createComponentFactoriesSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
const args = createComponentFactoriesSpy.calls.mostRecent().args;
|
||||
expect(args[0]).toBe(testLazyEmbeddedComponents);
|
||||
|
||||
if (useComponents) {
|
||||
expect(args[1]).toBe(resolver);
|
||||
} else {
|
||||
expect(args[1]).not.toBe(resolver);
|
||||
}
|
||||
});
|
||||
|
||||
it('should not create create the component factories more than once', async () => {
|
||||
const results = await Promise.all([
|
||||
doPrepareComponentFactories(),
|
||||
doPrepareComponentFactories(),
|
||||
]);
|
||||
|
||||
expect(createComponentFactoriesSpy).toHaveBeenCalledTimes(1);
|
||||
expect(results[1]).toBe(results[0]);
|
||||
|
||||
const anotherResult = await doPrepareComponentFactories();
|
||||
|
||||
expect(createComponentFactoriesSpy).toHaveBeenCalledTimes(1);
|
||||
expect(anotherResult).toBe(results[0]);
|
||||
});
|
||||
|
||||
it(`should ${useComponents ? 'not load' : 'load'} the embedded module`, async () => {
|
||||
expect(loader.loadedPaths).toEqual([]);
|
||||
|
||||
await doPrepareComponentFactories();
|
||||
const expectedLoadedPaths = useComponents ? [] : [mockEmbeddedModulePath];
|
||||
|
||||
expect(loader.loadedPaths).toEqual(expectedLoadedPaths);
|
||||
});
|
||||
|
||||
it(`should not load the embedded module more than once`, async () => {
|
||||
await Promise.all([
|
||||
doPrepareComponentFactories(),
|
||||
doPrepareComponentFactories(),
|
||||
]);
|
||||
const loadedPathCount = loader.loadedPaths.length;
|
||||
|
||||
expect(loadedPathCount).toBeLessThan(2);
|
||||
|
||||
await doPrepareComponentFactories();
|
||||
|
||||
expect(loader.loadedPaths.length).toBe(loadedPathCount);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#selectorToContentPropertyName()', () => {
|
||||
it('should convert an element selector to a property name', () => {
|
||||
expect(service.selectorToContentPropertyName('foobar')).toBe('foobarContent');
|
||||
expect(service.selectorToContentPropertyName('baz-qux')).toBe('bazQuxContent');
|
||||
});
|
||||
});
|
||||
});
|
154
aio/src/app/embed-components/embed-components.service.ts
Normal file
154
aio/src/app/embed-components/embed-components.service.ts
Normal file
@ -0,0 +1,154 @@
|
||||
import {
|
||||
ComponentFactory, ComponentFactoryResolver, ComponentRef, Inject, Injectable, InjectionToken,
|
||||
Injector, NgModuleFactory, NgModuleFactoryLoader, Type
|
||||
} from '@angular/core';
|
||||
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
import { of } from 'rxjs/observable/of';
|
||||
import 'rxjs/add/operator/switchMap';
|
||||
|
||||
|
||||
export interface EmbeddedComponentFactory {
|
||||
contentPropertyName: string;
|
||||
factory: ComponentFactory<any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A mapping from combined component selectors (keys) to the corresponding components (values). The
|
||||
* components can be specified either as a list of embedded components or a path to a module that
|
||||
* provides embedded components (i.e. implements `WithEmbeddedComponents`).
|
||||
*/
|
||||
export interface EmbeddedComponentsMap {
|
||||
[multiSelector: string]: ComponentsOrModulePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface expected to be implemented by all modules that contribute components to the
|
||||
* `EmbeddedComponentsMap`.
|
||||
*/
|
||||
export interface WithEmbeddedComponents {
|
||||
embeddedComponents: Type<any>[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Either an array of components or the path to a module that implements `WithEmbeddedComponents`.
|
||||
*/
|
||||
export type ComponentsOrModulePath = Type<any>[] | string;
|
||||
|
||||
/**
|
||||
* The injection token for the `EmbeddedComponentsMap`.
|
||||
*/
|
||||
export const EMBEDDED_COMPONENTS = new InjectionToken<EmbeddedComponentsMap>('EMBEDDED_COMPONENTS');
|
||||
|
||||
/**
|
||||
* Embed components into an element. It takes care of indentifying the embedded components, loading
|
||||
* the necessary modules and instantiating the components.
|
||||
*
|
||||
* Embeddable components are identified and loaded based on the info in `EmbeddedComponentsMap`
|
||||
* (provided through dependency injection).
|
||||
*
|
||||
* The caller is responsible for trigering change detection and destroying the components as
|
||||
* necessary.
|
||||
*/
|
||||
@Injectable()
|
||||
export class EmbedComponentsService {
|
||||
private componentFactoriesReady = new Map<ComponentsOrModulePath, Promise<void>>();
|
||||
protected componentFactories = new Map<string, EmbeddedComponentFactory>();
|
||||
|
||||
constructor(
|
||||
private injector: Injector,
|
||||
private loader: NgModuleFactoryLoader,
|
||||
private resolver: ComponentFactoryResolver,
|
||||
@Inject(EMBEDDED_COMPONENTS) private embeddedComponentsMap: EmbeddedComponentsMap) { }
|
||||
|
||||
/**
|
||||
* Embed components into the specified element:
|
||||
* - Load the necessary modules (if any).
|
||||
* - Prepare the component factories.
|
||||
* - Instantiate the components.
|
||||
*
|
||||
* Return the list of `ComponentRef`s.
|
||||
*/
|
||||
embedInto(elem: HTMLElement): Observable<ComponentRef<any>[]> {
|
||||
const requiredComponents = Object.keys(this.embeddedComponentsMap)
|
||||
.filter(selector => elem.querySelector(selector))
|
||||
.map(selector => this.embeddedComponentsMap[selector]);
|
||||
|
||||
const factoriesReady = requiredComponents.map(compsOrPath => this.prepareComponentFactories(compsOrPath));
|
||||
|
||||
return !requiredComponents.length
|
||||
? of([])
|
||||
: of(undefined)
|
||||
.switchMap(() => Promise.all(factoriesReady))
|
||||
.switchMap(() => [this.createComponents(elem)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the embedded component factories (which will later be used to instantiate components).
|
||||
*/
|
||||
protected createComponentFactories(components: Type<any>[], resolver: ComponentFactoryResolver): void {
|
||||
for (const comp of components) {
|
||||
const factory = resolver.resolveComponentFactory(comp);
|
||||
const selector = factory.selector;
|
||||
const contentPropertyName = this.selectorToContentPropertyName(selector);
|
||||
this.componentFactories.set(selector, {contentPropertyName, factory});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiate embedded components for the current contents of `elem`.
|
||||
* (Store the original HTML contents of each element on the corresponding property for later
|
||||
* retrieval by the component instance.)
|
||||
*/
|
||||
protected createComponents(elem: HTMLElement): ComponentRef<any>[] {
|
||||
const componentRefs: ComponentRef<any>[] = [];
|
||||
|
||||
this.componentFactories.forEach(({contentPropertyName, factory}, selector) => {
|
||||
const componentHosts = elem.querySelectorAll(selector);
|
||||
|
||||
// Cast due to https://github.com/Microsoft/TypeScript/issues/4947.
|
||||
for (const host of componentHosts as any as HTMLElement[]) {
|
||||
// Hack: Preserve the current element content, because the factory will empty it out.
|
||||
// Security: The source of this `innerHTML` should always be authored by the documentation
|
||||
// team and is considered to be safe.
|
||||
host[contentPropertyName] = host.innerHTML;
|
||||
componentRefs.push(factory.create(this.injector, [], host));
|
||||
}
|
||||
});
|
||||
|
||||
return componentRefs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the component factories for the given components.
|
||||
* If necessary, load and instantiate the module first.
|
||||
*/
|
||||
protected prepareComponentFactories(compsOrPath: ComponentsOrModulePath): Promise<void> {
|
||||
if (!this.componentFactoriesReady.has(compsOrPath)) {
|
||||
const componentsAndResolverPromise = (typeof compsOrPath !== 'string')
|
||||
? Promise.resolve({components: compsOrPath, resolver: this.resolver})
|
||||
: this.loader.load(compsOrPath).then((ngModuleFactory: NgModuleFactory<WithEmbeddedComponents>) => {
|
||||
const moduleRef = ngModuleFactory.create(this.injector);
|
||||
return {
|
||||
components: moduleRef.instance.embeddedComponents,
|
||||
resolver: moduleRef.componentFactoryResolver,
|
||||
};
|
||||
});
|
||||
|
||||
const readyPromise = componentsAndResolverPromise
|
||||
.then(({components, resolver}) => this.createComponentFactories(components, resolver));
|
||||
|
||||
this.componentFactoriesReady.set(compsOrPath, readyPromise);
|
||||
}
|
||||
|
||||
return this.componentFactoriesReady.get(compsOrPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the component content property name by converting the selector to camelCase and
|
||||
* appending `Content`, e.g. `live-example` => `liveExampleContent`.
|
||||
*/
|
||||
protected selectorToContentPropertyName(selector: string): string {
|
||||
return selector.replace(/-(.)/g, (match, $1) => $1.toUpperCase()) + 'Content';
|
||||
}
|
||||
}
|
@ -43,15 +43,15 @@ export class ApiListComponent implements OnInit {
|
||||
// API types
|
||||
types: Option[] = [
|
||||
{ value: 'all', title: 'All' },
|
||||
{ value: 'directive', title: 'Directive' },
|
||||
{ value: 'pipe', title: 'Pipe'},
|
||||
{ value: 'decorator', title: 'Decorator' },
|
||||
{ value: 'class', title: 'Class' },
|
||||
{ value: 'interface', title: 'Interface' },
|
||||
{ value: 'function', title: 'Function' },
|
||||
{ value: 'const', title: 'Const'},
|
||||
{ value: 'decorator', title: 'Decorator' },
|
||||
{ value: 'directive', title: 'Directive' },
|
||||
{ value: 'enum', title: 'Enum' },
|
||||
{ value: 'type-alias', title: 'Type Alias' },
|
||||
{ value: 'const', title: 'Const'}
|
||||
{ value: 'function', title: 'Function' },
|
||||
{ value: 'interface', title: 'Interface' },
|
||||
{ value: 'pipe', title: 'Pipe'},
|
||||
{ value: 'type-alias', title: 'Type Alias' }
|
||||
];
|
||||
|
||||
statuses: Option[] = [
|
||||
|
@ -2,7 +2,7 @@ import { Component, ElementRef, ViewChild, OnChanges, Input } from '@angular/cor
|
||||
import { Logger } from 'app/shared/logger.service';
|
||||
import { PrettyPrinter } from './pretty-printer.service';
|
||||
import { CopierService } from 'app/shared/copier.service';
|
||||
import { MatSnackBar } from '@angular/material';
|
||||
import { MatSnackBar } from '@angular/material/snack-bar';
|
||||
|
||||
const defaultLineNumsCount = 10; // by default, show linenums over this number
|
||||
|
||||
|
@ -1,20 +1,24 @@
|
||||
import { NgModule } from '@angular/core';
|
||||
import { NgModule, Type } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
import { ContributorService } from './contributor/contributor.service';
|
||||
import { CopierService } from 'app/shared/copier.service';
|
||||
import { PrettyPrinter } from './code/pretty-printer.service';
|
||||
import { WithEmbeddedComponents } from 'app/embed-components/embed-components.service';
|
||||
|
||||
// Any components that we want to use inside embedded components must be declared or imported here
|
||||
// It is not enough just to import them inside the AppModule
|
||||
|
||||
// Reusable components (used inside embedded components)
|
||||
import { MatIconModule, MatSnackBarModule, MatTabsModule } from '@angular/material';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatSnackBarModule } from '@angular/material/snack-bar';
|
||||
import { MatTabsModule } from '@angular/material/tabs';
|
||||
import { CodeComponent } from './code/code.component';
|
||||
import { SharedModule } from 'app/shared/shared.module';
|
||||
|
||||
// Embedded Components
|
||||
import { ApiListComponent } from './api/api-list.component';
|
||||
import { ApiService } from './api/api.service';
|
||||
import { CodeExampleComponent } from './code/code-example.component';
|
||||
import { CodeTabsComponent } from './code/code-tabs.component';
|
||||
import { ContributorListComponent } from './contributor/contributor-list.component';
|
||||
@ -24,22 +28,16 @@ import { FileNotFoundSearchComponent } from './search/file-not-found-search.comp
|
||||
import { LiveExampleComponent, EmbeddedPlunkerComponent } from './live-example/live-example.component';
|
||||
import { ResourceListComponent } from './resource/resource-list.component';
|
||||
import { ResourceService } from './resource/resource.service';
|
||||
import { TocComponent } from './toc/toc.component';
|
||||
|
||||
/** Components that can be embedded in docs
|
||||
/**
|
||||
* Components that can be embedded in docs,
|
||||
* such as CodeExampleComponent, LiveExampleComponent,...
|
||||
*/
|
||||
export const embeddedComponents: any[] = [
|
||||
export const embeddedComponents: Type<any>[] = [
|
||||
ApiListComponent, CodeExampleComponent, CodeTabsComponent, ContributorListComponent,
|
||||
CurrentLocationComponent, FileNotFoundSearchComponent, LiveExampleComponent, ResourceListComponent,
|
||||
TocComponent
|
||||
CurrentLocationComponent, FileNotFoundSearchComponent, LiveExampleComponent, ResourceListComponent
|
||||
];
|
||||
|
||||
/** Injectable class w/ property returning components that can be embedded in docs */
|
||||
export class EmbeddedComponents {
|
||||
components = embeddedComponents;
|
||||
}
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
CommonModule,
|
||||
@ -54,16 +52,15 @@ export class EmbeddedComponents {
|
||||
ContributorComponent,
|
||||
EmbeddedPlunkerComponent
|
||||
],
|
||||
exports: [
|
||||
TocComponent
|
||||
],
|
||||
providers: [
|
||||
ApiService,
|
||||
ContributorService,
|
||||
CopierService,
|
||||
EmbeddedComponents,
|
||||
PrettyPrinter,
|
||||
ResourceService
|
||||
],
|
||||
entryComponents: [ embeddedComponents ]
|
||||
})
|
||||
export class EmbeddedModule { }
|
||||
export class EmbeddedModule implements WithEmbeddedComponents {
|
||||
embeddedComponents = embeddedComponents;
|
||||
}
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -1,18 +1,22 @@
|
||||
import {
|
||||
Component, ComponentFactory, ComponentFactoryResolver, ComponentRef,
|
||||
DoCheck, ElementRef, EventEmitter, Injector, Input, OnDestroy,
|
||||
Output
|
||||
} from '@angular/core';
|
||||
|
||||
import { EmbeddedComponents } from 'app/embedded/embedded.module';
|
||||
import { DocumentContents } from 'app/documents/document.service';
|
||||
import { Component, ComponentRef, DoCheck, ElementRef, EventEmitter, Input, OnDestroy, Output } from '@angular/core';
|
||||
import { Title } from '@angular/platform-browser';
|
||||
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
import { of } from 'rxjs/observable/of';
|
||||
import { timer } from 'rxjs/observable/timer';
|
||||
import 'rxjs/add/operator/catch';
|
||||
import 'rxjs/add/operator/do';
|
||||
import 'rxjs/add/operator/switchMap';
|
||||
import 'rxjs/add/operator/takeUntil';
|
||||
|
||||
import { DocumentContents } from 'app/documents/document.service';
|
||||
import { EmbedComponentsService } from 'app/embed-components/embed-components.service';
|
||||
import { Logger } from 'app/shared/logger.service';
|
||||
import { TocService } from 'app/shared/toc.service';
|
||||
|
||||
interface EmbeddedComponentFactory {
|
||||
contentPropertyName: string;
|
||||
factory: ComponentFactory<any>;
|
||||
}
|
||||
|
||||
// Constants
|
||||
export const NO_ANIMATIONS = 'no-animations';
|
||||
|
||||
// Initialization prevents flicker once pre-rendering is on
|
||||
const initialDocViewerElement = document.querySelector('aio-doc-viewer');
|
||||
@ -25,19 +29,48 @@ const initialDocViewerContent = initialDocViewerElement ? initialDocViewerElemen
|
||||
// encapsulation: ViewEncapsulation.Native
|
||||
})
|
||||
export class DocViewerComponent implements DoCheck, OnDestroy {
|
||||
// Enable/Disable view transition animations.
|
||||
static animationsEnabled = true;
|
||||
|
||||
private embeddedComponents: ComponentRef<any>[] = [];
|
||||
private embeddedComponentFactories: Map<string, EmbeddedComponentFactory> = new Map();
|
||||
private hostElement: HTMLElement;
|
||||
|
||||
@Output()
|
||||
docRendered = new EventEmitter();
|
||||
private void$ = of<void>(undefined);
|
||||
private onDestroy$ = new EventEmitter<void>();
|
||||
private docContents$ = new EventEmitter<DocumentContents>();
|
||||
|
||||
protected embeddedComponentRefs: ComponentRef<any>[] = [];
|
||||
protected currViewContainer: HTMLElement = document.createElement('div');
|
||||
protected nextViewContainer: HTMLElement = document.createElement('div');
|
||||
|
||||
@Input()
|
||||
set doc(newDoc: DocumentContents) {
|
||||
// Ignore `undefined` values that could happen if the host component
|
||||
// does not initially specify a value for the `doc` input.
|
||||
if (newDoc) {
|
||||
this.docContents$.emit(newDoc);
|
||||
}
|
||||
}
|
||||
|
||||
// The new document is ready to be inserted into the viewer.
|
||||
// (Embedded components have been loaded and instantiated, if necessary.)
|
||||
@Output() docReady = new EventEmitter<void>();
|
||||
|
||||
// The previous document has been removed from the viewer.
|
||||
// (The leaving animation (if any) has been completed and the node has been removed from the DOM.)
|
||||
@Output() docRemoved = new EventEmitter<void>();
|
||||
|
||||
// The new document has been inserted into the viewer.
|
||||
// (The node has been inserted into the DOM, but the entering animation may still be in progress.)
|
||||
@Output() docInserted = new EventEmitter<void>();
|
||||
|
||||
// The new document has been fully rendered into the viewer.
|
||||
// (The entering animation has been completed.)
|
||||
@Output() docRendered = new EventEmitter<void>();
|
||||
|
||||
constructor(
|
||||
componentFactoryResolver: ComponentFactoryResolver,
|
||||
elementRef: ElementRef,
|
||||
embeddedComponents: EmbeddedComponents,
|
||||
private injector: Injector,
|
||||
private embedComponentsService: EmbedComponentsService,
|
||||
private logger: Logger,
|
||||
private titleService: Title,
|
||||
private tocService: TocService
|
||||
) {
|
||||
@ -45,84 +78,158 @@ export class DocViewerComponent implements DoCheck, OnDestroy {
|
||||
// Security: the initialDocViewerContent comes from the prerendered DOM and is considered to be secure
|
||||
this.hostElement.innerHTML = initialDocViewerContent;
|
||||
|
||||
for (const component of embeddedComponents.components) {
|
||||
const factory = componentFactoryResolver.resolveComponentFactory(component);
|
||||
const selector = factory.selector;
|
||||
const contentPropertyName = this.selectorToContentPropertyName(selector);
|
||||
this.embeddedComponentFactories.set(selector, { contentPropertyName, factory });
|
||||
}
|
||||
}
|
||||
|
||||
@Input()
|
||||
set doc(newDoc: DocumentContents) {
|
||||
this.ngOnDestroy();
|
||||
if (newDoc) {
|
||||
this.build(newDoc);
|
||||
this.docRendered.emit();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add doc content to host element and build it out with embedded components
|
||||
*/
|
||||
private build(doc: DocumentContents) {
|
||||
|
||||
// security: the doc.content is always authored by the documentation team
|
||||
// and is considered to be safe
|
||||
this.hostElement.innerHTML = doc.contents || '';
|
||||
|
||||
if (!doc.contents) { return; }
|
||||
|
||||
this.addTitleAndToc(doc.id);
|
||||
|
||||
// TODO(i): why can't I use for-of? why doesn't typescript like Map#value() iterators?
|
||||
this.embeddedComponentFactories.forEach(({ contentPropertyName, factory }, selector) => {
|
||||
const embeddedComponentElements = this.hostElement.querySelectorAll(selector);
|
||||
|
||||
// cast due to https://github.com/Microsoft/TypeScript/issues/4947
|
||||
for (const element of embeddedComponentElements as any as HTMLElement[]){
|
||||
// hack: preserve the current element content because the factory will empty it out
|
||||
// security: the source of this innerHTML is always authored by the documentation team
|
||||
// and is considered to be safe
|
||||
element[contentPropertyName] = element.innerHTML;
|
||||
this.embeddedComponents.push(factory.create(this.injector, [], element));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private addTitleAndToc(docId: string) {
|
||||
this.tocService.reset();
|
||||
const titleEl = this.hostElement.querySelector('h1');
|
||||
let title = '';
|
||||
|
||||
// Only create TOC for docs with an <h1> title
|
||||
// If you don't want a TOC, add "no-toc" class to <h1>
|
||||
if (titleEl) {
|
||||
title = (typeof titleEl.innerText === 'string') ? titleEl.innerText : titleEl.textContent;
|
||||
if (!/(no-toc|notoc)/i.test(titleEl.className)) {
|
||||
this.tocService.genToc(this.hostElement, docId);
|
||||
titleEl.insertAdjacentHTML('afterend', '<aio-toc class="embedded"></aio-toc>');
|
||||
}
|
||||
if (this.hostElement.firstElementChild) {
|
||||
this.currViewContainer = this.hostElement.firstElementChild as HTMLElement;
|
||||
}
|
||||
|
||||
this.titleService.setTitle(title ? `Angular - ${title}` : 'Angular');
|
||||
this.onDestroy$.subscribe(() => this.destroyEmbeddedComponents());
|
||||
this.docContents$
|
||||
.switchMap(newDoc => this.render(newDoc))
|
||||
.takeUntil(this.onDestroy$)
|
||||
.subscribe();
|
||||
}
|
||||
|
||||
ngDoCheck() {
|
||||
this.embeddedComponents.forEach(comp => comp.changeDetectorRef.detectChanges());
|
||||
this.embeddedComponentRefs.forEach(comp => comp.changeDetectorRef.detectChanges());
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
// destroy these components else there will be memory leaks
|
||||
this.embeddedComponents.forEach(comp => comp.destroy());
|
||||
this.embeddedComponents.length = 0;
|
||||
this.onDestroy$.emit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the component content property name by converting the selector to camelCase and appending
|
||||
* 'Content', e.g. live-example => liveExampleContent
|
||||
* Destroy the embedded components to avoid memory leaks.
|
||||
*/
|
||||
private selectorToContentPropertyName(selector: string) {
|
||||
return selector.replace(/-(.)/g, (match, $1) => $1.toUpperCase()) + 'Content';
|
||||
protected destroyEmbeddedComponents(): void {
|
||||
this.embeddedComponentRefs.forEach(comp => comp.destroy());
|
||||
this.embeddedComponentRefs = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare for setting the window title and ToC.
|
||||
* Return a function to actually set them.
|
||||
*/
|
||||
protected prepareTitleAndToc(targetElem: HTMLElement, docId: string): () => void {
|
||||
const titleEl = targetElem.querySelector('h1');
|
||||
const hasToc = !!titleEl && !/no-?toc/i.test(titleEl.className);
|
||||
|
||||
if (hasToc) {
|
||||
titleEl.insertAdjacentHTML('afterend', '<aio-toc class="embedded"></aio-toc>');
|
||||
}
|
||||
|
||||
return () => {
|
||||
this.tocService.reset();
|
||||
let title = '';
|
||||
|
||||
// Only create ToC for docs with an `<h1>` heading.
|
||||
// If you don't want a ToC, add "no-toc" class to `<h1>`.
|
||||
if (titleEl) {
|
||||
title = (typeof titleEl.innerText === 'string') ? titleEl.innerText : titleEl.textContent;
|
||||
|
||||
if (hasToc) {
|
||||
this.tocService.genToc(targetElem, docId);
|
||||
}
|
||||
}
|
||||
|
||||
this.titleService.setTitle(title ? `Angular - ${title}` : 'Angular');
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Add doc content to host element and build it out with embedded components.
|
||||
*/
|
||||
protected render(doc: DocumentContents): Observable<void> {
|
||||
let addTitleAndToc: () => void;
|
||||
|
||||
return this.void$
|
||||
// Security: `doc.contents` is always authored by the documentation team
|
||||
// and is considered to be safe.
|
||||
.do(() => this.nextViewContainer.innerHTML = doc.contents || '')
|
||||
.do(() => addTitleAndToc = this.prepareTitleAndToc(this.nextViewContainer, doc.id))
|
||||
.switchMap(() => this.embedComponentsService.embedInto(this.nextViewContainer))
|
||||
.do(() => this.docReady.emit())
|
||||
.do(() => this.destroyEmbeddedComponents())
|
||||
.do(componentRefs => this.embeddedComponentRefs = componentRefs)
|
||||
.switchMap(() => this.swapViews(addTitleAndToc))
|
||||
.do(() => this.docRendered.emit())
|
||||
.catch(err => {
|
||||
const errorMessage = (err instanceof Error) ? err.stack : err;
|
||||
this.logger.error(`[DocViewer] Error preparing document '${doc.id}': ${errorMessage}`);
|
||||
this.nextViewContainer.innerHTML = '';
|
||||
return this.void$;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Swap the views, removing `currViewContainer` and inserting `nextViewContainer`.
|
||||
* (At this point all content should be ready, including having loaded and instantiated embedded
|
||||
* components.)
|
||||
*
|
||||
* Optionally, run a callback as soon as `nextViewContainer` has been inserted, but before the
|
||||
* entering animation has been completed. This is useful for work that needs to be done as soon as
|
||||
* the element has been attached to the DOM.
|
||||
*/
|
||||
protected swapViews(onInsertedCb = () => undefined): Observable<void> {
|
||||
const raf$ = new Observable<void>(subscriber => {
|
||||
const rafId = requestAnimationFrame(() => {
|
||||
subscriber.next();
|
||||
subscriber.complete();
|
||||
});
|
||||
return () => cancelAnimationFrame(rafId);
|
||||
});
|
||||
|
||||
// Get the actual transition duration (taking global styles into account).
|
||||
// According to the [CSSOM spec](https://drafts.csswg.org/cssom/#serializing-css-values),
|
||||
// `time` values should be returned in seconds.
|
||||
const getActualDuration = (elem: HTMLElement) => {
|
||||
const cssValue = getComputedStyle(elem).transitionDuration;
|
||||
const seconds = Number(cssValue.replace(/s$/, ''));
|
||||
return 1000 * seconds;
|
||||
};
|
||||
const animateProp =
|
||||
(elem: HTMLElement, prop: string, from: string, to: string, duration = 200) => {
|
||||
const animationsDisabled = !DocViewerComponent.animationsEnabled
|
||||
|| this.hostElement.classList.contains(NO_ANIMATIONS);
|
||||
|
||||
elem.style.transition = '';
|
||||
return animationsDisabled
|
||||
? this.void$.do(() => elem.style[prop] = to)
|
||||
: this.void$
|
||||
// In order to ensure that the `from` value will be applied immediately (i.e.
|
||||
// without transition) and that the `to` value will be affected by the
|
||||
// `transition` style, we need to ensure an animation frame has passed between
|
||||
// setting each style.
|
||||
.switchMap(() => raf$).do(() => elem.style[prop] = from)
|
||||
.switchMap(() => raf$).do(() => elem.style.transition = `all ${duration}ms ease-in-out`)
|
||||
.switchMap(() => raf$).do(() => elem.style[prop] = to)
|
||||
.switchMap(() => timer(getActualDuration(elem))).switchMap(() => this.void$);
|
||||
};
|
||||
|
||||
const animateLeave = (elem: HTMLElement) => animateProp(elem, 'opacity', '1', '0.1');
|
||||
const animateEnter = (elem: HTMLElement) => animateProp(elem, 'opacity', '0.1', '1');
|
||||
|
||||
let done$ = this.void$;
|
||||
|
||||
if (this.currViewContainer.parentElement) {
|
||||
done$ = done$
|
||||
// Remove the current view from the viewer.
|
||||
.switchMap(() => animateLeave(this.currViewContainer))
|
||||
.do(() => this.currViewContainer.parentElement.removeChild(this.currViewContainer))
|
||||
.do(() => this.docRemoved.emit());
|
||||
}
|
||||
|
||||
return done$
|
||||
// Insert the next view into the viewer.
|
||||
.do(() => this.hostElement.appendChild(this.nextViewContainer))
|
||||
.do(() => onInsertedCb())
|
||||
.do(() => this.docInserted.emit())
|
||||
.switchMap(() => animateEnter(this.nextViewContainer))
|
||||
// Update the view references and clean up unused nodes.
|
||||
.do(() => {
|
||||
const prevViewContainer = this.currViewContainer;
|
||||
this.currViewContainer = this.nextViewContainer;
|
||||
this.nextViewContainer = prevViewContainer;
|
||||
this.nextViewContainer.innerHTML = ''; // Empty to release memory.
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@ -12,7 +12,7 @@
|
||||
</div>
|
||||
|
||||
<p>
|
||||
Powered by Google ©2010-2017.
|
||||
Powered by Google ©2010-2018.
|
||||
Code licensed under an <a href="license" title="License text" >MIT-style License</a>.
|
||||
Documentation licensed under
|
||||
<a href="http://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>.
|
||||
|
@ -36,7 +36,7 @@ describe('SearchBoxComponent', () => {
|
||||
|
||||
describe('initialisation', () => {
|
||||
it('should get the current search query from the location service',
|
||||
inject([LocationService], (location: MockLocationService) => fakeAsync(() => {
|
||||
fakeAsync(inject([LocationService], (location: MockLocationService) => {
|
||||
location.search.and.returnValue({ search: 'initial search' });
|
||||
component.ngOnInit();
|
||||
expect(location.search).toHaveBeenCalled();
|
||||
|
@ -11,8 +11,9 @@ interface StringMap { [index: string]: string; }
|
||||
export function getAttrs(el: HTMLElement | ElementRef): StringMap {
|
||||
const attrs: NamedNodeMap = el instanceof ElementRef ? el.nativeElement.attributes : el.attributes;
|
||||
const attrMap = {};
|
||||
Object.keys(attrs).forEach(key =>
|
||||
attrMap[(attrs[key] as Attr).name.toLowerCase()] = (attrs[key] as Attr).value);
|
||||
for (const attr of attrs as any /* cast due to https://github.com/Microsoft/TypeScript/issues/2695 */) {
|
||||
attrMap[attr.name.toLowerCase()] = attr.value;
|
||||
}
|
||||
return attrMap;
|
||||
}
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
import { InjectionToken, Inject, Injectable } from '@angular/core';
|
||||
import { of } from 'rxjs/observable/of';
|
||||
import { MatIconRegistry } from '@angular/material';
|
||||
import { MatIconRegistry } from '@angular/material/icon';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { DomSanitizer } from '@angular/platform-browser';
|
||||
|
||||
@ -27,19 +27,6 @@ interface SvgIconMap {
|
||||
[iconName: string]: SVGElement;
|
||||
}
|
||||
|
||||
// <hack-alert>
|
||||
// @angular/material's `MdIconRegitry` currently (v2.0.0-beta.8) requires an instance of `Http`
|
||||
// (from @angular/http). It is only used to [get some text content][1], so we can create a wrapper
|
||||
// around `HttpClient` and pretend it is `Http`.
|
||||
// [1]: https://github.com/angular/material2/blob/2.0.0-beta.8/src/lib/icon/icon-registry.ts#L465-L466
|
||||
// </hack-alert>
|
||||
function createFakeHttp(http: HttpClient): any {
|
||||
return {
|
||||
get: (url: string) => http.get(url, {responseType: 'text'})
|
||||
.map(data => ({text: () => data}))
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A custom replacement for Angular Material's `MdIconRegistry`, which allows
|
||||
* us to provide preloaded icon SVG sources.
|
||||
@ -49,7 +36,7 @@ export class CustomIconRegistry extends MatIconRegistry {
|
||||
private preloadedSvgElements: SvgIconMap = {};
|
||||
|
||||
constructor(http: HttpClient, sanitizer: DomSanitizer, @Inject(SVG_ICONS) svgIcons: SvgIconInfo[]) {
|
||||
super(createFakeHttp(http), sanitizer);
|
||||
super(http, sanitizer);
|
||||
this.loadSvgElements(svgIcons);
|
||||
}
|
||||
|
||||
|
@ -17,7 +17,7 @@ export class ScrollService {
|
||||
// at the top (e.g. toolbar) + some margin
|
||||
get topOffset() {
|
||||
if (!this._topOffset) {
|
||||
const toolbar = this.document.querySelector('mat-toolbar.app-toolbar');
|
||||
const toolbar = this.document.querySelector('.app-toolbar');
|
||||
this._topOffset = (toolbar && toolbar.clientHeight || 0) + topMargin;
|
||||
}
|
||||
return this._topOffset;
|
||||
|
@ -100,7 +100,7 @@ a {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.mat-toolbar-row a {
|
||||
.app-toolbar a {
|
||||
font-size: 16px;
|
||||
font-weight: 400;
|
||||
color: white;
|
||||
|
4
aio/src/styles/1-layouts/_doc-viewer.scss
Normal file
4
aio/src/styles/1-layouts/_doc-viewer.scss
Normal file
@ -0,0 +1,4 @@
|
||||
.no-animations aio-doc-viewer > * {
|
||||
// Disable view transition animations.
|
||||
transition: none !important;
|
||||
}
|
@ -4,6 +4,7 @@
|
||||
|
||||
@import 'api-page';
|
||||
@import 'content-layout';
|
||||
@import 'doc-viewer';
|
||||
@import 'footer';
|
||||
@import 'layout-global';
|
||||
@import 'marketing-layout';
|
||||
|
@ -1,3 +1,92 @@
|
||||
// VARIABLES
|
||||
$hamburgerShownMargin: 0;
|
||||
$hamburgerHiddenMargin: 0 24px 0 -88px;
|
||||
|
||||
|
||||
// DOCS PAGE / STANDARD: TOPNAV TOOLBAR FIXED
|
||||
mat-toolbar.mat-toolbar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
left: 0;
|
||||
z-index: 10;
|
||||
padding: 0 16px 0 0;
|
||||
box-shadow: 0 2px 5px 0 rgba(0,0,0,0.30);
|
||||
|
||||
mat-icon {
|
||||
color: $white;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// HOME PAGE OVERRIDE: TOPNAV TOOLBAR
|
||||
aio-shell.page-home mat-toolbar.mat-toolbar {
|
||||
background-color: $blue;
|
||||
|
||||
@media (min-width: 481px) {
|
||||
&:not(.transitioning) {
|
||||
background-color: transparent;
|
||||
transition: background-color .2s linear;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARKETING PAGES OVERRIDE: TOPNAV TOOLBAR AND HAMBURGER
|
||||
aio-shell.page-home mat-toolbar.mat-toolbar,
|
||||
aio-shell.page-features mat-toolbar.mat-toolbar,
|
||||
aio-shell.page-events mat-toolbar.mat-toolbar,
|
||||
aio-shell.page-resources mat-toolbar.mat-toolbar {
|
||||
box-shadow: none;
|
||||
|
||||
// FIXED TOPNAV TOOLBAR FOR SMALL MOBILE
|
||||
@media (min-width: 481px) {
|
||||
position: absolute;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// DOCS PAGES OVERRIDE: HAMBURGER
|
||||
aio-shell.folder-api mat-toolbar.mat-toolbar,
|
||||
aio-shell.folder-docs mat-toolbar.mat-toolbar,
|
||||
aio-shell.folder-guide mat-toolbar.mat-toolbar,
|
||||
aio-shell.folder-tutorial mat-toolbar.mat-toolbar {
|
||||
@media (min-width: 992px) {
|
||||
.hamburger.mat-button {
|
||||
// Hamburger shown on non-marketing pages on large screens.
|
||||
margin: $hamburgerShownMargin;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// HAMBURGER BUTTON
|
||||
.hamburger.mat-button {
|
||||
height: 100%;
|
||||
margin: $hamburgerShownMargin;
|
||||
padding: 0;
|
||||
transition-duration: .4s;
|
||||
transition-property: color, margin;
|
||||
transition-timing-function: cubic-bezier(.25, .8, .25, 1);
|
||||
|
||||
@media (min-width: 992px) {
|
||||
// Hamburger hidden by default on large screens.
|
||||
// (Will be shown per doc.)
|
||||
margin: $hamburgerHiddenMargin;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
color: $offwhite;
|
||||
}
|
||||
|
||||
& .mat-icon {
|
||||
color: white;
|
||||
position: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// HOME NAV-LINK
|
||||
.nav-link.home img {
|
||||
position: relative;
|
||||
margin-top: -21px;
|
||||
@ -12,6 +101,8 @@
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// TOP MENU
|
||||
aio-top-menu {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
@ -56,55 +147,6 @@ aio-top-menu {
|
||||
}
|
||||
}
|
||||
|
||||
// HOME PAGE OVERRIDE: TOPNAV TOOLBAR HAMBURGER MENU
|
||||
aio-shell.page-home mat-toolbar.app-toolbar.mat-toolbar {
|
||||
background-color: transparent;
|
||||
transition: background-color .2s linear .3s;
|
||||
|
||||
@media (max-width: 480px) {
|
||||
background-color: $blue;
|
||||
}
|
||||
}
|
||||
|
||||
// DOCS PAGE / STANDARD: TOPNAV TOOLBAR FIXED
|
||||
mat-toolbar.mat-toolbar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
left: 0;
|
||||
z-index: 10;
|
||||
padding: 0 16px 0 0;
|
||||
box-shadow: 0 2px 5px 0 rgba(0,0,0,0.30);
|
||||
|
||||
mat-icon {
|
||||
color: $white;
|
||||
}
|
||||
}
|
||||
|
||||
// MARKETING PAGES OVERRIDE: TOPNAV TOOLBAR AND HAMBURGER
|
||||
aio-shell.page-home mat-toolbar.mat-toolbar,
|
||||
aio-shell.page-features mat-toolbar.mat-toolbar,
|
||||
aio-shell.page-events mat-toolbar.mat-toolbar,
|
||||
aio-shell.page-resources mat-toolbar.mat-toolbar {
|
||||
// FIXED TOPNAV TOOLBAR FOR SMALL MOBILE
|
||||
@media (min-width: 481px) {
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
@media (min-width: 992px) {
|
||||
button.hamburger {
|
||||
margin: 0 24px 0 -88px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// REMOVE BOX SHADOW ON CERTAIN MARKETING PAGES
|
||||
aio-shell.page-home mat-toolbar.mat-toolbar,
|
||||
aio-shell.page-events mat-toolbar.mat-toolbar,
|
||||
aio-shell.page-resources mat-toolbar.mat-toolbar {
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
|
||||
// SEARCH BOX
|
||||
aio-search-box.search-container {
|
||||
|
@ -1,29 +0,0 @@
|
||||
.hamburger {
|
||||
transition-duration: 150ms;
|
||||
transition-property: background-color, color;
|
||||
transition-timing-function: ease-in-out;
|
||||
&:hover {
|
||||
color: $lightgray;
|
||||
}
|
||||
}
|
||||
|
||||
.hamburger.mat-button {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
|
||||
&:not(.starting) {
|
||||
transition-duration: .4s;
|
||||
transition-property: color, margin;
|
||||
transition-timing-function: cubic-bezier(.25, .8, .25, 1);
|
||||
}
|
||||
}
|
||||
|
||||
.hamburger.mat-button:hover {
|
||||
color: $offwhite;
|
||||
}
|
||||
|
||||
.hamburger .mat-icon {
|
||||
position: inherit;
|
||||
color: white;
|
||||
}
|
@ -16,7 +16,6 @@
|
||||
@import 'edit-page-cta';
|
||||
@import 'features';
|
||||
@import 'filetree';
|
||||
@import 'hamburger';
|
||||
@import 'heading-anchors';
|
||||
@import 'hr';
|
||||
@import 'images';
|
||||
|
88
aio/src/testing/doc-viewer-utils.ts
Normal file
88
aio/src/testing/doc-viewer-utils.ts
Normal file
@ -0,0 +1,88 @@
|
||||
import { Component, ComponentRef, NgModule, ViewChild } from '@angular/core';
|
||||
import { Title } from '@angular/platform-browser';
|
||||
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
|
||||
import { DocumentContents } from 'app/documents/document.service';
|
||||
import { EmbedComponentsService } from 'app/embed-components/embed-components.service';
|
||||
import { DocViewerComponent } from 'app/layout/doc-viewer/doc-viewer.component';
|
||||
import { Logger } from 'app/shared/logger.service';
|
||||
import { TocService } from 'app/shared/toc.service';
|
||||
import { MockLogger } from 'testing/logger.service';
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// `TestDocViewerComponent` (for exposing internal `DocViewerComponent` methods as public). ///
|
||||
/// Only used for type-casting; the actual implementation is irrelevant. ///
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
export class TestDocViewerComponent extends DocViewerComponent {
|
||||
embeddedComponentRefs: ComponentRef<any>[];
|
||||
currViewContainer: HTMLElement;
|
||||
nextViewContainer: HTMLElement;
|
||||
|
||||
destroyEmbeddedComponents(): void { return null as any; }
|
||||
prepareTitleAndToc(targetElem: HTMLElement, docId: string): () => void { return null as any; }
|
||||
render(doc: DocumentContents): Observable<void> { return null as any; }
|
||||
swapViews(onInsertedCb?: () => void): Observable<void> { return null as any; }
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// `TestModule` and `TestParentComponent`. ///
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// Test parent component.
|
||||
@Component({
|
||||
selector: 'aio-test',
|
||||
template: '<aio-doc-viewer [doc]="currentDoc">Test Component</aio-doc-viewer>',
|
||||
})
|
||||
export class TestParentComponent {
|
||||
currentDoc: DocumentContents;
|
||||
@ViewChild(DocViewerComponent) docViewer: DocViewerComponent;
|
||||
}
|
||||
|
||||
// Mock services.
|
||||
export class MockEmbedComponentsService {
|
||||
embedInto = jasmine.createSpy('EmbedComponentsService#embedInto');
|
||||
}
|
||||
|
||||
export class MockTitle {
|
||||
setTitle = jasmine.createSpy('Title#reset');
|
||||
}
|
||||
|
||||
export class MockTocService {
|
||||
genToc = jasmine.createSpy('TocService#genToc');
|
||||
reset = jasmine.createSpy('TocService#reset');
|
||||
}
|
||||
|
||||
@NgModule({
|
||||
declarations: [
|
||||
DocViewerComponent,
|
||||
TestParentComponent,
|
||||
],
|
||||
providers: [
|
||||
{ provide: Logger, useClass: MockLogger },
|
||||
{ provide: EmbedComponentsService, useClass: MockEmbedComponentsService },
|
||||
{ provide: Title, useClass: MockTitle },
|
||||
{ provide: TocService, useClass: MockTocService },
|
||||
],
|
||||
})
|
||||
export class TestModule { }
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// An observable with spies to test subscribing/unsubscribing. ///
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
export class ObservableWithSubscriptionSpies<T = void> extends Observable<T> {
|
||||
unsubscribeSpies: jasmine.Spy[] = [];
|
||||
subscribeSpy = spyOn(this, 'subscribe').and.callFake((...args) => {
|
||||
const subscription = super.subscribe(...args);
|
||||
const unsubscribeSpy = spyOn(subscription, 'unsubscribe').and.callThrough();
|
||||
this.unsubscribeSpies.push(unsubscribeSpy);
|
||||
return subscription;
|
||||
});
|
||||
|
||||
constructor(subscriber = () => undefined) { super(subscriber); }
|
||||
}
|
138
aio/src/testing/embed-components-utils.ts
Normal file
138
aio/src/testing/embed-components-utils.ts
Normal file
@ -0,0 +1,138 @@
|
||||
import {
|
||||
Component, ComponentFactoryResolver, ComponentRef, CompilerFactory, ElementRef, NgModule,
|
||||
NgModuleFactoryLoader, OnInit, Type, ViewChild, getPlatform
|
||||
} from '@angular/core';
|
||||
|
||||
import {
|
||||
ComponentsOrModulePath, EMBEDDED_COMPONENTS, EmbedComponentsService, EmbeddedComponentFactory,
|
||||
WithEmbeddedComponents
|
||||
} from 'app/embed-components/embed-components.service';
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// `TestEmbedComponentsService` (for exposing internal methods as public). ///
|
||||
/// Only used for type-casting; the actual implementation is irrelevant. ///
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
export class TestEmbedComponentsService extends EmbedComponentsService {
|
||||
componentFactories: Map<string, EmbeddedComponentFactory>;
|
||||
|
||||
createComponentFactories(components: Type<any>[], resolver: ComponentFactoryResolver): void { return null as any; }
|
||||
createComponents(elem: HTMLElement): ComponentRef<any>[] { return null as any; }
|
||||
prepareComponentFactories(compsOrPath: ComponentsOrModulePath): Promise<void> { return null as any; }
|
||||
selectorToContentPropertyName(selector: string): string { return null as any; }
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// Mock `EmbeddedModule` and test components. ///
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// Test embedded components.
|
||||
@Component({
|
||||
selector: 'aio-eager-foo',
|
||||
template: `Eager Foo Component`,
|
||||
})
|
||||
class EagerFooComponent { }
|
||||
|
||||
@Component({
|
||||
selector: 'aio-eager-bar',
|
||||
template: `
|
||||
<hr>
|
||||
<h2>Eager Bar Component</h2>
|
||||
<p #content></p>
|
||||
<hr>
|
||||
`,
|
||||
})
|
||||
class EagerBarComponent implements OnInit {
|
||||
@ViewChild('content') contentRef: ElementRef;
|
||||
|
||||
constructor(public elementRef: ElementRef) { }
|
||||
|
||||
// Project content in `ngOnInit()` just like in `CodeExampleComponent`.
|
||||
ngOnInit() {
|
||||
// Security: This is a test component; never deployed.
|
||||
this.contentRef.nativeElement.innerHTML = this.elementRef.nativeElement.aioEagerBarContent;
|
||||
}
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'aio-lazy-foo',
|
||||
template: `Lazy Foo Component`,
|
||||
})
|
||||
class LazyFooComponent { }
|
||||
|
||||
@Component({
|
||||
selector: 'aio-lazy-bar',
|
||||
template: `
|
||||
<hr>
|
||||
<h2>Lazy Bar Component</h2>
|
||||
<p #content></p>
|
||||
<hr>
|
||||
`,
|
||||
})
|
||||
class LazyBarComponent implements OnInit {
|
||||
@ViewChild('content') contentRef: ElementRef;
|
||||
|
||||
constructor(public elementRef: ElementRef) { }
|
||||
|
||||
// Project content in `ngOnInit()` just like in `CodeExampleComponent`.
|
||||
ngOnInit() {
|
||||
// Security: This is a test component; never deployed.
|
||||
this.contentRef.nativeElement.innerHTML = this.elementRef.nativeElement.aioLazyBarContent;
|
||||
}
|
||||
}
|
||||
|
||||
// Export test embedded selectors and components.
|
||||
export const testEagerEmbeddedSelectors = ['aio-eager-foo', 'aio-eager-bar'];
|
||||
export const testEagerEmbeddedComponents = [EagerFooComponent, EagerBarComponent];
|
||||
export const testLazyEmbeddedSelectors = ['aio-lazy-foo', 'aio-lazy-bar'];
|
||||
export const testLazyEmbeddedComponents = [LazyFooComponent, LazyBarComponent];
|
||||
|
||||
// Export mock `EmbeddedModule` and path.
|
||||
export const mockEmbeddedModulePath = 'mock/mock-embedded#MockEmbeddedModule';
|
||||
|
||||
@NgModule({
|
||||
declarations: [testLazyEmbeddedComponents],
|
||||
entryComponents: [testLazyEmbeddedComponents],
|
||||
})
|
||||
class MockEmbeddedModule implements WithEmbeddedComponents {
|
||||
embeddedComponents = testLazyEmbeddedComponents;
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// `TestModule`. ///
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// Mock services.
|
||||
export class MockNgModuleFactoryLoader implements NgModuleFactoryLoader {
|
||||
loadedPaths: string[] = [];
|
||||
|
||||
load(path: string) {
|
||||
this.loadedPaths.push(path);
|
||||
|
||||
const platformRef = getPlatform();
|
||||
const compilerFactory = platformRef.injector.get(CompilerFactory) as CompilerFactory;
|
||||
const compiler = compilerFactory.createCompiler([]);
|
||||
|
||||
return compiler.compileModuleAsync(MockEmbeddedModule);
|
||||
}
|
||||
}
|
||||
|
||||
@NgModule({
|
||||
providers: [
|
||||
EmbedComponentsService,
|
||||
{ provide: NgModuleFactoryLoader, useClass: MockNgModuleFactoryLoader },
|
||||
{
|
||||
provide: EMBEDDED_COMPONENTS,
|
||||
useValue: {
|
||||
[testEagerEmbeddedSelectors.join(',')]: testEagerEmbeddedComponents,
|
||||
[testLazyEmbeddedSelectors.join(',')]: mockEmbeddedModulePath,
|
||||
},
|
||||
},
|
||||
],
|
||||
declarations: [testEagerEmbeddedComponents],
|
||||
entryComponents: [testEagerEmbeddedComponents],
|
||||
})
|
||||
export class TestModule { }
|
@ -1,6 +1,7 @@
|
||||
{
|
||||
"scripts": [
|
||||
{ "name": "ng", "command": "ng" },
|
||||
{ "name": "build", "command": "ng build" },
|
||||
{ "name": "start", "command": "ng serve" },
|
||||
{ "name": "test", "command": "ng test" },
|
||||
{ "name": "lint", "command": "ng lint" },
|
||||
|
@ -54,6 +54,19 @@ class ExampleZipper {
|
||||
}
|
||||
}
|
||||
|
||||
// rename a custom main.ts or index.html file
|
||||
_renameFile(file) {
|
||||
if (/src\/main[-.]\w+\.ts$/.test(file)) {
|
||||
return 'src/main.ts';
|
||||
}
|
||||
|
||||
if (/src\/index[-.]\w+\.html$/.test(file)) {
|
||||
return 'src/index.html';
|
||||
}
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
_zipExample(configFileName, sourceDirName, outputDirName) {
|
||||
let json = require(configFileName, 'utf-8');
|
||||
const basePath = json.basePath || '';
|
||||
@ -79,12 +92,16 @@ class ExampleZipper {
|
||||
'tslint.json',
|
||||
'karma-test-shim.js',
|
||||
'karma.conf.js',
|
||||
'tsconfig.json',
|
||||
'src/testing/**/*',
|
||||
'src/.babelrc',
|
||||
'src/favicon.ico',
|
||||
'src/typings.d.ts'
|
||||
'src/polyfills.ts',
|
||||
'src/typings.d.ts',
|
||||
'src/environments/**/*',
|
||||
'src/tsconfig.*'
|
||||
];
|
||||
var defaultExcludes = [
|
||||
var alwaysExcludes = [
|
||||
'!**/bs-config.e2e.json',
|
||||
'!**/*plnkr.*',
|
||||
'!**/*zipper.*',
|
||||
@ -132,13 +149,14 @@ class ExampleZipper {
|
||||
}
|
||||
});
|
||||
|
||||
Array.prototype.push.apply(gpaths, defaultExcludes);
|
||||
Array.prototype.push.apply(gpaths, alwaysExcludes);
|
||||
|
||||
let fileNames = globby.sync(gpaths, { ignore: ['**/node_modules/**']});
|
||||
|
||||
let zip = this._createZipArchive(outputFileName);
|
||||
fileNames.forEach((fileName) => {
|
||||
let relativePath = path.relative(exampleDirName, fileName);
|
||||
relativePath = this._renameFile(relativePath);
|
||||
let content = fs.readFileSync(fileName, 'utf8');
|
||||
let extn = path.extname(fileName).substr(1);
|
||||
// if we don't need to clean up the file then we can do the following.
|
||||
|
@ -200,8 +200,10 @@ function runProtractorAoT(appDir, outputFile) {
|
||||
// All protractor output is appended to the outputFile.
|
||||
// CLI version
|
||||
function runE2eTestsCLI(appDir, outputFile) {
|
||||
// --preserve-symlinks is needed due the symlinked node_modules in each example
|
||||
const e2eSpawn = spawnExt('yarn', ['e2e', '--preserve-symlinks'], { cwd: appDir });
|
||||
// `--preserve-symlinks` is needed due the symlinked `node_modules/` in each example.
|
||||
// `--no-webdriver-update` is needed to preserve the ChromeDriver version already installed.
|
||||
const args = ['e2e', '--preserve-symlinks', '--no-webdriver-update'];
|
||||
const e2eSpawn = spawnExt('yarn', args, { cwd: appDir });
|
||||
return e2eSpawn.promise.then(
|
||||
function () {
|
||||
fs.appendFileSync(outputFile, `Passed: ${appDir}\n\n`);
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user