diff --git a/.bazelignore b/.bazelignore index 3c3629e647f5..b7f92cee892f 100644 --- a/.bazelignore +++ b/.bazelignore @@ -1 +1,7 @@ node_modules + +integration/ng-update-v13/.angular +integration/ng-update-v13/node_modules + +integration/ng-add/.angular +integration/ng-add/node_modules diff --git a/.bazelrc b/.bazelrc index b001134120f1..46a978fbc6ad 100644 --- a/.bazelrc +++ b/.bazelrc @@ -45,36 +45,35 @@ test --test_output=errors # Configures script to do version stamping. # See https://docs.bazel.build/versions/master/user-manual.html#flag--workspace_status_command -build:release --workspace_status_command="node ./tools/bazel-stamp-vars.js" +build:release --workspace_status_command="yarn -s ng-dev release build-env-stamp --mode=release" build:release --stamp -build:snapshot-build --workspace_status_command="node ./tools/bazel-stamp-vars.js --snapshot" +build:snapshot-build --workspace_status_command="yarn -s ng-dev release build-env-stamp --mode=snapshot" build:snapshot-build --stamp -################################ -# View Engine / Ivy toggle # -################################ -build:view-engine --define=angular_ivy_enabled=False -build:ivy --define=angular_ivy_enabled=True +#################################### +# Bazel custom flags # +#################################### +build --flag_alias=partial_compilation=@npm//@angular/bazel/src:partial_compilation -# Set Ivy as the default -build --config=ivy +################################## +# Always enable Ivy compilation # +################################## +build --define=angular_ivy_enabled=True ################################ # Remote Execution Setup # ################################ # Use the Angular team internal GCP instance for remote execution. -build:remote --remote_instance_name=projects/internal-200822/instances/default_instance +build:remote --remote_instance_name=projects/internal-200822/instances/primary_instance build:remote --project_id=internal-200822 # Needed due to: https://github.com/bazelbuild/bazel/issues/7254 build:remote --define=EXECUTOR=remote -# For remote execution, we use the `ubuntu16_04_clang` toolchain configurations. These only -# support `k8` or `armeabi-v7a`. Since we run on remotely with `k8` containers, we need to -# ensure that the proper CPU is configured so that the correct toolchain can be used. -# https://github.com/bazelbuild/bazel-toolchains/blob/master/configs/ubuntu16_04_clang/10.0.0/bazel_2.1.0/cc/BUILD#L50 +# Since remote builds run within Google Cloud `k8`-based containers, we set the +# host and target CPU accordingly. build:remote --cpu=k8 build:remote --host_cpu=k8 @@ -84,16 +83,21 @@ build:remote --remote_executor=remotebuildexecution.googleapis.com build:remote --auth_enabled=true # Setup the toolchain and platform for the remote build execution. The platform -# is automatically configured by the "rbe_autoconfig" rule in the project workpsace. -build:remote --crosstool_top=@rbe_default//cc:toolchain -build:remote --host_javabase=@rbe_default//java:jdk -build:remote --javabase=@rbe_default//java:jdk -build:remote --host_java_toolchain=@bazel_tools//tools/jdk:toolchain_hostjdk8 -build:remote --java_toolchain=@bazel_tools//tools/jdk:toolchain_hostjdk8 -build:remote --extra_execution_platforms=//tools:rbe_platform -build:remote --host_platform=//tools:rbe_platform -build:remote --platforms=//tools:rbe_platform -build:remote --extra_toolchains=@rbe_default//config:cc-toolchain +# is provided by the shared dev-infra package and targets k8 remote containers. +build:remote --crosstool_top=@npm//@angular/dev-infra-private/bazel/remote-execution/cpp:cc_toolchain_suite +build:remote --extra_toolchains=@npm//@angular/dev-infra-private/bazel/remote-execution/cpp:cc_toolchain +build:remote --extra_execution_platforms=@npm//@angular/dev-infra-private/bazel/remote-execution:platform_with_network +build:remote --host_platform=@npm//@angular/dev-infra-private/bazel/remote-execution:platform_with_network +build:remote --platforms=@npm//@angular/dev-infra-private/bazel/remote-execution:platform_with_network + +################################ +# Sandbox settings # +################################ + +# By default, network access should be disabled unless explicitly granted for certain targets +# using the `requires-network` tag. https://docs.bazel.build/versions/main/be/common-definitions.html +build --sandbox_default_allow_network=false +test --sandbox_default_allow_network=false ################################ # --config=build-results # diff --git a/.bazelversion b/.bazelversion index 40c341bdcdbe..fcdb2e109f68 100644 --- a/.bazelversion +++ b/.bazelversion @@ -1 +1 @@ -3.6.0 +4.0.0 diff --git a/.circleci/config.yml b/.circleci/config.yml index d66fd6023910..9642727ceb4f 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -7,18 +7,18 @@ # To validate changes, use an online parser, eg. # http://yaml-online-parser.appspot.com/ -var_1: &docker_image circleci/node:12.9.1 -var_2: &docker-firefox-image circleci/node:12.9.1-browsers +var_1: &docker_image circleci/node:16.10.0 +var_2: &docker-browser-image circleci/node:16.10.0-browsers # **Note**: When updating the beginning of the cache key, also update the cache key to match # the new cache key prefix. This allows us to take advantage of CircleCI's fallback caching. # Read more here: https://circleci.com/docs/2.0/caching/#restoring-cache. -var_3: &cache_key v6-ng-mat-{{ checksum ".bazelversion" }}-{{ checksum "tools/postinstall/apply-patches.js" }}-{{ checksum "WORKSPACE" }}-{{ checksum "yarn.lock" }} +var_3: &cache_key v9-ng-mat-{{ checksum ".bazelversion" }}-{{ checksum "tools/postinstall/apply-patches.js" }}-{{ checksum "WORKSPACE" }}-{{ checksum "yarn.lock" }} # We want to invalidate the cache if the postinstall patches change. In order to apply new # patches, a clean version of the node modules is needed. Additionally, we invalidate the cache # if the Bazel version changes. We do this because otherwise the `bazelisk` cache folder will # contain all previously used versions and ultimately cause the cache restoring to be slower. -var_4: &cache_fallback_key v6-ng-mat-{{ checksum ".bazelversion" }}-{{ checksum "tools/postinstall/apply-patches.js" }}- +var_4: &cache_fallback_key v9-ng-mat-{{ checksum ".bazelversion" }}-{{ checksum "tools/postinstall/apply-patches.js" }}- # Settings common to each job var_5: &job_defaults @@ -103,7 +103,7 @@ var_15: &ignore_presubmit_branch_filter var_16: &setup_bazel_remote_execution run: name: "Setup bazel RBE remote execution" - command: ./scripts/circleci/bazel/setup-remote-execution.sh + command: ./scripts/bazel/setup-remote-execution.sh # Sets up the bazel binary globally. We don't want to access bazel through Yarn and NodeJS # because it could mean that the Bazel child process only has access to limited memory. @@ -118,25 +118,25 @@ var_18: &setup_snapshot_builds name: "Setting up Angular snapshot builds" command: node ./scripts/circleci/setup-angular-snapshots.js master -# Filter to skip a job on builds for pull requests. -var_19: &skip_on_pull_requests_filter - branches: - ignore: - - /pull\/\d+/ - # Filter which ensures that jobs only run for pull requests. -var_20: &only_on_pull_requests_filter +var_19: &only_on_pull_requests_filter branches: only: - /pull\/\d+/ # Anchor for a step that notifies Slack when preceding steps failed. -var_21: &slack_notify_on_failure +var_20: &slack_notify_on_failure run: name: "Notifying team about job failure" when: on_fail command: node ./scripts/circleci/notify-slack-job-failure.js +# Branch filter that only matches the main branch. +var_21: &only_main_branch_filter + branches: + only: + - master + # ----------------------------- # Container version of CircleCI # ----------------------------- @@ -157,15 +157,12 @@ commands: description: Checkout and rebase the repository steps: - checkout - - run: - name: Set up environment - environment: - CIRCLE_GIT_BASE_REVISION: << pipeline.git.base_revision >> - CIRCLE_GIT_REVISION: << pipeline.git.revision >> - command: ./.circleci/env.sh + # After checkout, rebase on top of target branch. - run: name: Rebase PR on target branch - # After checkout, rebase on top of target branch. + environment: + CIRCLE_GIT_BASE_REVISION: << pipeline.git.base_revision >> + CIRCLE_GIT_REVISION: << pipeline.git.revision >> command: | if [ -n "$CIRCLE_PR_NUMBER" ]; then # User is required for rebase. @@ -197,33 +194,11 @@ jobs: # Exclude release and docs packages here as those will be built within # the "build_release_packages" and "publish_snapshots" jobs. - - run: bazel build src/... --build_tag_filters=-docs-package,-release-package - - *slack_notify_on_failure - - # ----------------------------------- - # Job which ensures that all non-test Bazel targets build properly - # in View Engine configuration. - # ----------------------------------- - view_engine_build: - <<: *job_defaults - resource_class: xlarge - environment: - GCP_DECRYPT_TOKEN: *gcp_decrypt_token - steps: - - checkout_and_rebase - - *restore_cache - - *setup_bazel_ci_config - - *setup_bazel_remote_execution - - *yarn_install - - *setup_bazel_binary - - # Exclude release and docs packages here as those will be built within - # the "build_release_packages" and "publish_snapshots" jobs. - - run: bazel build src/... --build_tag_filters=-docs-package,-release-package --config=view-engine + - run: bazel build --build_tag_filters=-docs-package,-release-package -- src/... - *slack_notify_on_failure # -------------------------------------------------------------------------------------------- - # Job that runs ts-api-guardian against our API goldens in "tools/public_api_guard". + # Job that runs API golden tests in "tools/public_api_guard". # This job fails whenever an API has been updated but not explicitly approved through goldens. # -------------------------------------------------------------------------------------------- api_golden_checks: @@ -281,7 +256,7 @@ jobs: - *yarn_install - *setup_bazel_binary - - run: bazel test src/... --build_tag_filters=-e2e --test_tag_filters=-e2e --build_tests_only + - run: bazel test --build_tag_filters=-e2e --test_tag_filters=-e2e --build_tests_only -- src/... - *slack_notify_on_failure # ---------------------------------------------------------------------------- @@ -341,10 +316,10 @@ jobs: - *setup_bazel_binary - run: - name: Checking rollup globals + name: Checking package externals command: | - bazel build //:rollup_globals - yarn check-rollup-globals $(bazel info bazel-bin)/rollup_globals.json + bazel build //:package_externals + yarn check-package-externals $(bazel info bazel-bin)/package_externals.json - run: name: Checking entry-points configuration @@ -353,20 +328,21 @@ jobs: yarn check-entry-point-setup $(bazel info bazel-bin)/entry_points_manifest.json - run: yarn ng-dev format changed --check << pipeline.git.base_revision >> + - run: yarn ownerslint + - run: yarn check-mdc-tests + - run: yarn stylelint + - run: yarn tslint + - run: yarn -s ts-circular-deps:check + - run: yarn check-mdc-exports + # Should be last so that it doesn't prevent the other lint checks from running. - run: name: Check Commit Message (PR Only) # Only run the commit message checks on pull requests since we can't do # much about any failures that have made it into the main branch. command: | if [ -n "$CIRCLE_PR_NUMBER" ]; then - yarn ng-dev commit-message validate-range --range $CI_COMMIT_RANGE + yarn ng-dev commit-message validate-range $CI_GIT_BASE_REVISION $CI_GIT_REVISION fi - - run: yarn ownerslint - - run: yarn check-mdc-tests - - run: yarn stylelint - - run: yarn tslint - - run: yarn -s ts-circular-deps:check - - run: yarn check-mdc-exports - *slack_notify_on_failure - *save_cache @@ -388,13 +364,8 @@ jobs: - *yarn_install - *setup_bazel_binary - - run: yarn build - - run: - name: Checking release output - command: | - pkg_json_version=$(node -pe "require('./package.json').version") - expected_version="${pkg_json_version}-sha-$(git rev-parse --short HEAD)" - yarn check-release-output ${expected_version} + - run: yarn build-and-check-release-output + - run: yarn check-tooling-setup # TODO(devversion): replace this with bazel tests that run Madge. This is # cumbersome and doesn't guarantee no circular deps for other entry-points. @@ -406,28 +377,6 @@ jobs: root: dist paths: - "releases/**/*" - - # Since there is no UMD bundle that includes everything from the CDK, we need to move - # all bundles into a directory. This allows us to store all CDK UMD bundles as job - # artifacts that can be picked up by the Angular Github bot. - - run: - name: Prepare CDK artifacts for publish. - command: | - mkdir -p /tmp/cdk-umd-minified-bundles - cp dist/releases/cdk/bundles/*.umd.min.js /tmp/cdk-umd-minified-bundles - # Publish bundle artifacts which will be used to calculate the size change. - # Note: Make sure that the size plugin from the Angular robot fetches the artifacts - # from this CircleCI job (see .github/angular-robot.yml). Additionally any artifacts need to - # be stored with the following path format: "{projectName}/{context}/{fileName}" - # This format is necessary because otherwise the bot is not able to pick up the - # artifacts from CircleCI. See: - # https://github.com/angular/github-robot/blob/master/functions/src/plugins/size.ts#L392-L394 - - store_artifacts: - path: dist/releases/material/bundles/material.umd.min.js - destination: /angular_material/material_release_output/material.umd.min.js - - store_artifacts: - path: /tmp/cdk-umd-minified-bundles - destination: /angular_material/cdk_release_output/ - *slack_notify_on_failure upload_release_packages: @@ -485,60 +434,12 @@ jobs: - run: ./scripts/circleci/publish-snapshots.sh - *slack_notify_on_failure - # ----------------------------------------------------------------- - # Job that ensures that the release output is compatible with ngcc. - # ----------------------------------------------------------------- - ngcc_compatibility: - <<: *job_defaults - resource_class: xlarge - steps: - - checkout_and_rebase - - *restore_cache - - *attach_release_output - - *yarn_install - - # Copy the release packages into the node modules so that ngcc can process them. - - run: cp -R dist/releases/* node_modules/@angular/ - # Delete existing ngcc manifests that would prevent the copied packages - # from being discovered. - - run: rm -f node_modules/__ngcc_entry_points__.json - # Ensure that the job fails if an entry-point cannot be compiled. Also disable - # tsconfig parsing as that causes the release packages to be incorrectly resolved - # to the sources due to path mapping. - - run: yarn ngcc --error-on-failed-entry-point --no-tsconfig - - *slack_notify_on_failure - - # ----------------------------------------------------------------- - # Job that ensures that the release output is compatible with the - # latest snapshot ngcc changes. - # ----------------------------------------------------------------- - ngcc_compatibility_snapshot: - <<: *job_defaults - resource_class: xlarge - steps: - - checkout_and_rebase - - *restore_cache - - *attach_release_output - - *setup_snapshot_builds - - *yarn_install_loose_lockfile - - # Copy the release packages into the node modules so that ngcc can process them. - - run: cp -R dist/releases/* node_modules/@angular/ - # Delete existing ngcc manifests that would prevent the copied packages - # from being discovered. - - run: rm -f node_modules/__ngcc_entry_points__.json - # Ensure that the job fails if an entry-point cannot be compiled. Also disable - # tsconfig parsing as that causes the release packages to be incorrectly resolved - # to the sources due to path mapping. - - run: yarn ngcc --error-on-failed-entry-point --no-tsconfig - - *slack_notify_on_failure - # ---------------------------------------------------------------------------- # Job that runs the local browser tests against the Angular Github snapshots # ---------------------------------------------------------------------------- snapshot_tests_local_browsers: docker: - - image: *docker-firefox-image + - image: *docker-browser-image resource_class: xlarge environment: GCP_DECRYPT_TOKEN: *gcp_decrypt_token @@ -551,15 +452,15 @@ jobs: - *yarn_install_loose_lockfile - *setup_bazel_binary - - run: bazel test src/... --build_tag_filters=-e2e --test_tag_filters=-e2e --build_tests_only + - run: bazel test --build_tag_filters=-e2e --test_tag_filters=-e2e --build_tests_only -- src/... - *slack_notify_on_failure # ---------------------------------------------------------------------------- - # Job that runs all Bazel tests against View Engine with the current Angular version - # specified in the project dev dependencies. + # Job that runs all Bazel integration tests. # ---------------------------------------------------------------------------- - view_engine_test: - <<: *job_defaults + integration_tests: + docker: + - image: *docker-browser-image resource_class: xlarge environment: GCP_DECRYPT_TOKEN: *gcp_decrypt_token @@ -571,14 +472,18 @@ jobs: - *yarn_install - *setup_bazel_binary - # Run project tests with NGC and View Engine. - - run: bazel test src/... --build_tag_filters=-docs-package,-e2e --test_tag_filters=-e2e --config=view-engine --build_tests_only + - run: yarn integration-tests + - run: + name: Running size integration tests (failures are reported in Slack only). + command: | + # If the size integration tests fail, report the failure to a dedicated #components-ci-size-tracking Slack channel. + yarn integration-tests:size-test || node ./scripts/circleci/notify-slack-job-failure.js components-ci-size-tracking - *slack_notify_on_failure # ---------------------------------------------------------------------------- - # Job that runs all Bazel tests against View Engine from angular/angular#master. + # Job that runs the AOT linker tests. # ---------------------------------------------------------------------------- - view_engine_snapshot_test_cronjob: + linker_aot_test: <<: *job_defaults resource_class: xlarge environment: @@ -588,18 +493,16 @@ jobs: - *restore_cache - *setup_bazel_ci_config - *setup_bazel_remote_execution - - *setup_snapshot_builds - - *yarn_install_loose_lockfile + - *yarn_install - *setup_bazel_binary - # Run project tests with NGC and View Engine. - - run: bazel test src/... --build_tag_filters=-docs-package,-e2e --test_tag_filters=-e2e --config=view-engine --build_tests_only + - run: yarn test-linker-aot - *slack_notify_on_failure # ---------------------------------------------------------------------------- - # Job that runs all Bazel integration tests. + # Job that runs the JIT linker tests. # ---------------------------------------------------------------------------- - integration_tests: + linker_jit_test: <<: *job_defaults resource_class: xlarge environment: @@ -611,15 +514,29 @@ jobs: - *setup_bazel_remote_execution - *yarn_install - *setup_bazel_binary - # TODO: Re-enable when there are integration tests that should run with Ivy. - # Currently this command fails as there are no tests. - # - run: yarn integration-tests - - run: - name: Running size integration tests (failures are reported in Slack only). - command: | - # If the size integration tests fail, report the failure to a dedicated #components-ci-size-tracking Slack channel. - yarn integration-tests:size-test || node ./scripts/circleci/notify-slack-job-failure.js components-ci-size-tracking - - run: yarn integration-tests:view-engine + + - run: yarn test-linker-jit + - *slack_notify_on_failure + + # ---------------------------------------------------------------------------- + # Job that runs both AOT and JIT linker tests against Angular snapshot builds. + # ---------------------------------------------------------------------------- + snapshot_linker_tests: + <<: *job_defaults + resource_class: xlarge + environment: + GCP_DECRYPT_TOKEN: *gcp_decrypt_token + steps: + - checkout_and_rebase + - *restore_cache + - *setup_bazel_ci_config + - *setup_bazel_remote_execution + - *setup_snapshot_builds + - *yarn_install_loose_lockfile + - *setup_bazel_binary + + - run: yarn test-linker-aot + - run: yarn test-linker-jit - *slack_notify_on_failure # ---------------------------------------------------------------------------- @@ -633,17 +550,18 @@ jobs: steps: - checkout_and_rebase - *restore_cache + - *yarn_install_loose_lockfile - *setup_bazel_binary - *setup_bazel_ci_config - *setup_bazel_remote_execution - *yarn_install # Install the latest canary version of the "material-components-web". - - run: yarn add material-components-web@canary + - run: node ./scripts/circleci/setup-mdc-canary.js # Setup the components repository to use the MDC snapshot builds. # Run project tests with the MDC canary builds. - - run: bazel test src/... --build_tag_filters=-docs-package,-e2e --test_tag_filters=-e2e --build_tests_only + - run: bazel test --build_tag_filters=-docs-package,-e2e --test_tag_filters=-e2e --build_tests_only -- src/... - *slack_notify_on_failure # ---------------------------------------------------------------------------------------- @@ -660,14 +578,14 @@ workflows: jobs: - bazel_build: filters: *ignore_presubmit_branch_filter - - view_engine_build: - filters: *ignore_presubmit_branch_filter - - view_engine_test: - filters: *ignore_presubmit_branch_filter - api_golden_checks: filters: *ignore_presubmit_branch_filter - integration_tests: filters: *ignore_presubmit_branch_filter + - linker_aot_test: + filters: *ignore_presubmit_branch_filter + - linker_jit_test: + filters: *ignore_presubmit_branch_filter - tests_local_browsers: filters: *ignore_presubmit_branch_filter - tests_browserstack: @@ -686,14 +604,6 @@ workflows: - build_release_packages - lint: filters: *ignore_presubmit_branch_filter - - ngcc_compatibility: - filters: *ignore_presubmit_branch_filter - requires: - - build_release_packages - - ngcc_compatibility_snapshot: - filters: *skip_on_pull_requests_filter - requires: - - build_release_packages - publish_snapshots: filters: *publish_branches_filter requires: @@ -706,9 +616,12 @@ workflows: # Note that we need additional jobs for the cronjob snapshot tests because there # is no easy way to detect whether a job runs inside of a cronjob or specific # workflow. See: https://circleci.com/ideas/?idea=CCI-I-295 - - snapshot_tests_local_browsers - - view_engine_snapshot_test_cronjob - - mdc_snapshot_test_cronjob + - snapshot_tests_local_browsers: + filters: *only_main_branch_filter + - mdc_snapshot_test_cronjob: + filters: *only_main_branch_filter + - snapshot_linker_tests: + filters: *only_main_branch_filter triggers: - schedule: diff --git a/.circleci/env-helpers.inc.sh b/.circleci/env-helpers.inc.sh deleted file mode 100755 index 5fa1263e112f..000000000000 --- a/.circleci/env-helpers.inc.sh +++ /dev/null @@ -1,73 +0,0 @@ -#################################################################################################### -# Helpers for defining environment variables for CircleCI. -# -# In CircleCI, each step runs in a new shell. The way to share ENV variables across steps is to -# export them from `$BASH_ENV`, which is automatically sourced at the beginning of every step (for -# the default `bash` shell). -# -# See also https://circleci.com/docs/2.0/env-vars/#using-bash_env-to-set-environment-variables. -#################################################################################################### - -# Set and print an environment variable. -# -# Use this function for setting environment variables that are public, i.e. it is OK for them to be -# visible to anyone through the CI logs. -# -# Usage: `setPublicVar ` -function setPublicVar() { - setSecretVar $1 "$2"; - echo "$1=$2"; -} - -# Set (without printing) an environment variable. -# -# Use this function for setting environment variables that are secret, i.e. should not be visible to -# everyone through the CI logs. -# -# Usage: `setSecretVar ` -function setSecretVar() { - # WARNING: Secrets (e.g. passwords, access tokens) should NOT be printed. - # (Keep original shell options to restore at the end.) - local -r originalShellOptions=$(set +o); - set +x -eu -o pipefail; - - echo "export $1=\"${2:-}\";" >> $BASH_ENV; - - # Restore original shell options. - eval "$originalShellOptions"; -} - - -# Create a function to set an environment variable, when called. -# -# Use this function for creating setter for public environment variables that require expensive or -# time-consuming computaions and may not be needed. When needed, you can call this function to set -# the environment variable (which will be available through `$BASH_ENV` from that point onwards). -# -# Arguments: -# - ``: The name of the environment variable. The generated setter function will be -# `setPublicVar_`. -# - ``: The code to run to compute the value for the variable. Since this code should be -# executed lazily, it must be properly escaped. For example: -# ```sh -# # DO NOT do this: -# createPublicVarSetter MY_VAR "$(whoami)"; # `whoami` will be evaluated eagerly -# -# # DO this isntead: -# createPublicVarSetter MY_VAR "\$(whoami)"; # `whoami` will NOT be evaluated eagerly -# ``` -# -# Usage: `createPublicVarSetter ` -# -# Example: -# ```sh -# createPublicVarSetter MY_VAR 'echo "FOO"'; -# echo $MY_VAR; # Not defined -# -# setPublicVar_MY_VAR; -# source $BASH_ENV; -# echo $MY_VAR; # FOO -# ``` -function createPublicVarSetter() { - echo "setPublicVar_$1() { setPublicVar $1 \"$2\"; }" >> $BASH_ENV; -} diff --git a/.circleci/env.sh b/.circleci/env.sh deleted file mode 100755 index 09e83b0b82fd..000000000000 --- a/.circleci/env.sh +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env bash - -# Variables -readonly projectDir=$(realpath "$(dirname ${BASH_SOURCE[0]})/..") -readonly envHelpersPath="$projectDir/.circleci/env-helpers.inc.sh"; -readonly bashEnvCachePath="$projectDir/.circleci/bash_env_cache"; - -# Load helpers and make them available everywhere (through `$BASH_ENV`). -source $envHelpersPath; -echo "source $envHelpersPath;" >> $BASH_ENV; - - -#################################################################################################### -# Define PUBLIC environment variables for CircleCI. -#################################################################################################### -# See https://circleci.com/docs/2.0/env-vars/#built-in-environment-variables for more info. -#################################################################################################### -setPublicVar CI "$CI" -setPublicVar PROJECT_ROOT "$projectDir"; -# This is the branch being built; e.g. `pull/12345` for PR builds. -setPublicVar CI_BRANCH "$CIRCLE_BRANCH"; -setPublicVar CI_BUILD_URL "$CIRCLE_BUILD_URL"; -setPublicVar CI_COMMIT "$CIRCLE_SHA1"; -# `CI_COMMIT_RANGE` is only used on push builds (a.k.a. non-PR, non-scheduled builds and rerun -# workflows of such builds). -setPublicVar CI_GIT_BASE_REVISION "${CIRCLE_GIT_BASE_REVISION}"; -setPublicVar CI_GIT_REVISION "${CIRCLE_GIT_REVISION}"; -setPublicVar CI_COMMIT_RANGE "$CIRCLE_GIT_BASE_REVISION..$CIRCLE_GIT_REVISION"; -setPublicVar CI_PULL_REQUEST "${CIRCLE_PR_NUMBER:-false}"; -setPublicVar CI_REPO_NAME "$CIRCLE_PROJECT_REPONAME"; -setPublicVar CI_REPO_OWNER "$CIRCLE_PROJECT_USERNAME"; -setPublicVar CI_PR_REPONAME "$CIRCLE_PR_REPONAME"; -setPublicVar CI_PR_USERNAME "$CIRCLE_PR_USERNAME"; - -#################################################################################################### -# Decrypt GCP Credentials and store them as the Google default credentials. -#################################################################################################### -mkdir -p "$HOME/.config/gcloud"; -openssl aes-256-cbc -d -in "${projectDir}/.circleci/gcp_token" \ - -md md5 -k "$CIRCLE_PROJECT_REPONAME" -out "$HOME/.config/gcloud/application_default_credentials.json" -#################################################################################################### -# Set bazel configuration for CircleCI runs. -#################################################################################################### -cp "${projectDir}/.circleci/bazel.linux.rc" "$HOME/.bazelrc"; - -#################################################################################################### -#################################################################################################### -## Source `$BASH_ENV` to make the variables available immediately. ## -## ***NOTE: This must remain the the last action in this script*** ## -#################################################################################################### -#################################################################################################### -source $BASH_ENV; diff --git a/.circleci/rebase-pr.js b/.circleci/rebase-pr.js index 7248a3482d4f..b9c6865fa445 100644 --- a/.circleci/rebase-pr.js +++ b/.circleci/rebase-pr.js @@ -21,7 +21,6 @@ // tslint:disable:no-console const {execSync: execSync_} = require('child_process'); - /** A regex to select a ref that matches our semver refs. */ const semverRegex = /^(\d+)\.(\d+)\.x$/; @@ -34,7 +33,9 @@ function exec(command, allowStderr = true) { let output = new String(); output.code = 0; try { - output += execSync_(command, {stdio: ['pipe', 'pipe', 'pipe']}).toString().trim(); + output += execSync_(command, {stdio: ['pipe', 'pipe', 'pipe']}) + .toString() + .trim(); } catch (err) { allowStderr && console.error(err.stderr.toString()); output.code = err.status; @@ -44,7 +45,6 @@ function exec(command, allowStderr = true) { // Run - // Helpers async function _main() { const refs = await getRefsAndShasForChange(); @@ -59,12 +59,16 @@ async function _main() { console.log(); // Get the count of commits between the latest commit from origin and the common ancestor SHA. - const commitCount = exec(`git rev-list --count origin/${refs.base.ref}...${refs.commonAncestorSha}`); + const commitCount = exec( + `git rev-list --count origin/${refs.base.ref}...${refs.commonAncestorSha}`, + ); console.log(`Checking ${commitCount} commits for changes in the CircleCI config file.`); // Check if the files changed between the latest commit from origin and the common ancestor SHA // includes the CircleCI config. - const circleCIConfigChanged = exec(`git diff --name-only origin/${refs.base.ref} ${refs.commonAncestorSha} -- .circleci/config.yml`); + const circleCIConfigChanged = exec( + `git diff --name-only origin/${refs.base.ref} ${refs.commonAncestorSha} -- .circleci/config.yml`, + ); if (!!circleCIConfigChanged) { throw Error(` @@ -90,8 +94,6 @@ async function _main() { console.log(`Rebased current branch onto ${refs.base.ref}.`); } - - /** * Sort a list of fullpath refs into a list and then provide the first entry. * @@ -116,8 +118,11 @@ function getRefFromBranchList(gitOutput) { if (aIsSemver && bIsSemver) { const [, aMajor, aMinor] = a.match(semverRegex); const [, bMajor, bMinor] = b.match(semverRegex); - return parseInt(bMajor, 10) - parseInt(aMajor, 10) || - parseInt(aMinor, 10) - parseInt(bMinor, 10) || 0; + return ( + parseInt(bMajor, 10) - parseInt(aMajor, 10) || + parseInt(aMinor, 10) - parseInt(bMinor, 10) || + 0 + ); } if (aIsSemver) { return -1; @@ -168,7 +173,6 @@ function addAndFetchRemote(owner, name) { return remoteName; } - /** Get the ref and latest shas for the provided sha on a specific remote. */ function getRefAndShas(sha, owner, name) { const remoteName = addAndFetchRemote(owner, name); @@ -181,11 +185,20 @@ function getRefAndShas(sha, owner, name) { return {remote: remoteName, ref, latestSha, sha}; } - /** Gets the refs and shas for the base and target of the current environment. */ function getRefsAndShasForChange() { - const base = getRefAndShas(process.env['CI_GIT_BASE_REVISION'], process.env['CI_REPO_OWNER'], process.env['CI_REPO_NAME']); - const target = getRefAndShas(process.env['CI_GIT_REVISION'], process.env['CI_PR_USERNAME'], process.env['CI_PR_REPONAME']); + const base = getRefAndShas( + process.env['CIRCLE_GIT_BASE_REVISION'], + process.env['CIRCLE_PROJECT_USERNAME'], + process.env['CIRCLE_PROJECT_REPONAME'], + ); + + const target = getRefAndShas( + process.env['CIRCLE_GIT_REVISION'], + process.env['CIRCLE_PR_USERNAME'], + process.env['CIRCLE_PR_REPONAME'], + ); + const commonAncestorSha = getCommonAncestorSha(base.sha, target.sha); return { base, @@ -194,7 +207,6 @@ function getRefsAndShasForChange() { }; } - _main().catch(err => { console.log('Failed to rebase on top of target branch.\n'); console.error(err); diff --git a/.clang-format b/.clang-format deleted file mode 100644 index b3462b5403c2..000000000000 --- a/.clang-format +++ /dev/null @@ -1,14 +0,0 @@ -Language: JavaScript -BasedOnStyle: Google -ColumnLimit: 100 - -TabWidth: 2 -ContinuationIndentWidth: 4 -MaxEmptyLinesToKeep: 2 - -AllowShortBlocksOnASingleLine: false -AllowShortIfStatementsOnASingleLine: false -AllowShortLoopsOnASingleLine: false -AllowShortFunctionsOnASingleLine: Empty -JavaScriptWrapImports: true - diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 5d2fe3e574b6..b3d36e29d263 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -88,8 +88,10 @@ /src/cdk/text-field/** @mmalerba /src/cdk/tree/** @jelbourn @andrewseguin -# Moment adapter package +# Date adapters /src/material-moment-adapter/** @mmalerba +/src/material-luxon-adapter/** @crisbeto +/src/material-date-fns-adapter/** @crisbeto # Material experimental package /src/material-experimental/* @jelbourn @@ -117,6 +119,7 @@ /src/material-experimental/mdc-slide-toggle/** @crisbeto /src/material-experimental/mdc-slider/** @devversion /src/material-experimental/mdc-tabs/** @crisbeto +/src/material-experimental/mdc-tooltip/** @crisbeto /src/material-experimental/mdc-sidenav/** @crisbeto /src/material-experimental/mdc-table/** @andrewseguin /src/material-experimental/mdc-theming/** @mmalerba @@ -133,6 +136,7 @@ /src/cdk-experimental/menu/** @jelbourn @andy9775 /src/cdk-experimental/popover-edit/** @kseamon @andrewseguin /src/cdk-experimental/scrolling/** @mmalerba +/src/cdk-experimental/table-scroll-container/** @kseamon @andrewseguin /src/cdk-experimental/listbox/** @nielsr98 @jelbourn /src/cdk-experimental/selection/** @yifange @jelbourn @@ -173,6 +177,8 @@ /src/dev-app/grid-list/** @jelbourn /src/dev-app/icon/** @jelbourn /src/dev-app/input/** @mmalerba +/src/dev-app/layout/** @jelbourn +/src/dev-app/input-modality/** @jelbourn @zelliott /src/dev-app/list/** @jelbourn @crisbeto @devversion /src/dev-app/live-announcer/** @jelbourn /src/dev-app/mdc-button/** @andrewseguin @@ -196,6 +202,7 @@ /src/dev-app/mdc-slider/** @devversion /src/dev-app/mdc-table/** @andrewseguin /src/dev-app/mdc-tabs/** @crisbeto +/src/dev-app/mdc-tooltip/** @crisbeto /src/dev-app/menu/** @crisbeto /src/dev-app/menubar/** @jelbourn @andy9775 /src/dev-app/overlay/** @jelbourn @crisbeto @@ -215,6 +222,7 @@ /src/dev-app/snack-bar/** @jelbourn @crisbeto /src/dev-app/stepper/** @mmalerba /src/dev-app/table/** @andrewseguin +/src/dev-app/table-scroll-container/** @kseamon @andrewseguin /src/dev-app/tabs/** @andrewseguin /src/dev-app/toolbar/** @devversion /src/dev-app/tooltip/** @andrewseguin @@ -340,6 +348,7 @@ # Misc /.github/** @angular/dev-infra-components +/.husky/** @angular/dev-infra-components /.github/CODEOWNERS @angular/dev-infra-components @jelbourn /.github/ISSUE_TEMPLATE/** @andrewseguin @jelbourn /.vscode/** @angular/dev-infra-components @mmalerba diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md deleted file mode 100644 index a77209ec73ee..000000000000 --- a/.github/ISSUE_TEMPLATE/bug.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: Bug Report -title: "bug(COMPONENT): TITLE" -about: Report a bug in Angular Material or the CDK -labels: needs triage ---- - -#### Reproduction - -Use StackBlitz to reproduce your issue: -- Components: https://stackblitz.com/fork/components-issue -- Harnesses: https://stackblitz.com/fork/harness-issue - -Steps to reproduce: -1. -2. - - -#### Expected Behavior - -What behavior were you expecting to see? - - -#### Actual Behavior - -What behavior did you actually see? - - -#### Environment - -- Angular: -- CDK/Material: -- Browser(s): -- Operating System (e.g. Windows, macOS, Ubuntu): diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml new file mode 100644 index 000000000000..a4923a2c100e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -0,0 +1,65 @@ +name: Bug Report +description: Report a bug in Angular Material or the CDK +title: "bug(COMPONENT): TITLE" +labels: ["needs triage"] +body: + - type: checkboxes + id: is-regression + attributes: + label: Is this a regression? + description: Did this behavior use to work in the previous version? + options: + - label: Yes, this behavior used to work in the previous version + - type: input + id: version-bug-was-not-present + attributes: + label: The previous version in which this bug was not present was + validations: + required: false + - type: textarea + id: description + attributes: + label: Description + description: A clear and concise description of the problem. + validations: + required: true + - type: textarea + id: reproduction + attributes: + label: Reproduction + description: | + **Use StackBlitz to reproduce your issue:** + - [Components](https://stackblitz.com/fork/components-issue) + - [Harnesses](https://stackblitz.com/fork/harness-issue) + value: | + Steps to reproduce: + 1. + 2. + validations: + required: true + - type: textarea + id: expected-behavior + attributes: + label: Expected Behavior + description: What behavior were you expecting to see? + validations: + required: true + - type: textarea + id: actual-behavior + attributes: + label: Actual Behavior + description: What behavior did you actually see? + validations: + required: true + - type: textarea + id: environment + attributes: + label: Environment + description: You can use `ng version` command. + value: | + - Angular: + - CDK/Material: + - Browser(s): + - Operating System (e.g. Windows, macOS, Ubuntu): + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000000..486735b8058b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Angular Framework + url: https://github.com/angular/angular/issues/new + about: Issues and feature requests for Angular Framework diff --git a/.github/ISSUE_TEMPLATE/docs.md b/.github/ISSUE_TEMPLATE/docs.md deleted file mode 100644 index 40947c2ca6dd..000000000000 --- a/.github/ISSUE_TEMPLATE/docs.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -name: Documentation -title: "docs-bug(COMPONENT): TITLE" -about: Suggest an improvement to our documentation at material.angular.io -labels: docs, needs triage ---- - -#### Documentation Feedback - -Provide a brief summary of what you would like to see changed in our -documentation at material.angular.io. - -Feel free to provide any suggestions of content or examples you’d like us to include. - -**Affected documentation page:** Insert a link to the affected page on material.angular.io diff --git a/.github/ISSUE_TEMPLATE/docs.yml b/.github/ISSUE_TEMPLATE/docs.yml new file mode 100644 index 000000000000..afc76a94cb7d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/docs.yml @@ -0,0 +1,21 @@ +name: Documentation +description: Suggest an improvement to our documentation at material.angular.io +title: "docs-bug(COMPONENT): TITLE" +labels: ["docs", "needs triage"] +body: + - type: textarea + id: description + attributes: + label: Documentation Feedback + description: | + Provide a brief summary of what you would like to see changed in our documentation at [material.angular.io](https://material.angular.io/). + Feel free to provide any suggestions of content or examples you’d like us to include. + validations: + required: true + - type: input + id: affected-documentation-page + attributes: + label: Affected documentation page + description: Insert a link to the affected page on [material.angular.io](https://material.angular.io/). + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/feature.md b/.github/ISSUE_TEMPLATE/feature.md deleted file mode 100644 index bce7e24680fa..000000000000 --- a/.github/ISSUE_TEMPLATE/feature.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -name: Feature -title: "feat(COMPONENT): TITLE" -about: Propose a new feature for Angular Material or the CDK -labels: feature, needs triage ---- - -#### Feature Description - -Provide a brief summary of the feature you would like to see. - -#### Use Case - -Describe the use case(s) that the proposed feature would enable. diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml new file mode 100644 index 000000000000..8c01fd13a222 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature.yml @@ -0,0 +1,19 @@ +name: Feature +description: Propose a new feature for Angular Material or the CDK +title: "feat(COMPONENT): TITLE" +labels: ["feature", "needs triage"] +body: + - type: textarea + id: description + attributes: + label: Feature Description + description: Provide a brief summary of the feature you would like to see. + validations: + required: true + - type: textarea + id: use-case + attributes: + label: Use Case + description: Describe the use case(s) that the proposed feature would enable. + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/troubleshooting.md b/.github/ISSUE_TEMPLATE/troubleshooting.md deleted file mode 100644 index 6762501f38f3..000000000000 --- a/.github/ISSUE_TEMPLATE/troubleshooting.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -name: Troubleshooting -title: "help(COMPONENT): TITLE" -about: Request for help on an issue you are facing with Angular Material or the CDK -labels: troubleshooting, needs triage ---- - - - - -#### What are you trying to do? - -What are you trying to do? - -#### What troubleshooting steps have you tried? - -What are you seeing that does not match your expectations? - -#### Reproduction - -We can only help if we can reproduce the problem ourselves. - -Use StackBlitz to demonstrate what you are trying to do: -- Components: https://stackblitz.com/fork/components-issue -- Harnesses: https://stackblitz.com/fork/harness-issue - -Steps to reproduce: -1. -2. - -#### Environment - -- Angular: -- CDK/Material: -- Browser(s): -- Operating System (e.g. Windows, macOS, Ubuntu): diff --git a/.github/ISSUE_TEMPLATE/troubleshooting.yml b/.github/ISSUE_TEMPLATE/troubleshooting.yml new file mode 100644 index 000000000000..1fc66dcb5d3b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/troubleshooting.yml @@ -0,0 +1,55 @@ +name: Troubleshooting +description: Request for help on an issue you are facing with Angular Material or the CDK +title: "help(COMPONENT): TITLE" +labels: ["troubleshooting", "needs triage"] +body: + - type: markdown + attributes: + value: | + The Angular team can't provide general troubleshooting help. However, the extended community of users can provide more help: + - [StackOverflow](https://stackoverflow.com/questions/tagged/angular-material2) + - [Gitter](https://gitter.im/angular/material2) + - [Google Groups](https://groups.google.com/forum/#!forum/angular-material2) + + Issues should capture only bug reports and feature requests. However, we understand that it is not always clear whether an issue is caused by a bug or incorrect usage of a feature/component. + Most support requests will be automatically closed. If the answer is quickly obvious, though, we might be able to provide a brief answer. + - type: textarea + id: description + attributes: + label: What are you trying to do? + validations: + required: true + - type: textarea + id: troubleshooting-steps + attributes: + label: What troubleshooting steps have you tried? + description: What are you seeing that does not match your expectations? + validations: + required: true + - type: textarea + id: reproduction + attributes: + label: Reproduction + description: | + We can only help if we can reproduce the problem ourselves. + **Use StackBlitz to demonstrate what you are trying to do:** + - [Components](https://stackblitz.com/fork/components-issue) + - [Harnesses](https://stackblitz.com/fork/harness-issue) + value: | + Steps to reproduce: + 1. + 2. + validations: + required: true + - type: textarea + id: environment + attributes: + label: Environment + description: You can use `ng version` command. + value: | + - Angular: + - CDK/Material: + - Browser(s): + - Operating System (e.g. Windows, macOS, Ubuntu): + validations: + required: true diff --git a/.github/actions/yarn-install/action.yml b/.github/actions/yarn-install/action.yml new file mode 100644 index 000000000000..fc29e4503bb3 --- /dev/null +++ b/.github/actions/yarn-install/action.yml @@ -0,0 +1,18 @@ +name: "Installing Yarn dependencies" +description: "Installs the dependencies using Yarn" + +runs: + using: "composite" + steps: + - uses: actions/cache@v2 + with: + path: | + ./node_modules/ + # Cache key. Whenever the postinstall patches change, the cache needs to be invalidated. + # If just the `yarn.lock` file changes, the most recent cache can be restored though. + # See: https://docs.github.com/en/actions/guides/caching-dependencies-to-speed-up-workflows#example-using-the-cache-action. + key: v3-${{hashFiles('tools/postinstall/apply-patches.js')}}-${{hashFiles('yarn.lock')}} + restore-keys: v3-${{hashFiles('tools/postinstall/apply-patches.js')}}- + + - run: yarn install --frozen-lockfile --non-interactive + shell: bash diff --git a/.github/angular-robot.yml b/.github/angular-robot.yml index ca11177cedb8..e4ac26b78618 100644 --- a/.github/angular-robot.yml +++ b/.github/angular-robot.yml @@ -30,8 +30,7 @@ merge: disabled: true # comment that will be added to a PR when there is a conflict, leave empty or set to false to disable - mergeConflictComment: "Hi @{{PRAuthor}}! This PR has merge conflicts due to recent upstream merges. -\nPlease help to unblock it by resolving these conflicts. Thanks!" + mergeConflictComment: "Hi @{{PRAuthor}}! This PR has merge conflicts due to recent upstream merges.\nPlease help to unblock it by resolving these conflicts. Thanks!" # label to monitor mergeLabel: "pr: merge ready" @@ -45,7 +44,6 @@ merge: # list of labels that a PR needs to have, checked with a regexp (e.g. "PR target:" will work for the label "PR target: master") requiredLabels: - "target: *" - - "cla: yes" # list of labels that a PR shouldn't have, checked after the required labels with a regexp forbiddenLabels: @@ -53,7 +51,6 @@ merge: - "pr: blocked" - "pr: needs*" - "presubmit failures" - - "cla: no" # list of PR statuses that need to be successful requiredStatuses: @@ -67,12 +64,7 @@ merge: # the comment that will be added when the merge label is added despite failing checks, leave empty or set to false to disable # {{MERGE_LABEL}} will be replaced by the value of the mergeLabel option # {{PLACEHOLDER}} will be replaced by the list of failing checks - mergeRemovedComment: "I see that you just added the `{{MERGE_LABEL}}` label, but the following checks are still failing: -\n{{PLACEHOLDER}} -\n -\n**If you want your PR to be merged, it has to pass all the CI checks.** -\n -\nIf you can't get the PR to a green state due to flakes or broken master, please try rebasing to master and/or restarting the CI job. If that fails and you believe that the issue is not due to your change, please contact the caretaker and ask for help." + mergeRemovedComment: "I see that you just added the `{{MERGE_LABEL}}` label, but the following checks are still failing:\n{{PLACEHOLDER}}\n\n**If you want your PR to be merged, it has to pass all the CI checks.**\n\nIf you can't get the PR to a green state due to flakes or broken master, please try rebasing to master and/or restarting the CI job. If that fails and you believe that the issue is not due to your change, please contact the caretaker and ask for help." # options for the triage plugin triage: diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index fd74afd0c83a..000000000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,15 +0,0 @@ -version: 2 - -updates: - - package-ecosystem: "npm" - directory: "/" - schedule: - interval: "daily" - commit-message: - prefix: "build" - labels: - - "area: build" - - "merge ready" - - "merge safe" - - "target: patch" - open-pull-requests-limit: 5 diff --git a/.github/workflows/build-dev-app.yml b/.github/workflows/build-dev-app.yml new file mode 100644 index 000000000000..83ac750ac49c --- /dev/null +++ b/.github/workflows/build-dev-app.yml @@ -0,0 +1,52 @@ +# This workflow builds the dev-app for pull requests when a certain label is applied. +# The actual deployment happens as part of a dedicated second workflow to avoid security +# issues where the building would otherwise occur in an authorized context where secrets +# could be leaked. More details can be found here: + +# https://securitylab.github.com/research/github-actions-preventing-pwn-requests/. + +name: Build dev-app for deployment + +on: + pull_request: + types: [synchronize, labeled] + +jobs: + dev-app-build: + runs-on: ubuntu-latest + # We only want to build and deploy the dev-app if the `dev-app preview` label has been + # added, or if the label is already applied and new changes have been made in the PR. + if: | + (github.event.action == 'labeled' && github.event.label.name == 'dev-app preview') || + (github.event.action == 'synchronize' && contains(github.event.pull_request.labels.*.name, 'dev-app preview')) + steps: + - uses: actions/checkout@v2 + - uses: ./.github/actions/yarn-install + + - run: ./scripts/bazel/setup-remote-execution.sh + env: + GCP_DECRYPT_TOKEN: angular + + # Build the web package. Note that we also need to make the Github environment + # variables available so that the RBE is configured. Note: We run Bazel from a + # low-resource Github action container, so we manually need to instruct Bazel to run + # more actions concurrently as by default this is computed based on the host resources. + - name: Building dev-app + run: | + source ${GITHUB_ENV} + bazel build //src/dev-app:web_package --symlink_prefix=dist/ --jobs=32 + + # Prepare the workflow artifact that is available for the deploy workflow. We store the pull + # request number and SHA in a file that can be read by the deploy workflow. This is necessary + # so that the deploy workflow can create a comment on the PR that triggered the deploy. + - run: | + mkdir -p dist/devapp + cp -R dist/bin/src/dev-app/web_package/* dist/devapp + echo ${{github.event.pull_request.number}} > dist/devapp/pr_number + echo ${{github.event.pull_request.head.sha}} > dist/devapp/pr_sha + + # Upload the generated dev-app archive. + - uses: actions/upload-artifact@v2 + with: + name: devapp + path: dist/devapp diff --git a/.github/workflows/deploy-dev-app.yml b/.github/workflows/deploy-dev-app.yml new file mode 100644 index 000000000000..01669e07e7c6 --- /dev/null +++ b/.github/workflows/deploy-dev-app.yml @@ -0,0 +1,52 @@ +# This workflow runs whenever the dev-app build workflow has completed. Deployment happens +# as part of a dedicated second workflow to avoid security issues where the building would +# otherwise occur in an authorized context where secrets could be leaked. +# +# More details can be found here: +# https://securitylab.github.com/research/github-actions-preventing-pwn-requests/. + +name: Deploying dev-app to Firebase previews + +on: + workflow_run: + workflows: [Build dev-app for deployment] + types: [completed] + +jobs: + deploy-dev-app: + runs-on: ubuntu-latest + if: ${{ github.event.workflow_run.conclusion == 'success' }} + steps: + - uses: actions/checkout@v2 + - uses: ./.github/actions/yarn-install + + - name: 'Download artifact from build job' + run: | + ./scripts/github/fetch-workflow-artifact.mjs ${{secrets.GITHUB_TOKEN}} \ + ${{github.event.workflow_run.id}} devapp > devapp.zip + + - name: Extracting workflow artifact into Firebase public directory. + run: | + mkdir -p dist/dev-app-web-pkg + unzip devapp.zip -d dist/dev-app-web-pkg + + - name: Extracting pull request from extracted workflow artifact. + id: pr_info + run: | + echo "::set-output name=number::$(cat ./dist/dev-app-web-pkg/pr_number)" + echo "::set-output name=sha::$(cat ./dist/dev-app-web-pkg/pr_sha)" + + - uses: FirebaseExtended/action-hosting-deploy@v0 + id: deploy + with: + repoToken: '${{secrets.GITHUB_TOKEN}}' + firebaseServiceAccount: '${{secrets.FIREBASE_PREVIEW_SERVICE_TOKEN}}' + expires: 20d + projectId: ng-comp-dev + channelId: pr-${{steps.pr_info.outputs.number}}-${{steps.pr_info.outputs.sha}} + + - uses: marocchino/sticky-pull-request-comment@v2 + with: + message: | + Deployed dev-app to: ${{ steps.deploy.outputs.details_url }} + number: ${{ steps.pr_info.outputs.number }} diff --git a/.github/workflows/dev-infra.yml b/.github/workflows/dev-infra.yml new file mode 100644 index 000000000000..081e698ab0af --- /dev/null +++ b/.github/workflows/dev-infra.yml @@ -0,0 +1,14 @@ +name: DevInfra + +on: + pull_request_target: + types: [opened, synchronize, reopened] + +jobs: + labels: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: angular/dev-infra/github-actions/commit-message-based-labels@f0f363cb4ce5b5faf14e3d3bb7eeb7c7aee72da7 + with: + angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }} diff --git a/.github/workflows/lock-closed.yml b/.github/workflows/lock-closed.yml index a3ef267cdc58..f19b35c6f13b 100644 --- a/.github/workflows/lock-closed.yml +++ b/.github/workflows/lock-closed.yml @@ -9,6 +9,6 @@ jobs: lock_closed: runs-on: ubuntu-latest steps: - - uses: angular/dev-infra/github-actions/lock-closed@0fc6f4d839e93312ed0dd9a2be88d4c11e947a0b + - uses: angular/dev-infra/github-actions/lock-closed@f0f363cb4ce5b5faf14e3d3bb7eeb7c7aee72da7 with: lock-bot-key: ${{ secrets.LOCK_BOT_PRIVATE_KEY }} diff --git a/.gitignore b/.gitignore index 798771a9f3d5..ce0991dfb3e0 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,9 @@ node_modules /bower_components +# Angular CLI project cache +.angular/ + # Dart /.pub /.packages @@ -25,6 +28,9 @@ node_modules /.idea /.vscode/launch.json /*.iml +/.vs +*.swo +*.swp # misc .DS_Store @@ -42,3 +48,6 @@ testem.log *.log .ng-dev.user* .husky/_ + +# Variables that are inlined into the dev app index.html +/src/dev-app/variables.json diff --git a/.husky/commit-msg b/.husky/commit-msg new file mode 100755 index 000000000000..5de69ce0b147 --- /dev/null +++ b/.husky/commit-msg @@ -0,0 +1,6 @@ +#!/bin/sh +# commit-msg git hook, see https://typicode.github.io/husky/#/ for more on how husky works. +. "$(dirname $0)/_/husky.sh" + +# Ahead of creating the commit, validate the commit message. +yarn -s ng-dev commit-message pre-commit-validate --file $1; diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100755 index 000000000000..7c7220b3d4de --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,11 @@ +#!/bin/sh +. "$(dirname "$0")/_/husky.sh" + +# Allow for the formatting command to fail without exiting the script. +set +e + +yarn -s ng-dev format staged 2>/dev/null + +if [ $? -ne 0 ]; then + echo "WARNING: failed to run file formatting (ng-dev format staged)" +fi \ No newline at end of file diff --git a/.husky/prepare-commit-msg b/.husky/prepare-commit-msg new file mode 100755 index 000000000000..fdf5c9b17f59 --- /dev/null +++ b/.husky/prepare-commit-msg @@ -0,0 +1,6 @@ +#!/bin/sh +# prepare-commit-msg git hook, see https://typicode.github.io/husky/#/ for more on how husky works. +. "$(dirname $0)/_/husky.sh" + +# When a commit is started, restore the previous commit message draft if it exists. +yarn -s ng-dev commit-message restore-commit-message-draft $1 $2; diff --git a/.ng-dev/caretaker.ts b/.ng-dev/caretaker.ts new file mode 100644 index 000000000000..e9cc536d17a1 --- /dev/null +++ b/.ng-dev/caretaker.ts @@ -0,0 +1,15 @@ +import {CaretakerConfig} from '@angular/dev-infra-private/ng-dev/caretaker/config'; + +/** The configuration for `ng-dev caretaker` commands. */ +export const caretaker: CaretakerConfig = { + githubQueries: [ + { + name: 'Merge Queue', + query: `is:pr is:open status:success label:"pr: merge ready"`, + }, + { + name: 'Triage Queue', + query: `is:open label:"needs triage"`, + }, + ], +}; diff --git a/.ng-dev/commit-message.ts b/.ng-dev/commit-message.ts index 4ab19a6de595..773ee2e7fc36 100644 --- a/.ng-dev/commit-message.ts +++ b/.ng-dev/commit-message.ts @@ -1,13 +1,14 @@ -import {CommitMessageConfig} from '@angular/dev-infra-private/commit-message/config'; +import {CommitMessageConfig} from '@angular/dev-infra-private/ng-dev/commit-message/config'; /** * The configuration for `ng-dev commit-message` commands. */ export const commitMessage: CommitMessageConfig = { - maxLineLength: 120, + maxLineLength: Infinity, minBodyLength: 0, minBodyLengthTypeExcludes: ['docs'], scopes: [ + 'multiple', // For when a commit applies to multiple components. 'cdk-experimental/column-resize', 'cdk-experimental/combobox', 'cdk-experimental/dialog', @@ -16,6 +17,7 @@ export const commitMessage: CommitMessageConfig = { 'cdk-experimental/popover-edit', 'cdk-experimental/scrolling', 'cdk-experimental/selection', + 'cdk-experimental/table-scroll-container', 'cdk/a11y', 'cdk/accordion', 'cdk/bidi', @@ -63,12 +65,15 @@ export const commitMessage: CommitMessageConfig = { 'material-experimental/mdc-snack-bar', 'material-experimental/mdc-table', 'material-experimental/mdc-tabs', + 'material-experimental/mdc-tooltip', 'material-experimental/mdc-theming', 'material-experimental/mdc-typography', 'material-experimental/menubar', 'material-experimental/popover-edit', 'material-experimental/selection', 'material-moment-adapter', + 'material-date-fns-adapter', + 'material-luxon-adapter', 'material/autocomplete', 'material/badge', 'material/bottom-sheet', @@ -108,6 +113,6 @@ export const commitMessage: CommitMessageConfig = { 'material/toolbar', 'material/tooltip', 'material/tree', - 'youtube-player' + 'youtube-player', ], }; diff --git a/.ng-dev/config.ts b/.ng-dev/config.ts index ef72a842993f..6f2515fc9054 100644 --- a/.ng-dev/config.ts +++ b/.ng-dev/config.ts @@ -1,11 +1,15 @@ import {format} from './format'; import {github} from './github'; -import {merge} from './merge'; +import {pullRequest} from './pull-request'; import {commitMessage} from './commit-message'; +import {caretaker} from './caretaker'; +import {release} from './release'; module.exports = { commitMessage, format, github, - merge, + pullRequest, + caretaker, + release, }; diff --git a/.ng-dev/format.ts b/.ng-dev/format.ts index 6f209c51c66b..14bd51df0763 100644 --- a/.ng-dev/format.ts +++ b/.ng-dev/format.ts @@ -1,4 +1,4 @@ -import {FormatConfig} from '@angular/dev-infra-private/format/config'; +import {FormatConfig} from '@angular/dev-infra-private/ng-dev/format/config'; /** * Configuration for the ng-dev format command. We currently only use the buildifier @@ -6,4 +6,5 @@ import {FormatConfig} from '@angular/dev-infra-private/format/config'; */ export const format: FormatConfig = { buildifier: true, + prettier: true, }; diff --git a/.ng-dev/github.ts b/.ng-dev/github.ts index aea24f6abca3..b48fd6c7fa35 100644 --- a/.ng-dev/github.ts +++ b/.ng-dev/github.ts @@ -1,4 +1,4 @@ -import {GithubConfig} from '@angular/dev-infra-private/utils/config'; +import {GithubConfig} from '@angular/dev-infra-private/ng-dev/utils/config'; /** * Github configuration for the ng-dev command. This repository is @@ -6,5 +6,6 @@ import {GithubConfig} from '@angular/dev-infra-private/utils/config'; */ export const github: GithubConfig = { owner: 'angular', - name: 'components' + name: 'components', + mainBranchName: 'master', }; diff --git a/.ng-dev/merge.ts b/.ng-dev/merge.ts deleted file mode 100644 index 9986012dc9c4..000000000000 --- a/.ng-dev/merge.ts +++ /dev/null @@ -1,27 +0,0 @@ -import {DevInfraMergeConfig} from '@angular/dev-infra-private/pr/merge/config'; -import {getDefaultTargetLabelConfiguration} from '@angular/dev-infra-private/pr/merge/defaults'; -import {github} from './github'; - -/** - * Configuration for the merge tool in `ng-dev`. This sets up the labels which - * are respected by the merge script (e.g. the target labels). - */ -export const merge: DevInfraMergeConfig['merge'] = async api => { - return { - // By default, the merge script merges locally with `git cherry-pick` and autosquash. - // This has the downside of pull requests showing up as `Closed` instead of `Merged`. - // In the components repository, since we don't use fixup or squash commits, we can - // use the Github API merge strategy. That way we ensure that PRs show up as `Merged`. - githubApiMerge: { - default: 'squash', - labels: [ - {pattern: 'preserve commits', method: 'rebase'} - ] - }, - claSignedLabel: 'cla: yes', - mergeReadyLabel: 'merge ready', - commitMessageFixupLabel: 'commit message fixup', - caretakerNoteLabel: 'caretaker note', - labels: await getDefaultTargetLabelConfiguration(api, github, '@angular/cdk'), - }; -}; diff --git a/.ng-dev/pull-request.ts b/.ng-dev/pull-request.ts new file mode 100644 index 000000000000..45006ba5035d --- /dev/null +++ b/.ng-dev/pull-request.ts @@ -0,0 +1,19 @@ +import {PullRequestConfig} from '@angular/dev-infra-private/ng-dev/pr/config'; + +/** + * Configuration for the pull request commands in `ng-dev`. This includes the + * setup for the merge command. + */ +export const pullRequest: PullRequestConfig = { + // By default, the merge script merges locally with `git cherry-pick` and autosquash. + // This has the downside of pull requests showing up as `Closed` instead of `Merged`. + // In the components repository, since we don't use fixup or squash commits, we can + // use the Github API merge strategy. That way we ensure that PRs show up as `Merged`. + githubApiMerge: { + default: 'squash', + labels: [{pattern: 'preserve commits', method: 'rebase'}], + }, + mergeReadyLabel: 'merge ready', + commitMessageFixupLabel: 'commit message fixup', + caretakerNoteLabel: 'caretaker note', +}; diff --git a/.ng-dev/release.ts b/.ng-dev/release.ts new file mode 100644 index 000000000000..c07485e8f494 --- /dev/null +++ b/.ng-dev/release.ts @@ -0,0 +1,100 @@ +import {BuiltPackage, ReleaseConfig} from '@angular/dev-infra-private/ng-dev/release/config'; +import {ReleaseAction} from '@angular/dev-infra-private/ng-dev/release/publish/actions'; +import {SemVer} from 'semver'; +import {assertValidNpmPackageOutput} from '../tools/release-checks/npm-package-output'; +import {fork} from 'child_process'; +import {join} from 'path'; +import {FatalReleaseActionError} from '@angular/dev-infra-private/ng-dev/release/publish/actions-error'; + +const actionProto = ReleaseAction.prototype as any; +const _origStageFn = actionProto.stageVersionForBranchAndCreatePullRequest; +const _origVerifyFn = actionProto._verifyPackageVersions; + +/** Runs the staging sanity release checks for the given new version. */ +async function runStagingReleaseChecks(newVersion: SemVer) { + return new Promise((resolve, reject) => { + // Note: We run the staging release checks in a new node process. This is necessary + // because before staging, the correct publish branch is checked out. If we'd + // directly call into the release checks, the `.ng-dev/release` config would be + // cached by NodeJS and release checks would potentially check for packages which + // no longer exist in the publish branch (or the other way around). + const releaseChecksProcess = fork(join(__dirname, '../tools/release-checks/index.js'), [ + newVersion.format(), + ]); + + releaseChecksProcess.on('close', code => { + if (code !== 0) { + reject(new FatalReleaseActionError()); + } else { + resolve(); + } + }); + }); +} + +// Patches the `@angular/dev-infra-private` release tool to perform sanity checks +// before staging a release. This is temporary until the dev-infra team has implemented +// a more generic solution to running sanity checks before releasing (potentially building +// some of the checks we have in the components repository into the release tool). +actionProto.stageVersionForBranchAndCreatePullRequest = async function (newVersion: SemVer) { + await runStagingReleaseChecks(newVersion); + + return await _origStageFn.apply(this, arguments); +}; + +// Patches the `@angular/dev-infra-private` release tool to perform sanity +// checks of the NPM package output, before publishing to NPM. +actionProto._verifyPackageVersions = async function ( + newVersion: SemVer, + builtPackages: BuiltPackage[], +) { + await assertValidNpmPackageOutput(builtPackages, newVersion); + + return await _origVerifyFn.apply(this, arguments); +}; + +/** + * Packages that will be published as part of the project. + * + * Note: The order of packages here will control how sections + * appear in the changelog. + */ +export const releasePackages = [ + 'cdk', + 'material', + 'google-maps', + 'youtube-player', + 'cdk-experimental', + 'material-experimental', + 'material-moment-adapter', + 'material-luxon-adapter', + 'material-date-fns-adapter', +]; + +/** Configuration for the `ng-dev release` command. */ +export const release: ReleaseConfig = { + releaseNotes: { + useReleaseTitle: true, + groupOrder: releasePackages, + categorizeCommit: commit => { + const [packageName, entryPointName] = commit.scope.split('/'); + const entryPointPrefix = entryPointName ? `**${entryPointName}:** ` : ''; + + // In the `angular/components` repository, commit messages may include entry-point + // information in the scope. We expect commits to be grouped based on their package + // name. Commits are then described with their subject and optional entry-point name. + return { + groupName: packageName, + description: `${entryPointPrefix}${commit.subject}`, + }; + }, + }, + publishRegistry: 'https://wombat-dressing-room.appspot.com', + npmPackages: releasePackages.map(pkg => `@angular/${pkg}`), + buildPackages: async () => { + // The `performNpmReleaseBuild` function is loaded at runtime as loading of the + // script results in an invocation of Bazel for any `yarn ng-dev` command. + const {performNpmReleaseBuild} = await import('../scripts/build-packages-dist'); + return performNpmReleaseBuild(); + }, +}; diff --git a/.ng-dev/tsconfig.json b/.ng-dev/tsconfig.json new file mode 100644 index 000000000000..9e9c1b746523 --- /dev/null +++ b/.ng-dev/tsconfig.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "strict": true, + "target": "es2015", + "module": "commonjs", + "noEmit": true, + "skipLibCheck": true, + "types": [] + }, +} diff --git a/.npmrc b/.npmrc new file mode 100644 index 000000000000..d1cdf2f06be7 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +engine-strict = true \ No newline at end of file diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 000000000000..3027af39c1b9 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +16.10.0 diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000000..5085bcf48958 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,13 @@ +# Generated files for infrastructure. +.yarn/releases/*.cjs + +# These schematic ng-generate files are template files that cannot be formatted. +src/material/schematics/ng-generate/*/files/**/* +src/cdk/schematics/ng-generate/*/files/**/* + +# Schematic ng-update test cases should not be formatted as that could break the +# expected output tests. Generated code does is not formatted according to prettier. +src/cdk/schematics/ng-update/test-cases/**/*_input.ts +src/cdk/schematics/ng-update/test-cases/**/*_expected_output.ts +src/material/schematics/ng-update/test-cases/**/*_input.ts +src/material/schematics/ng-update/test-cases/**/*_expected_output.ts \ No newline at end of file diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 000000000000..da93a7ee3ab0 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,9 @@ +{ + "printWidth": 100, + "singleQuote": true, + "trailingComma": "all", + "quoteProps": "preserve", + "bracketSpacing": false, + "arrowParens": "avoid", + "embeddedLanguageFormatting": "off" +} diff --git a/.stylelintrc.json b/.stylelintrc.json index 0dcf0f8a9588..72cbf7187eea 100644 --- a/.stylelintrc.json +++ b/.stylelintrc.json @@ -1,5 +1,8 @@ { + "customSyntax": "postcss-scss", "defaultSeverity": "error", + "reportNeedlessDisables": true, + "reportInvalidScopeDisables": true, "plugins": [ "./tools/stylelint/loader-rule.js", "./tools/stylelint/no-prefixes/index.ts", @@ -8,16 +11,26 @@ "./tools/stylelint/no-nested-mixin.ts", "./tools/stylelint/no-concrete-rules.ts", "./tools/stylelint/no-top-level-ampersand-in-mixin.ts", - "./tools/stylelint/theme-mixin-api.ts" + "./tools/stylelint/theme-mixin-api.ts", + "./tools/stylelint/no-import.ts", + "./tools/stylelint/single-line-comment-only.ts", + "./tools/stylelint/no-unused-import.ts" ], "rules": { "material/no-prefixes": [true, { - "browsers": ["last 2 versions", "not ie <= 10", "not ie_mob <= 10"], + "browsers": ["last 2 versions", "not dead", "not and_qq > 0", "not OperaMini all", "not ie > 0", "not edge < 78"], "filePattern": "**/!(*-example.css)" }], "material/theme-mixin-api": true, "material/selector-no-deep": true, "material/no-nested-mixin": true, + "material/no-unused-import": true, + "material/single-line-comment-only": [true, { + "filePattern": "\\.scss$" + }], + "material/no-import": [true, { + "exclude": "\\.import\\.scss$" + }], "material/no-ampersand-beyond-selector-start": [true, { "filePattern": "-theme\\.scss$" }], @@ -69,8 +82,8 @@ "declaration-block-semicolon-newline-after": "always-multi-line", "declaration-colon-space-after": "always-single-line", "declaration-property-value-disallowed-list": [ - {"/.*/": ["initial"]}, - {"message": "The `initial` value is not supported in IE."} + {"/.*/": ["initial"]}, + {"message": "The `initial` value is not supported in IE."} ], "block-closing-brace-newline-after": "always", diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 6aa839723a0b..ba8740af8547 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,10 +1,10 @@ { // See http://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations. // Extension identifier format: ${publisher}.${name}. Example: vscode.csharp - + // List of extensions which should be recommended for users of this workspace. "recommendations": [ "ms-vscode.vscode-typescript-tslint-plugin", - "xaver.clang-format", - ], + "esbenp.prettier-vscode" + ] } diff --git a/.vscode/settings.json b/.vscode/settings.json index c53375cdbd96..277935bdd679 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,7 +1,4 @@ { - // Please install https://marketplace.visualstudio.com/items?itemName=xaver.clang-format to take advantage of `clang-format` in VSCode. - // (See https://clang.llvm.org/docs/ClangFormat.html for more info `clang-format`.) - "clang-format.executable": "${workspaceRoot}/node_modules/.bin/clang-format", "files.watcherExclude": { "**/.git/objects/**": true, "**/.git/subtree-cache/**": true, @@ -11,9 +8,16 @@ }, "search.exclude": { "**/node_modules": true, - "**/bower_components": true, "**/bazel-out": true, "**/dist": true, }, "git.ignoreLimitWarning": true, + "[javascript]": { + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true + }, + "[typescript]": { + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true + } } diff --git a/.yarn/releases/yarn-1.22.17.cjs b/.yarn/releases/yarn-1.22.17.cjs new file mode 100755 index 000000000000..3cf00ad6264d --- /dev/null +++ b/.yarn/releases/yarn-1.22.17.cjs @@ -0,0 +1,147520 @@ +#!/usr/bin/env node +module.exports = +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // identity function for calling harmony imports with the correct context +/******/ __webpack_require__.i = function(value) { return value; }; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 549); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports) { + +module.exports = require("path"); + +/***/ }), +/* 1 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = __extends; +/* unused harmony export __assign */ +/* unused harmony export __rest */ +/* unused harmony export __decorate */ +/* unused harmony export __param */ +/* unused harmony export __metadata */ +/* unused harmony export __awaiter */ +/* unused harmony export __generator */ +/* unused harmony export __exportStar */ +/* unused harmony export __values */ +/* unused harmony export __read */ +/* unused harmony export __spread */ +/* unused harmony export __await */ +/* unused harmony export __asyncGenerator */ +/* unused harmony export __asyncDelegator */ +/* unused harmony export __asyncValues */ +/* unused harmony export __makeTemplateObject */ +/* unused harmony export __importStar */ +/* unused harmony export __importDefault */ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + } + return __assign.apply(this, arguments); +} + +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +} + +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +function __awaiter(thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function __exportStar(m, exports) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} + +function __values(o) { + var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; + if (m) return m.call(o); + return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; +} + +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result.default = mod; + return result; +} + +function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +exports.__esModule = true; + +var _promise = __webpack_require__(227); + +var _promise2 = _interopRequireDefault(_promise); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (fn) { + return function () { + var gen = fn.apply(this, arguments); + return new _promise2.default(function (resolve, reject) { + function step(key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + + if (info.done) { + resolve(value); + } else { + return _promise2.default.resolve(value).then(function (value) { + step("next", value); + }, function (err) { + step("throw", err); + }); + } + } + + return step("next"); + }); + }; +}; + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + +module.exports = require("util"); + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + +module.exports = require("fs"); + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getFirstSuitableFolder = exports.readFirstAvailableStream = exports.makeTempDir = exports.hardlinksWork = exports.writeFilePreservingEol = exports.getFileSizeOnDisk = exports.walk = exports.symlink = exports.find = exports.readJsonAndFile = exports.readJson = exports.readFileAny = exports.hardlinkBulk = exports.copyBulk = exports.unlink = exports.glob = exports.link = exports.chmod = exports.lstat = exports.exists = exports.mkdirp = exports.stat = exports.access = exports.rename = exports.readdir = exports.realpath = exports.readlink = exports.writeFile = exports.open = exports.readFileBuffer = exports.lockQueue = exports.constants = undefined; + +var _asyncToGenerator2; + +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(2)); +} + +let buildActionsForCopy = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, events, possibleExtraneous, reporter) { + + // + let build = (() => { + var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { + const src = data.src, + dest = data.dest, + type = data.type; + + const onFresh = data.onFresh || noop; + const onDone = data.onDone || noop; + + // TODO https://github.com/yarnpkg/yarn/issues/3751 + // related to bundled dependencies handling + if (files.has(dest.toLowerCase())) { + reporter.verbose(`The case-insensitive file ${dest} shouldn't be copied twice in one bulk copy`); + } else { + files.add(dest.toLowerCase()); + } + + if (type === 'symlink') { + yield mkdirp((_path || _load_path()).default.dirname(dest)); + onFresh(); + actions.symlink.push({ + dest, + linkname: src + }); + onDone(); + return; + } + + if (events.ignoreBasenames.indexOf((_path || _load_path()).default.basename(src)) >= 0) { + // ignored file + return; + } + + const srcStat = yield lstat(src); + let srcFiles; + + if (srcStat.isDirectory()) { + srcFiles = yield readdir(src); + } + + let destStat; + try { + // try accessing the destination + destStat = yield lstat(dest); + } catch (e) { + // proceed if destination doesn't exist, otherwise error + if (e.code !== 'ENOENT') { + throw e; + } + } + + // if destination exists + if (destStat) { + const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink(); + const bothFolders = srcStat.isDirectory() && destStat.isDirectory(); + const bothFiles = srcStat.isFile() && destStat.isFile(); + + // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving + // us modes that aren't valid. investigate this, it's generally safe to proceed. + + /* if (srcStat.mode !== destStat.mode) { + try { + await access(dest, srcStat.mode); + } catch (err) {} + } */ + + if (bothFiles && artifactFiles.has(dest)) { + // this file gets changed during build, likely by a custom install script. Don't bother checking it. + onDone(); + reporter.verbose(reporter.lang('verboseFileSkipArtifact', src)); + return; + } + + if (bothFiles && srcStat.size === destStat.size && (0, (_fsNormalized || _load_fsNormalized()).fileDatesEqual)(srcStat.mtime, destStat.mtime)) { + // we can safely assume this is the same file + onDone(); + reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.size, +srcStat.mtime)); + return; + } + + if (bothSymlinks) { + const srcReallink = yield readlink(src); + if (srcReallink === (yield readlink(dest))) { + // if both symlinks are the same then we can continue on + onDone(); + reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink)); + return; + } + } + + if (bothFolders) { + // mark files that aren't in this folder as possibly extraneous + const destFiles = yield readdir(dest); + invariant(srcFiles, 'src files not initialised'); + + for (var _iterator4 = destFiles, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) { + var _ref6; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref6 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref6 = _i4.value; + } + + const file = _ref6; + + if (srcFiles.indexOf(file) < 0) { + const loc = (_path || _load_path()).default.join(dest, file); + possibleExtraneous.add(loc); + + if ((yield lstat(loc)).isDirectory()) { + for (var _iterator5 = yield readdir(loc), _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) { + var _ref7; + + if (_isArray5) { + if (_i5 >= _iterator5.length) break; + _ref7 = _iterator5[_i5++]; + } else { + _i5 = _iterator5.next(); + if (_i5.done) break; + _ref7 = _i5.value; + } + + const file = _ref7; + + possibleExtraneous.add((_path || _load_path()).default.join(loc, file)); + } + } + } + } + } + } + + if (destStat && destStat.isSymbolicLink()) { + yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(dest); + destStat = null; + } + + if (srcStat.isSymbolicLink()) { + onFresh(); + const linkname = yield readlink(src); + actions.symlink.push({ + dest, + linkname + }); + onDone(); + } else if (srcStat.isDirectory()) { + if (!destStat) { + reporter.verbose(reporter.lang('verboseFileFolder', dest)); + yield mkdirp(dest); + } + + const destParts = dest.split((_path || _load_path()).default.sep); + while (destParts.length) { + files.add(destParts.join((_path || _load_path()).default.sep).toLowerCase()); + destParts.pop(); + } + + // push all files to queue + invariant(srcFiles, 'src files not initialised'); + let remaining = srcFiles.length; + if (!remaining) { + onDone(); + } + for (var _iterator6 = srcFiles, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) { + var _ref8; + + if (_isArray6) { + if (_i6 >= _iterator6.length) break; + _ref8 = _iterator6[_i6++]; + } else { + _i6 = _iterator6.next(); + if (_i6.done) break; + _ref8 = _i6.value; + } + + const file = _ref8; + + queue.push({ + dest: (_path || _load_path()).default.join(dest, file), + onFresh, + onDone: function (_onDone) { + function onDone() { + return _onDone.apply(this, arguments); + } + + onDone.toString = function () { + return _onDone.toString(); + }; + + return onDone; + }(function () { + if (--remaining === 0) { + onDone(); + } + }), + src: (_path || _load_path()).default.join(src, file) + }); + } + } else if (srcStat.isFile()) { + onFresh(); + actions.file.push({ + src, + dest, + atime: srcStat.atime, + mtime: srcStat.mtime, + mode: srcStat.mode + }); + onDone(); + } else { + throw new Error(`unsure how to copy this: ${src}`); + } + }); + + return function build(_x5) { + return _ref5.apply(this, arguments); + }; + })(); + + const artifactFiles = new Set(events.artifactFiles || []); + const files = new Set(); + + // initialise events + for (var _iterator = queue, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref2; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref2 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref2 = _i.value; + } + + const item = _ref2; + + const onDone = item.onDone; + item.onDone = function () { + events.onProgress(item.dest); + if (onDone) { + onDone(); + } + }; + } + events.onStart(queue.length); + + // start building actions + const actions = { + file: [], + symlink: [], + link: [] + }; + + // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items + // at a time due to the requirement to push items onto the queue + while (queue.length) { + const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS); + yield Promise.all(items.map(build)); + } + + // simulate the existence of some files to prevent considering them extraneous + for (var _iterator2 = artifactFiles, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { + var _ref3; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref3 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref3 = _i2.value; + } + + const file = _ref3; + + if (possibleExtraneous.has(file)) { + reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file)); + possibleExtraneous.delete(file); + } + } + + for (var _iterator3 = possibleExtraneous, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { + var _ref4; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref4 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref4 = _i3.value; + } + + const loc = _ref4; + + if (files.has(loc.toLowerCase())) { + possibleExtraneous.delete(loc); + } + } + + return actions; + }); + + return function buildActionsForCopy(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); + +let buildActionsForHardlink = (() => { + var _ref9 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, events, possibleExtraneous, reporter) { + + // + let build = (() => { + var _ref13 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { + const src = data.src, + dest = data.dest; + + const onFresh = data.onFresh || noop; + const onDone = data.onDone || noop; + if (files.has(dest.toLowerCase())) { + // Fixes issue https://github.com/yarnpkg/yarn/issues/2734 + // When bulk hardlinking we have A -> B structure that we want to hardlink to A1 -> B1, + // package-linker passes that modules A1 and B1 need to be hardlinked, + // the recursive linking algorithm of A1 ends up scheduling files in B1 to be linked twice which will case + // an exception. + onDone(); + return; + } + files.add(dest.toLowerCase()); + + if (events.ignoreBasenames.indexOf((_path || _load_path()).default.basename(src)) >= 0) { + // ignored file + return; + } + + const srcStat = yield lstat(src); + let srcFiles; + + if (srcStat.isDirectory()) { + srcFiles = yield readdir(src); + } + + const destExists = yield exists(dest); + if (destExists) { + const destStat = yield lstat(dest); + + const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink(); + const bothFolders = srcStat.isDirectory() && destStat.isDirectory(); + const bothFiles = srcStat.isFile() && destStat.isFile(); + + if (srcStat.mode !== destStat.mode) { + try { + yield access(dest, srcStat.mode); + } catch (err) { + // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving + // us modes that aren't valid. investigate this, it's generally safe to proceed. + reporter.verbose(err); + } + } + + if (bothFiles && artifactFiles.has(dest)) { + // this file gets changed during build, likely by a custom install script. Don't bother checking it. + onDone(); + reporter.verbose(reporter.lang('verboseFileSkipArtifact', src)); + return; + } + + // correct hardlink + if (bothFiles && srcStat.ino !== null && srcStat.ino === destStat.ino) { + onDone(); + reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.ino)); + return; + } + + if (bothSymlinks) { + const srcReallink = yield readlink(src); + if (srcReallink === (yield readlink(dest))) { + // if both symlinks are the same then we can continue on + onDone(); + reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink)); + return; + } + } + + if (bothFolders) { + // mark files that aren't in this folder as possibly extraneous + const destFiles = yield readdir(dest); + invariant(srcFiles, 'src files not initialised'); + + for (var _iterator10 = destFiles, _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : _iterator10[Symbol.iterator]();;) { + var _ref14; + + if (_isArray10) { + if (_i10 >= _iterator10.length) break; + _ref14 = _iterator10[_i10++]; + } else { + _i10 = _iterator10.next(); + if (_i10.done) break; + _ref14 = _i10.value; + } + + const file = _ref14; + + if (srcFiles.indexOf(file) < 0) { + const loc = (_path || _load_path()).default.join(dest, file); + possibleExtraneous.add(loc); + + if ((yield lstat(loc)).isDirectory()) { + for (var _iterator11 = yield readdir(loc), _isArray11 = Array.isArray(_iterator11), _i11 = 0, _iterator11 = _isArray11 ? _iterator11 : _iterator11[Symbol.iterator]();;) { + var _ref15; + + if (_isArray11) { + if (_i11 >= _iterator11.length) break; + _ref15 = _iterator11[_i11++]; + } else { + _i11 = _iterator11.next(); + if (_i11.done) break; + _ref15 = _i11.value; + } + + const file = _ref15; + + possibleExtraneous.add((_path || _load_path()).default.join(loc, file)); + } + } + } + } + } + } + + if (srcStat.isSymbolicLink()) { + onFresh(); + const linkname = yield readlink(src); + actions.symlink.push({ + dest, + linkname + }); + onDone(); + } else if (srcStat.isDirectory()) { + reporter.verbose(reporter.lang('verboseFileFolder', dest)); + yield mkdirp(dest); + + const destParts = dest.split((_path || _load_path()).default.sep); + while (destParts.length) { + files.add(destParts.join((_path || _load_path()).default.sep).toLowerCase()); + destParts.pop(); + } + + // push all files to queue + invariant(srcFiles, 'src files not initialised'); + let remaining = srcFiles.length; + if (!remaining) { + onDone(); + } + for (var _iterator12 = srcFiles, _isArray12 = Array.isArray(_iterator12), _i12 = 0, _iterator12 = _isArray12 ? _iterator12 : _iterator12[Symbol.iterator]();;) { + var _ref16; + + if (_isArray12) { + if (_i12 >= _iterator12.length) break; + _ref16 = _iterator12[_i12++]; + } else { + _i12 = _iterator12.next(); + if (_i12.done) break; + _ref16 = _i12.value; + } + + const file = _ref16; + + queue.push({ + onFresh, + src: (_path || _load_path()).default.join(src, file), + dest: (_path || _load_path()).default.join(dest, file), + onDone: function (_onDone2) { + function onDone() { + return _onDone2.apply(this, arguments); + } + + onDone.toString = function () { + return _onDone2.toString(); + }; + + return onDone; + }(function () { + if (--remaining === 0) { + onDone(); + } + }) + }); + } + } else if (srcStat.isFile()) { + onFresh(); + actions.link.push({ + src, + dest, + removeDest: destExists + }); + onDone(); + } else { + throw new Error(`unsure how to copy this: ${src}`); + } + }); + + return function build(_x10) { + return _ref13.apply(this, arguments); + }; + })(); + + const artifactFiles = new Set(events.artifactFiles || []); + const files = new Set(); + + // initialise events + for (var _iterator7 = queue, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) { + var _ref10; + + if (_isArray7) { + if (_i7 >= _iterator7.length) break; + _ref10 = _iterator7[_i7++]; + } else { + _i7 = _iterator7.next(); + if (_i7.done) break; + _ref10 = _i7.value; + } + + const item = _ref10; + + const onDone = item.onDone || noop; + item.onDone = function () { + events.onProgress(item.dest); + onDone(); + }; + } + events.onStart(queue.length); + + // start building actions + const actions = { + file: [], + symlink: [], + link: [] + }; + + // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items + // at a time due to the requirement to push items onto the queue + while (queue.length) { + const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS); + yield Promise.all(items.map(build)); + } + + // simulate the existence of some files to prevent considering them extraneous + for (var _iterator8 = artifactFiles, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : _iterator8[Symbol.iterator]();;) { + var _ref11; + + if (_isArray8) { + if (_i8 >= _iterator8.length) break; + _ref11 = _iterator8[_i8++]; + } else { + _i8 = _iterator8.next(); + if (_i8.done) break; + _ref11 = _i8.value; + } + + const file = _ref11; + + if (possibleExtraneous.has(file)) { + reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file)); + possibleExtraneous.delete(file); + } + } + + for (var _iterator9 = possibleExtraneous, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : _iterator9[Symbol.iterator]();;) { + var _ref12; + + if (_isArray9) { + if (_i9 >= _iterator9.length) break; + _ref12 = _iterator9[_i9++]; + } else { + _i9 = _iterator9.next(); + if (_i9.done) break; + _ref12 = _i9.value; + } + + const loc = _ref12; + + if (files.has(loc.toLowerCase())) { + possibleExtraneous.delete(loc); + } + } + + return actions; + }); + + return function buildActionsForHardlink(_x6, _x7, _x8, _x9) { + return _ref9.apply(this, arguments); + }; +})(); + +let copyBulk = exports.copyBulk = (() => { + var _ref17 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, reporter, _events) { + const events = { + onStart: _events && _events.onStart || noop, + onProgress: _events && _events.onProgress || noop, + possibleExtraneous: _events ? _events.possibleExtraneous : new Set(), + ignoreBasenames: _events && _events.ignoreBasenames || [], + artifactFiles: _events && _events.artifactFiles || [] + }; + + const actions = yield buildActionsForCopy(queue, events, events.possibleExtraneous, reporter); + events.onStart(actions.file.length + actions.symlink.length + actions.link.length); + + const fileActions = actions.file; + + const currentlyWriting = new Map(); + + yield (_promise || _load_promise()).queue(fileActions, (() => { + var _ref18 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { + let writePromise; + while (writePromise = currentlyWriting.get(data.dest)) { + yield writePromise; + } + + reporter.verbose(reporter.lang('verboseFileCopy', data.src, data.dest)); + const copier = (0, (_fsNormalized || _load_fsNormalized()).copyFile)(data, function () { + return currentlyWriting.delete(data.dest); + }); + currentlyWriting.set(data.dest, copier); + events.onProgress(data.dest); + return copier; + }); + + return function (_x14) { + return _ref18.apply(this, arguments); + }; + })(), CONCURRENT_QUEUE_ITEMS); + + // we need to copy symlinks last as they could reference files we were copying + const symlinkActions = actions.symlink; + yield (_promise || _load_promise()).queue(symlinkActions, function (data) { + const linkname = (_path || _load_path()).default.resolve((_path || _load_path()).default.dirname(data.dest), data.linkname); + reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname)); + return symlink(linkname, data.dest); + }); + }); + + return function copyBulk(_x11, _x12, _x13) { + return _ref17.apply(this, arguments); + }; +})(); + +let hardlinkBulk = exports.hardlinkBulk = (() => { + var _ref19 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, reporter, _events) { + const events = { + onStart: _events && _events.onStart || noop, + onProgress: _events && _events.onProgress || noop, + possibleExtraneous: _events ? _events.possibleExtraneous : new Set(), + artifactFiles: _events && _events.artifactFiles || [], + ignoreBasenames: [] + }; + + const actions = yield buildActionsForHardlink(queue, events, events.possibleExtraneous, reporter); + events.onStart(actions.file.length + actions.symlink.length + actions.link.length); + + const fileActions = actions.link; + + yield (_promise || _load_promise()).queue(fileActions, (() => { + var _ref20 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { + reporter.verbose(reporter.lang('verboseFileLink', data.src, data.dest)); + if (data.removeDest) { + yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(data.dest); + } + yield link(data.src, data.dest); + }); + + return function (_x18) { + return _ref20.apply(this, arguments); + }; + })(), CONCURRENT_QUEUE_ITEMS); + + // we need to copy symlinks last as they could reference files we were copying + const symlinkActions = actions.symlink; + yield (_promise || _load_promise()).queue(symlinkActions, function (data) { + const linkname = (_path || _load_path()).default.resolve((_path || _load_path()).default.dirname(data.dest), data.linkname); + reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname)); + return symlink(linkname, data.dest); + }); + }); + + return function hardlinkBulk(_x15, _x16, _x17) { + return _ref19.apply(this, arguments); + }; +})(); + +let readFileAny = exports.readFileAny = (() => { + var _ref21 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (files) { + for (var _iterator13 = files, _isArray13 = Array.isArray(_iterator13), _i13 = 0, _iterator13 = _isArray13 ? _iterator13 : _iterator13[Symbol.iterator]();;) { + var _ref22; + + if (_isArray13) { + if (_i13 >= _iterator13.length) break; + _ref22 = _iterator13[_i13++]; + } else { + _i13 = _iterator13.next(); + if (_i13.done) break; + _ref22 = _i13.value; + } + + const file = _ref22; + + if (yield exists(file)) { + return readFile(file); + } + } + return null; + }); + + return function readFileAny(_x19) { + return _ref21.apply(this, arguments); + }; +})(); + +let readJson = exports.readJson = (() => { + var _ref23 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { + return (yield readJsonAndFile(loc)).object; + }); + + return function readJson(_x20) { + return _ref23.apply(this, arguments); + }; +})(); + +let readJsonAndFile = exports.readJsonAndFile = (() => { + var _ref24 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { + const file = yield readFile(loc); + try { + return { + object: (0, (_map || _load_map()).default)(JSON.parse(stripBOM(file))), + content: file + }; + } catch (err) { + err.message = `${loc}: ${err.message}`; + throw err; + } + }); + + return function readJsonAndFile(_x21) { + return _ref24.apply(this, arguments); + }; +})(); + +let find = exports.find = (() => { + var _ref25 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (filename, dir) { + const parts = dir.split((_path || _load_path()).default.sep); + + while (parts.length) { + const loc = parts.concat(filename).join((_path || _load_path()).default.sep); + + if (yield exists(loc)) { + return loc; + } else { + parts.pop(); + } + } + + return false; + }); + + return function find(_x22, _x23) { + return _ref25.apply(this, arguments); + }; +})(); + +let symlink = exports.symlink = (() => { + var _ref26 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (src, dest) { + if (process.platform !== 'win32') { + // use relative paths otherwise which will be retained if the directory is moved + src = (_path || _load_path()).default.relative((_path || _load_path()).default.dirname(dest), src); + // When path.relative returns an empty string for the current directory, we should instead use + // '.', which is a valid fs.symlink target. + src = src || '.'; + } + + try { + const stats = yield lstat(dest); + if (stats.isSymbolicLink()) { + const resolved = dest; + if (resolved === src) { + return; + } + } + } catch (err) { + if (err.code !== 'ENOENT') { + throw err; + } + } + + // We use rimraf for unlink which never throws an ENOENT on missing target + yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(dest); + + if (process.platform === 'win32') { + // use directory junctions if possible on win32, this requires absolute paths + yield fsSymlink(src, dest, 'junction'); + } else { + yield fsSymlink(src, dest); + } + }); + + return function symlink(_x24, _x25) { + return _ref26.apply(this, arguments); + }; +})(); + +let walk = exports.walk = (() => { + var _ref27 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir, relativeDir, ignoreBasenames = new Set()) { + let files = []; + + let filenames = yield readdir(dir); + if (ignoreBasenames.size) { + filenames = filenames.filter(function (name) { + return !ignoreBasenames.has(name); + }); + } + + for (var _iterator14 = filenames, _isArray14 = Array.isArray(_iterator14), _i14 = 0, _iterator14 = _isArray14 ? _iterator14 : _iterator14[Symbol.iterator]();;) { + var _ref28; + + if (_isArray14) { + if (_i14 >= _iterator14.length) break; + _ref28 = _iterator14[_i14++]; + } else { + _i14 = _iterator14.next(); + if (_i14.done) break; + _ref28 = _i14.value; + } + + const name = _ref28; + + const relative = relativeDir ? (_path || _load_path()).default.join(relativeDir, name) : name; + const loc = (_path || _load_path()).default.join(dir, name); + const stat = yield lstat(loc); + + files.push({ + relative, + basename: name, + absolute: loc, + mtime: +stat.mtime + }); + + if (stat.isDirectory()) { + files = files.concat((yield walk(loc, relative, ignoreBasenames))); + } + } + + return files; + }); + + return function walk(_x26, _x27) { + return _ref27.apply(this, arguments); + }; +})(); + +let getFileSizeOnDisk = exports.getFileSizeOnDisk = (() => { + var _ref29 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { + const stat = yield lstat(loc); + const size = stat.size, + blockSize = stat.blksize; + + + return Math.ceil(size / blockSize) * blockSize; + }); + + return function getFileSizeOnDisk(_x28) { + return _ref29.apply(this, arguments); + }; +})(); + +let getEolFromFile = (() => { + var _ref30 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path) { + if (!(yield exists(path))) { + return undefined; + } + + const buffer = yield readFileBuffer(path); + + for (let i = 0; i < buffer.length; ++i) { + if (buffer[i] === cr) { + return '\r\n'; + } + if (buffer[i] === lf) { + return '\n'; + } + } + return undefined; + }); + + return function getEolFromFile(_x29) { + return _ref30.apply(this, arguments); + }; +})(); + +let writeFilePreservingEol = exports.writeFilePreservingEol = (() => { + var _ref31 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path, data) { + const eol = (yield getEolFromFile(path)) || (_os || _load_os()).default.EOL; + if (eol !== '\n') { + data = data.replace(/\n/g, eol); + } + yield writeFile(path, data); + }); + + return function writeFilePreservingEol(_x30, _x31) { + return _ref31.apply(this, arguments); + }; +})(); + +let hardlinksWork = exports.hardlinksWork = (() => { + var _ref32 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir) { + const filename = 'test-file' + Math.random(); + const file = (_path || _load_path()).default.join(dir, filename); + const fileLink = (_path || _load_path()).default.join(dir, filename + '-link'); + try { + yield writeFile(file, 'test'); + yield link(file, fileLink); + } catch (err) { + return false; + } finally { + yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(file); + yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(fileLink); + } + return true; + }); + + return function hardlinksWork(_x32) { + return _ref32.apply(this, arguments); + }; +})(); + +// not a strict polyfill for Node's fs.mkdtemp + + +let makeTempDir = exports.makeTempDir = (() => { + var _ref33 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (prefix) { + const dir = (_path || _load_path()).default.join((_os || _load_os()).default.tmpdir(), `yarn-${prefix || ''}-${Date.now()}-${Math.random()}`); + yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(dir); + yield mkdirp(dir); + return dir; + }); + + return function makeTempDir(_x33) { + return _ref33.apply(this, arguments); + }; +})(); + +let readFirstAvailableStream = exports.readFirstAvailableStream = (() => { + var _ref34 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (paths) { + for (var _iterator15 = paths, _isArray15 = Array.isArray(_iterator15), _i15 = 0, _iterator15 = _isArray15 ? _iterator15 : _iterator15[Symbol.iterator]();;) { + var _ref35; + + if (_isArray15) { + if (_i15 >= _iterator15.length) break; + _ref35 = _iterator15[_i15++]; + } else { + _i15 = _iterator15.next(); + if (_i15.done) break; + _ref35 = _i15.value; + } + + const path = _ref35; + + try { + const fd = yield open(path, 'r'); + return (_fs || _load_fs()).default.createReadStream(path, { fd }); + } catch (err) { + // Try the next one + } + } + return null; + }); + + return function readFirstAvailableStream(_x34) { + return _ref34.apply(this, arguments); + }; +})(); + +let getFirstSuitableFolder = exports.getFirstSuitableFolder = (() => { + var _ref36 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (paths, mode = constants.W_OK | constants.X_OK) { + const result = { + skipped: [], + folder: null + }; + + for (var _iterator16 = paths, _isArray16 = Array.isArray(_iterator16), _i16 = 0, _iterator16 = _isArray16 ? _iterator16 : _iterator16[Symbol.iterator]();;) { + var _ref37; + + if (_isArray16) { + if (_i16 >= _iterator16.length) break; + _ref37 = _iterator16[_i16++]; + } else { + _i16 = _iterator16.next(); + if (_i16.done) break; + _ref37 = _i16.value; + } + + const folder = _ref37; + + try { + yield mkdirp(folder); + yield access(folder, mode); + + result.folder = folder; + + return result; + } catch (error) { + result.skipped.push({ + error, + folder + }); + } + } + return result; + }); + + return function getFirstSuitableFolder(_x35) { + return _ref36.apply(this, arguments); + }; +})(); + +exports.copy = copy; +exports.readFile = readFile; +exports.readFileRaw = readFileRaw; +exports.normalizeOS = normalizeOS; + +var _fs; + +function _load_fs() { + return _fs = _interopRequireDefault(__webpack_require__(4)); +} + +var _glob; + +function _load_glob() { + return _glob = _interopRequireDefault(__webpack_require__(99)); +} + +var _os; + +function _load_os() { + return _os = _interopRequireDefault(__webpack_require__(46)); +} + +var _path; + +function _load_path() { + return _path = _interopRequireDefault(__webpack_require__(0)); +} + +var _blockingQueue; + +function _load_blockingQueue() { + return _blockingQueue = _interopRequireDefault(__webpack_require__(111)); +} + +var _promise; + +function _load_promise() { + return _promise = _interopRequireWildcard(__webpack_require__(51)); +} + +var _promise2; + +function _load_promise2() { + return _promise2 = __webpack_require__(51); +} + +var _map; + +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(29)); +} + +var _fsNormalized; + +function _load_fsNormalized() { + return _fsNormalized = __webpack_require__(219); +} + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const constants = exports.constants = typeof (_fs || _load_fs()).default.constants !== 'undefined' ? (_fs || _load_fs()).default.constants : { + R_OK: (_fs || _load_fs()).default.R_OK, + W_OK: (_fs || _load_fs()).default.W_OK, + X_OK: (_fs || _load_fs()).default.X_OK +}; + +const lockQueue = exports.lockQueue = new (_blockingQueue || _load_blockingQueue()).default('fs lock'); + +const readFileBuffer = exports.readFileBuffer = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.readFile); +const open = exports.open = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.open); +const writeFile = exports.writeFile = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.writeFile); +const readlink = exports.readlink = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.readlink); +const realpath = exports.realpath = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.realpath); +const readdir = exports.readdir = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.readdir); +const rename = exports.rename = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.rename); +const access = exports.access = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.access); +const stat = exports.stat = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.stat); +const mkdirp = exports.mkdirp = (0, (_promise2 || _load_promise2()).promisify)(__webpack_require__(145)); +const exists = exports.exists = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.exists, true); +const lstat = exports.lstat = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.lstat); +const chmod = exports.chmod = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.chmod); +const link = exports.link = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.link); +const glob = exports.glob = (0, (_promise2 || _load_promise2()).promisify)((_glob || _load_glob()).default); +exports.unlink = (_fsNormalized || _load_fsNormalized()).unlink; + +// fs.copyFile uses the native file copying instructions on the system, performing much better +// than any JS-based solution and consumes fewer resources. Repeated testing to fine tune the +// concurrency level revealed 128 as the sweet spot on a quad-core, 16 CPU Intel system with SSD. + +const CONCURRENT_QUEUE_ITEMS = (_fs || _load_fs()).default.copyFile ? 128 : 4; + +const fsSymlink = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.symlink); +const invariant = __webpack_require__(9); +const stripBOM = __webpack_require__(160); + +const noop = () => {}; + +function copy(src, dest, reporter) { + return copyBulk([{ src, dest }], reporter); +} + +function _readFile(loc, encoding) { + return new Promise((resolve, reject) => { + (_fs || _load_fs()).default.readFile(loc, encoding, function (err, content) { + if (err) { + reject(err); + } else { + resolve(content); + } + }); + }); +} + +function readFile(loc) { + return _readFile(loc, 'utf8').then(normalizeOS); +} + +function readFileRaw(loc) { + return _readFile(loc, 'binary'); +} + +function normalizeOS(body) { + return body.replace(/\r\n/g, '\n'); +} + +const cr = '\r'.charCodeAt(0); +const lf = '\n'.charCodeAt(0); + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +class MessageError extends Error { + constructor(msg, code) { + super(msg); + this.code = code; + } + +} + +exports.MessageError = MessageError; +class ProcessSpawnError extends MessageError { + constructor(msg, code, process) { + super(msg, code); + this.process = process; + } + +} + +exports.ProcessSpawnError = ProcessSpawnError; +class SecurityError extends MessageError {} + +exports.SecurityError = SecurityError; +class ProcessTermError extends MessageError {} + +exports.ProcessTermError = ProcessTermError; +class ResponseError extends Error { + constructor(msg, responseCode) { + super(msg); + this.responseCode = responseCode; + } + +} + +exports.ResponseError = ResponseError; +class OneTimePasswordError extends Error {} +exports.OneTimePasswordError = OneTimePasswordError; + +/***/ }), +/* 7 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Subscriber; }); +/* unused harmony export SafeSubscriber */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(1); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util_isFunction__ = __webpack_require__(154); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Observer__ = __webpack_require__(420); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Subscription__ = __webpack_require__(25); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__internal_symbol_rxSubscriber__ = __webpack_require__(321); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__config__ = __webpack_require__(186); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__util_hostReportError__ = __webpack_require__(323); +/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ + + + + + + + +var Subscriber = /*@__PURE__*/ (function (_super) { + __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](Subscriber, _super); + function Subscriber(destinationOrNext, error, complete) { + var _this = _super.call(this) || this; + _this.syncErrorValue = null; + _this.syncErrorThrown = false; + _this.syncErrorThrowable = false; + _this.isStopped = false; + _this._parentSubscription = null; + switch (arguments.length) { + case 0: + _this.destination = __WEBPACK_IMPORTED_MODULE_2__Observer__["a" /* empty */]; + break; + case 1: + if (!destinationOrNext) { + _this.destination = __WEBPACK_IMPORTED_MODULE_2__Observer__["a" /* empty */]; + break; + } + if (typeof destinationOrNext === 'object') { + if (destinationOrNext instanceof Subscriber) { + _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; + _this.destination = destinationOrNext; + destinationOrNext.add(_this); + } + else { + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext); + } + break; + } + default: + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); + break; + } + return _this; + } + Subscriber.prototype[__WEBPACK_IMPORTED_MODULE_4__internal_symbol_rxSubscriber__["a" /* rxSubscriber */]] = function () { return this; }; + Subscriber.create = function (next, error, complete) { + var subscriber = new Subscriber(next, error, complete); + subscriber.syncErrorThrowable = false; + return subscriber; + }; + Subscriber.prototype.next = function (value) { + if (!this.isStopped) { + this._next(value); + } + }; + Subscriber.prototype.error = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this._error(err); + } + }; + Subscriber.prototype.complete = function () { + if (!this.isStopped) { + this.isStopped = true; + this._complete(); + } + }; + Subscriber.prototype.unsubscribe = function () { + if (this.closed) { + return; + } + this.isStopped = true; + _super.prototype.unsubscribe.call(this); + }; + Subscriber.prototype._next = function (value) { + this.destination.next(value); + }; + Subscriber.prototype._error = function (err) { + this.destination.error(err); + this.unsubscribe(); + }; + Subscriber.prototype._complete = function () { + this.destination.complete(); + this.unsubscribe(); + }; + Subscriber.prototype._unsubscribeAndRecycle = function () { + var _a = this, _parent = _a._parent, _parents = _a._parents; + this._parent = null; + this._parents = null; + this.unsubscribe(); + this.closed = false; + this.isStopped = false; + this._parent = _parent; + this._parents = _parents; + this._parentSubscription = null; + return this; + }; + return Subscriber; +}(__WEBPACK_IMPORTED_MODULE_3__Subscription__["a" /* Subscription */])); + +var SafeSubscriber = /*@__PURE__*/ (function (_super) { + __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](SafeSubscriber, _super); + function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { + var _this = _super.call(this) || this; + _this._parentSubscriber = _parentSubscriber; + var next; + var context = _this; + if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util_isFunction__["a" /* isFunction */])(observerOrNext)) { + next = observerOrNext; + } + else if (observerOrNext) { + next = observerOrNext.next; + error = observerOrNext.error; + complete = observerOrNext.complete; + if (observerOrNext !== __WEBPACK_IMPORTED_MODULE_2__Observer__["a" /* empty */]) { + context = Object.create(observerOrNext); + if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util_isFunction__["a" /* isFunction */])(context.unsubscribe)) { + _this.add(context.unsubscribe.bind(context)); + } + context.unsubscribe = _this.unsubscribe.bind(_this); + } + } + _this._context = context; + _this._next = next; + _this._error = error; + _this._complete = complete; + return _this; + } + SafeSubscriber.prototype.next = function (value) { + if (!this.isStopped && this._next) { + var _parentSubscriber = this._parentSubscriber; + if (!__WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._next, value); + } + else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + var useDeprecatedSynchronousErrorHandling = __WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling; + if (this._error) { + if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._error, err); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, this._error, err); + this.unsubscribe(); + } + } + else if (!_parentSubscriber.syncErrorThrowable) { + this.unsubscribe(); + if (useDeprecatedSynchronousErrorHandling) { + throw err; + } + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_6__util_hostReportError__["a" /* hostReportError */])(err); + } + else { + if (useDeprecatedSynchronousErrorHandling) { + _parentSubscriber.syncErrorValue = err; + _parentSubscriber.syncErrorThrown = true; + } + else { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_6__util_hostReportError__["a" /* hostReportError */])(err); + } + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.complete = function () { + var _this = this; + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + if (this._complete) { + var wrappedComplete = function () { return _this._complete.call(_this._context); }; + if (!__WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(wrappedComplete); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, wrappedComplete); + this.unsubscribe(); + } + } + else { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { + try { + fn.call(this._context, value); + } + catch (err) { + this.unsubscribe(); + if (__WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling) { + throw err; + } + else { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_6__util_hostReportError__["a" /* hostReportError */])(err); + } + } + }; + SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { + if (!__WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling) { + throw new Error('bad call'); + } + try { + fn.call(this._context, value); + } + catch (err) { + if (__WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling) { + parent.syncErrorValue = err; + parent.syncErrorThrown = true; + return true; + } + else { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_6__util_hostReportError__["a" /* hostReportError */])(err); + return true; + } + } + return false; + }; + SafeSubscriber.prototype._unsubscribe = function () { + var _parentSubscriber = this._parentSubscriber; + this._context = null; + this._parentSubscriber = null; + _parentSubscriber.unsubscribe(); + }; + return SafeSubscriber; +}(Subscriber)); + +//# sourceMappingURL=Subscriber.js.map + + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getPathKey = getPathKey; +const os = __webpack_require__(46); +const path = __webpack_require__(0); +const userHome = __webpack_require__(67).default; + +var _require = __webpack_require__(225); + +const getCacheDir = _require.getCacheDir, + getConfigDir = _require.getConfigDir, + getDataDir = _require.getDataDir; + +const isWebpackBundle = __webpack_require__(278); + +const DEPENDENCY_TYPES = exports.DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'optionalDependencies', 'peerDependencies']; +const OWNED_DEPENDENCY_TYPES = exports.OWNED_DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'optionalDependencies']; + +const RESOLUTIONS = exports.RESOLUTIONS = 'resolutions'; +const MANIFEST_FIELDS = exports.MANIFEST_FIELDS = [RESOLUTIONS, ...DEPENDENCY_TYPES]; + +const SUPPORTED_NODE_VERSIONS = exports.SUPPORTED_NODE_VERSIONS = '^4.8.0 || ^5.7.0 || ^6.2.2 || >=8.0.0'; + +const YARN_REGISTRY = exports.YARN_REGISTRY = 'https://registry.yarnpkg.com'; +const NPM_REGISTRY_RE = exports.NPM_REGISTRY_RE = /https?:\/\/registry\.npmjs\.org/g; + +const YARN_DOCS = exports.YARN_DOCS = 'https://yarnpkg.com/en/docs/cli/'; +const YARN_INSTALLER_SH = exports.YARN_INSTALLER_SH = 'https://yarnpkg.com/install.sh'; +const YARN_INSTALLER_MSI = exports.YARN_INSTALLER_MSI = 'https://yarnpkg.com/latest.msi'; + +const SELF_UPDATE_VERSION_URL = exports.SELF_UPDATE_VERSION_URL = 'https://yarnpkg.com/latest-version'; + +// cache version, bump whenever we make backwards incompatible changes +const CACHE_VERSION = exports.CACHE_VERSION = 6; + +// lockfile version, bump whenever we make backwards incompatible changes +const LOCKFILE_VERSION = exports.LOCKFILE_VERSION = 1; + +// max amount of network requests to perform concurrently +const NETWORK_CONCURRENCY = exports.NETWORK_CONCURRENCY = 8; + +// HTTP timeout used when downloading packages +const NETWORK_TIMEOUT = exports.NETWORK_TIMEOUT = 30 * 1000; // in milliseconds + +// max amount of child processes to execute concurrently +const CHILD_CONCURRENCY = exports.CHILD_CONCURRENCY = 5; + +const REQUIRED_PACKAGE_KEYS = exports.REQUIRED_PACKAGE_KEYS = ['name', 'version', '_uid']; + +function getPreferredCacheDirectories() { + const preferredCacheDirectories = [getCacheDir()]; + + if (process.getuid) { + // $FlowFixMe: process.getuid exists, dammit + preferredCacheDirectories.push(path.join(os.tmpdir(), `.yarn-cache-${process.getuid()}`)); + } + + preferredCacheDirectories.push(path.join(os.tmpdir(), `.yarn-cache`)); + + return preferredCacheDirectories; +} + +const PREFERRED_MODULE_CACHE_DIRECTORIES = exports.PREFERRED_MODULE_CACHE_DIRECTORIES = getPreferredCacheDirectories(); +const CONFIG_DIRECTORY = exports.CONFIG_DIRECTORY = getConfigDir(); +const DATA_DIRECTORY = exports.DATA_DIRECTORY = getDataDir(); +const LINK_REGISTRY_DIRECTORY = exports.LINK_REGISTRY_DIRECTORY = path.join(DATA_DIRECTORY, 'link'); +const GLOBAL_MODULE_DIRECTORY = exports.GLOBAL_MODULE_DIRECTORY = path.join(DATA_DIRECTORY, 'global'); + +const NODE_BIN_PATH = exports.NODE_BIN_PATH = process.execPath; +const YARN_BIN_PATH = exports.YARN_BIN_PATH = getYarnBinPath(); + +// Webpack needs to be configured with node.__dirname/__filename = false +function getYarnBinPath() { + if (isWebpackBundle) { + return __filename; + } else { + return path.join(__dirname, '..', 'bin', 'yarn.js'); + } +} + +const NODE_MODULES_FOLDER = exports.NODE_MODULES_FOLDER = 'node_modules'; +const NODE_PACKAGE_JSON = exports.NODE_PACKAGE_JSON = 'package.json'; + +const PNP_FILENAME = exports.PNP_FILENAME = '.pnp.js'; + +const POSIX_GLOBAL_PREFIX = exports.POSIX_GLOBAL_PREFIX = `${process.env.DESTDIR || ''}/usr/local`; +const FALLBACK_GLOBAL_PREFIX = exports.FALLBACK_GLOBAL_PREFIX = path.join(userHome, '.yarn'); + +const META_FOLDER = exports.META_FOLDER = '.yarn-meta'; +const INTEGRITY_FILENAME = exports.INTEGRITY_FILENAME = '.yarn-integrity'; +const LOCKFILE_FILENAME = exports.LOCKFILE_FILENAME = 'yarn.lock'; +const METADATA_FILENAME = exports.METADATA_FILENAME = '.yarn-metadata.json'; +const TARBALL_FILENAME = exports.TARBALL_FILENAME = '.yarn-tarball.tgz'; +const CLEAN_FILENAME = exports.CLEAN_FILENAME = '.yarnclean'; + +const NPM_LOCK_FILENAME = exports.NPM_LOCK_FILENAME = 'package-lock.json'; +const NPM_SHRINKWRAP_FILENAME = exports.NPM_SHRINKWRAP_FILENAME = 'npm-shrinkwrap.json'; + +const DEFAULT_INDENT = exports.DEFAULT_INDENT = ' '; +const SINGLE_INSTANCE_PORT = exports.SINGLE_INSTANCE_PORT = 31997; +const SINGLE_INSTANCE_FILENAME = exports.SINGLE_INSTANCE_FILENAME = '.yarn-single-instance'; + +const ENV_PATH_KEY = exports.ENV_PATH_KEY = getPathKey(process.platform, process.env); + +function getPathKey(platform, env) { + let pathKey = 'PATH'; + + // windows calls its path "Path" usually, but this is not guaranteed. + if (platform === 'win32') { + pathKey = 'Path'; + + for (const key in env) { + if (key.toLowerCase() === 'path') { + pathKey = key; + } + } + } + + return pathKey; +} + +const VERSION_COLOR_SCHEME = exports.VERSION_COLOR_SCHEME = { + major: 'red', + premajor: 'red', + minor: 'yellow', + preminor: 'yellow', + patch: 'green', + prepatch: 'green', + prerelease: 'red', + unchanged: 'white', + unknown: 'red' +}; + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +/** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + +var NODE_ENV = process.env.NODE_ENV; + +var invariant = function(condition, format, a, b, c, d, e, f) { + if (NODE_ENV !== 'production') { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } +}; + +module.exports = invariant; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var YAMLException = __webpack_require__(55); + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +module.exports = Type; + + +/***/ }), +/* 11 */ +/***/ (function(module, exports) { + +module.exports = require("crypto"); + +/***/ }), +/* 12 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Observable; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__util_canReportError__ = __webpack_require__(322); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util_toSubscriber__ = __webpack_require__(932); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__internal_symbol_observable__ = __webpack_require__(118); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util_pipe__ = __webpack_require__(324); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__config__ = __webpack_require__(186); +/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_internal_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ + + + + + +var Observable = /*@__PURE__*/ (function () { + function Observable(subscribe) { + this._isScalar = false; + if (subscribe) { + this._subscribe = subscribe; + } + } + Observable.prototype.lift = function (operator) { + var observable = new Observable(); + observable.source = this; + observable.operator = operator; + return observable; + }; + Observable.prototype.subscribe = function (observerOrNext, error, complete) { + var operator = this.operator; + var sink = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util_toSubscriber__["a" /* toSubscriber */])(observerOrNext, error, complete); + if (operator) { + operator.call(sink, this.source); + } + else { + sink.add(this.source || (__WEBPACK_IMPORTED_MODULE_4__config__["a" /* config */].useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? + this._subscribe(sink) : + this._trySubscribe(sink)); + } + if (__WEBPACK_IMPORTED_MODULE_4__config__["a" /* config */].useDeprecatedSynchronousErrorHandling) { + if (sink.syncErrorThrowable) { + sink.syncErrorThrowable = false; + if (sink.syncErrorThrown) { + throw sink.syncErrorValue; + } + } + } + return sink; + }; + Observable.prototype._trySubscribe = function (sink) { + try { + return this._subscribe(sink); + } + catch (err) { + if (__WEBPACK_IMPORTED_MODULE_4__config__["a" /* config */].useDeprecatedSynchronousErrorHandling) { + sink.syncErrorThrown = true; + sink.syncErrorValue = err; + } + if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__util_canReportError__["a" /* canReportError */])(sink)) { + sink.error(err); + } + else { + console.warn(err); + } + } + }; + Observable.prototype.forEach = function (next, promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var subscription; + subscription = _this.subscribe(function (value) { + try { + next(value); + } + catch (err) { + reject(err); + if (subscription) { + subscription.unsubscribe(); + } + } + }, reject, resolve); + }); + }; + Observable.prototype._subscribe = function (subscriber) { + var source = this.source; + return source && source.subscribe(subscriber); + }; + Observable.prototype[__WEBPACK_IMPORTED_MODULE_2__internal_symbol_observable__["a" /* observable */]] = function () { + return this; + }; + Observable.prototype.pipe = function () { + var operations = []; + for (var _i = 0; _i < arguments.length; _i++) { + operations[_i] = arguments[_i]; + } + if (operations.length === 0) { + return this; + } + return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__util_pipe__["b" /* pipeFromArray */])(operations)(this); + }; + Observable.prototype.toPromise = function (promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var value; + _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); + }); + }; + Observable.create = function (subscribe) { + return new Observable(subscribe); + }; + return Observable; +}()); + +function getPromiseCtor(promiseCtor) { + if (!promiseCtor) { + promiseCtor = __WEBPACK_IMPORTED_MODULE_4__config__["a" /* config */].Promise || Promise; + } + if (!promiseCtor) { + throw new Error('no Promise impl found'); + } + return promiseCtor; +} +//# sourceMappingURL=Observable.js.map + + +/***/ }), +/* 13 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return OuterSubscriber; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(1); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Subscriber__ = __webpack_require__(7); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ + + +var OuterSubscriber = /*@__PURE__*/ (function (_super) { + __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](OuterSubscriber, _super); + function OuterSubscriber() { + return _super !== null && _super.apply(this, arguments) || this; + } + OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.destination.next(innerValue); + }; + OuterSubscriber.prototype.notifyError = function (error, innerSub) { + this.destination.error(error); + }; + OuterSubscriber.prototype.notifyComplete = function (innerSub) { + this.destination.complete(); + }; + return OuterSubscriber; +}(__WEBPACK_IMPORTED_MODULE_1__Subscriber__["a" /* Subscriber */])); + +//# sourceMappingURL=OuterSubscriber.js.map + + +/***/ }), +/* 14 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = subscribeToResult; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__InnerSubscriber__ = __webpack_require__(84); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__subscribeTo__ = __webpack_require__(446); +/** PURE_IMPORTS_START _InnerSubscriber,_subscribeTo PURE_IMPORTS_END */ + + +function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, destination) { + if (destination === void 0) { + destination = new __WEBPACK_IMPORTED_MODULE_0__InnerSubscriber__["a" /* InnerSubscriber */](outerSubscriber, outerValue, outerIndex); + } + if (destination.closed) { + return; + } + return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__subscribeTo__["a" /* subscribeTo */])(result)(destination); +} +//# sourceMappingURL=subscribeToResult.js.map + + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* eslint-disable node/no-deprecated-api */ + + + +var buffer = __webpack_require__(64) +var Buffer = buffer.Buffer + +var safer = {} + +var key + +for (key in buffer) { + if (!buffer.hasOwnProperty(key)) continue + if (key === 'SlowBuffer' || key === 'Buffer') continue + safer[key] = buffer[key] +} + +var Safer = safer.Buffer = {} +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue + if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue + Safer[key] = Buffer[key] +} + +safer.Buffer.prototype = Buffer.prototype + +if (!Safer.from || Safer.from === Uint8Array.from) { + Safer.from = function (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) + } + if (value && typeof value.length === 'undefined') { + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) + } + return Buffer(value, encodingOrOffset, length) + } +} + +if (!Safer.alloc) { + Safer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + var buf = Buffer(size) + if (!fill || fill.length === 0) { + buf.fill(0) + } else if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + return buf + } +} + +if (!safer.kStringMaxLength) { + try { + safer.kStringMaxLength = process.binding('buffer').kStringMaxLength + } catch (e) { + // we can't determine kStringMaxLength in environments where process.binding + // is unsupported, so let's not set it + } +} + +if (!safer.constants) { + safer.constants = { + MAX_LENGTH: safer.kMaxLength + } + if (safer.kStringMaxLength) { + safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength + } +} + +module.exports = safer + + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright (c) 2012, Mark Cavage. All rights reserved. +// Copyright 2015 Joyent, Inc. + +var assert = __webpack_require__(28); +var Stream = __webpack_require__(23).Stream; +var util = __webpack_require__(3); + + +///--- Globals + +/* JSSTYLED */ +var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; + + +///--- Internal + +function _capitalize(str) { + return (str.charAt(0).toUpperCase() + str.slice(1)); +} + +function _toss(name, expected, oper, arg, actual) { + throw new assert.AssertionError({ + message: util.format('%s (%s) is required', name, expected), + actual: (actual === undefined) ? typeof (arg) : actual(arg), + expected: expected, + operator: oper || '===', + stackStartFunction: _toss.caller + }); +} + +function _getClass(arg) { + return (Object.prototype.toString.call(arg).slice(8, -1)); +} + +function noop() { + // Why even bother with asserts? +} + + +///--- Exports + +var types = { + bool: { + check: function (arg) { return typeof (arg) === 'boolean'; } + }, + func: { + check: function (arg) { return typeof (arg) === 'function'; } + }, + string: { + check: function (arg) { return typeof (arg) === 'string'; } + }, + object: { + check: function (arg) { + return typeof (arg) === 'object' && arg !== null; + } + }, + number: { + check: function (arg) { + return typeof (arg) === 'number' && !isNaN(arg); + } + }, + finite: { + check: function (arg) { + return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); + } + }, + buffer: { + check: function (arg) { return Buffer.isBuffer(arg); }, + operator: 'Buffer.isBuffer' + }, + array: { + check: function (arg) { return Array.isArray(arg); }, + operator: 'Array.isArray' + }, + stream: { + check: function (arg) { return arg instanceof Stream; }, + operator: 'instanceof', + actual: _getClass + }, + date: { + check: function (arg) { return arg instanceof Date; }, + operator: 'instanceof', + actual: _getClass + }, + regexp: { + check: function (arg) { return arg instanceof RegExp; }, + operator: 'instanceof', + actual: _getClass + }, + uuid: { + check: function (arg) { + return typeof (arg) === 'string' && UUID_REGEXP.test(arg); + }, + operator: 'isUUID' + } +}; + +function _setExports(ndebug) { + var keys = Object.keys(types); + var out; + + /* re-export standard assert */ + if (process.env.NODE_NDEBUG) { + out = noop; + } else { + out = function (arg, msg) { + if (!arg) { + _toss(msg, 'true', arg); + } + }; + } + + /* standard checks */ + keys.forEach(function (k) { + if (ndebug) { + out[k] = noop; + return; + } + var type = types[k]; + out[k] = function (arg, msg) { + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); + } + }; + }); + + /* optional checks */ + keys.forEach(function (k) { + var name = 'optional' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); + } + }; + }); + + /* arrayOf checks */ + keys.forEach(function (k) { + var name = 'arrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); + + /* optionalArrayOf checks */ + keys.forEach(function (k) { + var name = 'optionalArrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); + + /* re-export built-in assertions */ + Object.keys(assert).forEach(function (k) { + if (k === 'AssertionError') { + out[k] = assert[k]; + return; + } + if (ndebug) { + out[k] = noop; + return; + } + out[k] = assert[k]; + }); + + /* export ourselves (for unit tests _only_) */ + out._setExports = _setExports; + + return out; +} + +module.exports = _setExports(process.env.NODE_NDEBUG); + + +/***/ }), +/* 17 */ +/***/ (function(module, exports) { + +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self + // eslint-disable-next-line no-new-func + : Function('return this')(); +if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef + + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.sortAlpha = sortAlpha; +exports.sortOptionsByFlags = sortOptionsByFlags; +exports.entries = entries; +exports.removePrefix = removePrefix; +exports.removeSuffix = removeSuffix; +exports.addSuffix = addSuffix; +exports.hyphenate = hyphenate; +exports.camelCase = camelCase; +exports.compareSortedArrays = compareSortedArrays; +exports.sleep = sleep; +const _camelCase = __webpack_require__(230); + +function sortAlpha(a, b) { + // sort alphabetically in a deterministic way + const shortLen = Math.min(a.length, b.length); + for (let i = 0; i < shortLen; i++) { + const aChar = a.charCodeAt(i); + const bChar = b.charCodeAt(i); + if (aChar !== bChar) { + return aChar - bChar; + } + } + return a.length - b.length; +} + +function sortOptionsByFlags(a, b) { + const aOpt = a.flags.replace(/-/g, ''); + const bOpt = b.flags.replace(/-/g, ''); + return sortAlpha(aOpt, bOpt); +} + +function entries(obj) { + const entries = []; + if (obj) { + for (const key in obj) { + entries.push([key, obj[key]]); + } + } + return entries; +} + +function removePrefix(pattern, prefix) { + if (pattern.startsWith(prefix)) { + pattern = pattern.slice(prefix.length); + } + + return pattern; +} + +function removeSuffix(pattern, suffix) { + if (pattern.endsWith(suffix)) { + return pattern.slice(0, -suffix.length); + } + + return pattern; +} + +function addSuffix(pattern, suffix) { + if (!pattern.endsWith(suffix)) { + return pattern + suffix; + } + + return pattern; +} + +function hyphenate(str) { + return str.replace(/[A-Z]/g, match => { + return '-' + match.charAt(0).toLowerCase(); + }); +} + +function camelCase(str) { + if (/[A-Z]/.test(str)) { + return null; + } else { + return _camelCase(str); + } +} + +function compareSortedArrays(array1, array2) { + if (array1.length !== array2.length) { + return false; + } + for (let i = 0, len = array1.length; i < len; i++) { + if (array1[i] !== array2[i]) { + return false; + } + } + return true; +} + +function sleep(ms) { + return new Promise(resolve => { + setTimeout(resolve, ms); + }); +} + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.stringify = exports.parse = undefined; + +var _asyncToGenerator2; + +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(2)); +} + +var _parse; + +function _load_parse() { + return _parse = __webpack_require__(106); +} + +Object.defineProperty(exports, 'parse', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_parse || _load_parse()).default; + } +}); + +var _stringify; + +function _load_stringify() { + return _stringify = __webpack_require__(200); +} + +Object.defineProperty(exports, 'stringify', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_stringify || _load_stringify()).default; + } +}); +exports.implodeEntry = implodeEntry; +exports.explodeEntry = explodeEntry; + +var _misc; + +function _load_misc() { + return _misc = __webpack_require__(18); +} + +var _normalizePattern; + +function _load_normalizePattern() { + return _normalizePattern = __webpack_require__(37); +} + +var _parse2; + +function _load_parse2() { + return _parse2 = _interopRequireDefault(__webpack_require__(106)); +} + +var _constants; + +function _load_constants() { + return _constants = __webpack_require__(8); +} + +var _fs; + +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(5)); +} + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const invariant = __webpack_require__(9); + +const path = __webpack_require__(0); +const ssri = __webpack_require__(65); + +function getName(pattern) { + return (0, (_normalizePattern || _load_normalizePattern()).normalizePattern)(pattern).name; +} + +function blankObjectUndefined(obj) { + return obj && Object.keys(obj).length ? obj : undefined; +} + +function keyForRemote(remote) { + return remote.resolved || (remote.reference && remote.hash ? `${remote.reference}#${remote.hash}` : null); +} + +function serializeIntegrity(integrity) { + // We need this because `Integrity.toString()` does not use sorting to ensure a stable string output + // See https://git.io/vx2Hy + return integrity.toString().split(' ').sort().join(' '); +} + +function implodeEntry(pattern, obj) { + const inferredName = getName(pattern); + const integrity = obj.integrity ? serializeIntegrity(obj.integrity) : ''; + const imploded = { + name: inferredName === obj.name ? undefined : obj.name, + version: obj.version, + uid: obj.uid === obj.version ? undefined : obj.uid, + resolved: obj.resolved, + registry: obj.registry === 'npm' ? undefined : obj.registry, + dependencies: blankObjectUndefined(obj.dependencies), + optionalDependencies: blankObjectUndefined(obj.optionalDependencies), + permissions: blankObjectUndefined(obj.permissions), + prebuiltVariants: blankObjectUndefined(obj.prebuiltVariants) + }; + if (integrity) { + imploded.integrity = integrity; + } + return imploded; +} + +function explodeEntry(pattern, obj) { + obj.optionalDependencies = obj.optionalDependencies || {}; + obj.dependencies = obj.dependencies || {}; + obj.uid = obj.uid || obj.version; + obj.permissions = obj.permissions || {}; + obj.registry = obj.registry || 'npm'; + obj.name = obj.name || getName(pattern); + const integrity = obj.integrity; + if (integrity && integrity.isIntegrity) { + obj.integrity = ssri.parse(integrity); + } + return obj; +} + +class Lockfile { + constructor({ cache, source, parseResultType } = {}) { + this.source = source || ''; + this.cache = cache; + this.parseResultType = parseResultType; + } + + // source string if the `cache` was parsed + + + // if true, we're parsing an old yarn file and need to update integrity fields + hasEntriesExistWithoutIntegrity() { + if (!this.cache) { + return false; + } + + for (const key in this.cache) { + // $FlowFixMe - `this.cache` is clearly defined at this point + if (!/^.*@(file:|http)/.test(key) && this.cache[key] && !this.cache[key].integrity) { + return true; + } + } + + return false; + } + + static fromDirectory(dir, reporter) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // read the manifest in this directory + const lockfileLoc = path.join(dir, (_constants || _load_constants()).LOCKFILE_FILENAME); + + let lockfile; + let rawLockfile = ''; + let parseResult; + + if (yield (_fs || _load_fs()).exists(lockfileLoc)) { + rawLockfile = yield (_fs || _load_fs()).readFile(lockfileLoc); + parseResult = (0, (_parse2 || _load_parse2()).default)(rawLockfile, lockfileLoc); + + if (reporter) { + if (parseResult.type === 'merge') { + reporter.info(reporter.lang('lockfileMerged')); + } else if (parseResult.type === 'conflict') { + reporter.warn(reporter.lang('lockfileConflict')); + } + } + + lockfile = parseResult.object; + } else if (reporter) { + reporter.info(reporter.lang('noLockfileFound')); + } + + if (lockfile && lockfile.__metadata) { + const lockfilev2 = lockfile; + lockfile = {}; + } + + return new Lockfile({ cache: lockfile, source: rawLockfile, parseResultType: parseResult && parseResult.type }); + })(); + } + + getLocked(pattern) { + const cache = this.cache; + if (!cache) { + return undefined; + } + + const shrunk = pattern in cache && cache[pattern]; + + if (typeof shrunk === 'string') { + return this.getLocked(shrunk); + } else if (shrunk) { + explodeEntry(pattern, shrunk); + return shrunk; + } + + return undefined; + } + + removePattern(pattern) { + const cache = this.cache; + if (!cache) { + return; + } + delete cache[pattern]; + } + + getLockfile(patterns) { + const lockfile = {}; + const seen = new Map(); + + // order by name so that lockfile manifest is assigned to the first dependency with this manifest + // the others that have the same remoteKey will just refer to the first + // ordering allows for consistency in lockfile when it is serialized + const sortedPatternsKeys = Object.keys(patterns).sort((_misc || _load_misc()).sortAlpha); + + for (var _iterator = sortedPatternsKeys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + const pattern = _ref; + + const pkg = patterns[pattern]; + const remote = pkg._remote, + ref = pkg._reference; + + invariant(ref, 'Package is missing a reference'); + invariant(remote, 'Package is missing a remote'); + + const remoteKey = keyForRemote(remote); + const seenPattern = remoteKey && seen.get(remoteKey); + if (seenPattern) { + // no point in duplicating it + lockfile[pattern] = seenPattern; + + // if we're relying on our name being inferred and two of the patterns have + // different inferred names then we need to set it + if (!seenPattern.name && getName(pattern) !== pkg.name) { + seenPattern.name = pkg.name; + } + continue; + } + const obj = implodeEntry(pattern, { + name: pkg.name, + version: pkg.version, + uid: pkg._uid, + resolved: remote.resolved, + integrity: remote.integrity, + registry: remote.registry, + dependencies: pkg.dependencies, + peerDependencies: pkg.peerDependencies, + optionalDependencies: pkg.optionalDependencies, + permissions: ref.permissions, + prebuiltVariants: pkg.prebuiltVariants + }); + + lockfile[pattern] = obj; + + if (remoteKey) { + seen.set(remoteKey, obj); + } + } + + return lockfile; + } +} +exports.default = Lockfile; + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +exports.__esModule = true; + +var _assign = __webpack_require__(591); + +var _assign2 = _interopRequireDefault(_assign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = _assign2.default || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; +}; + +/***/ }), +/* 21 */ +/***/ (function(module, exports, __webpack_require__) { + +var store = __webpack_require__(133)('wks'); +var uid = __webpack_require__(137); +var Symbol = __webpack_require__(17).Symbol; +var USE_SYMBOL = typeof Symbol == 'function'; + +var $exports = module.exports = function (name) { + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); +}; + +$exports.store = store; + + +/***/ }), +/* 22 */ +/***/ (function(module, exports) { + +exports = module.exports = SemVer; + +// The debug function is excluded entirely from the minified version. +/* nomin */ var debug; +/* nomin */ if (typeof process === 'object' && + /* nomin */ process.env && + /* nomin */ process.env.NODE_DEBUG && + /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) + /* nomin */ debug = function() { + /* nomin */ var args = Array.prototype.slice.call(arguments, 0); + /* nomin */ args.unshift('SEMVER'); + /* nomin */ console.log.apply(console, args); + /* nomin */ }; +/* nomin */ else + /* nomin */ debug = function() {}; + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0'; + +var MAX_LENGTH = 256; +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16; + +// The actual regexps go on exports.re +var re = exports.re = []; +var src = exports.src = []; +var R = 0; + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++; +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; +var NUMERICIDENTIFIERLOOSE = R++; +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; + + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++; +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; + + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++; +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')'; + +var MAINVERSIONLOOSE = R++; +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++; +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + +var PRERELEASEIDENTIFIERLOOSE = R++; +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++; +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; + +var PRERELEASELOOSE = R++; +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++; +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++; +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; + + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++; +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?'; + +src[FULL] = '^' + FULLPLAIN + '$'; + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?'; + +var LOOSE = R++; +src[LOOSE] = '^' + LOOSEPLAIN + '$'; + +var GTLT = R++; +src[GTLT] = '((?:<|>)?=?)'; + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++; +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; +var XRANGEIDENTIFIER = R++; +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; + +var XRANGEPLAIN = R++; +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGEPLAINLOOSE = R++; +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGE = R++; +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; +var XRANGELOOSE = R++; +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++; +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])'; + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++; +src[LONETILDE] = '(?:~>?)'; + +var TILDETRIM = R++; +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); +var tildeTrimReplace = '$1~'; + +var TILDE = R++; +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; +var TILDELOOSE = R++; +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++; +src[LONECARET] = '(?:\\^)'; + +var CARETTRIM = R++; +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); +var caretTrimReplace = '$1^'; + +var CARET = R++; +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; +var CARETLOOSE = R++; +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++; +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; +var COMPARATOR = R++; +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; + + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++; +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); +var comparatorTrimReplace = '$1$2$3'; + + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++; +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$'; + +var HYPHENRANGELOOSE = R++; +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$'; + +// Star ranges basically just allow anything at all. +var STAR = R++; +src[STAR] = '(<|>)?=?\\s*\\*'; + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]); + if (!re[i]) + re[i] = new RegExp(src[i]); +} + +exports.parse = parse; +function parse(version, loose) { + if (version instanceof SemVer) + return version; + + if (typeof version !== 'string') + return null; + + if (version.length > MAX_LENGTH) + return null; + + var r = loose ? re[LOOSE] : re[FULL]; + if (!r.test(version)) + return null; + + try { + return new SemVer(version, loose); + } catch (er) { + return null; + } +} + +exports.valid = valid; +function valid(version, loose) { + var v = parse(version, loose); + return v ? v.version : null; +} + + +exports.clean = clean; +function clean(version, loose) { + var s = parse(version.trim().replace(/^[=v]+/, ''), loose); + return s ? s.version : null; +} + +exports.SemVer = SemVer; + +function SemVer(version, loose) { + if (version instanceof SemVer) { + if (version.loose === loose) + return version; + else + version = version.version; + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version); + } + + if (version.length > MAX_LENGTH) + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + + if (!(this instanceof SemVer)) + return new SemVer(version, loose); + + debug('SemVer', version, loose); + this.loose = loose; + var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); + + if (!m) + throw new TypeError('Invalid Version: ' + version); + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) + throw new TypeError('Invalid major version') + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) + throw new TypeError('Invalid minor version') + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) + throw new TypeError('Invalid patch version') + + // numberify any prerelease numeric ids + if (!m[4]) + this.prerelease = []; + else + this.prerelease = m[4].split('.').map(function(id) { + if (/^[0-9]+$/.test(id)) { + var num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) + return num; + } + return id; + }); + + this.build = m[5] ? m[5].split('.') : []; + this.format(); +} + +SemVer.prototype.format = function() { + this.version = this.major + '.' + this.minor + '.' + this.patch; + if (this.prerelease.length) + this.version += '-' + this.prerelease.join('.'); + return this.version; +}; + +SemVer.prototype.toString = function() { + return this.version; +}; + +SemVer.prototype.compare = function(other) { + debug('SemVer.compare', this.version, this.loose, other); + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return this.compareMain(other) || this.comparePre(other); +}; + +SemVer.prototype.compareMain = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch); +}; + +SemVer.prototype.comparePre = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) + return -1; + else if (!this.prerelease.length && other.prerelease.length) + return 1; + else if (!this.prerelease.length && !other.prerelease.length) + return 0; + + var i = 0; + do { + var a = this.prerelease[i]; + var b = other.prerelease[i]; + debug('prerelease compare', i, a, b); + if (a === undefined && b === undefined) + return 0; + else if (b === undefined) + return 1; + else if (a === undefined) + return -1; + else if (a === b) + continue; + else + return compareIdentifiers(a, b); + } while (++i); +}; + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) + this.major++; + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) + this.minor++; + this.patch = 0; + this.prerelease = []; + break; + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) + this.patch++; + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) + this.prerelease = [0]; + else { + var i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) // didn't increment anything + this.prerelease.push(0); + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) + this.prerelease = [identifier, 0]; + } else + this.prerelease = [identifier, 0]; + } + break; + + default: + throw new Error('invalid increment argument: ' + release); + } + this.format(); + this.raw = this.version; + return this; +}; + +exports.inc = inc; +function inc(version, release, loose, identifier) { + if (typeof(loose) === 'string') { + identifier = loose; + loose = undefined; + } + + try { + return new SemVer(version, loose).inc(release, identifier).version; + } catch (er) { + return null; + } +} + +exports.diff = diff; +function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + if (v1.prerelease.length || v2.prerelease.length) { + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return 'pre'+key; + } + } + } + return 'prerelease'; + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return key; + } + } + } + } +} + +exports.compareIdentifiers = compareIdentifiers; + +var numeric = /^[0-9]+$/; +function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return (anum && !bnum) ? -1 : + (bnum && !anum) ? 1 : + a < b ? -1 : + a > b ? 1 : + 0; +} + +exports.rcompareIdentifiers = rcompareIdentifiers; +function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); +} + +exports.major = major; +function major(a, loose) { + return new SemVer(a, loose).major; +} + +exports.minor = minor; +function minor(a, loose) { + return new SemVer(a, loose).minor; +} + +exports.patch = patch; +function patch(a, loose) { + return new SemVer(a, loose).patch; +} + +exports.compare = compare; +function compare(a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)); +} + +exports.compareLoose = compareLoose; +function compareLoose(a, b) { + return compare(a, b, true); +} + +exports.rcompare = rcompare; +function rcompare(a, b, loose) { + return compare(b, a, loose); +} + +exports.sort = sort; +function sort(list, loose) { + return list.sort(function(a, b) { + return exports.compare(a, b, loose); + }); +} + +exports.rsort = rsort; +function rsort(list, loose) { + return list.sort(function(a, b) { + return exports.rcompare(a, b, loose); + }); +} + +exports.gt = gt; +function gt(a, b, loose) { + return compare(a, b, loose) > 0; +} + +exports.lt = lt; +function lt(a, b, loose) { + return compare(a, b, loose) < 0; +} + +exports.eq = eq; +function eq(a, b, loose) { + return compare(a, b, loose) === 0; +} + +exports.neq = neq; +function neq(a, b, loose) { + return compare(a, b, loose) !== 0; +} + +exports.gte = gte; +function gte(a, b, loose) { + return compare(a, b, loose) >= 0; +} + +exports.lte = lte; +function lte(a, b, loose) { + return compare(a, b, loose) <= 0; +} + +exports.cmp = cmp; +function cmp(a, op, b, loose) { + var ret; + switch (op) { + case '===': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a === b; + break; + case '!==': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a !== b; + break; + case '': case '=': case '==': ret = eq(a, b, loose); break; + case '!=': ret = neq(a, b, loose); break; + case '>': ret = gt(a, b, loose); break; + case '>=': ret = gte(a, b, loose); break; + case '<': ret = lt(a, b, loose); break; + case '<=': ret = lte(a, b, loose); break; + default: throw new TypeError('Invalid operator: ' + op); + } + return ret; +} + +exports.Comparator = Comparator; +function Comparator(comp, loose) { + if (comp instanceof Comparator) { + if (comp.loose === loose) + return comp; + else + comp = comp.value; + } + + if (!(this instanceof Comparator)) + return new Comparator(comp, loose); + + debug('comparator', comp, loose); + this.loose = loose; + this.parse(comp); + + if (this.semver === ANY) + this.value = ''; + else + this.value = this.operator + this.semver.version; + + debug('comp', this); +} + +var ANY = {}; +Comparator.prototype.parse = function(comp) { + var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var m = comp.match(r); + + if (!m) + throw new TypeError('Invalid comparator: ' + comp); + + this.operator = m[1]; + if (this.operator === '=') + this.operator = ''; + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) + this.semver = ANY; + else + this.semver = new SemVer(m[2], this.loose); +}; + +Comparator.prototype.toString = function() { + return this.value; +}; + +Comparator.prototype.test = function(version) { + debug('Comparator.test', version, this.loose); + + if (this.semver === ANY) + return true; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + return cmp(version, this.operator, this.semver, this.loose); +}; + +Comparator.prototype.intersects = function(comp, loose) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required'); + } + + var rangeTmp; + + if (this.operator === '') { + rangeTmp = new Range(comp.value, loose); + return satisfies(this.value, rangeTmp, loose); + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, loose); + return satisfies(comp.semver, rangeTmp, loose); + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + var sameSemVer = this.semver.version === comp.semver.version; + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, loose) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')); + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, loose) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')); + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; +}; + + +exports.Range = Range; +function Range(range, loose) { + if (range instanceof Range) { + if (range.loose === loose) { + return range; + } else { + return new Range(range.raw, loose); + } + } + + if (range instanceof Comparator) { + return new Range(range.value, loose); + } + + if (!(this instanceof Range)) + return new Range(range, loose); + + this.loose = loose; + + // First, split based on boolean or || + this.raw = range; + this.set = range.split(/\s*\|\|\s*/).map(function(range) { + return this.parseRange(range.trim()); + }, this).filter(function(c) { + // throw out any that are not relevant for whatever reason + return c.length; + }); + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range); + } + + this.format(); +} + +Range.prototype.format = function() { + this.range = this.set.map(function(comps) { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; +}; + +Range.prototype.toString = function() { + return this.range; +}; + +Range.prototype.parseRange = function(range) { + var loose = this.loose; + range = range.trim(); + debug('range', range, loose); + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); + debug('comparator trim', range, re[COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var set = range.split(' ').map(function(comp) { + return parseComparator(comp, loose); + }).join(' ').split(/\s+/); + if (this.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function(comp) { + return !!comp.match(compRe); + }); + } + set = set.map(function(comp) { + return new Comparator(comp, loose); + }); + + return set; +}; + +Range.prototype.intersects = function(range, loose) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required'); + } + + return this.set.some(function(thisComparators) { + return thisComparators.every(function(thisComparator) { + return range.set.some(function(rangeComparators) { + return rangeComparators.every(function(rangeComparator) { + return thisComparator.intersects(rangeComparator, loose); + }); + }); + }); + }); +}; + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators; +function toComparators(range, loose) { + return new Range(range, loose).set.map(function(comp) { + return comp.map(function(c) { + return c.value; + }).join(' ').trim().split(' '); + }); +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator(comp, loose) { + debug('comp', comp); + comp = replaceCarets(comp, loose); + debug('caret', comp); + comp = replaceTildes(comp, loose); + debug('tildes', comp); + comp = replaceXRanges(comp, loose); + debug('xrange', comp); + comp = replaceStars(comp, loose); + debug('stars', comp); + return comp; +} + +function isX(id) { + return !id || id.toLowerCase() === 'x' || id === '*'; +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceTilde(comp, loose); + }).join(' '); +} + +function replaceTilde(comp, loose) { + var r = loose ? re[TILDELOOSE] : re[TILDE]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else if (pr) { + debug('replaceTilde pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + + debug('tilde return', ret); + return ret; + }); +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceCaret(comp, loose); + }).join(' '); +} + +function replaceCaret(comp, loose) { + debug('caret', comp, loose); + var r = loose ? re[CARETLOOSE] : re[CARET]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) { + if (M === '0') + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; + } else if (pr) { + debug('replaceCaret pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + (+M + 1) + '.0.0'; + } else { + debug('no pr'); + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0'; + } + + debug('caret return', ret); + return ret; + }); +} + +function replaceXRanges(comp, loose) { + debug('replaceXRanges', comp, loose); + return comp.split(/\s+/).map(function(comp) { + return replaceXRange(comp, loose); + }).join(' '); +} + +function replaceXRange(comp, loose) { + comp = comp.trim(); + var r = loose ? re[XRANGELOOSE] : re[XRANGE]; + return comp.replace(r, function(ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + + if (gtlt === '=' && anyX) + gtlt = ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // replace X with 0 + if (xm) + m = 0; + if (xp) + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else if (xp) { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) + M = +M + 1; + else + m = +m + 1; + } + + ret = gtlt + M + '.' + m + '.' + p; + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } + + debug('xRange return', ret); + + return ret; + }); +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars(comp, loose) { + debug('replaceStars', comp, loose); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], ''); +} + +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + + if (isX(fM)) + from = ''; + else if (isX(fm)) + from = '>=' + fM + '.0.0'; + else if (isX(fp)) + from = '>=' + fM + '.' + fm + '.0'; + else + from = '>=' + from; + + if (isX(tM)) + to = ''; + else if (isX(tm)) + to = '<' + (+tM + 1) + '.0.0'; + else if (isX(tp)) + to = '<' + tM + '.' + (+tm + 1) + '.0'; + else if (tpr) + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; + else + to = '<=' + to; + + return (from + ' ' + to).trim(); +} + + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function(version) { + if (!version) + return false; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version)) + return true; + } + return false; +}; + +function testSet(set, version) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) + return false; + } + + if (version.prerelease.length) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (var i = 0; i < set.length; i++) { + debug(set[i].semver); + if (set[i].semver === ANY) + continue; + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) + return true; + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false; + } + + return true; +} + +exports.satisfies = satisfies; +function satisfies(version, range, loose) { + try { + range = new Range(range, loose); + } catch (er) { + return false; + } + return range.test(version); +} + +exports.maxSatisfying = maxSatisfying; +function maxSatisfying(versions, range, loose) { + var max = null; + var maxSV = null; + try { + var rangeObj = new Range(range, loose); + } catch (er) { + return null; + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { // satisfies(v, range, loose) + if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) + max = v; + maxSV = new SemVer(max, loose); + } + } + }) + return max; +} + +exports.minSatisfying = minSatisfying; +function minSatisfying(versions, range, loose) { + var min = null; + var minSV = null; + try { + var rangeObj = new Range(range, loose); + } catch (er) { + return null; + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { // satisfies(v, range, loose) + if (!min || minSV.compare(v) === 1) { // compare(min, v, true) + min = v; + minSV = new SemVer(min, loose); + } + } + }) + return min; +} + +exports.validRange = validRange; +function validRange(range, loose) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, loose).range || '*'; + } catch (er) { + return null; + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr; +function ltr(version, range, loose) { + return outside(version, range, '<', loose); +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr; +function gtr(version, range, loose) { + return outside(version, range, '>', loose); +} + +exports.outside = outside; +function outside(version, range, hilo, loose) { + version = new SemVer(version, loose); + range = new Range(range, loose); + + var gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, loose)) { + return false; + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + + var high = null; + var low = null; + + comparators.forEach(function(comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, loose)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, loose)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false; + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + return true; +} + +exports.prerelease = prerelease; +function prerelease(version, loose) { + var parsed = parse(version, loose); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null; +} + +exports.intersects = intersects; +function intersects(r1, r2, loose) { + r1 = new Range(r1, loose) + r2 = new Range(r2, loose) + return r1.intersects(r2) +} + +exports.coerce = coerce; +function coerce(version) { + if (version instanceof SemVer) + return version; + + if (typeof version !== 'string') + return null; + + var match = version.match(re[COERCE]); + + if (match == null) + return null; + + return parse((match[1] || '0') + '.' + (match[2] || '0') + '.' + (match[3] || '0')); +} + + +/***/ }), +/* 23 */ +/***/ (function(module, exports) { + +module.exports = require("stream"); + +/***/ }), +/* 24 */ +/***/ (function(module, exports) { + +module.exports = require("url"); + +/***/ }), +/* 25 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Subscription; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__util_isArray__ = __webpack_require__(41); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util_isObject__ = __webpack_require__(444); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__util_isFunction__ = __webpack_require__(154); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util_tryCatch__ = __webpack_require__(57); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__util_errorObject__ = __webpack_require__(48); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__util_UnsubscriptionError__ = __webpack_require__(441); +/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_tryCatch,_util_errorObject,_util_UnsubscriptionError PURE_IMPORTS_END */ + + + + + + +var Subscription = /*@__PURE__*/ (function () { + function Subscription(unsubscribe) { + this.closed = false; + this._parent = null; + this._parents = null; + this._subscriptions = null; + if (unsubscribe) { + this._unsubscribe = unsubscribe; + } + } + Subscription.prototype.unsubscribe = function () { + var hasErrors = false; + var errors; + if (this.closed) { + return; + } + var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; + this.closed = true; + this._parent = null; + this._parents = null; + this._subscriptions = null; + var index = -1; + var len = _parents ? _parents.length : 0; + while (_parent) { + _parent.remove(this); + _parent = ++index < len && _parents[index] || null; + } + if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util_isFunction__["a" /* isFunction */])(_unsubscribe)) { + var trial = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__util_tryCatch__["a" /* tryCatch */])(_unsubscribe).call(this); + if (trial === __WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */]) { + hasErrors = true; + errors = errors || (__WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */].e instanceof __WEBPACK_IMPORTED_MODULE_5__util_UnsubscriptionError__["a" /* UnsubscriptionError */] ? + flattenUnsubscriptionErrors(__WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */].e.errors) : [__WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */].e]); + } + } + if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__util_isArray__["a" /* isArray */])(_subscriptions)) { + index = -1; + len = _subscriptions.length; + while (++index < len) { + var sub = _subscriptions[index]; + if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util_isObject__["a" /* isObject */])(sub)) { + var trial = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__util_tryCatch__["a" /* tryCatch */])(sub.unsubscribe).call(sub); + if (trial === __WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */]) { + hasErrors = true; + errors = errors || []; + var err = __WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */].e; + if (err instanceof __WEBPACK_IMPORTED_MODULE_5__util_UnsubscriptionError__["a" /* UnsubscriptionError */]) { + errors = errors.concat(flattenUnsubscriptionErrors(err.errors)); + } + else { + errors.push(err); + } + } + } + } + } + if (hasErrors) { + throw new __WEBPACK_IMPORTED_MODULE_5__util_UnsubscriptionError__["a" /* UnsubscriptionError */](errors); + } + }; + Subscription.prototype.add = function (teardown) { + if (!teardown || (teardown === Subscription.EMPTY)) { + return Subscription.EMPTY; + } + if (teardown === this) { + return this; + } + var subscription = teardown; + switch (typeof teardown) { + case 'function': + subscription = new Subscription(teardown); + case 'object': + if (subscription.closed || typeof subscription.unsubscribe !== 'function') { + return subscription; + } + else if (this.closed) { + subscription.unsubscribe(); + return subscription; + } + else if (typeof subscription._addParent !== 'function') { + var tmp = subscription; + subscription = new Subscription(); + subscription._subscriptions = [tmp]; + } + break; + default: + throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); + } + var subscriptions = this._subscriptions || (this._subscriptions = []); + subscriptions.push(subscription); + subscription._addParent(this); + return subscription; + }; + Subscription.prototype.remove = function (subscription) { + var subscriptions = this._subscriptions; + if (subscriptions) { + var subscriptionIndex = subscriptions.indexOf(subscription); + if (subscriptionIndex !== -1) { + subscriptions.splice(subscriptionIndex, 1); + } + } + }; + Subscription.prototype._addParent = function (parent) { + var _a = this, _parent = _a._parent, _parents = _a._parents; + if (!_parent || _parent === parent) { + this._parent = parent; + } + else if (!_parents) { + this._parents = [parent]; + } + else if (_parents.indexOf(parent) === -1) { + _parents.push(parent); + } + }; + Subscription.EMPTY = (function (empty) { + empty.closed = true; + return empty; + }(new Subscription())); + return Subscription; +}()); + +function flattenUnsubscriptionErrors(errors) { + return errors.reduce(function (errs, err) { return errs.concat((err instanceof __WEBPACK_IMPORTED_MODULE_5__util_UnsubscriptionError__["a" /* UnsubscriptionError */]) ? err.errors : err); }, []); +} +//# sourceMappingURL=Subscription.js.map + + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright 2015 Joyent, Inc. + +module.exports = { + bufferSplit: bufferSplit, + addRSAMissing: addRSAMissing, + calculateDSAPublic: calculateDSAPublic, + calculateED25519Public: calculateED25519Public, + calculateX25519Public: calculateX25519Public, + mpNormalize: mpNormalize, + mpDenormalize: mpDenormalize, + ecNormalize: ecNormalize, + countZeros: countZeros, + assertCompatible: assertCompatible, + isCompatible: isCompatible, + opensslKeyDeriv: opensslKeyDeriv, + opensshCipherInfo: opensshCipherInfo, + publicFromPrivateECDSA: publicFromPrivateECDSA, + zeroPadToLength: zeroPadToLength, + writeBitString: writeBitString, + readBitString: readBitString +}; + +var assert = __webpack_require__(16); +var Buffer = __webpack_require__(15).Buffer; +var PrivateKey = __webpack_require__(33); +var Key = __webpack_require__(27); +var crypto = __webpack_require__(11); +var algs = __webpack_require__(32); +var asn1 = __webpack_require__(66); + +var ec, jsbn; +var nacl; + +var MAX_CLASS_DEPTH = 3; + +function isCompatible(obj, klass, needVer) { + if (obj === null || typeof (obj) !== 'object') + return (false); + if (needVer === undefined) + needVer = klass.prototype._sshpkApiVersion; + if (obj instanceof klass && + klass.prototype._sshpkApiVersion[0] == needVer[0]) + return (true); + var proto = Object.getPrototypeOf(obj); + var depth = 0; + while (proto.constructor.name !== klass.name) { + proto = Object.getPrototypeOf(proto); + if (!proto || ++depth > MAX_CLASS_DEPTH) + return (false); + } + if (proto.constructor.name !== klass.name) + return (false); + var ver = proto._sshpkApiVersion; + if (ver === undefined) + ver = klass._oldVersionDetect(obj); + if (ver[0] != needVer[0] || ver[1] < needVer[1]) + return (false); + return (true); +} + +function assertCompatible(obj, klass, needVer, name) { + if (name === undefined) + name = 'object'; + assert.ok(obj, name + ' must not be null'); + assert.object(obj, name + ' must be an object'); + if (needVer === undefined) + needVer = klass.prototype._sshpkApiVersion; + if (obj instanceof klass && + klass.prototype._sshpkApiVersion[0] == needVer[0]) + return; + var proto = Object.getPrototypeOf(obj); + var depth = 0; + while (proto.constructor.name !== klass.name) { + proto = Object.getPrototypeOf(proto); + assert.ok(proto && ++depth <= MAX_CLASS_DEPTH, + name + ' must be a ' + klass.name + ' instance'); + } + assert.strictEqual(proto.constructor.name, klass.name, + name + ' must be a ' + klass.name + ' instance'); + var ver = proto._sshpkApiVersion; + if (ver === undefined) + ver = klass._oldVersionDetect(obj); + assert.ok(ver[0] == needVer[0] && ver[1] >= needVer[1], + name + ' must be compatible with ' + klass.name + ' klass ' + + 'version ' + needVer[0] + '.' + needVer[1]); +} + +var CIPHER_LEN = { + 'des-ede3-cbc': { key: 7, iv: 8 }, + 'aes-128-cbc': { key: 16, iv: 16 } +}; +var PKCS5_SALT_LEN = 8; + +function opensslKeyDeriv(cipher, salt, passphrase, count) { + assert.buffer(salt, 'salt'); + assert.buffer(passphrase, 'passphrase'); + assert.number(count, 'iteration count'); + + var clen = CIPHER_LEN[cipher]; + assert.object(clen, 'supported cipher'); + + salt = salt.slice(0, PKCS5_SALT_LEN); + + var D, D_prev, bufs; + var material = Buffer.alloc(0); + while (material.length < clen.key + clen.iv) { + bufs = []; + if (D_prev) + bufs.push(D_prev); + bufs.push(passphrase); + bufs.push(salt); + D = Buffer.concat(bufs); + for (var j = 0; j < count; ++j) + D = crypto.createHash('md5').update(D).digest(); + material = Buffer.concat([material, D]); + D_prev = D; + } + + return ({ + key: material.slice(0, clen.key), + iv: material.slice(clen.key, clen.key + clen.iv) + }); +} + +/* Count leading zero bits on a buffer */ +function countZeros(buf) { + var o = 0, obit = 8; + while (o < buf.length) { + var mask = (1 << obit); + if ((buf[o] & mask) === mask) + break; + obit--; + if (obit < 0) { + o++; + obit = 8; + } + } + return (o*8 + (8 - obit) - 1); +} + +function bufferSplit(buf, chr) { + assert.buffer(buf); + assert.string(chr); + + var parts = []; + var lastPart = 0; + var matches = 0; + for (var i = 0; i < buf.length; ++i) { + if (buf[i] === chr.charCodeAt(matches)) + ++matches; + else if (buf[i] === chr.charCodeAt(0)) + matches = 1; + else + matches = 0; + + if (matches >= chr.length) { + var newPart = i + 1; + parts.push(buf.slice(lastPart, newPart - matches)); + lastPart = newPart; + matches = 0; + } + } + if (lastPart <= buf.length) + parts.push(buf.slice(lastPart, buf.length)); + + return (parts); +} + +function ecNormalize(buf, addZero) { + assert.buffer(buf); + if (buf[0] === 0x00 && buf[1] === 0x04) { + if (addZero) + return (buf); + return (buf.slice(1)); + } else if (buf[0] === 0x04) { + if (!addZero) + return (buf); + } else { + while (buf[0] === 0x00) + buf = buf.slice(1); + if (buf[0] === 0x02 || buf[0] === 0x03) + throw (new Error('Compressed elliptic curve points ' + + 'are not supported')); + if (buf[0] !== 0x04) + throw (new Error('Not a valid elliptic curve point')); + if (!addZero) + return (buf); + } + var b = Buffer.alloc(buf.length + 1); + b[0] = 0x0; + buf.copy(b, 1); + return (b); +} + +function readBitString(der, tag) { + if (tag === undefined) + tag = asn1.Ber.BitString; + var buf = der.readString(tag, true); + assert.strictEqual(buf[0], 0x00, 'bit strings with unused bits are ' + + 'not supported (0x' + buf[0].toString(16) + ')'); + return (buf.slice(1)); +} + +function writeBitString(der, buf, tag) { + if (tag === undefined) + tag = asn1.Ber.BitString; + var b = Buffer.alloc(buf.length + 1); + b[0] = 0x00; + buf.copy(b, 1); + der.writeBuffer(b, tag); +} + +function mpNormalize(buf) { + assert.buffer(buf); + while (buf.length > 1 && buf[0] === 0x00 && (buf[1] & 0x80) === 0x00) + buf = buf.slice(1); + if ((buf[0] & 0x80) === 0x80) { + var b = Buffer.alloc(buf.length + 1); + b[0] = 0x00; + buf.copy(b, 1); + buf = b; + } + return (buf); +} + +function mpDenormalize(buf) { + assert.buffer(buf); + while (buf.length > 1 && buf[0] === 0x00) + buf = buf.slice(1); + return (buf); +} + +function zeroPadToLength(buf, len) { + assert.buffer(buf); + assert.number(len); + while (buf.length > len) { + assert.equal(buf[0], 0x00); + buf = buf.slice(1); + } + while (buf.length < len) { + var b = Buffer.alloc(buf.length + 1); + b[0] = 0x00; + buf.copy(b, 1); + buf = b; + } + return (buf); +} + +function bigintToMpBuf(bigint) { + var buf = Buffer.from(bigint.toByteArray()); + buf = mpNormalize(buf); + return (buf); +} + +function calculateDSAPublic(g, p, x) { + assert.buffer(g); + assert.buffer(p); + assert.buffer(x); + try { + var bigInt = __webpack_require__(81).BigInteger; + } catch (e) { + throw (new Error('To load a PKCS#8 format DSA private key, ' + + 'the node jsbn library is required.')); + } + g = new bigInt(g); + p = new bigInt(p); + x = new bigInt(x); + var y = g.modPow(x, p); + var ybuf = bigintToMpBuf(y); + return (ybuf); +} + +function calculateED25519Public(k) { + assert.buffer(k); + + if (nacl === undefined) + nacl = __webpack_require__(76); + + var kp = nacl.sign.keyPair.fromSeed(new Uint8Array(k)); + return (Buffer.from(kp.publicKey)); +} + +function calculateX25519Public(k) { + assert.buffer(k); + + if (nacl === undefined) + nacl = __webpack_require__(76); + + var kp = nacl.box.keyPair.fromSeed(new Uint8Array(k)); + return (Buffer.from(kp.publicKey)); +} + +function addRSAMissing(key) { + assert.object(key); + assertCompatible(key, PrivateKey, [1, 1]); + try { + var bigInt = __webpack_require__(81).BigInteger; + } catch (e) { + throw (new Error('To write a PEM private key from ' + + 'this source, the node jsbn lib is required.')); + } + + var d = new bigInt(key.part.d.data); + var buf; + + if (!key.part.dmodp) { + var p = new bigInt(key.part.p.data); + var dmodp = d.mod(p.subtract(1)); + + buf = bigintToMpBuf(dmodp); + key.part.dmodp = {name: 'dmodp', data: buf}; + key.parts.push(key.part.dmodp); + } + if (!key.part.dmodq) { + var q = new bigInt(key.part.q.data); + var dmodq = d.mod(q.subtract(1)); + + buf = bigintToMpBuf(dmodq); + key.part.dmodq = {name: 'dmodq', data: buf}; + key.parts.push(key.part.dmodq); + } +} + +function publicFromPrivateECDSA(curveName, priv) { + assert.string(curveName, 'curveName'); + assert.buffer(priv); + if (ec === undefined) + ec = __webpack_require__(139); + if (jsbn === undefined) + jsbn = __webpack_require__(81).BigInteger; + var params = algs.curves[curveName]; + var p = new jsbn(params.p); + var a = new jsbn(params.a); + var b = new jsbn(params.b); + var curve = new ec.ECCurveFp(p, a, b); + var G = curve.decodePointHex(params.G.toString('hex')); + + var d = new jsbn(mpNormalize(priv)); + var pub = G.multiply(d); + pub = Buffer.from(curve.encodePointHex(pub), 'hex'); + + var parts = []; + parts.push({name: 'curve', data: Buffer.from(curveName)}); + parts.push({name: 'Q', data: pub}); + + var key = new Key({type: 'ecdsa', curve: curve, parts: parts}); + return (key); +} + +function opensshCipherInfo(cipher) { + var inf = {}; + switch (cipher) { + case '3des-cbc': + inf.keySize = 24; + inf.blockSize = 8; + inf.opensslName = 'des-ede3-cbc'; + break; + case 'blowfish-cbc': + inf.keySize = 16; + inf.blockSize = 8; + inf.opensslName = 'bf-cbc'; + break; + case 'aes128-cbc': + case 'aes128-ctr': + case 'aes128-gcm@openssh.com': + inf.keySize = 16; + inf.blockSize = 16; + inf.opensslName = 'aes-128-' + cipher.slice(7, 10); + break; + case 'aes192-cbc': + case 'aes192-ctr': + case 'aes192-gcm@openssh.com': + inf.keySize = 24; + inf.blockSize = 16; + inf.opensslName = 'aes-192-' + cipher.slice(7, 10); + break; + case 'aes256-cbc': + case 'aes256-ctr': + case 'aes256-gcm@openssh.com': + inf.keySize = 32; + inf.blockSize = 16; + inf.opensslName = 'aes-256-' + cipher.slice(7, 10); + break; + default: + throw (new Error( + 'Unsupported openssl cipher "' + cipher + '"')); + } + return (inf); +} + + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright 2017 Joyent, Inc. + +module.exports = Key; + +var assert = __webpack_require__(16); +var algs = __webpack_require__(32); +var crypto = __webpack_require__(11); +var Fingerprint = __webpack_require__(156); +var Signature = __webpack_require__(75); +var DiffieHellman = __webpack_require__(325).DiffieHellman; +var errs = __webpack_require__(74); +var utils = __webpack_require__(26); +var PrivateKey = __webpack_require__(33); +var edCompat; + +try { + edCompat = __webpack_require__(454); +} catch (e) { + /* Just continue through, and bail out if we try to use it. */ +} + +var InvalidAlgorithmError = errs.InvalidAlgorithmError; +var KeyParseError = errs.KeyParseError; + +var formats = {}; +formats['auto'] = __webpack_require__(455); +formats['pem'] = __webpack_require__(86); +formats['pkcs1'] = __webpack_require__(327); +formats['pkcs8'] = __webpack_require__(157); +formats['rfc4253'] = __webpack_require__(103); +formats['ssh'] = __webpack_require__(456); +formats['ssh-private'] = __webpack_require__(193); +formats['openssh'] = formats['ssh-private']; +formats['dnssec'] = __webpack_require__(326); + +function Key(opts) { + assert.object(opts, 'options'); + assert.arrayOfObject(opts.parts, 'options.parts'); + assert.string(opts.type, 'options.type'); + assert.optionalString(opts.comment, 'options.comment'); + + var algInfo = algs.info[opts.type]; + if (typeof (algInfo) !== 'object') + throw (new InvalidAlgorithmError(opts.type)); + + var partLookup = {}; + for (var i = 0; i < opts.parts.length; ++i) { + var part = opts.parts[i]; + partLookup[part.name] = part; + } + + this.type = opts.type; + this.parts = opts.parts; + this.part = partLookup; + this.comment = undefined; + this.source = opts.source; + + /* for speeding up hashing/fingerprint operations */ + this._rfc4253Cache = opts._rfc4253Cache; + this._hashCache = {}; + + var sz; + this.curve = undefined; + if (this.type === 'ecdsa') { + var curve = this.part.curve.data.toString(); + this.curve = curve; + sz = algs.curves[curve].size; + } else if (this.type === 'ed25519' || this.type === 'curve25519') { + sz = 256; + this.curve = 'curve25519'; + } else { + var szPart = this.part[algInfo.sizePart]; + sz = szPart.data.length; + sz = sz * 8 - utils.countZeros(szPart.data); + } + this.size = sz; +} + +Key.formats = formats; + +Key.prototype.toBuffer = function (format, options) { + if (format === undefined) + format = 'ssh'; + assert.string(format, 'format'); + assert.object(formats[format], 'formats[format]'); + assert.optionalObject(options, 'options'); + + if (format === 'rfc4253') { + if (this._rfc4253Cache === undefined) + this._rfc4253Cache = formats['rfc4253'].write(this); + return (this._rfc4253Cache); + } + + return (formats[format].write(this, options)); +}; + +Key.prototype.toString = function (format, options) { + return (this.toBuffer(format, options).toString()); +}; + +Key.prototype.hash = function (algo) { + assert.string(algo, 'algorithm'); + algo = algo.toLowerCase(); + if (algs.hashAlgs[algo] === undefined) + throw (new InvalidAlgorithmError(algo)); + + if (this._hashCache[algo]) + return (this._hashCache[algo]); + var hash = crypto.createHash(algo). + update(this.toBuffer('rfc4253')).digest(); + this._hashCache[algo] = hash; + return (hash); +}; + +Key.prototype.fingerprint = function (algo) { + if (algo === undefined) + algo = 'sha256'; + assert.string(algo, 'algorithm'); + var opts = { + type: 'key', + hash: this.hash(algo), + algorithm: algo + }; + return (new Fingerprint(opts)); +}; + +Key.prototype.defaultHashAlgorithm = function () { + var hashAlgo = 'sha1'; + if (this.type === 'rsa') + hashAlgo = 'sha256'; + if (this.type === 'dsa' && this.size > 1024) + hashAlgo = 'sha256'; + if (this.type === 'ed25519') + hashAlgo = 'sha512'; + if (this.type === 'ecdsa') { + if (this.size <= 256) + hashAlgo = 'sha256'; + else if (this.size <= 384) + hashAlgo = 'sha384'; + else + hashAlgo = 'sha512'; + } + return (hashAlgo); +}; + +Key.prototype.createVerify = function (hashAlgo) { + if (hashAlgo === undefined) + hashAlgo = this.defaultHashAlgorithm(); + assert.string(hashAlgo, 'hash algorithm'); + + /* ED25519 is not supported by OpenSSL, use a javascript impl. */ + if (this.type === 'ed25519' && edCompat !== undefined) + return (new edCompat.Verifier(this, hashAlgo)); + if (this.type === 'curve25519') + throw (new Error('Curve25519 keys are not suitable for ' + + 'signing or verification')); + + var v, nm, err; + try { + nm = hashAlgo.toUpperCase(); + v = crypto.createVerify(nm); + } catch (e) { + err = e; + } + if (v === undefined || (err instanceof Error && + err.message.match(/Unknown message digest/))) { + nm = 'RSA-'; + nm += hashAlgo.toUpperCase(); + v = crypto.createVerify(nm); + } + assert.ok(v, 'failed to create verifier'); + var oldVerify = v.verify.bind(v); + var key = this.toBuffer('pkcs8'); + var curve = this.curve; + var self = this; + v.verify = function (signature, fmt) { + if (Signature.isSignature(signature, [2, 0])) { + if (signature.type !== self.type) + return (false); + if (signature.hashAlgorithm && + signature.hashAlgorithm !== hashAlgo) + return (false); + if (signature.curve && self.type === 'ecdsa' && + signature.curve !== curve) + return (false); + return (oldVerify(key, signature.toBuffer('asn1'))); + + } else if (typeof (signature) === 'string' || + Buffer.isBuffer(signature)) { + return (oldVerify(key, signature, fmt)); + + /* + * Avoid doing this on valid arguments, walking the prototype + * chain can be quite slow. + */ + } else if (Signature.isSignature(signature, [1, 0])) { + throw (new Error('signature was created by too old ' + + 'a version of sshpk and cannot be verified')); + + } else { + throw (new TypeError('signature must be a string, ' + + 'Buffer, or Signature object')); + } + }; + return (v); +}; + +Key.prototype.createDiffieHellman = function () { + if (this.type === 'rsa') + throw (new Error('RSA keys do not support Diffie-Hellman')); + + return (new DiffieHellman(this)); +}; +Key.prototype.createDH = Key.prototype.createDiffieHellman; + +Key.parse = function (data, format, options) { + if (typeof (data) !== 'string') + assert.buffer(data, 'data'); + if (format === undefined) + format = 'auto'; + assert.string(format, 'format'); + if (typeof (options) === 'string') + options = { filename: options }; + assert.optionalObject(options, 'options'); + if (options === undefined) + options = {}; + assert.optionalString(options.filename, 'options.filename'); + if (options.filename === undefined) + options.filename = '(unnamed)'; + + assert.object(formats[format], 'formats[format]'); + + try { + var k = formats[format].read(data, options); + if (k instanceof PrivateKey) + k = k.toPublic(); + if (!k.comment) + k.comment = options.filename; + return (k); + } catch (e) { + if (e.name === 'KeyEncryptedError') + throw (e); + throw (new KeyParseError(options.filename, format, e)); + } +}; + +Key.isKey = function (obj, ver) { + return (utils.isCompatible(obj, Key, ver)); +}; + +/* + * API versions for Key: + * [1,0] -- initial ver, may take Signature for createVerify or may not + * [1,1] -- added pkcs1, pkcs8 formats + * [1,2] -- added auto, ssh-private, openssh formats + * [1,3] -- added defaultHashAlgorithm + * [1,4] -- added ed support, createDH + * [1,5] -- first explicitly tagged version + * [1,6] -- changed ed25519 part names + */ +Key.prototype._sshpkApiVersion = [1, 6]; + +Key._oldVersionDetect = function (obj) { + assert.func(obj.toBuffer); + assert.func(obj.fingerprint); + if (obj.createDH) + return ([1, 4]); + if (obj.defaultHashAlgorithm) + return ([1, 3]); + if (obj.formats['auto']) + return ([1, 2]); + if (obj.formats['pkcs1']) + return ([1, 1]); + return ([1, 0]); +}; + + +/***/ }), +/* 28 */ +/***/ (function(module, exports) { + +module.exports = require("assert"); + +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = nullify; +function nullify(obj = {}) { + if (Array.isArray(obj)) { + for (var _iterator = obj, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + const item = _ref; + + nullify(item); + } + } else if (obj !== null && typeof obj === 'object' || typeof obj === 'function') { + Object.setPrototypeOf(obj, null); + + // for..in can only be applied to 'object', not 'function' + if (typeof obj === 'object') { + for (const key in obj) { + nullify(obj[key]); + } + } + } + + return obj; +} + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const escapeStringRegexp = __webpack_require__(388); +const ansiStyles = __webpack_require__(506); +const stdoutColor = __webpack_require__(598).stdout; + +const template = __webpack_require__(599); + +const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; + +// `color-convert` models to exclude from the Chalk API due to conflicts and such +const skipModels = new Set(['gray']); + +const styles = Object.create(null); + +function applyOptions(obj, options) { + options = options || {}; + + // Detect level if not set manually + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; +} + +function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = Chalk; + + return chalk.template; + } + + applyOptions(this, options); +} + +// Use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; +} + +for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; +} + +styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } +}; + +ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); +for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); +for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +const proto = Object.defineProperties(() => {}, styles); + +function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + + const self = this; + + Object.defineProperty(builder, 'level', { + enumerable: true, + get() { + return self.level; + }, + set(level) { + self.level = level; + } + }); + + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get() { + return self.enabled; + }, + set(enabled) { + self.enabled = enabled; + } + }); + + // See below for fix regarding invisible grey/dim combination on Windows + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + + // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; +} + +function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } + + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + const originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + + // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } + + // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + ansiStyles.dim.open = originalDim; + + return str; +} + +function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return template(chalk, parts.join('')); +} + +Object.defineProperties(Chalk.prototype, styles); + +module.exports = Chalk(); // eslint-disable-line new-cap +module.exports.supportsColor = stdoutColor; +module.exports.default = module.exports; // For TypeScript + + +/***/ }), +/* 31 */ +/***/ (function(module, exports) { + +var core = module.exports = { version: '2.5.7' }; +if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef + + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright 2015 Joyent, Inc. + +var Buffer = __webpack_require__(15).Buffer; + +var algInfo = { + 'dsa': { + parts: ['p', 'q', 'g', 'y'], + sizePart: 'p' + }, + 'rsa': { + parts: ['e', 'n'], + sizePart: 'n' + }, + 'ecdsa': { + parts: ['curve', 'Q'], + sizePart: 'Q' + }, + 'ed25519': { + parts: ['A'], + sizePart: 'A' + } +}; +algInfo['curve25519'] = algInfo['ed25519']; + +var algPrivInfo = { + 'dsa': { + parts: ['p', 'q', 'g', 'y', 'x'] + }, + 'rsa': { + parts: ['n', 'e', 'd', 'iqmp', 'p', 'q'] + }, + 'ecdsa': { + parts: ['curve', 'Q', 'd'] + }, + 'ed25519': { + parts: ['A', 'k'] + } +}; +algPrivInfo['curve25519'] = algPrivInfo['ed25519']; + +var hashAlgs = { + 'md5': true, + 'sha1': true, + 'sha256': true, + 'sha384': true, + 'sha512': true +}; + +/* + * Taken from + * http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf + */ +var curves = { + 'nistp256': { + size: 256, + pkcs8oid: '1.2.840.10045.3.1.7', + p: Buffer.from(('00' + + 'ffffffff 00000001 00000000 00000000' + + '00000000 ffffffff ffffffff ffffffff'). + replace(/ /g, ''), 'hex'), + a: Buffer.from(('00' + + 'FFFFFFFF 00000001 00000000 00000000' + + '00000000 FFFFFFFF FFFFFFFF FFFFFFFC'). + replace(/ /g, ''), 'hex'), + b: Buffer.from(( + '5ac635d8 aa3a93e7 b3ebbd55 769886bc' + + '651d06b0 cc53b0f6 3bce3c3e 27d2604b'). + replace(/ /g, ''), 'hex'), + s: Buffer.from(('00' + + 'c49d3608 86e70493 6a6678e1 139d26b7' + + '819f7e90'). + replace(/ /g, ''), 'hex'), + n: Buffer.from(('00' + + 'ffffffff 00000000 ffffffff ffffffff' + + 'bce6faad a7179e84 f3b9cac2 fc632551'). + replace(/ /g, ''), 'hex'), + G: Buffer.from(('04' + + '6b17d1f2 e12c4247 f8bce6e5 63a440f2' + + '77037d81 2deb33a0 f4a13945 d898c296' + + '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16' + + '2bce3357 6b315ece cbb64068 37bf51f5'). + replace(/ /g, ''), 'hex') + }, + 'nistp384': { + size: 384, + pkcs8oid: '1.3.132.0.34', + p: Buffer.from(('00' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff ffffffff fffffffe' + + 'ffffffff 00000000 00000000 ffffffff'). + replace(/ /g, ''), 'hex'), + a: Buffer.from(('00' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE' + + 'FFFFFFFF 00000000 00000000 FFFFFFFC'). + replace(/ /g, ''), 'hex'), + b: Buffer.from(( + 'b3312fa7 e23ee7e4 988e056b e3f82d19' + + '181d9c6e fe814112 0314088f 5013875a' + + 'c656398d 8a2ed19d 2a85c8ed d3ec2aef'). + replace(/ /g, ''), 'hex'), + s: Buffer.from(('00' + + 'a335926a a319a27a 1d00896a 6773a482' + + '7acdac73'). + replace(/ /g, ''), 'hex'), + n: Buffer.from(('00' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff c7634d81 f4372ddf' + + '581a0db2 48b0a77a ecec196a ccc52973'). + replace(/ /g, ''), 'hex'), + G: Buffer.from(('04' + + 'aa87ca22 be8b0537 8eb1c71e f320ad74' + + '6e1d3b62 8ba79b98 59f741e0 82542a38' + + '5502f25d bf55296c 3a545e38 72760ab7' + + '3617de4a 96262c6f 5d9e98bf 9292dc29' + + 'f8f41dbd 289a147c e9da3113 b5f0b8c0' + + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'). + replace(/ /g, ''), 'hex') + }, + 'nistp521': { + size: 521, + pkcs8oid: '1.3.132.0.35', + p: Buffer.from(( + '01ffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffff').replace(/ /g, ''), 'hex'), + a: Buffer.from(('01FF' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFC'). + replace(/ /g, ''), 'hex'), + b: Buffer.from(('51' + + '953eb961 8e1c9a1f 929a21a0 b68540ee' + + 'a2da725b 99b315f3 b8b48991 8ef109e1' + + '56193951 ec7e937b 1652c0bd 3bb1bf07' + + '3573df88 3d2c34f1 ef451fd4 6b503f00'). + replace(/ /g, ''), 'hex'), + s: Buffer.from(('00' + + 'd09e8800 291cb853 96cc6717 393284aa' + + 'a0da64ba').replace(/ /g, ''), 'hex'), + n: Buffer.from(('01ff' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff ffffffff fffffffa' + + '51868783 bf2f966b 7fcc0148 f709a5d0' + + '3bb5c9b8 899c47ae bb6fb71e 91386409'). + replace(/ /g, ''), 'hex'), + G: Buffer.from(('04' + + '00c6 858e06b7 0404e9cd 9e3ecb66 2395b442' + + '9c648139 053fb521 f828af60 6b4d3dba' + + 'a14b5e77 efe75928 fe1dc127 a2ffa8de' + + '3348b3c1 856a429b f97e7e31 c2e5bd66' + + '0118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9' + + '98f54449 579b4468 17afbd17 273e662c' + + '97ee7299 5ef42640 c550b901 3fad0761' + + '353c7086 a272c240 88be9476 9fd16650'). + replace(/ /g, ''), 'hex') + } +}; + +module.exports = { + info: algInfo, + privInfo: algPrivInfo, + hashAlgs: hashAlgs, + curves: curves +}; + + +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright 2017 Joyent, Inc. + +module.exports = PrivateKey; + +var assert = __webpack_require__(16); +var Buffer = __webpack_require__(15).Buffer; +var algs = __webpack_require__(32); +var crypto = __webpack_require__(11); +var Fingerprint = __webpack_require__(156); +var Signature = __webpack_require__(75); +var errs = __webpack_require__(74); +var util = __webpack_require__(3); +var utils = __webpack_require__(26); +var dhe = __webpack_require__(325); +var generateECDSA = dhe.generateECDSA; +var generateED25519 = dhe.generateED25519; +var edCompat; +var nacl; + +try { + edCompat = __webpack_require__(454); +} catch (e) { + /* Just continue through, and bail out if we try to use it. */ +} + +var Key = __webpack_require__(27); + +var InvalidAlgorithmError = errs.InvalidAlgorithmError; +var KeyParseError = errs.KeyParseError; +var KeyEncryptedError = errs.KeyEncryptedError; + +var formats = {}; +formats['auto'] = __webpack_require__(455); +formats['pem'] = __webpack_require__(86); +formats['pkcs1'] = __webpack_require__(327); +formats['pkcs8'] = __webpack_require__(157); +formats['rfc4253'] = __webpack_require__(103); +formats['ssh-private'] = __webpack_require__(193); +formats['openssh'] = formats['ssh-private']; +formats['ssh'] = formats['ssh-private']; +formats['dnssec'] = __webpack_require__(326); + +function PrivateKey(opts) { + assert.object(opts, 'options'); + Key.call(this, opts); + + this._pubCache = undefined; +} +util.inherits(PrivateKey, Key); + +PrivateKey.formats = formats; + +PrivateKey.prototype.toBuffer = function (format, options) { + if (format === undefined) + format = 'pkcs1'; + assert.string(format, 'format'); + assert.object(formats[format], 'formats[format]'); + assert.optionalObject(options, 'options'); + + return (formats[format].write(this, options)); +}; + +PrivateKey.prototype.hash = function (algo) { + return (this.toPublic().hash(algo)); +}; + +PrivateKey.prototype.toPublic = function () { + if (this._pubCache) + return (this._pubCache); + + var algInfo = algs.info[this.type]; + var pubParts = []; + for (var i = 0; i < algInfo.parts.length; ++i) { + var p = algInfo.parts[i]; + pubParts.push(this.part[p]); + } + + this._pubCache = new Key({ + type: this.type, + source: this, + parts: pubParts + }); + if (this.comment) + this._pubCache.comment = this.comment; + return (this._pubCache); +}; + +PrivateKey.prototype.derive = function (newType) { + assert.string(newType, 'type'); + var priv, pub, pair; + + if (this.type === 'ed25519' && newType === 'curve25519') { + if (nacl === undefined) + nacl = __webpack_require__(76); + + priv = this.part.k.data; + if (priv[0] === 0x00) + priv = priv.slice(1); + + pair = nacl.box.keyPair.fromSecretKey(new Uint8Array(priv)); + pub = Buffer.from(pair.publicKey); + + return (new PrivateKey({ + type: 'curve25519', + parts: [ + { name: 'A', data: utils.mpNormalize(pub) }, + { name: 'k', data: utils.mpNormalize(priv) } + ] + })); + } else if (this.type === 'curve25519' && newType === 'ed25519') { + if (nacl === undefined) + nacl = __webpack_require__(76); + + priv = this.part.k.data; + if (priv[0] === 0x00) + priv = priv.slice(1); + + pair = nacl.sign.keyPair.fromSeed(new Uint8Array(priv)); + pub = Buffer.from(pair.publicKey); + + return (new PrivateKey({ + type: 'ed25519', + parts: [ + { name: 'A', data: utils.mpNormalize(pub) }, + { name: 'k', data: utils.mpNormalize(priv) } + ] + })); + } + throw (new Error('Key derivation not supported from ' + this.type + + ' to ' + newType)); +}; + +PrivateKey.prototype.createVerify = function (hashAlgo) { + return (this.toPublic().createVerify(hashAlgo)); +}; + +PrivateKey.prototype.createSign = function (hashAlgo) { + if (hashAlgo === undefined) + hashAlgo = this.defaultHashAlgorithm(); + assert.string(hashAlgo, 'hash algorithm'); + + /* ED25519 is not supported by OpenSSL, use a javascript impl. */ + if (this.type === 'ed25519' && edCompat !== undefined) + return (new edCompat.Signer(this, hashAlgo)); + if (this.type === 'curve25519') + throw (new Error('Curve25519 keys are not suitable for ' + + 'signing or verification')); + + var v, nm, err; + try { + nm = hashAlgo.toUpperCase(); + v = crypto.createSign(nm); + } catch (e) { + err = e; + } + if (v === undefined || (err instanceof Error && + err.message.match(/Unknown message digest/))) { + nm = 'RSA-'; + nm += hashAlgo.toUpperCase(); + v = crypto.createSign(nm); + } + assert.ok(v, 'failed to create verifier'); + var oldSign = v.sign.bind(v); + var key = this.toBuffer('pkcs1'); + var type = this.type; + var curve = this.curve; + v.sign = function () { + var sig = oldSign(key); + if (typeof (sig) === 'string') + sig = Buffer.from(sig, 'binary'); + sig = Signature.parse(sig, type, 'asn1'); + sig.hashAlgorithm = hashAlgo; + sig.curve = curve; + return (sig); + }; + return (v); +}; + +PrivateKey.parse = function (data, format, options) { + if (typeof (data) !== 'string') + assert.buffer(data, 'data'); + if (format === undefined) + format = 'auto'; + assert.string(format, 'format'); + if (typeof (options) === 'string') + options = { filename: options }; + assert.optionalObject(options, 'options'); + if (options === undefined) + options = {}; + assert.optionalString(options.filename, 'options.filename'); + if (options.filename === undefined) + options.filename = '(unnamed)'; + + assert.object(formats[format], 'formats[format]'); + + try { + var k = formats[format].read(data, options); + assert.ok(k instanceof PrivateKey, 'key is not a private key'); + if (!k.comment) + k.comment = options.filename; + return (k); + } catch (e) { + if (e.name === 'KeyEncryptedError') + throw (e); + throw (new KeyParseError(options.filename, format, e)); + } +}; + +PrivateKey.isPrivateKey = function (obj, ver) { + return (utils.isCompatible(obj, PrivateKey, ver)); +}; + +PrivateKey.generate = function (type, options) { + if (options === undefined) + options = {}; + assert.object(options, 'options'); + + switch (type) { + case 'ecdsa': + if (options.curve === undefined) + options.curve = 'nistp256'; + assert.string(options.curve, 'options.curve'); + return (generateECDSA(options.curve)); + case 'ed25519': + return (generateED25519()); + default: + throw (new Error('Key generation not supported with key ' + + 'type "' + type + '"')); + } +}; + +/* + * API versions for PrivateKey: + * [1,0] -- initial ver + * [1,1] -- added auto, pkcs[18], openssh/ssh-private formats + * [1,2] -- added defaultHashAlgorithm + * [1,3] -- added derive, ed, createDH + * [1,4] -- first tagged version + * [1,5] -- changed ed25519 part names and format + */ +PrivateKey.prototype._sshpkApiVersion = [1, 5]; + +PrivateKey._oldVersionDetect = function (obj) { + assert.func(obj.toPublic); + assert.func(obj.createSign); + if (obj.derive) + return ([1, 3]); + if (obj.defaultHashAlgorithm) + return ([1, 2]); + if (obj.formats['auto']) + return ([1, 1]); + return ([1, 0]); +}; + + +/***/ }), +/* 34 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.wrapLifecycle = exports.run = exports.install = exports.Install = undefined; + +var _extends2; + +function _load_extends() { + return _extends2 = _interopRequireDefault(__webpack_require__(20)); +} + +var _asyncToGenerator2; + +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(2)); +} + +let install = exports.install = (() => { + var _ref29 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, lockfile) { + yield wrapLifecycle(config, flags, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const install = new Install(flags, config, reporter, lockfile); + yield install.init(); + })); + }); + + return function install(_x7, _x8, _x9, _x10) { + return _ref29.apply(this, arguments); + }; +})(); + +let run = exports.run = (() => { + var _ref31 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + let lockfile; + let error = 'installCommandRenamed'; + if (flags.lockfile === false) { + lockfile = new (_lockfile || _load_lockfile()).default(); + } else { + lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.lockfileFolder, reporter); + } + + if (args.length) { + const exampleArgs = args.slice(); + + if (flags.saveDev) { + exampleArgs.push('--dev'); + } + if (flags.savePeer) { + exampleArgs.push('--peer'); + } + if (flags.saveOptional) { + exampleArgs.push('--optional'); + } + if (flags.saveExact) { + exampleArgs.push('--exact'); + } + if (flags.saveTilde) { + exampleArgs.push('--tilde'); + } + let command = 'add'; + if (flags.global) { + error = 'globalFlagRemoved'; + command = 'global add'; + } + throw new (_errors || _load_errors()).MessageError(reporter.lang(error, `yarn ${command} ${exampleArgs.join(' ')}`)); + } + + yield install(config, reporter, flags, lockfile); + }); + + return function run(_x11, _x12, _x13, _x14) { + return _ref31.apply(this, arguments); + }; +})(); + +let wrapLifecycle = exports.wrapLifecycle = (() => { + var _ref32 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, flags, factory) { + yield config.executeLifecycleScript('preinstall'); + + yield factory(); + + // npm behaviour, seems kinda funky but yay compatibility + yield config.executeLifecycleScript('install'); + yield config.executeLifecycleScript('postinstall'); + + if (!config.production) { + if (!config.disablePrepublish) { + yield config.executeLifecycleScript('prepublish'); + } + yield config.executeLifecycleScript('prepare'); + } + }); + + return function wrapLifecycle(_x15, _x16, _x17) { + return _ref32.apply(this, arguments); + }; +})(); + +exports.hasWrapper = hasWrapper; +exports.setFlags = setFlags; + +var _objectPath; + +function _load_objectPath() { + return _objectPath = _interopRequireDefault(__webpack_require__(304)); +} + +var _hooks; + +function _load_hooks() { + return _hooks = __webpack_require__(374); +} + +var _index; + +function _load_index() { + return _index = _interopRequireDefault(__webpack_require__(221)); +} + +var _errors; + +function _load_errors() { + return _errors = __webpack_require__(6); +} + +var _integrityChecker; + +function _load_integrityChecker() { + return _integrityChecker = _interopRequireDefault(__webpack_require__(209)); +} + +var _lockfile; + +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(19)); +} + +var _lockfile2; + +function _load_lockfile2() { + return _lockfile2 = __webpack_require__(19); +} + +var _packageFetcher; + +function _load_packageFetcher() { + return _packageFetcher = _interopRequireWildcard(__webpack_require__(211)); +} + +var _packageInstallScripts; + +function _load_packageInstallScripts() { + return _packageInstallScripts = _interopRequireDefault(__webpack_require__(557)); +} + +var _packageCompatibility; + +function _load_packageCompatibility() { + return _packageCompatibility = _interopRequireWildcard(__webpack_require__(210)); +} + +var _packageResolver; + +function _load_packageResolver() { + return _packageResolver = _interopRequireDefault(__webpack_require__(366)); +} + +var _packageLinker; + +function _load_packageLinker() { + return _packageLinker = _interopRequireDefault(__webpack_require__(212)); +} + +var _index2; + +function _load_index2() { + return _index2 = __webpack_require__(58); +} + +var _index3; + +function _load_index3() { + return _index3 = __webpack_require__(78); +} + +var _autoclean; + +function _load_autoclean() { + return _autoclean = __webpack_require__(354); +} + +var _constants; + +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(8)); +} + +var _normalizePattern; + +function _load_normalizePattern() { + return _normalizePattern = __webpack_require__(37); +} + +var _fs; + +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(5)); +} + +var _map; + +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(29)); +} + +var _yarnVersion; + +function _load_yarnVersion() { + return _yarnVersion = __webpack_require__(105); +} + +var _generatePnpMap; + +function _load_generatePnpMap() { + return _generatePnpMap = __webpack_require__(579); +} + +var _workspaceLayout; + +function _load_workspaceLayout() { + return _workspaceLayout = _interopRequireDefault(__webpack_require__(90)); +} + +var _resolutionMap; + +function _load_resolutionMap() { + return _resolutionMap = _interopRequireDefault(__webpack_require__(215)); +} + +var _guessName; + +function _load_guessName() { + return _guessName = _interopRequireDefault(__webpack_require__(169)); +} + +var _audit; + +function _load_audit() { + return _audit = _interopRequireDefault(__webpack_require__(353)); +} + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const deepEqual = __webpack_require__(631); + +const emoji = __webpack_require__(302); +const invariant = __webpack_require__(9); +const path = __webpack_require__(0); +const semver = __webpack_require__(22); +const uuid = __webpack_require__(120); +const ssri = __webpack_require__(65); + +const ONE_DAY = 1000 * 60 * 60 * 24; + +/** + * Try and detect the installation method for Yarn and provide a command to update it with. + */ + +function getUpdateCommand(installationMethod) { + if (installationMethod === 'tar') { + return `curl --compressed -o- -L ${(_constants || _load_constants()).YARN_INSTALLER_SH} | bash`; + } + + if (installationMethod === 'homebrew') { + return 'brew upgrade yarn'; + } + + if (installationMethod === 'deb') { + return 'sudo apt-get update && sudo apt-get install yarn'; + } + + if (installationMethod === 'rpm') { + return 'sudo yum install yarn'; + } + + if (installationMethod === 'npm') { + return 'npm install --global yarn'; + } + + if (installationMethod === 'chocolatey') { + return 'choco upgrade yarn'; + } + + if (installationMethod === 'apk') { + return 'apk update && apk add -u yarn'; + } + + if (installationMethod === 'portage') { + return 'sudo emerge --sync && sudo emerge -au sys-apps/yarn'; + } + + return null; +} + +function getUpdateInstaller(installationMethod) { + // Windows + if (installationMethod === 'msi') { + return (_constants || _load_constants()).YARN_INSTALLER_MSI; + } + + return null; +} + +function normalizeFlags(config, rawFlags) { + const flags = { + // install + har: !!rawFlags.har, + ignorePlatform: !!rawFlags.ignorePlatform, + ignoreEngines: !!rawFlags.ignoreEngines, + ignoreScripts: !!rawFlags.ignoreScripts, + ignoreOptional: !!rawFlags.ignoreOptional, + force: !!rawFlags.force, + flat: !!rawFlags.flat, + lockfile: rawFlags.lockfile !== false, + pureLockfile: !!rawFlags.pureLockfile, + updateChecksums: !!rawFlags.updateChecksums, + skipIntegrityCheck: !!rawFlags.skipIntegrityCheck, + frozenLockfile: !!rawFlags.frozenLockfile, + linkDuplicates: !!rawFlags.linkDuplicates, + checkFiles: !!rawFlags.checkFiles, + audit: !!rawFlags.audit, + + // add + peer: !!rawFlags.peer, + dev: !!rawFlags.dev, + optional: !!rawFlags.optional, + exact: !!rawFlags.exact, + tilde: !!rawFlags.tilde, + ignoreWorkspaceRootCheck: !!rawFlags.ignoreWorkspaceRootCheck, + + // outdated, update-interactive + includeWorkspaceDeps: !!rawFlags.includeWorkspaceDeps, + + // add, remove, update + workspaceRootIsCwd: rawFlags.workspaceRootIsCwd !== false + }; + + if (config.getOption('ignore-scripts')) { + flags.ignoreScripts = true; + } + + if (config.getOption('ignore-platform')) { + flags.ignorePlatform = true; + } + + if (config.getOption('ignore-engines')) { + flags.ignoreEngines = true; + } + + if (config.getOption('ignore-optional')) { + flags.ignoreOptional = true; + } + + if (config.getOption('force')) { + flags.force = true; + } + + return flags; +} + +class Install { + constructor(flags, config, reporter, lockfile) { + this.rootManifestRegistries = []; + this.rootPatternsToOrigin = (0, (_map || _load_map()).default)(); + this.lockfile = lockfile; + this.reporter = reporter; + this.config = config; + this.flags = normalizeFlags(config, flags); + this.resolutions = (0, (_map || _load_map()).default)(); // Legacy resolutions field used for flat install mode + this.resolutionMap = new (_resolutionMap || _load_resolutionMap()).default(config); // Selective resolutions for nested dependencies + this.resolver = new (_packageResolver || _load_packageResolver()).default(config, lockfile, this.resolutionMap); + this.integrityChecker = new (_integrityChecker || _load_integrityChecker()).default(config); + this.linker = new (_packageLinker || _load_packageLinker()).default(config, this.resolver); + this.scripts = new (_packageInstallScripts || _load_packageInstallScripts()).default(config, this.resolver, this.flags.force); + } + + /** + * Create a list of dependency requests from the current directories manifests. + */ + + fetchRequestFromCwd(excludePatterns = [], ignoreUnusedPatterns = false) { + var _this = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const patterns = []; + const deps = []; + let resolutionDeps = []; + const manifest = {}; + + const ignorePatterns = []; + const usedPatterns = []; + let workspaceLayout; + + // some commands should always run in the context of the entire workspace + const cwd = _this.flags.includeWorkspaceDeps || _this.flags.workspaceRootIsCwd ? _this.config.lockfileFolder : _this.config.cwd; + + // non-workspaces are always root, otherwise check for workspace root + const cwdIsRoot = !_this.config.workspaceRootFolder || _this.config.lockfileFolder === cwd; + + // exclude package names that are in install args + const excludeNames = []; + for (var _iterator = excludePatterns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + const pattern = _ref; + + if ((0, (_index3 || _load_index3()).getExoticResolver)(pattern)) { + excludeNames.push((0, (_guessName || _load_guessName()).default)(pattern)); + } else { + // extract the name + const parts = (0, (_normalizePattern || _load_normalizePattern()).normalizePattern)(pattern); + excludeNames.push(parts.name); + } + } + + const stripExcluded = function stripExcluded(manifest) { + for (var _iterator2 = excludeNames, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + const exclude = _ref2; + + if (manifest.dependencies && manifest.dependencies[exclude]) { + delete manifest.dependencies[exclude]; + } + if (manifest.devDependencies && manifest.devDependencies[exclude]) { + delete manifest.devDependencies[exclude]; + } + if (manifest.optionalDependencies && manifest.optionalDependencies[exclude]) { + delete manifest.optionalDependencies[exclude]; + } + } + }; + + for (var _iterator3 = Object.keys((_index2 || _load_index2()).registries), _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + const registry = _ref3; + + const filename = (_index2 || _load_index2()).registries[registry].filename; + + const loc = path.join(cwd, filename); + if (!(yield (_fs || _load_fs()).exists(loc))) { + continue; + } + + _this.rootManifestRegistries.push(registry); + + const projectManifestJson = yield _this.config.readJson(loc); + yield (0, (_index || _load_index()).default)(projectManifestJson, cwd, _this.config, cwdIsRoot); + + Object.assign(_this.resolutions, projectManifestJson.resolutions); + Object.assign(manifest, projectManifestJson); + + _this.resolutionMap.init(_this.resolutions); + for (var _iterator4 = Object.keys(_this.resolutionMap.resolutionsByPackage), _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) { + var _ref4; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref4 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref4 = _i4.value; + } + + const packageName = _ref4; + + const optional = (_objectPath || _load_objectPath()).default.has(manifest.optionalDependencies, packageName) && _this.flags.ignoreOptional; + for (var _iterator8 = _this.resolutionMap.resolutionsByPackage[packageName], _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : _iterator8[Symbol.iterator]();;) { + var _ref9; + + if (_isArray8) { + if (_i8 >= _iterator8.length) break; + _ref9 = _iterator8[_i8++]; + } else { + _i8 = _iterator8.next(); + if (_i8.done) break; + _ref9 = _i8.value; + } + + const _ref8 = _ref9; + const pattern = _ref8.pattern; + + resolutionDeps = [...resolutionDeps, { registry, pattern, optional, hint: 'resolution' }]; + } + } + + const pushDeps = function pushDeps(depType, manifest, { hint, optional }, isUsed) { + if (ignoreUnusedPatterns && !isUsed) { + return; + } + // We only take unused dependencies into consideration to get deterministic hoisting. + // Since flat mode doesn't care about hoisting and everything is top level and specified then we can safely + // leave these out. + if (_this.flags.flat && !isUsed) { + return; + } + const depMap = manifest[depType]; + for (const name in depMap) { + if (excludeNames.indexOf(name) >= 0) { + continue; + } + + let pattern = name; + if (!_this.lockfile.getLocked(pattern)) { + // when we use --save we save the dependency to the lockfile with just the name rather than the + // version combo + pattern += '@' + depMap[name]; + } + + // normalization made sure packages are mentioned only once + if (isUsed) { + usedPatterns.push(pattern); + } else { + ignorePatterns.push(pattern); + } + + _this.rootPatternsToOrigin[pattern] = depType; + patterns.push(pattern); + deps.push({ pattern, registry, hint, optional, workspaceName: manifest.name, workspaceLoc: manifest._loc }); + } + }; + + if (cwdIsRoot) { + pushDeps('dependencies', projectManifestJson, { hint: null, optional: false }, true); + pushDeps('devDependencies', projectManifestJson, { hint: 'dev', optional: false }, !_this.config.production); + pushDeps('optionalDependencies', projectManifestJson, { hint: 'optional', optional: true }, true); + } + + if (_this.config.workspaceRootFolder) { + const workspaceLoc = cwdIsRoot ? loc : path.join(_this.config.lockfileFolder, filename); + const workspacesRoot = path.dirname(workspaceLoc); + + let workspaceManifestJson = projectManifestJson; + if (!cwdIsRoot) { + // the manifest we read before was a child workspace, so get the root + workspaceManifestJson = yield _this.config.readJson(workspaceLoc); + yield (0, (_index || _load_index()).default)(workspaceManifestJson, workspacesRoot, _this.config, true); + } + + const workspaces = yield _this.config.resolveWorkspaces(workspacesRoot, workspaceManifestJson); + workspaceLayout = new (_workspaceLayout || _load_workspaceLayout()).default(workspaces, _this.config); + + // add virtual manifest that depends on all workspaces, this way package hoisters and resolvers will work fine + const workspaceDependencies = (0, (_extends2 || _load_extends()).default)({}, workspaceManifestJson.dependencies); + for (var _iterator5 = Object.keys(workspaces), _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) { + var _ref5; + + if (_isArray5) { + if (_i5 >= _iterator5.length) break; + _ref5 = _iterator5[_i5++]; + } else { + _i5 = _iterator5.next(); + if (_i5.done) break; + _ref5 = _i5.value; + } + + const workspaceName = _ref5; + + const workspaceManifest = workspaces[workspaceName].manifest; + workspaceDependencies[workspaceName] = workspaceManifest.version; + + // include dependencies from all workspaces + if (_this.flags.includeWorkspaceDeps) { + pushDeps('dependencies', workspaceManifest, { hint: null, optional: false }, true); + pushDeps('devDependencies', workspaceManifest, { hint: 'dev', optional: false }, !_this.config.production); + pushDeps('optionalDependencies', workspaceManifest, { hint: 'optional', optional: true }, true); + } + } + const virtualDependencyManifest = { + _uid: '', + name: `workspace-aggregator-${uuid.v4()}`, + version: '1.0.0', + _registry: 'npm', + _loc: workspacesRoot, + dependencies: workspaceDependencies, + devDependencies: (0, (_extends2 || _load_extends()).default)({}, workspaceManifestJson.devDependencies), + optionalDependencies: (0, (_extends2 || _load_extends()).default)({}, workspaceManifestJson.optionalDependencies), + private: workspaceManifestJson.private, + workspaces: workspaceManifestJson.workspaces + }; + workspaceLayout.virtualManifestName = virtualDependencyManifest.name; + const virtualDep = {}; + virtualDep[virtualDependencyManifest.name] = virtualDependencyManifest.version; + workspaces[virtualDependencyManifest.name] = { loc: workspacesRoot, manifest: virtualDependencyManifest }; + + // ensure dependencies that should be excluded are stripped from the correct manifest + stripExcluded(cwdIsRoot ? virtualDependencyManifest : workspaces[projectManifestJson.name].manifest); + + pushDeps('workspaces', { workspaces: virtualDep }, { hint: 'workspaces', optional: false }, true); + + const implicitWorkspaceDependencies = (0, (_extends2 || _load_extends()).default)({}, workspaceDependencies); + + for (var _iterator6 = (_constants || _load_constants()).OWNED_DEPENDENCY_TYPES, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) { + var _ref6; + + if (_isArray6) { + if (_i6 >= _iterator6.length) break; + _ref6 = _iterator6[_i6++]; + } else { + _i6 = _iterator6.next(); + if (_i6.done) break; + _ref6 = _i6.value; + } + + const type = _ref6; + + for (var _iterator7 = Object.keys(projectManifestJson[type] || {}), _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) { + var _ref7; + + if (_isArray7) { + if (_i7 >= _iterator7.length) break; + _ref7 = _iterator7[_i7++]; + } else { + _i7 = _iterator7.next(); + if (_i7.done) break; + _ref7 = _i7.value; + } + + const dependencyName = _ref7; + + delete implicitWorkspaceDependencies[dependencyName]; + } + } + + pushDeps('dependencies', { dependencies: implicitWorkspaceDependencies }, { hint: 'workspaces', optional: false }, true); + } + + break; + } + + // inherit root flat flag + if (manifest.flat) { + _this.flags.flat = true; + } + + return { + requests: [...resolutionDeps, ...deps], + patterns, + manifest, + usedPatterns, + ignorePatterns, + workspaceLayout + }; + })(); + } + + /** + * TODO description + */ + + prepareRequests(requests) { + return requests; + } + + preparePatterns(patterns) { + return patterns; + } + preparePatternsForLinking(patterns, cwdManifest, cwdIsRoot) { + return patterns; + } + + prepareManifests() { + var _this2 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const manifests = yield _this2.config.getRootManifests(); + return manifests; + })(); + } + + bailout(patterns, workspaceLayout) { + var _this3 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // We don't want to skip the audit - it could yield important errors + if (_this3.flags.audit) { + return false; + } + // PNP is so fast that the integrity check isn't pertinent + if (_this3.config.plugnplayEnabled) { + return false; + } + if (_this3.flags.skipIntegrityCheck || _this3.flags.force) { + return false; + } + const lockfileCache = _this3.lockfile.cache; + if (!lockfileCache) { + return false; + } + const lockfileClean = _this3.lockfile.parseResultType === 'success'; + const match = yield _this3.integrityChecker.check(patterns, lockfileCache, _this3.flags, workspaceLayout); + if (_this3.flags.frozenLockfile && (!lockfileClean || match.missingPatterns.length > 0)) { + throw new (_errors || _load_errors()).MessageError(_this3.reporter.lang('frozenLockfileError')); + } + + const haveLockfile = yield (_fs || _load_fs()).exists(path.join(_this3.config.lockfileFolder, (_constants || _load_constants()).LOCKFILE_FILENAME)); + + const lockfileIntegrityPresent = !_this3.lockfile.hasEntriesExistWithoutIntegrity(); + const integrityBailout = lockfileIntegrityPresent || !_this3.config.autoAddIntegrity; + + if (match.integrityMatches && haveLockfile && lockfileClean && integrityBailout) { + _this3.reporter.success(_this3.reporter.lang('upToDate')); + return true; + } + + if (match.integrityFileMissing && haveLockfile) { + // Integrity file missing, force script installations + _this3.scripts.setForce(true); + return false; + } + + if (match.hardRefreshRequired) { + // e.g. node version doesn't match, force script installations + _this3.scripts.setForce(true); + return false; + } + + if (!patterns.length && !match.integrityFileMissing) { + _this3.reporter.success(_this3.reporter.lang('nothingToInstall')); + yield _this3.createEmptyManifestFolders(); + yield _this3.saveLockfileAndIntegrity(patterns, workspaceLayout); + return true; + } + + return false; + })(); + } + + /** + * Produce empty folders for all used root manifests. + */ + + createEmptyManifestFolders() { + var _this4 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (_this4.config.modulesFolder) { + // already created + return; + } + + for (var _iterator9 = _this4.rootManifestRegistries, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : _iterator9[Symbol.iterator]();;) { + var _ref10; + + if (_isArray9) { + if (_i9 >= _iterator9.length) break; + _ref10 = _iterator9[_i9++]; + } else { + _i9 = _iterator9.next(); + if (_i9.done) break; + _ref10 = _i9.value; + } + + const registryName = _ref10; + const folder = _this4.config.registries[registryName].folder; + + yield (_fs || _load_fs()).mkdirp(path.join(_this4.config.lockfileFolder, folder)); + } + })(); + } + + /** + * TODO description + */ + + markIgnored(patterns) { + for (var _iterator10 = patterns, _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : _iterator10[Symbol.iterator]();;) { + var _ref11; + + if (_isArray10) { + if (_i10 >= _iterator10.length) break; + _ref11 = _iterator10[_i10++]; + } else { + _i10 = _iterator10.next(); + if (_i10.done) break; + _ref11 = _i10.value; + } + + const pattern = _ref11; + + const manifest = this.resolver.getStrictResolvedPattern(pattern); + const ref = manifest._reference; + invariant(ref, 'expected package reference'); + + // just mark the package as ignored. if the package is used by a required package, the hoister + // will take care of that. + ref.ignore = true; + } + } + + /** + * helper method that gets only recent manifests + * used by global.ls command + */ + getFlattenedDeps() { + var _this5 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + var _ref12 = yield _this5.fetchRequestFromCwd(); + + const depRequests = _ref12.requests, + rawPatterns = _ref12.patterns; + + + yield _this5.resolver.init(depRequests, {}); + + const manifests = yield (_packageFetcher || _load_packageFetcher()).fetch(_this5.resolver.getManifests(), _this5.config); + _this5.resolver.updateManifests(manifests); + + return _this5.flatten(rawPatterns); + })(); + } + + /** + * TODO description + */ + + init() { + var _this6 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this6.checkUpdate(); + + // warn if we have a shrinkwrap + if (yield (_fs || _load_fs()).exists(path.join(_this6.config.lockfileFolder, (_constants || _load_constants()).NPM_SHRINKWRAP_FILENAME))) { + _this6.reporter.warn(_this6.reporter.lang('shrinkwrapWarning')); + } + + // warn if we have an npm lockfile + if (yield (_fs || _load_fs()).exists(path.join(_this6.config.lockfileFolder, (_constants || _load_constants()).NPM_LOCK_FILENAME))) { + _this6.reporter.warn(_this6.reporter.lang('npmLockfileWarning')); + } + + if (_this6.config.plugnplayEnabled) { + _this6.reporter.info(_this6.reporter.lang('plugnplaySuggestV2L1')); + _this6.reporter.info(_this6.reporter.lang('plugnplaySuggestV2L2')); + } + + let flattenedTopLevelPatterns = []; + const steps = []; + + var _ref13 = yield _this6.fetchRequestFromCwd(); + + const depRequests = _ref13.requests, + rawPatterns = _ref13.patterns, + ignorePatterns = _ref13.ignorePatterns, + workspaceLayout = _ref13.workspaceLayout, + manifest = _ref13.manifest; + + let topLevelPatterns = []; + + const artifacts = yield _this6.integrityChecker.getArtifacts(); + if (artifacts) { + _this6.linker.setArtifacts(artifacts); + _this6.scripts.setArtifacts(artifacts); + } + + if ((_packageCompatibility || _load_packageCompatibility()).shouldCheck(manifest, _this6.flags)) { + steps.push((() => { + var _ref14 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { + _this6.reporter.step(curr, total, _this6.reporter.lang('checkingManifest'), emoji.get('mag')); + yield _this6.checkCompatibility(); + }); + + return function (_x, _x2) { + return _ref14.apply(this, arguments); + }; + })()); + } + + const audit = new (_audit || _load_audit()).default(_this6.config, _this6.reporter, { groups: (_constants || _load_constants()).OWNED_DEPENDENCY_TYPES }); + let auditFoundProblems = false; + + steps.push(function (curr, total) { + return (0, (_hooks || _load_hooks()).callThroughHook)('resolveStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this6.reporter.step(curr, total, _this6.reporter.lang('resolvingPackages'), emoji.get('mag')); + yield _this6.resolver.init(_this6.prepareRequests(depRequests), { + isFlat: _this6.flags.flat, + isFrozen: _this6.flags.frozenLockfile, + workspaceLayout + }); + topLevelPatterns = _this6.preparePatterns(rawPatterns); + flattenedTopLevelPatterns = yield _this6.flatten(topLevelPatterns); + return { bailout: !_this6.flags.audit && (yield _this6.bailout(topLevelPatterns, workspaceLayout)) }; + })); + }); + + if (_this6.flags.audit) { + steps.push(function (curr, total) { + return (0, (_hooks || _load_hooks()).callThroughHook)('auditStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this6.reporter.step(curr, total, _this6.reporter.lang('auditRunning'), emoji.get('mag')); + if (_this6.flags.offline) { + _this6.reporter.warn(_this6.reporter.lang('auditOffline')); + return { bailout: false }; + } + const preparedManifests = yield _this6.prepareManifests(); + // $FlowFixMe - Flow considers `m` in the map operation to be "mixed", so does not recognize `m.object` + const mergedManifest = Object.assign({}, ...Object.values(preparedManifests).map(function (m) { + return m.object; + })); + const auditVulnerabilityCounts = yield audit.performAudit(mergedManifest, _this6.lockfile, _this6.resolver, _this6.linker, topLevelPatterns); + auditFoundProblems = auditVulnerabilityCounts.info || auditVulnerabilityCounts.low || auditVulnerabilityCounts.moderate || auditVulnerabilityCounts.high || auditVulnerabilityCounts.critical; + return { bailout: yield _this6.bailout(topLevelPatterns, workspaceLayout) }; + })); + }); + } + + steps.push(function (curr, total) { + return (0, (_hooks || _load_hooks()).callThroughHook)('fetchStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this6.markIgnored(ignorePatterns); + _this6.reporter.step(curr, total, _this6.reporter.lang('fetchingPackages'), emoji.get('truck')); + const manifests = yield (_packageFetcher || _load_packageFetcher()).fetch(_this6.resolver.getManifests(), _this6.config); + _this6.resolver.updateManifests(manifests); + yield (_packageCompatibility || _load_packageCompatibility()).check(_this6.resolver.getManifests(), _this6.config, _this6.flags.ignoreEngines); + })); + }); + + steps.push(function (curr, total) { + return (0, (_hooks || _load_hooks()).callThroughHook)('linkStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // remove integrity hash to make this operation atomic + yield _this6.integrityChecker.removeIntegrityFile(); + _this6.reporter.step(curr, total, _this6.reporter.lang('linkingDependencies'), emoji.get('link')); + flattenedTopLevelPatterns = _this6.preparePatternsForLinking(flattenedTopLevelPatterns, manifest, _this6.config.lockfileFolder === _this6.config.cwd); + yield _this6.linker.init(flattenedTopLevelPatterns, workspaceLayout, { + linkDuplicates: _this6.flags.linkDuplicates, + ignoreOptional: _this6.flags.ignoreOptional + }); + })); + }); + + if (_this6.config.plugnplayEnabled) { + steps.push(function (curr, total) { + return (0, (_hooks || _load_hooks()).callThroughHook)('pnpStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const pnpPath = `${_this6.config.lockfileFolder}/${(_constants || _load_constants()).PNP_FILENAME}`; + + const code = yield (0, (_generatePnpMap || _load_generatePnpMap()).generatePnpMap)(_this6.config, flattenedTopLevelPatterns, { + resolver: _this6.resolver, + reporter: _this6.reporter, + targetPath: pnpPath, + workspaceLayout + }); + + try { + const file = yield (_fs || _load_fs()).readFile(pnpPath); + if (file === code) { + return; + } + } catch (error) {} + + yield (_fs || _load_fs()).writeFile(pnpPath, code); + yield (_fs || _load_fs()).chmod(pnpPath, 0o755); + })); + }); + } + + steps.push(function (curr, total) { + return (0, (_hooks || _load_hooks()).callThroughHook)('buildStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this6.reporter.step(curr, total, _this6.flags.force ? _this6.reporter.lang('rebuildingPackages') : _this6.reporter.lang('buildingFreshPackages'), emoji.get('hammer')); + + if (_this6.config.ignoreScripts) { + _this6.reporter.warn(_this6.reporter.lang('ignoredScripts')); + } else { + yield _this6.scripts.init(flattenedTopLevelPatterns); + } + })); + }); + + if (_this6.flags.har) { + steps.push((() => { + var _ref21 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { + const formattedDate = new Date().toISOString().replace(/:/g, '-'); + const filename = `yarn-install_${formattedDate}.har`; + _this6.reporter.step(curr, total, _this6.reporter.lang('savingHar', filename), emoji.get('black_circle_for_record')); + yield _this6.config.requestManager.saveHar(filename); + }); + + return function (_x3, _x4) { + return _ref21.apply(this, arguments); + }; + })()); + } + + if (yield _this6.shouldClean()) { + steps.push((() => { + var _ref22 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { + _this6.reporter.step(curr, total, _this6.reporter.lang('cleaningModules'), emoji.get('recycle')); + yield (0, (_autoclean || _load_autoclean()).clean)(_this6.config, _this6.reporter); + }); + + return function (_x5, _x6) { + return _ref22.apply(this, arguments); + }; + })()); + } + + let currentStep = 0; + for (var _iterator11 = steps, _isArray11 = Array.isArray(_iterator11), _i11 = 0, _iterator11 = _isArray11 ? _iterator11 : _iterator11[Symbol.iterator]();;) { + var _ref23; + + if (_isArray11) { + if (_i11 >= _iterator11.length) break; + _ref23 = _iterator11[_i11++]; + } else { + _i11 = _iterator11.next(); + if (_i11.done) break; + _ref23 = _i11.value; + } + + const step = _ref23; + + const stepResult = yield step(++currentStep, steps.length); + if (stepResult && stepResult.bailout) { + if (_this6.flags.audit) { + audit.summary(); + } + if (auditFoundProblems) { + _this6.reporter.warn(_this6.reporter.lang('auditRunAuditForDetails')); + } + _this6.maybeOutputUpdate(); + return flattenedTopLevelPatterns; + } + } + + // fin! + if (_this6.flags.audit) { + audit.summary(); + } + if (auditFoundProblems) { + _this6.reporter.warn(_this6.reporter.lang('auditRunAuditForDetails')); + } + yield _this6.saveLockfileAndIntegrity(topLevelPatterns, workspaceLayout); + yield _this6.persistChanges(); + _this6.maybeOutputUpdate(); + _this6.config.requestManager.clearCache(); + return flattenedTopLevelPatterns; + })(); + } + + checkCompatibility() { + var _this7 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + var _ref24 = yield _this7.fetchRequestFromCwd(); + + const manifest = _ref24.manifest; + + yield (_packageCompatibility || _load_packageCompatibility()).checkOne(manifest, _this7.config, _this7.flags.ignoreEngines); + })(); + } + + persistChanges() { + var _this8 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // get all the different registry manifests in this folder + const manifests = yield _this8.config.getRootManifests(); + + if (yield _this8.applyChanges(manifests)) { + yield _this8.config.saveRootManifests(manifests); + } + })(); + } + + applyChanges(manifests) { + let hasChanged = false; + + if (this.config.plugnplayPersist) { + const object = manifests.npm.object; + + + if (typeof object.installConfig !== 'object') { + object.installConfig = {}; + } + + if (this.config.plugnplayEnabled && object.installConfig.pnp !== true) { + object.installConfig.pnp = true; + hasChanged = true; + } else if (!this.config.plugnplayEnabled && typeof object.installConfig.pnp !== 'undefined') { + delete object.installConfig.pnp; + hasChanged = true; + } + + if (Object.keys(object.installConfig).length === 0) { + delete object.installConfig; + } + } + + return Promise.resolve(hasChanged); + } + + /** + * Check if we should run the cleaning step. + */ + + shouldClean() { + return (_fs || _load_fs()).exists(path.join(this.config.lockfileFolder, (_constants || _load_constants()).CLEAN_FILENAME)); + } + + /** + * TODO + */ + + flatten(patterns) { + var _this9 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (!_this9.flags.flat) { + return patterns; + } + + const flattenedPatterns = []; + + for (var _iterator12 = _this9.resolver.getAllDependencyNamesByLevelOrder(patterns), _isArray12 = Array.isArray(_iterator12), _i12 = 0, _iterator12 = _isArray12 ? _iterator12 : _iterator12[Symbol.iterator]();;) { + var _ref25; + + if (_isArray12) { + if (_i12 >= _iterator12.length) break; + _ref25 = _iterator12[_i12++]; + } else { + _i12 = _iterator12.next(); + if (_i12.done) break; + _ref25 = _i12.value; + } + + const name = _ref25; + + const infos = _this9.resolver.getAllInfoForPackageName(name).filter(function (manifest) { + const ref = manifest._reference; + invariant(ref, 'expected package reference'); + return !ref.ignore; + }); + + if (infos.length === 0) { + continue; + } + + if (infos.length === 1) { + // single version of this package + // take out a single pattern as multiple patterns may have resolved to this package + flattenedPatterns.push(_this9.resolver.patternsByPackage[name][0]); + continue; + } + + const options = infos.map(function (info) { + const ref = info._reference; + invariant(ref, 'expected reference'); + return { + // TODO `and is required by {PARENT}`, + name: _this9.reporter.lang('manualVersionResolutionOption', ref.patterns.join(', '), info.version), + + value: info.version + }; + }); + const versions = infos.map(function (info) { + return info.version; + }); + let version; + + const resolutionVersion = _this9.resolutions[name]; + if (resolutionVersion && versions.indexOf(resolutionVersion) >= 0) { + // use json `resolution` version + version = resolutionVersion; + } else { + version = yield _this9.reporter.select(_this9.reporter.lang('manualVersionResolution', name), _this9.reporter.lang('answer'), options); + _this9.resolutions[name] = version; + } + + flattenedPatterns.push(_this9.resolver.collapseAllVersionsOfPackage(name, version)); + } + + // save resolutions to their appropriate root manifest + if (Object.keys(_this9.resolutions).length) { + const manifests = yield _this9.config.getRootManifests(); + + for (const name in _this9.resolutions) { + const version = _this9.resolutions[name]; + + const patterns = _this9.resolver.patternsByPackage[name]; + if (!patterns) { + continue; + } + + let manifest; + for (var _iterator13 = patterns, _isArray13 = Array.isArray(_iterator13), _i13 = 0, _iterator13 = _isArray13 ? _iterator13 : _iterator13[Symbol.iterator]();;) { + var _ref26; + + if (_isArray13) { + if (_i13 >= _iterator13.length) break; + _ref26 = _iterator13[_i13++]; + } else { + _i13 = _iterator13.next(); + if (_i13.done) break; + _ref26 = _i13.value; + } + + const pattern = _ref26; + + manifest = _this9.resolver.getResolvedPattern(pattern); + if (manifest) { + break; + } + } + invariant(manifest, 'expected manifest'); + + const ref = manifest._reference; + invariant(ref, 'expected reference'); + + const object = manifests[ref.registry].object; + object.resolutions = object.resolutions || {}; + object.resolutions[name] = version; + } + + yield _this9.config.saveRootManifests(manifests); + } + + return flattenedPatterns; + })(); + } + + /** + * Remove offline tarballs that are no longer required + */ + + pruneOfflineMirror(lockfile) { + var _this10 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const mirror = _this10.config.getOfflineMirrorPath(); + if (!mirror) { + return; + } + + const requiredTarballs = new Set(); + for (const dependency in lockfile) { + const resolved = lockfile[dependency].resolved; + if (resolved) { + const basename = path.basename(resolved.split('#')[0]); + if (dependency[0] === '@' && basename[0] !== '@') { + requiredTarballs.add(`${dependency.split('/')[0]}-${basename}`); + } + requiredTarballs.add(basename); + } + } + + const mirrorFiles = yield (_fs || _load_fs()).walk(mirror); + for (var _iterator14 = mirrorFiles, _isArray14 = Array.isArray(_iterator14), _i14 = 0, _iterator14 = _isArray14 ? _iterator14 : _iterator14[Symbol.iterator]();;) { + var _ref27; + + if (_isArray14) { + if (_i14 >= _iterator14.length) break; + _ref27 = _iterator14[_i14++]; + } else { + _i14 = _iterator14.next(); + if (_i14.done) break; + _ref27 = _i14.value; + } + + const file = _ref27; + + const isTarball = path.extname(file.basename) === '.tgz'; + // if using experimental-pack-script-packages-in-mirror flag, don't unlink prebuilt packages + const hasPrebuiltPackage = file.relative.startsWith('prebuilt/'); + if (isTarball && !hasPrebuiltPackage && !requiredTarballs.has(file.basename)) { + yield (_fs || _load_fs()).unlink(file.absolute); + } + } + })(); + } + + /** + * Save updated integrity and lockfiles. + */ + + saveLockfileAndIntegrity(patterns, workspaceLayout) { + var _this11 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const resolvedPatterns = {}; + Object.keys(_this11.resolver.patterns).forEach(function (pattern) { + if (!workspaceLayout || !workspaceLayout.getManifestByPattern(pattern)) { + resolvedPatterns[pattern] = _this11.resolver.patterns[pattern]; + } + }); + + // TODO this code is duplicated in a few places, need a common way to filter out workspace patterns from lockfile + patterns = patterns.filter(function (p) { + return !workspaceLayout || !workspaceLayout.getManifestByPattern(p); + }); + + const lockfileBasedOnResolver = _this11.lockfile.getLockfile(resolvedPatterns); + + if (_this11.config.pruneOfflineMirror) { + yield _this11.pruneOfflineMirror(lockfileBasedOnResolver); + } + + // write integrity hash + if (!_this11.config.plugnplayEnabled) { + yield _this11.integrityChecker.save(patterns, lockfileBasedOnResolver, _this11.flags, workspaceLayout, _this11.scripts.getArtifacts()); + } + + // --no-lockfile or --pure-lockfile or --frozen-lockfile + if (_this11.flags.lockfile === false || _this11.flags.pureLockfile || _this11.flags.frozenLockfile) { + return; + } + + const lockFileHasAllPatterns = patterns.every(function (p) { + return _this11.lockfile.getLocked(p); + }); + const lockfilePatternsMatch = Object.keys(_this11.lockfile.cache || {}).every(function (p) { + return lockfileBasedOnResolver[p]; + }); + const resolverPatternsAreSameAsInLockfile = Object.keys(lockfileBasedOnResolver).every(function (pattern) { + const manifest = _this11.lockfile.getLocked(pattern); + return manifest && manifest.resolved === lockfileBasedOnResolver[pattern].resolved && deepEqual(manifest.prebuiltVariants, lockfileBasedOnResolver[pattern].prebuiltVariants); + }); + const integrityPatternsAreSameAsInLockfile = Object.keys(lockfileBasedOnResolver).every(function (pattern) { + const existingIntegrityInfo = lockfileBasedOnResolver[pattern].integrity; + if (!existingIntegrityInfo) { + // if this entry does not have an integrity, no need to re-write the lockfile because of it + return true; + } + const manifest = _this11.lockfile.getLocked(pattern); + if (manifest && manifest.integrity) { + const manifestIntegrity = ssri.stringify(manifest.integrity); + return manifestIntegrity === existingIntegrityInfo; + } + return false; + }); + + // remove command is followed by install with force, lockfile will be rewritten in any case then + if (!_this11.flags.force && _this11.lockfile.parseResultType === 'success' && lockFileHasAllPatterns && lockfilePatternsMatch && resolverPatternsAreSameAsInLockfile && integrityPatternsAreSameAsInLockfile && patterns.length) { + return; + } + + // build lockfile location + const loc = path.join(_this11.config.lockfileFolder, (_constants || _load_constants()).LOCKFILE_FILENAME); + + // write lockfile + const lockSource = (0, (_lockfile2 || _load_lockfile2()).stringify)(lockfileBasedOnResolver, false, _this11.config.enableLockfileVersions); + yield (_fs || _load_fs()).writeFilePreservingEol(loc, lockSource); + + _this11._logSuccessSaveLockfile(); + })(); + } + + _logSuccessSaveLockfile() { + this.reporter.success(this.reporter.lang('savedLockfile')); + } + + /** + * Load the dependency graph of the current install. Only does package resolving and wont write to the cwd. + */ + hydrate(ignoreUnusedPatterns) { + var _this12 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const request = yield _this12.fetchRequestFromCwd([], ignoreUnusedPatterns); + const depRequests = request.requests, + rawPatterns = request.patterns, + ignorePatterns = request.ignorePatterns, + workspaceLayout = request.workspaceLayout; + + + yield _this12.resolver.init(depRequests, { + isFlat: _this12.flags.flat, + isFrozen: _this12.flags.frozenLockfile, + workspaceLayout + }); + yield _this12.flatten(rawPatterns); + _this12.markIgnored(ignorePatterns); + + // fetch packages, should hit cache most of the time + const manifests = yield (_packageFetcher || _load_packageFetcher()).fetch(_this12.resolver.getManifests(), _this12.config); + _this12.resolver.updateManifests(manifests); + yield (_packageCompatibility || _load_packageCompatibility()).check(_this12.resolver.getManifests(), _this12.config, _this12.flags.ignoreEngines); + + // expand minimal manifests + for (var _iterator15 = _this12.resolver.getManifests(), _isArray15 = Array.isArray(_iterator15), _i15 = 0, _iterator15 = _isArray15 ? _iterator15 : _iterator15[Symbol.iterator]();;) { + var _ref28; + + if (_isArray15) { + if (_i15 >= _iterator15.length) break; + _ref28 = _iterator15[_i15++]; + } else { + _i15 = _iterator15.next(); + if (_i15.done) break; + _ref28 = _i15.value; + } + + const manifest = _ref28; + + const ref = manifest._reference; + invariant(ref, 'expected reference'); + const type = ref.remote.type; + // link specifier won't ever hit cache + + let loc = ''; + if (type === 'link') { + continue; + } else if (type === 'workspace') { + if (!ref.remote.reference) { + continue; + } + loc = ref.remote.reference; + } else { + loc = _this12.config.generateModuleCachePath(ref); + } + const newPkg = yield _this12.config.readManifest(loc); + yield _this12.resolver.updateManifest(ref, newPkg); + } + + return request; + })(); + } + + /** + * Check for updates every day and output a nag message if there's a newer version. + */ + + checkUpdate() { + if (this.config.nonInteractive) { + // don't show upgrade dialog on CI or non-TTY terminals + return; + } + + // don't check if disabled + if (this.config.getOption('disable-self-update-check')) { + return; + } + + // only check for updates once a day + const lastUpdateCheck = Number(this.config.getOption('lastUpdateCheck')) || 0; + if (lastUpdateCheck && Date.now() - lastUpdateCheck < ONE_DAY) { + return; + } + + // don't bug for updates on tagged releases + if ((_yarnVersion || _load_yarnVersion()).version.indexOf('-') >= 0) { + return; + } + + this._checkUpdate().catch(() => { + // swallow errors + }); + } + + _checkUpdate() { + var _this13 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + let latestVersion = yield _this13.config.requestManager.request({ + url: (_constants || _load_constants()).SELF_UPDATE_VERSION_URL + }); + invariant(typeof latestVersion === 'string', 'expected string'); + latestVersion = latestVersion.trim(); + if (!semver.valid(latestVersion)) { + return; + } + + // ensure we only check for updates periodically + _this13.config.registries.yarn.saveHomeConfig({ + lastUpdateCheck: Date.now() + }); + + if (semver.gt(latestVersion, (_yarnVersion || _load_yarnVersion()).version)) { + const installationMethod = yield (0, (_yarnVersion || _load_yarnVersion()).getInstallationMethod)(); + _this13.maybeOutputUpdate = function () { + _this13.reporter.warn(_this13.reporter.lang('yarnOutdated', latestVersion, (_yarnVersion || _load_yarnVersion()).version)); + + const command = getUpdateCommand(installationMethod); + if (command) { + _this13.reporter.info(_this13.reporter.lang('yarnOutdatedCommand')); + _this13.reporter.command(command); + } else { + const installer = getUpdateInstaller(installationMethod); + if (installer) { + _this13.reporter.info(_this13.reporter.lang('yarnOutdatedInstaller', installer)); + } + } + }; + } + })(); + } + + /** + * Method to override with a possible upgrade message. + */ + + maybeOutputUpdate() {} +} + +exports.Install = Install; +function hasWrapper(commander, args) { + return true; +} + +function setFlags(commander) { + commander.description('Yarn install is used to install all dependencies for a project.'); + commander.usage('install [flags]'); + commander.option('-A, --audit', 'Run vulnerability audit on installed packages'); + commander.option('-g, --global', 'DEPRECATED'); + commander.option('-S, --save', 'DEPRECATED - save package to your `dependencies`'); + commander.option('-D, --save-dev', 'DEPRECATED - save package to your `devDependencies`'); + commander.option('-P, --save-peer', 'DEPRECATED - save package to your `peerDependencies`'); + commander.option('-O, --save-optional', 'DEPRECATED - save package to your `optionalDependencies`'); + commander.option('-E, --save-exact', 'DEPRECATED'); + commander.option('-T, --save-tilde', 'DEPRECATED'); +} + +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { + +var isObject = __webpack_require__(53); +module.exports = function (it) { + if (!isObject(it)) throw TypeError(it + ' is not an object!'); + return it; +}; + + +/***/ }), +/* 36 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return SubjectSubscriber; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Subject; }); +/* unused harmony export AnonymousSubject */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(1); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Observable__ = __webpack_require__(12); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Subscriber__ = __webpack_require__(7); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Subscription__ = __webpack_require__(25); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__ = __webpack_require__(190); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__SubjectSubscription__ = __webpack_require__(422); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__internal_symbol_rxSubscriber__ = __webpack_require__(321); +/** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */ + + + + + + + +var SubjectSubscriber = /*@__PURE__*/ (function (_super) { + __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](SubjectSubscriber, _super); + function SubjectSubscriber(destination) { + var _this = _super.call(this, destination) || this; + _this.destination = destination; + return _this; + } + return SubjectSubscriber; +}(__WEBPACK_IMPORTED_MODULE_2__Subscriber__["a" /* Subscriber */])); + +var Subject = /*@__PURE__*/ (function (_super) { + __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](Subject, _super); + function Subject() { + var _this = _super.call(this) || this; + _this.observers = []; + _this.closed = false; + _this.isStopped = false; + _this.hasError = false; + _this.thrownError = null; + return _this; + } + Subject.prototype[__WEBPACK_IMPORTED_MODULE_6__internal_symbol_rxSubscriber__["a" /* rxSubscriber */]] = function () { + return new SubjectSubscriber(this); + }; + Subject.prototype.lift = function (operator) { + var subject = new AnonymousSubject(this, this); + subject.operator = operator; + return subject; + }; + Subject.prototype.next = function (value) { + if (this.closed) { + throw new __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__["a" /* ObjectUnsubscribedError */](); + } + if (!this.isStopped) { + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].next(value); + } + } + }; + Subject.prototype.error = function (err) { + if (this.closed) { + throw new __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__["a" /* ObjectUnsubscribedError */](); + } + this.hasError = true; + this.thrownError = err; + this.isStopped = true; + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].error(err); + } + this.observers.length = 0; + }; + Subject.prototype.complete = function () { + if (this.closed) { + throw new __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__["a" /* ObjectUnsubscribedError */](); + } + this.isStopped = true; + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].complete(); + } + this.observers.length = 0; + }; + Subject.prototype.unsubscribe = function () { + this.isStopped = true; + this.closed = true; + this.observers = null; + }; + Subject.prototype._trySubscribe = function (subscriber) { + if (this.closed) { + throw new __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__["a" /* ObjectUnsubscribedError */](); + } + else { + return _super.prototype._trySubscribe.call(this, subscriber); + } + }; + Subject.prototype._subscribe = function (subscriber) { + if (this.closed) { + throw new __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__["a" /* ObjectUnsubscribedError */](); + } + else if (this.hasError) { + subscriber.error(this.thrownError); + return __WEBPACK_IMPORTED_MODULE_3__Subscription__["a" /* Subscription */].EMPTY; + } + else if (this.isStopped) { + subscriber.complete(); + return __WEBPACK_IMPORTED_MODULE_3__Subscription__["a" /* Subscription */].EMPTY; + } + else { + this.observers.push(subscriber); + return new __WEBPACK_IMPORTED_MODULE_5__SubjectSubscription__["a" /* SubjectSubscription */](this, subscriber); + } + }; + Subject.prototype.asObservable = function () { + var observable = new __WEBPACK_IMPORTED_MODULE_1__Observable__["a" /* Observable */](); + observable.source = this; + return observable; + }; + Subject.create = function (destination, source) { + return new AnonymousSubject(destination, source); + }; + return Subject; +}(__WEBPACK_IMPORTED_MODULE_1__Observable__["a" /* Observable */])); + +var AnonymousSubject = /*@__PURE__*/ (function (_super) { + __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](AnonymousSubject, _super); + function AnonymousSubject(destination, source) { + var _this = _super.call(this) || this; + _this.destination = destination; + _this.source = source; + return _this; + } + AnonymousSubject.prototype.next = function (value) { + var destination = this.destination; + if (destination && destination.next) { + destination.next(value); + } + }; + AnonymousSubject.prototype.error = function (err) { + var destination = this.destination; + if (destination && destination.error) { + this.destination.error(err); + } + }; + AnonymousSubject.prototype.complete = function () { + var destination = this.destination; + if (destination && destination.complete) { + this.destination.complete(); + } + }; + AnonymousSubject.prototype._subscribe = function (subscriber) { + var source = this.source; + if (source) { + return this.source.subscribe(subscriber); + } + else { + return __WEBPACK_IMPORTED_MODULE_3__Subscription__["a" /* Subscription */].EMPTY; + } + }; + return AnonymousSubject; +}(Subject)); + +//# sourceMappingURL=Subject.js.map + + +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.normalizePattern = normalizePattern; + +/** + * Explode and normalize a pattern into its name and range. + */ + +function normalizePattern(pattern) { + let hasVersion = false; + let range = 'latest'; + let name = pattern; + + // if we're a scope then remove the @ and add it back later + let isScoped = false; + if (name[0] === '@') { + isScoped = true; + name = name.slice(1); + } + + // take first part as the name + const parts = name.split('@'); + if (parts.length > 1) { + name = parts.shift(); + range = parts.join('@'); + + if (range) { + hasVersion = true; + } else { + range = '*'; + } + } + + // add back @ scope suffix + if (isScoped) { + name = `@${name}`; + } + + return { name, range, hasVersion }; +} + +/***/ }), +/* 38 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;/** + * @license + * Lodash + * Copyright JS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '4.17.10'; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Error message constants. */ + var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', + FUNC_ERROR_TEXT = 'Expected a function'; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; + + /** Used to compose bitmasks for cloning. */ + var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** Used to compose bitmasks for function metadata. */ + var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256, + WRAP_FLIP_FLAG = 512; + + /** Used as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; + + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2, + LAZY_WHILE_FLAG = 3; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + + /** Used to associate wrap methods with their bit flags. */ + var wrapFlags = [ + ['ary', WRAP_ARY_FLAG], + ['bind', WRAP_BIND_FLAG], + ['bindKey', WRAP_BIND_KEY_FLAG], + ['curry', WRAP_CURRY_FLAG], + ['curryRight', WRAP_CURRY_RIGHT_FLAG], + ['flip', WRAP_FLIP_FLAG], + ['partial', WRAP_PARTIAL_FLAG], + ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], + ['rearg', WRAP_REARG_FLAG] + ]; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + domExcTag = '[object DOMException]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]', + weakSetTag = '[object WeakSet]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, + reUnescapedHtml = /[&<>"']/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); + + /** Used to match leading and trailing whitespace. */ + var reTrim = /^\s+|\s+$/g, + reTrimStart = /^\s+/, + reTrimEnd = /\s+$/; + + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; + + /** Used to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; + + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + + /** Used to compose unicode capture groups. */ + var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; + + /** Used to compose unicode regexes. */ + var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', + rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', + rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); + + /** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ + var reComboMark = RegExp(rsCombo, 'g'); + + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + + /** Used to match complex or compound words. */ + var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', + rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, + rsUpper + '+' + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji + ].join('|'), 'g'); + + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ + var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + + /** Used to detect strings that need a more robust regexp to match words. */ + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', + 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' + ]; + + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = + cloneableTags[boolTag] = cloneableTags[dateTag] = + cloneableTags[float32Tag] = cloneableTags[float64Tag] = + cloneableTags[int8Tag] = cloneableTags[int16Tag] = + cloneableTags[int32Tag] = cloneableTags[mapTag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[setTag] = + cloneableTags[stringTag] = cloneableTags[symbolTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[weakMapTag] = false; + + /** Used to map Latin Unicode letters to basic Latin letters. */ + var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' + }; + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; + + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, + nodeIsDate = nodeUtil && nodeUtil.isDate, + nodeIsMap = nodeUtil && nodeUtil.isMap, + nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, + nodeIsSet = nodeUtil && nodeUtil.isSet, + nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /*--------------------------------------------------------------------------*/ + + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + + /** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + return accumulator; + } + + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; + } + + /** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; + } + + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + + /** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); + + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } + + /** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); + } + + /** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } + + /** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ + function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? (baseSum(array, iteratee) / length) : NAN; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + + /** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; + + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); + } + } + return result; + } + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ + function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; + } + + /** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + var deburrLetter = basePropertyOf(deburredLetters); + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); + + /** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } + + /** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + + /** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ + function iteratorToArray(iterator) { + var data, + result = []; + + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; + } + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; + } + } + return result; + } + + /** + * Gets the value at `key`, unless `key` is "__proto__". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function safeGet(object, key) { + return key == '__proto__' + ? undefined + : object[key]; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ + function setToPairs(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } + + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } + } + return index; + } + + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); + } + + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); + } + + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; + } + + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + + /** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new pristine `lodash` function using the `context` object. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Util + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + var runInContext = (function runInContext(context) { + context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); + + /** Built-in constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Built-in value references. */ + var Buffer = moduleExports ? context.Buffer : undefined, + Symbol = context.Symbol, + Uint8Array = context.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, + symIterator = Symbol ? Symbol.iterator : undefined, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + /** Mocked built-ins. */ + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, + ctxNow = Date && Date.now !== root.Date.now && Date.now, + ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeIsFinite = context.isFinite, + nativeJoin = arrayProto.join, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = Date.now, + nativeParseInt = context.parseInt, + nativeRandom = Math.random, + nativeReverse = arrayProto.reverse; + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(context, 'DataView'), + Map = getNative(context, 'Map'), + Promise = getNative(context, 'Promise'), + Set = getNative(context, 'Set'), + WeakMap = getNative(context, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + /** + * The function whose prototype chain sequence wrappers inherit from. + * + * @private + */ + function baseLodash() { + // No operation performed. + } + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; + } + + /** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB) as well as ES2015 template strings. Change the + * following template settings to use alternative delimiters. + * + * @static + * @memberOf _ + * @type {Object} + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + '_': lodash + } + }; + + // Ensure wrappers are instances of `baseLodash`. + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; + + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @constructor + * @param {*} value The value to wrap. + */ + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; + } + + /** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */ + function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; + } + + /** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */ + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; + } + + /** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */ + function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); + + if (!isArr || (!isRight && arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); + } + var result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } + return result; + } + + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); + } + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** + * A specialized version of `_.sample` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. + */ + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; + } + + /** + * A specialized version of `_.sampleSize` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); + } + + /** + * A specialized version of `_.shuffle` for arrays. + * + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); + } + + /** + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); + } + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + /** + * The base implementation of `_.at` without support for individual paths. + * + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. + */ + function baseAt(object, paths) { + var index = -1, + length = paths.length, + result = Array(length), + skip = object == null; + + while (++index < length) { + result[index] = skip ? undefined : get(object, paths[index]); + } + return result; + } + + /** + * The base implementation of `_.clamp` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + */ + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; + } + + /** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG; + + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (isSet(value)) { + value.forEach(function(subValue) { + result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); + }); + + return result; + } + + if (isMap(value)) { + value.forEach(function(subValue, key) { + result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + + return result; + } + + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys) + : (isFlat ? keysIn : keys); + + var props = isArr ? undefined : keysFunc(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + return result; + } + + /** + * The base implementation of `_.conforms` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */ + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; + } + + /** + * The base implementation of `_.conformsTo` which accepts `props` to check. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + */ + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } + } + return true; + } + + /** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ + function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + + /** + * The base implementation of `_.forEachRight` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEachRight = createBaseEach(baseForOwnRight, true); + + /** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ + function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; + } + + /** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ + function baseFill(array, value, start, end) { + var length = array.length; + + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; + } + + /** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseForRight = createBaseFor(true); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); + } + + /** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ + function baseGt(value, other) { + return value > other; + } + + /** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + /** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */ + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } + + /** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. + */ + function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; + } + array = arrays[0]; + + var index = -1, + seen = caches[0]; + + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. + */ + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; + } + + /** + * The base implementation of `_.invoke` without support for individual + * method arguments. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + */ + function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined : apply(func, object, args); + } + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + + /** + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + */ + function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; + } + + /** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + /** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + */ + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; + } + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) + : result + )) { + return false; + } + } + } + return true; + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; + } + + /** + * The base implementation of `_.isSet` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + */ + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; + } + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ + function baseLt(value, other) { + return value < other; + } + + /** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; + } + + /** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + if (isObject(srcValue)) { + stack || (stack = new Stack); + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); + } + + /** + * The base implementation of `_.nth` which doesn't coerce arguments. + * + * @private + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. + */ + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; + } + + /** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ + function baseOrderBy(collection, iteratees, orders) { + var index = -1; + iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); + } + + /** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. + */ + function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); + } + + /** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ + function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + + /** + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + */ + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; + } + + /** + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; + + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } + } + } + return array; + } + + /** + * The base implementation of `_.random` without support for returning + * floating-point numbers. + * + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. + */ + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); + } + + /** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ + function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; + } + + /** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */ + function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + + return result; + } + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * The base implementation of `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */ + function baseSample(collection) { + return arraySample(values(collection)); + } + + /** + * The base implementation of `_.sampleSize` without param guards. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); + } + + /** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + + /** + * The base implementation of `setData` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + + /** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** + * The base implementation of `_.shuffle`. + * + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function baseShuffle(collection) { + return shuffleSelf(values(collection)); + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); + } + + /** + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndexBy(array, value, iteratee, retHighest) { + value = iteratee(value); + + var low = 0, + high = array == null ? 0 : array.length, + valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + + /** + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; + } + + /** + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. + * + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. + */ + function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; + } + + /** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.unset`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The property path to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + */ + function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; + } + + /** + * The base implementation of `_.update`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to update. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); + } + + /** + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); + } + + /** + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of values. + */ + function baseXor(arrays, iteratee, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; + } + var index = -1, + result = Array(length); + + while (++index < length) { + var array = arrays[index], + othIndex = -1; + + while (++othIndex < length) { + if (othIndex != index) { + result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); + } + } + } + return baseUniq(baseFlatten(result, 1), iteratee, comparator); + } + + /** + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. + * + * @private + * @param {Array} props The property identifiers. + * @param {Array} values The property values. + * @param {Function} assignFunc The function to assign values. + * @returns {Object} Returns the new object. + */ + function baseZipObject(props, values, assignFunc) { + var index = -1, + length = props.length, + valsLength = values.length, + result = {}; + + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } + return result; + } + + /** + * Casts `value` to an empty array if it's not an array like object. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. + */ + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; + } + + /** + * Casts `value` to `identity` if it's not a function. + * + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. + */ + function castFunction(value) { + return typeof value == 'function' ? value : identity; + } + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + + /** + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. + * + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + var castRest = baseRest; + + /** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); + } + + /** + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). + * + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */ + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; + } + + /** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; + } + + /** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + + /** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; + } + + /** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; + } + + /** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; + } + + /** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; + } + + /** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; + } + + /** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result; + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * Copies own symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); + } + + /** + * Copies own and inherited symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); + } + + /** + * Creates a function like `_.groupBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; + + return func(collection, setter, getIteratee(iteratee, 2), accumulator); + }; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; + } + + /** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; + } + + /** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a function that wraps `func` to enable currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; + } + + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + + /** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; + + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; + + if (data && isLaziable(data[0]) && + data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; + + if (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); + } + + /** + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & WRAP_ARY_FLAG, + isBind = bitmask & WRAP_BIND_FLAG, + isBindKey = bitmask & WRAP_BIND_KEY_FLAG, + isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), + isFlip = bitmask & WRAP_FLIP_FLAG, + Ctor = isBindKey ? undefined : createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; + + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; + + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; + } + + /** + * Creates a function like `_.invertBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. + */ + function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; + } + + /** + * Creates a function that performs a mathematical operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. + */ + function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); + } + return result; + }; + } + + /** + * Creates a function like `_.over`. + * + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. + */ + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); + } + + /** + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. + * + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. + */ + function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); + } + + /** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * Creates a `_.range` or `_.rangeRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. + */ + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; + } + + /** + * Creates a function that performs a relational operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. + */ + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; + } + + /** + * Creates a function that wraps `func` to continue currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); + } + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; + + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); + } + + /** + * Creates a function like `_.round`. + * + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. + */ + function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); + if (precision) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); + } + return func(number); + }; + } + + /** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ + var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); + }; + + /** + * Creates a `_.toPairs` or `_.toPairsIn` function. + * + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. + */ + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; + } + + /** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); + } + + /** + * Used by `_.defaults` to customize its `_.assignIn` use to assign properties + * of source objects to the destination object for all destination properties + * that resolve to `undefined`. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ + function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; + } + + /** + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. + */ + function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); + stack['delete'](srcValue); + } + return objValue; + } + + /** + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. + * + * @private + * @param {*} value The value to inspect. + * @param {string} key The key of the property to inspect. + * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. + */ + function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); + } + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + + /** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + + /** + * Gets the name of `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. + */ + function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; + } + + /** + * Gets the argument placeholder value for `func`. + * + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. + */ + function getHolder(func) { + var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; + return object.placeholder; + } + + /** + * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, + * this function returns the custom method, otherwise it returns `baseIteratee`. + * If arguments are provided, the chosen function is invoked with them and + * its result is returned. + * + * @private + * @param {*} [value] The value to convert to an iteratee. + * @param {number} [arity] The arity of the created iteratee. + * @returns {Function} Returns the chosen function or its result. + */ + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; + + /** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } + + /** + * Gets the view, applying any `transforms` to the `start` and `end` positions. + * + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */ + function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; + } + + /** + * Extracts wrapper details from the `source` body comment. + * + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. + */ + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; + } + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ + function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } + + /** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return new Ctor; + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return new Ctor; + + case symbolTag: + return cloneSymbol(object); + } + } + + /** + * Inserts wrapper `details` in a comment at the top of the `source` body. + * + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. + */ + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); + } + + /** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has a lazy counterpart. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. + */ + function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** + * Checks if `func` is capable of being masked. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + */ + var isMaskable = coreJsData ? isFunction : stubFalse; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + /** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + + var isCombo = + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + + /** + * Gets the parent value at `path` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. + */ + function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); + } + + /** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = copyArray(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; + } + + /** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var setData = shortOut(baseSetData); + + /** + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @returns {number|Object} Returns the timer id or timeout object. + */ + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. + * + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. + */ + function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + } + + /** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + /** + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. + */ + function shuffleSelf(array, size) { + var index = -1, + length = array.length, + lastIndex = length - 1; + + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; + } + array.length = size; + return array; + } + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Updates wrapper `details` based on `bitmask` flags. + * + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); + } + + /** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; + } + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } + + /** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ + var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; + }); + + /** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; + } + + /** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true) + : []; + } + + /** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */ + function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ + function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, getIteratee(predicate, 3), index); + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ + function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } + + /** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; + } + + /** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; + } + + /** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */ + function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); + } + + /** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ + function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; + } + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ + function head(array) { + return (array && array.length) ? array[0] : undefined; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ + function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); + } + + /** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ + function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; + } + + /** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; + }); + + /** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ + function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); + } + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; + } + + /** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); + } + + /** + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. + * + * @static + * @memberOf _ + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * + * _.nth(array, 1); + * // => 'b' + * + * _.nth(array, -2); + * // => 'c'; + */ + function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; + } + + /** + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] + */ + var pull = baseRest(pullAll); + + /** + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] + */ + function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ + function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, getIteratee(iteratee, 2)) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + */ + function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; + } + + /** + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); + * + * console.log(array); + * // => ['a', 'c'] + * + * console.log(pulled); + * // => ['b', 'd'] + */ + var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, + result = baseAt(array, indexes); + + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + + return result; + }); + + /** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). + * + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; + } + + /** + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function reverse(array) { + return array == null ? array : nativeReverse.call(array); + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); + } + + /** + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + */ + function sortedIndex(array, value) { + return baseSortedIndex(array, value); + } + + /** + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 + */ + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + } + + /** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 + */ + function sortedIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 + */ + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); + } + + /** + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 + * + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 + */ + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + } + + /** + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 + */ + function sortedLastIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] + */ + function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; + } + + /** + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] + */ + function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, getIteratee(iteratee, 2)) + : []; + } + + /** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.tail([1, 2, 3]); + * // => [2, 3] + */ + function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; + } + + /** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ + function take(array, n, guard) { + if (!(array && array.length)) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ + function takeRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] + */ + function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), false, true) + : []; + } + + /** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] + */ + function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3)) + : []; + } + + /** + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([2], [1, 2]); + * // => [2, 1] + */ + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + + /** + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); + }); + + /** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ + function uniq(array) { + return (array && array.length) ? baseUniq(array) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniqBy(array, iteratee) { + return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + */ + function uniqWith(array, comparator) { + comparator = typeof comparator == 'function' ? comparator : undefined; + return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + } + + /** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + * + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] + */ + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); + } + + /** + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */ + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); + } + + /** + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.pull`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor + * @example + * + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] + */ + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, values) + : []; + }); + + /** + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without + * @example + * + * _.xor([2, 1], [2, 3]); + * // => [1, 3] + */ + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); + + /** + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] + * + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); + + /** + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + */ + var zip = baseRest(unzip); + + /** + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. + * + * @static + * @memberOf _ + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } + */ + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); + } + + /** + * This method is like `_.zipObject` except that it supports property paths. + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + */ + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); + } + + /** + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine + * grouped values. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] + */ + var zipWith = baseRest(function(arrays) { + var length = arrays.length, + iteratee = length > 1 ? arrays[length - 1] : undefined; + + iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor) { + interceptor(value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + + /** + * This method is the wrapper version of `_.at`. + * + * @name at + * @memberOf _ + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] + */ + var wrapperAt = flatRest(function(paths) { + var length = paths.length, + start = length ? paths[0] : 0, + value = this.__wrapped__, + interceptor = function(object) { return baseAt(object, paths); }; + + if (length > 1 || this.__actions__.length || + !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); + } + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + 'func': thru, + 'args': [interceptor], + 'thisArg': undefined + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined); + } + return array; + }); + }); + + /** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chain sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + + /** + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). + * + * @name next + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped.next(); + * // => { 'done': false, 'value': 1 } + * + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } + */ + function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); + } + var done = this.__index__ >= this.__values__.length, + value = done ? undefined : this.__values__[this.__index__++]; + + return { 'done': done, 'value': value }; + } + + /** + * Enables the wrapper to be iterable. + * + * @name Symbol.iterator + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the wrapper object. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped[Symbol.iterator]() === wrapped; + * // => true + * + * Array.from(wrapped); + * // => [1, 2] + */ + function wrapperToIterator() { + return this; + } + + /** + * Creates a clone of the chain sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); + * + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */ + function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; + } + + /** + * This method is the wrapper version of `_.reverse`. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + 'func': thru, + 'args': [reverse], + 'thisArg': undefined + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } + + /** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } + }); + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + */ + function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ + var find = createFind(findIndex); + + /** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ + var findLast = createFind(findLastIndex); + + /** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ + function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); + } + + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forEach(collection, iteratee) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */ + function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } + }); + + /** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ + function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + } + + /** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); + }); + return result; + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */ + var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); + }); + + /** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. If `orders` is unspecified, all values + * are sorted in ascending order. Otherwise, specify an order of "desc" for + * descending or "asc" for ascending sort order of corresponding values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] + * The iteratees to sort by. + * @param {string[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // Sort by `user` in ascending order and by `age` in descending order. + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + */ + function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + orders = guard ? undefined : orders; + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseOrderBy(collection, iteratees, orders); + } + + /** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */ + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { return [[], []]; }); + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ + function reduce(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduce : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + } + + /** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduce + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduceRight : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + } + + /** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.filter + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * _.reject(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.reject(users, { 'age': 40, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.reject(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.reject(users, 'active'); + * // => objects for ['barney'] + */ + function reject(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, negate(getIteratee(predicate, 3))); + } + + /** + * Gets a random element from `collection`. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + */ + function sample(collection) { + var func = isArray(collection) ? arraySample : baseSample; + return func(collection); + } + + /** + * Gets `n` random elements at unique keys from `collection` up to the + * size of `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @param {number} [n=1] The number of elements to sample. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the random elements. + * @example + * + * _.sampleSize([1, 2, 3], 2); + * // => [3, 1] + * + * _.sampleSize([1, 2, 3], 4); + * // => [2, 3, 1] + */ + function sampleSize(collection, n, guard) { + if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + var func = isArray(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n); + } + + /** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ + function shuffle(collection) { + var func = isArray(collection) ? arrayShuffle : baseShuffle; + return func(collection); + } + + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + if (collection == null) { + return 0; + } + if (isArrayLike(collection)) { + return isString(collection) ? stringSize(collection) : collection.length; + } + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(collection).length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, guard) { + var func = isArray(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] + */ + var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ + var now = ctxNow || function() { + return root.Date.now(); + }; + + /*------------------------------------------------------------------------*/ + + /** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. + */ + function after(n, func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ + function ary(func, n, guard) { + n = guard ? undefined : n; + n = (func && n == null) ? func.length : n; + return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); + } + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = baseRest(function(func, thisArg, partials) { + var bitmask = WRAP_BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(func, bitmask, thisArg, partials, holders); + }); + + /** + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ + var bindKey = baseRest(function(object, key, partials) { + var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); + }); + + /** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ + function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; + } + + /** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ + function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; + } + + /** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ + function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + timeWaiting = wait - timeSinceLastCall; + + return maxing + ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) + : timeWaiting; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; + } + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + + /** + * Creates a function that invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ + function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ + function once(func) { + return before(2, func); + } + + /** + * Creates a function that invokes `func` with its arguments transformed. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms=[_.identity]] + * The argument transforms. + * @returns {Function} Returns the new function. + * @example + * + * function doubled(n) { + * return n * 2; + * } + * + * function square(n) { + * return n * n; + * } + * + * var func = _.overArgs(function(x, y) { + * return [x, y]; + * }, [square, doubled]); + * + * func(9, 3); + * // => [81, 6] + * + * func(10, 5); + * // => [100, 10] + */ + var overArgs = castRest(function(func, transforms) { + transforms = (transforms.length == 1 && isArray(transforms[0])) + ? arrayMap(transforms[0], baseUnary(getIteratee())) + : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, + length = nativeMin(args.length, funcsLength); + + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply(func, this, args); + }); + }); + + /** + * Creates a function that invokes `func` with `partials` prepended to the + * arguments it receives. This method is like `_.bind` except it does **not** + * alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 0.2.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // Partially applied with placeholders. + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ + var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); + }); + + /** + * This method is like `_.partial` except that partially applied arguments + * are appended to the arguments it receives. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // Partially applied with placeholders. + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ + var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); + }); + + /** + * Creates a function that invokes `func` with arguments arranged according + * to the specified `indexes` where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, [2, 0, 1]); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + */ + var rearg = flatRest(function(func, indexes) { + return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); + }); + + /** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ + function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); + } + + /** + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ + function spread(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start == null ? 0 : nativeMax(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], + otherArgs = castSlice(args, 0, start); + + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); + } + + /** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed `func` invocations and a `flush` method to + * immediately invoke them. Provide `options` to indicate whether `func` + * should be invoked on the leading and/or trailing edge of the `wait` + * timeout. The `func` is invoked with the last arguments provided to the + * throttled function. Subsequent calls to the throttled function return the + * result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the throttled function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); + * + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + 'leading': leading, + 'maxWait': wait, + 'trailing': trailing + }); + } + + /** + * Creates a function that accepts up to one argument, ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.unary(parseInt)); + * // => [6, 8, 10] + */ + function unary(func) { + return ary(func, 1); + } + + /** + * Creates a function that provides `value` to `wrapper` as its first + * argument. Any additional arguments provided to the function are appended + * to those provided to the `wrapper`. The wrapper is invoked with the `this` + * binding of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {*} value The value to wrap. + * @param {Function} [wrapper=identity] The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */ + function wrap(value, wrapper) { + return partial(castFunction(wrapper), value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Casts `value` as an array if it's not one. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. + * @example + * + * _.castArray(1); + * // => [1] + * + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] + * + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */ + function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray(value) ? value : [value]; + } + + /** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ + function clone(value) { + return baseClone(value, CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * } + * + * var el = _.cloneWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 + */ + function cloneWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ + function cloneDeep(value) { + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.cloneWith` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */ + function cloneDeepWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true + * + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false + */ + function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ + var gt = createRelationalOperation(baseGt); + + /** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ + var gte = createRelationalOperation(function(value, other) { + return value >= other; + }); + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */ + var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag); + } + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + + /** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ + function isElement(value) { + return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); + } + + /** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ + function isEqualWith(value, other, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; + } + + /** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ + function isError(value) { + if (!isObjectLike(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == errorTag || tag == domExcTag || + (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ + function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ + function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ + var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + + /** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */ + function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); + } + + /** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ + function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ + function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(value); + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ + function isNil(value) { + return value == null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); + } + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; + } + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + + /** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ + function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ + var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); + } + + /** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + + /** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */ + function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; + } + + /** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */ + function isWeakSet(value) { + return isObjectLike(value) && baseGetTag(value) == weakSetTag; + } + + /** + * Checks if `value` is less than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + * @see _.gt + * @example + * + * _.lt(1, 3); + * // => true + * + * _.lt(3, 3); + * // => false + * + * _.lt(3, 1); + * // => false + */ + var lt = createRelationalOperation(baseLt); + + /** + * Checks if `value` is less than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to + * `other`, else `false`. + * @see _.gte + * @example + * + * _.lte(1, 3); + * // => true + * + * _.lte(3, 3); + * // => true + * + * _.lte(3, 1); + * // => false + */ + var lte = createRelationalOperation(function(value, other) { + return value <= other; + }); + + /** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */ + function toArray(value) { + if (!value) { + return []; + } + if (isArrayLike(value)) { + return isString(value) ? stringToArray(value) : copyArray(value); + } + if (symIterator && value[symIterator]) { + return iteratorToArray(value[symIterator]()); + } + var tag = getTag(value), + func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); + + return func(value); + } + + /** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; + } + + /** + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toLength(3.2); + * // => 3 + * + * _.toLength(Number.MIN_VALUE); + * // => 0 + * + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3.2'); + * // => 3 + */ + function toLength(value) { + return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + } + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + + /** + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toSafeInteger(3.2); + * // => 3 + * + * _.toSafeInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toSafeInteger(Infinity); + * // => 9007199254740991 + * + * _.toSafeInteger('3.2'); + * // => 3 + */ + function toSafeInteger(value) { + return value + ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) + : (value === 0 ? value : 0); + } + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + return value == null ? '' : baseToString(value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ + var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } + }); + + /** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ + var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); + }); + + /** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); + + /** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); + }); + + /** + * Creates an array of values corresponding to `paths` of `object`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Array} Returns the picked values. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] + */ + var at = flatRest(baseAt); + + /** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties == null ? result : baseAssign(result, properties); + } + + /** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var defaults = baseRest(function(object, sources) { + object = Object(object); + + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; + } + + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; + + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; + + if (value === undefined || + (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { + object[key] = source[key]; + } + } + } + + return object; + }); + + /** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ + var defaultsDeep = baseRest(function(args) { + args.push(undefined, customDefaultsMerge); + return apply(mergeWith, undefined, args); + }); + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + } + + /** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ + function findLastKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + } + + /** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */ + function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */ + function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forOwn(object, iteratee) { + return object && baseForOwn(object, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */ + function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + } + + /** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ + function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); + } + + /** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ + function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ + function has(object, path) { + return object != null && hasPath(object, path, baseHas); + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */ + var invert = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + result[value] = key; + }, constant(identity)); + + /** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */ + var invertBy = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + }, getIteratee); + + /** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */ + var invoke = baseRest(baseInvoke); + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + function mapKeys(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + + /** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + + /** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + + /** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */ + var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); + }); + + /** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable property paths of `object` that are not omitted. + * + * **Note:** This method is considerably slower than `_.pick`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to omit. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } + */ + var omit = flatRest(function(object, paths) { + var result = {}; + if (object == null) { + return result; + } + var isDeep = false; + paths = arrayMap(paths, function(path) { + path = castPath(path, object); + isDeep || (isDeep = path.length > 1); + return path; + }); + copyObject(object, getAllKeysIn(object), result); + if (isDeep) { + result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); + } + var length = paths.length; + while (length--) { + baseUnset(result, paths[length]); + } + return result; + }); + + /** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + function omitBy(object, predicate) { + return pickBy(object, negate(getIteratee(predicate))); + } + + /** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + var pick = flatRest(function(object, paths) { + return object == null ? {} : basePick(object, paths); + }); + + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = getIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); + } + + /** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + path = castPath(path, object); + + var index = -1, + length = path.length; + + // Ensure the loop is entered when path is empty. + if (!length) { + length = 1; + object = undefined; + } + while (++index < length) { + var value = object == null ? undefined : object[toKey(path[index])]; + if (value === undefined) { + index = length; + value = defaultValue; + } + object = isFunction(value) ? value.call(object) : value; + } + return object; + } + + /** + * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, + * it's created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use `_.setWith` to customize + * `path` creation. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); + } + + /** + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } + */ + function setWith(object, path, value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseSet(object, path, value, customizer); + } + + /** + * Creates an array of own enumerable string keyed-value pairs for `object` + * which can be consumed by `_.fromPairs`. If `object` is a map or set, its + * entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entries + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + */ + var toPairs = createToPairs(keys); + + /** + * Creates an array of own and inherited enumerable string keyed-value pairs + * for `object` which can be consumed by `_.fromPairs`. If `object` is a map + * or set, its entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entriesIn + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairsIn(new Foo); + * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + */ + var toPairsIn = createToPairs(keysIn); + + /** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable string keyed properties thru `iteratee`, with each invocation + * potentially mutating the `accumulator` object. If `accumulator` is not + * provided, a new object with the same `[[Prototype]]` will be used. The + * iteratee is invoked with four arguments: (accumulator, value, key, object). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @returns {*} Returns the accumulated value. + * @example + * + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }, []); + * // => [4, 9] + * + * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } + */ + function transform(object, iteratee, accumulator) { + var isArr = isArray(object), + isArrLike = isArr || isBuffer(object) || isTypedArray(object); + + iteratee = getIteratee(iteratee, 4); + if (accumulator == null) { + var Ctor = object && object.constructor; + if (isArrLike) { + accumulator = isArr ? new Ctor : []; + } + else if (isObject(object)) { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; + } + else { + accumulator = {}; + } + } + (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + + /** + * Removes the property at `path` of `object`. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 7 } }] }; + * _.unset(object, 'a[0].b.c'); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + * + * _.unset(object, ['a', '0', 'b', 'c']); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + */ + function unset(object, path) { + return object == null ? true : baseUnset(object, path); + } + + /** + * This method is like `_.set` except that accepts `updater` to produce the + * value to set. Use `_.updateWith` to customize `path` creation. The `updater` + * is invoked with one argument: (value). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.update(object, 'a[0].b.c', function(n) { return n * n; }); + * console.log(object.a[0].b.c); + * // => 9 + * + * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); + * console.log(object.x[0].y.z); + * // => 0 + */ + function update(object, path, updater) { + return object == null ? object : baseUpdate(object, path, castFunction(updater)); + } + + /** + * This method is like `_.update` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.updateWith(object, '[0][1]', _.constant('a'), Object); + * // => { '0': { '1': 'a' } } + */ + function updateWith(object, path, updater, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + } + + /** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return object == null ? [] : baseValues(object, keys(object)); + } + + /** + * Creates an array of the own and inherited enumerable string keyed property + * values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */ + function valuesIn(object) { + return object == null ? [] : baseValues(object, keysIn(object)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Clamps `number` within the inclusive `lower` and `upper` bounds. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + * @example + * + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 + */ + function clamp(number, lower, upper) { + if (upper === undefined) { + upper = lower; + lower = undefined; + } + if (upper !== undefined) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); + } + + /** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */ + function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); + } + + /** + * Produces a random number between the inclusive `lower` and `upper` bounds. + * If only one argument is provided a number between `0` and the given number + * is returned. If `floating` is `true`, or either `lower` or `upper` are + * floats, a floating-point number is returned instead of an integer. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Number + * @param {number} [lower=0] The lower bound. + * @param {number} [upper=1] The upper bound. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(lower, upper, floating) { + if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined; + } + if (floating === undefined) { + if (typeof upper == 'boolean') { + floating = upper; + upper = undefined; + } + else if (typeof lower == 'boolean') { + floating = lower; + lower = undefined; + } + } + if (lower === undefined && upper === undefined) { + lower = 0; + upper = 1; + } + else { + lower = toFinite(lower); + if (upper === undefined) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); + } + return baseRandom(lower, upper); + } + + /*------------------------------------------------------------------------*/ + + /** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); + }); + + /** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } + + /** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); + } + + /** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ + function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); + + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; + } + + /** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ + function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; + } + + /** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); + }); + + /** + * Converts `string`, as space separated words, to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. + * @example + * + * _.lowerCase('--Foo-Bar--'); + * // => 'foo bar' + * + * _.lowerCase('fooBar'); + * // => 'foo bar' + * + * _.lowerCase('__FOO_BAR__'); + * // => 'foo bar' + */ + var lowerCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + word.toLowerCase(); + }); + + /** + * Converts the first character of `string` to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.lowerFirst('Fred'); + * // => 'fred' + * + * _.lowerFirst('FRED'); + * // => 'fRED' + */ + var lowerFirst = createCaseFirst('toLowerCase'); + + /** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ + function pad(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; + } + var mid = (length - strLength) / 2; + return ( + createPadding(nativeFloor(mid), chars) + + string + + createPadding(nativeCeil(mid), chars) + ); + } + + /** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padEnd('abc', 6); + * // => 'abc ' + * + * _.padEnd('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padEnd('abc', 3); + * // => 'abc' + */ + function padEnd(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (string + createPadding(length - strLength, chars)) + : string; + } + + /** + * Pads `string` on the left side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padStart('abc', 6); + * // => ' abc' + * + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */ + function padStart(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (createPadding(length - strLength, chars) + string) + : string; + } + + /** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a + * hexadecimal, in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the + * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category String + * @param {string} string The string to convert. + * @param {number} [radix=10] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ + function parseInt(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); + } + + /** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ + function repeat(string, n, guard) { + if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + return baseRepeat(toString(string), n); + } + + /** + * Replaces matches for `pattern` in `string` with `replacement`. + * + * **Note:** This method is based on + * [`String#replace`](https://mdn.io/String/replace). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to modify. + * @param {RegExp|string} pattern The pattern to replace. + * @param {Function|string} replacement The match replacement. + * @returns {string} Returns the modified string. + * @example + * + * _.replace('Hi Fred', 'Fred', 'Barney'); + * // => 'Hi Barney' + */ + function replace() { + var args = arguments, + string = toString(args[0]); + + return args.length < 3 ? string : string.replace(args[1], args[2]); + } + + /** + * Converts `string` to + * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--FOO-BAR--'); + * // => 'foo_bar' + */ + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); + }); + + /** + * Splits `string` by `separator`. + * + * **Note:** This method is based on + * [`String#split`](https://mdn.io/String/split). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to split. + * @param {RegExp|string} separator The separator pattern to split by. + * @param {number} [limit] The length to truncate results to. + * @returns {Array} Returns the string segments. + * @example + * + * _.split('a-b-c', '-', 2); + * // => ['a', 'b'] + */ + function split(string, separator, limit) { + if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { + separator = limit = undefined; + } + limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && ( + typeof separator == 'string' || + (separator != null && !isRegExp(separator)) + )) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); + } + } + return string.split(separator, limit); + } + + /** + * Converts `string` to + * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @since 3.1.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar--'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__FOO_BAR__'); + * // => 'FOO BAR' + */ + var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + upperFirst(word); + }); + + /** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ + function startsWith(string, target, position) { + string = toString(string); + position = position == null + ? 0 + : baseClamp(toInteger(position), 0, string.length); + + target = baseToString(target); + return string.slice(position, position + target.length) == target; + } + + /** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is given, it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options={}] The options object. + * @param {RegExp} [options.escape=_.templateSettings.escape] + * The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] + * The "evaluate" delimiter. + * @param {Object} [options.imports=_.templateSettings.imports] + * An object to import into the template as free variables. + * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] + * The "interpolate" delimiter. + * @param {string} [options.sourceURL='lodash.templateSources[n]'] + * The sourceURL of the compiled template. + * @param {string} [options.variable='obj'] + * The data object variable name. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the compiled template function. + * @example + * + * // Use the "interpolate" delimiter to create a compiled template. + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // Use the HTML "escape" delimiter to escape data property values. + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': ' - @@ -24,25 +18,19 @@ Loading... - + - - - + diff --git a/src/dev-app/input-modality/BUILD.bazel b/src/dev-app/input-modality/BUILD.bazel new file mode 100644 index 000000000000..4c21642634ce --- /dev/null +++ b/src/dev-app/input-modality/BUILD.bazel @@ -0,0 +1,18 @@ +load("//tools:defaults.bzl", "ng_module") + +package(default_visibility = ["//visibility:public"]) + +ng_module( + name = "input-modality", + srcs = glob(["**/*.ts"]), + assets = ["input-modality-detector-demo.html"], + deps = [ + "//src/cdk/a11y", + "//src/material/button", + "//src/material/form-field", + "//src/material/input", + "//src/material/radio", + "//src/material/select", + "@npm//@angular/router", + ], +) diff --git a/src/dev-app/input-modality/input-modality-detector-demo-module.ts b/src/dev-app/input-modality/input-modality-detector-demo-module.ts new file mode 100644 index 000000000000..6923aeaf41b0 --- /dev/null +++ b/src/dev-app/input-modality/input-modality-detector-demo-module.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {A11yModule} from '@angular/cdk/a11y'; +import {CommonModule} from '@angular/common'; +import {NgModule} from '@angular/core'; +import {MatButtonModule} from '@angular/material/button'; +import {MatFormFieldModule} from '@angular/material/form-field'; +import {MatInputModule} from '@angular/material/input'; +import {MatRadioModule} from '@angular/material/radio'; +import {MatSelectModule} from '@angular/material/select'; +import {RouterModule} from '@angular/router'; +import {InputModalityDetectorDemo} from './input-modality-detector-demo'; + +@NgModule({ + imports: [ + A11yModule, + CommonModule, + MatButtonModule, + MatFormFieldModule, + MatInputModule, + MatRadioModule, + MatSelectModule, + RouterModule.forChild([{path: '', component: InputModalityDetectorDemo}]), + ], + declarations: [InputModalityDetectorDemo], +}) +export class InputModalityDetectorDemoModule {} diff --git a/src/dev-app/input-modality/input-modality-detector-demo.html b/src/dev-app/input-modality/input-modality-detector-demo.html new file mode 100644 index 000000000000..6191e3a0be80 --- /dev/null +++ b/src/dev-app/input-modality/input-modality-detector-demo.html @@ -0,0 +1,40 @@ +
+

Input Modality

+ +
+

+ Interact with the controls below with keyboard, mouse, or touch to see the detected + input modality change. +

+ +

+ Detected input modality: + {{_modality || '(unknown)'}} +

+ + +

+ + + Name + + +

+ + + Food + + Apple + Banana + Carrot + + +

+ + + Red + Orange + Yellow + +
+
diff --git a/src/dev-app/input-modality/input-modality-detector-demo.ts b/src/dev-app/input-modality/input-modality-detector-demo.ts new file mode 100644 index 000000000000..d537250705c0 --- /dev/null +++ b/src/dev-app/input-modality/input-modality-detector-demo.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {Component, OnDestroy, NgZone} from '@angular/core'; +import {InputModality, InputModalityDetector} from '@angular/cdk/a11y'; + +import {Subject} from 'rxjs'; +import {takeUntil} from 'rxjs/operators'; + +@Component({ + selector: 'input-modality-detector-demo', + templateUrl: 'input-modality-detector-demo.html', +}) +export class InputModalityDetectorDemo implements OnDestroy { + _modality: InputModality = null; + _destroyed = new Subject(); + + constructor(inputModalityDetector: InputModalityDetector, ngZone: NgZone) { + inputModalityDetector.modalityChanged.pipe(takeUntil(this._destroyed)).subscribe(modality => + ngZone.run(() => { + this._modality = modality; + }), + ); + } + + ngOnDestroy() { + this._destroyed.next(); + this._destroyed.complete(); + } +} diff --git a/src/dev-app/input/input-demo-module.ts b/src/dev-app/input/input-demo-module.ts index 7e48dfdcc00c..3e6e2a65db0c 100644 --- a/src/dev-app/input/input-demo-module.ts +++ b/src/dev-app/input/input-demo-module.ts @@ -41,5 +41,4 @@ import {InputDemo} from './input-demo'; ], declarations: [InputDemo], }) -export class InputDemoModule { -} +export class InputDemoModule {} diff --git a/src/dev-app/input/input-demo.scss b/src/dev-app/input/input-demo.scss index 00f861b2f63f..85c883671d24 100644 --- a/src/dev-app/input/input-demo.scss +++ b/src/dev-app/input/input-demo.scss @@ -1,4 +1,4 @@ -@import '../../cdk/text-field/text-field'; +@use '../../cdk/text-field'; .demo-basic { padding: 0; @@ -33,7 +33,7 @@ } .demo-custom-autofill-style { - @include cdk-text-field-autofill-color(transparent, red); + @include text-field.text-field-autofill-color(transparent, red); } .demo-rows { diff --git a/src/dev-app/input/input-demo.ts b/src/dev-app/input/input-demo.ts index e060e06c03bc..98b05f6c9de3 100644 --- a/src/dev-app/input/input-demo.ts +++ b/src/dev-app/input/input-demo.ts @@ -11,7 +11,6 @@ import {FormControl, Validators} from '@angular/forms'; import {ErrorStateMatcher} from '@angular/material/core'; import {FloatLabelType} from '@angular/material/form-field'; - let max = 5; const EMAIL_REGEX = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/; @@ -40,13 +39,7 @@ export class InputDemo { dividerColorExample1: string; dividerColorExample2: string; dividerColorExample3: string; - items: {value: number}[] = [ - {value: 10}, - {value: 20}, - {value: 30}, - {value: 40}, - {value: 50}, - ]; + items: {value: number}[] = [{value: 10}, {value: 20}, {value: 30}, {value: 40}, {value: 50}]; rows = 8; formControl = new FormControl('hello', Validators.required); emailFormControl = new FormControl('', [Validators.required, Validators.pattern(EMAIL_REGEX)]); @@ -66,7 +59,7 @@ export class InputDemo { addABunch(n: number) { for (let x = 0; x < n; x++) { - this.items.push({ value: ++max }); + this.items.push({value: ++max}); } } @@ -80,7 +73,7 @@ export class InputDemo { } return false; - } + }, }; togglePlaceholderTestValue() { @@ -88,9 +81,9 @@ export class InputDemo { } togglePlaceholderTestTouched() { - this.placeholderTestControl.touched ? - this.placeholderTestControl.markAsUntouched() : - this.placeholderTestControl.markAsTouched(); + this.placeholderTestControl.touched + ? this.placeholderTestControl.markAsUntouched() + : this.placeholderTestControl.markAsTouched(); } parseNumber(value: string): number { diff --git a/src/dev-app/layout/BUILD.bazel b/src/dev-app/layout/BUILD.bazel new file mode 100644 index 000000000000..13ccdb19326b --- /dev/null +++ b/src/dev-app/layout/BUILD.bazel @@ -0,0 +1,22 @@ +load("//tools:defaults.bzl", "ng_module", "sass_binary") + +package(default_visibility = ["//visibility:public"]) + +ng_module( + name = "layout", + srcs = glob(["**/*.ts"]), + assets = [ + "layout-demo.html", + ":layout_demo_scss", + ], + deps = [ + "//src/cdk/layout", + "//src/components-examples/cdk/layout", + "@npm//@angular/router", + ], +) + +sass_binary( + name = "layout_demo_scss", + src = "layout-demo.scss", +) diff --git a/src/dev-app/layout/layout-demo-module.ts b/src/dev-app/layout/layout-demo-module.ts new file mode 100644 index 000000000000..835c10137bf0 --- /dev/null +++ b/src/dev-app/layout/layout-demo-module.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {CommonModule} from '@angular/common'; +import {NgModule} from '@angular/core'; +import {RouterModule} from '@angular/router'; +import {LayoutDemo} from './layout-demo'; +import {CdkLayoutExamplesModule} from '@angular/components-examples/cdk/layout'; + +@NgModule({ + imports: [ + CommonModule, + CdkLayoutExamplesModule, + RouterModule.forChild([{path: '', component: LayoutDemo}]), + ], + declarations: [LayoutDemo], +}) +export class LayoutDemoModule {} diff --git a/src/dev-app/layout/layout-demo.html b/src/dev-app/layout/layout-demo.html new file mode 100644 index 000000000000..705ee66e45bf --- /dev/null +++ b/src/dev-app/layout/layout-demo.html @@ -0,0 +1,2 @@ +

Respond to viewport changes with BreakpointObserver

+ diff --git a/src/dev-app/layout/layout-demo.scss b/src/dev-app/layout/layout-demo.scss new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/src/dev-app/layout/layout-demo.ts b/src/dev-app/layout/layout-demo.ts new file mode 100644 index 000000000000..4b41a7badc0c --- /dev/null +++ b/src/dev-app/layout/layout-demo.ts @@ -0,0 +1,16 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {Component} from '@angular/core'; + +@Component({ + selector: 'layout-demo', + templateUrl: 'layout-demo.html', + styleUrls: ['layout-demo.css'], +}) +export class LayoutDemo {} diff --git a/src/dev-app/list/list-demo-module.ts b/src/dev-app/list/list-demo-module.ts index 4d823b6f7f58..0ac8c7b10f0b 100644 --- a/src/dev-app/list/list-demo-module.ts +++ b/src/dev-app/list/list-demo-module.ts @@ -28,5 +28,4 @@ import {ListDemo} from './list-demo'; ], declarations: [ListDemo], }) -export class ListDemoModule { -} +export class ListDemoModule {} diff --git a/src/dev-app/list/list-demo.ts b/src/dev-app/list/list-demo.ts index 42a691b852ed..39ed9460eb22 100644 --- a/src/dev-app/list/list-demo.ts +++ b/src/dev-app/list/list-demo.ts @@ -9,55 +9,44 @@ import {Component} from '@angular/core'; import {MatListOptionCheckboxPosition} from '@angular/material/list'; - @Component({ selector: 'list-demo', templateUrl: 'list-demo.html', styleUrls: ['list-demo.css'], }) export class ListDemo { - items: string[] = [ - 'Pepper', - 'Salt', - 'Paprika' - ]; + items: string[] = ['Pepper', 'Salt', 'Paprika']; - contacts: {name: string, headline: string}[] = [ + contacts: {name: string; headline: string}[] = [ {name: 'Nancy', headline: 'Software engineer'}, {name: 'Mary', headline: 'TPM'}, - {name: 'Bobby', headline: 'UX designer'} + {name: 'Bobby', headline: 'UX designer'}, ]; checkboxPosition: MatListOptionCheckboxPosition = 'before'; - messages: {from: string, subject: string, message: string, image: string}[] = [ + messages: {from: string; subject: string; message: string; image: string}[] = [ { from: 'Nancy', subject: 'Brunch?', message: 'Did you want to go on Sunday? I was thinking that might work.', - image: 'https://angular.io/generated/images/bios/julie-ralph.jpg' + image: 'https://angular.io/generated/images/bios/cindygreenekaplan.jpg', }, { from: 'Mary', subject: 'Summer BBQ', message: 'Wish I could come, but I have some prior obligations.', - image: 'https://angular.io/generated/images/bios/juleskremer.jpg' + image: 'https://angular.io/generated/images/bios/twerske.jpg', }, { from: 'Bobby', subject: 'Oui oui', message: 'Do you have Paris reservations for the 15th? I just booked!', - image: 'https://angular.io/generated/images/bios/jelbourn.jpg' - } + image: 'https://angular.io/generated/images/bios/jelbourn.jpg', + }, ]; - links: {name: string}[] = [ - {name: 'Inbox'}, - {name: 'Outbox'}, - {name: 'Spam'}, - {name: 'Trash'} - - ]; + links: {name: string}[] = [{name: 'Inbox'}, {name: 'Outbox'}, {name: 'Spam'}, {name: 'Trash'}]; thirdLine = false; infoClicked = false; diff --git a/src/dev-app/live-announcer/live-announcer-demo-module.ts b/src/dev-app/live-announcer/live-announcer-demo-module.ts index 6782bc841789..1d47fa29f06f 100644 --- a/src/dev-app/live-announcer/live-announcer-demo-module.ts +++ b/src/dev-app/live-announcer/live-announcer-demo-module.ts @@ -20,5 +20,4 @@ import {LiveAnnouncerDemo} from './live-announcer-demo'; ], declarations: [LiveAnnouncerDemo], }) -export class LiveAnnouncerDemoModule { -} +export class LiveAnnouncerDemoModule {} diff --git a/src/dev-app/live-announcer/live-announcer-demo.ts b/src/dev-app/live-announcer/live-announcer-demo.ts index d4d5114a9ccc..8c1bcdd63994 100644 --- a/src/dev-app/live-announcer/live-announcer-demo.ts +++ b/src/dev-app/live-announcer/live-announcer-demo.ts @@ -9,7 +9,6 @@ import {Component} from '@angular/core'; import {LiveAnnouncer} from '@angular/cdk/a11y'; - @Component({ selector: 'toolbar-demo', templateUrl: 'live-announcer-demo.html', diff --git a/src/dev-app/main-module.ts b/src/dev-app/main-module.ts index 09b4c604a470..8e2b6c951cb0 100644 --- a/src/dev-app/main-module.ts +++ b/src/dev-app/main-module.ts @@ -17,20 +17,21 @@ import {RouterModule} from '@angular/router'; import {DevAppComponent} from './dev-app'; import {DevAppDirectionality} from './dev-app/dev-app-directionality'; import {DevAppModule} from './dev-app/dev-app-module'; -import {DEV_APP_ROUTES} from './dev-app/routes'; +import {DEV_APP_ROUTES} from './routes'; import {DevAppRippleOptions} from './dev-app/ripple-options'; +import {ANIMATIONS_STORAGE_KEY} from './dev-app/dev-app-layout'; @NgModule({ imports: [ - BrowserAnimationsModule, + BrowserAnimationsModule.withConfig({ + disableAnimations: localStorage.getItem(ANIMATIONS_STORAGE_KEY) === 'true', + }), BrowserModule, DevAppModule, HttpClientModule, RouterModule.forRoot(DEV_APP_ROUTES), ], - declarations: [ - DevAppComponent, - ], + declarations: [DevAppComponent], providers: [ {provide: OverlayContainer, useClass: FullscreenOverlayContainer}, {provide: MAT_RIPPLE_GLOBAL_OPTIONS, useExisting: DevAppRippleOptions}, @@ -38,5 +39,4 @@ import {DevAppRippleOptions} from './dev-app/ripple-options'; ], bootstrap: [DevAppComponent], }) -export class MainModule { -} +export class MainModule {} diff --git a/src/dev-app/main.ts b/src/dev-app/main.ts index da66a2ca0067..79d96916f253 100644 --- a/src/dev-app/main.ts +++ b/src/dev-app/main.ts @@ -6,11 +6,10 @@ * found in the LICENSE file at https://angular.io/license */ -/** - * This is the main entry-point for the AOT compilation. File will be used to test AOT support. - */ +// Load `$localize` for examples using it. +import '@angular/localize/init'; import {platformBrowser} from '@angular/platform-browser'; -import {MainModuleNgFactory} from './main-module.ngfactory'; +import {MainModule} from './main-module'; -platformBrowser().bootstrapModuleFactory(MainModuleNgFactory); +platformBrowser().bootstrapModule(MainModule); diff --git a/src/dev-app/mdc-autocomplete/mdc-autocomplete-demo-module.ts b/src/dev-app/mdc-autocomplete/mdc-autocomplete-demo-module.ts index a8a5bfb7a1a7..dc1b4d9d2dde 100644 --- a/src/dev-app/mdc-autocomplete/mdc-autocomplete-demo-module.ts +++ b/src/dev-app/mdc-autocomplete/mdc-autocomplete-demo-module.ts @@ -31,5 +31,4 @@ import {MdcAutocompleteDemo} from './mdc-autocomplete-demo'; ], declarations: [MdcAutocompleteDemo], }) -export class MdcAutocompleteDemoModule { -} +export class MdcAutocompleteDemoModule {} diff --git a/src/dev-app/mdc-autocomplete/mdc-autocomplete-demo.ts b/src/dev-app/mdc-autocomplete/mdc-autocomplete-demo.ts index eeac4b5e7b5f..cd1c51e5a80f 100644 --- a/src/dev-app/mdc-autocomplete/mdc-autocomplete-demo.ts +++ b/src/dev-app/mdc-autocomplete/mdc-autocomplete-demo.ts @@ -11,7 +11,6 @@ import {FormControl, NgModel} from '@angular/forms'; import {Observable} from 'rxjs'; import {map, startWith} from 'rxjs/operators'; - export interface State { code: string; name: string; @@ -25,7 +24,7 @@ export interface StateGroup { @Component({ selector: 'mdc-autocomplete-demo', templateUrl: 'mdc-autocomplete-demo.html', - styleUrls: ['mdc-autocomplete-demo.css'] + styleUrls: ['mdc-autocomplete-demo.css'], }) export class MdcAutocompleteDemo { stateCtrl: FormControl; @@ -98,26 +97,27 @@ export class MdcAutocompleteDemo { constructor() { this.tdStates = this.states; this.stateCtrl = new FormControl({code: 'CA', name: 'California'}); - this.reactiveStates = this.stateCtrl.valueChanges - .pipe( - startWith(this.stateCtrl.value), - map(val => this.displayFn(val)), - map(name => this.filterStates(name)) - ); - - this.filteredGroupedStates = this.groupedStates = - this.states.reduce((groups, state) => { - let group = groups.find(g => g.letter === state.name[0]); - - if (!group) { - group = { letter: state.name[0], states: [] }; - groups.push(group); - } - - group.states.push({ code: state.code, name: state.name }); - - return groups; - }, []); + this.reactiveStates = this.stateCtrl.valueChanges.pipe( + startWith(this.stateCtrl.value), + map(val => this.displayFn(val)), + map(name => this.filterStates(name)), + ); + + this.filteredGroupedStates = this.groupedStates = this.states.reduce( + (groups, state) => { + let group = groups.find(g => g.letter === state.name[0]); + + if (!group) { + group = {letter: state.name[0], states: []}; + groups.push(group); + } + + group.states.push({code: state.code, name: state.name}); + + return groups; + }, + [], + ); } displayFn(value: any): string { @@ -131,7 +131,7 @@ export class MdcAutocompleteDemo { filterStateGroups(val: string) { if (val) { return this.groupedStates - .map(group => ({ letter: group.letter, states: this._filter(group.states, val) })) + .map(group => ({letter: group.letter, states: this._filter(group.states, val)})) .filter(group => group.states.length > 0); } diff --git a/src/dev-app/mdc-button/mdc-button-demo-module.ts b/src/dev-app/mdc-button/mdc-button-demo-module.ts index 9de39be86134..de6fe13daecf 100644 --- a/src/dev-app/mdc-button/mdc-button-demo-module.ts +++ b/src/dev-app/mdc-button/mdc-button-demo-module.ts @@ -20,5 +20,4 @@ import {MdcButtonDemo} from './mdc-button-demo'; ], declarations: [MdcButtonDemo], }) -export class MdcButtonDemoModule { -} +export class MdcButtonDemoModule {} diff --git a/src/dev-app/mdc-button/mdc-button-demo.html b/src/dev-app/mdc-button/mdc-button-demo.html index b1d3f2377332..a1b9bd5797fe 100644 --- a/src/dev-app/mdc-button/mdc-button-demo.html +++ b/src/dev-app/mdc-button/mdc-button-demo.html @@ -11,6 +11,12 @@

Buttons

+ +
@@ -23,6 +29,12 @@

Buttons

+ +

Anchors

@@ -37,6 +49,12 @@

Anchors

check + Search + + check + Search + check +
SEARCH @@ -49,6 +67,12 @@

Anchors

check + Search + + check + Search + check +

Text Buttons [mat-button]

diff --git a/src/dev-app/mdc-card/mdc-card-demo-module.ts b/src/dev-app/mdc-card/mdc-card-demo-module.ts index 4df56fed7ea0..50c506af1237 100644 --- a/src/dev-app/mdc-card/mdc-card-demo-module.ts +++ b/src/dev-app/mdc-card/mdc-card-demo-module.ts @@ -24,5 +24,4 @@ import {MdcCardDemo} from './mdc-card-demo'; ], declarations: [MdcCardDemo], }) -export class MdcCardDemoModule { -} +export class MdcCardDemoModule {} diff --git a/src/dev-app/mdc-card/mdc-card-demo.html b/src/dev-app/mdc-card/mdc-card-demo.html index 2c3861dfbf8f..612c56a51175 100644 --- a/src/dev-app/mdc-card/mdc-card-demo.html +++ b/src/dev-app/mdc-card/mdc-card-demo.html @@ -1,18 +1,18 @@
- Use outlined cards + Use outlined cards - + Card with only text content - + Card with only <mat-card-content> and text content. - + Subtitle Card with title and footer @@ -25,7 +25,7 @@ - + Subtitle Card with title, footer, and inset-divider @@ -39,7 +39,7 @@ - + Content Title @@ -51,7 +51,7 @@ - + Header title @@ -63,7 +63,7 @@ - + Easily customizable @@ -74,7 +74,7 @@

Cards with media area

- + Card Small @@ -85,7 +85,7 @@

Cards with media area

- + Card Medium @@ -96,7 +96,7 @@

Cards with media area

- + Card Large @@ -107,7 +107,7 @@

Cards with media area

- + Card Extra large diff --git a/src/dev-app/mdc-card/mdc-card-demo.ts b/src/dev-app/mdc-card/mdc-card-demo.ts index ba63c3a7b5ae..dba474a55cd1 100644 --- a/src/dev-app/mdc-card/mdc-card-demo.ts +++ b/src/dev-app/mdc-card/mdc-card-demo.ts @@ -7,6 +7,7 @@ */ import {Component, ViewEncapsulation} from '@angular/core'; +import {MatCardAppearance} from '@angular/material-experimental/mdc-card'; @Component({ selector: 'mdc-card-demo', @@ -15,11 +16,14 @@ import {Component, ViewEncapsulation} from '@angular/core'; encapsulation: ViewEncapsulation.None, }) export class MdcCardDemo { - outlined = false; + appearance: MatCardAppearance = 'raised'; longText = `Once upon a midnight dreary, while I pondered, weak and weary, Over many a quaint and curious volume of forgotten lore— While I nodded, nearly napping, suddenly there came a tapping, As of some one gently rapping, rapping at my chamber door. “’Tis some visitor,” I muttered, “tapping at my chamber door— Only this and nothing more.”`; + toggleAppearance() { + this.appearance = this.appearance == 'raised' ? 'outlined' : 'raised'; + } } diff --git a/src/dev-app/mdc-checkbox/mdc-checkbox-demo-module.ts b/src/dev-app/mdc-checkbox/mdc-checkbox-demo-module.ts index ae3677bc8bd2..2e685c8096a8 100644 --- a/src/dev-app/mdc-checkbox/mdc-checkbox-demo-module.ts +++ b/src/dev-app/mdc-checkbox/mdc-checkbox-demo-module.ts @@ -21,7 +21,7 @@ import { ClickActionCheck, ClickActionNoop, MatCheckboxDemoNestedChecklist, - MdcCheckboxDemo + MdcCheckboxDemo, } from './mdc-checkbox-demo'; @NgModule({ @@ -37,9 +37,11 @@ import { RouterModule.forChild([{path: '', component: MdcCheckboxDemo}]), ], declarations: [ - MdcCheckboxDemo, MatCheckboxDemoNestedChecklist, ClickActionCheck, ClickActionNoop, - AnimationsNoop + MdcCheckboxDemo, + MatCheckboxDemoNestedChecklist, + ClickActionCheck, + ClickActionNoop, + AnimationsNoop, ], }) -export class MdcCheckboxDemoModule { -} +export class MdcCheckboxDemoModule {} diff --git a/src/dev-app/mdc-checkbox/mdc-checkbox-demo.html b/src/dev-app/mdc-checkbox/mdc-checkbox-demo.html index 0c867edb0597..73937c93eb2f 100644 --- a/src/dev-app/mdc-checkbox/mdc-checkbox-demo.html +++ b/src/dev-app/mdc-checkbox/mdc-checkbox-demo.html @@ -1,3 +1,22 @@ +

Themed Checkboxes

+ +
+ Default +
+ +
+ Primary +
+ +
+ Accent +
+ +
+ Warn +
+ +

mat-checkbox: Basic Example

t.completed = completed); + tasks.forEach(t => (t.completed = completed)); } } diff --git a/src/dev-app/mdc-chips/mdc-chips-demo-module.ts b/src/dev-app/mdc-chips/mdc-chips-demo-module.ts index 733d558d97a3..72f9de268ecf 100644 --- a/src/dev-app/mdc-chips/mdc-chips-demo-module.ts +++ b/src/dev-app/mdc-chips/mdc-chips-demo-module.ts @@ -35,5 +35,4 @@ import {MdcChipsDemo} from './mdc-chips-demo'; ], declarations: [MdcChipsDemo], }) -export class MdcChipsDemoModule { -} +export class MdcChipsDemoModule {} diff --git a/src/dev-app/mdc-chips/mdc-chips-demo.html b/src/dev-app/mdc-chips/mdc-chips-demo.html index 90c30a8c8147..d5f947051f45 100644 --- a/src/dev-app/mdc-chips/mdc-chips-demo.html +++ b/src/dev-app/mdc-chips/mdc-chips-demo.html @@ -25,13 +25,17 @@

With avatar, icons, and color

home Home - cancel + P Portel - cancel + @@ -41,7 +45,9 @@

With avatar, icons, and color

Koby - cancel + @@ -56,7 +62,9 @@

With avatar, icons, and color

Husi - cancel + @@ -77,7 +85,9 @@

With Events

With Events - cancel +
{{message}}
@@ -142,7 +152,9 @@

Input is last child of chip grid

(removed)="remove(person)" (edited)="edit(person, $event)"> {{person.name}} - cancel + Input is next sibling child of chip grid {{person.name}} - cancel + `, encapsulation: ViewEncapsulation.None, - styles: [`.hidden-dialog { opacity: 0; }`] + styles: [`.hidden-dialog { opacity: 0; }`], }) export class JazzDialog { private _dimesionToggle = false; constructor( public dialogRef: MatDialogRef, - @Inject(MAT_DIALOG_DATA) public data: any) { } + @Inject(MAT_DIALOG_DATA) public data: any, + ) {} togglePosition(): void { this._dimesionToggle = !this._dimesionToggle; if (this._dimesionToggle) { - this.dialogRef - .updateSize('500px', '500px') - .updatePosition({ top: '25px', left: '25px' }); + this.dialogRef.updateSize('500px', '500px').updatePosition({top: '25px', left: '25px'}); } else { - this.dialogRef - .updateSize() - .updatePosition(); + this.dialogRef.updateSize().updatePosition(); } } @@ -152,14 +147,15 @@ export class JazzDialog { } } - @Component({ selector: 'demo-content-element-dialog', - styles: [` + styles: [ + ` img { max-width: 100%; } - `], + `, + ], template: `

Neptune

@@ -195,12 +191,12 @@ export class JazzDialog { (click)="showInStackedDialog()"> Show in Dialog - ` + `, }) export class ContentElementDialog { actionsAlignment: string; - constructor(public dialog: MatDialog) { } + constructor(public dialog: MatDialog) {} showInStackedDialog() { this.dialog.open(IFrameDialog); @@ -209,11 +205,13 @@ export class ContentElementDialog { @Component({ selector: 'demo-iframe-dialog', - styles: [` + styles: [ + ` iframe { width: 800px; } - `], + `, + ], template: `

Neptune

@@ -227,6 +225,6 @@ export class ContentElementDialog { color="primary" mat-dialog-close>Close - ` + `, }) export class IFrameDialog {} diff --git a/src/dev-app/mdc-input/mdc-input-demo-module.ts b/src/dev-app/mdc-input/mdc-input-demo-module.ts index aee1e1c9da0f..6aa76e6d836c 100644 --- a/src/dev-app/mdc-input/mdc-input-demo-module.ts +++ b/src/dev-app/mdc-input/mdc-input-demo-module.ts @@ -7,9 +7,7 @@ */ import {CommonModule} from '@angular/common'; -import { - MdcFormFieldExamplesModule -} from '@angular/components-examples/material-experimental/mdc-form-field'; +import {MdcFormFieldExamplesModule} from '@angular/components-examples/material-experimental/mdc-form-field'; import {NgModule} from '@angular/core'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {MatFormFieldModule} from '@angular/material-experimental/mdc-form-field'; diff --git a/src/dev-app/mdc-input/mdc-input-demo.html b/src/dev-app/mdc-input/mdc-input-demo.html index f571548420e6..2e6a578f0119 100644 --- a/src/dev-app/mdc-input/mdc-input-demo.html +++ b/src/dev-app/mdc-input/mdc-input-demo.html @@ -124,32 +124,50 @@

Text

Amount - - .00 + $ + .00

Text (always outline)

Amount - - .00 + $ + .00

Icons

Amount - calendar_today - mode_edit + calendar_today + mode_edit

Icon buttons

Amount - - + + + + +

Text & Icons

+ + Amount + + $ + .00 + +

@@ -315,8 +333,8 @@

Textarea

Enter text to count - - Enter some text to count how many characters are in it. The character count is shown on + Enter + some text to count how many characters are in it. The character count is shown on the right. @@ -371,20 +389,22 @@

Textarea

Prefixed -
Example: 
+ Example: 
Suffixed - .00 € + .00 €
Both: Email address - email  -  @gmail.com + + email  + +  @gmail.com

@@ -679,8 +699,8 @@

<textarea> with bindable autosize

Amount - - .00 + + .00 @@ -692,9 +712,9 @@

<textarea> with bindable autosize

Amount - - - .00 + + + .00
@@ -711,6 +731,25 @@

<textarea> with bindable autosize

Label
+ +

+ Textarea alignment +

+ + + Textarea + + + + + Input + + + + + Input + + @@ -724,7 +763,7 @@

Custom control

Phone number - phone + phone Include area code

diff --git a/src/dev-app/mdc-input/mdc-input-demo.scss b/src/dev-app/mdc-input/mdc-input-demo.scss index cef3470bdf9f..7c0d9cdb4724 100644 --- a/src/dev-app/mdc-input/mdc-input-demo.scss +++ b/src/dev-app/mdc-input/mdc-input-demo.scss @@ -1,4 +1,4 @@ -@import '../../cdk/text-field/text-field'; +@use '../../cdk/text-field'; .demo-basic { padding: 0; @@ -41,7 +41,7 @@ } .demo-custom-autofill-style { - @include cdk-text-field-autofill-color(transparent, red); + @include text-field.text-field-autofill-color(transparent, red); } .demo-rows { diff --git a/src/dev-app/mdc-input/mdc-input-demo.ts b/src/dev-app/mdc-input/mdc-input-demo.ts index 6a73985fa166..b7b50d35cdc8 100644 --- a/src/dev-app/mdc-input/mdc-input-demo.ts +++ b/src/dev-app/mdc-input/mdc-input-demo.ts @@ -10,7 +10,7 @@ import {ChangeDetectionStrategy, Component} from '@angular/core'; import {FormControl, Validators} from '@angular/forms'; import { FloatLabelType, - MatFormFieldAppearance + MatFormFieldAppearance, } from '@angular/material-experimental/mdc-form-field'; import {ErrorStateMatcher, ThemePalette} from '@angular/material-experimental/mdc-core'; @@ -48,13 +48,7 @@ export class MdcInputDemo { dividerColorExample1: string; dividerColorExample2: string; dividerColorExample3: string; - items: {value: number}[] = [ - {value: 10}, - {value: 20}, - {value: 30}, - {value: 40}, - {value: 50}, - ]; + items: {value: number}[] = [{value: 10}, {value: 20}, {value: 30}, {value: 40}, {value: 50}]; rows = 8; formControl = new FormControl('hello', Validators.required); emailFormControl = new FormControl('', [Validators.required, Validators.pattern(EMAIL_REGEX)]); @@ -74,7 +68,7 @@ export class MdcInputDemo { addABunch(n: number) { for (let x = 0; x < n; x++) { - this.items.push({ value: ++max }); + this.items.push({value: ++max}); } } @@ -88,7 +82,7 @@ export class MdcInputDemo { } return false; - } + }, }; togglePlaceholderTestValue() { @@ -96,9 +90,9 @@ export class MdcInputDemo { } togglePlaceholderTestTouched() { - this.placeholderTestControl.touched ? - this.placeholderTestControl.markAsUntouched() : - this.placeholderTestControl.markAsTouched(); + this.placeholderTestControl.touched + ? this.placeholderTestControl.markAsUntouched() + : this.placeholderTestControl.markAsTouched(); } parseNumber(value: string): number { diff --git a/src/dev-app/mdc-list/mdc-list-demo-module.ts b/src/dev-app/mdc-list/mdc-list-demo-module.ts index ca44090456b2..844678ea2de5 100644 --- a/src/dev-app/mdc-list/mdc-list-demo-module.ts +++ b/src/dev-app/mdc-list/mdc-list-demo-module.ts @@ -26,5 +26,4 @@ import {MdcListDemo} from './mdc-list-demo'; ], declarations: [MdcListDemo], }) -export class MdcListDemoModule { -} +export class MdcListDemoModule {} diff --git a/src/dev-app/mdc-list/mdc-list-demo.html b/src/dev-app/mdc-list/mdc-list-demo.html index 31baa520f704..e8b2d376c888 100644 --- a/src/dev-app/mdc-list/mdc-list-demo.html +++ b/src/dev-app/mdc-list/mdc-list-demo.html @@ -1,9 +1,11 @@

mat-list demo

- + + + +
-

Normal lists

@@ -16,18 +18,18 @@

Normal lists

-
{{contact.name}}
-
extra line
-
{{contact.headline}}
+
{{contact.name}}
+
extra line
+
{{contact.headline}}
Today
- Image of {{message.from}} -
{{message.from}}
-
+ Image of {{message.from}} +
{{message.from}}
+
{{message.subject}} -- {{message.message}}
@@ -35,16 +37,16 @@

Normal lists

-
{{message.from}}
-
{{message.subject}}
-
{{message.message}}
+
{{message.from}}
+
{{message.subject}}
+
{{message.message}}
- {{ link.name }} - @@ -62,25 +64,25 @@

Dense lists

-
{{contact.name}}
-
{{contact.headline}}
+
{{contact.name}}
+
{{contact.headline}}
Today
- Image of {{message.from}} -
{{message.from}}
-
{{message.subject}}
-
{{message.message}}
+ Image of {{message.from}} +
{{message.from}}
+
{{message.subject}}
+
{{message.message}}
- {{ link.name }} - @@ -98,8 +100,8 @@

Nav lists

- folder - {{ link.name }} + folder + {{ link.name }}
@@ -134,13 +136,13 @@

Selection list

Dogs
- - Shiba Inu + + Shiba Inu - - Other Shiba Inu + + Other Shiba Inu @@ -183,21 +185,52 @@

Single Selection list

Selected: {{favoriteOptions | json}}

+
+

Line scenarios

+ + + Title + + Title + This is unscoped text content that is supposed to not wrap. The list has only + acquired two lines and therefore there is no space for wrapping. + + + Title + This is unscoped text content that is supposed to wrap to the third line. + The list item acquire spaces for three lines and text should have an ellipsis in the + third line upon text overflow. + + + Title + This is unscoped text content that is supposed to not wrap. The list has only + acquired two lines (automatically) and therefore there is no space for wrapping. + + + Title + Secondary line + Tertiary line + + + + +
+

Line alignment

- {{ link.name }} - Not in an matLine + {{ link.name }} + Unscoped content First - Second - Not in an matLine + Second + Unscoped content
@@ -207,19 +240,19 @@

Icon alignment in selection list

- info + info Bananas - info + info Oranges - info + info Cake - info + info Fries diff --git a/src/dev-app/mdc-list/mdc-list-demo.scss b/src/dev-app/mdc-list/mdc-list-demo.scss index 3f5fd9822baf..30bed5b5e262 100644 --- a/src/dev-app/mdc-list/mdc-list-demo.scss +++ b/src/dev-app/mdc-list/mdc-list-demo.scss @@ -15,6 +15,10 @@ .mat-mdc-icon-button { color: rgba(0, 0, 0, 0.12); } + + &.demo-show-boxes .mat-mdc-list-item { + border: 1px solid grey; + } } .demo-secondary-text { diff --git a/src/dev-app/mdc-list/mdc-list-demo.ts b/src/dev-app/mdc-list/mdc-list-demo.ts index 4863acbe50e0..a33fb58b67d4 100644 --- a/src/dev-app/mdc-list/mdc-list-demo.ts +++ b/src/dev-app/mdc-list/mdc-list-demo.ts @@ -9,57 +9,47 @@ import {Component} from '@angular/core'; import {MatListOptionCheckboxPosition} from '@angular/material-experimental/mdc-list'; - @Component({ selector: 'mdc-list-demo', templateUrl: 'mdc-list-demo.html', styleUrls: ['mdc-list-demo.css'], }) export class MdcListDemo { - items: string[] = [ - 'Pepper', - 'Salt', - 'Paprika' - ]; + items: string[] = ['Pepper', 'Salt', 'Paprika']; checkboxPosition: MatListOptionCheckboxPosition = 'before'; - contacts: {name: string, headline: string}[] = [ + contacts: {name: string; headline: string}[] = [ {name: 'Nancy', headline: 'Software engineer'}, {name: 'Mary', headline: 'TPM'}, - {name: 'Bobby', headline: 'UX designer'} + {name: 'Bobby', headline: 'UX designer'}, ]; - messages: {from: string, subject: string, message: string, image: string}[] = [ + messages: {from: string; subject: string; message: string; image: string}[] = [ { - from: 'Nancy', + from: 'John', subject: 'Brunch?', message: 'Did you want to go on Sunday? I was thinking that might work.', - image: 'https://angular.io/generated/images/bios/julie-ralph.jpg' + image: 'https://angular.io/generated/images/bios/devversion.jpg', }, { from: 'Mary', subject: 'Summer BBQ', message: 'Wish I could come, but I have some prior obligations.', - image: 'https://angular.io/generated/images/bios/juleskremer.jpg' + image: 'https://angular.io/generated/images/bios/twerske.jpg', }, { from: 'Bobby', subject: 'Oui oui', message: 'Do you have Paris reservations for the 15th? I just booked!', - image: 'https://angular.io/generated/images/bios/jelbourn.jpg' - } + image: 'https://angular.io/generated/images/bios/jelbourn.jpg', + }, ]; - links: {name: string}[] = [ - {name: 'Inbox'}, - {name: 'Outbox'}, - {name: 'Spam'}, - {name: 'Trash'} - - ]; + links: {name: string}[] = [{name: 'Inbox'}, {name: 'Outbox'}, {name: 'Spam'}, {name: 'Trash'}]; thirdLine = false; + showBoxes = false; infoClicked = false; selectionListDisabled = false; selectionListRippleDisabled = false; diff --git a/src/dev-app/mdc-menu/mdc-menu-demo-module.ts b/src/dev-app/mdc-menu/mdc-menu-demo-module.ts index ac479fb361b1..435ff7739042 100644 --- a/src/dev-app/mdc-menu/mdc-menu-demo-module.ts +++ b/src/dev-app/mdc-menu/mdc-menu-demo-module.ts @@ -28,5 +28,4 @@ import {MdcMenuDemo} from './mdc-menu-demo'; ], declarations: [MdcMenuDemo], }) -export class MdcMenuDemoModule { -} +export class MdcMenuDemoModule {} diff --git a/src/dev-app/mdc-menu/mdc-menu-demo.ts b/src/dev-app/mdc-menu/mdc-menu-demo.ts index cfdca42b4a88..019932847f9e 100644 --- a/src/dev-app/mdc-menu/mdc-menu-demo.ts +++ b/src/dev-app/mdc-menu/mdc-menu-demo.ts @@ -19,14 +19,16 @@ export class MdcMenuDemo { {text: 'Refresh'}, {text: 'Settings'}, {text: 'Help', disabled: true}, - {text: 'Sign Out'} + {text: 'Sign Out'}, ]; iconItems = [ {text: 'Redial', icon: 'dialpad'}, {text: 'Check voicemail', icon: 'voicemail', disabled: true}, - {text: 'Disable alerts', icon: 'notifications_off'} + {text: 'Disable alerts', icon: 'notifications_off'}, ]; - select(text: string) { this.selected = text; } + select(text: string) { + this.selected = text; + } } diff --git a/src/dev-app/mdc-paginator/mdc-paginator-demo-module.ts b/src/dev-app/mdc-paginator/mdc-paginator-demo-module.ts index 700e95738152..c1bb22a767c9 100644 --- a/src/dev-app/mdc-paginator/mdc-paginator-demo-module.ts +++ b/src/dev-app/mdc-paginator/mdc-paginator-demo-module.ts @@ -30,5 +30,4 @@ import {MdcPaginatorDemo} from './mdc-paginator-demo'; ], declarations: [MdcPaginatorDemo], }) -export class MdcPaginatorDemoModule { -} +export class MdcPaginatorDemoModule {} diff --git a/src/dev-app/mdc-paginator/mdc-paginator-demo.html b/src/dev-app/mdc-paginator/mdc-paginator-demo.html index 30b7abf00ff5..4859ac850b90 100644 --- a/src/dev-app/mdc-paginator/mdc-paginator-demo.html +++ b/src/dev-app/mdc-paginator/mdc-paginator-demo.html @@ -1,6 +1,6 @@

No inputs

- +
@@ -34,7 +34,8 @@

No inputs

[showFirstLastButtons]="showFirstLastButtons" [pageSizeOptions]="showPageSizeOptions ? pageSizeOptions : []" [hidePageSize]="hidePageSize" - [pageIndex]="pageIndex"> + [pageIndex]="pageIndex" + aria-label="Select page">
Output event: {{pageEvent | json}}
diff --git a/src/dev-app/mdc-progress-bar/mdc-progress-bar-demo-module.ts b/src/dev-app/mdc-progress-bar/mdc-progress-bar-demo-module.ts index 0b0b05858c8b..9ec41d95fdc8 100644 --- a/src/dev-app/mdc-progress-bar/mdc-progress-bar-demo-module.ts +++ b/src/dev-app/mdc-progress-bar/mdc-progress-bar-demo-module.ts @@ -26,5 +26,4 @@ import {MdcProgressBarDemo} from './mdc-progress-bar-demo'; ], declarations: [MdcProgressBarDemo], }) -export class MdcProgressBarDemoModule { -} +export class MdcProgressBarDemoModule {} diff --git a/src/dev-app/mdc-progress-spinner/mdc-progress-spinner-demo.ts b/src/dev-app/mdc-progress-spinner/mdc-progress-spinner-demo.ts index e5177f137285..8b66a9b16aa7 100644 --- a/src/dev-app/mdc-progress-spinner/mdc-progress-spinner-demo.ts +++ b/src/dev-app/mdc-progress-spinner/mdc-progress-spinner-demo.ts @@ -9,7 +9,6 @@ import {Component} from '@angular/core'; import {ThemePalette} from '@angular/material/core'; - @Component({ selector: 'mdc-progress-spinner-demo', templateUrl: 'mdc-progress-spinner-demo.html', diff --git a/src/dev-app/mdc-radio/mdc-radio-demo-module.ts b/src/dev-app/mdc-radio/mdc-radio-demo-module.ts index 5631c5311523..0f11225dcc94 100644 --- a/src/dev-app/mdc-radio/mdc-radio-demo-module.ts +++ b/src/dev-app/mdc-radio/mdc-radio-demo-module.ts @@ -26,5 +26,4 @@ import {CommonModule} from '@angular/common'; ], declarations: [MdcRadioDemo], }) -export class MdcRadioDemoModule { -} +export class MdcRadioDemoModule {} diff --git a/src/dev-app/mdc-radio/mdc-radio-demo.ts b/src/dev-app/mdc-radio/mdc-radio-demo.ts index 335dcb55a2d1..9a67d5a9d1e4 100644 --- a/src/dev-app/mdc-radio/mdc-radio-demo.ts +++ b/src/dev-app/mdc-radio/mdc-radio-demo.ts @@ -18,10 +18,5 @@ export class MdcRadioDemo { isDisabled: boolean = false; isRequired: boolean = false; favoriteSeason: string = 'Autumn'; - seasonOptions = [ - 'Winter', - 'Spring', - 'Summer', - 'Autumn', - ]; + seasonOptions = ['Winter', 'Spring', 'Summer', 'Autumn']; } diff --git a/src/dev-app/mdc-select/BUILD.bazel b/src/dev-app/mdc-select/BUILD.bazel index 343261a20084..05b476785a2f 100644 --- a/src/dev-app/mdc-select/BUILD.bazel +++ b/src/dev-app/mdc-select/BUILD.bazel @@ -1,5 +1,4 @@ -load("@io_bazel_rules_sass//:defs.bzl", "sass_binary") -load("//tools:defaults.bzl", "ng_module") +load("//tools:defaults.bzl", "ng_module", "sass_binary") package(default_visibility = ["//visibility:public"]) diff --git a/src/dev-app/mdc-select/mdc-select-demo-module.ts b/src/dev-app/mdc-select/mdc-select-demo-module.ts index b96d37d0c0b2..4d093ee454fe 100644 --- a/src/dev-app/mdc-select/mdc-select-demo-module.ts +++ b/src/dev-app/mdc-select/mdc-select-demo-module.ts @@ -33,5 +33,4 @@ import {MdcSelectDemo} from './mdc-select-demo'; ], declarations: [MdcSelectDemo], }) -export class MdcSelectDemoModule { -} +export class MdcSelectDemoModule {} diff --git a/src/dev-app/mdc-select/mdc-select-demo.html b/src/dev-app/mdc-select/mdc-select-demo.html index d3a189e74b65..c3f5d0b40e9c 100644 --- a/src/dev-app/mdc-select/mdc-select-demo.html +++ b/src/dev-app/mdc-select/mdc-select-demo.html @@ -26,8 +26,8 @@

Dirty: {{ drinkControl.dirty }}

Status: {{ drinkControl.control?.status }}

- - @@ -323,16 +323,6 @@

Option group

-

Place holder

- - -

Error message, hint, form sumbit

Select your car (required) diff --git a/src/dev-app/mdc-select/mdc-select-demo.ts b/src/dev-app/mdc-select/mdc-select-demo.ts index 1ca4c48ac642..3cb8bdff0562 100644 --- a/src/dev-app/mdc-select/mdc-select-demo.ts +++ b/src/dev-app/mdc-select/mdc-select-demo.ts @@ -23,9 +23,9 @@ export class MyErrorStateMatcher implements ErrorStateMatcher { } @Component({ - selector: 'mdc-select-demo', - templateUrl: 'mdc-select-demo.html', - styleUrls: ['mdc-select-demo.css'], + selector: 'mdc-select-demo', + templateUrl: 'mdc-select-demo.html', + styleUrls: ['mdc-select-demo.css'], }) export class MdcSelectDemo { drinksRequired = false; @@ -35,7 +35,7 @@ export class MdcSelectDemo { pokemonDisabled = false; showSelect = false; currentDrink: string; - currentDrinkObject: {}|undefined = {value: 'tea-5', viewValue: 'Tea'}; + currentDrinkObject: {} | undefined = {value: 'tea-5', viewValue: 'Tea'}; currentPokemon: string[]; currentPokemonFromGroup: string; currentDigimon: string; @@ -54,7 +54,7 @@ export class MdcSelectDemo { {value: null, viewValue: 'None'}, {value: 'steak-0', viewValue: 'Steak'}, {value: 'pizza-1', viewValue: 'Pizza'}, - {value: 'tacos-2', viewValue: 'Tacos'} + {value: 'tacos-2', viewValue: 'Tacos'}, ]; drinks = [ @@ -62,7 +62,7 @@ export class MdcSelectDemo { { value: 'long-name-1', viewValue: 'Decaf Chocolate Brownie Vanilla Gingerbread Frappuccino', - disabled: false + disabled: false, }, {value: 'water-2', viewValue: 'Water', disabled: false}, {value: 'pepper-3', viewValue: 'Dr. Pepper', disabled: false}, @@ -84,9 +84,9 @@ export class MdcSelectDemo { ]; availableThemes = [ - {value: 'primary', name: 'Primary' }, - {value: 'accent', name: 'Accent' }, - {value: 'warn', name: 'Warn' } + {value: 'primary', name: 'Primary'}, + {value: 'accent', name: 'Accent'}, + {value: 'warn', name: 'Warn'}, ]; pokemonGroups = [ @@ -95,16 +95,16 @@ export class MdcSelectDemo { pokemon: [ {value: 'bulbasaur-0', viewValue: 'Bulbasaur'}, {value: 'oddish-1', viewValue: 'Oddish'}, - {value: 'bellsprout-2', viewValue: 'Bellsprout'} - ] + {value: 'bellsprout-2', viewValue: 'Bellsprout'}, + ], }, { name: 'Water', pokemon: [ {value: 'squirtle-3', viewValue: 'Squirtle'}, {value: 'psyduck-4', viewValue: 'Psyduck'}, - {value: 'horsea-5', viewValue: 'Horsea'} - ] + {value: 'horsea-5', viewValue: 'Horsea'}, + ], }, { name: 'Fire', @@ -112,16 +112,16 @@ export class MdcSelectDemo { pokemon: [ {value: 'charmander-6', viewValue: 'Charmander'}, {value: 'vulpix-7', viewValue: 'Vulpix'}, - {value: 'flareon-8', viewValue: 'Flareon'} - ] + {value: 'flareon-8', viewValue: 'Flareon'}, + ], }, { name: 'Psychic', pokemon: [ {value: 'mew-9', viewValue: 'Mew'}, {value: 'mewtwo-10', viewValue: 'Mewtwo'}, - ] - } + ], + }, ]; digimon = [ @@ -130,7 +130,7 @@ export class MdcSelectDemo { {value: 'sinduramon-2', viewValue: 'Sinduramon'}, {value: 'pajiramon-3', viewValue: 'Pajiramon'}, {value: 'vajiramon-4', viewValue: 'Vajiramon'}, - {value: 'indramon-5', viewValue: 'Indramon'} + {value: 'indramon-5', viewValue: 'Indramon'}, ]; toggleDisabled() { diff --git a/src/dev-app/mdc-sidenav/BUILD.bazel b/src/dev-app/mdc-sidenav/BUILD.bazel index 013aa066a864..1f8b93d549a5 100644 --- a/src/dev-app/mdc-sidenav/BUILD.bazel +++ b/src/dev-app/mdc-sidenav/BUILD.bazel @@ -1,5 +1,4 @@ -load("@io_bazel_rules_sass//:defs.bzl", "sass_binary") -load("//tools:defaults.bzl", "ng_module") +load("//tools:defaults.bzl", "ng_module", "sass_binary") package(default_visibility = ["//visibility:public"]) diff --git a/src/dev-app/mdc-sidenav/mdc-sidenav-demo-module.ts b/src/dev-app/mdc-sidenav/mdc-sidenav-demo-module.ts index 353608060d10..59a0ab1edc9a 100644 --- a/src/dev-app/mdc-sidenav/mdc-sidenav-demo-module.ts +++ b/src/dev-app/mdc-sidenav/mdc-sidenav-demo-module.ts @@ -12,11 +12,7 @@ import {RouterModule} from '@angular/router'; import {MdcSidenavDemo} from './mdc-sidenav-demo'; @NgModule({ - imports: [ - MatSidenavModule, - RouterModule.forChild([{path: '', component: MdcSidenavDemo}]), - ], + imports: [MatSidenavModule, RouterModule.forChild([{path: '', component: MdcSidenavDemo}])], declarations: [MdcSidenavDemo], }) -export class MdcSidenavDemoModule { -} +export class MdcSidenavDemoModule {} diff --git a/src/dev-app/mdc-sidenav/mdc-sidenav-demo.ts b/src/dev-app/mdc-sidenav/mdc-sidenav-demo.ts index f0ed3c338000..4e281eef08d7 100644 --- a/src/dev-app/mdc-sidenav/mdc-sidenav-demo.ts +++ b/src/dev-app/mdc-sidenav/mdc-sidenav-demo.ts @@ -13,5 +13,4 @@ import {Component} from '@angular/core'; templateUrl: 'mdc-sidenav-demo.html', styleUrls: ['mdc-sidenav-demo.css'], }) -export class MdcSidenavDemo { -} +export class MdcSidenavDemo {} diff --git a/src/dev-app/mdc-slide-toggle/mdc-slide-toggle-demo-module.ts b/src/dev-app/mdc-slide-toggle/mdc-slide-toggle-demo-module.ts index 1b1a39a956ee..d2df1bb54862 100644 --- a/src/dev-app/mdc-slide-toggle/mdc-slide-toggle-demo-module.ts +++ b/src/dev-app/mdc-slide-toggle/mdc-slide-toggle-demo-module.ts @@ -20,5 +20,4 @@ import {MdcSlideToggleDemo} from './mdc-slide-toggle-demo'; ], declarations: [MdcSlideToggleDemo], }) -export class MdcSlideToggleDemoModule { -} +export class MdcSlideToggleDemoModule {} diff --git a/src/dev-app/mdc-slider/mdc-slider-demo-module.ts b/src/dev-app/mdc-slider/mdc-slider-demo-module.ts index e4dceb9e0f89..4f92c186bdf4 100644 --- a/src/dev-app/mdc-slider/mdc-slider-demo-module.ts +++ b/src/dev-app/mdc-slider/mdc-slider-demo-module.ts @@ -22,5 +22,4 @@ import {MdcSliderDemo} from './mdc-slider-demo'; ], declarations: [MdcSliderDemo], }) -export class MdcSliderDemoModule { -} +export class MdcSliderDemoModule {} diff --git a/src/dev-app/mdc-slider/mdc-slider-demo.html b/src/dev-app/mdc-slider/mdc-slider-demo.html index bb8e3de17870..68db534874f7 100644 --- a/src/dev-app/mdc-slider/mdc-slider-demo.html +++ b/src/dev-app/mdc-slider/mdc-slider-demo.html @@ -1,53 +1,88 @@

Default Slider

-Label +Label + + + {{slidey.value}}

Colors

- - - + + + + + + + + +

Slider with Min and Max

- + + {{slider2.value}}

Disabled Slider

- + +

Slider with set value

- + + +

Slider with step defined

- + + + {{slider5.value}}

Slider with set tick interval

- - + + + + + +

Slider with Thumb Label

- + + +

Slider with one-way binding

- + + +

Slider with two-way binding

- + + +

Set/lost focus to show thumblabel programmatically

- + + + - + + + + +

Range slider

+ + + + diff --git a/src/dev-app/mdc-slider/mdc-slider-demo.ts b/src/dev-app/mdc-slider/mdc-slider-demo.ts index fab41d01fc41..651dbff35ca5 100644 --- a/src/dev-app/mdc-slider/mdc-slider-demo.ts +++ b/src/dev-app/mdc-slider/mdc-slider-demo.ts @@ -8,10 +8,10 @@ import {Component} from '@angular/core'; - @Component({ selector: 'mdc-slider-demo', templateUrl: 'mdc-slider-demo.html', + styles: ['.mat-mdc-slider { width: 300px; }'], }) export class MdcSliderDemo { demo: number; diff --git a/src/dev-app/mdc-snack-bar/BUILD.bazel b/src/dev-app/mdc-snack-bar/BUILD.bazel index 38fa203848fc..f495a4b5933b 100644 --- a/src/dev-app/mdc-snack-bar/BUILD.bazel +++ b/src/dev-app/mdc-snack-bar/BUILD.bazel @@ -1,5 +1,4 @@ -load("@io_bazel_rules_sass//:defs.bzl", "sass_binary") -load("//tools:defaults.bzl", "ng_module") +load("//tools:defaults.bzl", "ng_module", "sass_binary") package(default_visibility = ["//visibility:public"]) diff --git a/src/dev-app/mdc-snack-bar/mdc-snack-bar-demo-module.ts b/src/dev-app/mdc-snack-bar/mdc-snack-bar-demo-module.ts index 9f6becf10d92..d1d885c2f268 100644 --- a/src/dev-app/mdc-snack-bar/mdc-snack-bar-demo-module.ts +++ b/src/dev-app/mdc-snack-bar/mdc-snack-bar-demo-module.ts @@ -32,5 +32,4 @@ import {MatSelectModule} from '@angular/material-experimental/mdc-select'; ], declarations: [MdcSnackBarDemo], }) -export class MdcSnackBarDemoModule { -} +export class MdcSnackBarDemoModule {} diff --git a/src/dev-app/mdc-snack-bar/mdc-snack-bar-demo.ts b/src/dev-app/mdc-snack-bar/mdc-snack-bar-demo.ts index da8eaba2787c..51d5bc2654c7 100644 --- a/src/dev-app/mdc-snack-bar/mdc-snack-bar-demo.ts +++ b/src/dev-app/mdc-snack-bar/mdc-snack-bar-demo.ts @@ -12,7 +12,7 @@ import {MatSnackBar} from '@angular/material-experimental/mdc-snack-bar'; import { MatSnackBarConfig, MatSnackBarHorizontalPosition, - MatSnackBarVerticalPosition + MatSnackBarVerticalPosition, } from '@angular/material/snack-bar'; @Component({ @@ -22,7 +22,6 @@ import { encapsulation: ViewEncapsulation.None, }) export class MdcSnackBarDemo { - @ViewChild('template') template: TemplateRef; message = 'Snack Bar opened.'; actionButtonLabel = 'Retry'; diff --git a/src/dev-app/mdc-table/BUILD.bazel b/src/dev-app/mdc-table/BUILD.bazel index b3cb0c52f2f8..43df5fbb0370 100644 --- a/src/dev-app/mdc-table/BUILD.bazel +++ b/src/dev-app/mdc-table/BUILD.bazel @@ -1,4 +1,3 @@ -load("@io_bazel_rules_sass//:defs.bzl", "sass_binary") load("//tools:defaults.bzl", "ng_module") package(default_visibility = ["//visibility:public"]) @@ -8,16 +7,10 @@ ng_module( srcs = glob(["**/*.ts"]), assets = [ "mdc-table-demo.html", - ":mdc_table_demo_scss", ], deps = [ + "//src/components-examples/material-experimental/mdc-table", "//src/material-experimental/mdc-table", - "//src/material/icon", "@npm//@angular/router", ], ) - -sass_binary( - name = "mdc_table_demo_scss", - src = "mdc-table-demo.scss", -) diff --git a/src/dev-app/mdc-table/mdc-table-demo-module.ts b/src/dev-app/mdc-table/mdc-table-demo-module.ts index 209f0849d420..717f573a11a4 100644 --- a/src/dev-app/mdc-table/mdc-table-demo-module.ts +++ b/src/dev-app/mdc-table/mdc-table-demo-module.ts @@ -11,14 +11,15 @@ import {MatIconModule} from '@angular/material/icon'; import {MatTableModule} from '@angular/material-experimental/mdc-table'; import {RouterModule} from '@angular/router'; import {MdcTableDemo} from './mdc-table-demo'; +import {MdcTableExamplesModule} from '@angular/components-examples/material-experimental/mdc-table'; @NgModule({ imports: [ MatIconModule, MatTableModule, + MdcTableExamplesModule, RouterModule.forChild([{path: '', component: MdcTableDemo}]), ], declarations: [MdcTableDemo], }) -export class MdcTableDemoModule { -} +export class MdcTableDemoModule {} diff --git a/src/dev-app/mdc-table/mdc-table-demo.html b/src/dev-app/mdc-table/mdc-table-demo.html index 856253ea5913..2b28db9618af 100644 --- a/src/dev-app/mdc-table/mdc-table-demo.html +++ b/src/dev-app/mdc-table/mdc-table-demo.html @@ -1,171 +1,71 @@ -

Basic

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
No. {{element.position}} Name {{element.name}} Weight {{element.weight}} Symbol {{element.symbol}}
-
- -

Sticky Columns

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Name {{element.name}} No. {{element.position}} Weight {{element.weight}} Symbol {{element.symbol}} - more_vert -
-
- -

Sticky Header

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
No. {{element.position}} Name {{element.name}} Weight {{element.weight}} Symbol {{element.symbol}}
-
- -

Sticky Footer

- - -

Basic flex table

- - - - No. - {{element.position}} - - - - - Name - {{element.name}} - - - - - Weight - {{element.weight}} - - - - - Symbol - {{element.symbol}} - - - - - +

Table basic

+ + +

Table basic with recycled rows

+ + +

Table basic flex

+ + +

Table flex with large row

+ + +

Table dynamic columns

+ + +

Table expandable rows

+ + +

Table filtering

+ + +

Table footer row

+ + +

Table with http

+ + +

Table with multiple headers and footers

+ + +

Table overview

+ + +

Table row context

+ + +

Table with pagination

+ + +

Table with selection

+ + +

Table with sorting

+ + +

Table with sticky columns

+ + +

Table with sticky headers, footers and columns

+ + +

Table flex with sticky headers, footers and columns

+ + +

Table with sticky footer

+ + +

Table with sticky header

+ + +

Table with mat-text-column

+ + +

Table with mat-text-column advanced

+ + +

Table wrapped in reusable component

+ + +

Table wrapped re-orderable columns

+ diff --git a/src/dev-app/mdc-table/mdc-table-demo.scss b/src/dev-app/mdc-table/mdc-table-demo.scss deleted file mode 100644 index 57d509167aee..000000000000 --- a/src/dev-app/mdc-table/mdc-table-demo.scss +++ /dev/null @@ -1,80 +0,0 @@ -.example-container { - height: 400px; - margin-bottom: 24px; - width: 550px; - max-width: 100%; - overflow: auto; -} - -h2 { - margin: 0 0 16px; -} - -table { - width: 800px; -} - -.example-sticky-columns { - td { - background-color: white; - } - - td.mat-mdc-column-star { - width: 20px; - padding-right: 8px; - } - - th.mat-mdc-column-position, td.mat-mdc-column-position { - padding-left: 8px; - } - - // Unlike with the classic MatTable, border-right does not work due to border-collapse. - // Using :before to not conflict with popover-edit and column-resize which use :after. - .mat-mdc-table-sticky:first-child, - .mat-mdc-table-sticky:last-child { - &::before { - background-color: #e0e0e0; - bottom: 0; - content: ''; - position: absolute; - top: 0; - width: 1px; - } - } - - .mat-mdc-table-sticky:first-child::before { - right: 0; - } - - .mat-mdc-table-sticky:last-child::before { - left: 0; - } -} - -.example-sticky-header { - .mat-mdc-header-row th::before { - background-color: #e0e0e0; - bottom: 0; - content: ''; - height: 1px; - left: 0; - position: absolute; - right: 0; - } -} - -.example-sticky-footer { - td { - background-color: white; - } - - .mat-mdc-footer-row td::before { - background-color: #e0e0e0; - content: ''; - height: 1px; - left: 0; - position: absolute; - right: 0; - top: 0; - } -} diff --git a/src/dev-app/mdc-table/mdc-table-demo.ts b/src/dev-app/mdc-table/mdc-table-demo.ts index 435c7d89229e..756c76cffa7e 100644 --- a/src/dev-app/mdc-table/mdc-table-demo.ts +++ b/src/dev-app/mdc-table/mdc-table-demo.ts @@ -8,34 +8,7 @@ import {Component} from '@angular/core'; -export interface PeriodicElement { - name: string; - position: number; - weight: number; - symbol: string; -} - -const ELEMENT_DATA: PeriodicElement[] = [ - {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'}, - {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}, - {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'}, - {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'}, - {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'}, - {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'}, - {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'}, - {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'}, - {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'}, - {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'}, -]; - @Component({ - selector: 'mdc-table-demo', templateUrl: 'mdc-table-demo.html', - styleUrls: ['mdc-table-demo.css'], }) -export class MdcTableDemo { - readonly displayedColumns: string[] = ['position', 'name', 'weight', 'symbol']; - readonly displayedColumns2 = - ['name', 'position', 'weight', 'symbol', 'position', 'weight', 'symbol', 'star']; - readonly dataSource = ELEMENT_DATA; -} +export class MdcTableDemo {} diff --git a/src/dev-app/mdc-tabs/mdc-tabs-demo-module.ts b/src/dev-app/mdc-tabs/mdc-tabs-demo-module.ts index 0ac7f5713e92..12a91968e9b0 100644 --- a/src/dev-app/mdc-tabs/mdc-tabs-demo-module.ts +++ b/src/dev-app/mdc-tabs/mdc-tabs-demo-module.ts @@ -22,5 +22,4 @@ import {MatButtonToggleModule} from '@angular/material/button-toggle'; ], declarations: [MdcTabsDemo], }) -export class MdcTabsDemoModule { -} +export class MdcTabsDemoModule {} diff --git a/src/dev-app/mdc-tooltip/BUILD.bazel b/src/dev-app/mdc-tooltip/BUILD.bazel new file mode 100644 index 000000000000..5e6d20b2a192 --- /dev/null +++ b/src/dev-app/mdc-tooltip/BUILD.bazel @@ -0,0 +1,27 @@ +load("//tools:defaults.bzl", "ng_module", "sass_binary") + +package(default_visibility = ["//visibility:public"]) + +ng_module( + name = "mdc-tooltip", + srcs = glob(["**/*.ts"]), + assets = [ + "mdc-tooltip-demo.html", + ":mdc_tooltip_demo_scss", + ], + deps = [ + "//src/material-experimental/mdc-button", + "//src/material-experimental/mdc-form-field", + "//src/material-experimental/mdc-input", + "//src/material-experimental/mdc-select", + "//src/material-experimental/mdc-tooltip", + "@npm//@angular/common", + "@npm//@angular/forms", + "@npm//@angular/router", + ], +) + +sass_binary( + name = "mdc_tooltip_demo_scss", + src = "mdc-tooltip-demo.scss", +) diff --git a/src/dev-app/mdc-tooltip/mdc-tooltip-demo-module.ts b/src/dev-app/mdc-tooltip/mdc-tooltip-demo-module.ts new file mode 100644 index 000000000000..4e884f6e6c56 --- /dev/null +++ b/src/dev-app/mdc-tooltip/mdc-tooltip-demo-module.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {NgModule} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {ReactiveFormsModule} from '@angular/forms'; +import {MatButtonModule} from '@angular/material-experimental/mdc-button'; +import {MatFormFieldModule} from '@angular/material-experimental/mdc-form-field'; +import {MatInputModule} from '@angular/material-experimental/mdc-input'; +import {MatSelectModule} from '@angular/material-experimental/mdc-select'; +import {MatTooltipModule} from '@angular/material-experimental/mdc-tooltip'; +import {RouterModule} from '@angular/router'; +import {MdcTooltipDemo} from './mdc-tooltip-demo'; + +@NgModule({ + imports: [ + CommonModule, + ReactiveFormsModule, + MatTooltipModule, + MatButtonModule, + MatFormFieldModule, + MatSelectModule, + MatInputModule, + RouterModule.forChild([{path: '', component: MdcTooltipDemo}]), + ], + declarations: [MdcTooltipDemo], +}) +export class MdcTooltipDemoModule {} diff --git a/src/dev-app/mdc-tooltip/mdc-tooltip-demo.html b/src/dev-app/mdc-tooltip/mdc-tooltip-demo.html new file mode 100644 index 000000000000..4f4af17f339c --- /dev/null +++ b/src/dev-app/mdc-tooltip/mdc-tooltip-demo.html @@ -0,0 +1,36 @@ +
+
+ + Message + + + + + Show delay + + milliseconds + + + + Hide delay + + milliseconds + + + + Tooltip position + + + {{positionOption}} + + + +
+ + +
diff --git a/src/dev-app/mdc-tooltip/mdc-tooltip-demo.scss b/src/dev-app/mdc-tooltip/mdc-tooltip-demo.scss new file mode 100644 index 000000000000..d1298121ea59 --- /dev/null +++ b/src/dev-app/mdc-tooltip/mdc-tooltip-demo.scss @@ -0,0 +1,15 @@ +.demo-wrapper { + // Prevent the container from stretching to 100%. + display: inline-block; + + .mat-mdc-tooltip-trigger { + // Center the trigger relative to the content so that it's not flush against one of the + // viewport edges. This will guarantee that we always get the specified demo position. + margin: 32px auto; + display: block; + } +} + +.demo-form-field { + margin: 0 8px; +} diff --git a/src/dev-app/mdc-tooltip/mdc-tooltip-demo.ts b/src/dev-app/mdc-tooltip/mdc-tooltip-demo.ts new file mode 100644 index 000000000000..fcb813b8a41a --- /dev/null +++ b/src/dev-app/mdc-tooltip/mdc-tooltip-demo.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {Component} from '@angular/core'; +import {FormControl} from '@angular/forms'; +import {TooltipPosition} from '@angular/material-experimental/mdc-tooltip'; + +@Component({ + selector: 'mdc-tooltip-demo', + templateUrl: 'mdc-tooltip-demo.html', + styleUrls: ['mdc-tooltip-demo.css'], +}) +export class MdcTooltipDemo { + message = new FormControl('Info about the action'); + showDelay = new FormControl(0); + hideDelay = new FormControl(0); + positionOptions: TooltipPosition[] = ['below', 'after', 'before', 'above', 'left', 'right']; + position = new FormControl(this.positionOptions[0]); +} diff --git a/src/dev-app/menu/menu-demo-module.ts b/src/dev-app/menu/menu-demo-module.ts index 2ebfcc5f849a..2abf5d0c2df4 100644 --- a/src/dev-app/menu/menu-demo-module.ts +++ b/src/dev-app/menu/menu-demo-module.ts @@ -28,5 +28,4 @@ import {MenuDemo} from './menu-demo'; ], declarations: [MenuDemo], }) -export class MenuDemoModule { -} +export class MenuDemoModule {} diff --git a/src/dev-app/menu/menu-demo.ts b/src/dev-app/menu/menu-demo.ts index ed7d846d9f49..aa6c1da15612 100644 --- a/src/dev-app/menu/menu-demo.ts +++ b/src/dev-app/menu/menu-demo.ts @@ -8,7 +8,6 @@ import {Component} from '@angular/core'; - @Component({ selector: 'menu-demo', templateUrl: 'menu-demo.html', @@ -20,14 +19,16 @@ export class MenuDemo { {text: 'Refresh'}, {text: 'Settings'}, {text: 'Help', disabled: true}, - {text: 'Sign Out'} + {text: 'Sign Out'}, ]; iconItems = [ {text: 'Redial', icon: 'dialpad'}, {text: 'Check voicemail', icon: 'voicemail', disabled: true}, - {text: 'Disable alerts', icon: 'notifications_off'} + {text: 'Disable alerts', icon: 'notifications_off'}, ]; - select(text: string) { this.selected = text; } + select(text: string) { + this.selected = text; + } } diff --git a/src/dev-app/menubar/mat-menubar-demo.scss b/src/dev-app/menubar/mat-menubar-demo.scss index dfafa9d003e1..4aff08a5ca12 100644 --- a/src/dev-app/menubar/mat-menubar-demo.scss +++ b/src/dev-app/menubar/mat-menubar-demo.scss @@ -24,5 +24,4 @@ padding: 16px; -webkit-user-select: none; -moz-user-select: none; - -ms-user-select: none; } diff --git a/src/dev-app/paginator/paginator-demo-module.ts b/src/dev-app/paginator/paginator-demo-module.ts index 42b0b1d4e6e2..ba0bf91d1129 100644 --- a/src/dev-app/paginator/paginator-demo-module.ts +++ b/src/dev-app/paginator/paginator-demo-module.ts @@ -30,5 +30,4 @@ import {PaginatorDemo} from './paginator-demo'; ], declarations: [PaginatorDemo], }) -export class PaginatorDemoModule { -} +export class PaginatorDemoModule {} diff --git a/src/dev-app/paginator/paginator-demo.html b/src/dev-app/paginator/paginator-demo.html index af3c21879c14..77bb73ea92b0 100644 --- a/src/dev-app/paginator/paginator-demo.html +++ b/src/dev-app/paginator/paginator-demo.html @@ -1,6 +1,6 @@

No inputs

- +
@@ -31,7 +31,8 @@

No inputs

[showFirstLastButtons]="showFirstLastButtons" [pageSizeOptions]="showPageSizeOptions ? pageSizeOptions : []" [hidePageSize]="hidePageSize" - [pageIndex]="pageIndex"> + [pageIndex]="pageIndex" + aria-label="Select page">
Output event: {{pageEvent | json}}
diff --git a/src/dev-app/platform/platform-demo-module.ts b/src/dev-app/platform/platform-demo-module.ts index 6118ff298fa9..0fe3b841c462 100644 --- a/src/dev-app/platform/platform-demo-module.ts +++ b/src/dev-app/platform/platform-demo-module.ts @@ -20,5 +20,4 @@ import {PlatformDemo} from './platform-demo'; ], declarations: [PlatformDemo], }) -export class PlatformDemoModule { -} +export class PlatformDemoModule {} diff --git a/src/dev-app/platform/platform-demo.ts b/src/dev-app/platform/platform-demo.ts index ae18818a3ebd..3ba6f345c0f5 100644 --- a/src/dev-app/platform/platform-demo.ts +++ b/src/dev-app/platform/platform-demo.ts @@ -9,7 +9,6 @@ import {Component} from '@angular/core'; import {Platform, getSupportedInputTypes} from '@angular/cdk/platform'; - @Component({ selector: 'platform-demo', templateUrl: 'platform-demo.html', diff --git a/src/dev-app/popover-edit/popover-edit-demo-module.ts b/src/dev-app/popover-edit/popover-edit-demo-module.ts index 5633f6994be8..52992a6d1f09 100644 --- a/src/dev-app/popover-edit/popover-edit-demo-module.ts +++ b/src/dev-app/popover-edit/popover-edit-demo-module.ts @@ -7,12 +7,8 @@ */ import {NgModule} from '@angular/core'; -import { - CdkPopoverEditExamplesModule -} from '@angular/components-examples/cdk-experimental/popover-edit'; -import { - PopoverEditExamplesModule -} from '@angular/components-examples/material-experimental/popover-edit'; +import {CdkPopoverEditExamplesModule} from '@angular/components-examples/cdk-experimental/popover-edit'; +import {PopoverEditExamplesModule} from '@angular/components-examples/material-experimental/popover-edit'; import {FormsModule} from '@angular/forms'; import {RouterModule} from '@angular/router'; import {PopoverEditDemo} from './popover-edit-demo'; @@ -26,5 +22,4 @@ import {PopoverEditDemo} from './popover-edit-demo'; ], declarations: [PopoverEditDemo], }) -export class PopoverEditDemoModule { -} +export class PopoverEditDemoModule {} diff --git a/src/dev-app/portal/portal-demo-module.ts b/src/dev-app/portal/portal-demo-module.ts index ec7ac9e07281..6bd2dd9ddf70 100644 --- a/src/dev-app/portal/portal-demo-module.ts +++ b/src/dev-app/portal/portal-demo-module.ts @@ -12,11 +12,7 @@ import {RouterModule} from '@angular/router'; import {PortalDemo, ScienceJoke} from './portal-demo'; @NgModule({ - imports: [ - PortalModule, - RouterModule.forChild([{path: '', component: PortalDemo}]), - ], + imports: [PortalModule, RouterModule.forChild([{path: '', component: PortalDemo}])], declarations: [PortalDemo, ScienceJoke], }) -export class PortalDemoModule { -} +export class PortalDemoModule {} diff --git a/src/dev-app/portal/portal-demo.ts b/src/dev-app/portal/portal-demo.ts index 6d7e4bc2e4c5..b0070478fc8f 100644 --- a/src/dev-app/portal/portal-demo.ts +++ b/src/dev-app/portal/portal-demo.ts @@ -9,7 +9,6 @@ import {ComponentPortal, Portal, CdkPortal, DomPortal} from '@angular/cdk/portal'; import {Component, QueryList, ViewChildren, ElementRef, ViewChild} from '@angular/core'; - @Component({ selector: 'portal-demo', templateUrl: 'portal-demo.html', @@ -38,9 +37,8 @@ export class PortalDemo { } } - @Component({ selector: 'science-joke', - template: `

100 kilopascals go into a bar.

` + template: `

100 kilopascals go into a bar.

`, }) -export class ScienceJoke { } +export class ScienceJoke {} diff --git a/src/dev-app/progress-bar/progress-bar-demo-module.ts b/src/dev-app/progress-bar/progress-bar-demo-module.ts index 583bd6d66bd8..7d02e7fabfd3 100644 --- a/src/dev-app/progress-bar/progress-bar-demo-module.ts +++ b/src/dev-app/progress-bar/progress-bar-demo-module.ts @@ -24,5 +24,4 @@ import {ProgressBarDemo} from './progress-bar-demo'; ], declarations: [ProgressBarDemo], }) -export class ProgressBarDemoModule { -} +export class ProgressBarDemoModule {} diff --git a/src/dev-app/progress-bar/progress-bar-demo.ts b/src/dev-app/progress-bar/progress-bar-demo.ts index 7650e84dfd2f..b709bf7cf1b1 100644 --- a/src/dev-app/progress-bar/progress-bar-demo.ts +++ b/src/dev-app/progress-bar/progress-bar-demo.ts @@ -9,7 +9,6 @@ import {Component} from '@angular/core'; import {ThemePalette} from '@angular/material/core'; - // TODO(josephperrott): Add an automatically filling example progress bar. @Component({ diff --git a/src/dev-app/progress-spinner/progress-spinner-demo-module.ts b/src/dev-app/progress-spinner/progress-spinner-demo-module.ts index c075d3754fc6..2765ea551c15 100644 --- a/src/dev-app/progress-spinner/progress-spinner-demo-module.ts +++ b/src/dev-app/progress-spinner/progress-spinner-demo-module.ts @@ -26,5 +26,4 @@ import {ProgressSpinnerDemo} from './progress-spinner-demo'; ], declarations: [ProgressSpinnerDemo], }) -export class ProgressSpinnerDemoModule { -} +export class ProgressSpinnerDemoModule {} diff --git a/src/dev-app/progress-spinner/progress-spinner-demo.ts b/src/dev-app/progress-spinner/progress-spinner-demo.ts index 2613a8906d39..5f6655ff15ea 100644 --- a/src/dev-app/progress-spinner/progress-spinner-demo.ts +++ b/src/dev-app/progress-spinner/progress-spinner-demo.ts @@ -9,7 +9,6 @@ import {Component} from '@angular/core'; import {ThemePalette} from '@angular/material/core'; - @Component({ selector: 'progress-spinner-demo', templateUrl: 'progress-spinner-demo.html', diff --git a/src/dev-app/radio/radio-demo-module.ts b/src/dev-app/radio/radio-demo-module.ts index c8c33dc14f29..a23dd4fc5264 100644 --- a/src/dev-app/radio/radio-demo-module.ts +++ b/src/dev-app/radio/radio-demo-module.ts @@ -26,5 +26,4 @@ import {RadioDemo} from './radio-demo'; ], declarations: [RadioDemo], }) -export class RadioDemoModule { -} +export class RadioDemoModule {} diff --git a/src/dev-app/radio/radio-demo.ts b/src/dev-app/radio/radio-demo.ts index c6f3e47cd490..c802fe7effa2 100644 --- a/src/dev-app/radio/radio-demo.ts +++ b/src/dev-app/radio/radio-demo.ts @@ -8,7 +8,6 @@ import {Component} from '@angular/core'; - @Component({ selector: 'radio-demo', templateUrl: 'radio-demo.html', @@ -19,10 +18,5 @@ export class RadioDemo { isDisabled: boolean = false; isRequired: boolean = false; favoriteSeason: string = 'Autumn'; - seasonOptions = [ - 'Winter', - 'Spring', - 'Summer', - 'Autumn', - ]; + seasonOptions = ['Winter', 'Spring', 'Summer', 'Autumn']; } diff --git a/src/dev-app/ripple/ripple-demo-module.ts b/src/dev-app/ripple/ripple-demo-module.ts index b93567fe51ce..869a7a0d8679 100644 --- a/src/dev-app/ripple/ripple-demo-module.ts +++ b/src/dev-app/ripple/ripple-demo-module.ts @@ -28,5 +28,4 @@ import {RippleDemo} from './ripple-demo'; ], declarations: [RippleDemo], }) -export class RippleDemoModule { -} +export class RippleDemoModule {} diff --git a/src/dev-app/ripple/ripple-demo.ts b/src/dev-app/ripple/ripple-demo.ts index f18d7575aad7..7ad7864853e0 100644 --- a/src/dev-app/ripple/ripple-demo.ts +++ b/src/dev-app/ripple/ripple-demo.ts @@ -9,7 +9,6 @@ import {Component, ViewChild} from '@angular/core'; import {MatRipple} from '@angular/material/core'; - @Component({ selector: 'ripple-demo', templateUrl: 'ripple-demo.html', @@ -36,7 +35,7 @@ export class RippleDemo { const rippleConfig = { centered: true, persistent: persistent, - animation: disableAnimation ? {enterDuration: 0, exitDuration: 0} : undefined + animation: disableAnimation ? {enterDuration: 0, exitDuration: 0} : undefined, }; this.ripple.launch(0, 0, rippleConfig); @@ -47,5 +46,4 @@ export class RippleDemo { this.ripple.fadeOutAll(); } } - } diff --git a/src/dev-app/routes.ts b/src/dev-app/routes.ts new file mode 100644 index 000000000000..8071764bac18 --- /dev/null +++ b/src/dev-app/routes.ts @@ -0,0 +1,394 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {Routes} from '@angular/router'; +import {DevApp404} from './dev-app/dev-app-404'; +import {DevAppHome} from './dev-app/dev-app-home'; + +export const DEV_APP_ROUTES: Routes = [ + {path: '', component: DevAppHome}, + { + path: 'autocomplete', + loadChildren: () => + import('./autocomplete/autocomplete-demo-module').then(m => m.AutocompleteDemoModule), + }, + { + path: 'badge', + loadChildren: () => import('./badge/badge-demo-module').then(m => m.BadgeDemoModule), + }, + { + path: 'bottom-sheet', + loadChildren: () => + import('./bottom-sheet/bottom-sheet-demo-module').then(m => m.BottomSheetDemoModule), + }, + { + path: 'baseline', + loadChildren: () => import('./baseline/baseline-demo-module').then(m => m.BaselineDemoModule), + }, + { + path: 'button', + loadChildren: () => import('./button/button-demo-module').then(m => m.ButtonDemoModule), + }, + { + path: 'button-toggle', + loadChildren: () => + import('./button-toggle/button-toggle-demo-module').then(m => m.ButtonToggleDemoModule), + }, + { + path: 'card', + loadChildren: () => import('./card/card-demo-module').then(m => m.CardDemoModule), + }, + { + path: 'cdk-experimental-combobox', + loadChildren: () => + import('./cdk-experimental-combobox/cdk-combobox-demo-module').then( + m => m.CdkComboboxDemoModule, + ), + }, + { + path: 'cdk-experimental-listbox', + loadChildren: () => + import('./cdk-experimental-listbox/cdk-listbox-demo-module').then( + m => m.CdkListboxDemoModule, + ), + }, + { + path: 'cdk-experimental-menu', + loadChildren: () => + import('./cdk-experimental-menu/cdk-menu-demo-module').then(m => m.CdkMenuDemoModule), + }, + { + path: 'checkbox', + loadChildren: () => import('./checkbox/checkbox-demo-module').then(m => m.CheckboxDemoModule), + }, + { + path: 'chips', + loadChildren: () => import('./chips/chips-demo-module').then(m => m.ChipsDemoModule), + }, + { + path: 'clipboard', + loadChildren: () => + import('./clipboard/clipboard-demo-module').then(m => m.ClipboardDemoModule), + }, + { + path: 'column-resize', + loadChildren: () => + import('./column-resize/column-resize-demo-module').then(m => m.ColumnResizeDemoModule), + }, + { + path: 'datepicker', + loadChildren: () => + import('./datepicker/datepicker-demo-module').then(m => m.DatepickerDemoModule), + }, + { + path: 'dialog', + loadChildren: () => import('./dialog/dialog-demo-module').then(m => m.DialogDemoModule), + }, + { + path: 'drawer', + loadChildren: () => import('./drawer/drawer-demo-module').then(m => m.DrawerDemoModule), + }, + { + path: 'drag-drop', + loadChildren: () => import('./drag-drop/drag-drop-demo-module').then(m => m.DragDropDemoModule), + }, + { + path: 'expansion', + loadChildren: () => + import('./expansion/expansion-demo-module').then(m => m.ExpansionDemoModule), + }, + { + path: 'focus-origin', + loadChildren: () => + import('./focus-origin/focus-origin-demo-module').then(m => m.FocusOriginDemoModule), + }, + { + path: 'focus-trap', + loadChildren: () => + import('./focus-trap/focus-trap-demo-module').then(m => m.FocusTrapDemoModule), + }, + { + path: 'google-map', + loadChildren: () => + import('./google-map/google-map-demo-module').then(m => m.GoogleMapDemoModule), + }, + { + path: 'grid-list', + loadChildren: () => import('./grid-list/grid-list-demo-module').then(m => m.GridListDemoModule), + }, + { + path: 'icon', + loadChildren: () => import('./icon/icon-demo-module').then(m => m.IconDemoModule), + }, + { + path: 'input', + loadChildren: () => import('./input/input-demo-module').then(m => m.InputDemoModule), + }, + { + path: 'layout', + loadChildren: () => import('./layout/layout-demo-module').then(m => m.LayoutDemoModule), + }, + { + path: 'input-modality', + loadChildren: () => + import('./input-modality/input-modality-detector-demo-module').then( + m => m.InputModalityDetectorDemoModule, + ), + }, + { + path: 'list', + loadChildren: () => import('./list/list-demo-module').then(m => m.ListDemoModule), + }, + { + path: 'live-announcer', + loadChildren: () => + import('./live-announcer/live-announcer-demo-module').then(m => m.LiveAnnouncerDemoModule), + }, + { + path: 'menubar', + loadChildren: () => + import('./menubar/mat-menubar-demo-module').then(m => m.MatMenuBarDemoModule), + }, + { + path: 'mdc-autocomplete', + loadChildren: () => + import('./mdc-autocomplete/mdc-autocomplete-demo-module').then( + m => m.MdcAutocompleteDemoModule, + ), + }, + { + path: 'mdc-button', + loadChildren: () => + import('./mdc-button/mdc-button-demo-module').then(m => m.MdcButtonDemoModule), + }, + { + path: 'mdc-card', + loadChildren: () => import('./mdc-card/mdc-card-demo-module').then(m => m.MdcCardDemoModule), + }, + { + path: 'mdc-checkbox', + loadChildren: () => + import('./mdc-checkbox/mdc-checkbox-demo-module').then(m => m.MdcCheckboxDemoModule), + }, + { + path: 'mdc-progress-bar', + loadChildren: () => + import('./mdc-progress-bar/mdc-progress-bar-demo-module').then( + m => m.MdcProgressBarDemoModule, + ), + }, + { + path: 'mdc-chips', + loadChildren: () => import('./mdc-chips/mdc-chips-demo-module').then(m => m.MdcChipsDemoModule), + }, + { + path: 'mdc-dialog', + loadChildren: () => + import('./mdc-dialog/mdc-dialog-demo-module').then(m => m.MdcDialogDemoModule), + }, + { + path: 'mdc-input', + loadChildren: () => import('./mdc-input/mdc-input-demo-module').then(m => m.MdcInputDemoModule), + }, + { + path: 'mdc-list', + loadChildren: () => import('./mdc-list/mdc-list-demo-module').then(m => m.MdcListDemoModule), + }, + { + path: 'mdc-menu', + loadChildren: () => import('./mdc-menu/mdc-menu-demo-module').then(m => m.MdcMenuDemoModule), + }, + { + path: 'mdc-paginator', + loadChildren: () => + import('./mdc-paginator/mdc-paginator-demo-module').then(m => m.MdcPaginatorDemoModule), + }, + { + path: 'mdc-progress-spinner', + loadChildren: () => + import('./mdc-progress-spinner/mdc-progress-spinner-demo-module').then( + m => m.MdcProgressSpinnerDemoModule, + ), + }, + { + path: 'mdc-radio', + loadChildren: () => import('./mdc-radio/mdc-radio-demo-module').then(m => m.MdcRadioDemoModule), + }, + { + path: 'mdc-select', + loadChildren: () => + import('./mdc-select/mdc-select-demo-module').then(m => m.MdcSelectDemoModule), + }, + { + path: 'mdc-sidenav', + loadChildren: () => + import('./mdc-sidenav/mdc-sidenav-demo-module').then(m => m.MdcSidenavDemoModule), + }, + { + path: 'mdc-snack-bar', + loadChildren: () => + import('./mdc-snack-bar/mdc-snack-bar-demo-module').then(m => m.MdcSnackBarDemoModule), + }, + { + path: 'mdc-slide-toggle', + loadChildren: () => + import('./mdc-slide-toggle/mdc-slide-toggle-demo-module').then( + m => m.MdcSlideToggleDemoModule, + ), + }, + { + path: 'mdc-slider', + loadChildren: () => + import('./mdc-slider/mdc-slider-demo-module').then(m => m.MdcSliderDemoModule), + }, + { + path: 'mdc-table', + loadChildren: () => import('./mdc-table/mdc-table-demo-module').then(m => m.MdcTableDemoModule), + }, + { + path: 'mdc-tabs', + loadChildren: () => import('./mdc-tabs/mdc-tabs-demo-module').then(m => m.MdcTabsDemoModule), + }, + { + path: 'mdc-tooltip', + loadChildren: () => + import('./mdc-tooltip/mdc-tooltip-demo-module').then(m => m.MdcTooltipDemoModule), + }, + { + path: 'menu', + loadChildren: () => import('./menu/menu-demo-module').then(m => m.MenuDemoModule), + }, + { + path: 'paginator', + loadChildren: () => + import('./paginator/paginator-demo-module').then(m => m.PaginatorDemoModule), + }, + { + path: 'platform', + loadChildren: () => import('./platform/platform-demo-module').then(m => m.PlatformDemoModule), + }, + { + path: 'popover-edit', + loadChildren: () => + import('./popover-edit/popover-edit-demo-module').then(m => m.PopoverEditDemoModule), + }, + { + path: 'portal', + loadChildren: () => import('./portal/portal-demo-module').then(m => m.PortalDemoModule), + }, + { + path: 'progress-bar', + loadChildren: () => + import('./progress-bar/progress-bar-demo-module').then(m => m.ProgressBarDemoModule), + }, + { + path: 'progress-spinner', + loadChildren: () => + import('./progress-spinner/progress-spinner-demo-module').then( + m => m.ProgressSpinnerDemoModule, + ), + }, + { + path: 'radio', + loadChildren: () => import('./radio/radio-demo-module').then(m => m.RadioDemoModule), + }, + { + path: 'ripple', + loadChildren: () => import('./ripple/ripple-demo-module').then(m => m.RippleDemoModule), + }, + { + path: 'select', + loadChildren: () => import('./select/select-demo-module').then(m => m.SelectDemoModule), + }, + { + path: 'sidenav', + loadChildren: () => import('./sidenav/sidenav-demo-module').then(m => m.SidenavDemoModule), + }, + { + path: 'slide-toggle', + loadChildren: () => + import('./slide-toggle/slide-toggle-demo-module').then(m => m.SlideToggleDemoModule), + }, + { + path: 'slider', + loadChildren: () => import('./slider/slider-demo-module').then(m => m.SliderDemoModule), + }, + { + path: 'snack-bar', + loadChildren: () => import('./snack-bar/snack-bar-demo-module').then(m => m.SnackBarDemoModule), + }, + { + path: 'stepper', + loadChildren: () => import('./stepper/stepper-demo-module').then(m => m.StepperDemoModule), + }, + { + path: 'table', + loadChildren: () => import('./table/table-demo-module').then(m => m.TableDemoModule), + }, + { + path: 'table-scroll-container', + loadChildren: () => + import('./table-scroll-container/table-scroll-container-demo-module').then( + m => m.TableScrollContainerDemoModule, + ), + }, + { + path: 'tabs', + loadChildren: () => import('./tabs/tabs-demo-module').then(m => m.TabsDemoModule), + }, + { + path: 'toolbar', + loadChildren: () => import('./toolbar/toolbar-demo-module').then(m => m.ToolbarDemoModule), + }, + { + path: 'tooltip', + loadChildren: () => import('./tooltip/tooltip-demo-module').then(m => m.TooltipDemoModule), + }, + { + path: 'tree', + loadChildren: () => import('./tree/tree-demo-module').then(m => m.TreeDemoModule), + }, + { + path: 'typography', + loadChildren: () => + import('./typography/typography-demo-module').then(m => m.TypographyDemoModule), + }, + { + path: 'screen-type', + loadChildren: () => + import('./screen-type/screen-type-demo-module').then(m => m.ScreenTypeDemoModule), + }, + { + path: 'connected-overlay', + loadChildren: () => + import('./connected-overlay/connected-overlay-demo-module').then( + m => m.ConnectedOverlayDemoModule, + ), + }, + { + path: 'virtual-scroll', + loadChildren: () => + import('./virtual-scroll/virtual-scroll-demo-module').then(m => m.VirtualScrollDemoModule), + }, + { + path: 'youtube-player', + loadChildren: () => + import('./youtube-player/youtube-player-demo-module').then(m => m.YouTubePlayerDemoModule), + }, + { + path: 'selection', + loadChildren: () => + import('./selection/selection-demo-module').then(m => m.SelectionDemoModule), + }, + { + path: 'examples', + loadChildren: () => + import('./examples-page/examples-page-module').then(m => m.ExamplesPageModule), + }, + {path: '**', component: DevApp404}, +]; diff --git a/src/dev-app/screen-type/screen-type-demo-module.ts b/src/dev-app/screen-type/screen-type-demo-module.ts index 81d80ee6397b..f069f9aac520 100644 --- a/src/dev-app/screen-type/screen-type-demo-module.ts +++ b/src/dev-app/screen-type/screen-type-demo-module.ts @@ -24,5 +24,4 @@ import {ScreenTypeDemo} from './screen-type-demo'; ], declarations: [ScreenTypeDemo], }) -export class ScreenTypeDemoModule { -} +export class ScreenTypeDemoModule {} diff --git a/src/dev-app/screen-type/screen-type-demo.scss b/src/dev-app/screen-type/screen-type-demo.scss index 055048e12d81..d479128b1a69 100644 --- a/src/dev-app/screen-type/screen-type-demo.scss +++ b/src/dev-app/screen-type/screen-type-demo.scss @@ -7,7 +7,7 @@ .mat-grid-tile { outline: 1px solid lightgray; - .mat-figure { + .mat-grid-tile-content { flex-direction: column; } } diff --git a/src/dev-app/screen-type/screen-type-demo.ts b/src/dev-app/screen-type/screen-type-demo.ts index 37428e65bf2a..55d2ef3cd750 100644 --- a/src/dev-app/screen-type/screen-type-demo.ts +++ b/src/dev-app/screen-type/screen-type-demo.ts @@ -10,7 +10,6 @@ import {BreakpointObserver, Breakpoints, BreakpointState} from '@angular/cdk/lay import {Component} from '@angular/core'; import {Observable} from 'rxjs'; - @Component({ selector: 'screen-type', templateUrl: 'screen-type-demo.html', @@ -24,11 +23,12 @@ export class ScreenTypeDemo { isLandscape: Observable; constructor(breakpointObserver: BreakpointObserver) { - this.isHandset = breakpointObserver.observe([Breakpoints.HandsetLandscape, - Breakpoints.HandsetPortrait]); + this.isHandset = breakpointObserver.observe([ + Breakpoints.HandsetLandscape, + Breakpoints.HandsetPortrait, + ]); this.isTablet = breakpointObserver.observe(Breakpoints.Tablet); - this.isWeb = breakpointObserver.observe([Breakpoints.WebLandscape, - Breakpoints.WebPortrait]); + this.isWeb = breakpointObserver.observe([Breakpoints.WebLandscape, Breakpoints.WebPortrait]); this.isPortrait = breakpointObserver.observe('(orientation: portrait)'); this.isLandscape = breakpointObserver.observe('(orientation: landscape)'); } diff --git a/src/dev-app/select/select-demo-module.ts b/src/dev-app/select/select-demo-module.ts index 85fe59944a14..29abe3ff20c4 100644 --- a/src/dev-app/select/select-demo-module.ts +++ b/src/dev-app/select/select-demo-module.ts @@ -35,5 +35,4 @@ import {SelectDemo} from './select-demo'; ], declarations: [SelectDemo], }) -export class SelectDemoModule { -} +export class SelectDemoModule {} diff --git a/src/dev-app/select/select-demo.ts b/src/dev-app/select/select-demo.ts index 5ee2f63793de..37c9e792a555 100644 --- a/src/dev-app/select/select-demo.ts +++ b/src/dev-app/select/select-demo.ts @@ -36,7 +36,7 @@ export class SelectDemo { pokemonDisabled = false; showSelect = false; currentDrink: string; - currentDrinkObject: {}|undefined = {value: 'tea-5', viewValue: 'Tea'}; + currentDrinkObject: {} | undefined = {value: 'tea-5', viewValue: 'Tea'}; currentPokemon: string[]; currentPokemonFromGroup: string; currentDigimon: string; @@ -55,7 +55,7 @@ export class SelectDemo { {value: null, viewValue: 'None'}, {value: 'steak-0', viewValue: 'Steak'}, {value: 'pizza-1', viewValue: 'Pizza'}, - {value: 'tacos-2', viewValue: 'Tacos'} + {value: 'tacos-2', viewValue: 'Tacos'}, ]; drinks = [ @@ -63,7 +63,7 @@ export class SelectDemo { { value: 'long-name-1', viewValue: 'Decaf Chocolate Brownie Vanilla Gingerbread Frappuccino', - disabled: false + disabled: false, }, {value: 'water-2', viewValue: 'Water', disabled: false}, {value: 'pepper-3', viewValue: 'Dr. Pepper', disabled: false}, @@ -85,9 +85,9 @@ export class SelectDemo { ]; availableThemes = [ - {value: 'primary', name: 'Primary' }, - {value: 'accent', name: 'Accent' }, - {value: 'warn', name: 'Warn' } + {value: 'primary', name: 'Primary'}, + {value: 'accent', name: 'Accent'}, + {value: 'warn', name: 'Warn'}, ]; pokemonGroups = [ @@ -96,16 +96,16 @@ export class SelectDemo { pokemon: [ {value: 'bulbasaur-0', viewValue: 'Bulbasaur'}, {value: 'oddish-1', viewValue: 'Oddish'}, - {value: 'bellsprout-2', viewValue: 'Bellsprout'} - ] + {value: 'bellsprout-2', viewValue: 'Bellsprout'}, + ], }, { name: 'Water', pokemon: [ {value: 'squirtle-3', viewValue: 'Squirtle'}, {value: 'psyduck-4', viewValue: 'Psyduck'}, - {value: 'horsea-5', viewValue: 'Horsea'} - ] + {value: 'horsea-5', viewValue: 'Horsea'}, + ], }, { name: 'Fire', @@ -113,16 +113,16 @@ export class SelectDemo { pokemon: [ {value: 'charmander-6', viewValue: 'Charmander'}, {value: 'vulpix-7', viewValue: 'Vulpix'}, - {value: 'flareon-8', viewValue: 'Flareon'} - ] + {value: 'flareon-8', viewValue: 'Flareon'}, + ], }, { name: 'Psychic', pokemon: [ {value: 'mew-9', viewValue: 'Mew'}, {value: 'mewtwo-10', viewValue: 'Mewtwo'}, - ] - } + ], + }, ]; digimon = [ @@ -131,7 +131,7 @@ export class SelectDemo { {value: 'sinduramon-2', viewValue: 'Sinduramon'}, {value: 'pajiramon-3', viewValue: 'Pajiramon'}, {value: 'vajiramon-4', viewValue: 'Vajiramon'}, - {value: 'indramon-5', viewValue: 'Indramon'} + {value: 'indramon-5', viewValue: 'Indramon'}, ]; constructor(private _dialog: MatDialog) {} diff --git a/src/dev-app/selection/selection-demo-module.ts b/src/dev-app/selection/selection-demo-module.ts index 8fe8841bab70..2b67c782d34a 100644 --- a/src/dev-app/selection/selection-demo-module.ts +++ b/src/dev-app/selection/selection-demo-module.ts @@ -7,8 +7,7 @@ */ import {CdkSelectionExamplesModule} from '@angular/components-examples/cdk-experimental/selection'; -import {MatSelectionExamplesModule} from -'@angular/components-examples/material-experimental/selection'; +import {MatSelectionExamplesModule} from '@angular/components-examples/material-experimental/selection'; import {NgModule} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {RouterModule} from '@angular/router'; @@ -24,5 +23,4 @@ import {SelectionDemo} from './selection-demo'; ], declarations: [SelectionDemo], }) -export class SelectionDemoModule { -} +export class SelectionDemoModule {} diff --git a/src/dev-app/selection/selection-demo.ts b/src/dev-app/selection/selection-demo.ts index a7d8f1c4fa4b..28e1dde78bd0 100644 --- a/src/dev-app/selection/selection-demo.ts +++ b/src/dev-app/selection/selection-demo.ts @@ -23,5 +23,4 @@ import {Component} from '@angular/core'; `, }) -export class SelectionDemo { -} +export class SelectionDemo {} diff --git a/src/dev-app/sidenav/sidenav-demo-module.ts b/src/dev-app/sidenav/sidenav-demo-module.ts index ba920d5e05f9..17d2837dac85 100644 --- a/src/dev-app/sidenav/sidenav-demo-module.ts +++ b/src/dev-app/sidenav/sidenav-demo-module.ts @@ -28,5 +28,4 @@ import {SidenavDemo} from './sidenav-demo'; ], declarations: [SidenavDemo], }) -export class SidenavDemoModule { -} +export class SidenavDemoModule {} diff --git a/src/dev-app/sidenav/sidenav-demo.ts b/src/dev-app/sidenav/sidenav-demo.ts index b1641c3c4838..ba3752182513 100644 --- a/src/dev-app/sidenav/sidenav-demo.ts +++ b/src/dev-app/sidenav/sidenav-demo.ts @@ -9,12 +9,10 @@ import {Component} from '@angular/core'; import {MatDrawerMode} from '@angular/material/sidenav'; - @Component({ selector: 'sidenav-demo', templateUrl: 'sidenav-demo.html', styleUrls: ['sidenav-demo.css'], - }) export class SidenavDemo { isLaunched = false; @@ -28,6 +26,10 @@ export class SidenavDemo { get mode(): MatDrawerMode { return (['side', 'over', 'push'] as MatDrawerMode[])[this.modeIndex]; } - get fixedTop() { return this.fixed && this.showHeader && !this.coverHeader ? 64 : 0; } - get fixedBottom() { return this.fixed && this.showFooter && !this.coverHeader ? 64 : 0; } + get fixedTop() { + return this.fixed && this.showHeader && !this.coverHeader ? 64 : 0; + } + get fixedBottom() { + return this.fixed && this.showFooter && !this.coverHeader ? 64 : 0; + } } diff --git a/src/dev-app/slide-toggle/slide-toggle-demo-module.ts b/src/dev-app/slide-toggle/slide-toggle-demo-module.ts index cf601c312e5f..50519d7bc3d7 100644 --- a/src/dev-app/slide-toggle/slide-toggle-demo-module.ts +++ b/src/dev-app/slide-toggle/slide-toggle-demo-module.ts @@ -22,5 +22,4 @@ import {SlideToggleDemo} from './slide-toggle-demo'; ], declarations: [SlideToggleDemo], }) -export class SlideToggleDemoModule { -} +export class SlideToggleDemoModule {} diff --git a/src/dev-app/slide-toggle/slide-toggle-demo.ts b/src/dev-app/slide-toggle/slide-toggle-demo.ts index cb54156d5f9e..1b327e32e86a 100644 --- a/src/dev-app/slide-toggle/slide-toggle-demo.ts +++ b/src/dev-app/slide-toggle/slide-toggle-demo.ts @@ -8,7 +8,6 @@ import {Component} from '@angular/core'; - @Component({ selector: 'slide-toggle-demo', templateUrl: 'slide-toggle-demo.html', @@ -20,5 +19,4 @@ export class SlideToggleDemo { onFormSubmit() { alert(`You submitted the form.`); } - } diff --git a/src/dev-app/slider/slider-demo-module.ts b/src/dev-app/slider/slider-demo-module.ts index 816a666c9eec..b31b89f6da8f 100644 --- a/src/dev-app/slider/slider-demo-module.ts +++ b/src/dev-app/slider/slider-demo-module.ts @@ -22,5 +22,4 @@ import {SliderDemo} from './slider-demo'; ], declarations: [SliderDemo], }) -export class SliderDemoModule { -} +export class SliderDemoModule {} diff --git a/src/dev-app/slider/slider-demo.ts b/src/dev-app/slider/slider-demo.ts index 452ac8185c72..4fd9d19f725f 100644 --- a/src/dev-app/slider/slider-demo.ts +++ b/src/dev-app/slider/slider-demo.ts @@ -8,7 +8,6 @@ import {Component} from '@angular/core'; - @Component({ selector: 'slider-demo', templateUrl: 'slider-demo.html', diff --git a/src/dev-app/snack-bar/snack-bar-demo-module.ts b/src/dev-app/snack-bar/snack-bar-demo-module.ts index 1896c7227f08..f5f5fc4e1ebc 100644 --- a/src/dev-app/snack-bar/snack-bar-demo-module.ts +++ b/src/dev-app/snack-bar/snack-bar-demo-module.ts @@ -32,5 +32,4 @@ import {SnackBarDemo} from './snack-bar-demo'; ], declarations: [SnackBarDemo], }) -export class SnackBarDemoModule { -} +export class SnackBarDemoModule {} diff --git a/src/dev-app/snack-bar/snack-bar-demo.ts b/src/dev-app/snack-bar/snack-bar-demo.ts index 66463ccade07..e87f5ed21aea 100644 --- a/src/dev-app/snack-bar/snack-bar-demo.ts +++ b/src/dev-app/snack-bar/snack-bar-demo.ts @@ -15,7 +15,6 @@ import { MatSnackBarVerticalPosition, } from '@angular/material/snack-bar'; - @Component({ selector: 'snack-bar-demo', styleUrls: ['snack-bar-demo.css'], diff --git a/src/dev-app/stepper/stepper-demo-module.ts b/src/dev-app/stepper/stepper-demo-module.ts index 4a46fca4659a..dcaad3bbeb35 100644 --- a/src/dev-app/stepper/stepper-demo-module.ts +++ b/src/dev-app/stepper/stepper-demo-module.ts @@ -33,5 +33,4 @@ import {StepperDemo} from './stepper-demo'; ], declarations: [StepperDemo], }) -export class StepperDemoModule { -} +export class StepperDemoModule {} diff --git a/src/dev-app/stepper/stepper-demo.html b/src/dev-app/stepper/stepper-demo.html index 6970e76cf078..9b6004bb2d8d 100644 --- a/src/dev-app/stepper/stepper-demo.html +++ b/src/dev-app/stepper/stepper-demo.html @@ -4,6 +4,9 @@

Disable header ripple

+

+ Vertical +

- +

- +

Linear Horizontal Stepper Demo using a different form for each step

- @@ -116,11 +124,11 @@

Linear Horizontal Stepper Demo using a different form for each step

- +

Vertical Stepper Demo

Make steps non-editable - + Fill out your name @@ -172,10 +180,10 @@

Vertical Stepper Demo

-
+

Horizontal Stepper Demo with Text Label

- + First name @@ -219,10 +227,10 @@

Horizontal Stepper Demo with Text Label

-
+

Horizontal Stepper Demo with Templated Label

- + {{step.label}} @@ -234,15 +242,15 @@

Horizontal Stepper Demo with Templated Label

-
+

Stepper with autosize textarea

- + Autosize textarea - + diff --git a/src/dev-app/stepper/stepper-demo.ts b/src/dev-app/stepper/stepper-demo.ts index 4df50cef9d65..12d87cec90f3 100644 --- a/src/dev-app/stepper/stepper-demo.ts +++ b/src/dev-app/stepper/stepper-demo.ts @@ -10,7 +10,6 @@ import {Component, OnInit} from '@angular/core'; import {ThemePalette} from '@angular/material/core'; import {AbstractControl, FormBuilder, FormGroup, Validators} from '@angular/forms'; - @Component({ selector: 'stepper-demo', templateUrl: 'stepper-demo.html', @@ -21,6 +20,7 @@ export class StepperDemo implements OnInit { isNonEditable = false; disableRipple = false; showLabelBottom = false; + isVertical = false; nameFormGroup: FormGroup; emailFormGroup: FormGroup; @@ -29,21 +29,23 @@ export class StepperDemo implements OnInit { {label: 'Confirm your name', content: 'Last name, First name.'}, {label: 'Confirm your contact information', content: '123-456-7890'}, {label: 'Confirm your address', content: '1600 Amphitheater Pkwy MTV'}, - {label: 'You are now done', content: 'Finished!'} + {label: 'You are now done', content: 'Finished!'}, ]; - availableThemes: {value: ThemePalette, name: string}[] = [ + availableThemes: {value: ThemePalette; name: string}[] = [ {value: 'primary', name: 'Primary'}, {value: 'accent', name: 'Accent'}, - {value: 'warn', name: 'Warn'} + {value: 'warn', name: 'Warn'}, ]; theme = this.availableThemes[0].value; /** Returns a FormArray with the name 'formArray'. */ - get formArray(): AbstractControl | null { return this.formGroup.get('formArray'); } + get formArray(): AbstractControl | null { + return this.formGroup.get('formArray'); + } - constructor(private _formBuilder: FormBuilder) { } + constructor(private _formBuilder: FormBuilder) {} ngOnInit() { this.formGroup = this._formBuilder.group({ @@ -53,9 +55,9 @@ export class StepperDemo implements OnInit { lastNameFormCtrl: ['', Validators.required], }), this._formBuilder.group({ - emailFormCtrl: ['', Validators.email] + emailFormCtrl: ['', Validators.email], }), - ]) + ]), }); this.nameFormGroup = this._formBuilder.group({ @@ -64,7 +66,7 @@ export class StepperDemo implements OnInit { }); this.emailFormGroup = this._formBuilder.group({ - emailCtrl: ['', Validators.email] + emailCtrl: ['', Validators.email], }); } } diff --git a/src/dev-app/table-scroll-container/BUILD.bazel b/src/dev-app/table-scroll-container/BUILD.bazel new file mode 100644 index 000000000000..9f6464ec3097 --- /dev/null +++ b/src/dev-app/table-scroll-container/BUILD.bazel @@ -0,0 +1,27 @@ +load("//tools:defaults.bzl", "ng_module", "sass_binary") + +package(default_visibility = ["//visibility:public"]) + +ng_module( + name = "table-scroll-container", + srcs = glob(["**/*.ts"]), + assets = [ + "table-scroll-container-demo.html", + ":table_scroll_container_demo_scss", + ], + deps = [ + "//src/cdk-experimental/table-scroll-container", + "//src/material-experimental/mdc-button", + "//src/material-experimental/mdc-table", + "//src/material/button-toggle", + "//src/material/table", + "@npm//@angular/common", + "@npm//@angular/core", + "@npm//@angular/router", + ], +) + +sass_binary( + name = "table_scroll_container_demo_scss", + src = "table-scroll-container-demo.scss", +) diff --git a/src/dev-app/table-scroll-container/table-scroll-container-demo-module.ts b/src/dev-app/table-scroll-container/table-scroll-container-demo-module.ts new file mode 100644 index 000000000000..04f58218ea3e --- /dev/null +++ b/src/dev-app/table-scroll-container/table-scroll-container-demo-module.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {NgModule} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {CdkTableScrollContainerModule} from '@angular/cdk-experimental/table-scroll-container'; +import {MatButtonModule} from '@angular/material-experimental/mdc-button'; +import {MatButtonToggleModule} from '@angular/material/button-toggle'; +/*import {MatTableModule} from '@angular/material-experimental/mdc-table';*/ +import {MatTableModule} from '@angular/material/table'; +import {RouterModule} from '@angular/router'; +import {TableScrollContainerDemo} from './table-scroll-container-demo'; + +@NgModule({ + imports: [ + CdkTableScrollContainerModule, + CommonModule, + MatButtonModule, + MatButtonToggleModule, + MatTableModule, + RouterModule.forChild([{path: '', component: TableScrollContainerDemo}]), + ], + declarations: [TableScrollContainerDemo], +}) +export class TableScrollContainerDemoModule {} diff --git a/src/dev-app/table-scroll-container/table-scroll-container-demo.html b/src/dev-app/table-scroll-container/table-scroll-container-demo.html new file mode 100644 index 000000000000..21aa8b40398d --- /dev/null +++ b/src/dev-app/table-scroll-container/table-scroll-container-demo.html @@ -0,0 +1,80 @@ +
+ + +
+ +
+ Sticky Headers: + + Row 1 + Row 2 + +
+ +
+ Sticky Footers: + + Row 1 + Row 2 + +
+ +
+ Sticky Columns: + + Position + Name + Weight + Symbol + +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Position {{element.position}} Position Footer Name {{element.name}} Name Footer Weight {{element.weight}} Weight Footer Symbol {{element.symbol}} Symbol Footer Filler header cell Filler data cell Filler footer cell
+
diff --git a/src/dev-app/table-scroll-container/table-scroll-container-demo.scss b/src/dev-app/table-scroll-container/table-scroll-container-demo.scss new file mode 100644 index 000000000000..5d6a5e701483 --- /dev/null +++ b/src/dev-app/table-scroll-container/table-scroll-container-demo.scss @@ -0,0 +1,40 @@ +.example-container { + height: 400px; + overflow: auto; +} + +.mat-table-sticky { + background: #59abfd; + opacity: 1; +} + +.example-sticky-toggle-group { + margin: 8px; +} + +.mat-column-filler { + padding: 0 8px; + font-size: 10px; + text-align: center; +} + +.mat-header-cell, .mat-footer-cell, .mat-cell { + min-width: 80px; + box-sizing: border-box; +} + +// A width and/or height must be specified to get the browser to show any customizations to +// the scrollbar. +.cdk-table-scroll-container::-webkit-scrollbar { + background: #59abfd; + height: 10px; + width: 10px; +} + +.cdk-table-scroll-container::-webkit-scrollbar-track { + background: white; +} + +.cdk-table-scroll-container::-webkit-scrollbar-thumb { + background: gray; +} diff --git a/src/dev-app/table-scroll-container/table-scroll-container-demo.ts b/src/dev-app/table-scroll-container/table-scroll-container-demo.ts new file mode 100644 index 000000000000..16fee97ad589 --- /dev/null +++ b/src/dev-app/table-scroll-container/table-scroll-container-demo.ts @@ -0,0 +1,61 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {Component} from '@angular/core'; +import {MatButtonToggleGroup} from '@angular/material/button-toggle'; + +/** + * @title Tables with toggle-able sticky headers, footers, and columns + */ +@Component({ + selector: 'table-scroll-container-demo', + styleUrls: ['table-scroll-container-demo.css'], + templateUrl: 'table-scroll-container-demo.html', +}) +export class TableScrollContainerDemo { + displayedColumns: string[] = []; + dataSource = ELEMENT_DATA; + + tables = [0]; + + constructor() { + this.displayedColumns.length = 24; + this.displayedColumns.fill('filler'); + + // The first two columns should be position and name; the last two columns: weight, symbol + this.displayedColumns[0] = 'position'; + this.displayedColumns[1] = 'name'; + this.displayedColumns[22] = 'weight'; + this.displayedColumns[23] = 'symbol'; + } + + /** Whether the button toggle group contains the id as an active value. */ + isSticky(buttonToggleGroup: MatButtonToggleGroup, id: string) { + return (buttonToggleGroup.value || []).indexOf(id) !== -1; + } +} + +export interface PeriodicElement { + name: string; + position: number; + weight: number; + symbol: string; +} + +const ELEMENT_DATA: PeriodicElement[] = [ + {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'}, + {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}, + {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'}, + {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'}, + {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'}, + {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'}, + {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'}, + {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'}, + {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'}, + {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'}, +]; diff --git a/src/dev-app/table/table-demo-module.ts b/src/dev-app/table/table-demo-module.ts index f461be951e77..603c3a75bdb9 100644 --- a/src/dev-app/table/table-demo-module.ts +++ b/src/dev-app/table/table-demo-module.ts @@ -20,5 +20,4 @@ import {TableDemo} from './table-demo'; ], declarations: [TableDemo], }) -export class TableDemoModule { -} +export class TableDemoModule {} diff --git a/src/dev-app/table/table-demo.html b/src/dev-app/table/table-demo.html index c4c07b9e4783..4b85241a1952 100644 --- a/src/dev-app/table/table-demo.html +++ b/src/dev-app/table/table-demo.html @@ -1,6 +1,9 @@

Cdk table basic

+

Cdk table with recycled rows

+ +

Cdk table basic with fixed column widths

@@ -10,6 +13,9 @@

Cdk table basic flex

Table basic

+

Table basic with recycled rows

+ +

Table basic flex

diff --git a/src/dev-app/tabs/tabs-demo-module.ts b/src/dev-app/tabs/tabs-demo-module.ts index 88de1465e711..cf55e8143e61 100644 --- a/src/dev-app/tabs/tabs-demo-module.ts +++ b/src/dev-app/tabs/tabs-demo-module.ts @@ -20,5 +20,4 @@ import {TabsDemo} from './tabs-demo'; ], declarations: [TabsDemo], }) -export class TabsDemoModule { -} +export class TabsDemoModule {} diff --git a/src/dev-app/theme.scss b/src/dev-app/theme.scss index 91b27fe001ba..8ae0901816f4 100644 --- a/src/dev-app/theme.scss +++ b/src/dev-app/theme.scss @@ -1,67 +1,46 @@ -@import '../material/core/color/all-color'; -@import '../material/core/density/private/all-density'; -@import '../material/core/focus-indicators/focus-indicators'; -@import '../material/core/theming/all-theme'; -@import '../material-experimental/column-resize/column-resize'; -@import '../material-experimental/mdc-helpers/mdc-helpers'; -@import '../material-experimental/mdc-helpers/focus-indicators'; -@import '../material-experimental/mdc-color/all-color'; -@import '../material-experimental/mdc-theming/all-theme'; -@import '../material-experimental/mdc-typography/all-typography'; -@import '../material-experimental/mdc-density/all-density'; -@import '../material-experimental/mdc-slider/slider-theme'; -@import '../material-experimental/popover-edit/popover-edit'; +@use '../material' as mat; +@use '../material-experimental' as experimental; +@use '../material-experimental/mdc-slider/slider-theme' as mdc-slider-theme; +@use '../material/core/density/private/all-density' as private-all-density; // Plus imports for other components in your app. -// Include the common styles for Angular Material. We include this here so that you only -// have to load a single css file for Angular Material in your app. -// **Be sure that you only ever include this mixin once!** -@include mat-core(); -@include angular-material-mdc-typography(); -@include mat-popover-edit-typography(mat-typography-config()); - -// Include base styles for strong focus indicators. -.demo-strong-focus { - @include mat-strong-focus-indicators(); - @include mat-mdc-strong-focus-indicators(); -} - -// Define the default theme (same as the example above). -$candy-app-primary: mat-palette($mat-indigo); -$candy-app-accent: mat-palette($mat-pink, A200, A100, A400); -$candy-app-theme: mat-light-theme(( +// Define the default (light) theme. +$candy-app-primary: mat.define-palette(mat.$indigo-palette); +$candy-app-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400); +$candy-app-theme: mat.define-light-theme(( + // Define the default colors for our app. color: ( primary: $candy-app-primary, accent: $candy-app-accent - ) + ), + // Define the default typography for our app. + // TODO(mmalerba): Update to `mat-mdc-typography-config()` once non-MDC components can handle + // 2018 configs. + typography: mat.define-typography-config(), + // Define the default density level for our app. + density: 0, )); -// Include the default theme styles. -@include angular-material-theme($candy-app-theme); -@include angular-material-mdc-theme($candy-app-theme); -@include mat-column-resize-theme($candy-app-theme); -@include mat-popover-edit-theme($candy-app-theme); - -// We add this in manually for now, because it isn't included in `angular-material-mdc-theme`. -@include mat-mdc-slider-theme($candy-app-theme); +// Include the common styles for Angular Material. We include this here so that you only +// have to load a single css file for Angular Material in your app. +// **Be sure that you only ever include this mixin once!** +@include mat.core($candy-app-theme); -// Define an alternate dark theme. -$dark-primary: mat-palette($mat-blue-grey); -$dark-accent: mat-palette($mat-amber, A200, A100, A400); -$dark-warn: mat-palette($mat-deep-orange); -$dark-theme: mat-dark-theme(( - color: ( - primary: $dark-primary, - accent: $dark-accent, - warn: $dark-warn - ) -)); +// Include the default theme styles. +@include mat.all-component-themes($candy-app-theme); +@include experimental.all-mdc-component-themes($candy-app-theme); +@include experimental.column-resize-theme($candy-app-theme); +@include experimental.popover-edit-theme($candy-app-theme); -// Include the default theme for focus indicators. .demo-strong-focus { - @include mat-strong-focus-indicators-theme($candy-app-theme); - @include mat-mdc-strong-focus-indicators-theme($candy-app-theme); + // Include base styles for strong focus indicators. + @include mat.strong-focus-indicators(); + @include experimental.mdc-strong-focus-indicators(); + + // Include the default theme for focus indicators. + @include mat.strong-focus-indicators-theme($candy-app-theme); + @include experimental.mdc-strong-focus-indicators-theme($candy-app-theme); } // Include the alternative theme styles inside of a block with a CSS class. You can make this @@ -69,17 +48,25 @@ $dark-theme: mat-dark-theme(( // `.demo-unicorn-dark-theme` will be affected by this alternate dark theme instead of the // default theme. .demo-unicorn-dark-theme { - @include angular-material-color($dark-theme); - @include angular-material-mdc-color($dark-theme); - @include mat-column-resize-color($dark-theme); - @include mat-popover-edit-color($dark-theme); - @include mat-mdc-slider-color($dark-theme); -} + // Create the color palettes used in our dark theme. + $dark-primary: mat.define-palette(mat.$blue-grey-palette); + $dark-accent: mat.define-palette(mat.$amber-palette, A200, A100, A400); + $dark-warn: mat.define-palette(mat.$deep-orange-palette); + $dark-colors: mat.define-dark-theme($dark-primary, $dark-accent, $dark-warn); -// Include the dark theme for focus indicators. -.demo-unicorn-dark-theme.demo-strong-focus { - @include mat-strong-focus-indicators-color($dark-theme); - @include mat-mdc-strong-focus-indicators-color($dark-theme); + // Include the dark theme color styles. + @include mat.all-component-colors($dark-colors); + @include experimental.all-mdc-component-colors($dark-colors); + @include experimental.column-resize-color($dark-colors); + @include experimental.popover-edit-color($dark-colors); + // We add this in manually for now, because it isn't included in `all-mdc-component-themes`. + @include mdc-slider-theme.color($dark-colors); + + // Include the dark theme colors for focus indicators. + &.demo-strong-focus { + @include mat.strong-focus-indicators-color($dark-colors); + @include experimental.mdc-strong-focus-indicators-color($dark-colors); + } } // Create classes for all density scales which are supported by all MDC-based components. @@ -88,7 +75,7 @@ $dark-theme: mat-dark-theme(( $density-scales: (-1, -2, minimum, maximum); @each $density in $density-scales { .demo-density-#{$density} { - @include angular-material-density($density); - @include angular-material-mdc-density($density); + @include private-all-density.all-component-densities($density); + @include experimental.all-mdc-component-densities($density); } } diff --git a/src/dev-app/toolbar/toolbar-demo-module.ts b/src/dev-app/toolbar/toolbar-demo-module.ts index 0529dcdae599..fd008b1e96ba 100644 --- a/src/dev-app/toolbar/toolbar-demo-module.ts +++ b/src/dev-app/toolbar/toolbar-demo-module.ts @@ -30,5 +30,4 @@ import {ToolbarExamplesModule} from '@angular/components-examples/material/toolb ], declarations: [ToolbarDemo], }) -export class ToolbarDemoModule { -} +export class ToolbarDemoModule {} diff --git a/src/dev-app/toolbar/toolbar-demo.ts b/src/dev-app/toolbar/toolbar-demo.ts index 204ed2563a12..531a7cd3baf4 100644 --- a/src/dev-app/toolbar/toolbar-demo.ts +++ b/src/dev-app/toolbar/toolbar-demo.ts @@ -8,7 +8,6 @@ import {Component} from '@angular/core'; - @Component({ selector: 'toolbar-demo', templateUrl: 'toolbar-demo.html', diff --git a/src/dev-app/tooltip/tooltip-demo-module.ts b/src/dev-app/tooltip/tooltip-demo-module.ts index 6d3e409ba1df..dc1443dc9bee 100644 --- a/src/dev-app/tooltip/tooltip-demo-module.ts +++ b/src/dev-app/tooltip/tooltip-demo-module.ts @@ -12,11 +12,7 @@ import {RouterModule} from '@angular/router'; import {TooltipDemo} from './tooltip-demo'; @NgModule({ - imports: [ - TooltipExamplesModule, - RouterModule.forChild([{path: '', component: TooltipDemo}]), - ], + imports: [TooltipExamplesModule, RouterModule.forChild([{path: '', component: TooltipDemo}])], declarations: [TooltipDemo], }) -export class TooltipDemoModule { -} +export class TooltipDemoModule {} diff --git a/src/dev-app/tree/tree-demo-module.ts b/src/dev-app/tree/tree-demo-module.ts index 3c77c15e283e..e7f94d54632a 100644 --- a/src/dev-app/tree/tree-demo-module.ts +++ b/src/dev-app/tree/tree-demo-module.ts @@ -42,5 +42,4 @@ import {TreeDemo} from './tree-demo'; ], declarations: [TreeDemo], }) -export class TreeDemoModule { -} +export class TreeDemoModule {} diff --git a/src/dev-app/tsconfig.json b/src/dev-app/tsconfig.json index 970d538c1003..7e17e7c5ce54 100644 --- a/src/dev-app/tsconfig.json +++ b/src/dev-app/tsconfig.json @@ -3,7 +3,6 @@ "extends": "../../tsconfig.json", "compilerOptions": { // Needed for Moment.js since it doesn't have a default export. - "allowSyntheticDefaultImports": true, "rootDir": "..", "baseUrl": ".", "paths": { @@ -14,6 +13,8 @@ "@angular/cdk-experimental/*": ["../cdk-experimental/*"], "@angular/cdk-experimental": ["../cdk-experimental"], "@angular/material-moment-adapter": ["../material-moment-adapter/public-api.ts"], + "@angular/material-luxon-adapter": ["../material-luxon-adapter/public-api.ts"], + "@angular/material-date-fns-adapter": ["../material-date-fns-adapter/public-api.ts"], "@angular/google-maps": ["../google-maps"], "@angular/components-examples": ["../components-examples"], "@angular/components-examples/*": ["../components-examples/*"], diff --git a/src/dev-app/typography/typography-demo-module.ts b/src/dev-app/typography/typography-demo-module.ts index 346f730846c1..978675d2315f 100644 --- a/src/dev-app/typography/typography-demo-module.ts +++ b/src/dev-app/typography/typography-demo-module.ts @@ -11,10 +11,7 @@ import {RouterModule} from '@angular/router'; import {TypographyDemo} from './typography-demo'; @NgModule({ - imports: [ - RouterModule.forChild([{path: '', component: TypographyDemo}]), - ], + imports: [RouterModule.forChild([{path: '', component: TypographyDemo}])], declarations: [TypographyDemo], }) -export class TypographyDemoModule { -} +export class TypographyDemoModule {} diff --git a/src/dev-app/typography/typography-demo.ts b/src/dev-app/typography/typography-demo.ts index 7240f1610bb8..5628a5883ace 100644 --- a/src/dev-app/typography/typography-demo.ts +++ b/src/dev-app/typography/typography-demo.ts @@ -8,10 +8,9 @@ import {Component} from '@angular/core'; - @Component({ selector: 'typography-demo', templateUrl: 'typography-demo.html', styleUrls: ['typography-demo.css'], }) -export class TypographyDemo { } +export class TypographyDemo {} diff --git a/src/dev-app/virtual-scroll/virtual-scroll-demo-module.ts b/src/dev-app/virtual-scroll/virtual-scroll-demo-module.ts index b6c2c09359ce..ad97734e75e0 100644 --- a/src/dev-app/virtual-scroll/virtual-scroll-demo-module.ts +++ b/src/dev-app/virtual-scroll/virtual-scroll-demo-module.ts @@ -32,5 +32,4 @@ import {VirtualScrollDemo} from './virtual-scroll-demo'; ], declarations: [VirtualScrollDemo], }) -export class VirtualScrollDemoModule { -} +export class VirtualScrollDemoModule {} diff --git a/src/dev-app/virtual-scroll/virtual-scroll-demo.html b/src/dev-app/virtual-scroll/virtual-scroll-demo.html index 40792b7aab14..7ada2fe5a921 100644 --- a/src/dev-app/virtual-scroll/virtual-scroll-demo.html +++ b/src/dev-app/virtual-scroll/virtual-scroll-demo.html @@ -170,3 +170,11 @@

Use with <table>

+ +

Append only

+ +
+ Item #{{i}} - ({{size}}px) +
+
diff --git a/src/dev-app/virtual-scroll/virtual-scroll-demo.scss b/src/dev-app/virtual-scroll/virtual-scroll-demo.scss index 0aa6a2a48e6f..3fcffe2c52c2 100644 --- a/src/dev-app/virtual-scroll/virtual-scroll-demo.scss +++ b/src/dev-app/virtual-scroll/virtual-scroll-demo.scss @@ -15,9 +15,7 @@ } .demo-item { - -ms-writing-mode: tb-lr; -webkit-writing-mode: vertical-lr; - /* stylelint-disable-next-line material/no-prefixes */ writing-mode: vertical-lr; } } diff --git a/src/dev-app/virtual-scroll/virtual-scroll-demo.ts b/src/dev-app/virtual-scroll/virtual-scroll-demo.ts index a5ef87c28d1b..be1a432d01be 100644 --- a/src/dev-app/virtual-scroll/virtual-scroll-demo.ts +++ b/src/dev-app/virtual-scroll/virtual-scroll-demo.ts @@ -10,13 +10,11 @@ import {CdkVirtualScrollViewport} from '@angular/cdk/scrolling'; import {ChangeDetectionStrategy, Component, OnDestroy, ViewEncapsulation} from '@angular/core'; import {BehaviorSubject} from 'rxjs'; - type State = { - name: string, - capital: string + name: string; + capital: string; }; - @Component({ selector: 'virtual-scroll-demo', templateUrl: 'virtual-scroll-demo.html', @@ -30,11 +28,16 @@ export class VirtualScrollDemo implements OnDestroy { scrollToBehavior: ScrollBehavior = 'auto'; scrolledIndex = new Map(); fixedSizeData = Array(10000).fill(50); - increasingSizeData = Array(10000).fill(0).map((_, i) => (1 + Math.floor(i / 1000)) * 20); - decreasingSizeData = Array(10000).fill(0) - .map((_, i) => (1 + Math.floor((10000 - i) / 1000)) * 20); - randomData = Array(10000).fill(0).map(() => Math.round(Math.random() * 100)); - observableData = new BehaviorSubject([]); + increasingSizeData = Array(10000) + .fill(0) + .map((_, i) => (1 + Math.floor(i / 1000)) * 20); + decreasingSizeData = Array(10000) + .fill(0) + .map((_, i) => (1 + Math.floor((10000 - i) / 1000)) * 20); + randomData = Array(10000) + .fill(0) + .map(() => Math.round(Math.random() * 100)); + readonly observableData = new BehaviorSubject([]); states = [ {name: 'Alabama', capital: 'Montgomery'}, {name: 'Alaska', capital: 'Juneau'}, @@ -105,15 +108,20 @@ export class VirtualScrollDemo implements OnDestroy { } sortBy(prop: 'name' | 'capital') { - this.statesObservable.next(this.states.map(s => ({...s})).sort((a, b) => { - const aProp = a[prop], bProp = b[prop]; - if (aProp < bProp) { - return -1; - } else if (aProp > bProp) { - return 1; - } - return 0; - })); + this.statesObservable.next( + this.states + .map(s => ({...s})) + .sort((a, b) => { + const aProp = a[prop], + bProp = b[prop]; + if (aProp < bProp) { + return -1; + } else if (aProp > bProp) { + return 1; + } + return 0; + }), + ); } scrolled(viewport: CdkVirtualScrollViewport, index: number) { diff --git a/src/dev-app/youtube-player/youtube-player-demo-module.ts b/src/dev-app/youtube-player/youtube-player-demo-module.ts index f290b6973f6e..e0a12bee08b8 100644 --- a/src/dev-app/youtube-player/youtube-player-demo-module.ts +++ b/src/dev-app/youtube-player/youtube-player-demo-module.ts @@ -24,5 +24,4 @@ import {YouTubePlayerDemo} from './youtube-player-demo'; ], declarations: [YouTubePlayerDemo], }) -export class YouTubePlayerDemoModule { -} +export class YouTubePlayerDemoModule {} diff --git a/src/dev-app/youtube-player/youtube-player-demo.ts b/src/dev-app/youtube-player/youtube-player-demo.ts index ae8aebb31d53..172947f05a7e 100644 --- a/src/dev-app/youtube-player/youtube-player-demo.ts +++ b/src/dev-app/youtube-player/youtube-player-demo.ts @@ -12,7 +12,7 @@ import { Component, ElementRef, OnDestroy, - ViewChild + ViewChild, } from '@angular/core'; interface Video { @@ -59,7 +59,7 @@ export class YouTubePlayerDemo implements AfterViewInit, OnDestroy { this.videoWidth = Math.min(this.demoYouTubePlayer.nativeElement.clientWidth, 1200); this.videoHeight = this.videoWidth * 0.6; this._changeDetectorRef.detectChanges(); - } + }; ngOnDestroy(): void { window.removeEventListener('resize', this.onResize); diff --git a/src/e2e-app/BUILD.bazel b/src/e2e-app/BUILD.bazel index 46f708fefaca..7320f33d761f 100644 --- a/src/e2e-app/BUILD.bazel +++ b/src/e2e-app/BUILD.bazel @@ -1,9 +1,21 @@ -load("@npm//@bazel/typescript:index.bzl", "ts_devserver") -load("//:packages.bzl", "getAngularUmdTargets") -load("//tools:defaults.bzl", "ng_module", "sass_binary") +load("//tools/dev-server:index.bzl", "dev_server") +load("//tools:defaults.bzl", "devmode_esbuild", "esbuild_config", "ng_module", "sass_binary") +load("//src/components-examples:config.bzl", "ALL_EXAMPLES") +load("//tools/angular:index.bzl", "LINKER_PROCESSED_FW_PACKAGES") package(default_visibility = ["//visibility:public"]) +# List of dependencies that are referenced in the `index.html` file. +devserverIndexHtmlDependencies = [ + "@npm//zone.js", + "@npm//core-js-bundle", + "@npm//kagekiri", + "@npm//material-components-web", + "//src/material/prebuilt-themes:indigo-pink", + ":index.html", + ":theme", +] + exports_files([ "protractor.conf.js", "start-devserver.js", @@ -65,7 +77,6 @@ ng_module( "//src/material/tabs", "@npm//@angular/animations", "@npm//@angular/core", - "@npm//@angular/elements", "@npm//@angular/forms", "@npm//@angular/platform-browser", "@npm//@angular/router", @@ -79,43 +90,44 @@ sass_binary( "external/npm/node_modules", ], deps = [ - "//src/material-experimental/mdc-theming:all_themes", - "//src/material-experimental/mdc-typography:all_typography", + "//src/material:theming_bundle", + "//src/material-experimental:theming_bundle", "//src/material/core:theming_scss_lib", ], ) -ts_devserver( +esbuild_config( + name = "esbuild_config", + testonly = True, + config_file = "esbuild.config.mjs", +) + +devmode_esbuild( + name = "bundles", + testonly = True, + config = ":esbuild_config", + entry_points = [":main.ts"] + ["%s:index.ts" % e for e in ALL_EXAMPLES], + platform = "browser", + splitting = True, + # We cannot use `ES2017` or higher as that would result in `async/await` not being downleveled. + # ZoneJS needs to be able to intercept these as otherwise change detection would not work properly. + target = "es2016", + # Note: We add all linker-processed FW packages as dependencies here so that ESBuild will + # map all framework packages to their linker-processed bundles from `tools/angular`. + deps = LINKER_PROCESSED_FW_PACKAGES + [ + ":e2e-app", + ], +) + +dev_server( name = "devserver", testonly = True, + srcs = devserverIndexHtmlDependencies, additional_root_paths = [ "npm/node_modules", ], - # Name of the AMD module that should be required on page load. - entry_module = "angular_material/src/e2e-app/main", - port = 4200, - # Scripts which will be included in the serving_path bundle after - # RequireJS has been loaded. - scripts = [ - ":devserver-configure.js", - "//tools/rxjs:rxjs_umd_modules", - "@npm//:node_modules/tslib/tslib.js", - ] + getAngularUmdTargets(), - # Serving path of the bundle that serves all files specified in "deps" and "scripts". - serving_path = "/bundle.js", - # Files which should be provided by Bazel when running the devserver. These are not - # automatically served, but can be loaded manually through HTTP requests. - static_files = [ - "@npm//zone.js", - "@npm//core-js", - "@npm//kagekiri", - "@npm//material-components-web", - "@npm//moment", - "@npm//@webcomponents/custom-elements", - "//src/material/prebuilt-themes:indigo-pink", - ":index.html", - ":theme", - ], tags = ["manual"], - deps = [":e2e-app"], + deps = [ + ":bundles", + ], ) diff --git a/src/e2e-app/block-scroll-strategy/block-scroll-strategy-e2e-module.ts b/src/e2e-app/block-scroll-strategy/block-scroll-strategy-e2e-module.ts index 243ccce595f0..fdcfef823668 100644 --- a/src/e2e-app/block-scroll-strategy/block-scroll-strategy-e2e-module.ts +++ b/src/e2e-app/block-scroll-strategy/block-scroll-strategy-e2e-module.ts @@ -14,5 +14,4 @@ import {BlockScrollStrategyE2E} from './block-scroll-strategy-e2e'; imports: [ScrollingModule], declarations: [BlockScrollStrategyE2E], }) -export class BlockScrollStrategyE2eModule { -} +export class BlockScrollStrategyE2eModule {} diff --git a/src/e2e-app/block-scroll-strategy/block-scroll-strategy-e2e.ts b/src/e2e-app/block-scroll-strategy/block-scroll-strategy-e2e.ts index d514d740fa36..2f0121bdf2a6 100644 --- a/src/e2e-app/block-scroll-strategy/block-scroll-strategy-e2e.ts +++ b/src/e2e-app/block-scroll-strategy/block-scroll-strategy-e2e.ts @@ -7,6 +7,6 @@ import {Overlay, ScrollStrategy} from '@angular/cdk/overlay'; styleUrls: ['block-scroll-strategy-e2e.css'], }) export class BlockScrollStrategyE2E { - constructor(private _overlay: Overlay) { } + constructor(private _overlay: Overlay) {} scrollStrategy: ScrollStrategy = this._overlay.scrollStrategies.block(); } diff --git a/src/e2e-app/button-toggle/button-toggle-e2e-module.ts b/src/e2e-app/button-toggle/button-toggle-e2e-module.ts index 52ab09a60cbe..3b397ea361ea 100644 --- a/src/e2e-app/button-toggle/button-toggle-e2e-module.ts +++ b/src/e2e-app/button-toggle/button-toggle-e2e-module.ts @@ -11,10 +11,7 @@ import {ExampleViewerModule} from '../example-viewer/example-viewer-module'; import {ButtonToggleE2e} from './button-toggle-e2e'; @NgModule({ - imports: [ - ExampleViewerModule, - ], + imports: [ExampleViewerModule], declarations: [ButtonToggleE2e], }) -export class ButtonToggleE2eModule { -} +export class ButtonToggleE2eModule {} diff --git a/src/e2e-app/button/button-e2e-module.ts b/src/e2e-app/button/button-e2e-module.ts index 92849510214a..e5d9edee958b 100644 --- a/src/e2e-app/button/button-e2e-module.ts +++ b/src/e2e-app/button/button-e2e-module.ts @@ -12,11 +12,7 @@ import {MatIconModule} from '@angular/material/icon'; import {ButtonE2E} from './button-e2e'; @NgModule({ - imports: [ - MatButtonModule, - MatIconModule, - ], + imports: [MatButtonModule, MatIconModule], declarations: [ButtonE2E], }) -export class ButtonE2eModule { -} +export class ButtonE2eModule {} diff --git a/src/e2e-app/card/card-e2e-module.ts b/src/e2e-app/card/card-e2e-module.ts index be1f46c1fc47..d127b46ff0d6 100644 --- a/src/e2e-app/card/card-e2e-module.ts +++ b/src/e2e-app/card/card-e2e-module.ts @@ -11,10 +11,7 @@ import {ExampleViewerModule} from '../example-viewer/example-viewer-module'; import {CardE2e} from './card-e2e'; @NgModule({ - imports: [ - ExampleViewerModule, - ], + imports: [ExampleViewerModule], declarations: [CardE2e], }) -export class CardE2eModule { -} +export class CardE2eModule {} diff --git a/src/e2e-app/checkbox/checkbox-e2e-module.ts b/src/e2e-app/checkbox/checkbox-e2e-module.ts index f8cd6a868e59..2515581bbea3 100644 --- a/src/e2e-app/checkbox/checkbox-e2e-module.ts +++ b/src/e2e-app/checkbox/checkbox-e2e-module.ts @@ -14,5 +14,4 @@ import {SimpleCheckboxes} from './checkbox-e2e'; imports: [MatCheckboxModule], declarations: [SimpleCheckboxes], }) -export class CheckboxE2eModule { -} +export class CheckboxE2eModule {} diff --git a/src/e2e-app/component-harness/component-harness-e2e-module.ts b/src/e2e-app/component-harness/component-harness-e2e-module.ts index d68a93e328ba..572392c85ba3 100644 --- a/src/e2e-app/component-harness/component-harness-e2e-module.ts +++ b/src/e2e-app/component-harness/component-harness-e2e-module.ts @@ -15,5 +15,4 @@ import {ComponentHarnessE2e} from './component-harness-e2e'; imports: [CommonModule, FormsModule, TestComponentsModule], declarations: [ComponentHarnessE2e], }) -export class ComponentHarnessE2eModule { -} +export class ComponentHarnessE2eModule {} diff --git a/src/e2e-app/devserver-configure.js b/src/e2e-app/devserver-configure.js deleted file mode 100644 index 4b5b619a7d11..000000000000 --- a/src/e2e-app/devserver-configure.js +++ /dev/null @@ -1,43 +0,0 @@ -// We need to configure AMD modules which are not named because otherwise "require.js" is not -// able to resolve AMD imports to such modules. -require.config({ - paths: { - 'moment': 'moment/min/moment.min', - - // Support for lazy-loading of component examples. - '@angular/components-examples': 'angular_material/src/components-examples', - - // MDC Web - '@material/animation': '@material/animation/dist/mdc.animation', - '@material/auto-init': '@material/auto-init/dist/mdc.autoInit', - '@material/base': '@material/base/dist/mdc.base', - '@material/checkbox': '@material/checkbox/dist/mdc.checkbox', - '@material/chips': '@material/chips/dist/mdc.chips', - '@material/circular-progress': '@material/circular-progress/dist/mdc.circularProgress', - '@material/dialog': '@material/dialog/dist/mdc.dialog', - '@material/dom': '@material/dom/dist/mdc.dom', - '@material/drawer': '@material/drawer/dist/mdc.drawer', - '@material/floating-label': '@material/floating-label/dist/mdc.floatingLabel', - '@material/form-field': '@material/form-field/dist/mdc.formField', - '@material/grid-list': '@material/grid-list/dist/mdc.gridList', - '@material/icon-button': '@material/icon-button/dist/mdc.iconButton', - '@material/line-ripple': '@material/line-ripple/dist/mdc.lineRipple', - '@material/linear-progress': '@material/linear-progress/dist/mdc.linearProgress', - '@material/list': '@material/list/dist/mdc.list', - '@material/menu': '@material/menu/dist/mdc.menu', - '@material/menu-surface': '@material/menu-surface/dist/mdc.menuSurface', - '@material/notched-outline': '@material/notched-outline/dist/mdc.notchedOutline', - '@material/radio': '@material/radio/dist/mdc.radio', - '@material/ripple': '@material/ripple/dist/mdc.ripple', - '@material/select': '@material/select/dist/mdc.select', - '@material/slider': '@material/slider/dist/mdc.slider', - '@material/snackbar': '@material/snackbar/dist/mdc.snackbar', - '@material/switch': '@material/switch/dist/mdc.switch', - '@material/tab': '@material/tab/dist/mdc.tab', - '@material/tab-bar': '@material/tab-bar/dist/mdc.tabBar', - '@material/tab-indicator': '@material/tab-indicator/dist/mdc.tabIndicator', - '@material/tab-scroller': '@material/tab-scroller/dist/mdc.tabScroller', - '@material/textfield': '@material/textfield/dist/mdc.textfield', - '@material/top-app-bar': '@material/top-app-bar/dist/mdc.topAppBar', - } -}); diff --git a/src/e2e-app/dialog/dialog-e2e-module.ts b/src/e2e-app/dialog/dialog-e2e-module.ts index cb68c40fdb7c..6bb0d8c47f7e 100644 --- a/src/e2e-app/dialog/dialog-e2e-module.ts +++ b/src/e2e-app/dialog/dialog-e2e-module.ts @@ -14,5 +14,4 @@ import {DialogE2E, TestDialog} from './dialog-e2e'; imports: [MatDialogModule], declarations: [DialogE2E, TestDialog], }) -export class DialogE2eModule { -} +export class DialogE2eModule {} diff --git a/src/e2e-app/dialog/dialog-e2e.ts b/src/e2e-app/dialog/dialog-e2e.ts index 5f15bac8aa2b..a46e3cc2d4c0 100644 --- a/src/e2e-app/dialog/dialog-e2e.ts +++ b/src/e2e-app/dialog/dialog-e2e.ts @@ -3,18 +3,18 @@ import {MatDialog, MatDialogRef, MatDialogConfig} from '@angular/material/dialog @Component({ selector: 'dialog-e2e', - templateUrl: 'dialog-e2e.html' + templateUrl: 'dialog-e2e.html', }) export class DialogE2E { dialogRef: MatDialogRef | null; @ViewChild(TemplateRef) templateRef: TemplateRef; - constructor (private _dialog: MatDialog) { } + constructor(private _dialog: MatDialog) {} private _openDialog(config?: MatDialogConfig) { this.dialogRef = this._dialog.open(TestDialog, config); - this.dialogRef.afterClosed().subscribe(() => this.dialogRef = null); + this.dialogRef.afterClosed().subscribe(() => (this.dialogRef = null)); } openDefault() { @@ -23,7 +23,7 @@ export class DialogE2E { openDisabled() { this._openDialog({ - disableClose: true + disableClose: true, }); } @@ -37,8 +37,8 @@ export class DialogE2E { template: `

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

- ` + `, }) export class TestDialog { - constructor(public dialogRef: MatDialogRef) { } + constructor(public dialogRef: MatDialogRef) {} } diff --git a/src/e2e-app/e2e-app.ts b/src/e2e-app/e2e-app.ts index 12a1cea3c2e8..0bd04a2847a9 100644 --- a/src/e2e-app/e2e-app.ts +++ b/src/e2e-app/e2e-app.ts @@ -14,5 +14,4 @@ import {Component, ViewEncapsulation} from '@angular/core'; template: '', encapsulation: ViewEncapsulation.None, }) -export class E2eApp { -} +export class E2eApp {} diff --git a/src/e2e-app/e2e-app/e2e-app-layout.html b/src/e2e-app/e2e-app/e2e-app-layout.html index fa58bb0a3e91..4afcc5c8f576 100644 --- a/src/e2e-app/e2e-app/e2e-app-layout.html +++ b/src/e2e-app/e2e-app/e2e-app-layout.html @@ -1,43 +1,9 @@ - - Block scroll strategy - Button - Button Toggle - Checkbox - Component Harness - Dialog - Expansion - Grid list - Icon - Input - List - Menu - Progress bar - Progress Spinner - Radios - Sidenav - Slide Toggle - Stepper - Tabs - Cards - Toolbar - Virtual Scroll - MDC Button - MDC Card - MDC Checkbox - MDC Chips - MDC Dialog - MDC Input - MDC Menu - MDC Radio - MDC Slide Toggle - MDC Table - MDC Tabs - MDC Progress bar - MDC Progress spinner - -
+ + {{link.title}} + +
diff --git a/src/e2e-app/e2e-app/e2e-app-layout.ts b/src/e2e-app/e2e-app/e2e-app-layout.ts index 06854f8dcbe2..8fc83ee7824f 100644 --- a/src/e2e-app/e2e-app/e2e-app-layout.ts +++ b/src/e2e-app/e2e-app/e2e-app-layout.ts @@ -1,9 +1,7 @@ import {Component, ViewEncapsulation} from '@angular/core'; - @Component({selector: 'home', template: `

e2e website!

`}) -export class Home { -} +export class Home {} @Component({ selector: 'e2e-app-layout', @@ -11,5 +9,43 @@ export class Home { encapsulation: ViewEncapsulation.None, }) export class E2eAppLayout { - showLinks: boolean = false; + showLinks = false; + + navLinks = [ + {path: 'block-scroll-strategy', title: 'Block scroll strategy'}, + {path: 'button', title: 'Button'}, + {path: 'button-toggle', title: 'Button Toggle'}, + {path: 'checkbox', title: 'Checkbox'}, + {path: 'component-harness', title: 'Component Harness'}, + {path: 'dialog', title: 'Dialog'}, + {path: 'expansion', title: 'Expansion'}, + {path: 'grid-list', title: 'Grid list'}, + {path: 'icon', title: 'Icon'}, + {path: 'input', title: 'Input'}, + {path: 'list', title: 'List'}, + {path: 'menu', title: 'Menu'}, + {path: 'progress-bar', title: 'Progress bar'}, + {path: 'progress-spinner', title: 'Progress Spinner'}, + {path: 'radio', title: 'Radios'}, + {path: 'sidenav', title: 'Sidenav'}, + {path: 'slide-toggle', title: 'Slide Toggle'}, + {path: 'stepper', title: 'Stepper'}, + {path: 'tabs', title: 'Tabs'}, + {path: 'cards', title: 'Cards'}, + {path: 'toolbar', title: 'Toolbar'}, + {path: 'virtual-scroll', title: 'Virtual Scroll'}, + {path: 'mdc-button', title: 'MDC Button'}, + {path: 'mdc-card', title: 'MDC Card'}, + {path: 'mdc-checkbox', title: 'MDC Checkbox'}, + {path: 'mdc-chips', title: 'MDC Chips'}, + {path: 'mdc-dialog', title: 'MDC Dialog'}, + {path: 'mdc-input', title: 'MDC Input'}, + {path: 'mdc-menu', title: 'MDC Menu'}, + {path: 'mdc-radio', title: 'MDC Radio'}, + {path: 'mdc-slide-toggle', title: 'MDC Slide Toggle'}, + {path: 'mdc-table', title: 'MDC Table'}, + {path: 'mdc-tabs', title: 'MDC Tabs'}, + {path: 'mdc-progress-bar', title: 'MDC Progress bar'}, + {path: 'mdc-progress-spinner', title: 'MDC Progress spinner'}, + ]; } diff --git a/src/e2e-app/e2e-app/e2e-app-module.ts b/src/e2e-app/e2e-app/e2e-app-module.ts index 14a4a73b7c21..807c74be264a 100644 --- a/src/e2e-app/e2e-app/e2e-app-module.ts +++ b/src/e2e-app/e2e-app/e2e-app-module.ts @@ -13,13 +13,8 @@ import {RouterModule} from '@angular/router'; import {E2eAppLayout, Home} from './e2e-app-layout'; @NgModule({ - imports: [ - CommonModule, - MatListModule, - RouterModule, - ], + imports: [CommonModule, MatListModule, RouterModule], declarations: [E2eAppLayout, Home], exports: [E2eAppLayout], }) -export class E2eAppModule { -} +export class E2eAppModule {} diff --git a/src/e2e-app/e2e-app/routes.ts b/src/e2e-app/e2e-app/routes.ts deleted file mode 100644 index f30ced334f19..000000000000 --- a/src/e2e-app/e2e-app/routes.ts +++ /dev/null @@ -1,78 +0,0 @@ -import {Routes} from '@angular/router'; -import {BlockScrollStrategyE2E} from '../block-scroll-strategy/block-scroll-strategy-e2e'; -import {ButtonToggleE2e} from '../button-toggle/button-toggle-e2e'; -import {ButtonE2E} from '../button/button-e2e'; -import {CardE2e} from '../card/card-e2e'; -import {SimpleCheckboxes} from '../checkbox/checkbox-e2e'; -import {ComponentHarnessE2e} from '../component-harness/component-harness-e2e'; -import {DialogE2E} from '../dialog/dialog-e2e'; -import {ExpansionE2e} from '../expansion/expansion-e2e'; -import {GridListE2E} from '../grid-list/grid-list-e2e'; -import {IconE2E} from '../icon/icon-e2e'; -import {InputE2E} from '../input/input-e2e'; -import {ListE2e} from '../list/list-e2e'; -import {MdcButtonE2e} from '../mdc-button/mdc-button-e2e'; -import {MdcCardE2e} from '../mdc-card/mdc-card-e2e'; -import {MdcCheckboxE2e} from '../mdc-checkbox/mdc-checkbox-e2e'; -import {MdcChipsE2e} from '../mdc-chips/mdc-chips-e2e'; -import {MdcDialogE2E} from '../mdc-dialog/mdc-dialog-e2e'; -import {MdcInputE2E} from '../mdc-input/mdc-input-e2e'; -import {MdcMenuE2e} from '../mdc-menu/mdc-menu-e2e'; -import {MdcRadioE2e} from '../mdc-radio/mdc-radio-e2e'; -import {MdcSlideToggleE2e} from '../mdc-slide-toggle/mdc-slide-toggle-e2e'; -import {MdcSliderE2e} from '../mdc-slider/mdc-slider-e2e'; -import {MdcTableE2e} from '../mdc-table/mdc-table-e2e'; -import {MdcTabsE2e} from '../mdc-tabs/mdc-tabs-e2e'; -import {MdcProgressBarE2E} from '../mdc-progress-bar/mdc-progress-bar-e2e'; -import {MdcProgressSpinnerE2e} from '../mdc-progress-spinner/mdc-progress-spinner-e2e'; -import {MenuE2E} from '../menu/menu-e2e'; -import {ProgressBarE2E} from '../progress-bar/progress-bar-e2e'; -import {ProgressSpinnerE2E} from '../progress-spinner/progress-spinner-e2e'; -import {SimpleRadioButtons} from '../radio/radio-e2e'; -import {SidenavE2E} from '../sidenav/sidenav-e2e'; -import {SlideToggleE2E} from '../slide-toggle/slide-toggle-e2e'; -import {StepperE2e} from '../stepper/stepper-e2e'; -import {BasicTabs} from '../tabs/tabs-e2e'; -import {ToolbarE2e} from '../toolbar/toolbar-e2e'; -import {VirtualScrollE2E} from '../virtual-scroll/virtual-scroll-e2e'; -import {Home} from './e2e-app-layout'; - -export const E2E_APP_ROUTES: Routes = [ - {path: '', component: Home}, - {path: 'block-scroll-strategy', component: BlockScrollStrategyE2E}, - {path: 'button', component: ButtonE2E}, - {path: 'button-toggle', component: ButtonToggleE2e}, - {path: 'cards', component: CardE2e}, - {path: 'checkbox', component: SimpleCheckboxes}, - {path: 'component-harness', component: ComponentHarnessE2e}, - {path: 'dialog', component: DialogE2E}, - {path: 'expansion', component: ExpansionE2e}, - {path: 'grid-list', component: GridListE2E}, - {path: 'icon', component: IconE2E}, - {path: 'input', component: InputE2E}, - {path: 'list', component: ListE2e}, - {path: 'mdc-button', component: MdcButtonE2e}, - {path: 'mdc-card', component: MdcCardE2e}, - {path: 'mdc-checkbox', component: MdcCheckboxE2e}, - {path: 'mdc-chips', component: MdcChipsE2e}, - {path: 'mdc-dialog', component: MdcDialogE2E}, - {path: 'mdc-input', component: MdcInputE2E}, - {path: 'mdc-menu', component: MdcMenuE2e}, - {path: 'mdc-radio', component: MdcRadioE2e}, - {path: 'mdc-slider', component: MdcSliderE2e}, - {path: 'mdc-slide-toggle', component: MdcSlideToggleE2e}, - {path: 'mdc-tabs', component: MdcTabsE2e}, - {path: 'mdc-table', component: MdcTableE2e}, - {path: 'mdc-progress-bar', component: MdcProgressBarE2E}, - {path: 'mdc-progress-spinner', component: MdcProgressSpinnerE2e}, - {path: 'menu', component: MenuE2E}, - {path: 'progress-bar', component: ProgressBarE2E}, - {path: 'progress-spinner', component: ProgressSpinnerE2E}, - {path: 'radio', component: SimpleRadioButtons}, - {path: 'sidenav', component: SidenavE2E}, - {path: 'slide-toggle', component: SlideToggleE2E}, - {path: 'stepper', component: StepperE2e}, - {path: 'tabs', component: BasicTabs}, - {path: 'toolbar', component: ToolbarE2e}, - {path: 'virtual-scroll', component: VirtualScrollE2E}, -]; diff --git a/src/e2e-app/esbuild.config.mjs b/src/e2e-app/esbuild.config.mjs new file mode 100644 index 000000000000..475c2bf12bbd --- /dev/null +++ b/src/e2e-app/esbuild.config.mjs @@ -0,0 +1,12 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +export default { + resolveExtensions: ['.js'], + format: 'esm', +}; diff --git a/src/e2e-app/example-viewer/example-viewer-module.ts b/src/e2e-app/example-viewer/example-viewer-module.ts index 8ddf3faa6b08..ae214cac3903 100644 --- a/src/e2e-app/example-viewer/example-viewer-module.ts +++ b/src/e2e-app/example-viewer/example-viewer-module.ts @@ -14,7 +14,6 @@ import {ExampleViewer} from './example-viewer'; @NgModule({ imports: [CommonModule], declarations: [ExampleViewer, ExampleListViewer], - exports: [ExampleViewer, ExampleListViewer] + exports: [ExampleViewer, ExampleListViewer], }) -export class ExampleViewerModule { -} +export class ExampleViewerModule {} diff --git a/src/e2e-app/example-viewer/example-viewer.ts b/src/e2e-app/example-viewer/example-viewer.ts index aaa407baa547..9d6b62bb43fc 100644 --- a/src/e2e-app/example-viewer/example-viewer.ts +++ b/src/e2e-app/example-viewer/example-viewer.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {loadExampleFactory} from '@angular/components-examples/private'; +import {loadExample} from '@angular/components-examples/private'; import {Component, Injector, Input, OnInit, ViewContainerRef} from '@angular/core'; /** Loads an example component from `@angular/components-examples` */ @@ -22,10 +22,10 @@ export class ExampleViewer implements OnInit { /** ID of the material example to display. */ @Input() id: string; - constructor(private _injector: Injector, - private _viewContainerRef: ViewContainerRef) {} + constructor(private _injector: Injector, private _viewContainerRef: ViewContainerRef) {} async ngOnInit() { - this._viewContainerRef.createComponent(await loadExampleFactory(this.id, this._injector)); + const {component, injector} = await loadExample(this.id, this._injector); + this._viewContainerRef.createComponent(component, {injector}); } } diff --git a/src/e2e-app/expansion/expansion-e2e-module.ts b/src/e2e-app/expansion/expansion-e2e-module.ts index 88d76f82b156..677a7ea066a6 100644 --- a/src/e2e-app/expansion/expansion-e2e-module.ts +++ b/src/e2e-app/expansion/expansion-e2e-module.ts @@ -11,10 +11,7 @@ import {ExampleViewerModule} from '../example-viewer/example-viewer-module'; import {ExpansionE2e} from './expansion-e2e'; @NgModule({ - imports: [ - ExampleViewerModule, - ], + imports: [ExampleViewerModule], declarations: [ExpansionE2e], }) -export class ExpansionE2eModule { -} +export class ExpansionE2eModule {} diff --git a/src/e2e-app/grid-list/grid-list-e2e-module.ts b/src/e2e-app/grid-list/grid-list-e2e-module.ts index d4a51fc02b16..b8caee9ae3a1 100644 --- a/src/e2e-app/grid-list/grid-list-e2e-module.ts +++ b/src/e2e-app/grid-list/grid-list-e2e-module.ts @@ -14,5 +14,4 @@ import {GridListE2E} from './grid-list-e2e'; imports: [MatGridListModule], declarations: [GridListE2E], }) -export class GridListE2eModule { -} +export class GridListE2eModule {} diff --git a/src/e2e-app/icon/icon-e2e-module.ts b/src/e2e-app/icon/icon-e2e-module.ts index 3b2e713c0d6a..60286c39a063 100644 --- a/src/e2e-app/icon/icon-e2e-module.ts +++ b/src/e2e-app/icon/icon-e2e-module.ts @@ -14,5 +14,4 @@ import {IconE2E} from './icon-e2e'; imports: [MatIconModule], declarations: [IconE2E], }) -export class IconE2eModule { -} +export class IconE2eModule {} diff --git a/src/e2e-app/icon/icon-e2e.ts b/src/e2e-app/icon/icon-e2e.ts index 11945747a976..4e06feae4519 100644 --- a/src/e2e-app/icon/icon-e2e.ts +++ b/src/e2e-app/icon/icon-e2e.ts @@ -1,6 +1,5 @@ import {Component} from '@angular/core'; - @Component({ selector: 'icon-e2e', templateUrl: 'icon-e2e.html', diff --git a/src/e2e-app/index.html b/src/e2e-app/index.html index 0c0c2844f426..81722b6f5e02 100644 --- a/src/e2e-app/index.html +++ b/src/e2e-app/index.html @@ -7,31 +7,21 @@ + - + - - - - Loading... I am a sibling! - - + - - - + diff --git a/src/e2e-app/input/input-e2e-module.ts b/src/e2e-app/input/input-e2e-module.ts index b4b75e3298f5..011ebf648d0c 100644 --- a/src/e2e-app/input/input-e2e-module.ts +++ b/src/e2e-app/input/input-e2e-module.ts @@ -15,5 +15,4 @@ import {InputE2E} from './input-e2e'; imports: [MatFormFieldModule, MatInputModule], declarations: [InputE2E], }) -export class InputE2eModule { -} +export class InputE2eModule {} diff --git a/src/e2e-app/input/input-e2e.ts b/src/e2e-app/input/input-e2e.ts index a866fb8f4d5a..234838196720 100644 --- a/src/e2e-app/input/input-e2e.ts +++ b/src/e2e-app/input/input-e2e.ts @@ -1,6 +1,5 @@ import {Component} from '@angular/core'; - @Component({ selector: 'input-e2e', templateUrl: 'input-e2e.html', diff --git a/src/e2e-app/list/list-e2e-module.ts b/src/e2e-app/list/list-e2e-module.ts index 6d3dffeba739..7c9c3b862c9d 100644 --- a/src/e2e-app/list/list-e2e-module.ts +++ b/src/e2e-app/list/list-e2e-module.ts @@ -11,10 +11,7 @@ import {ExampleViewerModule} from '../example-viewer/example-viewer-module'; import {ListE2e} from './list-e2e'; @NgModule({ - imports: [ - ExampleViewerModule, - ], + imports: [ExampleViewerModule], declarations: [ListE2e], }) -export class ListE2eModule { -} +export class ListE2eModule {} diff --git a/src/e2e-app/main-module.ts b/src/e2e-app/main-module.ts index d44c9c753294..3aca19b85dd5 100644 --- a/src/e2e-app/main-module.ts +++ b/src/e2e-app/main-module.ts @@ -2,9 +2,7 @@ import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {RouterModule} from '@angular/router'; -import { - BlockScrollStrategyE2eModule -} from './block-scroll-strategy/block-scroll-strategy-e2e-module'; +import {BlockScrollStrategyE2eModule} from './block-scroll-strategy/block-scroll-strategy-e2e-module'; import {ButtonToggleE2eModule} from './button-toggle/button-toggle-e2e-module'; import {ButtonE2eModule} from './button/button-e2e-module'; import {CardE2eModule} from './card/card-e2e-module'; @@ -13,7 +11,7 @@ import {ComponentHarnessE2eModule} from './component-harness/component-harness-e import {DialogE2eModule} from './dialog/dialog-e2e-module'; import {E2eApp} from './e2e-app'; import {E2eAppModule} from './e2e-app/e2e-app-module'; -import {E2E_APP_ROUTES} from './e2e-app/routes'; +import {E2E_APP_ROUTES} from './routes'; import {ExpansionE2eModule} from './expansion/expansion-e2e-module'; import {GridListE2eModule} from './grid-list/grid-list-e2e-module'; import {IconE2eModule} from './icon/icon-e2e-module'; @@ -87,10 +85,7 @@ import {MdcProgressSpinnerE2eModule} from './mdc-progress-spinner/mdc-progress-s ToolbarE2eModule, VirtualScrollE2eModule, ], - declarations: [ - E2eApp, - ], + declarations: [E2eApp], bootstrap: [E2eApp], }) -export class MainModule { -} +export class MainModule {} diff --git a/src/e2e-app/main.ts b/src/e2e-app/main.ts index 3204e4f5d812..44c9253d5715 100644 --- a/src/e2e-app/main.ts +++ b/src/e2e-app/main.ts @@ -1,8 +1,8 @@ import {enableProdMode} from '@angular/core'; import {platformBrowser} from '@angular/platform-browser'; -import {MainModuleNgFactory} from './main-module.ngfactory'; +import {MainModule} from './main-module'; enableProdMode(); -platformBrowser().bootstrapModuleFactory(MainModuleNgFactory); +platformBrowser().bootstrapModule(MainModule); diff --git a/src/e2e-app/mdc-button/mdc-button-e2e-module.ts b/src/e2e-app/mdc-button/mdc-button-e2e-module.ts index b44d2d2712f3..b301cc4806b7 100644 --- a/src/e2e-app/mdc-button/mdc-button-e2e-module.ts +++ b/src/e2e-app/mdc-button/mdc-button-e2e-module.ts @@ -12,11 +12,7 @@ import {MatIconModule} from '@angular/material/icon'; import {MdcButtonE2e} from './mdc-button-e2e'; @NgModule({ - imports: [ - MatButtonModule, - MatIconModule, - ], + imports: [MatButtonModule, MatIconModule], declarations: [MdcButtonE2e], }) -export class MdcButtonE2eModule { -} +export class MdcButtonE2eModule {} diff --git a/src/e2e-app/mdc-button/mdc-button-e2e.ts b/src/e2e-app/mdc-button/mdc-button-e2e.ts index 7c58030964f8..2b2a37303317 100644 --- a/src/e2e-app/mdc-button/mdc-button-e2e.ts +++ b/src/e2e-app/mdc-button/mdc-button-e2e.ts @@ -16,5 +16,3 @@ export class MdcButtonE2e { isDisabled: boolean = false; clickCounter: number = 0; } - - diff --git a/src/e2e-app/mdc-card/mdc-card-e2e-module.ts b/src/e2e-app/mdc-card/mdc-card-e2e-module.ts index 3384f7c166b8..a597229d02fc 100644 --- a/src/e2e-app/mdc-card/mdc-card-e2e-module.ts +++ b/src/e2e-app/mdc-card/mdc-card-e2e-module.ts @@ -11,10 +11,7 @@ import {NgModule} from '@angular/core'; import {MdcCardE2e} from './mdc-card-e2e'; @NgModule({ - imports: [ - MdcCardExamplesModule, - ], + imports: [MdcCardExamplesModule], declarations: [MdcCardE2e], }) -export class MdcCardE2eModule { -} +export class MdcCardE2eModule {} diff --git a/src/e2e-app/mdc-card/mdc-card-e2e.ts b/src/e2e-app/mdc-card/mdc-card-e2e.ts index 231444a76787..d97edf34ecfb 100644 --- a/src/e2e-app/mdc-card/mdc-card-e2e.ts +++ b/src/e2e-app/mdc-card/mdc-card-e2e.ts @@ -12,5 +12,4 @@ import {Component} from '@angular/core'; selector: 'mdc-card-e2e', template: ``, }) -export class MdcCardE2e { -} +export class MdcCardE2e {} diff --git a/src/e2e-app/mdc-checkbox/mdc-checkbox-e2e-module.ts b/src/e2e-app/mdc-checkbox/mdc-checkbox-e2e-module.ts index 286426e0b77c..2aa7acb4e409 100644 --- a/src/e2e-app/mdc-checkbox/mdc-checkbox-e2e-module.ts +++ b/src/e2e-app/mdc-checkbox/mdc-checkbox-e2e-module.ts @@ -14,5 +14,4 @@ import {MdcCheckboxE2e} from './mdc-checkbox-e2e'; imports: [MatCheckboxModule], declarations: [MdcCheckboxE2e], }) -export class MdcCheckboxE2eModule { -} +export class MdcCheckboxE2eModule {} diff --git a/src/e2e-app/mdc-chips/mdc-chips-e2e-module.ts b/src/e2e-app/mdc-chips/mdc-chips-e2e-module.ts index 23af65a104a6..6894ba16441a 100644 --- a/src/e2e-app/mdc-chips/mdc-chips-e2e-module.ts +++ b/src/e2e-app/mdc-chips/mdc-chips-e2e-module.ts @@ -14,5 +14,4 @@ import {MdcChipsE2e} from './mdc-chips-e2e'; imports: [MatChipsModule], declarations: [MdcChipsE2e], }) -export class MdcChipsE2eModule { -} +export class MdcChipsE2eModule {} diff --git a/src/e2e-app/mdc-dialog/mdc-dialog-e2e-module.ts b/src/e2e-app/mdc-dialog/mdc-dialog-e2e-module.ts index 5fc5ae7edcf9..ea4980ebfd64 100644 --- a/src/e2e-app/mdc-dialog/mdc-dialog-e2e-module.ts +++ b/src/e2e-app/mdc-dialog/mdc-dialog-e2e-module.ts @@ -14,5 +14,4 @@ import {MdcDialogE2E, TestDialog} from './mdc-dialog-e2e'; imports: [MatDialogModule], declarations: [MdcDialogE2E, TestDialog], }) -export class MdcDialogE2eModule { -} +export class MdcDialogE2eModule {} diff --git a/src/e2e-app/mdc-dialog/mdc-dialog-e2e.ts b/src/e2e-app/mdc-dialog/mdc-dialog-e2e.ts index 0308ab6f56bf..f75044363f8f 100644 --- a/src/e2e-app/mdc-dialog/mdc-dialog-e2e.ts +++ b/src/e2e-app/mdc-dialog/mdc-dialog-e2e.ts @@ -3,18 +3,18 @@ import {MatDialog, MatDialogRef, MatDialogConfig} from '@angular/material-experi @Component({ selector: 'mdc-dialog-e2e', - templateUrl: 'mdc-dialog-e2e.html' + templateUrl: 'mdc-dialog-e2e.html', }) export class MdcDialogE2E { dialogRef: MatDialogRef | null; @ViewChild(TemplateRef) templateRef: TemplateRef; - constructor (private _dialog: MatDialog) { } + constructor(private _dialog: MatDialog) {} private _openDialog(config?: MatDialogConfig) { this.dialogRef = this._dialog.open(TestDialog, config); - this.dialogRef.afterClosed().subscribe(() => this.dialogRef = null); + this.dialogRef.afterClosed().subscribe(() => (this.dialogRef = null)); } openDefault() { @@ -23,7 +23,7 @@ export class MdcDialogE2E { openDisabled() { this._openDialog({ - disableClose: true + disableClose: true, }); } @@ -37,8 +37,8 @@ export class MdcDialogE2E { template: `

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

- ` + `, }) export class TestDialog { - constructor(public dialogRef: MatDialogRef) { } + constructor(public dialogRef: MatDialogRef) {} } diff --git a/src/e2e-app/mdc-input/mdc-input-e2e-module.ts b/src/e2e-app/mdc-input/mdc-input-e2e-module.ts index 11ea99bc06a0..3aff8e75373c 100644 --- a/src/e2e-app/mdc-input/mdc-input-e2e-module.ts +++ b/src/e2e-app/mdc-input/mdc-input-e2e-module.ts @@ -15,5 +15,4 @@ import {MdcInputE2E} from './mdc-input-e2e'; imports: [MatFormFieldModule, MatInputModule], declarations: [MdcInputE2E], }) -export class MdcInputE2eModule { -} +export class MdcInputE2eModule {} diff --git a/src/e2e-app/mdc-menu/mdc-menu-e2e-module.ts b/src/e2e-app/mdc-menu/mdc-menu-e2e-module.ts index dc0bc0cdaf14..0e4a8da6a396 100644 --- a/src/e2e-app/mdc-menu/mdc-menu-e2e-module.ts +++ b/src/e2e-app/mdc-menu/mdc-menu-e2e-module.ts @@ -14,5 +14,4 @@ import {MdcMenuE2e} from './mdc-menu-e2e'; imports: [MatMenuModule], declarations: [MdcMenuE2e], }) -export class MdcMenuE2eModule { -} +export class MdcMenuE2eModule {} diff --git a/src/e2e-app/mdc-menu/mdc-menu-e2e.ts b/src/e2e-app/mdc-menu/mdc-menu-e2e.ts index 568b1438f56b..90ecb4b06a8f 100644 --- a/src/e2e-app/mdc-menu/mdc-menu-e2e.ts +++ b/src/e2e-app/mdc-menu/mdc-menu-e2e.ts @@ -11,7 +11,8 @@ import {Component} from '@angular/core'; @Component({ selector: 'mdc-menu-e2e', templateUrl: 'mdc-menu-e2e.html', - styles: [` + styles: [ + ` #before-t, #above-t, #combined-t { width: 60px; height: 20px; @@ -20,7 +21,8 @@ import {Component} from '@angular/core'; .bottom-row { margin-top: 5px; } - `] + `, + ], }) export class MdcMenuE2e { selected: string = ''; diff --git a/src/e2e-app/mdc-progress-bar/mdc-progress-bar-e2e-module.ts b/src/e2e-app/mdc-progress-bar/mdc-progress-bar-e2e-module.ts index 07265236c201..9be7ddffb199 100644 --- a/src/e2e-app/mdc-progress-bar/mdc-progress-bar-e2e-module.ts +++ b/src/e2e-app/mdc-progress-bar/mdc-progress-bar-e2e-module.ts @@ -14,5 +14,4 @@ import {MdcProgressBarE2E} from './mdc-progress-bar-e2e'; imports: [MatProgressBarModule], declarations: [MdcProgressBarE2E], }) -export class MdcProgressBarE2eModule { -} +export class MdcProgressBarE2eModule {} diff --git a/src/e2e-app/mdc-progress-bar/mdc-progress-bar-e2e.html b/src/e2e-app/mdc-progress-bar/mdc-progress-bar-e2e.html index b1218f154b26..a18996fd83c4 100644 --- a/src/e2e-app/mdc-progress-bar/mdc-progress-bar-e2e.html +++ b/src/e2e-app/mdc-progress-bar/mdc-progress-bar-e2e.html @@ -1,4 +1,17 @@ - - - - + + + + + + + diff --git a/src/e2e-app/mdc-progress-bar/mdc-progress-bar-e2e.ts b/src/e2e-app/mdc-progress-bar/mdc-progress-bar-e2e.ts index 68dc344d4190..0af7c5ce2d53 100644 --- a/src/e2e-app/mdc-progress-bar/mdc-progress-bar-e2e.ts +++ b/src/e2e-app/mdc-progress-bar/mdc-progress-bar-e2e.ts @@ -1,14 +1,15 @@ import {Component} from '@angular/core'; - @Component({ selector: 'mdc-progress-bar-e2e', templateUrl: 'mdc-progress-bar-e2e.html', - styles: [` + styles: [ + ` mat-progress-bar { margin-bottom: 10px; } - `] + `, + ], }) export class MdcProgressBarE2E { determinateValue: number = 57; diff --git a/src/e2e-app/mdc-progress-spinner/mdc-progress-spinner-e2e.html b/src/e2e-app/mdc-progress-spinner/mdc-progress-spinner-e2e.html index e2672d5bd949..c0e3efcf5343 100644 --- a/src/e2e-app/mdc-progress-spinner/mdc-progress-spinner-e2e.html +++ b/src/e2e-app/mdc-progress-spinner/mdc-progress-spinner-e2e.html @@ -1,3 +1,11 @@ - - - + + + + + diff --git a/src/e2e-app/mdc-progress-spinner/mdc-progress-spinner-e2e.ts b/src/e2e-app/mdc-progress-spinner/mdc-progress-spinner-e2e.ts index ad20e871b974..989d1382d2d3 100644 --- a/src/e2e-app/mdc-progress-spinner/mdc-progress-spinner-e2e.ts +++ b/src/e2e-app/mdc-progress-spinner/mdc-progress-spinner-e2e.ts @@ -10,7 +10,7 @@ import {Component} from '@angular/core'; @Component({ selector: 'mdc-progress-spinner-e2e', - templateUrl: 'mdc-progress-spinner-e2e.html' + templateUrl: 'mdc-progress-spinner-e2e.html', }) export class MdcProgressSpinnerE2e { value = 65; diff --git a/src/e2e-app/mdc-progress-spinner/mdc-progress-spinner-module.ts b/src/e2e-app/mdc-progress-spinner/mdc-progress-spinner-module.ts index 78da71c0da20..fcdb71c53f71 100644 --- a/src/e2e-app/mdc-progress-spinner/mdc-progress-spinner-module.ts +++ b/src/e2e-app/mdc-progress-spinner/mdc-progress-spinner-module.ts @@ -12,6 +12,6 @@ import {MdcProgressSpinnerE2e} from './mdc-progress-spinner-e2e'; @NgModule({ imports: [MatProgressSpinnerModule], - declarations: [MdcProgressSpinnerE2e] + declarations: [MdcProgressSpinnerE2e], }) export class MdcProgressSpinnerE2eModule {} diff --git a/src/e2e-app/mdc-radio/mdc-radio-e2e-module.ts b/src/e2e-app/mdc-radio/mdc-radio-e2e-module.ts index 4a227d62415c..4baf556a7b7d 100644 --- a/src/e2e-app/mdc-radio/mdc-radio-e2e-module.ts +++ b/src/e2e-app/mdc-radio/mdc-radio-e2e-module.ts @@ -14,5 +14,4 @@ import {MdcRadioE2e} from './mdc-radio-e2e'; imports: [MatRadioModule], declarations: [MdcRadioE2e], }) -export class MdcRadioE2eModule { -} +export class MdcRadioE2eModule {} diff --git a/src/e2e-app/mdc-slide-toggle/mdc-slide-toggle-e2e-module.ts b/src/e2e-app/mdc-slide-toggle/mdc-slide-toggle-e2e-module.ts index 2dfca58899f5..f63918f917dd 100644 --- a/src/e2e-app/mdc-slide-toggle/mdc-slide-toggle-e2e-module.ts +++ b/src/e2e-app/mdc-slide-toggle/mdc-slide-toggle-e2e-module.ts @@ -14,5 +14,4 @@ import {MdcSlideToggleE2e} from './mdc-slide-toggle-e2e'; imports: [MatSlideToggleModule], declarations: [MdcSlideToggleE2e], }) -export class MdcSlideToggleE2eModule { -} +export class MdcSlideToggleE2eModule {} diff --git a/src/e2e-app/mdc-slider/mdc-slider-e2e-module.ts b/src/e2e-app/mdc-slider/mdc-slider-e2e-module.ts index ede0e5d1620d..c4b7678bada3 100644 --- a/src/e2e-app/mdc-slider/mdc-slider-e2e-module.ts +++ b/src/e2e-app/mdc-slider/mdc-slider-e2e-module.ts @@ -11,12 +11,7 @@ import {MatSliderModule} from '@angular/material-experimental/mdc-slider'; import {MdcSliderE2e} from './mdc-slider-e2e'; @NgModule({ - imports: [ - MatSliderModule, - ], - declarations: [ - MdcSliderE2e, - ], + imports: [MatSliderModule], + declarations: [MdcSliderE2e], }) -export class MdcSliderE2eModule { -} +export class MdcSliderE2eModule {} diff --git a/src/e2e-app/mdc-slider/mdc-slider-e2e.ts b/src/e2e-app/mdc-slider/mdc-slider-e2e.ts index ec5fe2d2b71d..2aff71228687 100644 --- a/src/e2e-app/mdc-slider/mdc-slider-e2e.ts +++ b/src/e2e-app/mdc-slider/mdc-slider-e2e.ts @@ -10,7 +10,19 @@ import {Component} from '@angular/core'; @Component({ selector: 'mdc-slider-e2e', - template: ``, + template: ` + + + + + + + + + + + + + `, }) -export class MdcSliderE2e { -} +export class MdcSliderE2e {} diff --git a/src/e2e-app/mdc-table/mdc-table-e2e-module.ts b/src/e2e-app/mdc-table/mdc-table-e2e-module.ts index 436c99921651..b4756eb81e69 100644 --- a/src/e2e-app/mdc-table/mdc-table-e2e-module.ts +++ b/src/e2e-app/mdc-table/mdc-table-e2e-module.ts @@ -14,5 +14,4 @@ import {MdcTableE2e} from './mdc-table-e2e'; imports: [MatTableModule], declarations: [MdcTableE2e], }) -export class MdcTableE2eModule { -} +export class MdcTableE2eModule {} diff --git a/src/e2e-app/mdc-tabs/mdc-tabs-e2e-module.ts b/src/e2e-app/mdc-tabs/mdc-tabs-e2e-module.ts index 23006d7a75b6..eb35f457bf3e 100644 --- a/src/e2e-app/mdc-tabs/mdc-tabs-e2e-module.ts +++ b/src/e2e-app/mdc-tabs/mdc-tabs-e2e-module.ts @@ -16,5 +16,4 @@ import {MdcTabsE2e} from './mdc-tabs-e2e'; imports: [MatTabsModule, MatFormFieldModule, MatInputModule], declarations: [MdcTabsE2e], }) -export class MdcTabsE2eModule { -} +export class MdcTabsE2eModule {} diff --git a/src/e2e-app/mdc-tabs/mdc-tabs-e2e.ts b/src/e2e-app/mdc-tabs/mdc-tabs-e2e.ts index e62833826f98..69f6f195098a 100644 --- a/src/e2e-app/mdc-tabs/mdc-tabs-e2e.ts +++ b/src/e2e-app/mdc-tabs/mdc-tabs-e2e.ts @@ -12,5 +12,4 @@ import {Component} from '@angular/core'; selector: 'mdc-tabs-e2e', templateUrl: 'mdc-tabs-e2e.html', }) -export class MdcTabsE2e { -} +export class MdcTabsE2e {} diff --git a/src/e2e-app/menu/menu-e2e-module.ts b/src/e2e-app/menu/menu-e2e-module.ts index 51cb6208eb8f..136440d5f59d 100644 --- a/src/e2e-app/menu/menu-e2e-module.ts +++ b/src/e2e-app/menu/menu-e2e-module.ts @@ -14,5 +14,4 @@ import {MenuE2E} from './menu-e2e'; imports: [MatMenuModule], declarations: [MenuE2E], }) -export class MenuE2eModule { -} +export class MenuE2eModule {} diff --git a/src/e2e-app/menu/menu-e2e.ts b/src/e2e-app/menu/menu-e2e.ts index ecff571fad03..489594b5fa8e 100644 --- a/src/e2e-app/menu/menu-e2e.ts +++ b/src/e2e-app/menu/menu-e2e.ts @@ -1,10 +1,10 @@ import {Component} from '@angular/core'; - @Component({ selector: 'menu-e2e', templateUrl: 'menu-e2e.html', - styles: [` + styles: [ + ` #before-t, #above-t, #combined-t { width: 60px; height: 20px; @@ -13,7 +13,8 @@ import {Component} from '@angular/core'; .bottom-row { margin-top: 5px; } - `] + `, + ], }) export class MenuE2E { selected: string = ''; diff --git a/src/e2e-app/progress-bar/progress-bar-e2e-module.ts b/src/e2e-app/progress-bar/progress-bar-e2e-module.ts index 03e0285b7f1c..7ea219e068ba 100644 --- a/src/e2e-app/progress-bar/progress-bar-e2e-module.ts +++ b/src/e2e-app/progress-bar/progress-bar-e2e-module.ts @@ -14,5 +14,4 @@ import {ProgressBarE2E} from './progress-bar-e2e'; imports: [MatProgressBarModule], declarations: [ProgressBarE2E], }) -export class ProgressBarE2eModule { -} +export class ProgressBarE2eModule {} diff --git a/src/e2e-app/progress-bar/progress-bar-e2e.html b/src/e2e-app/progress-bar/progress-bar-e2e.html index b1218f154b26..a18996fd83c4 100644 --- a/src/e2e-app/progress-bar/progress-bar-e2e.html +++ b/src/e2e-app/progress-bar/progress-bar-e2e.html @@ -1,4 +1,17 @@ - - - - + + + + + + + diff --git a/src/e2e-app/progress-bar/progress-bar-e2e.ts b/src/e2e-app/progress-bar/progress-bar-e2e.ts index 144f55f92294..a90213d0c3c1 100644 --- a/src/e2e-app/progress-bar/progress-bar-e2e.ts +++ b/src/e2e-app/progress-bar/progress-bar-e2e.ts @@ -1,14 +1,15 @@ import {Component} from '@angular/core'; - @Component({ selector: 'progress-bar-e2e', templateUrl: 'progress-bar-e2e.html', - styles: [` + styles: [ + ` mat-progress-bar { margin-bottom: 10px; } - `] + `, + ], }) export class ProgressBarE2E { determinateValue: number = 57; diff --git a/src/e2e-app/progress-spinner/progress-spinner-e2e-module.ts b/src/e2e-app/progress-spinner/progress-spinner-e2e-module.ts index d9b55dc6ac2a..54b4fa905778 100644 --- a/src/e2e-app/progress-spinner/progress-spinner-e2e-module.ts +++ b/src/e2e-app/progress-spinner/progress-spinner-e2e-module.ts @@ -14,5 +14,4 @@ import {ProgressSpinnerE2E} from './progress-spinner-e2e'; imports: [MatProgressSpinnerModule], declarations: [ProgressSpinnerE2E], }) -export class ProgressSpinnerE2eModule { -} +export class ProgressSpinnerE2eModule {} diff --git a/src/e2e-app/progress-spinner/progress-spinner-e2e.html b/src/e2e-app/progress-spinner/progress-spinner-e2e.html index 7971277ec758..e343cede786c 100644 --- a/src/e2e-app/progress-spinner/progress-spinner-e2e.html +++ b/src/e2e-app/progress-spinner/progress-spinner-e2e.html @@ -1,3 +1,9 @@ - - - + + + + + diff --git a/src/e2e-app/progress-spinner/progress-spinner-e2e.ts b/src/e2e-app/progress-spinner/progress-spinner-e2e.ts index 703d766a04a2..46e7b93bd891 100644 --- a/src/e2e-app/progress-spinner/progress-spinner-e2e.ts +++ b/src/e2e-app/progress-spinner/progress-spinner-e2e.ts @@ -4,4 +4,4 @@ import {Component} from '@angular/core'; selector: 'progress-spinner-e2e', templateUrl: 'progress-spinner-e2e.html', }) -export class ProgressSpinnerE2E { } +export class ProgressSpinnerE2E {} diff --git a/src/e2e-app/protractor.conf.js b/src/e2e-app/protractor.conf.js index 5bdf73471262..c9ec8169eda4 100644 --- a/src/e2e-app/protractor.conf.js +++ b/src/e2e-app/protractor.conf.js @@ -18,8 +18,18 @@ exports.config = { // Disable color contrast checks since the final colors will vary based on the theme. {id: 'color-contrast', enabled: false}, - ] - } + + // Don't require all content to be inside landmarks since some tests depend on the + // page layout and moving this around can break them. + {id: 'region', enabled: false}, + + // Don't require at least one `

` since we don't have any content. + {id: 'page-has-heading-one', enabled: false}, + + // Axe incorrectly picks up that `aria-required` is not allowed on the MDC slide toggle. + {id: 'aria-allowed-attr', selector: '*:not(.mdc-switch)'}, + ], + }, ], // Since we want to use async/await we don't want to mix up with selenium's promise diff --git a/src/e2e-app/radio/radio-e2e-module.ts b/src/e2e-app/radio/radio-e2e-module.ts index 69b68d86aced..47fc9a1f4a63 100644 --- a/src/e2e-app/radio/radio-e2e-module.ts +++ b/src/e2e-app/radio/radio-e2e-module.ts @@ -14,5 +14,4 @@ import {SimpleRadioButtons} from './radio-e2e'; imports: [MatRadioModule], declarations: [SimpleRadioButtons], }) -export class RadioE2eModule { -} +export class RadioE2eModule {} diff --git a/src/e2e-app/routes.ts b/src/e2e-app/routes.ts new file mode 100644 index 000000000000..17198e3ddd1d --- /dev/null +++ b/src/e2e-app/routes.ts @@ -0,0 +1,78 @@ +import {Routes} from '@angular/router'; +import {BlockScrollStrategyE2E} from './block-scroll-strategy/block-scroll-strategy-e2e'; +import {ButtonToggleE2e} from './button-toggle/button-toggle-e2e'; +import {ButtonE2E} from './button/button-e2e'; +import {CardE2e} from './card/card-e2e'; +import {SimpleCheckboxes} from './checkbox/checkbox-e2e'; +import {ComponentHarnessE2e} from './component-harness/component-harness-e2e'; +import {DialogE2E} from './dialog/dialog-e2e'; +import {ExpansionE2e} from './expansion/expansion-e2e'; +import {GridListE2E} from './grid-list/grid-list-e2e'; +import {IconE2E} from './icon/icon-e2e'; +import {InputE2E} from './input/input-e2e'; +import {ListE2e} from './list/list-e2e'; +import {MdcButtonE2e} from './mdc-button/mdc-button-e2e'; +import {MdcCardE2e} from './mdc-card/mdc-card-e2e'; +import {MdcCheckboxE2e} from './mdc-checkbox/mdc-checkbox-e2e'; +import {MdcChipsE2e} from './mdc-chips/mdc-chips-e2e'; +import {MdcDialogE2E} from './mdc-dialog/mdc-dialog-e2e'; +import {MdcInputE2E} from './mdc-input/mdc-input-e2e'; +import {MdcMenuE2e} from './mdc-menu/mdc-menu-e2e'; +import {MdcRadioE2e} from './mdc-radio/mdc-radio-e2e'; +import {MdcSlideToggleE2e} from './mdc-slide-toggle/mdc-slide-toggle-e2e'; +import {MdcSliderE2e} from './mdc-slider/mdc-slider-e2e'; +import {MdcTableE2e} from './mdc-table/mdc-table-e2e'; +import {MdcTabsE2e} from './mdc-tabs/mdc-tabs-e2e'; +import {MdcProgressBarE2E} from './mdc-progress-bar/mdc-progress-bar-e2e'; +import {MdcProgressSpinnerE2e} from './mdc-progress-spinner/mdc-progress-spinner-e2e'; +import {MenuE2E} from './menu/menu-e2e'; +import {ProgressBarE2E} from './progress-bar/progress-bar-e2e'; +import {ProgressSpinnerE2E} from './progress-spinner/progress-spinner-e2e'; +import {SimpleRadioButtons} from './radio/radio-e2e'; +import {SidenavE2E} from './sidenav/sidenav-e2e'; +import {SlideToggleE2E} from './slide-toggle/slide-toggle-e2e'; +import {StepperE2e} from './stepper/stepper-e2e'; +import {BasicTabs} from './tabs/tabs-e2e'; +import {ToolbarE2e} from './toolbar/toolbar-e2e'; +import {VirtualScrollE2E} from './virtual-scroll/virtual-scroll-e2e'; +import {Home} from './e2e-app/e2e-app-layout'; + +export const E2E_APP_ROUTES: Routes = [ + {path: '', component: Home}, + {path: 'block-scroll-strategy', component: BlockScrollStrategyE2E}, + {path: 'button', component: ButtonE2E}, + {path: 'button-toggle', component: ButtonToggleE2e}, + {path: 'cards', component: CardE2e}, + {path: 'checkbox', component: SimpleCheckboxes}, + {path: 'component-harness', component: ComponentHarnessE2e}, + {path: 'dialog', component: DialogE2E}, + {path: 'expansion', component: ExpansionE2e}, + {path: 'grid-list', component: GridListE2E}, + {path: 'icon', component: IconE2E}, + {path: 'input', component: InputE2E}, + {path: 'list', component: ListE2e}, + {path: 'mdc-button', component: MdcButtonE2e}, + {path: 'mdc-card', component: MdcCardE2e}, + {path: 'mdc-checkbox', component: MdcCheckboxE2e}, + {path: 'mdc-chips', component: MdcChipsE2e}, + {path: 'mdc-dialog', component: MdcDialogE2E}, + {path: 'mdc-input', component: MdcInputE2E}, + {path: 'mdc-menu', component: MdcMenuE2e}, + {path: 'mdc-radio', component: MdcRadioE2e}, + {path: 'mdc-slider', component: MdcSliderE2e}, + {path: 'mdc-slide-toggle', component: MdcSlideToggleE2e}, + {path: 'mdc-tabs', component: MdcTabsE2e}, + {path: 'mdc-table', component: MdcTableE2e}, + {path: 'mdc-progress-bar', component: MdcProgressBarE2E}, + {path: 'mdc-progress-spinner', component: MdcProgressSpinnerE2e}, + {path: 'menu', component: MenuE2E}, + {path: 'progress-bar', component: ProgressBarE2E}, + {path: 'progress-spinner', component: ProgressSpinnerE2E}, + {path: 'radio', component: SimpleRadioButtons}, + {path: 'sidenav', component: SidenavE2E}, + {path: 'slide-toggle', component: SlideToggleE2E}, + {path: 'stepper', component: StepperE2e}, + {path: 'tabs', component: BasicTabs}, + {path: 'toolbar', component: ToolbarE2e}, + {path: 'virtual-scroll', component: VirtualScrollE2E}, +]; diff --git a/src/e2e-app/sidenav/sidenav-e2e-module.ts b/src/e2e-app/sidenav/sidenav-e2e-module.ts index ceecc7415ebc..dd551474a57d 100644 --- a/src/e2e-app/sidenav/sidenav-e2e-module.ts +++ b/src/e2e-app/sidenav/sidenav-e2e-module.ts @@ -14,5 +14,4 @@ import {SidenavE2E} from './sidenav-e2e'; imports: [MatSidenavModule], declarations: [SidenavE2E], }) -export class SidenavE2eModule { -} +export class SidenavE2eModule {} diff --git a/src/e2e-app/sidenav/sidenav-e2e.ts b/src/e2e-app/sidenav/sidenav-e2e.ts index db9c7b4f3068..1564f7db8ab9 100644 --- a/src/e2e-app/sidenav/sidenav-e2e.ts +++ b/src/e2e-app/sidenav/sidenav-e2e.ts @@ -1,9 +1,7 @@ import {Component} from '@angular/core'; - @Component({ selector: 'sidenav-e2e', templateUrl: 'sidenav-e2e.html', }) -export class SidenavE2E { -} +export class SidenavE2E {} diff --git a/src/e2e-app/slide-toggle/slide-toggle-e2e-module.ts b/src/e2e-app/slide-toggle/slide-toggle-e2e-module.ts index 7ca9dbb2932e..88399587225b 100644 --- a/src/e2e-app/slide-toggle/slide-toggle-e2e-module.ts +++ b/src/e2e-app/slide-toggle/slide-toggle-e2e-module.ts @@ -14,5 +14,4 @@ import {SlideToggleE2E} from './slide-toggle-e2e'; imports: [MatSlideToggleModule], declarations: [SlideToggleE2E], }) -export class SlideToggleE2eModule { -} +export class SlideToggleE2eModule {} diff --git a/src/e2e-app/slide-toggle/slide-toggle-e2e.ts b/src/e2e-app/slide-toggle/slide-toggle-e2e.ts index f190f91b962c..126b6bccb75f 100644 --- a/src/e2e-app/slide-toggle/slide-toggle-e2e.ts +++ b/src/e2e-app/slide-toggle/slide-toggle-e2e.ts @@ -4,4 +4,4 @@ import {Component} from '@angular/core'; selector: 'slide-toggle-e2e', templateUrl: 'slide-toggle-e2e.html', }) -export class SlideToggleE2E { } +export class SlideToggleE2E {} diff --git a/src/e2e-app/start-devserver.js b/src/e2e-app/start-devserver.js index 103c9b366a07..c4d521edea41 100644 --- a/src/e2e-app/start-devserver.js +++ b/src/e2e-app/start-devserver.js @@ -1,37 +1,16 @@ const protractor = require('protractor'); -const utils = require('@bazel/protractor/protractor-utils'); -const spawn = require('child_process').spawn; -/** - * Runs the specified server binary from a given workspace and waits for the server - * being ready. The server binary will be resolved from the runfiles. - */ -async function runBazelServer(workspace, serverPath, timeout) { - const serverBinary = require.resolve(`${workspace}/${serverPath}`); - const port = await utils.findFreeTcpPort(); - - // Start the Bazel server binary with a random free TCP port. - const serverProcess = spawn(serverBinary, ['-port', port], {stdio: 'inherit'}); - - // In case the process exited with an error, we want to propagate the error. - serverProcess.on('exit', exitCode => { - if (exitCode !== 0) { - throw new Error(`Server exited with error code: ${exitCode}`); - } - }); - - // Wait for the server to be bound to the given port. - await utils.waitForServer(port, timeout); - - return port; -} +// Note: We need to specify an explicit file extension here because otherwise +// the Bazel-patched NodeJS module resolution would resolve to the `.mjs` file +// in non-sandbox environments (as usually with Bazel and Windows). +const utils = require('@bazel/protractor/protractor-utils.js'); /** * Called by Protractor before starting any tests. This is script is responsible for * starting up the devserver and updating the Protractor base URL to the proper port. */ -module.exports = async function(config) { - const port = await runBazelServer(config.workspace, config.server); +module.exports = async function (config) { + const {port} = await utils.runServer(config.workspace, config.server, '--port', []); const baseUrl = `http://localhost:${port}`; const processedConfig = await protractor.browser.getProcessedConfig(); diff --git a/src/e2e-app/stepper/stepper-e2e-module.ts b/src/e2e-app/stepper/stepper-e2e-module.ts index 7a8281348f4e..71b6d6e30312 100644 --- a/src/e2e-app/stepper/stepper-e2e-module.ts +++ b/src/e2e-app/stepper/stepper-e2e-module.ts @@ -11,10 +11,7 @@ import {ExampleViewerModule} from '../example-viewer/example-viewer-module'; import {StepperE2e} from './stepper-e2e'; @NgModule({ - imports: [ - ExampleViewerModule, - ], + imports: [ExampleViewerModule], declarations: [StepperE2e], }) -export class StepperE2eModule { -} +export class StepperE2eModule {} diff --git a/src/e2e-app/tabs/tabs-e2e-module.ts b/src/e2e-app/tabs/tabs-e2e-module.ts index 3da7de3ba507..52ec37b13230 100644 --- a/src/e2e-app/tabs/tabs-e2e-module.ts +++ b/src/e2e-app/tabs/tabs-e2e-module.ts @@ -16,5 +16,4 @@ import {BasicTabs} from './tabs-e2e'; imports: [MatTabsModule, MatFormFieldModule, MatInputModule], declarations: [BasicTabs], }) -export class TabsE2eModule { -} +export class TabsE2eModule {} diff --git a/src/e2e-app/test_suite.bzl b/src/e2e-app/test_suite.bzl index 9e83d06178fc..e854ca93c718 100644 --- a/src/e2e-app/test_suite.bzl +++ b/src/e2e-app/test_suite.bzl @@ -6,7 +6,7 @@ def e2e_test_suite(name, data = [], tags = ["e2e"], deps = []): configuration = "//src/e2e-app:protractor.conf.js", data = [ "//tools/axe-protractor", - "@npm//axe-webdriverjs", + "@npm//@axe-core/webdriverjs", ] + data, on_prepare = "//src/e2e-app:start-devserver.js", server = "//src/e2e-app:devserver", diff --git a/src/e2e-app/theme.scss b/src/e2e-app/theme.scss index b4ef263e63e0..23aa924ea564 100644 --- a/src/e2e-app/theme.scss +++ b/src/e2e-app/theme.scss @@ -1,20 +1,19 @@ -@import '../material/core/theming/all-theme'; -@import '../material-experimental/mdc-theming/all-theme'; -@import '../material-experimental/mdc-typography/all-typography'; +@use '../material' as mat; +@use '../material-experimental' as experimental; // Plus imports for other components in your app. // Include the common styles for Angular Material. We include this here so that you only // have to load a single css file for Angular Material in your app. // **Be sure that you only ever include this mixin once!** -@include mat-core(); -@include angular-material-mdc-typography(); +@include mat.core(); +@include experimental.all-mdc-component-typographies(); // Define the default theme (same as the example above). -$candy-app-primary: mat-palette($mat-indigo); -$candy-app-accent: mat-palette($mat-pink, A200, A100, A400); -$candy-app-theme: mat-light-theme($candy-app-primary, $candy-app-accent); +$candy-app-primary: mat.define-palette(mat.$indigo-palette); +$candy-app-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400); +$candy-app-theme: mat.define-light-theme($candy-app-primary, $candy-app-accent); // Include the default theme styles. -@include angular-material-theme($candy-app-theme); -@include angular-material-mdc-theme($candy-app-theme); +@include mat.all-component-themes($candy-app-theme); +@include experimental.all-mdc-component-themes($candy-app-theme); diff --git a/src/e2e-app/toolbar/toolbar-e2e-module.ts b/src/e2e-app/toolbar/toolbar-e2e-module.ts index ac81b925050a..0c5803c79d20 100644 --- a/src/e2e-app/toolbar/toolbar-e2e-module.ts +++ b/src/e2e-app/toolbar/toolbar-e2e-module.ts @@ -11,10 +11,7 @@ import {ExampleViewerModule} from '../example-viewer/example-viewer-module'; import {ToolbarE2e} from './toolbar-e2e'; @NgModule({ - imports: [ - ExampleViewerModule, - ], + imports: [ExampleViewerModule], declarations: [ToolbarE2e], }) -export class ToolbarE2eModule { -} +export class ToolbarE2eModule {} diff --git a/src/e2e-app/tsconfig.json b/src/e2e-app/tsconfig.json index 4cef3e72c68a..4f0a5cb5f393 100644 --- a/src/e2e-app/tsconfig.json +++ b/src/e2e-app/tsconfig.json @@ -12,6 +12,8 @@ "@angular/cdk-experimental/*": ["../cdk-experimental/*"], "@angular/cdk-experimental": ["../cdk-experimental/"], "@angular/material-moment-adapter": ["../material-moment-adapter/"], + "@angular/material-luxon-adapter": ["../material-luxon-adapter/"], + "@angular/material-date-fns-adapter": ["../material-date-fns-adapter/"], "@angular/components-examples": ["../components-examples/"], "@angular/components-examples/*": ["../components-examples/*"] } diff --git a/src/e2e-app/virtual-scroll/virtual-scroll-e2e-module.ts b/src/e2e-app/virtual-scroll/virtual-scroll-e2e-module.ts index d4579c98cc10..9415221c759f 100644 --- a/src/e2e-app/virtual-scroll/virtual-scroll-e2e-module.ts +++ b/src/e2e-app/virtual-scroll/virtual-scroll-e2e-module.ts @@ -15,5 +15,4 @@ import {VirtualScrollE2E} from './virtual-scroll-e2e'; imports: [ScrollingModule, ExperimentalScrollingModule], declarations: [VirtualScrollE2E], }) -export class VirtualScrollE2eModule { -} +export class VirtualScrollE2eModule {} diff --git a/src/e2e-app/virtual-scroll/virtual-scroll-e2e.html b/src/e2e-app/virtual-scroll/virtual-scroll-e2e.html index 182542cbe186..ed2deeea4f2e 100644 --- a/src/e2e-app/virtual-scroll/virtual-scroll-e2e.html +++ b/src/e2e-app/virtual-scroll/virtual-scroll-e2e.html @@ -1,6 +1,6 @@

Uniform size

- +
Uniform Item #{{i}} - ({{size}}px) @@ -10,7 +10,7 @@

Uniform size

Random size

- +
Variable Item #{{i}} - ({{size}}px) diff --git a/src/e2e-app/virtual-scroll/virtual-scroll-e2e.ts b/src/e2e-app/virtual-scroll/virtual-scroll-e2e.ts index 5b815cf45813..c91443dd88bb 100644 --- a/src/e2e-app/virtual-scroll/virtual-scroll-e2e.ts +++ b/src/e2e-app/virtual-scroll/virtual-scroll-e2e.ts @@ -1,9 +1,7 @@ import {Component} from '@angular/core'; - const itemSizeSample = [100, 25, 50, 50, 100, 200, 75, 100, 50, 250]; - @Component({ selector: 'virtual-scroll-e2e', templateUrl: 'virtual-scroll-e2e.html', @@ -11,5 +9,7 @@ const itemSizeSample = [100, 25, 50, 50, 100, 200, 75, 100, 50, 250]; }) export class VirtualScrollE2E { uniformItems = Array(1000).fill(50); - variableItems = Array(100).fill(0).reduce(acc => acc.concat(itemSizeSample), []); + variableItems = Array(100) + .fill(0) + .reduce(acc => acc.concat(itemSizeSample), []); } diff --git a/src/google-maps/BUILD.bazel b/src/google-maps/BUILD.bazel index 174a14ad0a7f..fee2c1fa8488 100644 --- a/src/google-maps/BUILD.bazel +++ b/src/google-maps/BUILD.bazel @@ -10,12 +10,11 @@ ng_module( "**/*.spec.ts", ], ), - module_name = "@angular/google-maps", deps = [ "//src:dev_mode_types", "@npm//@angular/common", "@npm//@angular/core", - "@npm//@types/googlemaps", + "@npm//@types/google.maps", "@npm//rxjs", ], ) @@ -24,8 +23,6 @@ ng_module( ng_package( name = "npm_package", srcs = ["package.json"], - entry_point = ":public-api.ts", - entry_point_name = "google-maps", tags = ["release-package"], deps = [":google-maps"], ) diff --git a/src/google-maps/README.md b/src/google-maps/README.md index 8c90cf1013b6..2b1fa151901d 100644 --- a/src/google-maps/README.md +++ b/src/google-maps/README.md @@ -19,14 +19,23 @@ To install, run `npm install @angular/google-maps`. ... - + ``` +**Note:** +If you're using the `` directive, you also have to include the `visualization` +library when loading the Google Maps API. To do so, you can add `&libraries=visualization` to the +script URL: + +```html + +``` + ## Lazy Loading the API -The API can be loaded when the component is actually used by using the Angular HttpClient jsonp method to make sure that the component doesn't load until after the API has loaded. +The API can be loaded when the component is actually used by using the Angular HttpClient jsonp +method to make sure that the component doesn't load until after the API has loaded. ```typescript // google-maps-demo.module.ts @@ -101,10 +110,20 @@ export class GoogleMapsDemoComponent { - [`MapTrafficLayer`](./map-traffic-layer/README.md) - [`MapTransitLayer`](./map-transit-layer/README.md) - [`MapBicyclingLayer`](./map-bicycling-layer/README.md) +- [`MapDirectionsRenderer`](./map-directions-renderer/README.md) +- [`MapHeatmapLayer`](./map-heatmap-layer/README.md) + +## Services + +- [`MapGeocoder`](./map-geocoder/README.md) + ## The Options Input -The Google Maps components implement all of the options for their respective objects from the Google Maps JavaScript API through an `options` input, but they also have specific inputs for some of the most common options. For example, the Google Maps component could have its options set either in with a google.maps.MapOptions object: +The Google Maps components implement all of the options for their respective objects from the +Google Maps JavaScript API through an `options` input, but they also have specific inputs for some +of the most common options. For example, the Google Maps component could have its options set either +in with a google.maps.MapOptions object: ```html @@ -129,4 +148,5 @@ center: google.maps.LatLngLiteral = {lat: 40, lng: -20}; zoom = 4; ``` -Not every option has its own input. See the API for each component to see if the option has a dedicated input or if it should be set in the options input. +Not every option has its own input. See the API for each component to see if the option has a +dedicated input or if it should be set in the options input. diff --git a/src/google-maps/google-map/README.md b/src/google-maps/google-map/README.md index 02290caff544..2da6dca4d0f1 100644 --- a/src/google-maps/google-map/README.md +++ b/src/google-maps/google-map/README.md @@ -34,11 +34,11 @@ export class GoogleMapDemo { center: google.maps.LatLngLiteral = {lat: 24, lng: 12}; zoom = 4; - moveMap(event: google.maps.MouseEvent) { + moveMap(event: google.maps.MapMouseEvent) { this.center = (event.latLng.toJSON()); } - move(event: google.maps.MouseEvent) { + move(event: google.maps.MapMouseEvent) { this.display = event.latLng.toJSON(); } } diff --git a/src/google-maps/google-map/google-map.spec.ts b/src/google-maps/google-map/google-map.spec.ts index a5bfc4340039..5eea53ede1c3 100644 --- a/src/google-maps/google-map/google-map.spec.ts +++ b/src/google-maps/google-map/google-map.spec.ts @@ -24,14 +24,14 @@ describe('GoogleMap', () => { let mapConstructorSpy: jasmine.Spy; let mapSpy: jasmine.SpyObj; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [ - GoogleMapsModule, - ], - declarations: [TestApp], - }); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + declarations: [TestApp], + }); + }), + ); beforeEach(() => { TestBed.compileComponents(); @@ -39,18 +39,21 @@ describe('GoogleMap', () => { afterEach(() => { (window.google as any) = undefined; + (window as any).gm_authFailure = undefined; }); it('throws an error is the Google Maps JavaScript API was not loaded', () => { mapSpy = createMapSpy(DEFAULT_OPTIONS); createMapConstructorSpy(mapSpy, false); - expect(() => TestBed.createComponent(TestApp)) - .toThrow(new Error( - 'Namespace google not found, cannot construct embedded google ' + - 'map. Please install the Google Maps JavaScript API: ' + - 'https://developers.google.com/maps/documentation/javascript/' + - 'tutorial#Loading_the_Maps_API')); + expect(() => TestBed.createComponent(TestApp)).toThrow( + new Error( + 'Namespace google not found, cannot construct embedded google ' + + 'map. Please install the Google Maps JavaScript API: ' + + 'https://developers.google.com/maps/documentation/javascript/' + + 'tutorial#Loading_the_Maps_API', + ), + ); }); it('initializes a Google map', () => { @@ -63,10 +66,7 @@ describe('GoogleMap', () => { const container = fixture.debugElement.query(By.css('div'))!; expect(container.nativeElement.style.height).toBe(DEFAULT_HEIGHT); expect(container.nativeElement.style.width).toBe(DEFAULT_WIDTH); - expect(mapConstructorSpy).toHaveBeenCalledWith(container.nativeElement, { - ...DEFAULT_OPTIONS, - mapTypeId: undefined - }); + expect(mapConstructorSpy).toHaveBeenCalledWith(container.nativeElement, DEFAULT_OPTIONS); }); it('sets height and width of the map', () => { @@ -81,10 +81,7 @@ describe('GoogleMap', () => { const container = fixture.debugElement.query(By.css('div'))!; expect(container.nativeElement.style.height).toBe('750px'); expect(container.nativeElement.style.width).toBe('400px'); - expect(mapConstructorSpy).toHaveBeenCalledWith(container.nativeElement, { - ...DEFAULT_OPTIONS, - mapTypeId: undefined - }); + expect(mapConstructorSpy).toHaveBeenCalledWith(container.nativeElement, DEFAULT_OPTIONS); fixture.componentInstance.height = '650px'; fixture.componentInstance.width = '350px'; @@ -131,7 +128,7 @@ describe('GoogleMap', () => { }); it('sets center and zoom of the map', () => { - const options = {center: {lat: 3, lng: 5}, zoom: 7, mapTypeId: undefined}; + const options = {center: {lat: 3, lng: 5}, zoom: 7, mapTypeId: DEFAULT_OPTIONS.mapTypeId}; mapSpy = createMapSpy(options); mapConstructorSpy = createMapConstructorSpy(mapSpy).and.callThrough(); @@ -152,7 +149,12 @@ describe('GoogleMap', () => { }); it('sets map options', () => { - const options = {center: {lat: 3, lng: 5}, zoom: 7, draggable: false, mapTypeId: undefined}; + const options = { + center: {lat: 3, lng: 5}, + zoom: 7, + draggable: false, + mapTypeId: DEFAULT_OPTIONS.mapTypeId, + }; mapSpy = createMapSpy(options); mapConstructorSpy = createMapConstructorSpy(mapSpy).and.callThrough(); @@ -211,7 +213,7 @@ describe('GoogleMap', () => { center: {lat: 12, lng: 15}, zoom: 5, heading: 170, - mapTypeId: undefined + mapTypeId: DEFAULT_OPTIONS.mapTypeId, }; mapSpy = createMapSpy(correctedOptions); mapConstructorSpy = createMapConstructorSpy(mapSpy); @@ -257,7 +259,7 @@ describe('GoogleMap', () => { const component = fixture.debugElement.query(By.directive(GoogleMap)).componentInstance; - mapSpy.getBounds.and.returnValue(null); + mapSpy.getBounds.and.returnValue(undefined); expect(component.getBounds()).toBe(null); component.getCenter(); @@ -272,7 +274,7 @@ describe('GoogleMap', () => { component.getMapTypeId(); expect(mapSpy.getMapTypeId).toHaveBeenCalled(); - mapSpy.getProjection.and.returnValue(null); + mapSpy.getProjection.and.returnValue(undefined); expect(component.getProjection()).toBe(null); component.getStreetView(); @@ -339,14 +341,62 @@ describe('GoogleMap', () => { fixture.componentInstance.mapTypeId = 'terrain' as unknown as google.maps.MapTypeId; fixture.detectChanges(); - expect(mapConstructorSpy).toHaveBeenCalledWith(jasmine.any(HTMLElement), - jasmine.objectContaining({mapTypeId: 'terrain'})); + expect(mapConstructorSpy).toHaveBeenCalledWith( + jasmine.any(HTMLElement), + jasmine.objectContaining({mapTypeId: 'terrain'}), + ); fixture.componentInstance.mapTypeId = 'roadmap' as unknown as google.maps.MapTypeId; fixture.detectChanges(); expect(mapSpy.setMapTypeId).toHaveBeenCalledWith('roadmap'); }); + + it('sets mapTypeId through the options', () => { + const options = {mapTypeId: 'satellite'}; + mapSpy = createMapSpy(options); + mapConstructorSpy = createMapConstructorSpy(mapSpy).and.callThrough(); + const fixture = TestBed.createComponent(TestApp); + fixture.componentInstance.options = options; + fixture.detectChanges(); + + expect(mapConstructorSpy.calls.mostRecent()?.args[1].mapTypeId).toBe('satellite'); + }); + + it('should emit mapInitialized event when the map is initialized', () => { + mapSpy = createMapSpy(DEFAULT_OPTIONS); + mapConstructorSpy = createMapConstructorSpy(mapSpy); + + const fixture = TestBed.createComponent(TestApp); + fixture.detectChanges(); + + expect(fixture.componentInstance.mapInitializedSpy).toHaveBeenCalledOnceWith( + fixture.componentInstance.map.googleMap, + ); + }); + + it('should emit authFailure event when window.gm_authFailure is called', () => { + mapSpy = createMapSpy(DEFAULT_OPTIONS); + mapConstructorSpy = createMapConstructorSpy(mapSpy); + + expect((window as any).gm_authFailure).toBeUndefined(); + + const createFixture = () => { + const fixture = TestBed.createComponent(TestApp); + fixture.detectChanges(); + spyOn(fixture.componentInstance.map.authFailure, 'emit'); + return fixture; + }; + + const fixture1 = createFixture(); + const fixture2 = createFixture(); + + expect((window as any).gm_authFailure).toBeDefined(); + (window as any).gm_authFailure(); + + expect(fixture1.componentInstance.map.authFailure.emit).toHaveBeenCalled(); + expect(fixture2.componentInstance.map.authFailure.emit).toHaveBeenCalled(); + }); }); @Component({ @@ -359,7 +409,8 @@ describe('GoogleMap', () => { [mapTypeId]="mapTypeId" (mapClick)="handleClick($event)" (centerChanged)="handleCenterChanged()" - (mapRightclick)="handleRightclick($event)"> + (mapRightclick)="handleRightclick($event)" + (mapInitialized)="mapInitializedSpy($event)"> `, }) class TestApp { @@ -371,7 +422,8 @@ class TestApp { options?: google.maps.MapOptions; mapTypeId?: google.maps.MapTypeId; - handleClick(event: google.maps.MouseEvent) {} + handleClick(event: google.maps.MapMouseEvent) {} handleCenterChanged() {} - handleRightclick(event: google.maps.MouseEvent) {} + handleRightclick(event: google.maps.MapMouseEvent) {} + mapInitializedSpy = jasmine.createSpy('mapInitialized'); } diff --git a/src/google-maps/google-map/google-map.ts b/src/google-maps/google-map/google-map.ts index 3a2399bbc5e1..1014fe7be4df 100644 --- a/src/google-maps/google-map/google-map.ts +++ b/src/google-maps/google-map/google-map.ts @@ -7,7 +7,7 @@ */ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 -/// +/// import { ChangeDetectionStrategy, @@ -22,20 +22,24 @@ import { Inject, PLATFORM_ID, NgZone, + SimpleChanges, + EventEmitter, } from '@angular/core'; import {isPlatformBrowser} from '@angular/common'; -import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; -import {map, shareReplay, take, takeUntil} from 'rxjs/operators'; +import {Observable} from 'rxjs'; import {MapEventManager} from '../map-event-manager'; interface GoogleMapsWindow extends Window { + gm_authFailure?: () => void; google?: typeof google; } /** default options set to the Googleplex */ export const DEFAULT_OPTIONS: google.maps.MapOptions = { center: {lat: 37.421995, lng: -122.084092}, - zoom: 17 + zoom: 17, + // Note: the type conversion here isn't necessary for our CI, but it resolves a g3 failure. + mapTypeId: 'roadmap' as unknown as google.maps.MapTypeId, }; /** Arbitrary default height for the map element */ @@ -57,14 +61,8 @@ export const DEFAULT_WIDTH = '500px'; }) export class GoogleMap implements OnChanges, OnInit, OnDestroy { private _eventManager: MapEventManager = new MapEventManager(this._ngZone); - private _googleMapChanges: Observable; - - private readonly _options = new BehaviorSubject(DEFAULT_OPTIONS); - private readonly _center = - new BehaviorSubject(undefined); - private readonly _zoom = new BehaviorSubject(undefined); - private readonly _destroy = new Subject(); private _mapEl: HTMLElement; + private _existingAuthFailureCallback: GoogleMapsWindow['gm_authFailure']; /** * The underlying google.maps.Map object @@ -89,167 +87,212 @@ export class GoogleMap implements OnChanges, OnInit, OnDestroy { @Input() mapTypeId: google.maps.MapTypeId | undefined; @Input() - set center(center: google.maps.LatLngLiteral|google.maps.LatLng) { - this._center.next(center); + set center(center: google.maps.LatLngLiteral | google.maps.LatLng) { + this._center = center; } + private _center: google.maps.LatLngLiteral | google.maps.LatLng; + @Input() set zoom(zoom: number) { - this._zoom.next(zoom); + this._zoom = zoom; } + private _zoom: number; + @Input() set options(options: google.maps.MapOptions) { - this._options.next(options || DEFAULT_OPTIONS); + this._options = options || DEFAULT_OPTIONS; } + private _options = DEFAULT_OPTIONS; + + /** Event emitted when the map is initialized. */ + @Output() readonly mapInitialized: EventEmitter = + new EventEmitter(); + + /** + * See + * https://developers.google.com/maps/documentation/javascript/events#auth-errors + */ + @Output() readonly authFailure: EventEmitter = new EventEmitter(); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.bounds_changed */ - @Output() - boundsChanged: Observable = this._eventManager.getLazyEmitter('bounds_changed'); + @Output() readonly boundsChanged: Observable = + this._eventManager.getLazyEmitter('bounds_changed'); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.center_changed */ - @Output() - centerChanged: Observable = this._eventManager.getLazyEmitter('center_changed'); + @Output() readonly centerChanged: Observable = + this._eventManager.getLazyEmitter('center_changed'); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.click */ - @Output() - mapClick: Observable = - this._eventManager.getLazyEmitter('click'); + @Output() readonly mapClick: Observable = + this._eventManager.getLazyEmitter( + 'click', + ); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.dblclick */ - @Output() - mapDblclick: Observable = - this._eventManager.getLazyEmitter('dblclick'); + @Output() readonly mapDblclick: Observable = + this._eventManager.getLazyEmitter('dblclick'); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.drag */ - @Output() mapDrag: Observable = this._eventManager.getLazyEmitter('drag'); + @Output() readonly mapDrag: Observable = this._eventManager.getLazyEmitter('drag'); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.dragend */ - @Output() mapDragend: Observable = this._eventManager.getLazyEmitter('dragend'); + @Output() readonly mapDragend: Observable = + this._eventManager.getLazyEmitter('dragend'); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.dragstart */ - @Output() mapDragstart: Observable = this._eventManager.getLazyEmitter('dragstart'); + @Output() readonly mapDragstart: Observable = + this._eventManager.getLazyEmitter('dragstart'); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.heading_changed */ - @Output() - headingChanged: Observable = this._eventManager.getLazyEmitter('heading_changed'); + @Output() readonly headingChanged: Observable = + this._eventManager.getLazyEmitter('heading_changed'); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.idle */ - @Output() idle: Observable = this._eventManager.getLazyEmitter('idle'); + @Output() readonly idle: Observable = this._eventManager.getLazyEmitter('idle'); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.maptypeid_changed */ - @Output() - maptypeidChanged: Observable = this._eventManager.getLazyEmitter('maptypeid_changed'); + @Output() readonly maptypeidChanged: Observable = + this._eventManager.getLazyEmitter('maptypeid_changed'); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.mousemove */ @Output() - mapMousemove: Observable = - this._eventManager.getLazyEmitter('mousemove'); + readonly mapMousemove: Observable = + this._eventManager.getLazyEmitter('mousemove'); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.mouseout */ - @Output() - mapMouseout: Observable = - this._eventManager.getLazyEmitter('mouseout'); + @Output() readonly mapMouseout: Observable = + this._eventManager.getLazyEmitter('mouseout'); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.mouseover */ - @Output() - mapMouseover: Observable = - this._eventManager.getLazyEmitter('mouseover'); + @Output() readonly mapMouseover: Observable = + this._eventManager.getLazyEmitter('mouseover'); /** * See * developers.google.com/maps/documentation/javascript/reference/map#Map.projection_changed */ - @Output() - projectionChanged: Observable = - this._eventManager.getLazyEmitter('projection_changed'); + @Output() readonly projectionChanged: Observable = + this._eventManager.getLazyEmitter('projection_changed'); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.rightclick */ - @Output() - mapRightclick: Observable = - this._eventManager.getLazyEmitter('rightclick'); + @Output() readonly mapRightclick: Observable = + this._eventManager.getLazyEmitter('rightclick'); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.tilesloaded */ - @Output() tilesloaded: Observable = this._eventManager.getLazyEmitter('tilesloaded'); + @Output() readonly tilesloaded: Observable = + this._eventManager.getLazyEmitter('tilesloaded'); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.tilt_changed */ - @Output() tiltChanged: Observable = this._eventManager.getLazyEmitter('tilt_changed'); + @Output() readonly tiltChanged: Observable = + this._eventManager.getLazyEmitter('tilt_changed'); /** * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.zoom_changed */ - @Output() zoomChanged: Observable = this._eventManager.getLazyEmitter('zoom_changed'); + @Output() readonly zoomChanged: Observable = + this._eventManager.getLazyEmitter('zoom_changed'); constructor( private readonly _elementRef: ElementRef, private _ngZone: NgZone, - @Inject(PLATFORM_ID) platformId: Object) { - + @Inject(PLATFORM_ID) platformId: Object, + ) { this._isBrowser = isPlatformBrowser(platformId); if (this._isBrowser) { const googleMapsWindow: GoogleMapsWindow = window; if (!googleMapsWindow.google && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw Error( - 'Namespace google not found, cannot construct embedded google ' + + 'Namespace google not found, cannot construct embedded google ' + 'map. Please install the Google Maps JavaScript API: ' + 'https://developers.google.com/maps/documentation/javascript/' + - 'tutorial#Loading_the_Maps_API'); + 'tutorial#Loading_the_Maps_API', + ); } + + this._existingAuthFailureCallback = googleMapsWindow.gm_authFailure; + googleMapsWindow.gm_authFailure = () => { + if (this._existingAuthFailureCallback) { + this._existingAuthFailureCallback(); + } + this.authFailure.emit(); + }; } } - ngOnChanges() { - this._setSize(); - if (this.googleMap && this.mapTypeId) { - this.googleMap.setMapTypeId(this.mapTypeId); + ngOnChanges(changes: SimpleChanges) { + if (changes['height'] || changes['width']) { + this._setSize(); + } + + const googleMap = this.googleMap; + + if (googleMap) { + if (changes['options']) { + googleMap.setOptions(this._combineOptions()); + } + + if (changes['center'] && this._center) { + googleMap.setCenter(this._center); + } + + // Note that the zoom can be zero. + if (changes['zoom'] && this._zoom != null) { + googleMap.setZoom(this._zoom); + } + + if (changes['mapTypeId'] && this.mapTypeId) { + googleMap.setMapTypeId(this.mapTypeId); + } } } @@ -258,22 +301,25 @@ export class GoogleMap implements OnChanges, OnInit, OnDestroy { if (this._isBrowser) { this._mapEl = this._elementRef.nativeElement.querySelector('.map-container')!; this._setSize(); - this._googleMapChanges = this._initializeMap(this._combineOptions()); - this._googleMapChanges.subscribe((googleMap: google.maps.Map) => { - this.googleMap = googleMap; - this._eventManager.setTarget(this.googleMap); - }); - this._watchForOptionsChanges(); - this._watchForCenterChanges(); - this._watchForZoomChanges(); + // Create the object outside the zone so its events don't trigger change detection. + // We'll bring it back in inside the `MapEventManager` only for the events that the + // user has subscribed to. + this._ngZone.runOutsideAngular(() => { + this.googleMap = new google.maps.Map(this._mapEl, this._combineOptions()); + }); + this._eventManager.setTarget(this.googleMap); + this.mapInitialized.emit(this.googleMap); } } ngOnDestroy() { this._eventManager.destroy(); - this._destroy.next(); - this._destroy.complete(); + + if (this._isBrowser) { + const googleMapsWindow: GoogleMapsWindow = window; + googleMapsWindow.gm_authFailure = this._existingAuthFailureCallback; + } } /** @@ -281,8 +327,9 @@ export class GoogleMap implements OnChanges, OnInit, OnDestroy { * https://developers.google.com/maps/documentation/javascript/reference/map#Map.fitBounds */ fitBounds( - bounds: google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral, - padding?: number|google.maps.Padding) { + bounds: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral, + padding?: number | google.maps.Padding, + ) { this._assertInitialized(); this.googleMap.fitBounds(bounds, padding); } @@ -300,7 +347,7 @@ export class GoogleMap implements OnChanges, OnInit, OnDestroy { * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.panTo */ - panTo(latLng: google.maps.LatLng|google.maps.LatLngLiteral) { + panTo(latLng: google.maps.LatLng | google.maps.LatLngLiteral) { this._assertInitialized(); this.googleMap.panTo(latLng); } @@ -310,8 +357,9 @@ export class GoogleMap implements OnChanges, OnInit, OnDestroy { * https://developers.google.com/maps/documentation/javascript/reference/map#Map.panToBounds */ panToBounds( - latLngBounds: google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral, - padding?: number|google.maps.Padding) { + latLngBounds: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral, + padding?: number | google.maps.Padding, + ) { this._assertInitialized(); this.googleMap.panToBounds(latLngBounds, padding); } @@ -320,7 +368,7 @@ export class GoogleMap implements OnChanges, OnInit, OnDestroy { * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.getBounds */ - getBounds(): google.maps.LatLngBounds|null { + getBounds(): google.maps.LatLngBounds | null { this._assertInitialized(); return this.googleMap.getBounds() || null; } @@ -329,7 +377,7 @@ export class GoogleMap implements OnChanges, OnInit, OnDestroy { * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.getCenter */ - getCenter(): google.maps.LatLng { + getCenter(): google.maps.LatLng | undefined { this._assertInitialized(); return this.googleMap.getCenter(); } @@ -338,7 +386,7 @@ export class GoogleMap implements OnChanges, OnInit, OnDestroy { * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.getClickableIcons */ - getClickableIcons(): boolean { + getClickableIcons(): boolean | undefined { this._assertInitialized(); return this.googleMap.getClickableIcons(); } @@ -347,7 +395,7 @@ export class GoogleMap implements OnChanges, OnInit, OnDestroy { * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.getHeading */ - getHeading(): number { + getHeading(): number | undefined { this._assertInitialized(); return this.googleMap.getHeading(); } @@ -356,7 +404,7 @@ export class GoogleMap implements OnChanges, OnInit, OnDestroy { * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.getMapTypeId */ - getMapTypeId(): google.maps.MapTypeId|string { + getMapTypeId(): google.maps.MapTypeId | string | undefined { this._assertInitialized(); return this.googleMap.getMapTypeId(); } @@ -365,9 +413,9 @@ export class GoogleMap implements OnChanges, OnInit, OnDestroy { * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.getProjection */ - getProjection(): google.maps.Projection|null { + getProjection(): google.maps.Projection | null { this._assertInitialized(); - return this.googleMap.getProjection(); + return this.googleMap.getProjection() || null; } /** @@ -383,7 +431,7 @@ export class GoogleMap implements OnChanges, OnInit, OnDestroy { * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.getTilt */ - getTilt(): number { + getTilt(): number | undefined { this._assertInitialized(); return this.googleMap.getTilt(); } @@ -392,7 +440,7 @@ export class GoogleMap implements OnChanges, OnInit, OnDestroy { * See * https://developers.google.com/maps/documentation/javascript/reference/map#Map.getZoom */ - getZoom(): number { + getZoom(): number | undefined { this._assertInitialized(); return this.googleMap.getZoom(); } @@ -437,73 +485,33 @@ export class GoogleMap implements OnChanges, OnInit, OnDestroy { if (this._mapEl) { const styles = this._mapEl.style; styles.height = - this.height === null ? '' : (coerceCssPixelValue(this.height) || DEFAULT_HEIGHT); - styles.width = this.width === null ? '' : (coerceCssPixelValue(this.width) || DEFAULT_WIDTH); + this.height === null ? '' : coerceCssPixelValue(this.height) || DEFAULT_HEIGHT; + styles.width = this.width === null ? '' : coerceCssPixelValue(this.width) || DEFAULT_WIDTH; } } /** Combines the center and zoom and the other map options into a single object */ - private _combineOptions(): Observable { - return combineLatest([this._options, this._center, this._zoom]) - .pipe(map(([options, center, zoom]) => { - const combinedOptions: google.maps.MapOptions = { - ...options, - // It's important that we set **some** kind of `center` and `zoom`, otherwise - // Google Maps will render a blank rectangle which looks broken. - center: center || options.center || DEFAULT_OPTIONS.center, - zoom: zoom ?? options.zoom ?? DEFAULT_OPTIONS.zoom, - mapTypeId: this.mapTypeId - }; - return combinedOptions; - })); - } - - private _initializeMap(optionsChanges: Observable): - Observable { - return optionsChanges.pipe( - take(1), - map(options => { - // Create the object outside the zone so its events don't trigger change detection. - // We'll bring it back in inside the `MapEventManager` only for the events that the - // user has subscribed to. - return this._ngZone.runOutsideAngular(() => new google.maps.Map(this._mapEl, options)); - }), - shareReplay(1)); - } - - private _watchForOptionsChanges() { - combineLatest([this._googleMapChanges, this._options]) - .pipe(takeUntil(this._destroy)) - .subscribe(([googleMap, options]) => { - googleMap.setOptions(options); - }); - } - - private _watchForCenterChanges() { - combineLatest([this._googleMapChanges, this._center]) - .pipe(takeUntil(this._destroy)) - .subscribe(([googleMap, center]) => { - if (center) { - googleMap.setCenter(center); - } - }); - } - - private _watchForZoomChanges() { - combineLatest([this._googleMapChanges, this._zoom]) - .pipe(takeUntil(this._destroy)) - .subscribe(([googleMap, zoom]) => { - if (zoom !== undefined) { - googleMap.setZoom(zoom); - } - }); + private _combineOptions(): google.maps.MapOptions { + const options = this._options || {}; + return { + ...options, + // It's important that we set **some** kind of `center` and `zoom`, otherwise + // Google Maps will render a blank rectangle which looks broken. + center: this._center || options.center || DEFAULT_OPTIONS.center, + zoom: this._zoom ?? options.zoom ?? DEFAULT_OPTIONS.zoom, + // Passing in an undefined `mapTypeId` seems to break tile loading + // so make sure that we have some kind of default (see #22082). + mapTypeId: this.mapTypeId || options.mapTypeId || DEFAULT_OPTIONS.mapTypeId, + }; } /** Asserts that the map has been initialized. */ private _assertInitialized(): asserts this is {googleMap: google.maps.Map} { if (!this.googleMap && (typeof ngDevMode === 'undefined' || ngDevMode)) { - throw Error('Cannot access Google Map information before the API has been initialized. ' + - 'Please wait for the API to load before trying to interact with it.'); + throw Error( + 'Cannot access Google Map information before the API has been initialized. ' + + 'Please wait for the API to load before trying to interact with it.', + ); } } } diff --git a/src/google-maps/google-maps-module.ts b/src/google-maps/google-maps-module.ts index cdb560aeb280..45f354f11fdf 100644 --- a/src/google-maps/google-maps-module.ts +++ b/src/google-maps/google-maps-module.ts @@ -12,6 +12,7 @@ import {GoogleMap} from './google-map/google-map'; import {MapBaseLayer} from './map-base-layer'; import {MapBicyclingLayer} from './map-bicycling-layer/map-bicycling-layer'; import {MapCircle} from './map-circle/map-circle'; +import {MapDirectionsRenderer} from './map-directions-renderer/map-directions-renderer'; import {MapGroundOverlay} from './map-ground-overlay/map-ground-overlay'; import {MapInfoWindow} from './map-info-window/map-info-window'; import {MapKmlLayer} from './map-kml-layer/map-kml-layer'; @@ -22,12 +23,14 @@ import {MapPolyline} from './map-polyline/map-polyline'; import {MapRectangle} from './map-rectangle/map-rectangle'; import {MapTrafficLayer} from './map-traffic-layer/map-traffic-layer'; import {MapTransitLayer} from './map-transit-layer/map-transit-layer'; +import {MapHeatmapLayer} from './map-heatmap-layer/map-heatmap-layer'; const COMPONENTS = [ GoogleMap, MapBaseLayer, MapBicyclingLayer, MapCircle, + MapDirectionsRenderer, MapGroundOverlay, MapInfoWindow, MapKmlLayer, @@ -38,11 +41,11 @@ const COMPONENTS = [ MapRectangle, MapTrafficLayer, MapTransitLayer, + MapHeatmapLayer, ]; @NgModule({ declarations: COMPONENTS, exports: COMPONENTS, }) -export class GoogleMapsModule { -} +export class GoogleMapsModule {} diff --git a/src/google-maps/map-anchor-point.ts b/src/google-maps/map-anchor-point.ts index ee394ff0f9d7..85876ae8c558 100644 --- a/src/google-maps/map-anchor-point.ts +++ b/src/google-maps/map-anchor-point.ts @@ -7,7 +7,7 @@ */ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 -/// +/// export interface MapAnchorPoint { getAnchor(): google.maps.MVCObject; diff --git a/src/google-maps/map-base-layer.ts b/src/google-maps/map-base-layer.ts index ec46c6502caf..782be10a703e 100644 --- a/src/google-maps/map-base-layer.ts +++ b/src/google-maps/map-base-layer.ts @@ -7,7 +7,7 @@ */ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 -/// +/// import {Directive, NgZone, OnDestroy, OnInit} from '@angular/core'; @@ -37,8 +37,9 @@ export class MapBaseLayer implements OnInit, OnDestroy { private _assertInitialized() { if (!this._map.googleMap) { throw Error( - 'Cannot access Google Map information before the API has been initialized. ' + - 'Please wait for the API to load before trying to interact with it.'); + 'Cannot access Google Map information before the API has been initialized. ' + + 'Please wait for the API to load before trying to interact with it.', + ); } } diff --git a/src/google-maps/map-bicycling-layer/map-bicycling-layer.spec.ts b/src/google-maps/map-bicycling-layer/map-bicycling-layer.spec.ts index 53ed9cb85ebc..a8a281606266 100644 --- a/src/google-maps/map-bicycling-layer/map-bicycling-layer.spec.ts +++ b/src/google-maps/map-bicycling-layer/map-bicycling-layer.spec.ts @@ -13,12 +13,14 @@ import { describe('MapBicyclingLayer', () => { let mapSpy: jasmine.SpyObj; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [GoogleMapsModule], - declarations: [TestApp], - }); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + declarations: [TestApp], + }); + }), + ); beforeEach(() => { TestBed.compileComponents(); @@ -34,7 +36,7 @@ describe('MapBicyclingLayer', () => { it('initializes a Google Map Bicycling Layer', () => { const bicyclingLayerSpy = createBicyclingLayerSpy(); const bicyclingLayerConstructorSpy = - createBicyclingLayerConstructorSpy(bicyclingLayerSpy).and.callThrough(); + createBicyclingLayerConstructorSpy(bicyclingLayerSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); fixture.detectChanges(); @@ -50,5 +52,4 @@ describe('MapBicyclingLayer', () => { `, }) -class TestApp { -} +class TestApp {} diff --git a/src/google-maps/map-bicycling-layer/map-bicycling-layer.ts b/src/google-maps/map-bicycling-layer/map-bicycling-layer.ts index 96bf2994f06e..a329dd578ae5 100644 --- a/src/google-maps/map-bicycling-layer/map-bicycling-layer.ts +++ b/src/google-maps/map-bicycling-layer/map-bicycling-layer.ts @@ -7,7 +7,7 @@ */ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 -/// +/// import {Directive} from '@angular/core'; @@ -30,16 +30,16 @@ export class MapBicyclingLayer extends MapBaseLayer { */ bicyclingLayer?: google.maps.BicyclingLayer; - protected _initializeObject() { + protected override _initializeObject() { this.bicyclingLayer = new google.maps.BicyclingLayer(); } - protected _setMap() { + protected override _setMap() { this._assertLayerInitialized(); this.bicyclingLayer.setMap(this._map.googleMap!); } - protected _unsetMap() { + protected override _unsetMap() { if (this.bicyclingLayer) { this.bicyclingLayer.setMap(null); } @@ -48,8 +48,9 @@ export class MapBicyclingLayer extends MapBaseLayer { private _assertLayerInitialized(): asserts this is {bicyclingLayer: google.maps.BicyclingLayer} { if (!this.bicyclingLayer) { throw Error( - 'Cannot interact with a Google Map Bicycling Layer before it has been initialized. ' + - 'Please wait for the Transit Layer to load before trying to interact with it.'); + 'Cannot interact with a Google Map Bicycling Layer before it has been initialized. ' + + 'Please wait for the Transit Layer to load before trying to interact with it.', + ); } } } diff --git a/src/google-maps/map-circle/README.md b/src/google-maps/map-circle/README.md index f73ccae95ebf..d7783d20d0d4 100644 --- a/src/google-maps/map-circle/README.md +++ b/src/google-maps/map-circle/README.md @@ -17,7 +17,7 @@ export class GoogleMapDemo { zoom = 4; circleCenter: google.maps.LatLngLiteral = {lat: 10, lng: 15}; - radius: 3; + radius = 3; } ``` diff --git a/src/google-maps/map-circle/map-circle.spec.ts b/src/google-maps/map-circle/map-circle.spec.ts index a5fca2244bd8..e38451688f98 100644 --- a/src/google-maps/map-circle/map-circle.spec.ts +++ b/src/google-maps/map-circle/map-circle.spec.ts @@ -19,20 +19,22 @@ describe('MapCircle', () => { let circleRadius: number; let circleOptions: google.maps.CircleOptions; - beforeEach(waitForAsync(() => { - circleCenter = {lat: 30, lng: 15}; - circleRadius = 15; - circleOptions = { - center: circleCenter, - radius: circleRadius, - strokeColor: 'grey', - strokeOpacity: 0.8, - }; - TestBed.configureTestingModule({ - imports: [GoogleMapsModule], - declarations: [TestApp], - }); - })); + beforeEach( + waitForAsync(() => { + circleCenter = {lat: 30, lng: 15}; + circleRadius = 15; + circleOptions = { + center: circleCenter, + radius: circleRadius, + strokeColor: 'grey', + strokeOpacity: 0.8, + }; + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + declarations: [TestApp], + }); + }), + ); beforeEach(() => { TestBed.compileComponents(); @@ -92,8 +94,9 @@ describe('MapCircle', () => { createCircleConstructorSpy(circleSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); - const circleComponent = - fixture.debugElement.query(By.directive(MapCircle))!.injector.get(MapCircle); + const circleComponent = fixture.debugElement + .query(By.directive(MapCircle))! + .injector.get(MapCircle); fixture.detectChanges(); circleComponent.getCenter(); diff --git a/src/google-maps/map-circle/map-circle.ts b/src/google-maps/map-circle/map-circle.ts index 535d77fb0c3b..283077ba5c91 100644 --- a/src/google-maps/map-circle/map-circle.ts +++ b/src/google-maps/map-circle/map-circle.ts @@ -7,7 +7,7 @@ */ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 -/// +/// import {Directive, Input, NgZone, OnDestroy, OnInit, Output} from '@angular/core'; import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; @@ -27,9 +27,10 @@ import {MapEventManager} from '../map-event-manager'; export class MapCircle implements OnInit, OnDestroy { private _eventManager = new MapEventManager(this._ngZone); private readonly _options = new BehaviorSubject({}); - private readonly _center = - new BehaviorSubject(undefined); - private readonly _radius = new BehaviorSubject(undefined); + private readonly _center = new BehaviorSubject< + google.maps.LatLng | google.maps.LatLngLiteral | undefined + >(undefined); + private readonly _radius = new BehaviorSubject(undefined); private readonly _destroyed = new Subject(); @@ -38,7 +39,7 @@ export class MapCircle implements OnInit, OnDestroy { * * @see developers.google.com/maps/documentation/javascript/reference/polygon#Circle */ - circle?: google.maps.Circle; // initialized in ngOnInit + circle?: google.maps.Circle; // initialized in ngOnInit @Input() set options(options: google.maps.CircleOptions) { @@ -46,7 +47,7 @@ export class MapCircle implements OnInit, OnDestroy { } @Input() - set center(center: google.maps.LatLng|google.maps.LatLngLiteral) { + set center(center: google.maps.LatLng | google.maps.LatLngLiteral) { this._center.next(center); } @@ -59,119 +60,110 @@ export class MapCircle implements OnInit, OnDestroy { * @see * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.center_changed */ - @Output() - centerChanged: Observable = this._eventManager.getLazyEmitter('center_changed'); + @Output() readonly centerChanged: Observable = + this._eventManager.getLazyEmitter('center_changed'); /** * @see * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.click */ - @Output() - circleClick: Observable = - this._eventManager.getLazyEmitter('click'); + @Output() readonly circleClick: Observable = + this._eventManager.getLazyEmitter('click'); /** * @see * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.dblclick */ - @Output() - circleDblclick: Observable = - this._eventManager.getLazyEmitter('dblclick'); + @Output() readonly circleDblclick: Observable = + this._eventManager.getLazyEmitter('dblclick'); /** * @see * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.drag */ - @Output() - circleDrag: Observable = - this._eventManager.getLazyEmitter('drag'); + @Output() readonly circleDrag: Observable = + this._eventManager.getLazyEmitter('drag'); /** * @see * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.dragend */ - @Output() - circleDragend: Observable = - this._eventManager.getLazyEmitter('dragend'); + @Output() readonly circleDragend: Observable = + this._eventManager.getLazyEmitter('dragend'); /** * @see * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.dragstart */ - @Output() - circleDragstart: Observable = - this._eventManager.getLazyEmitter('dragstart'); + @Output() readonly circleDragstart: Observable = + this._eventManager.getLazyEmitter('dragstart'); /** * @see * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.mousedown */ - @Output() - circleMousedown: Observable = - this._eventManager.getLazyEmitter('mousedown'); + @Output() readonly circleMousedown: Observable = + this._eventManager.getLazyEmitter('mousedown'); /** * @see * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.mousemove */ - @Output() - circleMousemove: Observable = - this._eventManager.getLazyEmitter('mousemove'); + @Output() readonly circleMousemove: Observable = + this._eventManager.getLazyEmitter('mousemove'); /** * @see * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.mouseout */ - @Output() - circleMouseout: Observable = - this._eventManager.getLazyEmitter('mouseout'); + @Output() readonly circleMouseout: Observable = + this._eventManager.getLazyEmitter('mouseout'); /** * @see * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.mouseover */ - @Output() - circleMouseover: Observable = - this._eventManager.getLazyEmitter('mouseover'); + @Output() readonly circleMouseover: Observable = + this._eventManager.getLazyEmitter('mouseover'); /** * @see * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.mouseup */ - @Output() - circleMouseup: Observable = - this._eventManager.getLazyEmitter('mouseup'); + @Output() readonly circleMouseup: Observable = + this._eventManager.getLazyEmitter('mouseup'); /** * @see * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.radius_changed */ - @Output() - radiusChanged: Observable = this._eventManager.getLazyEmitter('radius_changed'); + @Output() readonly radiusChanged: Observable = + this._eventManager.getLazyEmitter('radius_changed'); /** * @see * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.rightclick */ - @Output() - circleRightclick: Observable = - this._eventManager.getLazyEmitter('rightclick'); + @Output() readonly circleRightclick: Observable = + this._eventManager.getLazyEmitter('rightclick'); constructor(private readonly _map: GoogleMap, private readonly _ngZone: NgZone) {} ngOnInit() { if (this._map._isBrowser) { - this._combineOptions().pipe(take(1)).subscribe(options => { - // Create the object outside the zone so its events don't trigger change detection. - // We'll bring it back in inside the `MapEventManager` only for the events that the - // user has subscribed to. - this._ngZone.runOutsideAngular(() => { - this.circle = new google.maps.Circle(options); + this._combineOptions() + .pipe(take(1)) + .subscribe(options => { + // Create the object outside the zone so its events don't trigger change detection. + // We'll bring it back in inside the `MapEventManager` only for the events that the + // user has subscribed to. + this._ngZone.runOutsideAngular(() => { + this.circle = new google.maps.Circle(options); + }); + this._assertInitialized(); + this.circle.setMap(this._map.googleMap!); + this._eventManager.setTarget(this.circle); }); - this._assertInitialized(); - this.circle.setMap(this._map.googleMap!); - this._eventManager.setTarget(this.circle); - }); this._watchForOptionsChanges(); this._watchForCenterChanges(); @@ -192,7 +184,7 @@ export class MapCircle implements OnInit, OnDestroy { * @see * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.getBounds */ - getBounds(): google.maps.LatLngBounds { + getBounds(): google.maps.LatLngBounds | null { this._assertInitialized(); return this.circle.getBounds(); } @@ -201,7 +193,7 @@ export class MapCircle implements OnInit, OnDestroy { * @see * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.getCenter */ - getCenter(): google.maps.LatLng { + getCenter(): google.maps.LatLng | null { this._assertInitialized(); return this.circle.getCenter(); } @@ -226,7 +218,7 @@ export class MapCircle implements OnInit, OnDestroy { /** * @see - * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.getCenter + * developers.google.com/maps/documentation/javascript/reference/polygon#Circle.getRadius */ getRadius(): number { this._assertInitialized(); @@ -243,15 +235,16 @@ export class MapCircle implements OnInit, OnDestroy { } private _combineOptions(): Observable { - return combineLatest([this._options, this._center, this._radius]) - .pipe(map(([options, center, radius]) => { - const combinedOptions: google.maps.CircleOptions = { - ...options, - center: center || options.center, - radius: radius !== undefined ? radius : options.radius, - }; - return combinedOptions; - })); + return combineLatest([this._options, this._center, this._radius]).pipe( + map(([options, center, radius]) => { + const combinedOptions: google.maps.CircleOptions = { + ...options, + center: center || options.center, + radius: radius !== undefined ? radius : options.radius, + }; + return combinedOptions; + }), + ); } private _watchForOptionsChanges() { @@ -284,12 +277,14 @@ export class MapCircle implements OnInit, OnDestroy { if (!this._map.googleMap) { throw Error( 'Cannot access Google Map information before the API has been initialized. ' + - 'Please wait for the API to load before trying to interact with it.'); + 'Please wait for the API to load before trying to interact with it.', + ); } if (!this.circle) { throw Error( 'Cannot interact with a Google Map Circle before it has been ' + - 'initialized. Please wait for the Circle to load before trying to interact with it.'); + 'initialized. Please wait for the Circle to load before trying to interact with it.', + ); } } } diff --git a/src/google-maps/map-directions-renderer/README.md b/src/google-maps/map-directions-renderer/README.md new file mode 100644 index 000000000000..1b53a81fa46e --- /dev/null +++ b/src/google-maps/map-directions-renderer/README.md @@ -0,0 +1,57 @@ +# MapDirectionsRenderer + +The `MapDirectionsRenderer` component wraps the [`google.maps.DirectionsRenderer` class](https://developers.google.com/maps/documentation/javascript/reference/directions#DirectionsRenderer) from the Google Maps JavaScript API. This can easily be used with the `MapDirectionsService` that wraps [`google.maps.DirectionsService`](https://developers.google.com/maps/documentation/javascript/reference/directions#DirectionsService) which is designed to be used with Angular by returning an `Observable` response and works inside the Angular Zone. + +The `MapDirectionsService`, like the `google.maps.DirectionsService`, has a single method, `route`. Normally, the `google.maps.DirectionsService` takes two arguments, a `google.maps.DirectionsRequest` and a callback that takes the `google.maps.DirectionsResult` and `google.maps.DirectionsStatus` as arguments. The `MapDirectionsService` route method takes the `google.maps.DirectionsRequest` as the single argument, and returns an `Observable` of a `MapDirectionsResponse`, which is an interface defined as follows: + +```typescript +export interface MapDirectionsResponse { + status: google.maps.DirectionsStatus; + result?: google.maps.DirectionsResult; +} +``` + +The most common usecase for the component and class would be to use the `MapDirectionsService` to request a route between two points on the map, and then render them on the map using the `MapDirectionsRenderer`. + +## Loading the Library + +Using the `MapDirectionsService` requires the Directions API to be enabled in Google Cloud Console on the same project as the one set up for the Google Maps JavaScript API, and requires an API key that has billing enabled. See [here](https://developers.google.com/maps/documentation/javascript/directions#GetStarted) for details. + +## Example + +```typescript +// google-maps-demo.component.ts +import {MapDirectionsService} from '@angular/google-maps'; +import {Component} from '@angular/core'; + +@Component({ + selector: 'google-map-demo', + templateUrl: 'google-map-demo.html', +}) +export class GoogleMapDemo { + center: google.maps.LatLngLiteral = {lat: 24, lng: 12}; + zoom = 4; + + readonly directionsResults$: Observable; + + constructor(mapDirectionsService: MapDirectionsService) { + const request: google.maps.DirectionsRequest = { + destination: {lat: 12, lng: 4}, + origin: {lat: 14, lng: 8}, + travelMode: google.maps.TravelMode.DRIVING + }; + this.directionsResults$ = mapDirectionsService.route(request).pipe(map(response => response.result)); + } +} +``` + +```html + + + + +``` diff --git a/src/google-maps/map-directions-renderer/map-directions-renderer.spec.ts b/src/google-maps/map-directions-renderer/map-directions-renderer.spec.ts new file mode 100644 index 000000000000..f5d05df05274 --- /dev/null +++ b/src/google-maps/map-directions-renderer/map-directions-renderer.spec.ts @@ -0,0 +1,145 @@ +import {Component, ViewChild} from '@angular/core'; +import {TestBed, waitForAsync} from '@angular/core/testing'; +import {By} from '@angular/platform-browser'; +import {MapDirectionsRenderer} from './map-directions-renderer'; +import {DEFAULT_OPTIONS} from '../google-map/google-map'; +import {GoogleMapsModule} from '../google-maps-module'; +import { + createDirectionsRendererConstructorSpy, + createDirectionsRendererSpy, + createMapConstructorSpy, + createMapSpy, +} from '../testing/fake-google-map-utils'; + +const DEFAULT_DIRECTIONS: google.maps.DirectionsResult = { + geocoded_waypoints: [], + routes: [], +}; + +describe('MapDirectionsRenderer', () => { + let mapSpy: jasmine.SpyObj; + + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + declarations: [TestApp], + }); + }), + ); + + beforeEach(() => { + TestBed.compileComponents(); + + mapSpy = createMapSpy(DEFAULT_OPTIONS); + createMapConstructorSpy(mapSpy).and.callThrough(); + }); + + afterEach(() => { + (window.google as any) = undefined; + }); + + it('initializes a Google Maps DirectionsRenderer', () => { + const directionsRendererSpy = createDirectionsRendererSpy({directions: DEFAULT_DIRECTIONS}); + const directionsRendererConstructorSpy = + createDirectionsRendererConstructorSpy(directionsRendererSpy).and.callThrough(); + + const fixture = TestBed.createComponent(TestApp); + fixture.componentInstance.options = {directions: DEFAULT_DIRECTIONS}; + fixture.detectChanges(); + + expect(directionsRendererConstructorSpy).toHaveBeenCalledWith({ + directions: DEFAULT_DIRECTIONS, + map: jasmine.any(Object), + }); + expect(directionsRendererSpy.setMap).toHaveBeenCalledWith(mapSpy); + }); + + it('sets directions from directions input', () => { + const directionsRendererSpy = createDirectionsRendererSpy({directions: DEFAULT_DIRECTIONS}); + const directionsRendererConstructorSpy = + createDirectionsRendererConstructorSpy(directionsRendererSpy).and.callThrough(); + + const fixture = TestBed.createComponent(TestApp); + fixture.componentInstance.directions = DEFAULT_DIRECTIONS; + fixture.detectChanges(); + + expect(directionsRendererConstructorSpy).toHaveBeenCalledWith({ + directions: DEFAULT_DIRECTIONS, + map: jasmine.any(Object), + }); + expect(directionsRendererSpy.setMap).toHaveBeenCalledWith(mapSpy); + }); + + it('gives precedence to directions over options', () => { + const updatedDirections: google.maps.DirectionsResult = { + geocoded_waypoints: [{partial_match: false, place_id: 'test', types: []}], + routes: [], + }; + const directionsRendererSpy = createDirectionsRendererSpy({directions: updatedDirections}); + const directionsRendererConstructorSpy = + createDirectionsRendererConstructorSpy(directionsRendererSpy).and.callThrough(); + + const fixture = TestBed.createComponent(TestApp); + fixture.componentInstance.options = {directions: DEFAULT_DIRECTIONS}; + fixture.componentInstance.directions = updatedDirections; + fixture.detectChanges(); + + expect(directionsRendererConstructorSpy).toHaveBeenCalledWith({ + directions: updatedDirections, + map: jasmine.any(Object), + }); + expect(directionsRendererSpy.setMap).toHaveBeenCalledWith(mapSpy); + }); + + it('exposes methods that provide information from the DirectionsRenderer', () => { + const directionsRendererSpy = createDirectionsRendererSpy({}); + createDirectionsRendererConstructorSpy(directionsRendererSpy).and.callThrough(); + + const fixture = TestBed.createComponent(TestApp); + + const directionsRendererComponent = fixture.debugElement + .query(By.directive(MapDirectionsRenderer))! + .injector.get(MapDirectionsRenderer); + fixture.detectChanges(); + + directionsRendererSpy.getDirections.and.returnValue(DEFAULT_DIRECTIONS); + expect(directionsRendererComponent.getDirections()).toBe(DEFAULT_DIRECTIONS); + + directionsRendererComponent.getPanel(); + expect(directionsRendererSpy.getPanel).toHaveBeenCalled(); + + directionsRendererSpy.getRouteIndex.and.returnValue(10); + expect(directionsRendererComponent.getRouteIndex()).toBe(10); + }); + + it('initializes DirectionsRenderer event handlers', () => { + const directionsRendererSpy = createDirectionsRendererSpy({}); + createDirectionsRendererConstructorSpy(directionsRendererSpy).and.callThrough(); + + const fixture = TestBed.createComponent(TestApp); + fixture.detectChanges(); + + expect(directionsRendererSpy.addListener).toHaveBeenCalledWith( + 'directions_changed', + jasmine.any(Function), + ); + }); +}); + +@Component({ + selector: 'test-app', + template: ` + + + `, +}) +class TestApp { + @ViewChild(MapDirectionsRenderer) directionsRenderer: MapDirectionsRenderer; + options?: google.maps.DirectionsRendererOptions; + directions?: google.maps.DirectionsResult; + + handleDirectionsChanged() {} +} diff --git a/src/google-maps/map-directions-renderer/map-directions-renderer.ts b/src/google-maps/map-directions-renderer/map-directions-renderer.ts new file mode 100644 index 000000000000..80206b4f27be --- /dev/null +++ b/src/google-maps/map-directions-renderer/map-directions-renderer.ts @@ -0,0 +1,160 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 +/// + +import { + Directive, + Input, + NgZone, + OnChanges, + OnDestroy, + OnInit, + Output, + SimpleChanges, +} from '@angular/core'; +import {Observable} from 'rxjs'; +import {GoogleMap} from '../google-map/google-map'; +import {MapEventManager} from '../map-event-manager'; + +/** + * Angular component that renders a Google Maps Directions Renderer via the Google Maps + * JavaScript API. + * + * See developers.google.com/maps/documentation/javascript/reference/directions#DirectionsRenderer + */ +@Directive({ + selector: 'map-directions-renderer', + exportAs: 'mapDirectionsRenderer', +}) +export class MapDirectionsRenderer implements OnInit, OnChanges, OnDestroy { + private _eventManager = new MapEventManager(this._ngZone); + + /** + * See developers.google.com/maps/documentation/javascript/reference/directions + * #DirectionsRendererOptions.directions + */ + @Input() + set directions(directions: google.maps.DirectionsResult) { + this._directions = directions; + } + private _directions: google.maps.DirectionsResult; + + /** + * See developers.google.com/maps/documentation/javascript/reference/directions + * #DirectionsRendererOptions + */ + @Input() + set options(options: google.maps.DirectionsRendererOptions) { + this._options = options; + } + private _options: google.maps.DirectionsRendererOptions; + + /** + * See developers.google.com/maps/documentation/javascript/reference/directions + * #DirectionsRenderer.directions_changed + */ + @Output() + readonly directionsChanged: Observable = + this._eventManager.getLazyEmitter('directions_changed'); + + /** The underlying google.maps.DirectionsRenderer object. */ + directionsRenderer?: google.maps.DirectionsRenderer; + + constructor(private readonly _googleMap: GoogleMap, private _ngZone: NgZone) {} + + ngOnInit() { + if (this._googleMap._isBrowser) { + // Create the object outside the zone so its events don't trigger change detection. + // We'll bring it back in inside the `MapEventManager` only for the events that the + // user has subscribed to. + this._ngZone.runOutsideAngular(() => { + this.directionsRenderer = new google.maps.DirectionsRenderer(this._combineOptions()); + }); + this._assertInitialized(); + this.directionsRenderer.setMap(this._googleMap.googleMap!); + this._eventManager.setTarget(this.directionsRenderer); + } + } + + ngOnChanges(changes: SimpleChanges) { + if (this.directionsRenderer) { + if (changes['options']) { + this.directionsRenderer.setOptions(this._combineOptions()); + } + + if (changes['directions'] && this._directions !== undefined) { + this.directionsRenderer.setDirections(this._directions); + } + } + } + + ngOnDestroy() { + this._eventManager.destroy(); + if (this.directionsRenderer) { + this.directionsRenderer.setMap(null); + } + } + + /** + * See developers.google.com/maps/documentation/javascript/reference/directions + * #DirectionsRenderer.getDirections + */ + getDirections(): google.maps.DirectionsResult | null { + this._assertInitialized(); + return this.directionsRenderer.getDirections(); + } + + /** + * See developers.google.com/maps/documentation/javascript/reference/directions + * #DirectionsRenderer.getPanel + */ + getPanel(): Node | null { + this._assertInitialized(); + return this.directionsRenderer.getPanel(); + } + + /** + * See developers.google.com/maps/documentation/javascript/reference/directions + * #DirectionsRenderer.getRouteIndex + */ + getRouteIndex(): number { + this._assertInitialized(); + return this.directionsRenderer.getRouteIndex(); + } + + private _combineOptions(): google.maps.DirectionsRendererOptions { + const options = this._options || {}; + return { + ...options, + directions: this._directions || options.directions, + map: this._googleMap.googleMap, + }; + } + + private _assertInitialized(): asserts this is { + directionsRenderer: google.maps.DirectionsRenderer; + } { + if (typeof ngDevMode === 'undefined' || ngDevMode) { + if (!this._googleMap.googleMap) { + throw Error( + 'Cannot access Google Map information before the API has been initialized. ' + + 'Please wait for the API to load before trying to interact with it.', + ); + } + if (!this.directionsRenderer) { + throw Error( + 'Cannot interact with a Google Map Directions Renderer before it has been ' + + 'initialized. Please wait for the Directions Renderer to load before trying ' + + 'to interact with it.', + ); + } + } + } +} diff --git a/src/google-maps/map-directions-renderer/map-directions-service.spec.ts b/src/google-maps/map-directions-renderer/map-directions-service.spec.ts new file mode 100644 index 000000000000..1844d8d053be --- /dev/null +++ b/src/google-maps/map-directions-renderer/map-directions-service.spec.ts @@ -0,0 +1,63 @@ +import {TestBed} from '@angular/core/testing'; +import {MapDirectionsResponse, MapDirectionsService} from './map-directions-service'; +import {GoogleMapsModule} from '../google-maps-module'; +import { + createDirectionsServiceConstructorSpy, + createDirectionsServiceSpy, +} from '../testing/fake-google-map-utils'; + +describe('MapDirectionsService', () => { + let mapDirectionsService: MapDirectionsService; + let directionsServiceConstructorSpy: jasmine.Spy; + let directionsServiceSpy: jasmine.SpyObj; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + }); + + directionsServiceSpy = createDirectionsServiceSpy(); + directionsServiceConstructorSpy = + createDirectionsServiceConstructorSpy(directionsServiceSpy).and.callThrough(); + mapDirectionsService = TestBed.inject(MapDirectionsService); + }); + + afterEach(() => { + (window.google as any) = undefined; + }); + + it('does not initialize the Google Maps Directions Service immediately', () => { + expect(directionsServiceConstructorSpy).not.toHaveBeenCalled(); + }); + + it('initializes the Google Maps Directions Service when `route` is called', () => { + mapDirectionsService + .route({ + origin: 'home', + destination: 'work', + travelMode: 'BICYCLING' as google.maps.TravelMode, + }) + .subscribe(); + + expect(directionsServiceConstructorSpy).toHaveBeenCalled(); + }); + + it('calls route on inputs', () => { + const result: google.maps.DirectionsResult = {routes: []}; + const status = 'OK' as google.maps.DirectionsStatus; + directionsServiceSpy.route.and.callFake((_request, callback) => { + callback?.(result, status); + return Promise.resolve(result); + }); + + mapDirectionsService + .route({ + origin: 'home', + destination: 'work', + travelMode: 'BICYCLING' as google.maps.TravelMode, + }) + .subscribe(response => { + expect(response).toEqual({result, status} as MapDirectionsResponse); + }); + }); +}); diff --git a/src/google-maps/map-directions-renderer/map-directions-service.ts b/src/google-maps/map-directions-renderer/map-directions-service.ts new file mode 100644 index 000000000000..e5aae996e3db --- /dev/null +++ b/src/google-maps/map-directions-renderer/map-directions-service.ts @@ -0,0 +1,53 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 +/// + +import {Injectable, NgZone} from '@angular/core'; +import {Observable} from 'rxjs'; + +export interface MapDirectionsResponse { + status: google.maps.DirectionsStatus; + result?: google.maps.DirectionsResult; +} + +/** + * Angular service that wraps the Google Maps DirectionsService from the Google Maps JavaScript + * API. + * + * See developers.google.com/maps/documentation/javascript/reference/directions#DirectionsService + */ +@Injectable({providedIn: 'root'}) +export class MapDirectionsService { + private _directionsService: google.maps.DirectionsService | undefined; + + constructor(private readonly _ngZone: NgZone) {} + + /** + * See + * developers.google.com/maps/documentation/javascript/reference/directions + * #DirectionsService.route + */ + route(request: google.maps.DirectionsRequest): Observable { + return new Observable(observer => { + // Initialize the `DirectionsService` lazily since the Google Maps API may + // not have been loaded when the provider is instantiated. + if (!this._directionsService) { + this._directionsService = new google.maps.DirectionsService(); + } + + this._directionsService.route(request, (result, status) => { + this._ngZone.run(() => { + observer.next({result: result || undefined, status}); + observer.complete(); + }); + }); + }); + } +} diff --git a/src/google-maps/map-event-manager.spec.ts b/src/google-maps/map-event-manager.spec.ts index 2d7f2e2dfe50..2b9b8e2d9db0 100644 --- a/src/google-maps/map-event-manager.spec.ts +++ b/src/google-maps/map-event-manager.spec.ts @@ -8,7 +8,7 @@ describe('MapEventManager', () => { beforeEach(() => { dummyZone = { - run: jasmine.createSpy('NgZone.run').and.callFake((callback: () => void) => callback()) + run: jasmine.createSpy('NgZone.run').and.callFake((callback: () => void) => callback()), } as unknown as NgZone; target = new TestEventTarget(); manager = new MapEventManager(dummyZone); @@ -141,15 +141,15 @@ describe('MapEventManager', () => { alternateTarget.triggerListeners('click'); expect(spy).toHaveBeenCalledTimes(2); }); - }); /** Imitates a Google Maps event target and keeps track of the registered events. */ class TestEventTarget { events = new Map void>>(); - addListener = jasmine.createSpy('addListener').and.callFake( - (name: string, listener: () => void) => { + addListener = jasmine + .createSpy('addListener') + .and.callFake((name: string, listener: () => void) => { if (!this.events.has(name)) { this.events.set(name, new Set()); } diff --git a/src/google-maps/map-event-manager.ts b/src/google-maps/map-event-manager.ts index cdc0d2b5e2f4..fdbc7aa3aaed 100644 --- a/src/google-maps/map-event-manager.ts +++ b/src/google-maps/map-event-manager.ts @@ -10,14 +10,19 @@ import {NgZone} from '@angular/core'; import {BehaviorSubject, Observable, Subscriber} from 'rxjs'; import {switchMap} from 'rxjs/operators'; -type MapEventManagerTarget = { - addListener: (name: string, callback: (...args: any[]) => void) => google.maps.MapsEventListener; -} | undefined; +type MapEventManagerTarget = + | { + addListener: ( + name: string, + callback: (...args: any[]) => void, + ) => google.maps.MapsEventListener; + } + | undefined; /** Manages event on a Google Maps object, ensuring that events are added only when necessary. */ export class MapEventManager { /** Pending listeners that were added before the target was set. */ - private _pending: {observable: Observable, observer: Subscriber}[] = []; + private _pending: {observable: Observable; observer: Subscriber}[] = []; private _listeners: google.maps.MapsEventListener[] = []; private _targetStream = new BehaviorSubject(undefined); @@ -34,23 +39,25 @@ export class MapEventManager { /** Gets an observable that adds an event listener to the map when a consumer subscribes to it. */ getLazyEmitter(name: string): Observable { - return this._targetStream.pipe(switchMap(target => { - const observable = new Observable(observer => { - // If the target hasn't been initialized yet, cache the observer so it can be added later. - if (!target) { - this._pending.push({observable, observer}); - return undefined; - } + return this._targetStream.pipe( + switchMap(target => { + const observable = new Observable(observer => { + // If the target hasn't been initialized yet, cache the observer so it can be added later. + if (!target) { + this._pending.push({observable, observer}); + return undefined; + } - const listener = target.addListener(name, (event: T) => { - this._ngZone.run(() => observer.next(event)); + const listener = target.addListener(name, (event: T) => { + this._ngZone.run(() => observer.next(event)); + }); + this._listeners.push(listener); + return () => listener.remove(); }); - this._listeners.push(listener); - return () => listener.remove(); - }); - return observable; - })); + return observable; + }), + ); } /** Sets the current target that the manager should bind events to. */ diff --git a/src/google-maps/map-geocoder/README.md b/src/google-maps/map-geocoder/README.md new file mode 100644 index 000000000000..f6b8257fc9e4 --- /dev/null +++ b/src/google-maps/map-geocoder/README.md @@ -0,0 +1,43 @@ +# MapGeocoder + +The `MapGeocoder`, like the `google.maps.Geocoder`, has a single method, `geocode`. Normally, the +`google.maps.Geocoder` takes two arguments, a `google.maps.GeocoderRequest` and a callback that +takes the `google.maps.GeocoderResult` and `google.maps.GeocoderStatus` as arguments. +The `MapGeocoder.geocode` method takes the `google.maps.GeocoderRequest` as the single +argument, and returns an `Observable` of a `MapGeocoderResponse`, which is an interface defined as +follows: + +```typescript +export interface MapGeocoderResponse { + status: google.maps.GeocoderStatus; + results: google.maps.GeocoderResult[]; +} +``` + +## Loading the Library + +Using the `MapGeocoder` requires the Geocoding API to be enabled in Google Cloud Console on the +same project as the one set up for the Google Maps JavaScript API, and requires an API key that +has billing enabled. See [here](https://developers.google.com/maps/documentation/javascript/geocoding#GetStarted) for details. + +## Example + +```typescript +// google-maps-demo.component.ts +import {Component} from '@angular/core'; +import {MapGeocoder} from '@angular/google-maps'; + +@Component({ + selector: 'google-map-demo', + templateUrl: 'google-map-demo.html', +}) +export class GoogleMapDemo { + constructor(geocoder: MapGeocoder) { + geocoder.geocode({ + address: '1600 Amphitheatre Parkway, Mountain View, CA' + }).subscribe(({results}) => { + console.log(results); + }); + } +} +``` diff --git a/src/google-maps/map-geocoder/map-geocoder.spec.ts b/src/google-maps/map-geocoder/map-geocoder.spec.ts new file mode 100644 index 000000000000..e92a0c1d4838 --- /dev/null +++ b/src/google-maps/map-geocoder/map-geocoder.spec.ts @@ -0,0 +1,46 @@ +import {TestBed} from '@angular/core/testing'; +import {MapGeocoderResponse, MapGeocoder} from './map-geocoder'; +import {GoogleMapsModule} from '../google-maps-module'; +import {createGeocoderConstructorSpy, createGeocoderSpy} from '../testing/fake-google-map-utils'; + +describe('MapGeocoder', () => { + let geocoder: MapGeocoder; + let geocoderConstructorSpy: jasmine.Spy; + let geocoderSpy: jasmine.SpyObj; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + }); + + geocoderSpy = createGeocoderSpy(); + geocoderConstructorSpy = createGeocoderConstructorSpy(geocoderSpy).and.callThrough(); + geocoder = TestBed.inject(MapGeocoder); + }); + + afterEach(() => { + (window.google as any) = undefined; + }); + + it('does not initialize the Google Maps Geocoder immediately', () => { + expect(geocoderConstructorSpy).not.toHaveBeenCalled(); + }); + + it('initializes the Google Maps Geocoder after `geocode` is called', () => { + geocoder.geocode({}).subscribe(); + expect(geocoderConstructorSpy).toHaveBeenCalled(); + }); + + it('calls geocode on inputs', () => { + const results: google.maps.GeocoderResult[] = []; + const status = 'OK' as google.maps.GeocoderStatus; + geocoderSpy.geocode.and.callFake((_request, callback) => { + callback?.(results, status); + return Promise.resolve({results}); + }); + + geocoder.geocode({region: 'Europe'}).subscribe(response => { + expect(response).toEqual({results, status} as MapGeocoderResponse); + }); + }); +}); diff --git a/src/google-maps/map-geocoder/map-geocoder.ts b/src/google-maps/map-geocoder/map-geocoder.ts new file mode 100644 index 000000000000..cb18f3588c55 --- /dev/null +++ b/src/google-maps/map-geocoder/map-geocoder.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 +/// + +import {Injectable, NgZone} from '@angular/core'; +import {Observable} from 'rxjs'; + +export interface MapGeocoderResponse { + status: google.maps.GeocoderStatus; + results: google.maps.GeocoderResult[]; +} + +/** + * Angular service that wraps the Google Maps Geocoder from the Google Maps JavaScript API. + * See developers.google.com/maps/documentation/javascript/reference/geocoder#Geocoder + */ +@Injectable({providedIn: 'root'}) +export class MapGeocoder { + private _geocoder: google.maps.Geocoder | undefined; + + constructor(private readonly _ngZone: NgZone) {} + + /** + * See developers.google.com/maps/documentation/javascript/reference/geocoder#Geocoder.geocode + */ + geocode(request: google.maps.GeocoderRequest): Observable { + return new Observable(observer => { + // Initialize the `Geocoder` lazily since the Google Maps API may + // not have been loaded when the provider is instantiated. + if (!this._geocoder) { + this._geocoder = new google.maps.Geocoder(); + } + + this._geocoder.geocode(request, (results, status) => { + this._ngZone.run(() => { + observer.next({results: results || [], status}); + observer.complete(); + }); + }); + }); + } +} diff --git a/src/google-maps/map-ground-overlay/README.md b/src/google-maps/map-ground-overlay/README.md index 19ebfe0ed3ee..07488d9a171b 100644 --- a/src/google-maps/map-ground-overlay/README.md +++ b/src/google-maps/map-ground-overlay/README.md @@ -1,6 +1,6 @@ # MapGroundOverlay -The `MapGroundOverlay` component wraps the [`google.maps.BicyclingLayer` class](https://developers.google.com/maps/documentation/javascript/reference/image-overlay#GroundOverlay) from the Google Maps JavaScript API. A url and a bounds are required. +The `MapGroundOverlay` component wraps the [`google.maps.GroundOverlay` class](https://developers.google.com/maps/documentation/javascript/reference/image-overlay#GroundOverlay) from the Google Maps JavaScript API. A url and a bounds are required. ## Example diff --git a/src/google-maps/map-ground-overlay/map-ground-overlay.spec.ts b/src/google-maps/map-ground-overlay/map-ground-overlay.spec.ts index 06d9bf9cc67c..6e3b8f22f8f9 100644 --- a/src/google-maps/map-ground-overlay/map-ground-overlay.spec.ts +++ b/src/google-maps/map-ground-overlay/map-ground-overlay.spec.ts @@ -21,12 +21,14 @@ describe('MapGroundOverlay', () => { const opacity = 0.5; const groundOverlayOptions: google.maps.GroundOverlayOptions = {clickable, opacity}; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [GoogleMapsModule], - declarations: [TestApp], - }); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + declarations: [TestApp], + }); + }), + ); beforeEach(() => { TestBed.compileComponents(); @@ -42,7 +44,7 @@ describe('MapGroundOverlay', () => { it('initializes a Google Map Ground Overlay', () => { const groundOverlaySpy = createGroundOverlaySpy(url, bounds, groundOverlayOptions); const groundOverlayConstructorSpy = - createGroundOverlayConstructorSpy(groundOverlaySpy).and.callThrough(); + createGroundOverlayConstructorSpy(groundOverlaySpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); fixture.componentInstance.url = url; @@ -60,8 +62,9 @@ describe('MapGroundOverlay', () => { createGroundOverlayConstructorSpy(groundOverlaySpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); - const groundOverlayComponent = fixture.debugElement.query(By.directive( - MapGroundOverlay))!.injector.get(MapGroundOverlay); + const groundOverlayComponent = fixture.debugElement + .query(By.directive(MapGroundOverlay))! + .injector.get(MapGroundOverlay); fixture.componentInstance.url = url; fixture.componentInstance.bounds = bounds; fixture.componentInstance.opacity = opacity; @@ -114,7 +117,7 @@ describe('MapGroundOverlay', () => { it('should be able to change the image after init', () => { const groundOverlaySpy = createGroundOverlaySpy(url, bounds, groundOverlayOptions); const groundOverlayConstructorSpy = - createGroundOverlayConstructorSpy(groundOverlaySpy).and.callThrough(); + createGroundOverlayConstructorSpy(groundOverlaySpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); fixture.componentInstance.url = url; @@ -151,7 +154,6 @@ describe('MapGroundOverlay', () => { expect(newOverlay).toBeTruthy(); expect(newOverlay).not.toBe(oldOverlay); }); - }); @Component({ diff --git a/src/google-maps/map-ground-overlay/map-ground-overlay.ts b/src/google-maps/map-ground-overlay/map-ground-overlay.ts index 1be363977723..26e458bcca8b 100644 --- a/src/google-maps/map-ground-overlay/map-ground-overlay.ts +++ b/src/google-maps/map-ground-overlay/map-ground-overlay.ts @@ -7,7 +7,7 @@ */ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 -/// +/// import {Directive, Input, NgZone, OnDestroy, OnInit, Output} from '@angular/core'; import {BehaviorSubject, Observable, Subject} from 'rxjs'; @@ -30,9 +30,9 @@ export class MapGroundOverlay implements OnInit, OnDestroy { private readonly _opacity = new BehaviorSubject(1); private readonly _url = new BehaviorSubject(''); - private readonly _bounds = - new BehaviorSubject( - undefined); + private readonly _bounds = new BehaviorSubject< + google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral | undefined + >(undefined); private readonly _destroyed = new Subject(); /** @@ -50,10 +50,10 @@ export class MapGroundOverlay implements OnInit, OnDestroy { /** Bounds for the overlay. */ @Input() - get bounds(): google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral { + get bounds(): google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral { return this._bounds.value!; } - set bounds(bounds: google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral) { + set bounds(bounds: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral) { this._bounds.next(bounds); } @@ -70,18 +70,16 @@ export class MapGroundOverlay implements OnInit, OnDestroy { * See * developers.google.com/maps/documentation/javascript/reference/image-overlay#GroundOverlay.click */ - @Output() - mapClick: Observable = - this._eventManager.getLazyEmitter('click'); + @Output() readonly mapClick: Observable = + this._eventManager.getLazyEmitter('click'); /** * See * developers.google.com/maps/documentation/javascript/reference/image-overlay * #GroundOverlay.dblclick */ - @Output() - mapDblclick: Observable = - this._eventManager.getLazyEmitter('dblclick'); + @Output() readonly mapDblclick: Observable = + this._eventManager.getLazyEmitter('dblclick'); constructor(private readonly _map: GoogleMap, private readonly _ngZone: NgZone) {} @@ -131,7 +129,7 @@ export class MapGroundOverlay implements OnInit, OnDestroy { * developers.google.com/maps/documentation/javascript/reference/image-overlay * #GroundOverlay.getBounds */ - getBounds(): google.maps.LatLngBounds { + getBounds(): google.maps.LatLngBounds | null { this._assertInitialized(); return this.groundOverlay.getBounds(); } @@ -181,13 +179,15 @@ export class MapGroundOverlay implements OnInit, OnDestroy { if (typeof ngDevMode === 'undefined' || ngDevMode) { if (!this._map.googleMap) { throw Error( - 'Cannot access Google Map information before the API has been initialized. ' + - 'Please wait for the API to load before trying to interact with it.'); + 'Cannot access Google Map information before the API has been initialized. ' + + 'Please wait for the API to load before trying to interact with it.', + ); } if (!this.groundOverlay) { throw Error( - 'Cannot interact with a Google Map GroundOverlay before it has been initialized. ' + - 'Please wait for the GroundOverlay to load before trying to interact with it.'); + 'Cannot interact with a Google Map GroundOverlay before it has been initialized. ' + + 'Please wait for the GroundOverlay to load before trying to interact with it.', + ); } } } diff --git a/src/google-maps/map-heatmap-layer/README.md b/src/google-maps/map-heatmap-layer/README.md new file mode 100644 index 000000000000..cca046f0560a --- /dev/null +++ b/src/google-maps/map-heatmap-layer/README.md @@ -0,0 +1,64 @@ +# MapHeatmapLayer + +The `MapHeatmapLayer` directive wraps the [`google.maps.visualization.HeatmapLayer` class](https://developers.google.com/maps/documentation/javascript/reference/visualization#HeatmapLayer) from the Google Maps Visualization JavaScript API. It displays +a heatmap layer on the map when it is a content child of a `GoogleMap` component. Like `GoogleMap`, +this directive offers an `options` input as well as a convenience input for passing in the `data` +that is shown on the heatmap. + +## Requirements + +In order to render a heatmap, the Google Maps JavaScript API has to be loaded with the +`visualization` library. To load the library, you have to add `&libraries=visualization` to the +script that loads the Google Maps API. E.g. + +**Before:** +```html + +``` + +**After:** +```html + +``` + +More information: https://developers.google.com/maps/documentation/javascript/heatmaplayer + +## Example + +```typescript +// google-map-demo.component.ts +import {Component} from '@angular/core'; + +@Component({ + selector: 'google-map-demo', + templateUrl: 'google-map-demo.html', +}) +export class GoogleMapDemo { + center = {lat: 37.774546, lng: -122.433523}; + zoom = 12; + heatmapOptions = {radius: 5}; + heatmapData = [ + {lat: 37.782, lng: -122.447}, + {lat: 37.782, lng: -122.445}, + {lat: 37.782, lng: -122.443}, + {lat: 37.782, lng: -122.441}, + {lat: 37.782, lng: -122.439}, + {lat: 37.782, lng: -122.437}, + {lat: 37.782, lng: -122.435}, + {lat: 37.785, lng: -122.447}, + {lat: 37.785, lng: -122.445}, + {lat: 37.785, lng: -122.443}, + {lat: 37.785, lng: -122.441}, + {lat: 37.785, lng: -122.439}, + {lat: 37.785, lng: -122.437}, + {lat: 37.785, lng: -122.435} + ]; +} +``` + +```html + + + + +``` diff --git a/src/google-maps/map-heatmap-layer/map-heatmap-layer.spec.ts b/src/google-maps/map-heatmap-layer/map-heatmap-layer.spec.ts new file mode 100644 index 000000000000..1b167613e6f7 --- /dev/null +++ b/src/google-maps/map-heatmap-layer/map-heatmap-layer.spec.ts @@ -0,0 +1,170 @@ +import {Component, ViewChild} from '@angular/core'; +import {waitForAsync, TestBed} from '@angular/core/testing'; + +import {DEFAULT_OPTIONS} from '../google-map/google-map'; + +import {GoogleMapsModule} from '../google-maps-module'; +import { + createMapConstructorSpy, + createMapSpy, + createHeatmapLayerConstructorSpy, + createHeatmapLayerSpy, + createLatLngSpy, + createLatLngConstructorSpy, +} from '../testing/fake-google-map-utils'; +import {HeatmapData, MapHeatmapLayer} from './map-heatmap-layer'; + +describe('MapHeatmapLayer', () => { + let mapSpy: jasmine.SpyObj; + let latLngSpy: jasmine.SpyObj; + + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + declarations: [TestApp], + }); + }), + ); + + beforeEach(() => { + TestBed.compileComponents(); + mapSpy = createMapSpy(DEFAULT_OPTIONS); + latLngSpy = createLatLngSpy(); + createMapConstructorSpy(mapSpy).and.callThrough(); + createLatLngConstructorSpy(latLngSpy).and.callThrough(); + }); + + afterEach(() => { + (window.google as any) = undefined; + }); + + it('initializes a Google Map heatmap layer', () => { + const heatmapSpy = createHeatmapLayerSpy(); + const heatmapConstructorSpy = createHeatmapLayerConstructorSpy(heatmapSpy).and.callThrough(); + + const fixture = TestBed.createComponent(TestApp); + fixture.detectChanges(); + + expect(heatmapConstructorSpy).toHaveBeenCalledWith({ + data: [], + map: mapSpy, + }); + }); + + it('should throw if the `visualization` library has not been loaded', () => { + createHeatmapLayerConstructorSpy(createHeatmapLayerSpy()); + delete (window.google.maps as any).visualization; + + expect(() => { + const fixture = TestBed.createComponent(TestApp); + fixture.detectChanges(); + }).toThrowError(/Namespace `google.maps.visualization` not found, cannot construct heatmap/); + }); + + it('sets heatmap inputs', () => { + const options: google.maps.visualization.HeatmapLayerOptions = { + map: mapSpy, + data: [ + new google.maps.LatLng(37.782, -122.447), + new google.maps.LatLng(37.782, -122.445), + new google.maps.LatLng(37.782, -122.443), + ], + }; + const heatmapSpy = createHeatmapLayerSpy(); + const heatmapConstructorSpy = createHeatmapLayerConstructorSpy(heatmapSpy).and.callThrough(); + + const fixture = TestBed.createComponent(TestApp); + fixture.componentInstance.data = options.data; + fixture.detectChanges(); + + expect(heatmapConstructorSpy).toHaveBeenCalledWith(options); + }); + + it('sets heatmap options, ignoring map', () => { + const options: Partial = { + radius: 5, + dissipating: true, + }; + const data = [ + new google.maps.LatLng(37.782, -122.447), + new google.maps.LatLng(37.782, -122.445), + new google.maps.LatLng(37.782, -122.443), + ]; + const heatmapSpy = createHeatmapLayerSpy(); + const heatmapConstructorSpy = createHeatmapLayerConstructorSpy(heatmapSpy).and.callThrough(); + + const fixture = TestBed.createComponent(TestApp); + fixture.componentInstance.data = data; + fixture.componentInstance.options = options; + fixture.detectChanges(); + + expect(heatmapConstructorSpy).toHaveBeenCalledWith({...options, map: mapSpy, data}); + }); + + it('exposes methods that provide information about the heatmap', () => { + const heatmapSpy = createHeatmapLayerSpy(); + createHeatmapLayerConstructorSpy(heatmapSpy).and.callThrough(); + + const fixture = TestBed.createComponent(TestApp); + fixture.detectChanges(); + const heatmap = fixture.componentInstance.heatmap; + + heatmapSpy.getData.and.returnValue([] as any); + expect(heatmap.getData()).toEqual([]); + }); + + it('should update the heatmap data when the input changes', () => { + const heatmapSpy = createHeatmapLayerSpy(); + const heatmapConstructorSpy = createHeatmapLayerConstructorSpy(heatmapSpy).and.callThrough(); + let data = [ + new google.maps.LatLng(1, 2), + new google.maps.LatLng(3, 4), + new google.maps.LatLng(5, 6), + ]; + + const fixture = TestBed.createComponent(TestApp); + fixture.componentInstance.data = data; + fixture.detectChanges(); + + expect(heatmapConstructorSpy).toHaveBeenCalledWith(jasmine.objectContaining({data})); + data = [ + new google.maps.LatLng(7, 8), + new google.maps.LatLng(9, 10), + new google.maps.LatLng(11, 12), + ]; + fixture.componentInstance.data = data; + fixture.detectChanges(); + + expect(heatmapSpy.setData).toHaveBeenCalledWith(data); + }); + + it('should create a LatLng object if a LatLngLiteral is passed in', () => { + const latLngConstructor = createLatLngConstructorSpy(latLngSpy).and.callThrough(); + createHeatmapLayerConstructorSpy(createHeatmapLayerSpy()).and.callThrough(); + const fixture = TestBed.createComponent(TestApp); + fixture.componentInstance.data = [ + {lat: 1, lng: 2}, + {lat: 3, lng: 4}, + ]; + fixture.detectChanges(); + + expect(latLngConstructor).toHaveBeenCalledWith(1, 2); + expect(latLngConstructor).toHaveBeenCalledWith(3, 4); + expect(latLngConstructor).toHaveBeenCalledTimes(2); + }); +}); + +@Component({ + selector: 'test-app', + template: ` + + + + `, +}) +class TestApp { + @ViewChild(MapHeatmapLayer) heatmap: MapHeatmapLayer; + options?: Partial; + data?: HeatmapData | null; +} diff --git a/src/google-maps/map-heatmap-layer/map-heatmap-layer.ts b/src/google-maps/map-heatmap-layer/map-heatmap-layer.ts new file mode 100644 index 000000000000..652cddedbed8 --- /dev/null +++ b/src/google-maps/map-heatmap-layer/map-heatmap-layer.ts @@ -0,0 +1,162 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 +/// + +import {Input, OnDestroy, OnInit, NgZone, Directive, OnChanges, SimpleChanges} from '@angular/core'; + +import {GoogleMap} from '../google-map/google-map'; + +/** Possible data that can be shown on a heatmap layer. */ +export type HeatmapData = + | google.maps.MVCArray< + google.maps.LatLng | google.maps.visualization.WeightedLocation | google.maps.LatLngLiteral + > + | (google.maps.LatLng | google.maps.visualization.WeightedLocation | google.maps.LatLngLiteral)[]; + +/** + * Angular directive that renders a Google Maps heatmap via the Google Maps JavaScript API. + * + * See: https://developers.google.com/maps/documentation/javascript/reference/visualization + */ +@Directive({ + selector: 'map-heatmap-layer', + exportAs: 'mapHeatmapLayer', +}) +export class MapHeatmapLayer implements OnInit, OnChanges, OnDestroy { + /** + * Data shown on the heatmap. + * See: https://developers.google.com/maps/documentation/javascript/reference/visualization + */ + @Input() + set data(data: HeatmapData) { + this._data = data; + } + private _data: HeatmapData; + + /** + * Options used to configure the heatmap. See: + * developers.google.com/maps/documentation/javascript/reference/visualization#HeatmapLayerOptions + */ + @Input() + set options(options: Partial) { + this._options = options; + } + private _options: Partial; + + /** + * The underlying google.maps.visualization.HeatmapLayer object. + * + * See: https://developers.google.com/maps/documentation/javascript/reference/visualization + */ + heatmap?: google.maps.visualization.HeatmapLayer; + + constructor(private readonly _googleMap: GoogleMap, private _ngZone: NgZone) {} + + ngOnInit() { + if (this._googleMap._isBrowser) { + if (!window.google?.maps?.visualization && (typeof ngDevMode === 'undefined' || ngDevMode)) { + throw Error( + 'Namespace `google.maps.visualization` not found, cannot construct heatmap. ' + + 'Please install the Google Maps JavaScript API with the "visualization" library: ' + + 'https://developers.google.com/maps/documentation/javascript/visualization', + ); + } + + // Create the object outside the zone so its events don't trigger change detection. + // We'll bring it back in inside the `MapEventManager` only for the events that the + // user has subscribed to. + this._ngZone.runOutsideAngular(() => { + this.heatmap = new google.maps.visualization.HeatmapLayer(this._combineOptions()); + }); + this._assertInitialized(); + this.heatmap.setMap(this._googleMap.googleMap!); + } + } + + ngOnChanges(changes: SimpleChanges) { + const {_data, heatmap} = this; + + if (heatmap) { + if (changes['options']) { + heatmap.setOptions(this._combineOptions()); + } + + if (changes['data'] && _data !== undefined) { + heatmap.setData(this._normalizeData(_data)); + } + } + } + + ngOnDestroy() { + if (this.heatmap) { + this.heatmap.setMap(null); + } + } + + /** + * Gets the data that is currently shown on the heatmap. + * See: developers.google.com/maps/documentation/javascript/reference/visualization#HeatmapLayer + */ + getData(): HeatmapData { + this._assertInitialized(); + return this.heatmap.getData(); + } + + /** Creates a combined options object using the passed-in options and the individual inputs. */ + private _combineOptions(): google.maps.visualization.HeatmapLayerOptions { + const options = this._options || {}; + return { + ...options, + data: this._normalizeData(this._data || options.data || []), + map: this._googleMap.googleMap, + }; + } + + /** + * Most Google Maps APIs support both `LatLng` objects and `LatLngLiteral`. The latter is more + * convenient to write out, because the Google Maps API doesn't have to have been loaded in order + * to construct them. The `HeatmapLayer` appears to be an exception that only allows a `LatLng` + * object, or it throws a runtime error. Since it's more convenient and we expect that Angular + * users will load the API asynchronously, we allow them to pass in a `LatLngLiteral` and we + * convert it to a `LatLng` object before passing it off to Google Maps. + */ + private _normalizeData(data: HeatmapData) { + const result: (google.maps.LatLng | google.maps.visualization.WeightedLocation)[] = []; + + data.forEach(item => { + result.push(isLatLngLiteral(item) ? new google.maps.LatLng(item.lat, item.lng) : item); + }); + + return result; + } + + /** Asserts that the heatmap object has been initialized. */ + private _assertInitialized(): asserts this is {heatmap: google.maps.visualization.HeatmapLayer} { + if (typeof ngDevMode === 'undefined' || ngDevMode) { + if (!this._googleMap.googleMap) { + throw Error( + 'Cannot access Google Map information before the API has been initialized. ' + + 'Please wait for the API to load before trying to interact with it.', + ); + } + if (!this.heatmap) { + throw Error( + 'Cannot interact with a Google Map HeatmapLayer before it has been ' + + 'initialized. Please wait for the heatmap to load before trying to interact with it.', + ); + } + } + } +} + +/** Asserts that an object is a `LatLngLiteral`. */ +function isLatLngLiteral(value: any): value is google.maps.LatLngLiteral { + return value && typeof value.lat === 'number' && typeof value.lng === 'number'; +} diff --git a/src/google-maps/map-info-window/README.md b/src/google-maps/map-info-window/README.md index 2a67235cd116..4b60ab0ebfdb 100644 --- a/src/google-maps/map-info-window/README.md +++ b/src/google-maps/map-info-window/README.md @@ -22,7 +22,7 @@ export class GoogleMapDemo { markerPositions: google.maps.LatLngLiteral[] = []; zoom = 4; - addMarker(event: google.maps.MouseEvent) { + addMarker(event: google.maps.MapMouseEvent) { this.markerPositions.push(event.latLng.toJSON()); } diff --git a/src/google-maps/map-info-window/map-info-window.spec.ts b/src/google-maps/map-info-window/map-info-window.spec.ts index 3056996f94e0..c13c1741c8ca 100644 --- a/src/google-maps/map-info-window/map-info-window.spec.ts +++ b/src/google-maps/map-info-window/map-info-window.spec.ts @@ -10,19 +10,21 @@ import { createInfoWindowConstructorSpy, createInfoWindowSpy, createMapConstructorSpy, - createMapSpy + createMapSpy, } from '../testing/fake-google-map-utils'; import {MapInfoWindow} from './map-info-window'; describe('MapInfoWindow', () => { let mapSpy: jasmine.SpyObj; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [GoogleMapsModule], - declarations: [TestApp], - }); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + declarations: [TestApp], + }); + }), + ); beforeEach(() => { TestBed.compileComponents(); @@ -38,7 +40,7 @@ describe('MapInfoWindow', () => { it('initializes a Google Map Info Window', () => { const infoWindowSpy = createInfoWindowSpy({}); const infoWindowConstructorSpy = - createInfoWindowConstructorSpy(infoWindowSpy).and.callThrough(); + createInfoWindowConstructorSpy(infoWindowSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); fixture.detectChanges(); @@ -53,7 +55,7 @@ describe('MapInfoWindow', () => { const position: google.maps.LatLngLiteral = {lat: 5, lng: 7}; const infoWindowSpy = createInfoWindowSpy({position}); const infoWindowConstructorSpy = - createInfoWindowConstructorSpy(infoWindowSpy).and.callThrough(); + createInfoWindowConstructorSpy(infoWindowSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); fixture.componentInstance.position = position; @@ -73,7 +75,7 @@ describe('MapInfoWindow', () => { }; const infoWindowSpy = createInfoWindowSpy(options); const infoWindowConstructorSpy = - createInfoWindowConstructorSpy(infoWindowSpy).and.callThrough(); + createInfoWindowConstructorSpy(infoWindowSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); fixture.componentInstance.options = options; @@ -94,7 +96,7 @@ describe('MapInfoWindow', () => { }; const infoWindowSpy = createInfoWindowSpy({...options, position}); const infoWindowConstructorSpy = - createInfoWindowConstructorSpy(infoWindowSpy).and.callThrough(); + createInfoWindowConstructorSpy(infoWindowSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); fixture.componentInstance.options = options; @@ -112,14 +114,15 @@ describe('MapInfoWindow', () => { const fakeMarker = {} as unknown as google.maps.Marker; const fakeMarkerComponent = { marker: fakeMarker, - getAnchor: () => fakeMarker + getAnchor: () => fakeMarker, } as unknown as MapMarker; const infoWindowSpy = createInfoWindowSpy({}); createInfoWindowConstructorSpy(infoWindowSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); - const infoWindowComponent = fixture.debugElement.query(By.directive( - MapInfoWindow))!.injector.get(MapInfoWindow); + const infoWindowComponent = fixture.debugElement + .query(By.directive(MapInfoWindow))! + .injector.get(MapInfoWindow); fixture.detectChanges(); infoWindowComponent.close(); @@ -133,14 +136,15 @@ describe('MapInfoWindow', () => { const fakeMarker = {} as unknown as google.maps.Marker; const fakeMarkerComponent = { marker: fakeMarker, - getAnchor: () => fakeMarker + getAnchor: () => fakeMarker, } as unknown as MapMarker; const infoWindowSpy = createInfoWindowSpy({}); createInfoWindowConstructorSpy(infoWindowSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); - const infoWindowComponent = fixture.debugElement.query(By.directive( - MapInfoWindow))!.injector.get(MapInfoWindow); + const infoWindowComponent = fixture.debugElement + .query(By.directive(MapInfoWindow))! + .injector.get(MapInfoWindow); fixture.detectChanges(); infoWindowComponent.open(fakeMarkerComponent); @@ -159,8 +163,9 @@ describe('MapInfoWindow', () => { createInfoWindowConstructorSpy(infoWindowSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); - const infoWindowComponent = fixture.debugElement.query(By.directive( - MapInfoWindow))!.injector.get(MapInfoWindow); + const infoWindowComponent = fixture.debugElement + .query(By.directive(MapInfoWindow))! + .injector.get(MapInfoWindow); fixture.detectChanges(); infoWindowSpy.getContent.and.returnValue('test content'); @@ -211,14 +216,14 @@ describe('MapInfoWindow', () => { createInfoWindowConstructorSpy(infoWindowSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); - const infoWindowComponent = fixture.debugElement.query(By.directive( - MapInfoWindow))!.injector.get(MapInfoWindow); + const infoWindowComponent = fixture.debugElement + .query(By.directive(MapInfoWindow))! + .injector.get(MapInfoWindow); fixture.detectChanges(); infoWindowComponent.open(); expect(infoWindowSpy.open).toHaveBeenCalledTimes(1); }); - }); @Component({ diff --git a/src/google-maps/map-info-window/map-info-window.ts b/src/google-maps/map-info-window/map-info-window.ts index 50bd4397c7ce..85d014bb9c70 100644 --- a/src/google-maps/map-info-window/map-info-window.ts +++ b/src/google-maps/map-info-window/map-info-window.ts @@ -7,17 +7,9 @@ */ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 -/// - -import { - Directive, - ElementRef, - Input, - NgZone, - OnDestroy, - OnInit, - Output, -} from '@angular/core'; +/// + +import {Directive, ElementRef, Input, NgZone, OnDestroy, OnInit, Output} from '@angular/core'; import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; import {map, take, takeUntil} from 'rxjs/operators'; @@ -38,8 +30,9 @@ import {MapAnchorPoint} from '../map-anchor-point'; export class MapInfoWindow implements OnInit, OnDestroy { private _eventManager = new MapEventManager(this._ngZone); private readonly _options = new BehaviorSubject({}); - private readonly _position = - new BehaviorSubject(undefined); + private readonly _position = new BehaviorSubject< + google.maps.LatLngLiteral | google.maps.LatLng | undefined + >(undefined); private readonly _destroy = new Subject(); /** @@ -55,7 +48,7 @@ export class MapInfoWindow implements OnInit, OnDestroy { } @Input() - set position(position: google.maps.LatLngLiteral|google.maps.LatLng) { + set position(position: google.maps.LatLngLiteral | google.maps.LatLng) { this._position.next(position); } @@ -63,41 +56,45 @@ export class MapInfoWindow implements OnInit, OnDestroy { * See * developers.google.com/maps/documentation/javascript/reference/info-window#InfoWindow.closeclick */ - @Output() closeclick: Observable = this._eventManager.getLazyEmitter('closeclick'); + @Output() readonly closeclick: Observable = + this._eventManager.getLazyEmitter('closeclick'); /** * See * developers.google.com/maps/documentation/javascript/reference/info-window * #InfoWindow.content_changed */ - @Output() - contentChanged: Observable = this._eventManager.getLazyEmitter('content_changed'); + @Output() readonly contentChanged: Observable = + this._eventManager.getLazyEmitter('content_changed'); /** * See * developers.google.com/maps/documentation/javascript/reference/info-window#InfoWindow.domready */ - @Output() domready: Observable = this._eventManager.getLazyEmitter('domready'); + @Output() readonly domready: Observable = + this._eventManager.getLazyEmitter('domready'); /** * See * developers.google.com/maps/documentation/javascript/reference/info-window * #InfoWindow.position_changed */ - @Output() - positionChanged: Observable = this._eventManager.getLazyEmitter('position_changed'); + @Output() readonly positionChanged: Observable = + this._eventManager.getLazyEmitter('position_changed'); /** * See * developers.google.com/maps/documentation/javascript/reference/info-window * #InfoWindow.zindex_changed */ - @Output() - zindexChanged: Observable = this._eventManager.getLazyEmitter('zindex_changed'); + @Output() readonly zindexChanged: Observable = + this._eventManager.getLazyEmitter('zindex_changed'); - constructor(private readonly _googleMap: GoogleMap, - private _elementRef: ElementRef, - private _ngZone: NgZone) {} + constructor( + private readonly _googleMap: GoogleMap, + private _elementRef: ElementRef, + private _ngZone: NgZone, + ) {} ngOnInit() { if (this._googleMap._isBrowser) { @@ -143,9 +140,9 @@ export class MapInfoWindow implements OnInit, OnDestroy { * See * developers.google.com/maps/documentation/javascript/reference/info-window#InfoWindow.getContent */ - getContent(): string|Node { + getContent(): string | Node | null { this._assertInitialized(); - return this.infoWindow.getContent(); + return this.infoWindow.getContent() || null; } /** @@ -153,9 +150,9 @@ export class MapInfoWindow implements OnInit, OnDestroy { * developers.google.com/maps/documentation/javascript/reference/info-window * #InfoWindow.getPosition */ - getPosition(): google.maps.LatLng|null { + getPosition(): google.maps.LatLng | null { this._assertInitialized(); - return this.infoWindow.getPosition(); + return this.infoWindow.getPosition() || null; } /** @@ -186,14 +183,16 @@ export class MapInfoWindow implements OnInit, OnDestroy { } private _combineOptions(): Observable { - return combineLatest([this._options, this._position]).pipe(map(([options, position]) => { - const combinedOptions: google.maps.InfoWindowOptions = { - ...options, - position: position || options.position, - content: this._elementRef.nativeElement, - }; - return combinedOptions; - })); + return combineLatest([this._options, this._position]).pipe( + map(([options, position]) => { + const combinedOptions: google.maps.InfoWindowOptions = { + ...options, + position: position || options.position, + content: this._elementRef.nativeElement, + }; + return combinedOptions; + }), + ); } private _watchForOptionsChanges() { @@ -216,14 +215,16 @@ export class MapInfoWindow implements OnInit, OnDestroy { if (typeof ngDevMode === 'undefined' || ngDevMode) { if (!this._googleMap.googleMap) { throw Error( - 'Cannot access Google Map information before the API has been initialized. ' + - 'Please wait for the API to load before trying to interact with it.'); + 'Cannot access Google Map information before the API has been initialized. ' + + 'Please wait for the API to load before trying to interact with it.', + ); } if (!this.infoWindow) { throw Error( - 'Cannot interact with a Google Map Info Window before it has been ' + + 'Cannot interact with a Google Map Info Window before it has been ' + 'initialized. Please wait for the Info Window to load before trying to interact with ' + - 'it.'); + 'it.', + ); } } } diff --git a/src/google-maps/map-kml-layer/map-kml-layer.spec.ts b/src/google-maps/map-kml-layer/map-kml-layer.spec.ts index 2fd6064e5fe0..e77fffcc0552 100644 --- a/src/google-maps/map-kml-layer/map-kml-layer.spec.ts +++ b/src/google-maps/map-kml-layer/map-kml-layer.spec.ts @@ -23,12 +23,14 @@ const DEFAULT_KML_OPTIONS: google.maps.KmlLayerOptions = { describe('MapKmlLayer', () => { let mapSpy: jasmine.SpyObj; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [GoogleMapsModule], - declarations: [TestApp], - }); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + declarations: [TestApp], + }); + }), + ); beforeEach(() => { TestBed.compileComponents(); @@ -83,8 +85,9 @@ describe('MapKmlLayer', () => { createKmlLayerConstructorSpy(kmlLayerSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); - const kmlLayerComponent = fixture.debugElement.query(By.directive( - MapKmlLayer))!.injector.get(MapKmlLayer); + const kmlLayerComponent = fixture.debugElement + .query(By.directive(MapKmlLayer))! + .injector.get(MapKmlLayer); fixture.detectChanges(); kmlLayerComponent.getDefaultViewport(); diff --git a/src/google-maps/map-kml-layer/map-kml-layer.ts b/src/google-maps/map-kml-layer/map-kml-layer.ts index 32cf1c820924..53a817780948 100644 --- a/src/google-maps/map-kml-layer/map-kml-layer.ts +++ b/src/google-maps/map-kml-layer/map-kml-layer.ts @@ -7,16 +7,9 @@ */ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 -/// - -import { - Directive, - Input, - NgZone, - OnDestroy, - OnInit, - Output, -} from '@angular/core'; +/// + +import {Directive, Input, NgZone, OnDestroy, OnInit, Output} from '@angular/core'; import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; import {map, take, takeUntil} from 'rxjs/operators'; @@ -59,38 +52,38 @@ export class MapKmlLayer implements OnInit, OnDestroy { /** * See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.click */ - @Output() - kmlClick: Observable = - this._eventManager.getLazyEmitter('click'); + @Output() readonly kmlClick: Observable = + this._eventManager.getLazyEmitter('click'); /** * See * developers.google.com/maps/documentation/javascript/reference/kml * #KmlLayer.defaultviewport_changed */ - @Output() - defaultviewportChanged: Observable = - this._eventManager.getLazyEmitter('defaultviewport_changed'); + @Output() readonly defaultviewportChanged: Observable = + this._eventManager.getLazyEmitter('defaultviewport_changed'); /** * See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.status_changed */ - @Output() - statusChanged: Observable = this._eventManager.getLazyEmitter('status_changed'); + @Output() readonly statusChanged: Observable = + this._eventManager.getLazyEmitter('status_changed'); constructor(private readonly _map: GoogleMap, private _ngZone: NgZone) {} ngOnInit() { if (this._map._isBrowser) { - this._combineOptions().pipe(take(1)).subscribe(options => { - // Create the object outside the zone so its events don't trigger change detection. - // We'll bring it back in inside the `MapEventManager` only for the events that the - // user has subscribed to. - this._ngZone.runOutsideAngular(() => this.kmlLayer = new google.maps.KmlLayer(options)); - this._assertInitialized(); - this.kmlLayer.setMap(this._map.googleMap!); - this._eventManager.setTarget(this.kmlLayer); - }); + this._combineOptions() + .pipe(take(1)) + .subscribe(options => { + // Create the object outside the zone so its events don't trigger change detection. + // We'll bring it back in inside the `MapEventManager` only for the events that the + // user has subscribed to. + this._ngZone.runOutsideAngular(() => (this.kmlLayer = new google.maps.KmlLayer(options))); + this._assertInitialized(); + this.kmlLayer.setMap(this._map.googleMap!); + this._eventManager.setTarget(this.kmlLayer); + }); this._watchForOptionsChanges(); this._watchForUrlChanges(); @@ -110,7 +103,7 @@ export class MapKmlLayer implements OnInit, OnDestroy { * See * developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.getDefaultViewport */ - getDefaultViewport(): google.maps.LatLngBounds { + getDefaultViewport(): google.maps.LatLngBounds | null { this._assertInitialized(); return this.kmlLayer.getDefaultViewport(); } @@ -118,7 +111,7 @@ export class MapKmlLayer implements OnInit, OnDestroy { /** * See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.getMetadata */ - getMetadata(): google.maps.KmlLayerMetadata { + getMetadata(): google.maps.KmlLayerMetadata | null { this._assertInitialized(); return this.kmlLayer.getMetadata(); } @@ -148,13 +141,15 @@ export class MapKmlLayer implements OnInit, OnDestroy { } private _combineOptions(): Observable { - return combineLatest([this._options, this._url]).pipe(map(([options, url]) => { - const combinedOptions: google.maps.KmlLayerOptions = { - ...options, - url: url || options.url, - }; - return combinedOptions; - })); + return combineLatest([this._options, this._url]).pipe( + map(([options, url]) => { + const combinedOptions: google.maps.KmlLayerOptions = { + ...options, + url: url || options.url, + }; + return combinedOptions; + }), + ); } private _watchForOptionsChanges() { @@ -175,17 +170,19 @@ export class MapKmlLayer implements OnInit, OnDestroy { }); } - private _assertInitialized(): asserts this is { kmlLayer: google.maps.KmlLayer } { + private _assertInitialized(): asserts this is {kmlLayer: google.maps.KmlLayer} { if (typeof ngDevMode === 'undefined' || ngDevMode) { if (!this._map.googleMap) { throw Error( - 'Cannot access Google Map information before the API has been initialized. ' + - 'Please wait for the API to load before trying to interact with it.'); + 'Cannot access Google Map information before the API has been initialized. ' + + 'Please wait for the API to load before trying to interact with it.', + ); } if (!this.kmlLayer) { throw Error( - 'Cannot interact with a Google Map KmlLayer before it has been ' + - 'initialized. Please wait for the KmlLayer to load before trying to interact with it.'); + 'Cannot interact with a Google Map KmlLayer before it has been ' + + 'initialized. Please wait for the KmlLayer to load before trying to interact with it.', + ); } } } diff --git a/src/google-maps/map-marker-clusterer/README.md b/src/google-maps/map-marker-clusterer/README.md index ed2a0afa0e8b..4b73cc8d6a77 100644 --- a/src/google-maps/map-marker-clusterer/README.md +++ b/src/google-maps/map-marker-clusterer/README.md @@ -29,7 +29,7 @@ export class GoogleMapDemo { markerClustererImagePath = 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'; - addMarker(event: google.maps.MouseEvent) { + addMarker(event: google.maps.MapMouseEvent) { this.markerPositions.push(event.latLng.toJSON()); } } diff --git a/src/google-maps/map-marker-clusterer/map-marker-clusterer.spec.ts b/src/google-maps/map-marker-clusterer/map-marker-clusterer.spec.ts index 00231268e734..ef418830b7e9 100644 --- a/src/google-maps/map-marker-clusterer/map-marker-clusterer.spec.ts +++ b/src/google-maps/map-marker-clusterer/map-marker-clusterer.spec.ts @@ -21,12 +21,14 @@ describe('MapMarkerClusterer', () => { const anyMarkerMatcher = jasmine.any(Object) as unknown as google.maps.Marker; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [GoogleMapsModule], - declarations: [TestApp], - }); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + declarations: [TestApp], + }); + }), + ); beforeEach(() => { TestBed.compileComponents(); @@ -35,19 +37,38 @@ describe('MapMarkerClusterer', () => { createMapConstructorSpy(mapSpy).and.callThrough(); const markerSpy = createMarkerSpy({}); - createMarkerConstructorSpy(markerSpy).and.callFake(() => { + // The spy target function cannot be an arrow-function as this breaks when created + // through `new`. + createMarkerConstructorSpy(markerSpy).and.callFake(function () { return createMarkerSpy({}); }); markerClustererSpy = createMarkerClustererSpy(); - markerClustererConstructorSpy = createMarkerClustererConstructorSpy(markerClustererSpy) - .and.callThrough(); + markerClustererConstructorSpy = + createMarkerClustererConstructorSpy(markerClustererSpy).and.callThrough(); fixture = TestBed.createComponent(TestApp); }); afterEach(() => { (window.google as any) = undefined; + (window as any).MarkerClusterer = undefined; + }); + + it('throws an error if the clustering library has not been loaded', () => { + (window as any).MarkerClusterer = undefined; + markerClustererConstructorSpy = createMarkerClustererConstructorSpy( + markerClustererSpy, + false, + ).and.callThrough(); + + expect(() => fixture.detectChanges()).toThrow( + new Error( + 'MarkerClusterer class not found, cannot construct a marker cluster. ' + + 'Please install the MarkerClustererPlus library: ' + + 'https://github.com/googlemaps/js-markerclustererplus', + ), + ); }); it('initializes a Google Map Marker Clusterer', () => { @@ -60,7 +81,7 @@ describe('MapMarkerClusterer', () => { batchSizeIE: undefined, calculator: undefined, clusterClass: undefined, - enableRetinalIcons: undefined, + enableRetinaIcons: undefined, gridSize: undefined, ignoreHidden: undefined, imageExtension: undefined, @@ -80,7 +101,7 @@ describe('MapMarkerClusterer', () => { fixture.componentInstance.averageCenter = true; fixture.componentInstance.batchSize = 1; fixture.componentInstance.clusterClass = 'testClusterClass'; - fixture.componentInstance.enableRetinalIcons = true; + fixture.componentInstance.enableRetinaIcons = true; fixture.componentInstance.gridSize = 2; fixture.componentInstance.ignoreHidden = true; fixture.componentInstance.imageExtension = 'testImageExtension'; @@ -101,7 +122,7 @@ describe('MapMarkerClusterer', () => { batchSizeIE: undefined, calculator: undefined, clusterClass: 'testClusterClass', - enableRetinalIcons: true, + enableRetinaIcons: true, gridSize: 2, ignoreHidden: true, imageExtension: 'testImageExtension', @@ -116,18 +137,61 @@ describe('MapMarkerClusterer', () => { }); }); + it('sets marker clusterer options', () => { + fixture.detectChanges(); + const options: MarkerClustererOptions = { + enableRetinaIcons: true, + gridSize: 1337, + ignoreHidden: true, + imageExtension: 'png', + }; + fixture.componentInstance.options = options; + fixture.detectChanges(); + expect(markerClustererSpy.setOptions).toHaveBeenCalledWith(jasmine.objectContaining(options)); + }); + + it('gives precedence to specific inputs over options', () => { + fixture.detectChanges(); + const options: MarkerClustererOptions = { + enableRetinaIcons: true, + gridSize: 1337, + ignoreHidden: true, + imageExtension: 'png', + }; + const expectedOptions: MarkerClustererOptions = { + enableRetinaIcons: false, + gridSize: 42, + ignoreHidden: false, + imageExtension: 'jpeg', + }; + fixture.componentInstance.enableRetinaIcons = expectedOptions.enableRetinaIcons; + fixture.componentInstance.gridSize = expectedOptions.gridSize; + fixture.componentInstance.ignoreHidden = expectedOptions.ignoreHidden; + fixture.componentInstance.imageExtension = expectedOptions.imageExtension; + fixture.componentInstance.options = options; + fixture.detectChanges(); + + expect(markerClustererSpy.setOptions).toHaveBeenCalledWith( + jasmine.objectContaining(expectedOptions), + ); + }); + it('sets Google Maps Markers in the MarkerClusterer', () => { fixture.detectChanges(); - expect(markerClustererSpy.addMarkers) - .toHaveBeenCalledWith([anyMarkerMatcher, anyMarkerMatcher]); + expect(markerClustererSpy.addMarkers).toHaveBeenCalledWith([ + anyMarkerMatcher, + anyMarkerMatcher, + ]); }); it('updates Google Maps Markers in the Marker Clusterer', () => { fixture.detectChanges(); - expect(markerClustererSpy.addMarkers) - .toHaveBeenCalledWith([anyMarkerMatcher, anyMarkerMatcher]); + expect(markerClustererSpy.addMarkers).toHaveBeenCalledWith([ + anyMarkerMatcher, + anyMarkerMatcher, + ]); fixture.componentInstance.state = 'state2'; fixture.detectChanges(); @@ -140,8 +204,10 @@ describe('MapMarkerClusterer', () => { fixture.detectChanges(); expect(markerClustererSpy.addMarkers).toHaveBeenCalledWith([], true); - expect(markerClustererSpy.removeMarkers) - .toHaveBeenCalledWith([anyMarkerMatcher, anyMarkerMatcher], true); + expect(markerClustererSpy.removeMarkers).toHaveBeenCalledWith( + [anyMarkerMatcher, anyMarkerMatcher], + true, + ); expect(markerClustererSpy.repaint).toHaveBeenCalledTimes(2); }); @@ -172,8 +238,8 @@ describe('MapMarkerClusterer', () => { markerClustererSpy.getClusters.and.returnValue([]); expect(markerClustererComponent.getClusters()).toEqual([]); - markerClustererSpy.getEnableRetinalIcons.and.returnValue(true); - expect(markerClustererComponent.getEnableRetinalIcons()).toBe(true); + markerClustererSpy.getEnableRetinaIcons.and.returnValue(true); + expect(markerClustererComponent.getEnableRetinaIcons()).toBe(true); markerClustererSpy.getGridSize.and.returnValue(7); expect(markerClustererComponent.getGridSize()).toBe(7); @@ -218,10 +284,15 @@ describe('MapMarkerClusterer', () => { it('initializes marker clusterer event handlers', () => { fixture.detectChanges(); - expect(markerClustererSpy.addListener) - .toHaveBeenCalledWith('clusteringbegin', jasmine.any(Function)); - expect(markerClustererSpy.addListener) - .not.toHaveBeenCalledWith('clusteringend', jasmine.any(Function)); + expect(markerClustererSpy.addListener).toHaveBeenCalledWith( + 'clusteringbegin', + jasmine.any(Function), + ); + expect(markerClustererSpy.addListener).not.toHaveBeenCalledWith( + 'clusteringend', + jasmine.any(Function), + ); + expect(markerClustererSpy.addListener).toHaveBeenCalledWith('click', jasmine.any(Function)); }); }); @@ -234,7 +305,7 @@ describe('MapMarkerClusterer', () => { [batchSizeIE]="batchSizeIE" [calculator]="calculator" [clusterClass]="clusterClass" - [enableRetinalIcons]="enableRetinalIcons" + [enableRetinaIcons]="enableRetinaIcons" [gridSize]="gridSize" [ignoreHidden]="ignoreHidden" [imageExtension]="imageExtension" @@ -246,7 +317,9 @@ describe('MapMarkerClusterer', () => { [title]="title" [zIndex]="zIndex" [zoomOnClick]="zoomOnClick" - (clusteringbegin)="onClusteringBegin()"> + [options]="options" + (clusteringbegin)="onClusteringBegin()" + (clusterClick)="onClusterClick()"> @@ -262,7 +335,7 @@ class TestApp { batchSizeIE?: number; calculator?: Calculator; clusterClass?: string; - enableRetinalIcons?: boolean; + enableRetinaIcons?: boolean; gridSize?: number; ignoreHidden?: boolean; imageExtension?: string; @@ -274,8 +347,10 @@ class TestApp { title?: string; zIndex?: number; zoomOnClick?: boolean; + options?: MarkerClustererOptions; state = 'state1'; onClusteringBegin() {} + onClusterClick() {} } diff --git a/src/google-maps/map-marker-clusterer/map-marker-clusterer.ts b/src/google-maps/map-marker-clusterer/map-marker-clusterer.ts index 76ddd266ee5e..538e5ed45551 100644 --- a/src/google-maps/map-marker-clusterer/map-marker-clusterer.ts +++ b/src/google-maps/map-marker-clusterer/map-marker-clusterer.ts @@ -7,7 +7,7 @@ */ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 -/// +/// /// import { @@ -17,19 +17,24 @@ import { ContentChildren, Input, NgZone, + OnChanges, OnDestroy, OnInit, Output, QueryList, - ViewEncapsulation + SimpleChanges, + ViewEncapsulation, } from '@angular/core'; -import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; -import {map, take, takeUntil} from 'rxjs/operators'; +import {Observable, Subject} from 'rxjs'; +import {takeUntil} from 'rxjs/operators'; import {GoogleMap} from '../google-map/google-map'; import {MapEventManager} from '../map-event-manager'; import {MapMarker} from '../map-marker/map-marker'; +/** Default options for a clusterer. */ +const DEFAULT_CLUSTERER_OPTIONS: MarkerClustererOptions = {}; + /** * Angular component for implementing a Google Maps Marker Clusterer. * @@ -42,27 +47,8 @@ import {MapMarker} from '../map-marker/map-marker'; template: '', encapsulation: ViewEncapsulation.None, }) -export class MapMarkerClusterer implements OnInit, AfterContentInit, OnDestroy { - private readonly _ariaLabelFn = new BehaviorSubject(undefined); - private readonly _averageCenter = new BehaviorSubject(undefined); - private readonly _batchSizeIE = new BehaviorSubject(undefined); - private readonly _calculator = new BehaviorSubject(undefined); - private readonly _clusterClass = new BehaviorSubject(undefined); - private readonly _enableRetinalIcons = new BehaviorSubject(undefined); - private readonly _gridSize = new BehaviorSubject(undefined); - private readonly _ignoreHidden = new BehaviorSubject(undefined); - private readonly _imageExtension = new BehaviorSubject(undefined); - private readonly _imagePath = new BehaviorSubject(undefined); - private readonly _imageSizes = new BehaviorSubject(undefined); - private readonly _maxZoom = new BehaviorSubject(undefined); - private readonly _minimumClusterSize = new BehaviorSubject(undefined); - private readonly _styles = new BehaviorSubject(undefined); - private readonly _title = new BehaviorSubject(undefined); - private readonly _zIndex = new BehaviorSubject(undefined); - private readonly _zoomOnClick = new BehaviorSubject(undefined); - +export class MapMarkerClusterer implements OnInit, AfterContentInit, OnChanges, OnDestroy { private readonly _currentMarkers = new Set(); - private readonly _eventManager = new MapEventManager(this._ngZone); private readonly _destroy = new Subject(); @@ -70,109 +56,130 @@ export class MapMarkerClusterer implements OnInit, AfterContentInit, OnDestroy { private readonly _canInitialize: boolean; @Input() - get ariaLabelFn(): AriaLabelFn { - return this.markerClusterer ? this.markerClusterer.ariaLabelFn : () => ''; - } - set ariaLabelFn(ariaLabelFn: AriaLabelFn) { - this._ariaLabelFn.next(ariaLabelFn); - } + ariaLabelFn: AriaLabelFn = () => ''; @Input() set averageCenter(averageCenter: boolean) { - this._averageCenter.next(averageCenter); + this._averageCenter = averageCenter; } + private _averageCenter: boolean; @Input() batchSize?: number; @Input() set batchSizeIE(batchSizeIE: number) { - this._batchSizeIE.next(batchSizeIE); + this._batchSizeIE = batchSizeIE; } + private _batchSizeIE: number; @Input() set calculator(calculator: Calculator) { - this._calculator.next(calculator); + this._calculator = calculator; } + private _calculator: Calculator; @Input() set clusterClass(clusterClass: string) { - this._clusterClass.next(clusterClass); + this._clusterClass = clusterClass; } + private _clusterClass: string; @Input() - set enableRetinalIcons(enableRetinalIcons: boolean) { - this._enableRetinalIcons.next(enableRetinalIcons); + set enableRetinaIcons(enableRetinaIcons: boolean) { + this._enableRetinaIcons = enableRetinaIcons; } + private _enableRetinaIcons: boolean; @Input() set gridSize(gridSize: number) { - this._gridSize.next(gridSize); + this._gridSize = gridSize; } + private _gridSize: number; @Input() set ignoreHidden(ignoreHidden: boolean) { - this._ignoreHidden.next(ignoreHidden); + this._ignoreHidden = ignoreHidden; } + private _ignoreHidden: boolean; @Input() set imageExtension(imageExtension: string) { - this._imageExtension.next(imageExtension); + this._imageExtension = imageExtension; } + private _imageExtension: string; @Input() set imagePath(imagePath: string) { - this._imagePath.next(imagePath); + this._imagePath = imagePath; } + private _imagePath: string; @Input() set imageSizes(imageSizes: number[]) { - this._imageSizes.next(imageSizes); + this._imageSizes = imageSizes; } + private _imageSizes: number[]; @Input() set maxZoom(maxZoom: number) { - this._maxZoom.next(maxZoom); + this._maxZoom = maxZoom; } + private _maxZoom: number; @Input() set minimumClusterSize(minimumClusterSize: number) { - this._minimumClusterSize.next(minimumClusterSize); + this._minimumClusterSize = minimumClusterSize; } + private _minimumClusterSize: number; @Input() set styles(styles: ClusterIconStyle[]) { - this._styles.next(styles); + this._styles = styles; } + private _styles: ClusterIconStyle[]; @Input() set title(title: string) { - this._title.next(title); + this._title = title; } + private _title: string; @Input() set zIndex(zIndex: number) { - this._zIndex.next(zIndex); + this._zIndex = zIndex; } + private _zIndex: number; @Input() set zoomOnClick(zoomOnClick: boolean) { - this._zoomOnClick.next(zoomOnClick); + this._zoomOnClick = zoomOnClick; + } + private _zoomOnClick: boolean; + + @Input() + set options(options: MarkerClustererOptions) { + this._options = options; } + private _options: MarkerClustererOptions; /** * See * googlemaps.github.io/v3-utility-library/modules/ * _google_markerclustererplus.html#clusteringbegin */ - @Output() - clusteringbegin: Observable = this._eventManager.getLazyEmitter('clusteringbegin'); + @Output() readonly clusteringbegin: Observable = + this._eventManager.getLazyEmitter('clusteringbegin'); /** * See * googlemaps.github.io/v3-utility-library/modules/_google_markerclustererplus.html#clusteringend */ + @Output() readonly clusteringend: Observable = + this._eventManager.getLazyEmitter('clusteringend'); + + /** Emits when a cluster has been clicked. */ @Output() - clusteringend: Observable = this._eventManager.getLazyEmitter('clusteringend'); + readonly clusterClick: Observable = this._eventManager.getLazyEmitter('click'); @ContentChildren(MapMarker, {descendants: true}) _markers: QueryList; @@ -191,35 +198,31 @@ export class MapMarkerClusterer implements OnInit, AfterContentInit, OnDestroy { ngOnInit() { if (this._canInitialize) { - this._combineOptions().pipe(take(1)).subscribe(options => { - // Create the object outside the zone so its events don't trigger change detection. - // We'll bring it back in inside the `MapEventManager` only for the events that the - // user has subscribed to. - this._ngZone.runOutsideAngular(() => { - this.markerClusterer = new MarkerClusterer(this._googleMap.googleMap!, [], options); - }); + const clustererWindow = window as unknown as typeof globalThis & { + MarkerClusterer?: MarkerClusterer; + }; - this._assertInitialized(); - this._eventManager.setTarget(this.markerClusterer); + if (!clustererWindow.MarkerClusterer && (typeof ngDevMode === 'undefined' || ngDevMode)) { + throw Error( + 'MarkerClusterer class not found, cannot construct a marker cluster. ' + + 'Please install the MarkerClustererPlus library: ' + + 'https://github.com/googlemaps/js-markerclustererplus', + ); + } + + // Create the object outside the zone so its events don't trigger change detection. + // We'll bring it back in inside the `MapEventManager` only for the events that the + // user has subscribed to. + this._ngZone.runOutsideAngular(() => { + this.markerClusterer = new MarkerClusterer( + this._googleMap.googleMap!, + [], + this._combineOptions(), + ); }); - this._watchForAriaLabelFnChanges(); - this._watchForAverageCenterChanges(); - this._watchForBatchSizeIEChanges(); - this._watchForCalculatorChanges(); - this._watchForClusterClassChanges(); - this._watchForEnableRetinalIconsChanges(); - this._watchForGridSizeChanges(); - this._watchForIgnoreHiddenChanges(); - this._watchForImageExtensionChanges(); - this._watchForImagePathChanges(); - this._watchForImageSizesChanges(); - this._watchForMaxZoomChanges(); - this._watchForMinimumClusterSizeChanges(); - this._watchForStylesChanges(); - this._watchForTitleChanges(); - this._watchForZIndexChanges(); - this._watchForZoomOnClickChanges(); + this._assertInitialized(); + this._eventManager.setTarget(this.markerClusterer); } } @@ -229,6 +232,86 @@ export class MapMarkerClusterer implements OnInit, AfterContentInit, OnDestroy { } } + ngOnChanges(changes: SimpleChanges) { + const { + markerClusterer: clusterer, + ariaLabelFn, + _averageCenter, + _batchSizeIE, + _calculator, + _styles, + _clusterClass, + _enableRetinaIcons, + _gridSize, + _ignoreHidden, + _imageExtension, + _imagePath, + _imageSizes, + _maxZoom, + _minimumClusterSize, + _title, + _zIndex, + _zoomOnClick, + } = this; + + if (clusterer) { + if (changes['options']) { + clusterer.setOptions(this._combineOptions()); + } + if (changes['ariaLabelFn']) { + clusterer.ariaLabelFn = ariaLabelFn; + } + if (changes['averageCenter'] && _averageCenter !== undefined) { + clusterer.setAverageCenter(_averageCenter); + } + if (changes['batchSizeIE'] && _batchSizeIE !== undefined) { + clusterer.setBatchSizeIE(_batchSizeIE); + } + if (changes['calculator'] && !!_calculator) { + clusterer.setCalculator(_calculator); + } + if (changes['clusterClass'] && _clusterClass !== undefined) { + clusterer.setClusterClass(_clusterClass); + } + if (changes['enableRetinaIcons'] && _enableRetinaIcons !== undefined) { + clusterer.setEnableRetinaIcons(_enableRetinaIcons); + } + if (changes['gridSize'] && _gridSize !== undefined) { + clusterer.setGridSize(_gridSize); + } + if (changes['ignoreHidden'] && _ignoreHidden !== undefined) { + clusterer.setIgnoreHidden(_ignoreHidden); + } + if (changes['imageExtension'] && _imageExtension !== undefined) { + clusterer.setImageExtension(_imageExtension); + } + if (changes['imagePath'] && _imagePath !== undefined) { + clusterer.setImagePath(_imagePath); + } + if (changes['imageSizes'] && _imageSizes) { + clusterer.setImageSizes(_imageSizes); + } + if (changes['maxZoom'] && _maxZoom !== undefined) { + clusterer.setMaxZoom(_maxZoom); + } + if (changes['minimumClusterSize'] && _minimumClusterSize !== undefined) { + clusterer.setMinimumClusterSize(_minimumClusterSize); + } + if (changes['styles'] && _styles) { + clusterer.setStyles(_styles); + } + if (changes['title'] && _title !== undefined) { + clusterer.setTitle(_title); + } + if (changes['zIndex'] && _zIndex !== undefined) { + clusterer.setZIndex(_zIndex); + } + if (changes['zoomOnClick'] && _zoomOnClick !== undefined) { + clusterer.setZoomOnClick(_zoomOnClick); + } + } + } + ngOnDestroy() { this._destroy.next(); this._destroy.complete(); @@ -238,7 +321,7 @@ export class MapMarkerClusterer implements OnInit, AfterContentInit, OnDestroy { } } - fitMapToMarkers(padding: number|google.maps.Padding) { + fitMapToMarkers(padding: number | google.maps.Padding) { this._assertInitialized(); this.markerClusterer.fitMapToMarkers(padding); } @@ -268,9 +351,9 @@ export class MapMarkerClusterer implements OnInit, AfterContentInit, OnDestroy { return this.markerClusterer.getClusters(); } - getEnableRetinalIcons(): boolean { + getEnableRetinaIcons(): boolean { this._assertInitialized(); - return this.markerClusterer.getEnableRetinalIcons(); + return this.markerClusterer.getEnableRetinaIcons(); } getGridSize(): number { @@ -338,219 +421,29 @@ export class MapMarkerClusterer implements OnInit, AfterContentInit, OnDestroy { return this.markerClusterer.getZoomOnClick(); } - private _combineOptions(): Observable { - return combineLatest([ - this._ariaLabelFn, - this._averageCenter, - this._batchSizeIE, - this._calculator, - this._clusterClass, - this._enableRetinalIcons, - this._gridSize, - this._ignoreHidden, - this._imageExtension, - this._imagePath, - this._imageSizes, - this._maxZoom, - this._minimumClusterSize, - this._styles, - this._title, - this._zIndex, - this._zoomOnClick, - ]).pipe(take(1), map(([ - ariaLabelFn, - averageCenter, - batchSizeIE, - calculator, - clusterClass, - enableRetinalIcons, - gridSize, - ignoreHidden, - imageExtension, - imagePath, - imageSizes, - maxZoom, - minimumClusterSize, - styles, - title, - zIndex, - zoomOnClick, - ]) => { - const combinedOptions: MarkerClustererOptions = { - ariaLabelFn: ariaLabelFn as AriaLabelFn|undefined, - averageCenter: averageCenter as boolean|undefined, - batchSize: this.batchSize, - batchSizeIE: batchSizeIE as number|undefined, - calculator: calculator as Calculator|undefined, - clusterClass: clusterClass as string|undefined, - enableRetinalIcons: enableRetinalIcons as boolean|undefined, - gridSize: gridSize as number|undefined, - ignoreHidden: ignoreHidden as boolean|undefined, - imageExtension: imageExtension as string|undefined, - imagePath: imagePath as string|undefined, - imageSizes: imageSizes as number[]|undefined, - maxZoom: maxZoom as number|undefined, - minimumClusterSize: minimumClusterSize as number|undefined, - styles: styles as ClusterIconStyle[]|undefined, - title: title as string|undefined, - zIndex: zIndex as number|undefined, - zoomOnClick: zoomOnClick as boolean|undefined, - }; - return combinedOptions; - })); - } - - private _watchForAriaLabelFnChanges() { - this._ariaLabelFn.pipe(takeUntil(this._destroy)).subscribe(ariaLabelFn => { - if (this.markerClusterer && ariaLabelFn) { - this._assertInitialized(); - this.markerClusterer.ariaLabelFn = ariaLabelFn; - } - }); - } - - private _watchForAverageCenterChanges() { - this._averageCenter.pipe(takeUntil(this._destroy)).subscribe(averageCenter => { - if (this.markerClusterer && averageCenter !== undefined) { - this._assertInitialized(); - this.markerClusterer.setAverageCenter(averageCenter); - } - }); - } - - private _watchForBatchSizeIEChanges() { - this._batchSizeIE.pipe(takeUntil(this._destroy)).subscribe(batchSizeIE => { - if (this.markerClusterer && batchSizeIE !== undefined) { - this._assertInitialized(); - this.markerClusterer.setBatchSizeIE(batchSizeIE); - } - }); - } - - private _watchForCalculatorChanges() { - this._calculator.pipe(takeUntil(this._destroy)).subscribe(calculator => { - if (this.markerClusterer && calculator) { - this._assertInitialized(); - this.markerClusterer.setCalculator(calculator); - } - }); - } - - private _watchForClusterClassChanges() { - this._clusterClass.pipe(takeUntil(this._destroy)).subscribe(clusterClass => { - if (this.markerClusterer && clusterClass !== undefined) { - this._assertInitialized(); - this.markerClusterer.setClusterClass(clusterClass); - } - }); - } - - private _watchForEnableRetinalIconsChanges() { - this._enableRetinalIcons.pipe(takeUntil(this._destroy)).subscribe(enableRetinalIcons => { - if (this.markerClusterer && enableRetinalIcons !== undefined) { - this._assertInitialized(); - this.markerClusterer.setEnableRetinalIcons(enableRetinalIcons); - } - }); - } - - private _watchForGridSizeChanges() { - this._gridSize.pipe(takeUntil(this._destroy)).subscribe(gridSize => { - if (this.markerClusterer && gridSize !== undefined) { - this._assertInitialized(); - this.markerClusterer.setGridSize(gridSize); - } - }); - } - - private _watchForIgnoreHiddenChanges() { - this._ignoreHidden.pipe(takeUntil(this._destroy)).subscribe(ignoreHidden => { - if (this.markerClusterer && ignoreHidden !== undefined) { - this._assertInitialized(); - this.markerClusterer.setIgnoreHidden(ignoreHidden); - } - }); - } - - private _watchForImageExtensionChanges() { - this._imageExtension.pipe(takeUntil(this._destroy)).subscribe(imageExtension => { - if (this.markerClusterer && imageExtension !== undefined) { - this._assertInitialized(); - this.markerClusterer.setImageExtension(imageExtension); - } - }); - } - - private _watchForImagePathChanges() { - this._imagePath.pipe(takeUntil(this._destroy)).subscribe(imagePath => { - if (this.markerClusterer && imagePath !== undefined) { - this._assertInitialized(); - this.markerClusterer.setImagePath(imagePath); - } - }); - } - - private _watchForImageSizesChanges() { - this._imageSizes.pipe(takeUntil(this._destroy)).subscribe(imageSizes => { - if (this.markerClusterer && imageSizes) { - this._assertInitialized(); - this.markerClusterer.setImageSizes(imageSizes); - } - }); - } - - private _watchForMaxZoomChanges() { - this._maxZoom.pipe(takeUntil(this._destroy)).subscribe(maxZoom => { - if (this.markerClusterer && maxZoom !== undefined) { - this._assertInitialized(); - this.markerClusterer.setMaxZoom(maxZoom); - } - }); - } - - private _watchForMinimumClusterSizeChanges() { - this._minimumClusterSize.pipe(takeUntil(this._destroy)).subscribe(minimumClusterSize => { - if (this.markerClusterer && minimumClusterSize !== undefined) { - this._assertInitialized(); - this.markerClusterer.setMinimumClusterSize(minimumClusterSize); - } - }); - } - - private _watchForStylesChanges() { - this._styles.pipe(takeUntil(this._destroy)).subscribe(styles => { - if (this.markerClusterer && styles) { - this._assertInitialized(); - this.markerClusterer.setStyles(styles); - } - }); - } - - private _watchForTitleChanges() { - this._title.pipe(takeUntil(this._destroy)).subscribe(title => { - if (this.markerClusterer && title !== undefined) { - this._assertInitialized(); - this.markerClusterer.setTitle(title); - } - }); - } - - private _watchForZIndexChanges() { - this._zIndex.pipe(takeUntil(this._destroy)).subscribe(zIndex => { - if (this.markerClusterer && zIndex !== undefined) { - this._assertInitialized(); - this.markerClusterer.setZIndex(zIndex); - } - }); - } - - private _watchForZoomOnClickChanges() { - this._zoomOnClick.pipe(takeUntil(this._destroy)).subscribe(zoomOnClick => { - if (this.markerClusterer && zoomOnClick !== undefined) { - this._assertInitialized(); - this.markerClusterer.setZoomOnClick(zoomOnClick); - } - }); + private _combineOptions(): MarkerClustererOptions { + const options = this._options || DEFAULT_CLUSTERER_OPTIONS; + return { + ...options, + ariaLabelFn: this.ariaLabelFn ?? options.ariaLabelFn, + averageCenter: this._averageCenter ?? options.averageCenter, + batchSize: this.batchSize ?? options.batchSize, + batchSizeIE: this._batchSizeIE ?? options.batchSizeIE, + calculator: this._calculator ?? options.calculator, + clusterClass: this._clusterClass ?? options.clusterClass, + enableRetinaIcons: this._enableRetinaIcons ?? options.enableRetinaIcons, + gridSize: this._gridSize ?? options.gridSize, + ignoreHidden: this._ignoreHidden ?? options.ignoreHidden, + imageExtension: this._imageExtension ?? options.imageExtension, + imagePath: this._imagePath ?? options.imagePath, + imageSizes: this._imageSizes ?? options.imageSizes, + maxZoom: this._maxZoom ?? options.maxZoom, + minimumClusterSize: this._minimumClusterSize ?? options.minimumClusterSize, + styles: this._styles ?? options.styles, + title: this._title ?? options.title, + zIndex: this._zIndex ?? options.zIndex, + zoomOnClick: this._zoomOnClick ?? options.zoomOnClick, + }; } private _watchForMarkerChanges() { @@ -562,8 +455,9 @@ export class MapMarkerClusterer implements OnInit, AfterContentInit, OnDestroy { } this.markerClusterer.addMarkers(initialMarkers); - this._markers.changes.pipe(takeUntil(this._destroy)).subscribe( - (markerComponents: MapMarker[]) => { + this._markers.changes + .pipe(takeUntil(this._destroy)) + .subscribe((markerComponents: MapMarker[]) => { this._assertInitialized(); const newMarkers = new Set(this._getInternalMarkers(markerComponents)); const markersToAdd: google.maps.Marker[] = []; @@ -585,12 +479,13 @@ export class MapMarkerClusterer implements OnInit, AfterContentInit, OnDestroy { for (const marker of markersToRemove) { this._currentMarkers.delete(marker); } - }); + }); } private _getInternalMarkers(markers: MapMarker[]): google.maps.Marker[] { - return markers.filter(markerComponent => !!markerComponent.marker) - .map(markerComponent => markerComponent.marker!); + return markers + .filter(markerComponent => !!markerComponent.marker) + .map(markerComponent => markerComponent.marker!); } private _assertInitialized(): asserts this is {markerClusterer: MarkerClusterer} { @@ -598,12 +493,14 @@ export class MapMarkerClusterer implements OnInit, AfterContentInit, OnDestroy { if (!this._googleMap.googleMap) { throw Error( 'Cannot access Google Map information before the API has been initialized. ' + - 'Please wait for the API to load before trying to interact with it.'); + 'Please wait for the API to load before trying to interact with it.', + ); } if (!this.markerClusterer) { throw Error( 'Cannot interact with a MarkerClusterer before it has been initialized. ' + - 'Please wait for the MarkerClusterer to load before trying to interact with it.'); + 'Please wait for the MarkerClusterer to load before trying to interact with it.', + ); } } } diff --git a/src/google-maps/map-marker-clusterer/marker-clusterer-types.ts b/src/google-maps/map-marker-clusterer/marker-clusterer-types.ts index d554920ad18f..fd4b43b28a1d 100644 --- a/src/google-maps/map-marker-clusterer/marker-clusterer-types.ts +++ b/src/google-maps/map-marker-clusterer/marker-clusterer-types.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ - /// +/// /** * Class for clustering markers on a Google Map. @@ -16,7 +16,10 @@ */ declare class MarkerClusterer { constructor( - map: google.maps.Map, markers?: google.maps.Marker[], options?: MarkerClustererOptions); + map: google.maps.Map, + markers?: google.maps.Marker[], + options?: MarkerClustererOptions, + ); ariaLabelFn: AriaLabelFn; static BATCH_SIZE: number; static BATCH_SIZE_IE: number; @@ -36,7 +39,7 @@ declare class MarkerClusterer { getCalculator(): Calculator; getClusterClass(): string; getClusters(): Cluster[]; - getEnableRetinalIcons(): boolean; + getEnableRetinaIcons(): boolean; getGridSize(): number; getIgnoreHidden(): boolean; getImageExtension(): string; @@ -63,7 +66,7 @@ declare class MarkerClusterer { setBatchSizeIE(batchSizeIE: number): void; setCalculator(calculator: Calculator): void; setClusterClass(clusterClass: string): void; - setEnableRetinalIcons(enableRetinalIcons: boolean): void; + setEnableRetinaIcons(enableRetinaIcons: boolean): void; setGridSize(gridSize: number): void; setIgnoreHidden(ignoreHidden: boolean): void; setImageExtension(imageExtension: string): void; @@ -77,6 +80,8 @@ declare class MarkerClusterer { setValues(values: any): void; setZIndex(zIndex: number): void; setZoomOnClick(zoomOnClick: boolean): void; + // Note: This one doesn't appear in the docs page, but it exists at runtime. + setOptions(options: MarkerClustererOptions): void; unbind(key: string): void; unbindAll(): void; static CALCULATOR(markers: google.maps.Marker[], numStyles: number): ClusterIconInfo; @@ -110,7 +115,7 @@ declare interface MarkerClustererOptions { batchSizeIE?: number; calculator?: Calculator; clusterClass?: string; - enableRetinalIcons?: boolean; + enableRetinaIcons?: boolean; gridSize?: number; ignoreHidden?: boolean; imageExtension?: string; @@ -173,5 +178,7 @@ declare type AriaLabelFn = (text: string) => string; * * See googlemaps.github.io/v3-utility-library/modules/_google_markerclustererplus.html#calculator */ -declare type Calculator = - (markers: google.maps.Marker[], clusterIconStylesCount: number) => ClusterIconInfo; +declare type Calculator = ( + markers: google.maps.Marker[], + clusterIconStylesCount: number, +) => ClusterIconInfo; diff --git a/src/google-maps/map-marker/README.md b/src/google-maps/map-marker/README.md index 17eae41759e7..2089aebd9f2d 100644 --- a/src/google-maps/map-marker/README.md +++ b/src/google-maps/map-marker/README.md @@ -19,7 +19,7 @@ export class GoogleMapDemo { markerOptions: google.maps.MarkerOptions = {draggable: false}; markerPositions: google.maps.LatLngLiteral[] = []; - addMarker(event: google.maps.MouseEvent) { + addMarker(event: google.maps.MapMouseEvent) { this.markerPositions.push(event.latLng.toJSON()); } } diff --git a/src/google-maps/map-marker/map-marker.spec.ts b/src/google-maps/map-marker/map-marker.spec.ts index 81d99968376a..850319a529c9 100644 --- a/src/google-maps/map-marker/map-marker.spec.ts +++ b/src/google-maps/map-marker/map-marker.spec.ts @@ -8,19 +8,21 @@ import { createMapConstructorSpy, createMapSpy, createMarkerConstructorSpy, - createMarkerSpy + createMarkerSpy, } from '../testing/fake-google-map-utils'; import {DEFAULT_MARKER_OPTIONS, MapMarker} from './map-marker'; describe('MapMarker', () => { let mapSpy: jasmine.SpyObj; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [GoogleMapsModule], - declarations: [TestApp], - }); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + declarations: [TestApp], + }); + }), + ); beforeEach(() => { TestBed.compileComponents(); @@ -45,6 +47,8 @@ describe('MapMarker', () => { title: undefined, label: undefined, clickable: undefined, + icon: undefined, + visible: undefined, map: mapSpy, }); }); @@ -55,6 +59,8 @@ describe('MapMarker', () => { title: 'marker title', label: 'marker label', clickable: false, + icon: 'icon.png', + visible: false, map: mapSpy, }; const markerSpy = createMarkerSpy(options); @@ -65,6 +71,8 @@ describe('MapMarker', () => { fixture.componentInstance.title = options.title; fixture.componentInstance.label = options.label; fixture.componentInstance.clickable = options.clickable; + fixture.componentInstance.icon = 'icon.png'; + fixture.componentInstance.visible = false; fixture.detectChanges(); expect(markerConstructorSpy).toHaveBeenCalledWith(options); @@ -77,6 +85,7 @@ describe('MapMarker', () => { label: 'marker label', clickable: false, icon: 'icon name', + visible: undefined, }; const markerSpy = createMarkerSpy(options); const markerConstructorSpy = createMarkerConstructorSpy(markerSpy).and.callThrough(); @@ -103,6 +112,7 @@ describe('MapMarker', () => { clickable: true, icon: 'icon name', map: mapSpy, + visible: undefined, }; const markerSpy = createMarkerSpy(options); const markerConstructorSpy = createMarkerConstructorSpy(markerSpy).and.callThrough(); @@ -221,6 +231,8 @@ describe('MapMarker', () => { [label]="label" [clickable]="clickable" [options]="options" + [icon]="icon" + [visible]="visible" (mapClick)="handleClick()" (positionChanged)="handlePositionChanged()"> @@ -228,11 +240,13 @@ describe('MapMarker', () => { }) class TestApp { @ViewChild(MapMarker) marker: MapMarker; - title?: string; - position?: google.maps.LatLng|google.maps.LatLngLiteral; - label?: string|google.maps.MarkerLabel; - clickable?: boolean; + title?: string | null; + position?: google.maps.LatLng | google.maps.LatLngLiteral | null; + label?: string | google.maps.MarkerLabel | null; + clickable?: boolean | null; options?: google.maps.MarkerOptions; + icon?: string; + visible?: boolean; handleClick() {} diff --git a/src/google-maps/map-marker/map-marker.ts b/src/google-maps/map-marker/map-marker.ts index 144a334d264e..aa4b3565a22e 100644 --- a/src/google-maps/map-marker/map-marker.ts +++ b/src/google-maps/map-marker/map-marker.ts @@ -7,7 +7,7 @@ */ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 -/// +/// import { Input, @@ -56,24 +56,24 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { private _title: string; /** - * Title of the marker. See: + * Position of the marker. See: * developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions.position */ @Input() - set position(position: google.maps.LatLngLiteral|google.maps.LatLng) { + set position(position: google.maps.LatLngLiteral | google.maps.LatLng) { this._position = position; } - private _position: google.maps.LatLngLiteral|google.maps.LatLng; + private _position: google.maps.LatLngLiteral | google.maps.LatLng; /** * Label for the marker. * See: developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions.label */ @Input() - set label(label: string|google.maps.MarkerLabel) { + set label(label: string | google.maps.MarkerLabel) { this._label = label; } - private _label: string|google.maps.MarkerLabel; + private _label: string | google.maps.MarkerLabel; /** * Whether the marker is clickable. See: @@ -95,160 +95,172 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { } private _options: google.maps.MarkerOptions; + /** + * Icon to be used for the marker. + * See: https://developers.google.com/maps/documentation/javascript/reference/marker#Icon + */ + @Input() + set icon(icon: string | google.maps.Icon | google.maps.Symbol) { + this._icon = icon; + } + private _icon: string | google.maps.Icon | google.maps.Symbol; + + /** + * Whether the marker is visible. + * See: developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions.visible + */ + @Input() + set visible(value: boolean) { + this._visible = value; + } + private _visible: boolean; + /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.animation_changed */ - @Output() - animationChanged: Observable = this._eventManager.getLazyEmitter('animation_changed'); + @Output() readonly animationChanged: Observable = + this._eventManager.getLazyEmitter('animation_changed'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.click */ - @Output() - mapClick: Observable = - this._eventManager.getLazyEmitter('click'); + @Output() readonly mapClick: Observable = + this._eventManager.getLazyEmitter('click'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.clickable_changed */ - @Output() - clickableChanged: Observable = this._eventManager.getLazyEmitter('clickable_changed'); + @Output() readonly clickableChanged: Observable = + this._eventManager.getLazyEmitter('clickable_changed'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.cursor_changed */ - @Output() - cursorChanged: Observable = this._eventManager.getLazyEmitter('cursor_changed'); + @Output() readonly cursorChanged: Observable = + this._eventManager.getLazyEmitter('cursor_changed'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.dblclick */ - @Output() - mapDblclick: Observable = - this._eventManager.getLazyEmitter('dblclick'); + @Output() readonly mapDblclick: Observable = + this._eventManager.getLazyEmitter('dblclick'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.drag */ - @Output() - mapDrag: Observable = - this._eventManager.getLazyEmitter('drag'); + @Output() readonly mapDrag: Observable = + this._eventManager.getLazyEmitter('drag'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.dragend */ - @Output() - mapDragend: Observable = - this._eventManager.getLazyEmitter('dragend'); + @Output() readonly mapDragend: Observable = + this._eventManager.getLazyEmitter('dragend'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.draggable_changed */ - @Output() - draggableChanged: Observable = this._eventManager.getLazyEmitter('draggable_changed'); + @Output() readonly draggableChanged: Observable = + this._eventManager.getLazyEmitter('draggable_changed'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.dragstart */ - @Output() - mapDragstart: Observable = - this._eventManager.getLazyEmitter('dragstart'); + @Output() readonly mapDragstart: Observable = + this._eventManager.getLazyEmitter('dragstart'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.flat_changed */ - @Output() flatChanged: Observable = this._eventManager.getLazyEmitter('flat_changed'); + @Output() readonly flatChanged: Observable = + this._eventManager.getLazyEmitter('flat_changed'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.icon_changed */ - @Output() iconChanged: Observable = this._eventManager.getLazyEmitter('icon_changed'); + @Output() readonly iconChanged: Observable = + this._eventManager.getLazyEmitter('icon_changed'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.mousedown */ - @Output() - mapMousedown: Observable = - this._eventManager.getLazyEmitter('mousedown'); + @Output() readonly mapMousedown: Observable = + this._eventManager.getLazyEmitter('mousedown'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.mouseout */ - @Output() - mapMouseout: Observable = - this._eventManager.getLazyEmitter('mouseout'); + @Output() readonly mapMouseout: Observable = + this._eventManager.getLazyEmitter('mouseout'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.mouseover */ - @Output() - mapMouseover: Observable = - this._eventManager.getLazyEmitter('mouseover'); + @Output() readonly mapMouseover: Observable = + this._eventManager.getLazyEmitter('mouseover'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.mouseup */ - @Output() - mapMouseup: Observable = - this._eventManager.getLazyEmitter('mouseup'); + @Output() readonly mapMouseup: Observable = + this._eventManager.getLazyEmitter('mouseup'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.position_changed */ - @Output() - positionChanged: Observable = this._eventManager.getLazyEmitter('position_changed'); + @Output() readonly positionChanged: Observable = + this._eventManager.getLazyEmitter('position_changed'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.rightclick */ - @Output() - mapRightclick: Observable = - this._eventManager.getLazyEmitter('rightclick'); + @Output() readonly mapRightclick: Observable = + this._eventManager.getLazyEmitter('rightclick'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.shape_changed */ - @Output() shapeChanged: - Observable = this._eventManager.getLazyEmitter('shape_changed'); + @Output() readonly shapeChanged: Observable = + this._eventManager.getLazyEmitter('shape_changed'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.title_changed */ - @Output() - titleChanged: Observable = this._eventManager.getLazyEmitter('title_changed'); + @Output() readonly titleChanged: Observable = + this._eventManager.getLazyEmitter('title_changed'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.visible_changed */ - @Output() - visibleChanged: Observable = this._eventManager.getLazyEmitter('visible_changed'); + @Output() readonly visibleChanged: Observable = + this._eventManager.getLazyEmitter('visible_changed'); /** * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.zindex_changed */ - @Output() - zindexChanged: Observable = this._eventManager.getLazyEmitter('zindex_changed'); + @Output() readonly zindexChanged: Observable = + this._eventManager.getLazyEmitter('zindex_changed'); /** * The underlying google.maps.Marker object. @@ -257,9 +269,7 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { */ marker?: google.maps.Marker; - constructor( - private readonly _googleMap: GoogleMap, - private _ngZone: NgZone) {} + constructor(private readonly _googleMap: GoogleMap, private _ngZone: NgZone) {} ngOnInit() { if (this._googleMap._isBrowser) { @@ -276,7 +286,7 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { } ngOnChanges(changes: SimpleChanges) { - const {marker, _title, _position, _label, _clickable} = this; + const {marker, _title, _position, _label, _clickable, _icon, _visible} = this; if (marker) { if (changes['options']) { @@ -298,6 +308,14 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { if (changes['clickable'] && _clickable !== undefined) { marker.setClickable(_clickable); } + + if (changes['icon'] && _icon) { + marker.setIcon(_icon); + } + + if (changes['visible'] && _visible !== undefined) { + marker.setVisible(_visible); + } } } @@ -312,7 +330,7 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.getAnimation */ - getAnimation(): google.maps.Animation|null { + getAnimation(): google.maps.Animation | null { this._assertInitialized(); return this.marker.getAnimation() || null; } @@ -330,7 +348,7 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.getCursor */ - getCursor(): string|null { + getCursor(): string | null { this._assertInitialized(); return this.marker.getCursor() || null; } @@ -348,7 +366,7 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.getIcon */ - getIcon(): string|google.maps.Icon|google.maps.Symbol|null { + getIcon(): string | google.maps.Icon | google.maps.Symbol | null { this._assertInitialized(); return this.marker.getIcon() || null; } @@ -357,7 +375,7 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.getLabel */ - getLabel(): google.maps.MarkerLabel|null { + getLabel(): google.maps.MarkerLabel | null { this._assertInitialized(); return this.marker.getLabel() || null; } @@ -366,7 +384,7 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.getOpacity */ - getOpacity(): number|null { + getOpacity(): number | null { this._assertInitialized(); return this.marker.getOpacity() || null; } @@ -375,7 +393,7 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.getPosition */ - getPosition(): google.maps.LatLng|null { + getPosition(): google.maps.LatLng | null { this._assertInitialized(); return this.marker.getPosition() || null; } @@ -384,7 +402,7 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.getShape */ - getShape(): google.maps.MarkerShape|null { + getShape(): google.maps.MarkerShape | null { this._assertInitialized(); return this.marker.getShape() || null; } @@ -393,7 +411,7 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.getTitle */ - getTitle(): string|null { + getTitle(): string | null { this._assertInitialized(); return this.marker.getTitle() || null; } @@ -411,7 +429,7 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { * See * developers.google.com/maps/documentation/javascript/reference/marker#Marker.getZIndex */ - getZIndex(): number|null { + getZIndex(): number | null { this._assertInitialized(); return this.marker.getZIndex() || null; } @@ -430,8 +448,10 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { title: this._title || options.title, position: this._position || options.position, label: this._label || options.label, - clickable: this._clickable !== undefined ? this._clickable : options.clickable, + clickable: this._clickable ?? options.clickable, map: this._googleMap.googleMap, + icon: this._icon || options.icon, + visible: this._visible ?? options.visible, }; } @@ -439,13 +459,15 @@ export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint { if (typeof ngDevMode === 'undefined' || ngDevMode) { if (!this._googleMap.googleMap) { throw Error( - 'Cannot access Google Map information before the API has been initialized. ' + - 'Please wait for the API to load before trying to interact with it.'); + 'Cannot access Google Map information before the API has been initialized. ' + + 'Please wait for the API to load before trying to interact with it.', + ); } if (!this.marker) { throw Error( - 'Cannot interact with a Google Map Marker before it has been ' + - 'initialized. Please wait for the Marker to load before trying to interact with it.'); + 'Cannot interact with a Google Map Marker before it has been ' + + 'initialized. Please wait for the Marker to load before trying to interact with it.', + ); } } } diff --git a/src/google-maps/map-polygon/map-polygon.spec.ts b/src/google-maps/map-polygon/map-polygon.spec.ts index 6db0f36c3bfe..589c8e9e337b 100644 --- a/src/google-maps/map-polygon/map-polygon.spec.ts +++ b/src/google-maps/map-polygon/map-polygon.spec.ts @@ -18,14 +18,20 @@ describe('MapPolygon', () => { let polygonPath: google.maps.LatLngLiteral[]; let polygonOptions: google.maps.PolygonOptions; - beforeEach(waitForAsync(() => { - polygonPath = [{lat: 25, lng: 26}, {lat: 26, lng: 27}, {lat: 30, lng: 34}]; - polygonOptions = {paths: polygonPath, strokeColor: 'grey', strokeOpacity: 0.8}; - TestBed.configureTestingModule({ - imports: [GoogleMapsModule], - declarations: [TestApp], - }); - })); + beforeEach( + waitForAsync(() => { + polygonPath = [ + {lat: 25, lng: 26}, + {lat: 26, lng: 27}, + {lat: 30, lng: 34}, + ]; + polygonOptions = {paths: polygonPath, strokeColor: 'grey', strokeOpacity: 0.8}; + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + declarations: [TestApp], + }); + }), + ); beforeEach(() => { TestBed.compileComponents(); @@ -81,8 +87,9 @@ describe('MapPolygon', () => { createPolygonConstructorSpy(polygonSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); - const polygonComponent = - fixture.debugElement.query(By.directive(MapPolygon))!.injector.get(MapPolygon); + const polygonComponent = fixture.debugElement + .query(By.directive(MapPolygon))! + .injector.get(MapPolygon); fixture.detectChanges(); polygonSpy.getDraggable.and.returnValue(true); diff --git a/src/google-maps/map-polygon/map-polygon.ts b/src/google-maps/map-polygon/map-polygon.ts index a16666e2904e..e34ade2f71f6 100644 --- a/src/google-maps/map-polygon/map-polygon.ts +++ b/src/google-maps/map-polygon/map-polygon.ts @@ -7,16 +7,9 @@ */ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 -/// - -import { - Directive, - Input, - OnDestroy, - OnInit, - Output, - NgZone, -} from '@angular/core'; +/// + +import {Directive, Input, OnDestroy, OnInit, Output, NgZone} from '@angular/core'; import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; import {map, take, takeUntil} from 'rxjs/operators'; @@ -35,10 +28,13 @@ import {MapEventManager} from '../map-event-manager'; export class MapPolygon implements OnInit, OnDestroy { private _eventManager = new MapEventManager(this._ngZone); private readonly _options = new BehaviorSubject({}); - private readonly _paths = - new BehaviorSubject>| - google.maps.MVCArray|google.maps.LatLng[]| - google.maps.LatLngLiteral[]|undefined>(undefined); + private readonly _paths = new BehaviorSubject< + | google.maps.MVCArray> + | google.maps.MVCArray + | google.maps.LatLng[] + | google.maps.LatLngLiteral[] + | undefined + >(undefined); private readonly _destroyed = new Subject(); @@ -55,104 +51,99 @@ export class MapPolygon implements OnInit, OnDestroy { } @Input() - set paths(paths: google.maps.MVCArray>| - google.maps.MVCArray|google.maps.LatLng[]| - google.maps.LatLngLiteral[]) { + set paths( + paths: + | google.maps.MVCArray> + | google.maps.MVCArray + | google.maps.LatLng[] + | google.maps.LatLngLiteral[], + ) { this._paths.next(paths); } /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.click */ - @Output() - polygonClick: Observable = - this._eventManager.getLazyEmitter('click'); + @Output() readonly polygonClick: Observable = + this._eventManager.getLazyEmitter('click'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.dblclick */ - @Output() - polygonDblclick: Observable = - this._eventManager.getLazyEmitter('dblclick'); + @Output() readonly polygonDblclick: Observable = + this._eventManager.getLazyEmitter('dblclick'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.drag */ - @Output() - polygonDrag: Observable = - this._eventManager.getLazyEmitter('drag'); + @Output() readonly polygonDrag: Observable = + this._eventManager.getLazyEmitter('drag'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.dragend */ - @Output() - polygonDragend: Observable = - this._eventManager.getLazyEmitter('dragend'); + @Output() readonly polygonDragend: Observable = + this._eventManager.getLazyEmitter('dragend'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.dragstart */ - @Output() - polygonDragstart: Observable = - this._eventManager.getLazyEmitter('dragstart'); + @Output() readonly polygonDragstart: Observable = + this._eventManager.getLazyEmitter('dragstart'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.mousedown */ - @Output() - polygonMousedown: Observable = - this._eventManager.getLazyEmitter('mousedown'); + @Output() readonly polygonMousedown: Observable = + this._eventManager.getLazyEmitter('mousedown'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.mousemove */ - @Output() - polygonMousemove: Observable = - this._eventManager.getLazyEmitter('mousemove'); + @Output() readonly polygonMousemove: Observable = + this._eventManager.getLazyEmitter('mousemove'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.mouseout */ - @Output() - polygonMouseout: Observable = - this._eventManager.getLazyEmitter('mouseout'); + @Output() readonly polygonMouseout: Observable = + this._eventManager.getLazyEmitter('mouseout'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.mouseover */ - @Output() - polygonMouseover: Observable = - this._eventManager.getLazyEmitter('mouseover'); + @Output() readonly polygonMouseover: Observable = + this._eventManager.getLazyEmitter('mouseover'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.mouseup */ - @Output() - polygonMouseup: Observable = - this._eventManager.getLazyEmitter('mouseup'); + @Output() readonly polygonMouseup: Observable = + this._eventManager.getLazyEmitter('mouseup'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.rightclick */ - @Output() - polygonRightclick: Observable = - this._eventManager.getLazyEmitter('rightclick'); + @Output() readonly polygonRightclick: Observable = + this._eventManager.getLazyEmitter('rightclick'); constructor(private readonly _map: GoogleMap, private readonly _ngZone: NgZone) {} ngOnInit() { if (this._map._isBrowser) { - this._combineOptions().pipe(take(1)).subscribe(options => { - // Create the object outside the zone so its events don't trigger change detection. - // We'll bring it back in inside the `MapEventManager` only for the events that the - // user has subscribed to. - this._ngZone.runOutsideAngular(() => { - this.polygon = new google.maps.Polygon(options); + this._combineOptions() + .pipe(take(1)) + .subscribe(options => { + // Create the object outside the zone so its events don't trigger change detection. + // We'll bring it back in inside the `MapEventManager` only for the events that the + // user has subscribed to. + this._ngZone.runOutsideAngular(() => { + this.polygon = new google.maps.Polygon(options); + }); + this._assertInitialized(); + this.polygon.setMap(this._map.googleMap!); + this._eventManager.setTarget(this.polygon); }); - this._assertInitialized(); - this.polygon.setMap(this._map.googleMap!); - this._eventManager.setTarget(this.polygon); - }); this._watchForOptionsChanges(); this._watchForPathChanges(); @@ -210,13 +201,15 @@ export class MapPolygon implements OnInit, OnDestroy { } private _combineOptions(): Observable { - return combineLatest([this._options, this._paths]).pipe(map(([options, paths]) => { - const combinedOptions: google.maps.PolygonOptions = { - ...options, - paths: paths || options.paths, - }; - return combinedOptions; - })); + return combineLatest([this._options, this._paths]).pipe( + map(([options, paths]) => { + const combinedOptions: google.maps.PolygonOptions = { + ...options, + paths: paths || options.paths, + }; + return combinedOptions; + }), + ); } private _watchForOptionsChanges() { @@ -239,13 +232,15 @@ export class MapPolygon implements OnInit, OnDestroy { if (typeof ngDevMode === 'undefined' || ngDevMode) { if (!this._map.googleMap) { throw Error( - 'Cannot access Google Map information before the API has been initialized. ' + - 'Please wait for the API to load before trying to interact with it.'); + 'Cannot access Google Map information before the API has been initialized. ' + + 'Please wait for the API to load before trying to interact with it.', + ); } if (!this.polygon) { throw Error( - 'Cannot interact with a Google Map Polygon before it has been ' + - 'initialized. Please wait for the Polygon to load before trying to interact with it.'); + 'Cannot interact with a Google Map Polygon before it has been ' + + 'initialized. Please wait for the Polygon to load before trying to interact with it.', + ); } } } diff --git a/src/google-maps/map-polyline/map-polyline.spec.ts b/src/google-maps/map-polyline/map-polyline.spec.ts index 9b85534c6100..2e8660d5d738 100644 --- a/src/google-maps/map-polyline/map-polyline.spec.ts +++ b/src/google-maps/map-polyline/map-polyline.spec.ts @@ -18,18 +18,24 @@ describe('MapPolyline', () => { let polylinePath: google.maps.LatLngLiteral[]; let polylineOptions: google.maps.PolylineOptions; - beforeEach(waitForAsync(() => { - polylinePath = [{ lat: 25, lng: 26 }, { lat: 26, lng: 27 }, { lat: 30, lng: 34 }]; - polylineOptions = { - path: polylinePath, - strokeColor: 'grey', - strokeOpacity: 0.8 - }; - TestBed.configureTestingModule({ - imports: [GoogleMapsModule], - declarations: [TestApp], - }); - })); + beforeEach( + waitForAsync(() => { + polylinePath = [ + {lat: 25, lng: 26}, + {lat: 26, lng: 27}, + {lat: 30, lng: 34}, + ]; + polylineOptions = { + path: polylinePath, + strokeColor: 'grey', + strokeOpacity: 0.8, + }; + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + declarations: [TestApp], + }); + }), + ); beforeEach(() => { TestBed.compileComponents(); @@ -85,8 +91,9 @@ describe('MapPolyline', () => { createPolylineConstructorSpy(polylineSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); - const polylineComponent = fixture.debugElement.query(By.directive( - MapPolyline))!.injector.get(MapPolyline); + const polylineComponent = fixture.debugElement + .query(By.directive(MapPolyline))! + .injector.get(MapPolyline); fixture.detectChanges(); polylineSpy.getDraggable.and.returnValue(true); diff --git a/src/google-maps/map-polyline/map-polyline.ts b/src/google-maps/map-polyline/map-polyline.ts index 846312e2c0ad..0a2b5d6d74de 100644 --- a/src/google-maps/map-polyline/map-polyline.ts +++ b/src/google-maps/map-polyline/map-polyline.ts @@ -7,16 +7,9 @@ */ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 -/// - -import { - Directive, - Input, - OnDestroy, - OnInit, - Output, - NgZone, -} from '@angular/core'; +/// + +import {Directive, Input, OnDestroy, OnInit, Output, NgZone} from '@angular/core'; import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; import {map, take, takeUntil} from 'rxjs/operators'; @@ -35,9 +28,12 @@ import {MapEventManager} from '../map-event-manager'; export class MapPolyline implements OnInit, OnDestroy { private _eventManager = new MapEventManager(this._ngZone); private readonly _options = new BehaviorSubject({}); - private readonly _path = - new BehaviorSubject|google.maps.LatLng[]| - google.maps.LatLngLiteral[]|undefined>(undefined); + private readonly _path = new BehaviorSubject< + | google.maps.MVCArray + | google.maps.LatLng[] + | google.maps.LatLngLiteral[] + | undefined + >(undefined); private readonly _destroyed = new Subject(); @@ -54,103 +50,96 @@ export class MapPolyline implements OnInit, OnDestroy { } @Input() - set path(path: google.maps.MVCArray|google.maps.LatLng[]| - google.maps.LatLngLiteral[]) { + set path( + path: + | google.maps.MVCArray + | google.maps.LatLng[] + | google.maps.LatLngLiteral[], + ) { this._path.next(path); } /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.click */ - @Output() - polylineClick: Observable = - this._eventManager.getLazyEmitter('click'); + @Output() readonly polylineClick: Observable = + this._eventManager.getLazyEmitter('click'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.dblclick */ - @Output() - polylineDblclick: Observable = - this._eventManager.getLazyEmitter('dblclick'); + @Output() readonly polylineDblclick: Observable = + this._eventManager.getLazyEmitter('dblclick'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.drag */ - @Output() - polylineDrag: Observable = - this._eventManager.getLazyEmitter('drag'); + @Output() readonly polylineDrag: Observable = + this._eventManager.getLazyEmitter('drag'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.dragend */ - @Output() - polylineDragend: Observable = - this._eventManager.getLazyEmitter('dragend'); + @Output() readonly polylineDragend: Observable = + this._eventManager.getLazyEmitter('dragend'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.dragstart */ - @Output() - polylineDragstart: Observable = - this._eventManager.getLazyEmitter('dragstart'); + @Output() readonly polylineDragstart: Observable = + this._eventManager.getLazyEmitter('dragstart'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.mousedown */ - @Output() - polylineMousedown: Observable = - this._eventManager.getLazyEmitter('mousedown'); + @Output() readonly polylineMousedown: Observable = + this._eventManager.getLazyEmitter('mousedown'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.mousemove */ - @Output() - polylineMousemove: Observable = - this._eventManager.getLazyEmitter('mousemove'); + @Output() readonly polylineMousemove: Observable = + this._eventManager.getLazyEmitter('mousemove'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.mouseout */ - @Output() - polylineMouseout: Observable = - this._eventManager.getLazyEmitter('mouseout'); + @Output() readonly polylineMouseout: Observable = + this._eventManager.getLazyEmitter('mouseout'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.mouseover */ - @Output() - polylineMouseover: Observable = - this._eventManager.getLazyEmitter('mouseover'); + @Output() readonly polylineMouseover: Observable = + this._eventManager.getLazyEmitter('mouseover'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.mouseup */ - @Output() - polylineMouseup: Observable = - this._eventManager.getLazyEmitter('mouseup'); + @Output() readonly polylineMouseup: Observable = + this._eventManager.getLazyEmitter('mouseup'); /** * See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.rightclick */ - @Output() - polylineRightclick: Observable = - this._eventManager.getLazyEmitter('rightclick'); + @Output() readonly polylineRightclick: Observable = + this._eventManager.getLazyEmitter('rightclick'); - constructor( - private readonly _map: GoogleMap, - private _ngZone: NgZone) {} + constructor(private readonly _map: GoogleMap, private _ngZone: NgZone) {} ngOnInit() { if (this._map._isBrowser) { - this._combineOptions().pipe(take(1)).subscribe(options => { - // Create the object outside the zone so its events don't trigger change detection. - // We'll bring it back in inside the `MapEventManager` only for the events that the - // user has subscribed to. - this._ngZone.runOutsideAngular(() => this.polyline = new google.maps.Polyline(options)); - this._assertInitialized(); - this.polyline.setMap(this._map.googleMap!); - this._eventManager.setTarget(this.polyline); - }); + this._combineOptions() + .pipe(take(1)) + .subscribe(options => { + // Create the object outside the zone so its events don't trigger change detection. + // We'll bring it back in inside the `MapEventManager` only for the events that the + // user has subscribed to. + this._ngZone.runOutsideAngular(() => (this.polyline = new google.maps.Polyline(options))); + this._assertInitialized(); + this.polyline.setMap(this._map.googleMap!); + this._eventManager.setTarget(this.polyline); + }); this._watchForOptionsChanges(); this._watchForPathChanges(); @@ -200,13 +189,15 @@ export class MapPolyline implements OnInit, OnDestroy { } private _combineOptions(): Observable { - return combineLatest([this._options, this._path]).pipe(map(([options, path]) => { - const combinedOptions: google.maps.PolylineOptions = { - ...options, - path: path || options.path, - }; - return combinedOptions; - })); + return combineLatest([this._options, this._path]).pipe( + map(([options, path]) => { + const combinedOptions: google.maps.PolylineOptions = { + ...options, + path: path || options.path, + }; + return combinedOptions; + }), + ); } private _watchForOptionsChanges() { @@ -229,13 +220,15 @@ export class MapPolyline implements OnInit, OnDestroy { if (typeof ngDevMode === 'undefined' || ngDevMode) { if (!this._map.googleMap) { throw Error( - 'Cannot access Google Map information before the API has been initialized. ' + - 'Please wait for the API to load before trying to interact with it.'); + 'Cannot access Google Map information before the API has been initialized. ' + + 'Please wait for the API to load before trying to interact with it.', + ); } if (!this.polyline) { throw Error( - 'Cannot interact with a Google Map Polyline before it has been ' + - 'initialized. Please wait for the Polyline to load before trying to interact with it.'); + 'Cannot interact with a Google Map Polyline before it has been ' + + 'initialized. Please wait for the Polyline to load before trying to interact with it.', + ); } } } diff --git a/src/google-maps/map-rectangle/map-rectangle.spec.ts b/src/google-maps/map-rectangle/map-rectangle.spec.ts index f2717da4540c..16bb29c9f296 100644 --- a/src/google-maps/map-rectangle/map-rectangle.spec.ts +++ b/src/google-maps/map-rectangle/map-rectangle.spec.ts @@ -18,14 +18,16 @@ describe('MapRectangle', () => { let rectangleBounds: google.maps.LatLngBoundsLiteral; let rectangleOptions: google.maps.RectangleOptions; - beforeEach(waitForAsync(() => { - rectangleBounds = {east: 30, north: 15, west: 10, south: -5}; - rectangleOptions = {bounds: rectangleBounds, strokeColor: 'grey', strokeOpacity: 0.8}; - TestBed.configureTestingModule({ - imports: [GoogleMapsModule], - declarations: [TestApp], - }); - })); + beforeEach( + waitForAsync(() => { + rectangleBounds = {east: 30, north: 15, west: 10, south: -5}; + rectangleOptions = {bounds: rectangleBounds, strokeColor: 'grey', strokeOpacity: 0.8}; + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + declarations: [TestApp], + }); + }), + ); beforeEach(() => { TestBed.compileComponents(); @@ -81,8 +83,9 @@ describe('MapRectangle', () => { createRectangleConstructorSpy(rectangleSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); - const rectangleComponent = fixture.debugElement.query(By.directive( - MapRectangle))!.injector.get(MapRectangle); + const rectangleComponent = fixture.debugElement + .query(By.directive(MapRectangle))! + .injector.get(MapRectangle); fixture.detectChanges(); rectangleComponent.getBounds(); diff --git a/src/google-maps/map-rectangle/map-rectangle.ts b/src/google-maps/map-rectangle/map-rectangle.ts index a990d902a938..5abfeebbdfc0 100644 --- a/src/google-maps/map-rectangle/map-rectangle.ts +++ b/src/google-maps/map-rectangle/map-rectangle.ts @@ -7,7 +7,7 @@ */ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 -/// +/// import {Directive, Input, OnDestroy, OnInit, Output, NgZone} from '@angular/core'; import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs'; @@ -28,9 +28,9 @@ import {MapEventManager} from '../map-event-manager'; export class MapRectangle implements OnInit, OnDestroy { private _eventManager = new MapEventManager(this._ngZone); private readonly _options = new BehaviorSubject({}); - private readonly _bounds = - new BehaviorSubject( - undefined); + private readonly _bounds = new BehaviorSubject< + google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral | undefined + >(undefined); private readonly _destroyed = new Subject(); @@ -47,120 +47,110 @@ export class MapRectangle implements OnInit, OnDestroy { } @Input() - set bounds(bounds: google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral) { + set bounds(bounds: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral) { this._bounds.next(bounds); } /** * See * developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.boundsChanged - */ - @Output() - boundsChanged: Observable = this._eventManager.getLazyEmitter('bounds_changed'); + */ @Output() readonly boundsChanged: Observable = + this._eventManager.getLazyEmitter('bounds_changed'); /** * See * developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.click */ - @Output() - rectangleClick: Observable = - this._eventManager.getLazyEmitter('click'); + @Output() readonly rectangleClick: Observable = + this._eventManager.getLazyEmitter('click'); /** * See * developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.dblclick */ - @Output() - rectangleDblclick: Observable = - this._eventManager.getLazyEmitter('dblclick'); + @Output() readonly rectangleDblclick: Observable = + this._eventManager.getLazyEmitter('dblclick'); /** * See * developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.drag */ - @Output() - rectangleDrag: Observable = - this._eventManager.getLazyEmitter('drag'); + @Output() readonly rectangleDrag: Observable = + this._eventManager.getLazyEmitter('drag'); /** * See * developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.dragend */ - @Output() - rectangleDragend: Observable = - this._eventManager.getLazyEmitter('dragend'); + @Output() readonly rectangleDragend: Observable = + this._eventManager.getLazyEmitter('dragend'); /** * See * developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.dragstart */ - @Output() - rectangleDragstart: Observable = - this._eventManager.getLazyEmitter('dragstart'); + @Output() readonly rectangleDragstart: Observable = + this._eventManager.getLazyEmitter('dragstart'); /** * See * developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.mousedown */ - @Output() - rectangleMousedown: Observable = - this._eventManager.getLazyEmitter('mousedown'); + @Output() readonly rectangleMousedown: Observable = + this._eventManager.getLazyEmitter('mousedown'); /** * See * developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.mousemove */ - @Output() - rectangleMousemove: Observable = - this._eventManager.getLazyEmitter('mousemove'); + @Output() readonly rectangleMousemove: Observable = + this._eventManager.getLazyEmitter('mousemove'); /** * See * developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.mouseout */ - @Output() - rectangleMouseout: Observable = - this._eventManager.getLazyEmitter('mouseout'); + @Output() readonly rectangleMouseout: Observable = + this._eventManager.getLazyEmitter('mouseout'); /** * See * developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.mouseover */ - @Output() - rectangleMouseover: Observable = - this._eventManager.getLazyEmitter('mouseover'); + @Output() readonly rectangleMouseover: Observable = + this._eventManager.getLazyEmitter('mouseover'); /** * See * developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.mouseup */ - @Output() - rectangleMouseup: Observable = - this._eventManager.getLazyEmitter('mouseup'); + @Output() readonly rectangleMouseup: Observable = + this._eventManager.getLazyEmitter('mouseup'); /** * See * developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.rightclick */ - @Output() - rectangleRightclick: Observable = - this._eventManager.getLazyEmitter('rightclick'); + @Output() readonly rectangleRightclick: Observable = + this._eventManager.getLazyEmitter('rightclick'); constructor(private readonly _map: GoogleMap, private readonly _ngZone: NgZone) {} ngOnInit() { if (this._map._isBrowser) { - this._combineOptions().pipe(take(1)).subscribe(options => { - // Create the object outside the zone so its events don't trigger change detection. - // We'll bring it back in inside the `MapEventManager` only for the events that the - // user has subscribed to. - this._ngZone.runOutsideAngular(() => { - this.rectangle = new google.maps.Rectangle(options); + this._combineOptions() + .pipe(take(1)) + .subscribe(options => { + // Create the object outside the zone so its events don't trigger change detection. + // We'll bring it back in inside the `MapEventManager` only for the events that the + // user has subscribed to. + this._ngZone.runOutsideAngular(() => { + this.rectangle = new google.maps.Rectangle(options); + }); + this._assertInitialized(); + this.rectangle.setMap(this._map.googleMap!); + this._eventManager.setTarget(this.rectangle); }); - this._assertInitialized(); - this.rectangle.setMap(this._map.googleMap!); - this._eventManager.setTarget(this.rectangle); - }); this._watchForOptionsChanges(); this._watchForBoundsChanges(); @@ -180,7 +170,7 @@ export class MapRectangle implements OnInit, OnDestroy { * See * developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.getBounds */ - getBounds(): google.maps.LatLngBounds { + getBounds(): google.maps.LatLngBounds | null { this._assertInitialized(); return this.rectangle.getBounds(); } @@ -213,13 +203,15 @@ export class MapRectangle implements OnInit, OnDestroy { } private _combineOptions(): Observable { - return combineLatest([this._options, this._bounds]).pipe(map(([options, bounds]) => { - const combinedOptions: google.maps.RectangleOptions = { - ...options, - bounds: bounds || options.bounds, - }; - return combinedOptions; - })); + return combineLatest([this._options, this._bounds]).pipe( + map(([options, bounds]) => { + const combinedOptions: google.maps.RectangleOptions = { + ...options, + bounds: bounds || options.bounds, + }; + return combinedOptions; + }), + ); } private _watchForOptionsChanges() { @@ -242,13 +234,15 @@ export class MapRectangle implements OnInit, OnDestroy { if (typeof ngDevMode === 'undefined' || ngDevMode) { if (!this._map.googleMap) { throw Error( - 'Cannot access Google Map information before the API has been initialized. ' + - 'Please wait for the API to load before trying to interact with it.'); + 'Cannot access Google Map information before the API has been initialized. ' + + 'Please wait for the API to load before trying to interact with it.', + ); } if (!this.rectangle) { throw Error( - 'Cannot interact with a Google Map Rectangle before it has been initialized. ' + - 'Please wait for the Rectangle to load before trying to interact with it.'); + 'Cannot interact with a Google Map Rectangle before it has been initialized. ' + + 'Please wait for the Rectangle to load before trying to interact with it.', + ); } } } diff --git a/src/google-maps/map-traffic-layer/map-traffic-layer.spec.ts b/src/google-maps/map-traffic-layer/map-traffic-layer.spec.ts index 9e93bdd76cd8..f643c288e301 100644 --- a/src/google-maps/map-traffic-layer/map-traffic-layer.spec.ts +++ b/src/google-maps/map-traffic-layer/map-traffic-layer.spec.ts @@ -14,12 +14,14 @@ describe('MapTrafficLayer', () => { let mapSpy: jasmine.SpyObj; const trafficLayerOptions: google.maps.TrafficLayerOptions = {autoRefresh: false}; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [GoogleMapsModule], - declarations: [TestApp], - }); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + declarations: [TestApp], + }); + }), + ); beforeEach(() => { TestBed.compileComponents(); @@ -35,7 +37,7 @@ describe('MapTrafficLayer', () => { it('initializes a Google Map Traffic Layer', () => { const trafficLayerSpy = createTrafficLayerSpy(trafficLayerOptions); const trafficLayerConstructorSpy = - createTrafficLayerConstructorSpy(trafficLayerSpy).and.callThrough(); + createTrafficLayerConstructorSpy(trafficLayerSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); fixture.componentInstance.autoRefresh = false; diff --git a/src/google-maps/map-traffic-layer/map-traffic-layer.ts b/src/google-maps/map-traffic-layer/map-traffic-layer.ts index 47c6988aa98e..a8d1e6f0f619 100644 --- a/src/google-maps/map-traffic-layer/map-traffic-layer.ts +++ b/src/google-maps/map-traffic-layer/map-traffic-layer.ts @@ -7,7 +7,7 @@ */ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 -/// +/// import {Directive, Input, NgZone, OnDestroy, OnInit} from '@angular/core'; import {BehaviorSubject, Observable, Subject} from 'rxjs'; @@ -47,14 +47,16 @@ export class MapTrafficLayer implements OnInit, OnDestroy { ngOnInit() { if (this._map._isBrowser) { - this._combineOptions().pipe(take(1)).subscribe(options => { - // Create the object outside the zone so its events don't trigger change detection. - this._ngZone.runOutsideAngular(() => { - this.trafficLayer = new google.maps.TrafficLayer(options); + this._combineOptions() + .pipe(take(1)) + .subscribe(options => { + // Create the object outside the zone so its events don't trigger change detection. + this._ngZone.runOutsideAngular(() => { + this.trafficLayer = new google.maps.TrafficLayer(options); + }); + this._assertInitialized(); + this.trafficLayer.setMap(this._map.googleMap!); }); - this._assertInitialized(); - this.trafficLayer.setMap(this._map.googleMap!); - }); this._watchForAutoRefreshChanges(); } @@ -69,29 +71,35 @@ export class MapTrafficLayer implements OnInit, OnDestroy { } private _combineOptions(): Observable { - return this._autoRefresh.pipe(map(autoRefresh => { - const combinedOptions: google.maps.TrafficLayerOptions = {autoRefresh}; - return combinedOptions; - })); + return this._autoRefresh.pipe( + map(autoRefresh => { + const combinedOptions: google.maps.TrafficLayerOptions = {autoRefresh}; + return combinedOptions; + }), + ); } private _watchForAutoRefreshChanges() { - this._combineOptions().pipe(takeUntil(this._destroyed)).subscribe(options => { - this._assertInitialized(); - this.trafficLayer.setOptions(options); - }); + this._combineOptions() + .pipe(takeUntil(this._destroyed)) + .subscribe(options => { + this._assertInitialized(); + this.trafficLayer.setOptions(options); + }); } private _assertInitialized(): asserts this is {trafficLayer: google.maps.TrafficLayer} { if (!this._map.googleMap) { throw Error( - 'Cannot access Google Map information before the API has been initialized. ' + - 'Please wait for the API to load before trying to interact with it.'); + 'Cannot access Google Map information before the API has been initialized. ' + + 'Please wait for the API to load before trying to interact with it.', + ); } if (!this.trafficLayer) { throw Error( - 'Cannot interact with a Google Map Traffic Layer before it has been initialized. ' + - 'Please wait for the Traffic Layer to load before trying to interact with it.'); + 'Cannot interact with a Google Map Traffic Layer before it has been initialized. ' + + 'Please wait for the Traffic Layer to load before trying to interact with it.', + ); } } } diff --git a/src/google-maps/map-transit-layer/map-transit-layer.spec.ts b/src/google-maps/map-transit-layer/map-transit-layer.spec.ts index c5b2945a5c6a..504055028c98 100644 --- a/src/google-maps/map-transit-layer/map-transit-layer.spec.ts +++ b/src/google-maps/map-transit-layer/map-transit-layer.spec.ts @@ -13,12 +13,14 @@ import { describe('MapTransitLayer', () => { let mapSpy: jasmine.SpyObj; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [GoogleMapsModule], - declarations: [TestApp], - }); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [GoogleMapsModule], + declarations: [TestApp], + }); + }), + ); beforeEach(() => { TestBed.compileComponents(); @@ -34,7 +36,7 @@ describe('MapTransitLayer', () => { it('initializes a Google Map Transit Layer', () => { const transitLayerSpy = createTransitLayerSpy(); const transitLayerConstructorSpy = - createTransitLayerConstructorSpy(transitLayerSpy).and.callThrough(); + createTransitLayerConstructorSpy(transitLayerSpy).and.callThrough(); const fixture = TestBed.createComponent(TestApp); fixture.detectChanges(); @@ -50,5 +52,4 @@ describe('MapTransitLayer', () => { `, }) -class TestApp { -} +class TestApp {} diff --git a/src/google-maps/map-transit-layer/map-transit-layer.ts b/src/google-maps/map-transit-layer/map-transit-layer.ts index 620f1b15d7a1..f1ef5af085d4 100644 --- a/src/google-maps/map-transit-layer/map-transit-layer.ts +++ b/src/google-maps/map-transit-layer/map-transit-layer.ts @@ -7,7 +7,7 @@ */ // Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265 -/// +/// import {Directive} from '@angular/core'; @@ -30,16 +30,16 @@ export class MapTransitLayer extends MapBaseLayer { */ transitLayer?: google.maps.TransitLayer; - protected _initializeObject() { + protected override _initializeObject() { this.transitLayer = new google.maps.TransitLayer(); } - protected _setMap() { + protected override _setMap() { this._assertLayerInitialized(); this.transitLayer.setMap(this._map.googleMap!); } - protected _unsetMap() { + protected override _unsetMap() { if (this.transitLayer) { this.transitLayer.setMap(null); } @@ -48,8 +48,9 @@ export class MapTransitLayer extends MapBaseLayer { private _assertLayerInitialized(): asserts this is {transitLayer: google.maps.TransitLayer} { if (!this.transitLayer) { throw Error( - 'Cannot interact with a Google Map Transit Layer before it has been initialized. ' + - 'Please wait for the Transit Layer to load before trying to interact with it.'); + 'Cannot interact with a Google Map Transit Layer before it has been initialized. ' + + 'Please wait for the Transit Layer to load before trying to interact with it.', + ); } } } diff --git a/src/google-maps/package.json b/src/google-maps/package.json index f5a1ee91498c..037408b53d8c 100644 --- a/src/google-maps/package.json +++ b/src/google-maps/package.json @@ -17,15 +17,14 @@ }, "homepage": "https://github.com/angular/components/tree/master/src/google-maps#readme", "dependencies": { - "@types/googlemaps": "^3.39.3", + "@types/google.maps": "^3.45.6", "tslib": "0.0.0-TSLIB" }, "peerDependencies": { "@angular/core": "0.0.0-NG", - "@angular/common": "0.0.0-NG" + "@angular/common": "0.0.0-NG", + "rxjs": "0.0.0-RXJS" }, "sideEffects": false, - "publishConfig": { - "registry": "https://wombat-dressing-room.appspot.com" - } + "ng-update": {} } diff --git a/src/google-maps/public-api.ts b/src/google-maps/public-api.ts index b50add5bad02..0da2107fd540 100644 --- a/src/google-maps/public-api.ts +++ b/src/google-maps/public-api.ts @@ -12,6 +12,11 @@ export {MapAnchorPoint} from './map-anchor-point'; export {MapBaseLayer} from './map-base-layer'; export {MapBicyclingLayer} from './map-bicycling-layer/map-bicycling-layer'; export {MapCircle} from './map-circle/map-circle'; +export {MapDirectionsRenderer} from './map-directions-renderer/map-directions-renderer'; +export { + MapDirectionsService, + MapDirectionsResponse, +} from './map-directions-renderer/map-directions-service'; export {MapGroundOverlay} from './map-ground-overlay/map-ground-overlay'; export {MapInfoWindow} from './map-info-window/map-info-window'; export {MapKmlLayer} from './map-kml-layer/map-kml-layer'; @@ -22,3 +27,5 @@ export {MapPolyline} from './map-polyline/map-polyline'; export {MapRectangle} from './map-rectangle/map-rectangle'; export {MapTrafficLayer} from './map-traffic-layer/map-traffic-layer'; export {MapTransitLayer} from './map-transit-layer/map-transit-layer'; +export {MapHeatmapLayer, HeatmapData} from './map-heatmap-layer/map-heatmap-layer'; +export {MapGeocoder, MapGeocoderResponse} from './map-geocoder/map-geocoder'; diff --git a/src/google-maps/testing/BUILD.bazel b/src/google-maps/testing/BUILD.bazel index 534b39c85850..415807b6a3b6 100644 --- a/src/google-maps/testing/BUILD.bazel +++ b/src/google-maps/testing/BUILD.bazel @@ -8,7 +8,7 @@ ts_library( srcs = glob(["**/*.ts"]), deps = [ "//src/google-maps", - "@npm//@types/googlemaps", + "@npm//@types/google.maps", "@npm//@types/jasmine", ], ) diff --git a/src/google-maps/testing/fake-google-map-utils.ts b/src/google-maps/testing/fake-google-map-utils.ts index 1a105ee2df8d..57c8d79b507f 100644 --- a/src/google-maps/testing/fake-google-map-utils.ts +++ b/src/google-maps/testing/fake-google-map-utils.ts @@ -28,6 +28,13 @@ export interface TestingWindow extends Window { TrafficLayer?: jasmine.Spy; TransitLayer?: jasmine.Spy; BicyclingLayer?: jasmine.Spy; + DirectionsRenderer?: jasmine.Spy; + DirectionsService?: jasmine.Spy; + LatLng?: jasmine.Spy; + visualization?: { + HeatmapLayer?: jasmine.Spy; + }; + Geocoder?: jasmine.Spy; }; }; MarkerClusterer?: jasmine.Spy; @@ -36,9 +43,25 @@ export interface TestingWindow extends Window { /** Creates a jasmine.SpyObj for a google.maps.Map. */ export function createMapSpy(options: google.maps.MapOptions): jasmine.SpyObj { const mapSpy = jasmine.createSpyObj('google.maps.Map', [ - 'setOptions', 'setCenter', 'setZoom', 'setMap', 'addListener', 'fitBounds', 'panBy', 'panTo', - 'panToBounds', 'getBounds', 'getCenter', 'getClickableIcons', 'getHeading', 'getMapTypeId', - 'getProjection', 'getStreetView', 'getTilt', 'getZoom', 'setMapTypeId' + 'setOptions', + 'setCenter', + 'setZoom', + 'setMap', + 'addListener', + 'fitBounds', + 'panBy', + 'panTo', + 'panToBounds', + 'getBounds', + 'getCenter', + 'getClickableIcons', + 'getHeading', + 'getMapTypeId', + 'getProjection', + 'getStreetView', + 'getTilt', + 'getZoom', + 'setMapTypeId', ]); mapSpy.addListener.and.returnValue({remove: () => {}}); return mapSpy; @@ -46,41 +69,57 @@ export function createMapSpy(options: google.maps.MapOptions): jasmine.SpyObj, apiLoaded = true): jasmine.Spy { - const mapConstructorSpy = - jasmine.createSpy('Map constructor', (_el: Element, _options: google.maps.MapOptions) => { - return mapSpy; - }); + mapSpy: jasmine.SpyObj, + apiLoaded = true, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const mapConstructorSpy = jasmine.createSpy('Map constructor', function () { + return mapSpy; + }); const testingWindow: TestingWindow = window; if (apiLoaded) { testingWindow.google = { maps: { 'Map': mapConstructorSpy, - } + }, }; } return mapConstructorSpy; } /** Creates a jasmine.SpyObj for a google.maps.Marker */ -export function createMarkerSpy(options: google.maps.MarkerOptions): - jasmine.SpyObj { +export function createMarkerSpy( + options: google.maps.MarkerOptions, +): jasmine.SpyObj { const markerSpy = jasmine.createSpyObj('google.maps.Marker', [ - 'setOptions', 'setMap', 'addListener', 'getAnimation', 'getClickable', 'getCursor', - 'getDraggable', 'getIcon', 'getLabel', 'getOpacity', 'getPosition', 'getShape', 'getTitle', - 'getVisible', 'getZIndex' + 'setOptions', + 'setMap', + 'addListener', + 'getAnimation', + 'getClickable', + 'getCursor', + 'getDraggable', + 'getIcon', + 'getLabel', + 'getOpacity', + 'getPosition', + 'getShape', + 'getTitle', + 'getVisible', + 'getZIndex', ]); markerSpy.addListener.and.returnValue({remove: () => {}}); return markerSpy; } /** Creates a jasmine.Spy to watch for the constructor of a google.maps.Marker */ -export function createMarkerConstructorSpy(markerSpy: jasmine.SpyObj): - jasmine.Spy { - const markerConstructorSpy = - jasmine.createSpy('Marker constructor', (_options: google.maps.MarkerOptions) => { - return markerSpy; - }); +export function createMarkerConstructorSpy( + markerSpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const markerConstructorSpy = jasmine.createSpy('Marker constructor', function () { + return markerSpy; + }); const testingWindow: TestingWindow = window; if (testingWindow.google && testingWindow.google.maps) { testingWindow.google.maps['Marker'] = markerConstructorSpy; @@ -95,26 +134,34 @@ export function createMarkerConstructorSpy(markerSpy: jasmine.SpyObj { +export function createInfoWindowSpy( + options: google.maps.InfoWindowOptions, +): jasmine.SpyObj { let anchor: any; - const infoWindowSpy = jasmine.createSpyObj( - 'google.maps.InfoWindow', - ['addListener', 'close', 'getContent', 'getPosition', 'getZIndex', 'open', 'get']); + const infoWindowSpy = jasmine.createSpyObj('google.maps.InfoWindow', [ + 'addListener', + 'close', + 'getContent', + 'getPosition', + 'getZIndex', + 'open', + 'get', + ]); infoWindowSpy.addListener.and.returnValue({remove: () => {}}); - infoWindowSpy.open.and.callFake((_map: any, target: any) => anchor = target); - infoWindowSpy.close.and.callFake(() => anchor = null); - infoWindowSpy.get.and.callFake((key: string) => key === 'anchor' ? anchor : null); + infoWindowSpy.open.and.callFake((_map: any, target: any) => (anchor = target)); + infoWindowSpy.close.and.callFake(() => (anchor = null)); + infoWindowSpy.get.and.callFake((key: string) => (key === 'anchor' ? anchor : null)); return infoWindowSpy; } /** Creates a jasmine.Spy to watch for the constructor of a google.maps.InfoWindow */ export function createInfoWindowConstructorSpy( - infoWindowSpy: jasmine.SpyObj): jasmine.Spy { - const infoWindowConstructorSpy = - jasmine.createSpy('InfoWindow constructor', (_options: google.maps.InfoWindowOptions) => { - return infoWindowSpy; - }); + infoWindowSpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const infoWindowConstructorSpy = jasmine.createSpy('InfoWindow constructor', function () { + return infoWindowSpy; + }); const testingWindow: TestingWindow = window; if (testingWindow.google && testingWindow.google.maps) { testingWindow.google.maps['InfoWindow'] = infoWindowConstructorSpy; @@ -129,23 +176,31 @@ export function createInfoWindowConstructorSpy( } /** Creates a jasmine.SpyObj for a google.maps.Polyline */ -export function createPolylineSpy(options: google.maps.PolylineOptions): - jasmine.SpyObj { +export function createPolylineSpy( + options: google.maps.PolylineOptions, +): jasmine.SpyObj { const polylineSpy = jasmine.createSpyObj('google.maps.Polyline', [ - 'addListener', 'getDraggable', 'getEditable', 'getPath', 'getVisible', 'setMap', 'setOptions', - 'setPath' + 'addListener', + 'getDraggable', + 'getEditable', + 'getPath', + 'getVisible', + 'setMap', + 'setOptions', + 'setPath', ]); polylineSpy.addListener.and.returnValue({remove: () => {}}); return polylineSpy; } /** Creates a jasmine.Spy to watch for the constructor of a google.maps.Polyline */ -export function createPolylineConstructorSpy(polylineSpy: jasmine.SpyObj): - jasmine.Spy { - const polylineConstructorSpy = - jasmine.createSpy('Polyline constructor', (_options: google.maps.PolylineOptions) => { - return polylineSpy; - }); +export function createPolylineConstructorSpy( + polylineSpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const polylineConstructorSpy = jasmine.createSpy('Polyline constructor', function () { + return polylineSpy; + }); const testingWindow: TestingWindow = window; if (testingWindow.google && testingWindow.google.maps) { testingWindow.google.maps['Polyline'] = polylineConstructorSpy; @@ -160,23 +215,32 @@ export function createPolylineConstructorSpy(polylineSpy: jasmine.SpyObj { +export function createPolygonSpy( + options: google.maps.PolygonOptions, +): jasmine.SpyObj { const polygonSpy = jasmine.createSpyObj('google.maps.Polygon', [ - 'addListener', 'getDraggable', 'getEditable', 'getPath', 'getPaths', 'getVisible', 'setMap', - 'setOptions', 'setPath' + 'addListener', + 'getDraggable', + 'getEditable', + 'getPath', + 'getPaths', + 'getVisible', + 'setMap', + 'setOptions', + 'setPath', ]); polygonSpy.addListener.and.returnValue({remove: () => {}}); return polygonSpy; } /** Creates a jasmine.Spy to watch for the constructor of a google.maps.Polygon */ -export function createPolygonConstructorSpy(polygonSpy: jasmine.SpyObj): - jasmine.Spy { - const polygonConstructorSpy = - jasmine.createSpy('Polygon constructor', (_options: google.maps.PolygonOptions) => { - return polygonSpy; - }); +export function createPolygonConstructorSpy( + polygonSpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const polygonConstructorSpy = jasmine.createSpy('Polygon constructor', function () { + return polygonSpy; + }); const testingWindow: TestingWindow = window; if (testingWindow.google && testingWindow.google.maps) { testingWindow.google.maps['Polygon'] = polygonConstructorSpy; @@ -191,23 +255,31 @@ export function createPolygonConstructorSpy(polygonSpy: jasmine.SpyObj { +export function createRectangleSpy( + options: google.maps.RectangleOptions, +): jasmine.SpyObj { const rectangleSpy = jasmine.createSpyObj('google.maps.Rectangle', [ - 'addListener', 'getBounds', 'getDraggable', 'getEditable', 'getVisible', 'setMap', 'setOptions', - 'setBounds' + 'addListener', + 'getBounds', + 'getDraggable', + 'getEditable', + 'getVisible', + 'setMap', + 'setOptions', + 'setBounds', ]); rectangleSpy.addListener.and.returnValue({remove: () => {}}); return rectangleSpy; } /** Creates a jasmine.Spy to watch for the constructor of a google.maps.Rectangle */ -export function createRectangleConstructorSpy(rectangleSpy: jasmine.SpyObj): - jasmine.Spy { - const rectangleConstructorSpy = - jasmine.createSpy('Rectangle constructor', (_options: google.maps.RectangleOptions) => { - return rectangleSpy; - }); +export function createRectangleConstructorSpy( + rectangleSpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const rectangleConstructorSpy = jasmine.createSpy('Rectangle constructor', function () { + return rectangleSpy; + }); const testingWindow: TestingWindow = window; if (testingWindow.google && testingWindow.google.maps) { testingWindow.google.maps['Rectangle'] = rectangleConstructorSpy; @@ -222,23 +294,33 @@ export function createRectangleConstructorSpy(rectangleSpy: jasmine.SpyObj { +export function createCircleSpy( + options: google.maps.CircleOptions, +): jasmine.SpyObj { const circleSpy = jasmine.createSpyObj('google.maps.Circle', [ - 'addListener', 'getCenter', 'getRadius', 'getDraggable', 'getEditable', 'getVisible', 'setMap', - 'setOptions', 'setCenter', 'setRadius' + 'addListener', + 'getCenter', + 'getRadius', + 'getDraggable', + 'getEditable', + 'getVisible', + 'setMap', + 'setOptions', + 'setCenter', + 'setRadius', ]); circleSpy.addListener.and.returnValue({remove: () => {}}); return circleSpy; } /** Creates a jasmine.Spy to watch for the constructor of a google.maps.Circle */ -export function createCircleConstructorSpy(circleSpy: jasmine.SpyObj): - jasmine.Spy { - const circleConstructorSpy = - jasmine.createSpy('Circle constructor', (_options: google.maps.CircleOptions) => { - return circleSpy; - }); +export function createCircleConstructorSpy( + circleSpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const circleConstructorSpy = jasmine.createSpy('Circle constructor', function () { + return circleSpy; + }); const testingWindow: TestingWindow = window; if (testingWindow.google && testingWindow.google.maps) { testingWindow.google.maps['Circle'] = circleConstructorSpy; @@ -254,8 +336,10 @@ export function createCircleConstructorSpy(circleSpy: jasmine.SpyObj { + url: string, + bounds: google.maps.LatLngBoundsLiteral, + options?: google.maps.GroundOverlayOptions, +): jasmine.SpyObj { const values: {[key: string]: any} = {url}; const groundOverlaySpy = jasmine.createSpyObj('google.maps.GroundOverlay', [ 'addListener', @@ -267,19 +351,18 @@ export function createGroundOverlaySpy( 'set', ]); groundOverlaySpy.addListener.and.returnValue({remove: () => {}}); - groundOverlaySpy.set.and.callFake((key: string, value: any) => values[key] = value); + groundOverlaySpy.set.and.callFake((key: string, value: any) => (values[key] = value)); return groundOverlaySpy; } /** Creates a jasmine.Spy to watch for the constructor of a google.maps.GroundOverlay */ export function createGroundOverlayConstructorSpy( - groundOverlaySpy: jasmine.SpyObj): jasmine.Spy { - const groundOverlayConstructorSpy = jasmine.createSpy( - 'GroundOverlay constructor', - (_url: string, _bounds: google.maps.LatLngBoundsLiteral, - _options: google.maps.GroundOverlayOptions) => { - return groundOverlaySpy; - }); + groundOverlaySpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const groundOverlayConstructorSpy = jasmine.createSpy('GroundOverlay constructor', function () { + return groundOverlaySpy; + }); const testingWindow: TestingWindow = window; if (testingWindow.google && testingWindow.google.maps) { testingWindow.google.maps['GroundOverlay'] = groundOverlayConstructorSpy; @@ -294,8 +377,9 @@ export function createGroundOverlayConstructorSpy( } /** Creates a jasmine.SpyObj for a google.maps.KmlLayer */ -export function createKmlLayerSpy(options?: google.maps.KmlLayerOptions): - jasmine.SpyObj { +export function createKmlLayerSpy( + options?: google.maps.KmlLayerOptions, +): jasmine.SpyObj { const kmlLayerSpy = jasmine.createSpyObj('google.maps.KmlLayer', [ 'addListener', 'getDefaultViewport', @@ -312,12 +396,13 @@ export function createKmlLayerSpy(options?: google.maps.KmlLayerOptions): } /** Creates a jasmine.Spy to watch for the constructor of a google.maps.KmlLayer */ -export function createKmlLayerConstructorSpy(kmlLayerSpy: jasmine.SpyObj): - jasmine.Spy { - const kmlLayerConstructorSpy = - jasmine.createSpy('KmlLayer constructor', (_options: google.maps.KmlLayerOptions) => { - return kmlLayerSpy; - }); +export function createKmlLayerConstructorSpy( + kmlLayerSpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const kmlLayerConstructorSpy = jasmine.createSpy('KmlLayer constructor', function () { + return kmlLayerSpy; + }); const testingWindow: TestingWindow = window; if (testingWindow.google && testingWindow.google.maps) { testingWindow.google.maps['KmlLayer'] = kmlLayerConstructorSpy; @@ -332,8 +417,9 @@ export function createKmlLayerConstructorSpy(kmlLayerSpy: jasmine.SpyObj { +export function createTrafficLayerSpy( + options?: google.maps.TrafficLayerOptions, +): jasmine.SpyObj { const trafficLayerSpy = jasmine.createSpyObj('google.maps.TrafficLayer', [ 'setOptions', 'setMap', @@ -343,11 +429,12 @@ export function createTrafficLayerSpy(options?: google.maps.TrafficLayerOptions) /** Creates a jasmine.Spy to watch for the constructor of a google.maps.TrafficLayer */ export function createTrafficLayerConstructorSpy( - trafficLayerSpy: jasmine.SpyObj): jasmine.Spy { - const trafficLayerConstructorSpy = - jasmine.createSpy('TrafficLayer constructor', (_options: google.maps.TrafficLayerOptions) => { - return trafficLayerSpy; - }); + trafficLayerSpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const trafficLayerConstructorSpy = jasmine.createSpy('TrafficLayer constructor', function () { + return trafficLayerSpy; + }); const testingWindow: TestingWindow = window; if (testingWindow.google && testingWindow.google.maps) { testingWindow.google.maps['TrafficLayer'] = trafficLayerConstructorSpy; @@ -363,16 +450,16 @@ export function createTrafficLayerConstructorSpy( /** Creates a jasmine.SpyObj for a google.maps.TransitLayer */ export function createTransitLayerSpy(): jasmine.SpyObj { - const transitLayerSpy = jasmine.createSpyObj('google.maps.TransitLayer', [ - 'setMap', - ]); + const transitLayerSpy = jasmine.createSpyObj('google.maps.TransitLayer', ['setMap']); return transitLayerSpy; } /** Creates a jasmine.Spy to watch for the constructor of a google.maps.TransitLayer */ export function createTransitLayerConstructorSpy( - transitLayerSpy: jasmine.SpyObj): jasmine.Spy { - const transitLayerConstructorSpy = jasmine.createSpy('TransitLayer constructor', () => { + transitLayerSpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const transitLayerConstructorSpy = jasmine.createSpy('TransitLayer constructor', function () { return transitLayerSpy; }); const testingWindow: TestingWindow = window; @@ -390,16 +477,16 @@ export function createTransitLayerConstructorSpy( /** Creates a jasmine.SpyObj for a google.maps.BicyclingLayer */ export function createBicyclingLayerSpy(): jasmine.SpyObj { - const bicylingLayerSpy = jasmine.createSpyObj('google.maps.BicyclingLayer', [ - 'setMap', - ]); + const bicylingLayerSpy = jasmine.createSpyObj('google.maps.BicyclingLayer', ['setMap']); return bicylingLayerSpy; } /** Creates a jasmine.Spy to watch for the constructor of a google.maps.BicyclingLayer */ export function createBicyclingLayerConstructorSpy( - bicylingLayerSpy: jasmine.SpyObj): jasmine.Spy { - const bicylingLayerConstructorSpy = jasmine.createSpy('BicyclingLayer constructor', () => { + bicylingLayerSpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const bicylingLayerConstructorSpy = jasmine.createSpy('BicyclingLayer constructor', function () { return bicylingLayerSpy; }); const testingWindow: TestingWindow = window; @@ -417,30 +504,232 @@ export function createBicyclingLayerConstructorSpy( /** Creates a jasmine.SpyObj for a MarkerClusterer */ export function createMarkerClustererSpy(): jasmine.SpyObj { - const markerClustererSpy = jasmine.createSpyObj('MarkerClusterer', ['addListener', - 'addMarkers', 'fitMapToMarkers', 'getAverageCenter', 'getBatchSizeIE', - 'getCalculator', 'getClusterClass', 'getClusters', 'getEnableRetinalIcons', - 'getGridSize', 'getIgnoreHidden', 'getImageExtension', 'getImagePath', - 'getImageSizes', 'getMaxZoom', 'getMinimumClusterSize', 'getStyles', - 'getTitle', 'getTotalClusters', 'getTotalMarkers', 'getZIndex', 'getZoomOnClick', - 'removeMarkers', 'repaint', 'setAverageCenter', 'setBatchSizeIE', - 'setCalculator', 'setClusterClass', 'setEnableRetinalIcons', 'setGridSize', - 'setIgnoreHidden', 'setImageExtension', 'setImagePath', 'setImageSizes', 'setMap', - 'setMaxZoom', 'setMinimumClusterSize', 'setStyles', 'setTitle', 'setZIndex', + const markerClustererSpy = jasmine.createSpyObj('MarkerClusterer', [ + 'addListener', + 'addMarkers', + 'fitMapToMarkers', + 'getAverageCenter', + 'getBatchSizeIE', + 'getCalculator', + 'getClusterClass', + 'getClusters', + 'getEnableRetinaIcons', + 'getGridSize', + 'getIgnoreHidden', + 'getImageExtension', + 'getImagePath', + 'getImageSizes', + 'getMaxZoom', + 'getMinimumClusterSize', + 'getStyles', + 'getTitle', + 'getTotalClusters', + 'getTotalMarkers', + 'getZIndex', + 'getZoomOnClick', + 'removeMarkers', + 'repaint', + 'setAverageCenter', + 'setBatchSizeIE', + 'setCalculator', + 'setClusterClass', + 'setEnableRetinaIcons', + 'setGridSize', + 'setIgnoreHidden', + 'setImageExtension', + 'setImagePath', + 'setImageSizes', + 'setMap', + 'setMaxZoom', + 'setMinimumClusterSize', + 'setStyles', + 'setTitle', + 'setZIndex', 'setZoomOnClick', + 'setOptions', ]); - markerClustererSpy.addListener.and.returnValue({ remove: () => { } }); + markerClustererSpy.addListener.and.returnValue({remove: () => {}}); return markerClustererSpy; } /** Creates a jasmine.Spy to watch for the constructor of a MarkerClusterer */ export function createMarkerClustererConstructorSpy( - markerClustererSpy: jasmine.SpyObj): jasmine.Spy { - const markerClustererConstructorSpy = jasmine.createSpy('MarkerClusterer constructor', - () => { - return markerClustererSpy; + markerClustererSpy: jasmine.SpyObj, + apiLoaded = true, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const markerClustererConstructorSpy = jasmine.createSpy( + 'MarkerClusterer constructor', + function () { + return markerClustererSpy; + }, + ); + if (apiLoaded) { + const testingWindow: TestingWindow = window; + testingWindow['MarkerClusterer'] = markerClustererConstructorSpy; + } + return markerClustererConstructorSpy; +} + +/** Creates a jasmine.SpyObj for DirectionsRenderer */ +export function createDirectionsRendererSpy( + options: google.maps.DirectionsRendererOptions, +): jasmine.SpyObj { + const directionsRendererSpy = jasmine.createSpyObj('google.maps.DirectionsRenderer', [ + 'addListener', + 'getDirections', + 'getPanel', + 'getRouteIndex', + 'setDirections', + 'setMap', + 'setOptions', + ]); + directionsRendererSpy.addListener.and.returnValue({remove: () => {}}); + return directionsRendererSpy; +} + +/** Creates a jasmine.Spy to watch for the constructor of a DirectionsRenderer */ +export function createDirectionsRendererConstructorSpy( + directionsRendererSpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const directionsRendererConstructorSpy = jasmine.createSpy( + 'DirectionsRenderer constructor', + function () { + return directionsRendererSpy; + }, + ); + const testingWindow: TestingWindow = window; + if (testingWindow.google && testingWindow.google.maps) { + testingWindow.google.maps['DirectionsRenderer'] = directionsRendererConstructorSpy; + } else { + testingWindow.google = { + maps: { + 'DirectionsRenderer': directionsRendererConstructorSpy, + }, + }; + } + return directionsRendererConstructorSpy; +} + +/** Creates a jasmine.SpyObj for the DirectionsService */ +export function createDirectionsServiceSpy(): jasmine.SpyObj { + const directionsServiceSpy = jasmine.createSpyObj('google.maps.DirectionsService', ['route']); + return directionsServiceSpy; +} + +/** Creates a jasmine.Spy to watch for the constructor of the DirectionsService */ +export function createDirectionsServiceConstructorSpy( + directionsServiceSpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const directionsServiceConstructorSpy = jasmine.createSpy( + 'DirectionsService constructor', + function () { + return directionsServiceSpy; + }, + ); + const testingWindow: TestingWindow = window; + if (testingWindow.google && testingWindow.google.maps) { + testingWindow.google.maps['DirectionsService'] = directionsServiceConstructorSpy; + } else { + testingWindow.google = { + maps: { + 'DirectionsService': directionsServiceConstructorSpy, + }, + }; + } + return directionsServiceConstructorSpy; +} + +/** Creates a jasmine.SpyObj for a `google.maps.visualization.HeatmapLayer`. */ +export function createHeatmapLayerSpy(): jasmine.SpyObj { + const heatmapLayerSpy = jasmine.createSpyObj('google.maps.visualization.HeatmapLayer', [ + 'setMap', + 'setOptions', + 'setData', + 'getData', + ]); + return heatmapLayerSpy; +} + +/** + * Creates a jasmine.Spy to watch for the constructor + * of a `google.maps.visualization.HeatmapLayer`. + */ +export function createHeatmapLayerConstructorSpy( + heatmapLayerSpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const heatmapLayerConstructorSpy = jasmine.createSpy('HeatmapLayer constructor', function () { + return heatmapLayerSpy; }); const testingWindow: TestingWindow = window; - testingWindow['MarkerClusterer'] = markerClustererConstructorSpy; - return markerClustererConstructorSpy; + if (testingWindow.google && testingWindow.google.maps) { + if (!testingWindow.google.maps.visualization) { + testingWindow.google.maps.visualization = {}; + } + testingWindow.google.maps.visualization['HeatmapLayer'] = heatmapLayerConstructorSpy; + } else { + testingWindow.google = { + maps: { + visualization: { + 'HeatmapLayer': heatmapLayerConstructorSpy, + }, + }, + }; + } + return heatmapLayerConstructorSpy; +} + +/** Creates a jasmine.SpyObj for a google.maps.LatLng. */ +export function createLatLngSpy(): jasmine.SpyObj { + return jasmine.createSpyObj('google.maps.LatLng', ['equals', 'lat', 'lng']); +} + +/** Creates a jasmine.Spy to watch for the constructor of a google.maps.LatLng */ +export function createLatLngConstructorSpy( + latLngSpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const latLngConstructorSpy = jasmine.createSpy('LatLng constructor', function () { + return latLngSpy; + }); + const testingWindow: TestingWindow = window; + if (testingWindow.google && testingWindow.google.maps) { + testingWindow.google.maps['LatLng'] = latLngConstructorSpy; + } else { + testingWindow.google = { + maps: { + 'LatLng': latLngConstructorSpy, + }, + }; + } + return latLngConstructorSpy; +} + +/** Creates a jasmine.SpyObj for the Geocoder */ +export function createGeocoderSpy(): jasmine.SpyObj { + return jasmine.createSpyObj('google.maps.Geocoder', ['geocode']); +} + +/** Creates a jasmine.Spy to watch for the constructor of the Geocoder. */ +export function createGeocoderConstructorSpy( + geocoderSpy: jasmine.SpyObj, +): jasmine.Spy { + // The spy target function cannot be an arrow-function as this breaks when created through `new`. + const geocoderConstructorSpy = jasmine.createSpy('Geocoder constructor', function () { + return geocoderSpy; + }); + const testingWindow: TestingWindow = window; + if (testingWindow.google && testingWindow.google.maps) { + testingWindow.google.maps['Geocoder'] = geocoderConstructorSpy; + } else { + testingWindow.google = { + maps: { + 'Geocoder': geocoderConstructorSpy, + }, + }; + } + return geocoderConstructorSpy; } diff --git a/src/google-maps/tsconfig-tests.json b/src/google-maps/tsconfig-tests.json deleted file mode 100644 index 0b483e5010b7..000000000000 --- a/src/google-maps/tsconfig-tests.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "extends": "../bazel-tsconfig-build.json", - "compilerOptions": { - "baseUrl": ".", - "outDir": "../../dist/packages/google-maps", - "rootDir": ".", - "rootDirs": [ - ".", - "../../dist/packages/google-maps" - ], - "importHelpers": false, - "module": "umd", - "target": "es5", - "types": ["jasmine"], - "experimentalDecorators": true, - "emitDecoratorMetadata": true - }, - "include": [ - "**/*.spec.ts", - "../dev-mode-types.d.ts" - ], - "exclude": [ - "**/*.e2e.spec.ts" - ] -} diff --git a/src/material-date-fns-adapter/BUILD.bazel b/src/material-date-fns-adapter/BUILD.bazel new file mode 100644 index 000000000000..e4d51b13d47b --- /dev/null +++ b/src/material-date-fns-adapter/BUILD.bazel @@ -0,0 +1,44 @@ +load("//tools:defaults.bzl", "ng_module", "ng_package", "ng_test_library", "ng_web_test_suite") + +package(default_visibility = ["//visibility:public"]) + +ng_module( + name = "material-date-fns-adapter", + srcs = glob( + ["**/*.ts"], + exclude = ["**/*.spec.ts"], + ), + deps = [ + "//src:dev_mode_types", + "//src/material/core", + "@npm//@angular/core", + "@npm//date-fns", + ], +) + +ng_test_library( + name = "unit_test_sources", + srcs = glob( + ["**/*.spec.ts"], + exclude = ["**/*.e2e.spec.ts"], + ), + deps = [ + ":material-date-fns-adapter", + "//src/material/core", + "@npm//date-fns", + ], +) + +ng_web_test_suite( + name = "unit_tests", + deps = [ + ":unit_test_sources", + ], +) + +ng_package( + name = "npm_package", + srcs = ["package.json"], + tags = ["release-package"], + deps = [":material-date-fns-adapter"], +) diff --git a/src/material-date-fns-adapter/adapter/date-fns-adapter.spec.ts b/src/material-date-fns-adapter/adapter/date-fns-adapter.spec.ts new file mode 100644 index 000000000000..3dbe6a3dcfb7 --- /dev/null +++ b/src/material-date-fns-adapter/adapter/date-fns-adapter.spec.ts @@ -0,0 +1,493 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {TestBed, waitForAsync} from '@angular/core/testing'; +import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material/core'; +import {Locale} from 'date-fns'; +import {ja, enUS, da, de} from 'date-fns/locale'; +import {DateFnsModule} from './index'; + +const JAN = 0, + FEB = 1, + MAR = 2, + DEC = 11; + +describe('DateFnsAdapter', () => { + let adapter: DateAdapter; + + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [DateFnsModule], + }).compileComponents(); + + adapter = TestBed.inject(DateAdapter); + adapter.setLocale(enUS); + }), + ); + + it('should get year', () => { + expect(adapter.getYear(new Date(2017, JAN, 1))).toBe(2017); + }); + + it('should get month', () => { + expect(adapter.getMonth(new Date(2017, JAN, 1))).toBe(0); + }); + + it('should get date', () => { + expect(adapter.getDate(new Date(2017, JAN, 1))).toBe(1); + }); + + it('should get day of week', () => { + expect(adapter.getDayOfWeek(new Date(2017, JAN, 1))).toBe(0); + }); + + it('should get long month names', () => { + expect(adapter.getMonthNames('long')).toEqual([ + 'January', + 'February', + 'March', + 'April', + 'May', + 'June', + 'July', + 'August', + 'September', + 'October', + 'November', + 'December', + ]); + }); + + it('should get short month names', () => { + expect(adapter.getMonthNames('short')).toEqual([ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec', + ]); + }); + + it('should get narrow month names', () => { + expect(adapter.getMonthNames('narrow')).toEqual([ + 'J', + 'F', + 'M', + 'A', + 'M', + 'J', + 'J', + 'A', + 'S', + 'O', + 'N', + 'D', + ]); + }); + + it('should get month names in a different locale', () => { + adapter.setLocale(da); + + expect(adapter.getMonthNames('long')).toEqual([ + 'januar', + 'februar', + 'marts', + 'april', + 'maj', + 'juni', + 'juli', + 'august', + 'september', + 'oktober', + 'november', + 'december', + ]); + }); + + it('should get date names', () => { + expect(adapter.getDateNames()).toEqual([ + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + '10', + '11', + '12', + '13', + '14', + '15', + '16', + '17', + '18', + '19', + '20', + '21', + '22', + '23', + '24', + '25', + '26', + '27', + '28', + '29', + '30', + '31', + ]); + }); + + it('should get date names in a different locale', () => { + adapter.setLocale(ja); + if (typeof Intl !== 'undefined') { + expect(adapter.getDateNames()).toEqual([ + '1日', + '2日', + '3日', + '4日', + '5日', + '6日', + '7日', + '8日', + '9日', + '10日', + '11日', + '12日', + '13日', + '14日', + '15日', + '16日', + '17日', + '18日', + '19日', + '20日', + '21日', + '22日', + '23日', + '24日', + '25日', + '26日', + '27日', + '28日', + '29日', + '30日', + '31日', + ]); + } else { + expect(adapter.getDateNames()).toEqual([ + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + '10', + '11', + '12', + '13', + '14', + '15', + '16', + '17', + '18', + '19', + '20', + '21', + '22', + '23', + '24', + '25', + '26', + '27', + '28', + '29', + '30', + '31', + ]); + } + }); + + it('should get long day of week names', () => { + expect(adapter.getDayOfWeekNames('long')).toEqual([ + 'Sunday', + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday', + ]); + }); + + it('should get short day of week names', () => { + expect(adapter.getDayOfWeekNames('short')).toEqual([ + 'Sun', + 'Mon', + 'Tue', + 'Wed', + 'Thu', + 'Fri', + 'Sat', + ]); + }); + + it('should get narrow day of week names', () => { + expect(adapter.getDayOfWeekNames('narrow')).toEqual(['S', 'M', 'T', 'W', 'T', 'F', 'S']); + }); + + it('should get day of week names in a different locale', () => { + adapter.setLocale(ja); + + expect(adapter.getDayOfWeekNames('long')).toEqual([ + '日曜日', + '月曜日', + '火曜日', + '水曜日', + '木曜日', + '金曜日', + '土曜日', + ]); + }); + + it('should get year name', () => { + expect(adapter.getYearName(new Date(2017, JAN, 1))).toBe('2017'); + }); + + it('should get year name in a different locale', () => { + adapter.setLocale(ja); + expect(adapter.getYearName(new Date(2017, JAN, 1))).toBe('2017'); + }); + + it('should get first day of week', () => { + expect(adapter.getFirstDayOfWeek()).toBe(0); + }); + + it('should not create Date with month over/under-flow', () => { + expect(() => adapter.createDate(2017, 12, 1)).toThrow(); + expect(() => adapter.createDate(2017, -1, 1)).toThrow(); + }); + + it('should not create Date with date over/under-flow', () => { + expect(() => adapter.createDate(2017, JAN, 32)).toThrow(); + expect(() => adapter.createDate(2017, JAN, 0)).toThrow(); + }); + + it("should get today's date", () => { + expect(adapter.sameDate(adapter.today(), new Date())) + .withContext("should be equal to today's date") + .toBe(true); + }); + + it('should parse string according to given format', () => { + expect(adapter.parse('1/2/2017', 'M/d/yyyy')).toEqual(new Date(2017, JAN, 2)); + expect(adapter.parse('1/2/2017', 'd/M/yyyy')).toEqual(new Date(2017, FEB, 1)); + }); + + it('should parse string according to first matching format', () => { + expect(adapter.parse('1/2/2017', ['M/d/yyyy', 'yyyy/d/M'])).toEqual(new Date(2017, JAN, 2)); + expect(adapter.parse('1/2/2017', ['yyyy/d/M', 'M/d/yyyy'])).toEqual(new Date(2017, JAN, 2)); + }); + + it('should throw if parse formats are an empty array', () => { + expect(() => adapter.parse('1/2/2017', [])).toThrowError('Formats array must not be empty.'); + }); + + it('should parse number', () => { + const timestamp = new Date().getTime(); + expect(adapter.parse(timestamp, 'MM/dd/yyyy')!.getTime()).toEqual(timestamp); + }); + + it('should parse Date', () => { + let date = new Date(2017, JAN, 1); + expect(adapter.parse(date, 'MM/dd/yyyy')).toEqual(date); + }); + + it('should parse empty string as null', () => { + expect(adapter.parse('', 'MM/dd/yyyy')).toBeNull(); + }); + + it('should parse based on the specified locale', () => { + adapter.setLocale(de); + expect(adapter.parse('02.01.2017', 'P')).toEqual(new Date(2017, JAN, 2)); + }); + + it('should parse invalid value as invalid', () => { + let d = adapter.parse('hello', 'MM/dd/yyyy'); + expect(d).not.toBeNull(); + expect(adapter.isDateInstance(d)).toBe(true); + expect(adapter.isValid(d as Date)) + .withContext('Expected to parse as "invalid date" object') + .toBe(false); + }); + + it('should format date according to given format', () => { + expect(adapter.format(new Date(2017, JAN, 2), 'MM/dd/yyyy')).toEqual('01/02/2017'); + }); + + it('should format with a different locale', () => { + let date = adapter.format(new Date(2017, JAN, 2), 'PP'); + + expect(stripDirectionalityCharacters(date)).toEqual('Jan 2, 2017'); + adapter.setLocale(da); + + date = adapter.format(new Date(2017, JAN, 2), 'PP'); + expect(stripDirectionalityCharacters(date)).toEqual('2. jan. 2017'); + }); + + it('should throw when attempting to format invalid date', () => { + expect(() => adapter.format(new Date(NaN), 'MM/dd/yyyy')).toThrowError( + /DateFnsAdapter: Cannot format invalid date\./, + ); + }); + + it('should add years', () => { + expect(adapter.addCalendarYears(new Date(2017, JAN, 1), 1)).toEqual(new Date(2018, JAN, 1)); + expect(adapter.addCalendarYears(new Date(2017, JAN, 1), -1)).toEqual(new Date(2016, JAN, 1)); + }); + + it('should respect leap years when adding years', () => { + expect(adapter.addCalendarYears(new Date(2016, FEB, 29), 1)).toEqual(new Date(2017, FEB, 28)); + expect(adapter.addCalendarYears(new Date(2016, FEB, 29), -1)).toEqual(new Date(2015, FEB, 28)); + }); + + it('should add months', () => { + expect(adapter.addCalendarMonths(new Date(2017, JAN, 1), 1)).toEqual(new Date(2017, FEB, 1)); + expect(adapter.addCalendarMonths(new Date(2017, JAN, 1), -1)).toEqual(new Date(2016, DEC, 1)); + }); + + it('should respect month length differences when adding months', () => { + expect(adapter.addCalendarMonths(new Date(2017, JAN, 31), 1)).toEqual(new Date(2017, FEB, 28)); + expect(adapter.addCalendarMonths(new Date(2017, MAR, 31), -1)).toEqual(new Date(2017, FEB, 28)); + }); + + it('should add days', () => { + expect(adapter.addCalendarDays(new Date(2017, JAN, 1), 1)).toEqual(new Date(2017, JAN, 2)); + expect(adapter.addCalendarDays(new Date(2017, JAN, 1), -1)).toEqual(new Date(2016, DEC, 31)); + }); + + it('should clone', () => { + let date = new Date(2017, JAN, 1); + let clone = adapter.clone(date); + + expect(clone).not.toBe(date); + expect(clone.getTime()).toEqual(date.getTime()); + }); + + it('should compare dates', () => { + expect(adapter.compareDate(new Date(2017, JAN, 1), new Date(2017, JAN, 2))).toBeLessThan(0); + expect(adapter.compareDate(new Date(2017, JAN, 1), new Date(2017, FEB, 1))).toBeLessThan(0); + expect(adapter.compareDate(new Date(2017, JAN, 1), new Date(2018, JAN, 1))).toBeLessThan(0); + expect(adapter.compareDate(new Date(2017, JAN, 1), new Date(2017, JAN, 1))).toBe(0); + expect(adapter.compareDate(new Date(2018, JAN, 1), new Date(2017, JAN, 1))).toBeGreaterThan(0); + expect(adapter.compareDate(new Date(2017, FEB, 1), new Date(2017, JAN, 1))).toBeGreaterThan(0); + expect(adapter.compareDate(new Date(2017, JAN, 2), new Date(2017, JAN, 1))).toBeGreaterThan(0); + }); + + it('should clamp date at lower bound', () => { + expect( + adapter.clampDate(new Date(2017, JAN, 1), new Date(2018, JAN, 1), new Date(2019, JAN, 1)), + ).toEqual(new Date(2018, JAN, 1)); + }); + + it('should clamp date at upper bound', () => { + expect( + adapter.clampDate(new Date(2020, JAN, 1), new Date(2018, JAN, 1), new Date(2019, JAN, 1)), + ).toEqual(new Date(2019, JAN, 1)); + }); + + it('should clamp date already within bounds', () => { + expect( + adapter.clampDate(new Date(2018, FEB, 1), new Date(2018, JAN, 1), new Date(2019, JAN, 1)), + ).toEqual(new Date(2018, FEB, 1)); + }); + + it('should count today as a valid date instance', () => { + let d = new Date(); + expect(adapter.isValid(d)).toBe(true); + expect(adapter.isDateInstance(d)).toBe(true); + }); + + it('should count an invalid date as an invalid date instance', () => { + let d = new Date(NaN); + expect(adapter.isValid(d)).toBe(false); + expect(adapter.isDateInstance(d)).toBe(true); + }); + + it('should count a string as not a date instance', () => { + let d = '1/1/2017'; + expect(adapter.isDateInstance(d)).toBe(false); + }); + + it('should create valid dates from valid ISO strings', () => { + assertValidDate(adapter, adapter.deserialize('1985-04-12T23:20:50.52Z'), true); + assertValidDate(adapter, adapter.deserialize('1996-12-19T16:39:57-08:00'), true); + assertValidDate(adapter, adapter.deserialize('1937-01-01T12:00:27.87+00:20'), true); + assertValidDate(adapter, adapter.deserialize('1990-13-31T23:59:00Z'), false); + assertValidDate(adapter, adapter.deserialize('1/1/2017'), false); + expect(adapter.deserialize('')).toBeNull(); + expect(adapter.deserialize(null)).toBeNull(); + assertValidDate(adapter, adapter.deserialize(new Date()), true); + assertValidDate(adapter, adapter.deserialize(new Date(NaN)), false); + assertValidDate(adapter, adapter.deserialize(new Date()), true); + assertValidDate(adapter, adapter.deserialize(new Date('Not valid')), false); + }); + + it('should create invalid date', () => { + assertValidDate(adapter, adapter.invalid(), false); + }); +}); + +describe('DateFnsAdapter with MAT_DATE_LOCALE override', () => { + let adapter: DateAdapter; + + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [DateFnsModule], + providers: [{provide: MAT_DATE_LOCALE, useValue: da}], + }).compileComponents(); + + adapter = TestBed.inject(DateAdapter); + }), + ); + + it('should take the default locale id from the MAT_DATE_LOCALE injection token', () => { + const date = adapter.format(new Date(2017, JAN, 2), 'PP'); + expect(stripDirectionalityCharacters(date)).toEqual('2. jan. 2017'); + }); +}); + +function stripDirectionalityCharacters(str: string) { + return str.replace(/[\u200e\u200f]/g, ''); +} + +function assertValidDate(adapter: DateAdapter, d: Date | null, valid: boolean) { + expect(adapter.isDateInstance(d)) + .not.withContext(`Expected ${d} to be a date instance`) + .toBeNull(); + expect(adapter.isValid(d!)) + .withContext( + `Expected ${d} to be ${valid ? 'valid' : 'invalid'},` + + ` but was ${valid ? 'invalid' : 'valid'}`, + ) + .toBe(valid); +} diff --git a/src/material-date-fns-adapter/adapter/date-fns-adapter.ts b/src/material-date-fns-adapter/adapter/date-fns-adapter.ts new file mode 100644 index 000000000000..840d946abd45 --- /dev/null +++ b/src/material-date-fns-adapter/adapter/date-fns-adapter.ts @@ -0,0 +1,241 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {Inject, Injectable, Optional} from '@angular/core'; +import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material/core'; +import { + Locale, + getMonth, + getYear, + getDate, + getDay, + getDaysInMonth, + formatISO, + addYears, + addMonths, + addDays, + isValid, + isDate, + format, + parseISO, + parse, +} from 'date-fns'; + +/** Creates an array and fills it with values. */ +function range(length: number, valueFunction: (index: number) => T): T[] { + const valuesArray = Array(length); + for (let i = 0; i < length; i++) { + valuesArray[i] = valueFunction(i); + } + return valuesArray; +} + +// date-fns doesn't have a way to read/print month names or days of the week directly, +// so we get them by formatting a date with a format that produces the desired month/day. +const MONTH_FORMATS = { + long: 'LLLL', + short: 'LLL', + narrow: 'LLLLL', +}; + +const DAY_OF_WEEK_FORMATS = { + long: 'EEEE', + short: 'EEE', + narrow: 'EEEEE', +}; + +/** Adds date-fns support to Angular Material. */ +@Injectable() +export class DateFnsAdapter extends DateAdapter { + constructor(@Optional() @Inject(MAT_DATE_LOCALE) matDateLocale: {}) { + super(); + this.setLocale(matDateLocale); + } + + getYear(date: Date): number { + return getYear(date); + } + + getMonth(date: Date): number { + return getMonth(date); + } + + getDate(date: Date): number { + return getDate(date); + } + + getDayOfWeek(date: Date): number { + return getDay(date); + } + + getMonthNames(style: 'long' | 'short' | 'narrow'): string[] { + const pattern = MONTH_FORMATS[style]; + return range(12, i => this.format(new Date(2017, i, 1), pattern)); + } + + getDateNames(): string[] { + const dtf = + typeof Intl !== 'undefined' + ? new Intl.DateTimeFormat(this.locale.code, { + day: 'numeric', + timeZone: 'utc', + }) + : null; + + return range(31, i => { + if (dtf) { + // date-fns doesn't appear to support this functionality. + // Fall back to `Intl` on supported browsers. + const date = new Date(); + date.setUTCFullYear(2017, 0, i + 1); + date.setUTCHours(0, 0, 0, 0); + return dtf.format(date).replace(/[\u200e\u200f]/g, ''); + } + + return i + ''; + }); + } + + getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[] { + const pattern = DAY_OF_WEEK_FORMATS[style]; + return range(7, i => this.format(new Date(2017, 0, i + 1), pattern)); + } + + getYearName(date: Date): string { + return this.format(date, 'y'); + } + + getFirstDayOfWeek(): number { + return this.locale.options?.weekStartsOn ?? 0; + } + + getNumDaysInMonth(date: Date): number { + return getDaysInMonth(date); + } + + clone(date: Date): Date { + return new Date(date.getTime()); + } + + createDate(year: number, month: number, date: number): Date { + if (typeof ngDevMode === 'undefined' || ngDevMode) { + // Check for invalid month and date (except upper bound on date which we have to check after + // creating the Date). + if (month < 0 || month > 11) { + throw Error(`Invalid month index "${month}". Month index has to be between 0 and 11.`); + } + + if (date < 1) { + throw Error(`Invalid date "${date}". Date has to be greater than 0.`); + } + } + + // Passing the year to the constructor causes year numbers <100 to be converted to 19xx. + // To work around this we use `setFullYear` and `setHours` instead. + const result = new Date(); + result.setFullYear(year, month, date); + result.setHours(0, 0, 0, 0); + + // Check that the date wasn't above the upper bound for the month, causing the month to overflow + if (result.getMonth() != month && (typeof ngDevMode === 'undefined' || ngDevMode)) { + throw Error(`Invalid date "${date}" for month with index "${month}".`); + } + + return result; + } + + today(): Date { + return new Date(); + } + + parse(value: any, parseFormat: string | string[]): Date | null { + if (typeof value == 'string' && value.length > 0) { + const iso8601Date = parseISO(value); + + if (this.isValid(iso8601Date)) { + return iso8601Date; + } + + const formats = Array.isArray(parseFormat) ? parseFormat : [parseFormat]; + + if (!parseFormat.length) { + throw Error('Formats array must not be empty.'); + } + + for (const currentFormat of formats) { + const fromFormat = parse(value, currentFormat, new Date(), {locale: this.locale}); + + if (this.isValid(fromFormat)) { + return fromFormat; + } + } + + return this.invalid(); + } else if (typeof value === 'number') { + return new Date(value); + } else if (value instanceof Date) { + return this.clone(value); + } + + return null; + } + + format(date: Date, displayFormat: string): string { + if (!this.isValid(date)) { + throw Error('DateFnsAdapter: Cannot format invalid date.'); + } + + return format(date, displayFormat, {locale: this.locale}); + } + + addCalendarYears(date: Date, years: number): Date { + return addYears(date, years); + } + + addCalendarMonths(date: Date, months: number): Date { + return addMonths(date, months); + } + + addCalendarDays(date: Date, days: number): Date { + return addDays(date, days); + } + + toIso8601(date: Date): string { + return formatISO(date, {representation: 'date'}); + } + + /** + * Returns the given value if given a valid Date or null. Deserializes valid ISO 8601 strings + * (https://www.ietf.org/rfc/rfc3339.txt) into valid Dates and empty string into null. Returns an + * invalid date for all other values. + */ + override deserialize(value: any): Date | null { + if (typeof value === 'string') { + if (!value) { + return null; + } + const date = parseISO(value); + if (this.isValid(date)) { + return date; + } + } + return super.deserialize(value); + } + + isDateInstance(obj: any): boolean { + return isDate(obj); + } + + isValid(date: Date): boolean { + return isValid(date); + } + + invalid(): Date { + return new Date(NaN); + } +} diff --git a/src/material-date-fns-adapter/adapter/date-fns-formats.ts b/src/material-date-fns-adapter/adapter/date-fns-formats.ts new file mode 100644 index 000000000000..e067ad83a9c8 --- /dev/null +++ b/src/material-date-fns-adapter/adapter/date-fns-formats.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {MatDateFormats} from '@angular/material/core'; + +export const MAT_DATE_FNS_FORMATS: MatDateFormats = { + parse: { + dateInput: 'P', + }, + display: { + dateInput: 'P', + monthYearLabel: 'LLL uuuu', + dateA11yLabel: 'PP', + monthYearA11yLabel: 'LLLL uuuu', + }, +}; diff --git a/src/material-date-fns-adapter/adapter/index.ts b/src/material-date-fns-adapter/adapter/index.ts new file mode 100644 index 000000000000..53705b2a1ce0 --- /dev/null +++ b/src/material-date-fns-adapter/adapter/index.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {NgModule} from '@angular/core'; +import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core'; +import {DateFnsAdapter} from './date-fns-adapter'; +import {MAT_DATE_FNS_FORMATS} from './date-fns-formats'; + +export * from './date-fns-adapter'; +export * from './date-fns-formats'; + +@NgModule({ + providers: [ + { + provide: DateAdapter, + useClass: DateFnsAdapter, + deps: [MAT_DATE_LOCALE], + }, + ], +}) +export class DateFnsModule {} + +@NgModule({ + imports: [DateFnsModule], + providers: [{provide: MAT_DATE_FORMATS, useValue: MAT_DATE_FNS_FORMATS}], +}) +export class MatDateFnsModule {} diff --git a/src/material-date-fns-adapter/index.ts b/src/material-date-fns-adapter/index.ts new file mode 100644 index 000000000000..676ca90f1ffa --- /dev/null +++ b/src/material-date-fns-adapter/index.ts @@ -0,0 +1,9 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +export * from './public-api'; diff --git a/src/material-date-fns-adapter/package.json b/src/material-date-fns-adapter/package.json new file mode 100644 index 000000000000..153e2343ad9c --- /dev/null +++ b/src/material-date-fns-adapter/package.json @@ -0,0 +1,30 @@ +{ + "name": "@angular/material-date-fns-adapter", + "version": "0.0.0-PLACEHOLDER", + "description": "Angular Material date-fns Adapter", + "repository": { + "type": "git", + "url": "https://github.com/angular/components.git" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/angular/components/issues" + }, + "homepage": "https://github.com/angular/components#readme", + "peerDependencies": { + "@angular/material": "0.0.0-PLACEHOLDER", + "@angular/core": "0.0.0-NG", + "date-fns": "^2.23.0" + }, + "dependencies": { + "tslib": "0.0.0-TSLIB" + }, + "ng-update": { + "packageGroup": [ + "@angular/material", + "@angular/cdk", + "@angular/material-date-fns-adapter" + ] + }, + "sideEffects": false +} diff --git a/src/material-date-fns-adapter/public-api.ts b/src/material-date-fns-adapter/public-api.ts new file mode 100644 index 000000000000..c9246d3a07b8 --- /dev/null +++ b/src/material-date-fns-adapter/public-api.ts @@ -0,0 +1,9 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +export * from './adapter/index'; diff --git a/src/material-date-fns-adapter/tsconfig.json b/src/material-date-fns-adapter/tsconfig.json new file mode 100644 index 000000000000..a8acc041c9ca --- /dev/null +++ b/src/material-date-fns-adapter/tsconfig.json @@ -0,0 +1,14 @@ +// Configuration for IDEs only. +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "rootDir": "..", + "baseUrl": ".", + "paths": { + "@angular/cdk/*": ["../cdk/*"], + "@angular/material/*": ["../material/*"], + "@angular/material": ["../material/public-api.ts"] + } + }, + "include": ["./**/*.ts", "../dev-mode-types.d.ts"] +} diff --git a/src/material-experimental/BUILD.bazel b/src/material-experimental/BUILD.bazel index de089e86d564..fabb2dc7df0a 100644 --- a/src/material-experimental/BUILD.bazel +++ b/src/material-experimental/BUILD.bazel @@ -4,33 +4,43 @@ load( "MATERIAL_EXPERIMENTAL_TARGETS", "MATERIAL_EXPERIMENTAL_TESTING_TARGETS", ) -load("//tools:defaults.bzl", "ng_package", "ts_library") +load("//tools:defaults.bzl", "ng_package", "sass_library", "ts_library") package(default_visibility = ["//visibility:public"]) -exports_files(["mdc_require_config.js"]) - ts_library( name = "material-experimental", srcs = glob( ["*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material-experimental", deps = ["@npm//@angular/core"], ) -ng_package( - name = "npm_package", - srcs = ["package.json"], - data = MATERIAL_EXPERIMENTAL_SCSS_LIBS + [ +sass_library( + name = "theming_scss_lib", + srcs = MATERIAL_EXPERIMENTAL_SCSS_LIBS + [ "//src/material-experimental/mdc-color", "//src/material-experimental/mdc-density", "//src/material-experimental/mdc-helpers", "//src/material-experimental/mdc-theming", "//src/material-experimental/mdc-typography", ], - entry_point = ":public-api.ts", +) + +sass_library( + name = "theming_bundle", + srcs = ["_index.scss"], + deps = [":theming_scss_lib"], +) + +ng_package( + name = "npm_package", + srcs = ["package.json"], + data = [ + ":theming_bundle", + ":theming_scss_lib", + ], tags = ["release-package"], deps = MATERIAL_EXPERIMENTAL_TARGETS + MATERIAL_EXPERIMENTAL_TESTING_TARGETS, ) diff --git a/src/material-experimental/README.md b/src/material-experimental/README.md index cf40fae63223..3f08dd3ffbf2 100644 --- a/src/material-experimental/README.md +++ b/src/material-experimental/README.md @@ -29,7 +29,7 @@ component by following these steps: }, ... ``` - + 3. Import the `NgModule` for the component you want to use. For example, the checkbox: ```ts import {MatCheckboxModule} from '@angular/material-experimental/mdc-checkbox'; @@ -41,8 +41,8 @@ component by following these steps: export class MyModule {} ``` -4. Add use the components just as you would the normal Angular Material components. For example, -the checkbox: +4. Use the components just as you would the normal Angular Material components. For example, +the checkbox: ```html Check me ``` @@ -52,18 +52,23 @@ mixins except that they are suffixed with `-mdc`. Some experimental components m be included in the pre-built CSS mixin and will need to be explicitly included. ```scss - @import '~@angular/material/theming'; - @import '~@angular/material-experimental/mdc-theming/all-theme'; - - $my-primary: mat-palette($mat-indigo); - $my-accent: mat-palette($mat-pink, A200, A100, A400); - $my-theme: mat-light-theme(( + @use '@angular/material' as mat; + @use '@angular/material-experimental' as mat-experimental; + + $my-primary: mat.define-palette(mat.$indigo-palette); + $my-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400); + $my-theme: mat.define-light-theme(( color: ( - primary: $my-primary, + primary: $my-primary, accent: $my-accent - ) + ), + // Using `define-mdc-typography-config` rather than `define-typography-config` generates a + // typography config directly from the official Material Design styles. This includes using + // `rem`-based measurements rather than `px`-based ones as the spec recommends. + typography: mat-experimental.define-mdc-typography-config(), + // The density level to use in this theme, defaults to 0 if not specified. + density: 0 )); - @include angular-material-mdc-theme($my-theme); - @include angular-material-mdc-typography(); + @include mat-experimental.all-mdc-component-themes($my-theme); ``` diff --git a/src/material-experimental/_index.scss b/src/material-experimental/_index.scss new file mode 100644 index 000000000000..c7571ca82471 --- /dev/null +++ b/src/material-experimental/_index.scss @@ -0,0 +1,73 @@ +// Structural +@forward './mdc-helpers/focus-indicators' as mdc-* show mdc-strong-focus-indicators; +@forward './mdc-core/elevation' as mdc-* show mdc-elevation, mdc-overridable-elevation; + +// Theme bundles +@forward './mdc-theming/all-theme' show all-mdc-component-themes; +@forward './mdc-color/all-color' show all-mdc-component-colors; +@forward './mdc-typography/all-typography' show all-mdc-component-typographies, + define-mdc-typography-config; +@forward './mdc-density/all-density' show all-mdc-component-densities; + +// Component themes +@forward './column-resize/column-resize-theme' as column-resize-* show column-resize-color, + column-resize-typography, column-resize-density, column-resize-theme; +@forward './popover-edit/popover-edit-theme' as popover-edit-* show popover-edit-color, + popover-edit-typography, popover-edit-density, popover-edit-theme; + +// MDC-related themes +@forward './mdc-core/core-theme' as mdc-core-* show mdc-core-theme, mdc-core-color, + mdc-core-density, mdc-core-typography; +@forward './mdc-helpers/focus-indicators-theme' as mdc-strong-focus-indicators-* show + mdc-strong-focus-indicators-color, mdc-strong-focus-indicators-theme; +@forward './mdc-core/option/option-theme' as mdc-option-* show mdc-option-color, + mdc-option-typography, mdc-option-density, mdc-option-theme; +@forward './mdc-core/option/optgroup-theme' as mdc-optgroup-* show mdc-optgroup-color, + mdc-optgroup-typography, mdc-optgroup-density, mdc-optgroup-theme; +@forward './mdc-autocomplete/autocomplete-theme' as mdc-autocomplete-* show mdc-autocomplete-color, + mdc-autocomplete-typography, mdc-autocomplete-density, mdc-autocomplete-theme; +@forward './mdc-button/button-theme' as mdc-button-* show mdc-button-color, mdc-button-typography, + mdc-button-density, mdc-button-theme; +@forward './mdc-button/fab-theme' as mdc-fab-* show mdc-fab-color, mdc-fab-typography, + mdc-fab-density, mdc-fab-theme; +@forward './mdc-button/icon-button-theme' as mdc-icon-button-* show mdc-icon-button-color, + mdc-icon-button-typography, mdc-icon-button-density, mdc-icon-button-theme; +@forward './mdc-card/card-theme' as mdc-card-* show mdc-card-color, mdc-card-typography, + mdc-card-density, mdc-card-theme; +@forward './mdc-checkbox/checkbox-theme' as mdc-checkbox-* show mdc-checkbox-color, + mdc-checkbox-typography, mdc-checkbox-density, mdc-checkbox-theme; +@forward './mdc-chips/chips-theme' as mdc-chips-* show mdc-chips-color, mdc-chips-typography, + mdc-chips-density, mdc-chips-theme; +@forward './mdc-dialog/dialog-theme' as mdc-dialog-* show mdc-dialog-color, mdc-dialog-typography, + mdc-dialog-density, mdc-dialog-theme; +@forward './mdc-form-field/form-field-theme' as mdc-form-field-* show mdc-form-field-color, + mdc-form-field-typography, mdc-form-field-density, mdc-form-field-theme; +@forward './mdc-input/input-theme' as mdc-input-* show mdc-input-color, mdc-input-typography, + mdc-input-density, mdc-input-theme; +@forward './mdc-list/list-theme' as mdc-list-* show mdc-list-color, mdc-list-typography, + mdc-list-density, mdc-list-theme; +@forward './mdc-menu/menu-theme' as mdc-menu-* show mdc-menu-color, mdc-menu-typography, + mdc-menu-density, mdc-menu-theme; +@forward './mdc-paginator/paginator-theme' as mdc-paginator-* show mdc-paginator-color, + mdc-paginator-typography, mdc-paginator-density, mdc-paginator-theme; +@forward './mdc-progress-bar/progress-bar-theme' as mdc-progress-bar-* show mdc-progress-bar-color, + mdc-progress-bar-typography, mdc-progress-bar-density, mdc-progress-bar-theme; +@forward './mdc-progress-spinner/progress-spinner-theme' as mdc-progress-spinner-* show + mdc-progress-spinner-color, mdc-progress-spinner-typography, mdc-progress-spinner-density, + mdc-progress-spinner-theme; +@forward './mdc-radio/radio-theme' as mdc-radio-* show mdc-radio-color, mdc-radio-typography, + mdc-radio-density, mdc-radio-theme; +@forward './mdc-select/select-theme' as mdc-select-* show mdc-select-color, mdc-select-typography, + mdc-select-density, mdc-select-theme; +@forward './mdc-slide-toggle/slide-toggle-theme' as mdc-slide-toggle-* show mdc-slide-toggle-color, + mdc-slide-toggle-typography, mdc-slide-toggle-density, mdc-slide-toggle-theme; +@forward './mdc-slider/slider-theme' as mdc-slider-* show mdc-slider-color, + mdc-slider-typography, mdc-slider-density, mdc-slider-theme; +@forward './mdc-snack-bar/snack-bar-theme' as mdc-snack-bar-* show mdc-snack-bar-color, + mdc-snack-bar-typography, mdc-snack-bar-density, mdc-snack-bar-theme; +@forward './mdc-table/table-theme' as mdc-table-* show mdc-table-color, mdc-table-typography, + mdc-table-density, mdc-table-theme; +@forward './mdc-tabs/tabs-theme' as mdc-tabs-* show mdc-tabs-color, mdc-tabs-typography, + mdc-tabs-density, mdc-tabs-theme; +@forward './mdc-tooltip/tooltip-theme' as mdc-tooltip-* show mdc-tooltip-color, + mdc-tooltip-typography, mdc-tooltip-density, mdc-tooltip-theme; diff --git a/src/material-experimental/column-resize/BUILD.bazel b/src/material-experimental/column-resize/BUILD.bazel index 8824945e5bc5..b08e4db707dc 100644 --- a/src/material-experimental/column-resize/BUILD.bazel +++ b/src/material-experimental/column-resize/BUILD.bazel @@ -1,5 +1,4 @@ -load("@io_bazel_rules_sass//:defs.bzl", "sass_library") -load("//tools:defaults.bzl", "ng_module", "ng_test_library", "ng_web_test_suite") +load("//tools:defaults.bzl", "ng_module", "ng_test_library", "ng_web_test_suite", "sass_library") package(default_visibility = ["//visibility:public"]) @@ -9,7 +8,6 @@ ng_module( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material-experimental/column-resize", deps = [ "//src/cdk-experimental/column-resize", "//src/cdk/overlay", diff --git a/src/material-experimental/column-resize/_column-resize-theme.scss b/src/material-experimental/column-resize/_column-resize-theme.scss new file mode 100644 index 000000000000..10a798c2660e --- /dev/null +++ b/src/material-experimental/column-resize/_column-resize-theme.scss @@ -0,0 +1,161 @@ +@use 'sass:map'; +@use '../../material/core/style/variables'; +@use '../../material/core/style/vendor-prefixes'; +@use '../../material/core/theming/theming'; + +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $primary: map.get($config, primary); + $foreground: map.get($config, foreground); + + $non-resizable-hover-divider: theming.get-color-from-palette($foreground, divider); + $resizable-hover-divider: theming.get-color-from-palette($primary, 600); + $resizable-active-divider: theming.get-color-from-palette($primary, 600); + + // TODO: these styles don't really belong in the `color` part of the theme. + // We should figure out a better place for them. + // Required for resizing to work properly. + .mat-column-resize-table.cdk-column-resize-with-resized-column { + table-layout: fixed; + } + + .mat-column-resize-flex { + .mat-header-cell, + .mat-mdc-header-cell, + .mat-cell, + .mat-mdc-cell { + box-sizing: border-box; + min-width: 32px; + } + } + + .mat-header-cell, + .mat-mdc-header-cell { + position: relative; + } + + .mat-resizable { + box-sizing: border-box; + } + + .mat-header-cell:not(.mat-resizable)::after, + .mat-mdc-header-cell:not(.mat-resizable)::after, + .mat-resizable-handle { + background: transparent; + bottom: 0; + position: absolute; + top: 0; + transition: background variables.$swift-ease-in-duration + variables.$swift-ease-in-timing-function; + width: 1px; + } + + .mat-header-cell:not(.mat-resizable)::after, + .mat-mdc-header-cell:not(.mat-resizable)::after { + content: ''; + } + + .mat-header-cell:not(.mat-resizable)::after, + .mat-mdc-header-cell:not(.mat-resizable)::after, + .mat-resizable-handle { + right: 0; + } + + .mat-header-row.cdk-column-resize-hover-or-active, + .mat-mdc-header-row.cdk-column-resize-hover-or-active { + .mat-header-cell, + .mat-mdc-header-cell { + border-right: none; + } + + .mat-header-cell:not(.mat-resizable)::after, + .mat-mdc-header-cell:not(.mat-resizable)::after { + background: $non-resizable-hover-divider; + } + + .mat-resizable-handle { + background: $resizable-hover-divider; + } + } + + [dir='rtl'] { + .mat-header-cell:not(.mat-resizable)::after, + .mat-mdc-header-cell:not(.mat-resizable)::after, + .mat-resizable-handle { + left: 0; + right: auto; + } + + .mat-header-row.cdk-column-resize-hover-or-active, + .mat-mdc-header-row.cdk-column-resize-hover-or-active { + .mat-header-cell, + .mat-mdc-header-cell { + border-left: none; + } + } + } + + .mat-resizable.cdk-resizable-overlay-thumb-active > .mat-resizable-handle { + opacity: 0; + transition: none; + } + + .mat-resizable-handle:focus, + .mat-header-row.cdk-column-resize-hover-or-active .mat-resizable-handle:focus, + .mat-mdc-header-row.cdk-column-resize-hover-or-active .mat-resizable-handle:focus { + background: $resizable-active-divider; + outline: none; + } + + .mat-column-resize-overlay-thumb { + background: transparent; + cursor: col-resize; + height: 100%; + transition: background variables.$swift-ease-in-duration + variables.$swift-ease-in-timing-function; + @include vendor-prefixes.user-select(none); + width: 100%; + + &:active { + background: linear-gradient(90deg, + transparent, transparent 7px, + $resizable-active-divider 7px, $resizable-active-divider 9px, + transparent 9px, transparent); + will-change: transform; + + .mat-column-resize-overlay-thumb-top { + background: linear-gradient(90deg, + transparent, transparent 4px, + $resizable-active-divider 4px, $resizable-active-divider 12px, + transparent 12px, transparent); + } + } + } + + .mat-column-resize-overlay-thumb-top { + width: 100%; + } +} + +@mixin typography($config-or-theme) {} + +@mixin density($config-or-theme) {} + +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-column-resize') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); + + @if $color != null { + @include color($color); + } + @if $density != null { + @include density($density); + } + @if $typography != null { + @include typography($typography); + } + } +} diff --git a/src/material-experimental/column-resize/_column-resize.import.scss b/src/material-experimental/column-resize/_column-resize.import.scss new file mode 100644 index 000000000000..58505a9c8f24 --- /dev/null +++ b/src/material-experimental/column-resize/_column-resize.import.scss @@ -0,0 +1,9 @@ +@forward '../../material/core/style/variables.import'; +@forward '../../material/core/theming/theming.import'; +@forward '../../material/core/style/vendor-prefixes.import'; +@forward 'column-resize-theme' as mat-column-resize-*; + +@import '../../material/core/style/variables'; +@import '../../material/core/style/vendor-prefixes'; +@import '../../material/core/theming/palette'; +@import '../../material/core/theming/theming'; diff --git a/src/material-experimental/column-resize/_column-resize.scss b/src/material-experimental/column-resize/_column-resize.scss deleted file mode 100644 index 4cb7f2359c6c..000000000000 --- a/src/material-experimental/column-resize/_column-resize.scss +++ /dev/null @@ -1,121 +0,0 @@ -@import '../../material/core/style/variables'; -@import '../../material/core/style/vendor-prefixes'; -@import '../../material/core/theming/palette'; -@import '../../material/core/theming/theming'; - -@mixin mat-column-resize-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $primary: map-get($config, primary); - $foreground: map-get($config, foreground); - - $non-resizable-hover-divider: mat-color($foreground, divider); - $resizable-hover-divider: mat-color($primary, 200); - $resizable-active-divider: mat-color($primary, 500); - - // Required for resizing to work properly. - .mat-column-resize-table.cdk-column-resize-with-resized-column { - table-layout: fixed; - } - - .mat-column-resize-flex { - .mat-header-cell, - .mat-cell { - box-sizing: border-box; - min-width: 32px; - } - } - - .mat-header-cell { - position: relative; - } - - .mat-resizable { - box-sizing: border-box; - } - - .mat-header-cell:not(.mat-resizable)::after, - .mat-resizable-handle { - background: transparent; - bottom: 0; - position: absolute; - top: 0; - transition: background $swift-ease-in-duration $swift-ease-in-timing-function; - width: 1px; - } - - .mat-header-cell:not(.mat-resizable)::after { - content: ''; - } - - .mat-header-cell:not(.mat-resizable)::after, - .mat-resizable-handle { - right: 0; - } - - [dir='rtl'] .mat-header-cell:not(.mat-resizable)::after, - [dir='rtl'] .mat-resizable-handle { - left: 0; - right: auto; - } - - .mat-header-row.cdk-column-resize-hover-or-active { - .mat-header-cell:not(.mat-resizable)::after { - background: $non-resizable-hover-divider; - } - - .mat-resizable-handle { - background: $resizable-hover-divider; - } - } - - .mat-resizable.cdk-resizable-overlay-thumb-active > .mat-resizable-handle { - opacity: 0; - transition: none; - } - - .mat-resizable-handle:focus, - .mat-header-row.cdk-column-resize-hover-or-active .mat-resizable-handle:focus { - background: $resizable-active-divider; - outline: none; - } - - .mat-column-resize-overlay-thumb { - background: transparent; - cursor: col-resize; - height: 100%; - transition: background $swift-ease-in-duration $swift-ease-in-timing-function; - @include user-select(none); - width: 100%; - - &:active { - background: linear-gradient(90deg, - transparent, transparent 7px, - $resizable-active-divider, $resizable-active-divider 1px, - transparent 8px, transparent); - will-change: transform; - } - } -} - -@mixin mat-column-resize-typography($config-or-theme) {} - -@mixin mat-column-resize-density($config-or-theme) {} - -@mixin mat-column-resize-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-column-resize') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); - - @if $color != null { - @include mat-column-resize-color($color); - } - @if $density != null { - @include mat-column-resize-density($density); - } - @if $typography != null { - @include mat-column-resize-typography($typography); - } - } -} diff --git a/src/material-experimental/column-resize/column-resize-directives/column-resize-flex.ts b/src/material-experimental/column-resize/column-resize-directives/column-resize-flex.ts index 7a6665ae56b2..c61d8c7ef04d 100644 --- a/src/material-experimental/column-resize/column-resize-directives/column-resize-flex.ts +++ b/src/material-experimental/column-resize/column-resize-directives/column-resize-flex.ts @@ -23,18 +23,16 @@ import {AbstractMatColumnResize, FLEX_HOST_BINDINGS, FLEX_PROVIDERS} from './com @Directive({ selector: 'mat-table[columnResize]', host: FLEX_HOST_BINDINGS, - providers: [ - ...FLEX_PROVIDERS, - {provide: ColumnResize, useExisting: MatColumnResizeFlex}, - ], + providers: [...FLEX_PROVIDERS, {provide: ColumnResize, useExisting: MatColumnResizeFlex}], }) export class MatColumnResizeFlex extends AbstractMatColumnResize { constructor( - readonly columnResizeNotifier: ColumnResizeNotifier, - readonly elementRef: ElementRef, - protected readonly eventDispatcher: HeaderRowEventDispatcher, - protected readonly ngZone: NgZone, - protected readonly notifier: ColumnResizeNotifierSource) { + readonly columnResizeNotifier: ColumnResizeNotifier, + readonly elementRef: ElementRef, + protected readonly eventDispatcher: HeaderRowEventDispatcher, + protected readonly ngZone: NgZone, + protected readonly notifier: ColumnResizeNotifierSource, + ) { super(); } } diff --git a/src/material-experimental/column-resize/column-resize-directives/column-resize.ts b/src/material-experimental/column-resize/column-resize-directives/column-resize.ts index f6014c9334f6..cf8fded62545 100644 --- a/src/material-experimental/column-resize/column-resize-directives/column-resize.ts +++ b/src/material-experimental/column-resize/column-resize-directives/column-resize.ts @@ -23,18 +23,16 @@ import {AbstractMatColumnResize, TABLE_HOST_BINDINGS, TABLE_PROVIDERS} from './c @Directive({ selector: 'table[mat-table][columnResize]', host: TABLE_HOST_BINDINGS, - providers: [ - ...TABLE_PROVIDERS, - {provide: ColumnResize, useExisting: MatColumnResize}, - ], + providers: [...TABLE_PROVIDERS, {provide: ColumnResize, useExisting: MatColumnResize}], }) export class MatColumnResize extends AbstractMatColumnResize { constructor( - readonly columnResizeNotifier: ColumnResizeNotifier, - readonly elementRef: ElementRef, - protected readonly eventDispatcher: HeaderRowEventDispatcher, - protected readonly ngZone: NgZone, - protected readonly notifier: ColumnResizeNotifierSource) { + readonly columnResizeNotifier: ColumnResizeNotifier, + readonly elementRef: ElementRef, + protected readonly eventDispatcher: HeaderRowEventDispatcher, + protected readonly ngZone: NgZone, + protected readonly notifier: ColumnResizeNotifierSource, + ) { super(); } } diff --git a/src/material-experimental/column-resize/column-resize-directives/default-enabled-column-resize-flex.ts b/src/material-experimental/column-resize/column-resize-directives/default-enabled-column-resize-flex.ts index 7d11cb0c8afe..696d203e1128 100644 --- a/src/material-experimental/column-resize/column-resize-directives/default-enabled-column-resize-flex.ts +++ b/src/material-experimental/column-resize/column-resize-directives/default-enabled-column-resize-flex.ts @@ -30,11 +30,12 @@ import {AbstractMatColumnResize, FLEX_HOST_BINDINGS, FLEX_PROVIDERS} from './com }) export class MatDefaultEnabledColumnResizeFlex extends AbstractMatColumnResize { constructor( - readonly columnResizeNotifier: ColumnResizeNotifier, - readonly elementRef: ElementRef, - protected readonly eventDispatcher: HeaderRowEventDispatcher, - protected readonly ngZone: NgZone, - protected readonly notifier: ColumnResizeNotifierSource) { + readonly columnResizeNotifier: ColumnResizeNotifier, + readonly elementRef: ElementRef, + protected readonly eventDispatcher: HeaderRowEventDispatcher, + protected readonly ngZone: NgZone, + protected readonly notifier: ColumnResizeNotifierSource, + ) { super(); } } diff --git a/src/material-experimental/column-resize/column-resize-directives/default-enabled-column-resize.ts b/src/material-experimental/column-resize/column-resize-directives/default-enabled-column-resize.ts index aca54c3439e9..7b56b39024d2 100644 --- a/src/material-experimental/column-resize/column-resize-directives/default-enabled-column-resize.ts +++ b/src/material-experimental/column-resize/column-resize-directives/default-enabled-column-resize.ts @@ -30,11 +30,12 @@ import {AbstractMatColumnResize, TABLE_HOST_BINDINGS, TABLE_PROVIDERS} from './c }) export class MatDefaultEnabledColumnResize extends AbstractMatColumnResize { constructor( - readonly columnResizeNotifier: ColumnResizeNotifier, - readonly elementRef: ElementRef, - protected readonly eventDispatcher: HeaderRowEventDispatcher, - protected readonly ngZone: NgZone, - protected readonly notifier: ColumnResizeNotifierSource) { + readonly columnResizeNotifier: ColumnResizeNotifier, + readonly elementRef: ElementRef, + protected readonly eventDispatcher: HeaderRowEventDispatcher, + protected readonly ngZone: NgZone, + protected readonly notifier: ColumnResizeNotifierSource, + ) { super(); } } diff --git a/src/material-experimental/column-resize/column-resize-module.ts b/src/material-experimental/column-resize/column-resize-module.ts index 95cb1ed94066..55add11dcc99 100644 --- a/src/material-experimental/column-resize/column-resize-module.ts +++ b/src/material-experimental/column-resize/column-resize-module.ts @@ -12,32 +12,21 @@ import {OverlayModule} from '@angular/cdk/overlay'; import {MatColumnResize} from './column-resize-directives/column-resize'; import {MatColumnResizeFlex} from './column-resize-directives/column-resize-flex'; -import { - MatDefaultEnabledColumnResize -} from './column-resize-directives/default-enabled-column-resize'; -import { - MatDefaultEnabledColumnResizeFlex -} from './column-resize-directives/default-enabled-column-resize-flex'; +import {MatDefaultEnabledColumnResize} from './column-resize-directives/default-enabled-column-resize'; +import {MatDefaultEnabledColumnResizeFlex} from './column-resize-directives/default-enabled-column-resize-flex'; import {MatDefaultResizable} from './resizable-directives/default-enabled-resizable'; import {MatResizable} from './resizable-directives/resizable'; import {MatColumnResizeOverlayHandle} from './overlay-handle'; -const ENTRY_COMMON_COMPONENTS = [ - MatColumnResizeOverlayHandle, -]; +const ENTRY_COMMON_COMPONENTS = [MatColumnResizeOverlayHandle]; @NgModule({ declarations: ENTRY_COMMON_COMPONENTS, exports: ENTRY_COMMON_COMPONENTS, - entryComponents: ENTRY_COMMON_COMPONENTS, }) export class MatColumnResizeCommonModule {} -const IMPORTS = [ - MatCommonModule, - OverlayModule, - MatColumnResizeCommonModule, -]; +const IMPORTS = [MatCommonModule, OverlayModule, MatColumnResizeCommonModule]; @NgModule({ imports: IMPORTS, @@ -46,25 +35,13 @@ const IMPORTS = [ MatDefaultEnabledColumnResizeFlex, MatDefaultResizable, ], - exports: [ - MatDefaultEnabledColumnResize, - MatDefaultEnabledColumnResizeFlex, - MatDefaultResizable, - ], + exports: [MatDefaultEnabledColumnResize, MatDefaultEnabledColumnResizeFlex, MatDefaultResizable], }) export class MatDefaultEnabledColumnResizeModule {} @NgModule({ imports: IMPORTS, - declarations: [ - MatColumnResize, - MatColumnResizeFlex, - MatResizable, - ], - exports: [ - MatColumnResize, - MatColumnResizeFlex, - MatResizable, - ], + declarations: [MatColumnResize, MatColumnResizeFlex, MatResizable], + exports: [MatColumnResize, MatColumnResizeFlex, MatResizable], }) export class MatColumnResizeModule {} diff --git a/src/material-experimental/column-resize/column-resize.spec.ts b/src/material-experimental/column-resize/column-resize.spec.ts index 0d54e02bc864..62fc437b5fd9 100644 --- a/src/material-experimental/column-resize/column-resize.spec.ts +++ b/src/material-experimental/column-resize/column-resize.spec.ts @@ -1,17 +1,9 @@ -import { - Component, - Directive, - ElementRef, - Type, - ViewChild, - ChangeDetectionStrategy, -} from '@angular/core'; -import {ComponentFixture, TestBed, fakeAsync, flushMicrotasks, inject} from '@angular/core/testing'; +import {Component, Directive, ElementRef, ViewChild, ChangeDetectionStrategy} from '@angular/core'; +import {ComponentFixture, TestBed, fakeAsync, flushMicrotasks} from '@angular/core/testing'; import {BidiModule} from '@angular/cdk/bidi'; import {DataSource} from '@angular/cdk/collections'; -import {dispatchKeyboardEvent} from '@angular/cdk/testing/private'; +import {dispatchKeyboardEvent} from '../../cdk/testing/private'; import {ESCAPE} from '@angular/cdk/keycodes'; -import {OverlayContainer} from '@angular/cdk/overlay'; import {MatTableModule} from '@angular/material/table'; import {BehaviorSubject} from 'rxjs'; @@ -43,8 +35,9 @@ function getOptInDirectiveStrings() { } function getTableTemplate(defaultEnabled: boolean) { - const directives = defaultEnabled ? - getDefaultEnabledDirectiveStrings() : getOptInDirectiveStrings(); + const directives = defaultEnabled + ? getDefaultEnabledDirectiveStrings() + : getOptInDirectiveStrings(); return ` - `)); + `), + ); const fixture = TestBed.createComponent(IconFromSvgName); fixture.componentInstance.iconName = 'fido'; @@ -847,7 +870,9 @@ describe('MatIcon', () => { })); it('should prepend the current path to attributes with `url()` references', fakeAsync(() => { - iconRegistry.addSvgIconLiteral('fido', trustHtml(` + iconRegistry.addSvgIconLiteral( + 'fido', + trustHtml(` @@ -855,7 +880,8 @@ describe('MatIcon', () => { - `)); + `), + ); const fixture = TestBed.createComponent(IconFromSvgName); fixture.componentInstance.iconName = 'fido'; @@ -870,7 +896,9 @@ describe('MatIcon', () => { })); it('should use latest path when prefixing the `url()` references', fakeAsync(() => { - iconRegistry.addSvgIconLiteral('fido', trustHtml(` + iconRegistry.addSvgIconLiteral( + 'fido', + trustHtml(` @@ -878,7 +906,8 @@ describe('MatIcon', () => { - `)); + `), + ); let fixture = TestBed.createComponent(IconFromSvgName); fixture.componentInstance.iconName = 'fido'; @@ -895,13 +924,16 @@ describe('MatIcon', () => { fixture.detectChanges(); circle = fixture.nativeElement.querySelector('mat-icon svg circle'); - expect(circle.getAttribute('filter')) - .toMatch(/^url\(['"]?\/\$another-fake-path#blur['"]?\)$/); + expect(circle.getAttribute('filter')).toMatch( + /^url\(['"]?\/\$another-fake-path#blur['"]?\)$/, + ); tick(); })); it('should update the `url()` references when the path changes', fakeAsync(() => { - iconRegistry.addSvgIconLiteral('fido', trustHtml(` + iconRegistry.addSvgIconLiteral( + 'fido', + trustHtml(` @@ -909,7 +941,8 @@ describe('MatIcon', () => { - `)); + `), + ); const fixture = TestBed.createComponent(IconFromSvgName); fixture.componentInstance.iconName = 'fido'; @@ -926,7 +959,6 @@ describe('MatIcon', () => { expect(circle.getAttribute('filter')).toMatch(/^url\(['"]?\/\$different-path#blur['"]?\)$/); })); - }); describe('custom fonts', () => { @@ -941,20 +973,35 @@ describe('MatIcon', () => { testComponent.fontSet = 'f1'; testComponent.fontIcon = 'house'; fixture.detectChanges(); - expect(sortedClassNames(matIconElement)) - .toEqual(['font1', 'house', 'mat-icon', 'mat-icon-no-color', 'notranslate']); + expect(sortedClassNames(matIconElement)).toEqual([ + 'font1', + 'house', + 'mat-icon', + 'mat-icon-no-color', + 'notranslate', + ]); testComponent.fontSet = 'f2'; testComponent.fontIcon = 'igloo'; fixture.detectChanges(); - expect(sortedClassNames(matIconElement)) - .toEqual(['f2', 'igloo', 'mat-icon', 'mat-icon-no-color', 'notranslate']); + expect(sortedClassNames(matIconElement)).toEqual([ + 'f2', + 'igloo', + 'mat-icon', + 'mat-icon-no-color', + 'notranslate', + ]); testComponent.fontSet = 'f3'; testComponent.fontIcon = 'tent'; fixture.detectChanges(); - expect(sortedClassNames(matIconElement)) - .toEqual(['f3', 'mat-icon', 'mat-icon-no-color', 'notranslate', 'tent']); + expect(sortedClassNames(matIconElement)).toEqual([ + 'f3', + 'mat-icon', + 'mat-icon-no-color', + 'notranslate', + 'tent', + ]); }); it('should handle values with extraneous spaces being passed in to `fontSet`', () => { @@ -966,16 +1013,24 @@ describe('MatIcon', () => { fixture.detectChanges(); }).not.toThrow(); - expect(sortedClassNames(matIconElement)) - .toEqual(['font', 'mat-icon', 'mat-icon-no-color', 'notranslate']); + expect(sortedClassNames(matIconElement)).toEqual([ + 'font', + 'mat-icon', + 'mat-icon-no-color', + 'notranslate', + ]); expect(() => { fixture.componentInstance.fontSet = ' changed'; fixture.detectChanges(); }).not.toThrow(); - expect(sortedClassNames(matIconElement)) - .toEqual(['changed', 'mat-icon', 'mat-icon-no-color', 'notranslate']); + expect(sortedClassNames(matIconElement)).toEqual([ + 'changed', + 'mat-icon', + 'mat-icon-no-color', + 'notranslate', + ]); }); it('should handle values with extraneous spaces being passed in to `fontIcon`', () => { @@ -987,18 +1042,138 @@ describe('MatIcon', () => { fixture.detectChanges(); }).not.toThrow(); - expect(sortedClassNames(matIconElement)) - .toEqual(['font', 'mat-icon', 'mat-icon-no-color', 'material-icons', 'notranslate']); + expect(sortedClassNames(matIconElement)).toEqual([ + 'font', + 'mat-icon', + 'mat-icon-no-color', + 'material-icons', + 'notranslate', + ]); expect(() => { fixture.componentInstance.fontIcon = ' changed'; fixture.detectChanges(); }).not.toThrow(); - expect(sortedClassNames(matIconElement)) - .toEqual(['changed', 'mat-icon', 'mat-icon-no-color', 'material-icons', 'notranslate']); + expect(sortedClassNames(matIconElement)).toEqual([ + 'changed', + 'mat-icon', + 'mat-icon-no-color', + 'material-icons', + 'notranslate', + ]); }); + }); + describe('Icons resolved through a resolver function', () => { + it('should resolve icons through a resolver function', fakeAsync(() => { + iconRegistry.addSvgIconResolver(name => { + if (name === 'fluffy') { + return trustUrl('cat.svg'); + } else if (name === 'fido') { + return trustUrl('dog.svg'); + } else if (name === 'felix') { + return {url: trustUrl('auth-cat.svg'), options: {withCredentials: true}}; + } + return null; + }); + + const fixture = TestBed.createComponent(IconFromSvgName); + let svgElement: SVGElement; + let testRequest: TestRequest; + const testComponent = fixture.componentInstance; + const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); + + testComponent.iconName = 'fido'; + fixture.detectChanges(); + http.expectOne('dog.svg').flush(FAKE_SVGS.dog); + svgElement = verifyAndGetSingleSvgChild(iconElement); + verifyPathChildElement(svgElement, 'woof'); + + // Change the icon, and the SVG element should be replaced. + testComponent.iconName = 'fluffy'; + fixture.detectChanges(); + http.expectOne('cat.svg').flush(FAKE_SVGS.cat); + svgElement = verifyAndGetSingleSvgChild(iconElement); + verifyPathChildElement(svgElement, 'meow'); + + // Using an icon from a previously loaded URL should not cause another HTTP request. + testComponent.iconName = 'fido'; + fixture.detectChanges(); + http.expectNone('dog.svg'); + svgElement = verifyAndGetSingleSvgChild(iconElement); + verifyPathChildElement(svgElement, 'woof'); + + // Change icon to one that needs credentials during fetch. + testComponent.iconName = 'felix'; + fixture.detectChanges(); + testRequest = http.expectOne('auth-cat.svg'); + expect(testRequest.request.withCredentials).toBeTrue(); + testRequest.flush(FAKE_SVGS.cat); + svgElement = verifyAndGetSingleSvgChild(iconElement); + verifyPathChildElement(svgElement, 'meow'); + + // Assert that a registered icon can be looked-up by url. + iconRegistry.getSvgIconFromUrl(trustUrl('cat.svg')).subscribe(element => { + verifyPathChildElement(element, 'meow'); + }); + + tick(); + })); + + it('should fall back to second resolver if the first one returned null', fakeAsync(() => { + iconRegistry + .addSvgIconResolver(() => null) + .addSvgIconResolver(name => (name === 'fido' ? trustUrl('dog.svg') : null)); + + const fixture = TestBed.createComponent(IconFromSvgName); + const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); + + fixture.componentInstance.iconName = 'fido'; + fixture.detectChanges(); + http.expectOne('dog.svg').flush(FAKE_SVGS.dog); + verifyPathChildElement(verifyAndGetSingleSvgChild(iconElement), 'woof'); + tick(); + })); + + it('should be able to set the viewBox when resolving an icon with a function', fakeAsync(() => { + iconRegistry.addSvgIconResolver(name => { + if (name === 'fluffy') { + return {url: trustUrl('cat.svg'), options: {viewBox: '0 0 27 27'}}; + } else if (name === 'fido') { + return {url: trustUrl('dog.svg'), options: {viewBox: '0 0 43 43'}}; + } + return null; + }); + + const fixture = TestBed.createComponent(IconFromSvgName); + let svgElement: SVGElement; + const testComponent = fixture.componentInstance; + const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); + + testComponent.iconName = 'fido'; + fixture.detectChanges(); + http.expectOne('dog.svg').flush(FAKE_SVGS.dog); + svgElement = verifyAndGetSingleSvgChild(iconElement); + expect(svgElement.getAttribute('viewBox')).toBe('0 0 43 43'); + + // Change the icon, and the SVG element should be replaced. + testComponent.iconName = 'fluffy'; + fixture.detectChanges(); + http.expectOne('cat.svg').flush(FAKE_SVGS.cat); + svgElement = verifyAndGetSingleSvgChild(iconElement); + expect(svgElement.getAttribute('viewBox')).toBe('0 0 27 27'); + })); + + it('should throw an error when the resolver returns an untrusted URL', () => { + iconRegistry.addSvgIconResolver(() => 'not-trusted.svg'); + + expect(() => { + const fixture = TestBed.createComponent(IconFromSvgName); + fixture.componentInstance.iconName = 'fluffy'; + fixture.detectChanges(); + }).toThrowError(/unsafe value used in a resource URL context/); + }); }); it('should handle assigning an icon through the setter', fakeAsync(() => { @@ -1028,19 +1203,20 @@ describe('MatIcon', () => { } }); - describe('MatIcon without HttpClientModule', () => { let iconRegistry: MatIconRegistry; let sanitizer: DomSanitizer; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatIconModule], - declarations: [IconFromSvgName], - }); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatIconModule], + declarations: [IconFromSvgName], + }); - TestBed.compileComponents(); - })); + TestBed.compileComponents(); + }), + ); beforeEach(inject([MatIconRegistry, DomSanitizer], (mir: MatIconRegistry, ds: DomSanitizer) => { iconRegistry = mir; @@ -1061,7 +1237,6 @@ describe('MatIcon without HttpClientModule', () => { }); }); - @Component({template: `{{iconName}}`}) class IconWithLigature { iconName = ''; diff --git a/src/material/icon/icon.ts b/src/material/icon/icon.ts index d4b699301392..7fd9f00cdecc 100644 --- a/src/material/icon/icon.ts +++ b/src/material/icon/icon.ts @@ -23,19 +23,19 @@ import { OnInit, ViewEncapsulation, } from '@angular/core'; -import {CanColor, CanColorCtor, mixinColor} from '@angular/material/core'; +import {CanColor, mixinColor} from '@angular/material/core'; import {Subscription} from 'rxjs'; import {take} from 'rxjs/operators'; import {MatIconRegistry} from './icon-registry'; - // Boilerplate for applying mixins to MatIcon. /** @docs-private */ -class MatIconBase { - constructor(public _elementRef: ElementRef) {} -} -const _MatIconMixinBase: CanColorCtor & typeof MatIconBase = mixinColor(MatIconBase); +const _MatIconBase = mixinColor( + class { + constructor(public _elementRef: ElementRef) {} + }, +); /** * Injection token used to provide the current location to `MatIcon`. @@ -44,7 +44,7 @@ const _MatIconMixinBase: CanColorCtor & typeof MatIconBase = mixinColor(MatIconB */ export const MAT_ICON_LOCATION = new InjectionToken('mat-icon-location', { providedIn: 'root', - factory: MAT_ICON_LOCATION_FACTORY + factory: MAT_ICON_LOCATION_FACTORY, }); /** @@ -63,11 +63,10 @@ export function MAT_ICON_LOCATION_FACTORY(): MatIconLocation { return { // Note that this needs to be a function, rather than a property, because Angular // will only resolve it once, but we want the current path on each call. - getPathname: () => _location ? (_location.pathname + _location.search) : '' + getPathname: () => (_location ? _location.pathname + _location.search : ''), }; } - /** SVG attributes that accept a FuncIRI (e.g. `url()`). */ const funcIriAttributes = [ 'clip-path', @@ -81,7 +80,7 @@ const funcIriAttributes = [ 'marker-mid', 'marker-end', 'mask', - 'stroke' + 'stroke', ]; /** Selector that can be used to find all elements that are using a `FuncIRI`. */ @@ -135,9 +134,7 @@ const funcIriPattern = /^url\(['"]?#(.*?)['"]?\)$/; encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) -export class MatIcon extends _MatIconMixinBase implements OnInit, AfterViewChecked, CanColor, - OnDestroy { - +export class MatIcon extends _MatIconBase implements OnInit, AfterViewChecked, CanColor, OnDestroy { /** * Whether the icon should be inlined, automatically sizing the icon to match the font size of * the element the icon is contained in. @@ -146,14 +143,16 @@ export class MatIcon extends _MatIconMixinBase implements OnInit, AfterViewCheck get inline(): boolean { return this._inline; } - set inline(inline: boolean) { + set inline(inline: BooleanInput) { this._inline = coerceBooleanProperty(inline); } private _inline: boolean = false; /** Name of the icon in the SVG icon set. */ @Input() - get svgIcon(): string { return this._svgIcon; } + get svgIcon(): string { + return this._svgIcon; + } set svgIcon(value: string) { if (value !== this._svgIcon) { if (value) { @@ -168,7 +167,9 @@ export class MatIcon extends _MatIconMixinBase implements OnInit, AfterViewCheck /** Font set that the icon is a part of. */ @Input() - get fontSet(): string { return this._fontSet; } + get fontSet(): string { + return this._fontSet; + } set fontSet(value: string) { const newValue = this._cleanupFontValue(value); @@ -181,7 +182,9 @@ export class MatIcon extends _MatIconMixinBase implements OnInit, AfterViewCheck /** Name of an icon within a font set. */ @Input() - get fontIcon(): string { return this._fontIcon; } + get fontIcon(): string { + return this._fontIcon; + } set fontIcon(value: string) { const newValue = this._cleanupFontValue(value); @@ -202,16 +205,18 @@ export class MatIcon extends _MatIconMixinBase implements OnInit, AfterViewCheck private _previousPath?: string; /** Keeps track of the elements and attributes that we've prefixed with the current path. */ - private _elementsWithExternalReferences?: Map; + private _elementsWithExternalReferences?: Map; /** Subscription to the current in-progress SVG icon request. */ private _currentIconFetch = Subscription.EMPTY; constructor( - elementRef: ElementRef, private _iconRegistry: MatIconRegistry, - @Attribute('aria-hidden') ariaHidden: string, - @Inject(MAT_ICON_LOCATION) private _location: MatIconLocation, - private readonly _errorHandler: ErrorHandler) { + elementRef: ElementRef, + private _iconRegistry: MatIconRegistry, + @Attribute('aria-hidden') ariaHidden: string, + @Inject(MAT_ICON_LOCATION) private _location: MatIconLocation, + private readonly _errorHandler: ErrorHandler, + ) { super(elementRef); // If the user has not explicitly set aria-hidden, mark the icon as hidden, as this is @@ -240,9 +245,12 @@ export class MatIcon extends _MatIconMixinBase implements OnInit, AfterViewCheck } const parts = iconName.split(':'); switch (parts.length) { - case 1: return ['', parts[0]]; // Use default namespace. - case 2: return <[string, string]>parts; - default: throw Error(`Invalid icon name: "${iconName}"`); // TODO: add an ngDevMode check + case 1: + return ['', parts[0]]; // Use default namespace. + case 2: + return <[string, string]>parts; + default: + throw Error(`Invalid icon name: "${iconName}"`); // TODO: add an ngDevMode check } } @@ -320,7 +328,7 @@ export class MatIcon extends _MatIconMixinBase implements OnInit, AfterViewCheck // 1 corresponds to Node.ELEMENT_NODE. We remove all non-element nodes in order to get rid // of any loose text nodes, as well as any SVG elements in order to remove any old icons. if (child.nodeType !== 1 || child.nodeName.toLowerCase() === 'svg') { - layoutElement.removeChild(child); + child.remove(); } } } @@ -331,9 +339,9 @@ export class MatIcon extends _MatIconMixinBase implements OnInit, AfterViewCheck } const elem: HTMLElement = this._elementRef.nativeElement; - const fontSetClass = this.fontSet ? - this._iconRegistry.classNameForFontAlias(this.fontSet) : - this._iconRegistry.getDefaultFontSetClass(); + const fontSetClass = this.fontSet + ? this._iconRegistry.classNameForFontAlias(this.fontSet) + : this._iconRegistry.getDefaultFontSetClass(); if (fontSetClass != this._previousFontSetClass) { if (this._previousFontSetClass) { @@ -388,8 +396,8 @@ export class MatIcon extends _MatIconMixinBase implements OnInit, AfterViewCheck */ private _cacheChildrenWithExternalReferences(element: SVGElement) { const elementsWithFuncIri = element.querySelectorAll(funcIriAttributeSelector); - const elements = this._elementsWithExternalReferences = - this._elementsWithExternalReferences || new Map(); + const elements = (this._elementsWithExternalReferences = + this._elementsWithExternalReferences || new Map()); for (let i = 0; i < elementsWithFuncIri.length; i++) { funcIriAttributes.forEach(attr => { @@ -412,7 +420,7 @@ export class MatIcon extends _MatIconMixinBase implements OnInit, AfterViewCheck } /** Sets a new SVG icon with a particular name. */ - private _updateSvgIcon(rawName: string|undefined) { + private _updateSvgIcon(rawName: string | undefined) { this._svgNamespace = null; this._svgName = null; this._currentIconFetch.unsubscribe(); @@ -428,14 +436,16 @@ export class MatIcon extends _MatIconMixinBase implements OnInit, AfterViewCheck this._svgName = iconName; } - this._currentIconFetch = this._iconRegistry.getNamedSvgIcon(iconName, namespace) - .pipe(take(1)) - .subscribe(svg => this._setSvgElement(svg), (err: Error) => { + this._currentIconFetch = this._iconRegistry + .getNamedSvgIcon(iconName, namespace) + .pipe(take(1)) + .subscribe( + svg => this._setSvgElement(svg), + (err: Error) => { const errorMessage = `Error retrieving icon ${namespace}:${iconName}! ${err.message}`; this._errorHandler.handleError(new Error(errorMessage)); - }); + }, + ); } } - - static ngAcceptInputType_inline: BooleanInput; } diff --git a/src/material/icon/public-api.ts b/src/material/icon/public-api.ts index 7714c30fff55..3552a9e19361 100644 --- a/src/material/icon/public-api.ts +++ b/src/material/icon/public-api.ts @@ -9,4 +9,3 @@ export * from './icon-module'; export * from './icon'; export * from './icon-registry'; - diff --git a/src/material/icon/testing/BUILD.bazel b/src/material/icon/testing/BUILD.bazel index 2101e7593af7..db67b5115418 100644 --- a/src/material/icon/testing/BUILD.bazel +++ b/src/material/icon/testing/BUILD.bazel @@ -8,7 +8,6 @@ ng_module( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material/icon/testing", deps = [ "//src/cdk/coercion", "//src/cdk/testing", diff --git a/src/material/icon/testing/fake-icon-registry.ts b/src/material/icon/testing/fake-icon-registry.ts index e6cfd68f33b7..1204c52febb1 100644 --- a/src/material/icon/testing/fake-icon-registry.ts +++ b/src/material/icon/testing/fake-icon-registry.ts @@ -10,11 +10,9 @@ import {Injectable, NgModule, OnDestroy} from '@angular/core'; import {MatIconRegistry} from '@angular/material/icon'; import {Observable, of as observableOf} from 'rxjs'; -// tslint:disable:no-any Impossible to tell param types. type PublicApi = { - [K in keyof T]: T[K] extends (...x: any[]) => T ? (...x: any[]) => PublicApi : T[K] + [K in keyof T]: T[K] extends (...x: any[]) => T ? (...x: any[]) => PublicApi : T[K]; }; -// tslint:enable:no-any /** * A null icon registry that must be imported to allow disabling of custom @@ -78,7 +76,11 @@ export class FakeMatIconRegistry implements PublicApi, OnDestro return this; } - ngOnDestroy() { } + addSvgIconResolver(): this { + return this; + } + + ngOnDestroy() {} private _generateEmptySvg(): SVGElement { const emptySvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); @@ -95,7 +97,6 @@ export class FakeMatIconRegistry implements PublicApi, OnDestro /** Import this module in tests to install the null icon registry. */ @NgModule({ - providers: [{provide: MatIconRegistry, useClass: FakeMatIconRegistry}] + providers: [{provide: MatIconRegistry, useClass: FakeMatIconRegistry}], }) -export class MatIconTestingModule { -} +export class MatIconTestingModule {} diff --git a/src/material/icon/testing/icon-harness-filters.ts b/src/material/icon/testing/icon-harness-filters.ts index 761514875564..849ec9d7f052 100644 --- a/src/material/icon/testing/icon-harness-filters.ts +++ b/src/material/icon/testing/icon-harness-filters.ts @@ -9,7 +9,10 @@ import {BaseHarnessFilters} from '@angular/cdk/testing'; /** Possible types of icons. */ -export const enum IconType {SVG, FONT} +export const enum IconType { + SVG, + FONT, +} /** A set of criteria that can be used to filter a list of `MatIconHarness` instances. */ export interface IconHarnessFilters extends BaseHarnessFilters { diff --git a/src/material/icon/testing/icon-harness.ts b/src/material/icon/testing/icon-harness.ts index 497ca65e4a8a..eb3a90fc4b18 100644 --- a/src/material/icon/testing/icon-harness.ts +++ b/src/material/icon/testing/icon-harness.ts @@ -9,7 +9,6 @@ import {ComponentHarness, HarnessPredicate} from '@angular/cdk/testing'; import {IconHarnessFilters, IconType} from './icon-harness-filters'; - /** Harness for interacting with a standard mat-icon in tests. */ export class MatIconHarness extends ComponentHarness { /** The selector for the host element of a `MatIcon` instance. */ @@ -23,12 +22,13 @@ export class MatIconHarness extends ComponentHarness { */ static with(options: IconHarnessFilters = {}): HarnessPredicate { return new HarnessPredicate(MatIconHarness, options) - .addOption('type', options.type, - async (harness, type) => (await harness.getType()) === type) - .addOption('name', options.name, - (harness, text) => HarnessPredicate.stringMatches(harness.getName(), text)) - .addOption('namespace', options.namespace, - (harness, text) => HarnessPredicate.stringMatches(harness.getNamespace(), text)); + .addOption('type', options.type, async (harness, type) => (await harness.getType()) === type) + .addOption('name', options.name, (harness, text) => + HarnessPredicate.stringMatches(harness.getName(), text), + ) + .addOption('namespace', options.namespace, (harness, text) => + HarnessPredicate.stringMatches(harness.getNamespace(), text), + ); } /** Gets the type of the icon. */ @@ -49,7 +49,7 @@ export class MatIconHarness extends ComponentHarness { // Some icons support defining the icon as a ligature. // As a fallback, try to extract it from the DOM text. - if (await this.getType() === IconType.FONT) { + if ((await this.getType()) === IconType.FONT) { return host.text(); } diff --git a/src/material/icon/testing/shared.spec.ts b/src/material/icon/testing/shared.spec.ts index a10b42b6abe6..36c6c5ee9874 100644 --- a/src/material/icon/testing/shared.spec.ts +++ b/src/material/icon/testing/shared.spec.ts @@ -9,9 +9,10 @@ import {IconType} from './icon-harness-filters'; /** Shared tests to run on both the original and MDC-based icons. */ export function runHarnessTests( - iconModule: typeof MatIconModule, - iconRegistry: typeof MatIconRegistry, - iconHarness: typeof MatIconHarness) { + iconModule: typeof MatIconModule, + iconRegistry: typeof MatIconRegistry, + iconHarness: typeof MatIconHarness, +) { let fixture: ComponentFixture; let loader: HarnessLoader; @@ -24,8 +25,11 @@ export function runHarnessTests( const registry = TestBed.inject(iconRegistry); const sanitizer = TestBed.inject(DomSanitizer); - registry.addSvgIconLiteralInNamespace('svgIcons', 'svgIcon', - sanitizer.bypassSecurityTrustHtml('')); + registry.addSvgIconLiteralInNamespace( + 'svgIcons', + 'svgIcon', + sanitizer.bypassSecurityTrustHtml(''), + ); fixture = TestBed.createComponent(IconHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); @@ -39,7 +43,7 @@ export function runHarnessTests( it('should filter icon harnesses based on their type', async () => { const [svgIcons, fontIcons] = await parallel(() => [ loader.getAllHarnesses(iconHarness.with({type: IconType.SVG})), - loader.getAllHarnesses(iconHarness.with({type: IconType.FONT})) + loader.getAllHarnesses(iconHarness.with({type: IconType.FONT})), ]); expect(svgIcons.length).toBe(1); @@ -49,7 +53,7 @@ export function runHarnessTests( it('should filter icon harnesses based on their name', async () => { const [regexFilterResults, stringFilterResults] = await parallel(() => [ loader.getAllHarnesses(iconHarness.with({name: /^font/})), - loader.getAllHarnesses(iconHarness.with({name: 'fontIcon'})) + loader.getAllHarnesses(iconHarness.with({name: 'fontIcon'})), ]); expect(regexFilterResults.length).toBe(1); @@ -60,7 +64,7 @@ export function runHarnessTests( const [regexFilterResults, stringFilterResults, nullFilterResults] = await parallel(() => [ loader.getAllHarnesses(iconHarness.with({namespace: /^font/})), loader.getAllHarnesses(iconHarness.with({namespace: 'svgIcons'})), - loader.getAllHarnesses(iconHarness.with({namespace: null})) + loader.getAllHarnesses(iconHarness.with({namespace: null})), ]); expect(regexFilterResults.length).toBe(1); @@ -91,7 +95,6 @@ export function runHarnessTests( const inlineStates = await parallel(() => icons.map(icon => icon.isInline())); expect(inlineStates).toEqual([false, false, true]); }); - } @Component({ @@ -99,8 +102,6 @@ export function runHarnessTests( ligature_icon - ` + `, }) -class IconHarnessTest { -} - +class IconHarnessTest {} diff --git a/src/material/icon/trusted-types.ts b/src/material/icon/trusted-types.ts new file mode 100644 index 000000000000..78f3c7da19b6 --- /dev/null +++ b/src/material/icon/trusted-types.ts @@ -0,0 +1,72 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +/** + * @fileoverview + * A module to facilitate use of a Trusted Types policy internally within + * Angular Material. It lazily constructs the Trusted Types policy, providing + * helper utilities for promoting strings to Trusted Types. When Trusted Types + * are not available, strings are used as a fallback. + * @security All use of this module is security-sensitive and should go through + * security review. + */ + +export declare interface TrustedHTML { + __brand__: 'TrustedHTML'; +} + +export declare interface TrustedTypePolicyFactory { + createPolicy( + policyName: string, + policyOptions: { + createHTML?: (input: string) => string; + }, + ): TrustedTypePolicy; +} + +export declare interface TrustedTypePolicy { + createHTML(input: string): TrustedHTML; +} + +/** + * The Trusted Types policy, or null if Trusted Types are not + * enabled/supported, or undefined if the policy has not been created yet. + */ +let policy: TrustedTypePolicy | null | undefined; + +/** + * Returns the Trusted Types policy, or null if Trusted Types are not + * enabled/supported. The first call to this function will create the policy. + */ +function getPolicy(): TrustedTypePolicy | null { + if (policy === undefined) { + policy = null; + if (typeof window !== 'undefined') { + const ttWindow = window as unknown as {trustedTypes?: TrustedTypePolicyFactory}; + if (ttWindow.trustedTypes !== undefined) { + policy = ttWindow.trustedTypes.createPolicy('angular#components', { + createHTML: (s: string) => s, + }); + } + } + } + return policy; +} + +/** + * Unsafely promote a string to a TrustedHTML, falling back to strings when + * Trusted Types are not available. + * @security This is a security-sensitive function; any use of this function + * must go through security review. In particular, it must be assured that the + * provided string will never cause an XSS vulnerability if used in a context + * that will be interpreted as HTML by a browser, e.g. when assigning to + * element.innerHTML. + */ +export function trustedHTMLFromString(html: string): TrustedHTML { + return getPolicy()?.createHTML(html) || (html as unknown as TrustedHTML); +} diff --git a/src/material/index.ts b/src/material/index.ts index 5221a1cb959e..3edef8e096e2 100644 --- a/src/material/index.ts +++ b/src/material/index.ts @@ -9,3 +9,7 @@ // primary entry-point which is empty as of version 9. All components should // be imported through their individual entry-points. This file is needed to // satisfy the "ng_package" bazel rule which also requires a primary entry-point. + +// Workaround for: https://github.com/microsoft/rushstack/issues/2806. +// This is a private export that can be removed at any time. +export const ɵɵtsModuleIndicatorApiExtractorWorkaround = true; diff --git a/src/material/input/BUILD.bazel b/src/material/input/BUILD.bazel index b3ad7b882b67..9e8d202e6760 100644 --- a/src/material/input/BUILD.bazel +++ b/src/material/input/BUILD.bazel @@ -18,7 +18,6 @@ ng_module( exclude = ["**/*.spec.ts"], ), assets = glob(["**/*.html"]), - module_name = "@angular/material/input", deps = [ "//src:dev_mode_types", "//src/cdk/coercion", @@ -51,8 +50,6 @@ ng_test_library( "//src/cdk/testing/private", "//src/material/core", "//src/material/form-field", - "//src/material/stepper", - "//src/material/tabs", "@npm//@angular/forms", "@npm//@angular/platform-browser", "@npm//rxjs", diff --git a/src/material/input/_input-legacy-index.scss b/src/material/input/_input-legacy-index.scss new file mode 100644 index 000000000000..9e266d7608ec --- /dev/null +++ b/src/material/input/_input-legacy-index.scss @@ -0,0 +1,2 @@ +@forward 'input-theme' hide color, theme, typography; +@forward 'input-theme' as mat-input-* hide mat-input-density; diff --git a/src/material/input/_input-theme.import.scss b/src/material/input/_input-theme.import.scss new file mode 100644 index 000000000000..e2414e5da693 --- /dev/null +++ b/src/material/input/_input-theme.import.scss @@ -0,0 +1,11 @@ +@forward '../core/style/form-common.import'; +@forward '../core/typography/typography-utils.import'; +@forward '../core/style/vendor-prefixes.import'; +@forward 'input-theme' hide color, theme, typography; +@forward 'input-theme' as mat-input-* hide mat-input-density; + +@import '../core/theming/palette'; +@import '../core/theming/theming'; +@import '../core/style/form-common'; +@import '../core/typography/typography-utils'; +@import '../core/style/vendor-prefixes'; diff --git a/src/material/input/_input-theme.scss b/src/material/input/_input-theme.scss index 6e728383df2b..7a730b1d87c1 100644 --- a/src/material/input/_input-theme.scss +++ b/src/material/input/_input-theme.scss @@ -1,31 +1,34 @@ -@import '../core/theming/palette'; -@import '../core/theming/theming'; -@import '../core/style/form-common'; -@import '../core/typography/typography-utils'; -@import '../core/style/vendor-prefixes'; - - -@mixin mat-input-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $primary: map-get($config, primary); - $accent: map-get($config, accent); - $warn: map-get($config, warn); - $foreground: map-get($config, foreground); +@use 'sass:map'; +@use 'sass:math'; +@use '../core/theming/palette'; +@use '../core/theming/theming'; +@use '../core/style/form-common'; +@use '../core/typography/typography'; +@use '../core/typography/typography-utils'; +@use '../core/style/vendor-prefixes'; + + +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $primary: map.get($config, primary); + $accent: map.get($config, accent); + $warn: map.get($config, warn); + $foreground: map.get($config, foreground); .mat-form-field-type-mat-native-select .mat-form-field-infix::after { - color: mat-color($foreground, secondary-text); + color: theming.get-color-from-palette($foreground, secondary-text); } .mat-input-element:disabled, .mat-form-field-type-mat-native-select.mat-form-field-disabled .mat-form-field-infix::after { - color: mat-color($foreground, disabled-text); + color: theming.get-color-from-palette($foreground, disabled-text); } .mat-input-element { - caret-color: mat-color($primary, text); + caret-color: theming.get-color-from-palette($primary, text); - @include input-placeholder { - color: mat-private-control-placeholder-color($config); + @include vendor-prefixes.input-placeholder { + color: form-common.private-control-placeholder-color($config); } // On dark themes we set the native `select` color to some shade of white, @@ -33,64 +36,67 @@ // always on a white background inside the dropdown, causing them to blend in. // Since we can't change background of the dropdown, we need to explicitly // reset the color of the options to something dark. - @if (map-get($config, is-dark)) { - option { - color: $dark-primary-text; - } - - option:disabled { - color: $dark-disabled-text; + @if (map.get($config, is-dark)) { + &:not(.mat-native-select-inline) { + option { + color: palette.$dark-primary-text; + } + + option:disabled { + color: palette.$dark-disabled-text; + } } } } .mat-form-field.mat-accent .mat-input-element { - caret-color: mat-color($accent, text); + caret-color: theming.get-color-from-palette($accent, text); } .mat-form-field.mat-warn .mat-input-element, .mat-form-field-invalid .mat-input-element { - caret-color: mat-color($warn, text); + caret-color: theming.get-color-from-palette($warn, text); } .mat-form-field-type-mat-native-select.mat-form-field-invalid .mat-form-field-infix::after { - color: mat-color($warn, text); + color: theming.get-color-from-palette($warn, text); } } -@mixin mat-input-typography($config-or-theme) { - $config: mat-get-typography-config($config-or-theme); +@mixin typography($config-or-theme) { + $config: typography.private-typography-to-2014-config( + theming.get-typography-config($config-or-theme)); // The unit-less line-height from the font config. - $line-height: mat-line-height($config, input); + $line-height: typography-utils.line-height($config, input); // The amount of space between the top of the line and the top of the actual text // (as a fraction of the font-size). - $line-spacing: ($line-height - 1) / 2; + $line-spacing: math.div($line-height - 1, 2); // elements seem to have their height set slightly too large on Safari causing the text to // be misaligned w.r.t. the placeholder. Adding this margin corrects it. input.mat-input-element { - margin-top: -$line-spacing * 1em; + margin-top: typography-utils.private-coerce-unitless-to-em(-$line-spacing); } } -@mixin _mat-input-density($config-or-theme) {} +@mixin _density($config-or-theme) {} -@mixin mat-input-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-input') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-input') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); @if $color != null { - @include mat-input-color($color); + @include color($color); } @if $density != null { - @include _mat-input-density($density); + @include _density($density); } @if $typography != null { - @include mat-input-typography($typography); + @include typography($typography); } } } diff --git a/src/material/input/autosize.ts b/src/material/input/autosize.ts deleted file mode 100644 index 8b7d82af5457..000000000000 --- a/src/material/input/autosize.ts +++ /dev/null @@ -1,44 +0,0 @@ -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import {CdkTextareaAutosize} from '@angular/cdk/text-field'; -import {Directive, Input} from '@angular/core'; - -/** - * Directive to automatically resize a textarea to fit its content. - * @deprecated Use `cdkTextareaAutosize` from `@angular/cdk/text-field` instead. - * @breaking-change 8.0.0 - */ -@Directive({ - selector: 'textarea[mat-autosize], textarea[matTextareaAutosize]', - exportAs: 'matTextareaAutosize', - inputs: ['cdkAutosizeMinRows', 'cdkAutosizeMaxRows'], - host: { - 'class': 'cdk-textarea-autosize mat-autosize', - // Textarea elements that have the directive applied should have a single row by default. - // Browsers normally show two rows by default and therefore this limits the minRows binding. - 'rows': '1', - }, -}) -export class MatTextareaAutosize extends CdkTextareaAutosize { - @Input() - get matAutosizeMinRows(): number { return this.minRows; } - set matAutosizeMinRows(value: number) { this.minRows = value; } - - @Input() - get matAutosizeMaxRows(): number { return this.maxRows; } - set matAutosizeMaxRows(value: number) { this.maxRows = value; } - - @Input('mat-autosize') - get matAutosize(): boolean { return this.enabled; } - set matAutosize(value: boolean) { this.enabled = value; } - - @Input() - get matTextareaAutosize(): boolean { return this.enabled; } - set matTextareaAutosize(value: boolean) { this.enabled = value; } -} diff --git a/src/material/input/input-module.ts b/src/material/input/input-module.ts index 3a95577226c5..0abb0195dbaf 100644 --- a/src/material/input/input-module.ts +++ b/src/material/input/input-module.ts @@ -10,23 +10,17 @@ import {TextFieldModule} from '@angular/cdk/text-field'; import {NgModule} from '@angular/core'; import {ErrorStateMatcher, MatCommonModule} from '@angular/material/core'; import {MatFormFieldModule} from '@angular/material/form-field'; -import {MatTextareaAutosize} from './autosize'; import {MatInput} from './input'; @NgModule({ - declarations: [MatInput, MatTextareaAutosize], - imports: [ - TextFieldModule, - MatFormFieldModule, - MatCommonModule, - ], + declarations: [MatInput], + imports: [TextFieldModule, MatFormFieldModule, MatCommonModule], exports: [ TextFieldModule, // We re-export the `MatFormFieldModule` since `MatInput` will almost always // be used together with `MatFormField`. MatFormFieldModule, MatInput, - MatTextareaAutosize, ], providers: [ErrorStateMatcher], }) diff --git a/src/material/input/input-value-accessor.ts b/src/material/input/input-value-accessor.ts index 158c8b7bba19..20328ffbb7ed 100644 --- a/src/material/input/input-value-accessor.ts +++ b/src/material/input/input-value-accessor.ts @@ -8,12 +8,12 @@ import {InjectionToken} from '@angular/core'; - /** * This token is used to inject the object whose value should be set into `MatInput`. If none is * provided, the native `HTMLInputElement` is used. Directives like `MatDatepickerInput` can provide * themselves for this token, in order to make `MatInput` delegate the getting and setting of the * value to them. */ -export const MAT_INPUT_VALUE_ACCESSOR = - new InjectionToken<{value: any}>('MAT_INPUT_VALUE_ACCESSOR'); +export const MAT_INPUT_VALUE_ACCESSOR = new InjectionToken<{value: any}>( + 'MAT_INPUT_VALUE_ACCESSOR', +); diff --git a/src/material/input/input.e2e.spec.ts b/src/material/input/input.e2e.spec.ts index 4bb13e84c419..7676c0e79ea6 100644 --- a/src/material/input/input.e2e.spec.ts +++ b/src/material/input/input.e2e.spec.ts @@ -1,11 +1,9 @@ import {browser, by, element} from 'protractor'; describe('input', () => { - beforeEach(async () => await browser.get('/input')); describe('text input', () => { - it('should update input value when user types', async () => { const input = element(by.id('text-input')); await input.sendKeys('abc123'); @@ -14,7 +12,6 @@ describe('input', () => { }); describe('number input', () => { - it('should update input value when user types', async () => { const input = element(by.id('number-input')); await input.sendKeys('abc123'); @@ -27,7 +24,8 @@ describe('input', () => { const size = await input.getSize(); - await browser.actions() + await browser + .actions() .mouseMove(input, {x: size.width - 5, y: 5}) .perform(); // Workaround: https://github.com/angular/protractor/issues/4578 @@ -35,9 +33,10 @@ describe('input', () => { expect(await input.getAttribute('value')).toBe('1'); - await browser.actions() - .mouseMove(input, {x: size.width - 5, y: size.height - 5}) - .perform(); + await browser + .actions() + .mouseMove(input, {x: size.width - 5, y: size.height - 5}) + .perform(); // Workaround: https://github.com/angular/protractor/issues/4578 await browser.actions().click().perform(); @@ -46,7 +45,6 @@ describe('input', () => { }); describe('textarea', () => { - it('should update input value when user types', async () => { const input = element(by.id('text-area')); await input.sendKeys('abc123'); @@ -55,7 +53,6 @@ describe('input', () => { }); describe('autosize-textarea', () => { - it('should resize correctly', async () => { const input = element(by.id('autosize-text-area')); await input.sendKeys('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'); @@ -64,10 +61,11 @@ describe('input', () => { it('should enfore max rows', async () => { const input = element(by.id('autosize-text-area')); await input.sendKeys( + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'); + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + ); }); }); }); diff --git a/src/material/input/input.md b/src/material/input/input.md index dc425e0b261e..fbaf0150182f 100644 --- a/src/material/input/input.md +++ b/src/material/input/input.md @@ -88,13 +88,20 @@ for detecting when an input becomes autofilled and changing the appearance of th The `matInput` directive works with native `` to provide an accessible experience. +#### Aria attributes + If the containing `` has a label it will automatically be used as the `aria-label` for the ``. However, if there's no label specified in the form field, `aria-label`, `aria-labelledby` or ``, }) class MatInputWithId {} @Component({ - template: `` + template: ``, }) class MatInputWithDisabled { disabled: boolean; } @Component({ - template: `` + template: ``, }) class MatInputWithRequired { required: boolean; } @Component({ - template: `` + template: ``, }) class MatInputWithType { type: string; @@ -1782,7 +1877,7 @@ class MatInputWithType { @Component({ template: ` - ` + `, }) class MatInputPlaceholderRequiredTestComponent { hideRequiredMarker: boolean = false; @@ -1794,7 +1889,7 @@ class MatInputPlaceholderRequiredTestComponent { {{placeholder}} - ` + `, }) class MatInputPlaceholderElementTestComponent { placeholder: string = 'Default Placeholder'; @@ -1804,21 +1899,21 @@ class MatInputPlaceholderElementTestComponent { template: ` - ` + `, }) class MatInputWithFormControl { formControl = new FormControl(); } @Component({ - template: `` + template: ``, }) class MatInputPlaceholderAttrTestComponent { placeholder: string = ''; } @Component({ - template: `{{label}}` + template: `{{label}}`, }) class MatInputHintLabel2TestController { label: string = ''; @@ -1828,7 +1923,7 @@ class MatInputHintLabel2TestController { template: ` - ` + `, }) class MatInputHintLabelTestController { label: string = ''; @@ -1839,7 +1934,7 @@ class MatInputHintLabelTestController { Some error - ` + `, }) class MatInputWithSubscriptAndAriaDescribedBy { label: string = ''; @@ -1858,7 +1953,7 @@ class MatInputInvalidTypeTestController { World - ` + `, }) class MatInputInvalidPlaceholderTestController {} @@ -1867,7 +1962,7 @@ class MatInputInvalidPlaceholderTestController {} World - ` + `, }) class MatInputInvalidHint2TestController {} @@ -1877,7 +1972,7 @@ class MatInputInvalidHint2TestController {} Hello World - ` + `, }) class MatInputInvalidHintTestController {} @@ -1887,7 +1982,7 @@ class MatInputInvalidHintTestController {} Hello World - ` + `, }) class MatInputMultipleHintTestController { startId: string; @@ -1899,7 +1994,7 @@ class MatInputMultipleHintTestController { World - ` + `, }) class MatInputMultipleHintMixedTestController {} @@ -1907,7 +2002,7 @@ class MatInputMultipleHintMixedTestController {} template: ` - ` + `, }) class MatInputDateTestController {} @@ -1915,7 +2010,7 @@ class MatInputDateTestController {} template: ` - ` + `, }) class MatInputTextTestController {} @@ -1923,7 +2018,7 @@ class MatInputTextTestController {} template: ` - ` + `, }) class MatInputPasswordTestController {} @@ -1931,7 +2026,7 @@ class MatInputPasswordTestController {} template: ` - ` + `, }) class MatInputNumberTestController {} @@ -1939,7 +2034,7 @@ class MatInputNumberTestController {} template: ` - ` + `, }) class MatInputZeroTestController { value = 0; @@ -1949,7 +2044,7 @@ class MatInputZeroTestController { template: ` - ` + `, }) class MatInputWithValueBinding { value: string = 'Initial'; @@ -1960,7 +2055,7 @@ class MatInputWithValueBinding { - ` + `, }) class MatInputWithStaticLabel {} @@ -1968,7 +2063,7 @@ class MatInputWithStaticLabel {} template: ` - ` + `, }) class MatInputWithDynamicLabel { shouldFloat: string = 'always'; @@ -1979,7 +2074,7 @@ class MatInputWithDynamicLabel { - ` + `, }) class MatInputTextareaWithBindings { rows: number = 4; @@ -1988,7 +2083,7 @@ class MatInputTextareaWithBindings { } @Component({ - template: `` + template: ``, }) class MatInputMissingMatInputTestController {} @@ -2001,11 +2096,14 @@ class MatInputMissingMatInputTestController {} This field is required - ` + `, }) class MatInputWithFormErrorMessages { @ViewChild('form') form: NgForm; - formControl = new FormControl('', Validators.required); + formControl = new FormControl('incorrect', [ + Validators.required, + Validators.pattern(/valid value/), + ]); renderError = true; } @@ -2020,17 +2118,17 @@ class MatInputWithFormErrorMessages { This field is required - ` + `, }) class MatInputWithCustomErrorStateMatcher { formGroup = new FormGroup({ - name: new FormControl('', Validators.required) + name: new FormControl('', [Validators.required, Validators.pattern(/valid value/)]), }); errorState = false; customErrorStateMatcher = { - isErrorState: () => this.errorState + isErrorState: () => this.errorState, }; } @@ -2043,12 +2141,12 @@ class MatInputWithCustomErrorStateMatcher { This field is required - ` + `, }) class MatInputWithFormGroupErrorMessages { @ViewChild(FormGroupDirective) formGroupDirective: FormGroupDirective; formGroup = new FormGroup({ - name: new FormControl('', Validators.required) + name: new FormControl('incorrect', [Validators.required, Validators.pattern(/valid value/)]), }); } @@ -2059,7 +2157,7 @@ class MatInputWithFormGroupErrorMessages {
Suffix
- ` + `, }) class MatInputWithPrefixAndSuffix {} @@ -2068,7 +2166,7 @@ class MatInputWithPrefixAndSuffix {} - ` + `, }) class MatInputWithNgIf { renderInput = true; @@ -2080,30 +2178,19 @@ class MatInputWithNgIf { - ` + `, }) class MatInputOnPush { formControl = new FormControl(''); } -@Component({ - template: ` - - - - ` -}) -class MatInputWithReadonlyInput { - isReadonly = true; -} - @Component({ template: ` Label - ` + `, }) class MatInputWithLabel {} @@ -2113,7 +2200,7 @@ class MatInputWithLabel {} Label - ` + `, }) class MatInputWithLabelAndPlaceholder { floatLabel: FloatLabelType; @@ -2124,7 +2211,7 @@ class MatInputWithLabelAndPlaceholder { - ` + `, }) class MatInputWithAppearance { @ViewChild(MatFormField) formField: MatFormField; @@ -2138,7 +2225,7 @@ class MatInputWithAppearance { {{labelContent}} - ` + `, }) class MatInputWithAppearanceAndLabel { @ViewChild(MatFormField) formField: MatFormField; @@ -2152,10 +2239,9 @@ class MatInputWithAppearanceAndLabel { - ` + `, }) -class MatInputWithoutPlaceholder { -} +class MatInputWithoutPlaceholder {} @Component({ template: ` @@ -2163,7 +2249,7 @@ class MatInputWithoutPlaceholder { Label - ` + `, }) class MatInputWithOutlineInsideInvisibleElement {} @@ -2174,63 +2260,12 @@ class MatInputWithOutlineInsideInvisibleElement {} `, - encapsulation: ViewEncapsulation.ShadowDom + encapsulation: ViewEncapsulation.ShadowDom, }) class MatInputWithOutlineAppearanceInShadowDOM { @ViewChild('formField', {read: ElementRef}) formField: ElementRef; } - -// Styles to reset padding and border to make measurement comparisons easier. -const textareaStyleReset = ` - textarea { - padding: 0; - border: none; - overflow: auto; - }`; - -@Component({ - template: ` - - - `, - styles: [textareaStyleReset], -}) -class AutosizeTextareaWithLongPlaceholder { - placeholder = 'Long Long Long Long Long Long Long Long Placeholder'; - @ViewChild(MatTextareaAutosize) autosize: MatTextareaAutosize; -} - -@Component({ - template: ` - - - - - - - - ` -}) -class AutosizeTextareaInATab {} - -@Component({ - template: ` - - - - - - - - ` -}) -class AutosizeTextareaInAStep {} - @Component({ template: ` @@ -2240,7 +2275,7 @@ class AutosizeTextareaInAStep {} - ` + `, }) class MatInputSelect { disabled: boolean; @@ -2256,7 +2291,7 @@ class MatInputSelect { - ` + `, }) class MatInputSelectWithNoLabelNoValue {} @@ -2269,7 +2304,7 @@ class MatInputSelectWithNoLabelNoValue {} - ` + `, }) class MatInputSelectWithLabel {} @@ -2282,7 +2317,7 @@ class MatInputSelectWithLabel {} - ` + `, }) class MatInputSelectWithInnerHtml {} @@ -2290,7 +2325,7 @@ class MatInputSelectWithInnerHtml {} template: ` - ` + `, }) class MatInputWithCustomAccessor {} @@ -2299,26 +2334,28 @@ class MatInputWithCustomAccessor {} - ` + `, }) class MatInputSelectWithoutOptions {} - /** Custom component that never has a value. Used for testing the `MAT_INPUT_VALUE_ACCESSOR`. */ @Directive({ selector: 'input[customInputAccessor]', - providers: [{ - provide: MAT_INPUT_VALUE_ACCESSOR, - useExisting: CustomMatInputAccessor - }] + providers: [ + { + provide: MAT_INPUT_VALUE_ACCESSOR, + useExisting: CustomMatInputAccessor, + }, + ], }) class CustomMatInputAccessor { - get value() { return this._value; } + get value() { + return this._value; + } set value(_value: any) {} private _value = null; } - // Note that the DOM structure is slightly weird, but it's // testing a specific g3 issue. See the discussion on #10466. @Component({ @@ -2329,11 +2366,10 @@ class CustomMatInputAccessor { - ` + `, }) class MatInputWithDefaultNgIf {} - // Note that the DOM structure is slightly weird, but it's // testing a specific g3 issue. See the discussion on #10466. @Component({ @@ -2342,19 +2378,28 @@ class MatInputWithDefaultNgIf {} App name - ` + `, }) class MatInputWithAnotherNgIf { inputValue = 'test'; } - @Component({ template: ` - ` + `, }) class MatInputWithColor { color: ThemePalette; } + +@Component({ + template: ` + + + `, +}) +class MatInputWithRequiredFormControl { + formControl = new FormControl('', [Validators.required]); +} diff --git a/src/material/input/input.ts b/src/material/input/input.ts index c08560d26cd8..7c4abffd45a1 100644 --- a/src/material/input/input.ts +++ b/src/material/input/input.ts @@ -14,7 +14,6 @@ import { Directive, DoCheck, ElementRef, - HostListener, Inject, Input, NgZone, @@ -23,19 +22,13 @@ import { Optional, Self, } from '@angular/core'; -import {FormGroupDirective, NgControl, NgForm} from '@angular/forms'; -import { - CanUpdateErrorState, - CanUpdateErrorStateCtor, - ErrorStateMatcher, - mixinErrorState, -} from '@angular/material/core'; +import {FormGroupDirective, NgControl, NgForm, Validators} from '@angular/forms'; +import {CanUpdateErrorState, ErrorStateMatcher, mixinErrorState} from '@angular/material/core'; import {MatFormFieldControl, MatFormField, MAT_FORM_FIELD} from '@angular/material/form-field'; import {Subject} from 'rxjs'; import {getMatInputUnsupportedTypeError} from './input-errors'; import {MAT_INPUT_VALUE_ACCESSOR} from './input-value-accessor'; - // Invalid input type. Using one of these will throw an MatInputUnsupportedTypeError. const MAT_INPUT_INVALID_TYPES = [ 'button', @@ -46,22 +39,24 @@ const MAT_INPUT_INVALID_TYPES = [ 'radio', 'range', 'reset', - 'submit' + 'submit', ]; let nextUniqueId = 0; // Boilerplate for applying mixins to MatInput. /** @docs-private */ -class MatInputBase { - constructor(public _defaultErrorStateMatcher: ErrorStateMatcher, - public _parentForm: NgForm, - public _parentFormGroup: FormGroupDirective, - /** @docs-private */ - public ngControl: NgControl) {} -} -const _MatInputMixinBase: CanUpdateErrorStateCtor & typeof MatInputBase = - mixinErrorState(MatInputBase); +const _MatInputBase = mixinErrorState( + class { + constructor( + public _defaultErrorStateMatcher: ErrorStateMatcher, + public _parentForm: NgForm, + public _parentFormGroup: FormGroupDirective, + /** @docs-private */ + public ngControl: NgControl, + ) {} + }, +); /** Directive that allows a native input to work inside a `MatFormField`. */ @Directive({ @@ -84,13 +79,27 @@ const _MatInputMixinBase: CanUpdateErrorStateCtor & typeof MatInputBase = '[disabled]': 'disabled', '[required]': 'required', '[attr.readonly]': 'readonly && !_isNativeSelect || null', - '[attr.aria-invalid]': 'errorState', - '[attr.aria-required]': 'required.toString()', + '[class.mat-native-select-inline]': '_isInlineSelect()', + // Only mark the input as invalid for assistive technology if it has a value since the + // state usually overlaps with `aria-required` when the input is empty and can be redundant. + '[attr.aria-invalid]': '(empty && required) ? null : errorState', + '[attr.aria-required]': 'required', + '(focus)': '_focusChanged(true)', + '(blur)': '_focusChanged(false)', + '(input)': '_onInput()', }, providers: [{provide: MatFormFieldControl, useExisting: MatInput}], }) -export class MatInput extends _MatInputMixinBase implements MatFormFieldControl, OnChanges, - OnDestroy, AfterViewInit, DoCheck, CanUpdateErrorState { +export class MatInput + extends _MatInputBase + implements + MatFormFieldControl, + OnChanges, + OnDestroy, + AfterViewInit, + DoCheck, + CanUpdateErrorState +{ protected _uid = `mat-input-${nextUniqueId++}`; protected _previousNativeValue: any; private _inputValueAccessor: {value: any}; @@ -105,6 +114,9 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< /** Whether the component is a textarea. */ readonly _isTextarea: boolean; + /** Whether the input is inside of a form field. */ + readonly _isInFormField: boolean; + /** * Implemented as part of MatFormFieldControl. * @docs-private @@ -115,7 +127,7 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< * Implemented as part of MatFormFieldControl. * @docs-private */ - readonly stateChanges: Subject = new Subject(); + override readonly stateChanges: Subject = new Subject(); /** * Implemented as part of MatFormFieldControl. @@ -140,7 +152,7 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< } return this._disabled; } - set disabled(value: boolean) { + set disabled(value: BooleanInput) { this._disabled = coerceBooleanProperty(value); // Browsers may not fire the blur event if the input is disabled too quickly. @@ -157,8 +169,12 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< * @docs-private */ @Input() - get id(): string { return this._id; } - set id(value: string) { this._id = value || this._uid; } + get id(): string { + return this._id; + } + set id(value: string) { + this._id = value || this._uid; + } protected _id: string; /** @@ -172,13 +188,19 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< * @docs-private */ @Input() - get required(): boolean { return this._required; } - set required(value: boolean) { this._required = coerceBooleanProperty(value); } - protected _required = false; + get required(): boolean { + return this._required ?? this.ngControl?.control?.hasValidator(Validators.required) ?? false; + } + set required(value: BooleanInput) { + this._required = coerceBooleanProperty(value); + } + protected _required: boolean | undefined; /** Input type of the element. */ @Input() - get type(): string { return this._type; } + get type(): string { + return this._type; + } set type(value: string) { this._type = value || 'text'; this._validateType(); @@ -193,7 +215,7 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< protected _type = 'text'; /** An object used to control when error messages are shown. */ - @Input() errorStateMatcher: ErrorStateMatcher; + @Input() override errorStateMatcher: ErrorStateMatcher; /** * Implemented as part of MatFormFieldControl. @@ -206,8 +228,10 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< * @docs-private */ @Input() - get value(): string { return this._inputValueAccessor.value; } - set value(value: string) { + get value(): string { + return this._inputValueAccessor.value; + } + set value(value: any) { if (value !== this.value) { this._inputValueAccessor.value = value; this.stateChanges.next(); @@ -216,8 +240,12 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< /** Whether the element is readonly. */ @Input() - get readonly(): boolean { return this._readonly; } - set readonly(value: boolean) { this._readonly = coerceBooleanProperty(value); } + get readonly(): boolean { + return this._readonly; + } + set readonly(value: BooleanInput) { + this._readonly = coerceBooleanProperty(value); + } private _readonly = false; protected _neverEmptyInputTypes = [ @@ -226,24 +254,23 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< 'datetime-local', 'month', 'time', - 'week' + 'week', ].filter(t => getSupportedInputTypes().has(t)); constructor( - protected _elementRef: ElementRef, - protected _platform: Platform, - /** @docs-private */ - @Optional() @Self() public ngControl: NgControl, - @Optional() _parentForm: NgForm, - @Optional() _parentFormGroup: FormGroupDirective, - _defaultErrorStateMatcher: ErrorStateMatcher, - @Optional() @Self() @Inject(MAT_INPUT_VALUE_ACCESSOR) inputValueAccessor: any, - private _autofillMonitor: AutofillMonitor, - ngZone: NgZone, - // TODO: Remove this once the legacy appearance has been removed. We only need - // to inject the form-field for determining whether the placeholder has been promoted. - @Optional() @Inject(MAT_FORM_FIELD) private _formField?: MatFormField) { - + protected _elementRef: ElementRef, + protected _platform: Platform, + @Optional() @Self() ngControl: NgControl, + @Optional() _parentForm: NgForm, + @Optional() _parentFormGroup: FormGroupDirective, + _defaultErrorStateMatcher: ErrorStateMatcher, + @Optional() @Self() @Inject(MAT_INPUT_VALUE_ACCESSOR) inputValueAccessor: any, + private _autofillMonitor: AutofillMonitor, + ngZone: NgZone, + // TODO: Remove this once the legacy appearance has been removed. We only need + // to inject the form-field for determining whether the placeholder has been promoted. + @Optional() @Inject(MAT_FORM_FIELD) private _formField?: MatFormField, + ) { super(_defaultErrorStateMatcher, _parentForm, _parentFormGroup, ngControl); const element = this._elementRef.nativeElement; @@ -264,8 +291,15 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< if (_platform.IOS) { ngZone.runOutsideAngular(() => { _elementRef.nativeElement.addEventListener('keyup', (event: Event) => { - let el = event.target as HTMLInputElement; - if (!el.value && !el.selectionStart && !el.selectionEnd) { + const el = event.target as HTMLInputElement; + + // Note: We specifically check for 0, rather than `!el.selectionStart`, because the two + // indicate different things. If the value is 0, it means that the caret is at the start + // of the input, whereas a value of `null` means that the input doesn't support + // manipulating the selection range. Inputs that don't support setting the selection range + // will throw an error so we want to avoid calling `setSelectionRange` on them. See: + // https://html.spec.whatwg.org/multipage/input.html#do-not-apply + if (!el.value && el.selectionStart === 0 && el.selectionEnd === 0) { // Note: Just setting `0, 0` doesn't fix the issue. Setting // `1, 1` fixes it for the first time that you type text and // then hold delete. Toggling to `1, 1` and then back to @@ -280,10 +314,12 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< this._isServer = !this._platform.isBrowser; this._isNativeSelect = nodeName === 'select'; this._isTextarea = nodeName === 'textarea'; + this._isInFormField = !!_formField; if (this._isNativeSelect) { - this.controlType = (element as HTMLSelectElement).multiple ? 'mat-native-select-multiple' : - 'mat-native-select'; + this.controlType = (element as HTMLSelectElement).multiple + ? 'mat-native-select-multiple' + : 'mat-native-select'; } } @@ -331,28 +367,14 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< this._elementRef.nativeElement.focus(options); } - // We have to use a `HostListener` here in order to support both Ivy and ViewEngine. - // In Ivy the `host` bindings will be merged when this class is extended, whereas in - // ViewEngine they're overwritten. - // TODO(crisbeto): we move this back into `host` once Ivy is turned on by default. /** Callback for the cases where the focused state of the input changes. */ - // tslint:disable:no-host-decorator-in-concrete - @HostListener('focus', ['true']) - @HostListener('blur', ['false']) - // tslint:enable:no-host-decorator-in-concrete _focusChanged(isFocused: boolean) { - if (isFocused !== this.focused && (!this.readonly || !isFocused)) { + if (isFocused !== this.focused) { this.focused = isFocused; this.stateChanges.next(); } } - // We have to use a `HostListener` here in order to support both Ivy and ViewEngine. - // In Ivy the `host` bindings will be merged when this class is extended, whereas in - // ViewEngine they're overwritten. - // TODO(crisbeto): we move this back into `host` once Ivy is turned on by default. - // tslint:disable-next-line:no-host-decorator-in-concrete - @HostListener('input') _onInput() { // This is a noop function and is used to let Angular know whenever the value changes. // Angular will run a new change detection each time the `input` event has been dispatched. @@ -373,8 +395,9 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< if (placeholder !== this._previousPlaceholder) { const element = this._elementRef.nativeElement; this._previousPlaceholder = placeholder; - placeholder ? - element.setAttribute('placeholder', placeholder) : element.removeAttribute('placeholder'); + placeholder + ? element.setAttribute('placeholder', placeholder) + : element.removeAttribute('placeholder'); } } @@ -390,8 +413,10 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< /** Make sure the input is a supported type. */ protected _validateType() { - if (MAT_INPUT_INVALID_TYPES.indexOf(this._type) > -1 && - (typeof ngDevMode === 'undefined' || ngDevMode)) { + if ( + MAT_INPUT_INVALID_TYPES.indexOf(this._type) > -1 && + (typeof ngDevMode === 'undefined' || ngDevMode) + ) { throw getMatInputUnsupportedTypeError(this._type); } } @@ -413,8 +438,12 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< * @docs-private */ get empty(): boolean { - return !this._isNeverEmpty() && !this._elementRef.nativeElement.value && !this._isBadInput() && - !this.autofilled; + return ( + !this._isNeverEmpty() && + !this._elementRef.nativeElement.value && + !this._isBadInput() && + !this.autofilled + ); } /** @@ -431,8 +460,12 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< // On most browsers the `selectedIndex` will always be 0, however on IE and Edge it'll be // -1 if the `value` is set to something, that isn't in the list of options, at a later point. - return this.focused || selectElement.multiple || !this.empty || - !!(selectElement.selectedIndex > -1 && firstOption && firstOption.label); + return ( + this.focused || + selectElement.multiple || + !this.empty || + !!(selectElement.selectedIndex > -1 && firstOption && firstOption.label) + ); } else { return this.focused || !this.empty; } @@ -463,11 +496,9 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< } } - static ngAcceptInputType_disabled: BooleanInput; - static ngAcceptInputType_readonly: BooleanInput; - static ngAcceptInputType_required: BooleanInput; - - // Accept `any` to avoid conflicts with other directives on `` that may - // accept different types. - static ngAcceptInputType_value: any; + /** Whether the form control is a native select that is displayed inline. */ + _isInlineSelect(): boolean { + const element = this._elementRef.nativeElement as HTMLSelectElement; + return this._isNativeSelect && (element.multiple || element.size > 1); + } } diff --git a/src/material/input/public-api.ts b/src/material/input/public-api.ts index a76b4fc47d05..3c4f749d2065 100644 --- a/src/material/input/public-api.ts +++ b/src/material/input/public-api.ts @@ -6,9 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -export * from './autosize'; export * from './input'; export * from './input-errors'; export * from './input-module'; export * from './input-value-accessor'; - diff --git a/src/material/input/testing/BUILD.bazel b/src/material/input/testing/BUILD.bazel index b964ae39cd9a..6e68f42416b9 100644 --- a/src/material/input/testing/BUILD.bazel +++ b/src/material/input/testing/BUILD.bazel @@ -8,7 +8,6 @@ ts_library( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material/input/testing", deps = [ "//src/cdk/coercion", "//src/cdk/testing", diff --git a/src/material/input/testing/input-harness.ts b/src/material/input/testing/input-harness.ts index e645317e30e5..7e52cd0ef015 100644 --- a/src/material/input/testing/input-harness.ts +++ b/src/material/input/testing/input-harness.ts @@ -25,39 +25,39 @@ export class MatInputHarness extends MatFormFieldControlHarness { */ static with(options: InputHarnessFilters = {}): HarnessPredicate { return new HarnessPredicate(MatInputHarness, options) - .addOption('value', options.value, (harness, value) => { - return HarnessPredicate.stringMatches(harness.getValue(), value); - }) - .addOption('placeholder', options.placeholder, (harness, placeholder) => { - return HarnessPredicate.stringMatches(harness.getPlaceholder(), placeholder); - }); + .addOption('value', options.value, (harness, value) => { + return HarnessPredicate.stringMatches(harness.getValue(), value); + }) + .addOption('placeholder', options.placeholder, (harness, placeholder) => { + return HarnessPredicate.stringMatches(harness.getPlaceholder(), placeholder); + }); } /** Whether the input is disabled. */ async isDisabled(): Promise { - return (await this.host()).getProperty('disabled')!; + return (await this.host()).getProperty('disabled'); } /** Whether the input is required. */ async isRequired(): Promise { - return (await this.host()).getProperty('required')!; + return (await this.host()).getProperty('required'); } /** Whether the input is readonly. */ async isReadonly(): Promise { - return (await this.host()).getProperty('readOnly')!; + return (await this.host()).getProperty('readOnly'); } /** Gets the value of the input. */ async getValue(): Promise { // The "value" property of the native input is never undefined. - return (await (await this.host()).getProperty('value'))!; + return await (await this.host()).getProperty('value'); } /** Gets the name of the input. */ async getName(): Promise { // The "name" property of the native input is never undefined. - return (await (await this.host()).getProperty('name'))!; + return await (await this.host()).getProperty('name'); } /** @@ -66,7 +66,7 @@ export class MatInputHarness extends MatFormFieldControlHarness { */ async getType(): Promise { // The "type" property of the native input is never undefined. - return (await (await this.host()).getProperty('type'))!; + return await (await this.host()).getProperty('type'); } /** Gets the placeholder of the input. */ @@ -74,7 +74,7 @@ export class MatInputHarness extends MatFormFieldControlHarness { const host = await this.host(); const [nativePlaceholder, fallback] = await parallel(() => [ host.getProperty('placeholder'), - host.getAttribute('data-placeholder') + host.getAttribute('data-placeholder'), ]); return nativePlaceholder || fallback || ''; } @@ -83,7 +83,7 @@ export class MatInputHarness extends MatFormFieldControlHarness { async getId(): Promise { // The input directive always assigns a unique id to the input in // case no id has been explicitly specified. - return (await (await this.host()).getProperty('id'))!; + return await (await this.host()).getProperty('id'); } /** @@ -124,9 +124,6 @@ export class MatInputHarness extends MatFormFieldControlHarness { // Some input types won't respond to key presses (e.g. `color`) so to be sure that the // value is set, we also set the property after the keyboard sequence. Note that we don't // want to do it before, because it can cause the value to be entered twice. - // @breaking-change 11.0.0 Remove non-null assertion once `setInputValue` is required. - if (inputEl.setInputValue) { - await inputEl.setInputValue(newValue); - } + await inputEl.setInputValue(newValue); } } diff --git a/src/material/input/testing/native-option-harness.ts b/src/material/input/testing/native-option-harness.ts index 63085135581f..1869e541df2e 100644 --- a/src/material/input/testing/native-option-harness.ts +++ b/src/material/input/testing/native-option-harness.ts @@ -22,33 +22,38 @@ export class MatNativeOptionHarness extends ComponentHarness { */ static with(options: NativeOptionHarnessFilters = {}) { return new HarnessPredicate(MatNativeOptionHarness, options) - .addOption('text', options.text, - async (harness, title) => - HarnessPredicate.stringMatches(await harness.getText(), title)) - .addOption('index', options.index, - async (harness, index) => await harness.getIndex() === index) - .addOption('isSelected', options.isSelected, - async (harness, isSelected) => await harness.isSelected() === isSelected); - + .addOption('text', options.text, async (harness, title) => + HarnessPredicate.stringMatches(await harness.getText(), title), + ) + .addOption( + 'index', + options.index, + async (harness, index) => (await harness.getIndex()) === index, + ) + .addOption( + 'isSelected', + options.isSelected, + async (harness, isSelected) => (await harness.isSelected()) === isSelected, + ); } /** Gets the option's label text. */ async getText(): Promise { - return (await this.host()).getProperty('label'); + return (await this.host()).getProperty('label'); } /** Index of the option within the native `select` element. */ async getIndex(): Promise { - return (await this.host()).getProperty('index'); + return (await this.host()).getProperty('index'); } /** Gets whether the option is disabled. */ async isDisabled(): Promise { - return (await this.host()).getProperty('disabled'); + return (await this.host()).getProperty('disabled'); } /** Gets whether the option is selected. */ async isSelected(): Promise { - return (await this.host()).getProperty('selected'); + return (await this.host()).getProperty('selected'); } } diff --git a/src/material/input/testing/native-select-harness.ts b/src/material/input/testing/native-select-harness.ts index fea9f100f9d9..d690b55f8b45 100644 --- a/src/material/input/testing/native-select-harness.ts +++ b/src/material/input/testing/native-select-harness.ts @@ -14,7 +14,6 @@ import { NativeSelectHarnessFilters, } from './native-select-harness-filters'; - /** Harness for interacting with a native `select` in tests. */ export class MatNativeSelectHarness extends MatFormFieldControlHarness { static hostSelector = 'select[matNativeControl]'; @@ -31,29 +30,29 @@ export class MatNativeSelectHarness extends MatFormFieldControlHarness { /** Gets a boolean promise indicating if the select is disabled. */ async isDisabled(): Promise { - return (await this.host()).getProperty('disabled'); + return (await this.host()).getProperty('disabled'); } /** Gets a boolean promise indicating if the select is required. */ async isRequired(): Promise { - return (await this.host()).getProperty('required'); + return (await this.host()).getProperty('required'); } /** Gets a boolean promise indicating if the select is in multi-selection mode. */ async isMultiple(): Promise { - return (await this.host()).getProperty('multiple'); + return (await this.host()).getProperty('multiple'); } /** Gets the name of the select. */ async getName(): Promise { // The "name" property of the native select is never undefined. - return (await (await this.host()).getProperty('name'))!; + return await (await this.host()).getProperty('name'); } /** Gets the id of the select. */ async getId(): Promise { // We're guaranteed to have an id, because the `matNativeControl` always assigns one. - return (await (await this.host()).getProperty('id'))!; + return await (await this.host()).getProperty('id'); } /** Focuses the select and returns a void promise that indicates when the action is complete. */ @@ -72,8 +71,7 @@ export class MatNativeSelectHarness extends MatFormFieldControlHarness { } /** Gets the options inside the select panel. */ - async getOptions(filter: NativeOptionHarnessFilters = {}): - Promise { + async getOptions(filter: NativeOptionHarnessFilters = {}): Promise { return this.locatorForAll(MatNativeOptionHarness.with(filter))(); } @@ -92,15 +90,9 @@ export class MatNativeSelectHarness extends MatFormFieldControlHarness { const [host, optionIndexes] = await parallel(() => [ this.host(), - parallel(() => options.slice(0, isMultiple ? undefined : 1).map(option => option.getIndex())) + parallel(() => options.slice(0, isMultiple ? undefined : 1).map(option => option.getIndex())), ]); - // @breaking-change 12.0.0 Error can be removed once `selectOptions` is a required method. - if (!host.selectOptions) { - throw Error('TestElement implementation does not support the selectOptions ' + - 'method which is required for this function.'); - } - await host.selectOptions(...optionIndexes); } } diff --git a/src/material/input/testing/shared-input.spec.ts b/src/material/input/testing/shared-input.spec.ts index 8315fbd36e44..8eb4268975e5 100644 --- a/src/material/input/testing/shared-input.spec.ts +++ b/src/material/input/testing/shared-input.spec.ts @@ -10,17 +10,17 @@ import {MatInputHarness} from './input-harness'; /** Shared tests to run on both the original and MDC-based input's. */ export function runInputHarnessTests( - inputModule: typeof MatInputModule, inputHarness: typeof MatInputHarness) { + inputModule: typeof MatInputModule, + inputHarness: typeof MatInputHarness, +) { let fixture: ComponentFixture; let loader: HarnessLoader; beforeEach(async () => { - await TestBed - .configureTestingModule({ - imports: [NoopAnimationsModule, inputModule, ReactiveFormsModule], - declarations: [InputHarnessTest], - }) - .compileComponents(); + await TestBed.configureTestingModule({ + imports: [NoopAnimationsModule, inputModule, ReactiveFormsModule], + declarations: [InputHarnessTest], + }).compileComponents(); fixture = TestBed.createComponent(InputHarnessTest); fixture.detectChanges(); @@ -39,7 +39,8 @@ export function runInputHarnessTests( it('should load input with specific name', async () => { const inputs = await loader.getAllHarnesses( - inputHarness.with({selector: '[name="favorite-food"]'})); + inputHarness.with({selector: '[name="favorite-food"]'}), + ); expect(inputs.length).toBe(1); }); @@ -250,7 +251,7 @@ export function runInputHarnessTests( - ` + `, }) class InputHarnessTest { inputType = 'number'; diff --git a/src/material/input/testing/shared-native-select.spec.ts b/src/material/input/testing/shared-native-select.spec.ts index d09c08698e5e..75f5287680fe 100644 --- a/src/material/input/testing/shared-native-select.spec.ts +++ b/src/material/input/testing/shared-native-select.spec.ts @@ -9,8 +9,9 @@ import {MatNativeSelectHarness} from './native-select-harness'; /** Shared tests to run on both the original and MDC-based native selects. */ export function runNativeSelectHarnessTests( - inputModule: typeof MatInputModule, - selectHarness: typeof MatNativeSelectHarness) { + inputModule: typeof MatInputModule, + selectHarness: typeof MatNativeSelectHarness, +) { let fixture: ComponentFixture; let loader: HarnessLoader; @@ -40,15 +41,17 @@ export function runNativeSelectHarnessTests( expect(await parallel(() => selects.map(select => select.getName()))).toEqual([ 'favorite-food', - 'favorite-drink' + 'favorite-drink', ]); }); it('should get whether a select is disabled', async () => { const selects = await loader.getAllHarnesses(selectHarness); - expect(await parallel(() => { - return selects.map(select => select.isDisabled()); - })).toEqual([false, false]); + expect( + await parallel(() => { + return selects.map(select => select.isDisabled()); + }), + ).toEqual([false, false]); fixture.componentInstance.favoriteDrinkDisabled = true; expect(await parallel(() => selects.map(select => select.isDisabled()))).toEqual([false, true]); @@ -61,9 +64,11 @@ export function runNativeSelectHarnessTests( it('should get whether a select is required', async () => { const selects = await loader.getAllHarnesses(selectHarness); - expect(await parallel(() => { - return selects.map(select => select.isRequired()); - })).toEqual([false, false]); + expect( + await parallel(() => { + return selects.map(select => select.isRequired()); + }), + ).toEqual([false, false]); fixture.componentInstance.favoriteFoodRequired = true; expect(await parallel(() => selects.map(select => select.isRequired()))).toEqual([true, false]); @@ -118,7 +123,7 @@ export function runNativeSelectHarnessTests( 'Water', 'Soda', 'Coffee', - 'Juice' + 'Juice', ]); }); @@ -136,7 +141,7 @@ export function runNativeSelectHarnessTests( expect(await parallel(() => options.map(option => option.isDisabled()))).toEqual([ false, false, - false + false, ]); fixture.componentInstance.pastaDisabled = true; @@ -144,7 +149,7 @@ export function runNativeSelectHarnessTests( expect(await parallel(() => options.map(option => option.isDisabled()))).toEqual([ false, true, - false + false, ]); }); @@ -155,7 +160,7 @@ export function runNativeSelectHarnessTests( expect(await parallel(() => options.map(option => option.isSelected()))).toEqual([ false, false, - false + false, ]); await select.selectOptions({index: 2}); @@ -163,7 +168,7 @@ export function runNativeSelectHarnessTests( expect(await parallel(() => options.map(option => option.isSelected()))).toEqual([ false, false, - true + true, ]); }); @@ -175,7 +180,7 @@ export function runNativeSelectHarnessTests( false, false, false, - false + false, ]); await select.selectOptions({text: /Water|Coffee/}); @@ -184,10 +189,9 @@ export function runNativeSelectHarnessTests( true, false, true, - false + false, ]); }); - } @Component({ @@ -219,7 +223,7 @@ export function runNativeSelectHarnessTests( - ` + `, }) class SelectHarnessTest { favoriteFood: string; diff --git a/src/material/list/BUILD.bazel b/src/material/list/BUILD.bazel index e6579acad9a0..64d835bf5485 100644 --- a/src/material/list/BUILD.bazel +++ b/src/material/list/BUILD.bazel @@ -19,7 +19,6 @@ ng_module( exclude = ["**/*.spec.ts"], ), assets = [":list.css"] + glob(["**/*.html"]), - module_name = "@angular/material/list", deps = [ "//src:dev_mode_types", "//src/cdk/a11y", diff --git a/src/material/list/_list-legacy-index.scss b/src/material/list/_list-legacy-index.scss new file mode 100644 index 000000000000..271fe4dc8537 --- /dev/null +++ b/src/material/list/_list-legacy-index.scss @@ -0,0 +1,2 @@ +@forward 'list-theme' hide color, theme, typography; +@forward 'list-theme' as mat-list-* hide mat-list-density; diff --git a/src/material/list/_list-theme.import.scss b/src/material/list/_list-theme.import.scss new file mode 100644 index 000000000000..7d9dba1a9e42 --- /dev/null +++ b/src/material/list/_list-theme.import.scss @@ -0,0 +1,10 @@ +@forward '../core/theming/theming.import'; +@forward '../core/typography/typography-utils.import'; +@forward '../core/style/list-common.import'; +@forward 'list-theme' hide color, theme, typography; +@forward 'list-theme' as mat-list-* hide mat-list-density; + +@import '../core/theming/palette'; +@import '../core/theming/theming'; +@import '../core/typography/typography-utils'; +@import '../core/style/list-common'; diff --git a/src/material/list/_list-theme.scss b/src/material/list/_list-theme.scss index e49df6cd64c0..6cbe89e7fe5a 100644 --- a/src/material/list/_list-theme.scss +++ b/src/material/list/_list-theme.scss @@ -1,50 +1,52 @@ -@import '../core/theming/palette'; -@import '../core/theming/theming'; -@import '../core/typography/typography-utils'; -@import '../core/style/list-common'; +@use 'sass:map'; +@use '../core/theming/theming'; +@use '../core/typography/typography'; +@use '../core/typography/typography-utils'; +@use '../core/style/list-common'; -@mixin mat-list-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $background: map-get($config, background); - $foreground: map-get($config, foreground); +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $background: map.get($config, background); + $foreground: map.get($config, foreground); .mat-list-base { .mat-list-item { - color: mat-color($foreground, text); + color: theming.get-color-from-palette($foreground, text); } .mat-list-option { - color: mat-color($foreground, text); + color: theming.get-color-from-palette($foreground, text); } .mat-subheader { - color: mat-color($foreground, secondary-text); + color: theming.get-color-from-palette($foreground, secondary-text); } } .mat-list-item-disabled { - background-color: mat-color($background, disabled-list-option); + background-color: theming.get-color-from-palette($background, disabled-list-option); } .mat-list-option, .mat-nav-list .mat-list-item, .mat-action-list .mat-list-item { &:hover, &:focus { - background: mat-color($background, 'hover'); + background: theming.get-color-from-palette($background, 'hover'); } } .mat-list-single-selected-option { &, &:hover, &:focus { - background: mat-color($background, hover, 0.12); + background: theming.get-color-from-palette($background, hover, 0.12); } } } -@mixin mat-list-typography($config-or-theme) { - $config: mat-get-typography-config($config-or-theme); - $font-family: mat-font-family($config); +@mixin typography($config-or-theme) { + $config: typography.private-typography-to-2014-config( + theming.get-typography-config($config-or-theme)); + $font-family: typography-utils.font-family($config); .mat-list-item { font-family: $font-family; @@ -57,59 +59,59 @@ // Default list .mat-list-base { .mat-list-item { - font-size: mat-font-size($config, subheading-2); - @include mat-line-base(mat-font-size($config, body-1)); + font-size: typography-utils.font-size($config, subheading-2); + @include list-common.base(typography-utils.font-size($config, body-1)); } .mat-list-option { - font-size: mat-font-size($config, subheading-2); - @include mat-line-base(mat-font-size($config, body-1)); + font-size: typography-utils.font-size($config, subheading-2); + @include list-common.base(typography-utils.font-size($config, body-1)); } .mat-subheader { - font-family: mat-font-family($config, body-2); - font-size: mat-font-size($config, body-2); - font-weight: mat-font-weight($config, body-2); + font-family: typography-utils.font-family($config, body-2); + font-size: typography-utils.font-size($config, body-2); + font-weight: typography-utils.font-weight($config, body-2); } } // Dense list .mat-list-base[dense] { .mat-list-item { - font-size: mat-font-size($config, caption); - @include mat-line-base(mat-font-size($config, caption)); + font-size: typography-utils.font-size($config, caption); + @include list-common.base(typography-utils.font-size($config, caption)); } .mat-list-option { - font-size: mat-font-size($config, caption); - @include mat-line-base(mat-font-size($config, caption)); + font-size: typography-utils.font-size($config, caption); + @include list-common.base(typography-utils.font-size($config, caption)); } .mat-subheader { font-family: $font-family; - font-size: mat-font-size($config, caption); - font-weight: mat-font-weight($config, body-2); + font-size: typography-utils.font-size($config, caption); + font-weight: typography-utils.font-weight($config, body-2); } } } -@mixin _mat-list-density($config-or-theme) {} +@mixin _density($config-or-theme) {} -@mixin mat-list-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-list') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-list') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); @if $color != null { - @include mat-list-color($color); + @include color($color); } @if $density != null { - @include _mat-list-density($density); + @include _density($density); } @if $typography != null { - @include mat-list-typography($typography); + @include typography($typography); } } } diff --git a/src/material/list/list-module.ts b/src/material/list/list-module.ts index d3cfc0122021..c4ca757670ae 100644 --- a/src/material/list/list-module.ts +++ b/src/material/list/list-module.ts @@ -25,7 +25,6 @@ import { import {MatListOption, MatSelectionList} from './selection-list'; import {MatDividerModule} from '@angular/material/divider'; - @NgModule({ imports: [MatLineModule, MatRippleModule, MatCommonModule, MatPseudoCheckboxModule, CommonModule], exports: [ @@ -40,7 +39,7 @@ import {MatDividerModule} from '@angular/material/divider'; MatPseudoCheckboxModule, MatSelectionList, MatListOption, - MatDividerModule + MatDividerModule, ], declarations: [ MatList, @@ -50,7 +49,7 @@ import {MatDividerModule} from '@angular/material/divider'; MatListIconCssMatStyler, MatListSubheaderCssMatStyler, MatSelectionList, - MatListOption + MatListOption, ], }) export class MatListModule {} diff --git a/src/material/list/list.e2e.spec.ts b/src/material/list/list.e2e.spec.ts index 52e18064d498..346337ec4fe5 100644 --- a/src/material/list/list.e2e.spec.ts +++ b/src/material/list/list.e2e.spec.ts @@ -1,5 +1,5 @@ import {browser} from 'protractor'; -import {expectToExist} from '@angular/cdk/testing/private/e2e'; +import {expectToExist} from '../../cdk/testing/private/e2e'; describe('list', () => { beforeEach(async () => await browser.get('/list')); diff --git a/src/material/list/list.md b/src/material/list/list.md index be9668a084bb..16f07995215d 100644 --- a/src/material/list/list.md +++ b/src/material/list/list.md @@ -166,21 +166,32 @@ To add a divider, use ``. ``` ### Accessibility -The type of list used in any given situation depends on how the end-user will be interacting with it. + +Angular Material offers multiple varieties of list so that you can choose the type that best applies +to your use-case. #### Navigation -When the list-items navigate somewhere, `` should be used with `` -elements as the list items. The nav-list will be rendered using `role="navigation"` and can be -given an `aria-label` to give context on the set of navigation options presented. Additional -interactive content, such as buttons, should _not_ be added inside the anchors. + +You should use `MatNavList` when every item in the list is an anchor that navigate to another URL. +The root `` element sets `role="navigation"` and should contain only anchor elements +with the `mat-list-item` attribute. You should not nest any interactive elements inside these +anchors, including buttons and checkboxes. + +Always provide an accessible label for the `` element via `aria-label` or +`aria-labelledby`. #### Selection -When the list is primarily used to select one or more values, a `` should be -used with ``, which map to `role="listbox"` and `role="option"`, respectively. The -list should be given an `aria-label` that describes the value or values being selected. Each option -should _not_ contain any additional interactive elements, such as buttons. + +You should use `MatSelectionList` and `MatListOption` for lists that allow the user to select one +or more values. This list variant uses the `role="listbox"` interaction pattern, handling all +associated keyboard input and focus management. You should not nest any interactive elements inside +these options, including buttons and anchors. + +Always provide an accessible label for the `` element via `aria-label` or +`aria-labelledby` that describes the selection being made. #### Custom scenarios + By default, the list assumes that it will be used in a purely decorative fashion and thus sets no roles, ARIA attributes, or keyboard shortcuts. This is equivalent to having a sequence of `
` elements on the page. Any interactive content within the list should be given an appropriate diff --git a/src/material/list/list.scss b/src/material/list/list.scss index 0ca4640a058a..7321cd89ad35 100644 --- a/src/material/list/list.scss +++ b/src/material/list/list.scss @@ -1,41 +1,40 @@ -@import '../core/style/variables'; -@import '../core/style/list-common'; -@import '../core/style/layout-common'; -@import '../divider/divider-offset'; -@import '../../cdk/a11y/a11y'; +@use '../core/style/list-common'; +@use '../core/style/layout-common'; +@use '../divider/divider-offset'; +@use '../../cdk/a11y'; -$mat-list-side-padding: 16px; -$mat-list-icon-padding: 4px; -$mat-list-avatar-size: 40px; +$side-padding: 16px; +$icon-padding: 4px; +$avatar-size: 40px; // Normal list variables -$mat-list-top-padding: 8px; +$top-padding: 8px; // height for single-line lists -$mat-list-base-height: 48px; +$base-height: 48px; // height for single-line lists with avatars -$mat-list-avatar-height: 56px; +$avatar-height: 56px; // spec requires two- and three-line lists be taller -$mat-list-two-line-height: 72px; -$mat-list-three-line-height: 88px; -$mat-list-multi-line-padding: 16px; -$mat-list-icon-size: 24px; +$two-line-height: 72px; +$three-line-height: 88px; +$multi-line-padding: 16px; +$icon-size: 24px; // Dense list variables -$mat-dense-top-padding: 4px; -$mat-dense-base-height: 40px; -$mat-dense-avatar-height: 48px; -$mat-dense-two-line-height: 60px; -$mat-dense-three-line-height: 76px; -$mat-dense-multi-line-padding: 16px; -$mat-dense-list-icon-size: 20px; -$mat-dense-avatar-size: 36px; +$dense-top-padding: 4px; +$dense-base-height: 40px; +$dense-avatar-height: 48px; +$dense-two-line-height: 60px; +$dense-three-line-height: 76px; +$dense-multi-line-padding: 16px; +$dense-list-icon-size: 20px; +$dense-avatar-size: 36px; -$mat-list-item-inset-divider-offset: 72px; +$item-inset-divider-offset: 72px; // This mixin provides all list-item styles, changing font size and height // based on whether the list is in dense mode. -@mixin mat-list-item-base($base-height, $height-with-avatar, $two-line-height, +@mixin item-base($base-height, $height-with-avatar, $two-line-height, $three-line-height, $multi-line-padding, $icon-size, $avatar-size) { // Prevents the wrapper `mat-list-item-content` from collapsing due to it @@ -53,7 +52,7 @@ $mat-list-item-inset-divider-offset: 72px; flex-direction: row; align-items: center; box-sizing: border-box; - padding: 0 $mat-list-side-padding; + padding: 0 $side-padding; position: relative; height: inherit; } @@ -61,13 +60,13 @@ $mat-list-item-inset-divider-offset: 72px; .mat-list-item-content-reverse { display: flex; align-items: center; - padding: 0 $mat-list-side-padding; + padding: 0 $side-padding; flex-direction: row-reverse; justify-content: space-around; } .mat-list-item-ripple { - @include mat-fill; + @include layout-common.fill; // Disable pointer events for the ripple container because the container will overlay the // user content and we don't want to disable mouse events on the user content. @@ -100,7 +99,7 @@ $mat-list-item-inset-divider-offset: 72px; } .mat-list-text { - @include mat-line-wrapper-base(); + @include list-common.wrapper-base(); // By default, there will be no padding for the list item text because the padding is already // set on the `mat-list-item-content` element. Later, if the list-item detects that there are @@ -112,10 +111,10 @@ $mat-list-item-inset-divider-offset: 72px; &.mat-list-option { .mat-list-item-content .mat-list-text { padding-right: 0; - padding-left: $mat-list-side-padding; + padding-left: $side-padding; [dir='rtl'] & { - padding-right: $mat-list-side-padding; + padding-right: $side-padding; padding-left: 0; } } @@ -125,11 +124,11 @@ $mat-list-item-inset-divider-offset: 72px; // option, there needs to be a padding for the mat-list-text on the end-side. .mat-list-item-content-reverse .mat-list-text { padding-left: 0; - padding-right: $mat-list-side-padding; + padding-right: $side-padding; [dir='rtl'] & { padding-right: 0; - padding-left: $mat-list-side-padding; + padding-left: $side-padding; } } } @@ -137,8 +136,8 @@ $mat-list-item-inset-divider-offset: 72px; &.mat-list-item-with-avatar.mat-list-option { .mat-list-item-content-reverse .mat-list-text, .mat-list-item-content .mat-list-text { - padding-right: $mat-list-side-padding; - padding-left: $mat-list-side-padding; + padding-right: $side-padding; + padding-left: $side-padding; } } @@ -153,7 +152,7 @@ $mat-list-item-inset-divider-offset: 72px; object-fit: cover; ~ .mat-divider-inset { - @include mat-inset-divider-offset($avatar-size, $mat-list-side-padding); + @include divider-offset.inset-divider-offset($avatar-size, $side-padding); } } @@ -164,11 +163,11 @@ $mat-list-item-inset-divider-offset: 72px; font-size: $icon-size; box-sizing: content-box; border-radius: 50%; - padding: $mat-list-icon-padding; + padding: $icon-padding; ~ .mat-divider-inset { - @include mat-inset-divider-offset($icon-size + (2 * $mat-list-icon-padding), - $mat-list-side-padding); + @include divider-offset.inset-divider-offset($icon-size + (2 * $icon-padding), + $side-padding); } } @@ -193,7 +192,7 @@ $mat-list-item-inset-divider-offset: 72px; .mat-subheader { display: flex; box-sizing: border-box; - padding: $mat-list-side-padding; + padding: $side-padding; align-items: center; // This needs slightly more specificity, because it @@ -204,9 +203,9 @@ $mat-list-item-inset-divider-offset: 72px; } // This mixin adjusts the heights and padding based on whether the list is in dense mode. -@mixin mat-subheader-spacing($top-padding, $base-height) { +@mixin subheader-spacing($top-padding, $base-height) { height: $base-height; - line-height: $base-height - $mat-list-side-padding * 2; + line-height: $base-height - $side-padding * 2; &:first-child { margin-top: -$top-padding; @@ -214,45 +213,45 @@ $mat-list-item-inset-divider-offset: 72px; } .mat-list-base { - padding-top: $mat-list-top-padding; + padding-top: $top-padding; display: block; -webkit-tap-highlight-color: transparent; .mat-subheader { - @include mat-subheader-spacing($mat-list-top-padding, $mat-list-base-height); + @include subheader-spacing($top-padding, $base-height); } .mat-list-item, .mat-list-option { - @include mat-list-item-base( - $mat-list-base-height, - $mat-list-avatar-height, - $mat-list-two-line-height, - $mat-list-three-line-height, - $mat-list-multi-line-padding, - $mat-list-icon-size, - $mat-list-avatar-size + @include item-base( + $base-height, + $avatar-height, + $two-line-height, + $three-line-height, + $multi-line-padding, + $icon-size, + $avatar-size ); } } .mat-list-base[dense] { - padding-top: $mat-dense-top-padding; + padding-top: $dense-top-padding; display: block; .mat-subheader { - @include mat-subheader-spacing($mat-dense-top-padding, $mat-dense-base-height); + @include subheader-spacing($dense-top-padding, $dense-base-height); } .mat-list-item, .mat-list-option { - @include mat-list-item-base( - $mat-dense-base-height, - $mat-dense-avatar-height, - $mat-dense-two-line-height, - $mat-dense-three-line-height, - $mat-dense-multi-line-padding, - $mat-dense-list-icon-size, - $mat-dense-avatar-size + @include item-base( + $dense-base-height, + $dense-avatar-height, + $dense-two-line-height, + $dense-three-line-height, + $dense-multi-line-padding, + $dense-list-icon-size, + $dense-avatar-size ); } } @@ -305,12 +304,12 @@ mat-action-list { // Since we can't use a color to indicate that the list // item is disabled, we have to use opacity instead. - @include cdk-high-contrast { + @include a11y.high-contrast { opacity: 0.5; } } -@include cdk-high-contrast(active, off) { +@include a11y.high-contrast(active, off) { .mat-selection-list:focus { outline-style: dotted; } @@ -320,6 +319,7 @@ mat-action-list { mat-action-list .mat-list-item { &:hover, &:focus { outline: dotted 1px; + z-index: 1; } } @@ -331,7 +331,7 @@ mat-action-list { content: ''; position: absolute; top: 50%; - right: $mat-list-side-padding; + right: $side-padding; transform: translateY(-50%); width: $size; height: 0; @@ -341,7 +341,7 @@ mat-action-list { [dir='rtl'] .mat-list-single-selected-option::after { right: auto; - left: $mat-list-side-padding; + left: $side-padding; } } diff --git a/src/material/list/list.spec.ts b/src/material/list/list.spec.ts index fd948a3862d6..0d85de214d98 100644 --- a/src/material/list/list.spec.ts +++ b/src/material/list/list.spec.ts @@ -1,7 +1,7 @@ import {waitForAsync, TestBed, fakeAsync, tick} from '@angular/core/testing'; import {Component, QueryList, ViewChildren} from '@angular/core'; import {defaultRippleAnimationConfig} from '@angular/material/core'; -import {dispatchMouseEvent} from '@angular/cdk/testing/private'; +import {dispatchMouseEvent} from '../../cdk/testing/private'; import {By} from '@angular/platform-browser'; import {MatListItem, MatListModule} from './index'; @@ -9,19 +9,30 @@ describe('MatList', () => { // Default ripple durations used for testing. const {enterDuration, exitDuration} = defaultRippleAnimationConfig; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatListModule], - declarations: [ - ListWithOneAnchorItem, ListWithOneItem, ListWithTwoLineItem, ListWithThreeLineItem, - ListWithAvatar, ListWithItemWithCssClass, ListWithDynamicNumberOfLines, - ListWithMultipleItems, ListWithManyLines, NavListWithOneAnchorItem, ActionListWithoutType, - ActionListWithType, ListWithIndirectDescendantLines, ListWithDisabledItems, - ], - }); - - TestBed.compileComponents(); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatListModule], + declarations: [ + ListWithOneAnchorItem, + ListWithOneItem, + ListWithTwoLineItem, + ListWithThreeLineItem, + ListWithAvatar, + ListWithItemWithCssClass, + ListWithDynamicNumberOfLines, + ListWithMultipleItems, + ListWithManyLines, + NavListWithOneAnchorItem, + ActionListWithoutType, + ActionListWithType, + ListWithDisabledItems, + ], + }); + + TestBed.compileComponents(); + }), + ); it('should not apply any additional class to a list without lines', () => { const fixture = TestBed.createComponent(ListWithOneItem); @@ -100,8 +111,12 @@ describe('MatList', () => { const list = fixture.debugElement.children[0]; const listItem = fixture.debugElement.children[0].query(By.css('mat-list-item'))!; - expect(list.nativeElement.getAttribute('role')).toBeNull('Expect mat-list no role'); - expect(listItem.nativeElement.getAttribute('role')).toBeNull('Expect mat-list-item no role'); + expect(list.nativeElement.getAttribute('role')) + .withContext('Expect mat-list no role') + .toBeNull(); + expect(listItem.nativeElement.getAttribute('role')) + .withContext('Expect mat-list-item no role') + .toBeNull(); }); it('should not show ripples for non-nav lists', () => { @@ -215,94 +230,94 @@ describe('MatList', () => { expect(items.every(item => item._isRippleDisabled())).toBe(true); }); - it('should disable item ripples when list ripples are disabled via the input in nav list', - fakeAsync(() => { - const fixture = TestBed.createComponent(NavListWithOneAnchorItem); - fixture.detectChanges(); - - const rippleTarget = fixture.nativeElement.querySelector('.mat-list-item-content'); - - dispatchMouseEvent(rippleTarget, 'mousedown'); - dispatchMouseEvent(rippleTarget, 'mouseup'); - - expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) - .toBe(1, 'Expected ripples to be enabled by default.'); - - // Wait for the ripples to go away. - tick(enterDuration + exitDuration); - expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) - .toBe(0, 'Expected ripples to go away.'); + it('should disable item ripples when list ripples are disabled via the input in nav list', fakeAsync(() => { + const fixture = TestBed.createComponent(NavListWithOneAnchorItem); + fixture.detectChanges(); - fixture.componentInstance.disableListRipple = true; - fixture.detectChanges(); + const rippleTarget = fixture.nativeElement.querySelector('.mat-list-item-content'); - dispatchMouseEvent(rippleTarget, 'mousedown'); - dispatchMouseEvent(rippleTarget, 'mouseup'); + dispatchMouseEvent(rippleTarget, 'mousedown'); + dispatchMouseEvent(rippleTarget, 'mouseup'); - expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) - .toBe(0, 'Expected no ripples after list ripples are disabled.'); - })); + expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) + .withContext('Expected ripples to be enabled by default.') + .toBe(1); - it('should disable item ripples when list ripples are disabled via the input in an action list', - fakeAsync(() => { - const fixture = TestBed.createComponent(ActionListWithoutType); - fixture.detectChanges(); + // Wait for the ripples to go away. + tick(enterDuration + exitDuration); + expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) + .withContext('Expected ripples to go away.') + .toBe(0); - const rippleTarget = fixture.nativeElement.querySelector('.mat-list-item-content'); + fixture.componentInstance.disableListRipple = true; + fixture.detectChanges(); - dispatchMouseEvent(rippleTarget, 'mousedown'); - dispatchMouseEvent(rippleTarget, 'mouseup'); + dispatchMouseEvent(rippleTarget, 'mousedown'); + dispatchMouseEvent(rippleTarget, 'mouseup'); - expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) - .toBe(1, 'Expected ripples to be enabled by default.'); + expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) + .withContext('Expected no ripples after list ripples are disabled.') + .toBe(0); + })); - // Wait for the ripples to go away. - tick(enterDuration + exitDuration); - expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) - .toBe(0, 'Expected ripples to go away.'); + it('should disable item ripples when list ripples are disabled via the input in an action list', fakeAsync(() => { + const fixture = TestBed.createComponent(ActionListWithoutType); + fixture.detectChanges(); - fixture.componentInstance.disableListRipple = true; - fixture.detectChanges(); + const rippleTarget = fixture.nativeElement.querySelector('.mat-list-item-content'); - dispatchMouseEvent(rippleTarget, 'mousedown'); - dispatchMouseEvent(rippleTarget, 'mouseup'); + dispatchMouseEvent(rippleTarget, 'mousedown'); + dispatchMouseEvent(rippleTarget, 'mouseup'); - expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) - .toBe(0, 'Expected no ripples after list ripples are disabled.'); - })); + expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) + .withContext('Expected ripples to be enabled by default.') + .toBe(1); + // Wait for the ripples to go away. + tick(enterDuration + exitDuration); + expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) + .withContext('Expected ripples to go away.') + .toBe(0); - it('should pick up indirect descendant lines', () => { - const fixture = TestBed.createComponent(ListWithIndirectDescendantLines); + fixture.componentInstance.disableListRipple = true; fixture.detectChanges(); - const listItems = fixture.debugElement.children[0].queryAll(By.css('mat-list-item')); - expect(listItems[0].nativeElement.className).toContain('mat-2-line'); - expect(listItems[1].nativeElement.className).toContain('mat-2-line'); - }); + dispatchMouseEvent(rippleTarget, 'mousedown'); + dispatchMouseEvent(rippleTarget, 'mouseup'); + + expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) + .withContext('Expected no ripples after list ripples are disabled.') + .toBe(0); + })); it('should be able to disable a single list item', () => { const fixture = TestBed.createComponent(ListWithDisabledItems); - const listItems: HTMLElement[] = - Array.from(fixture.nativeElement.querySelectorAll('mat-list-item')); + const listItems: HTMLElement[] = Array.from( + fixture.nativeElement.querySelectorAll('mat-list-item'), + ); fixture.detectChanges(); - expect(listItems.map(item => { - return item.classList.contains('mat-list-item-disabled'); - })).toEqual([false, false, false]); + expect( + listItems.map(item => { + return item.classList.contains('mat-list-item-disabled'); + }), + ).toEqual([false, false, false]); fixture.componentInstance.firstItemDisabled = true; fixture.detectChanges(); - expect(listItems.map(item => { - return item.classList.contains('mat-list-item-disabled'); - })).toEqual([true, false, false]); + expect( + listItems.map(item => { + return item.classList.contains('mat-list-item-disabled'); + }), + ).toEqual([true, false, false]); }); it('should be able to disable the entire list', () => { const fixture = TestBed.createComponent(ListWithDisabledItems); - const listItems: HTMLElement[] = - Array.from(fixture.nativeElement.querySelectorAll('mat-list-item')); + const listItems: HTMLElement[] = Array.from( + fixture.nativeElement.querySelectorAll('mat-list-item'), + ); fixture.detectChanges(); expect(listItems.every(item => item.classList.contains('mat-list-item-disabled'))).toBe(false); @@ -312,93 +327,107 @@ describe('MatList', () => { expect(listItems.every(item => item.classList.contains('mat-list-item-disabled'))).toBe(true); }); - }); class BaseTestList { items: any[] = [ {'name': 'Paprika', 'description': 'A seasoning'}, - {'name': 'Pepper', 'description': 'Another seasoning'} + {'name': 'Pepper', 'description': 'Another seasoning'}, ]; showThirdLine: boolean = false; } -@Component({template: ` +@Component({ + template: ` Paprika - `}) + `, +}) class ListWithOneAnchorItem extends BaseTestList { // This needs to be declared directly on the class; if declared on the BaseTestList superclass, // it doesn't get populated. @ViewChildren(MatListItem) listItems: QueryList; } -@Component({template: ` +@Component({ + template: ` Paprika - `}) + `, +}) class NavListWithOneAnchorItem extends BaseTestList { @ViewChildren(MatListItem) listItems: QueryList; disableItemRipple: boolean = false; disableListRipple: boolean = false; } -@Component({template: ` +@Component({ + template: ` - `}) + `, +}) class ActionListWithoutType extends BaseTestList { @ViewChildren(MatListItem) listItems: QueryList; disableListRipple = false; disableItemRipple = false; } -@Component({template: ` +@Component({ + template: ` - `}) + `, +}) class ActionListWithType extends BaseTestList { @ViewChildren(MatListItem) listItems: QueryList; } -@Component({template: ` +@Component({ + template: ` Paprika - `}) -class ListWithOneItem extends BaseTestList { } + `, +}) +class ListWithOneItem extends BaseTestList {} -@Component({template: ` +@Component({ + template: `

{{item.name}}

{{item.description}}

-
`}) -class ListWithTwoLineItem extends BaseTestList { } + `, +}) +class ListWithTwoLineItem extends BaseTestList {} -@Component({template: ` +@Component({ + template: `

{{item.name}}

{{item.description}}

Some other text

-
`}) -class ListWithThreeLineItem extends BaseTestList { } + `, +}) +class ListWithThreeLineItem extends BaseTestList {} -@Component({template: ` +@Component({ + template: `

Line 1

@@ -406,10 +435,12 @@ class ListWithThreeLineItem extends BaseTestList { }

Line 3

Line 4

-
`}) -class ListWithManyLines extends BaseTestList { } + `, +}) +class ListWithManyLines extends BaseTestList {} -@Component({template: ` +@Component({ + template: ` @@ -418,58 +449,51 @@ class ListWithManyLines extends BaseTestList { } Pepper - `}) -class ListWithAvatar extends BaseTestList { } + `, +}) +class ListWithAvatar extends BaseTestList {} -@Component({template: ` +@Component({ + template: `

{{item.name}}

{{item.description}}

-
`}) -class ListWithItemWithCssClass extends BaseTestList { } + `, +}) +class ListWithItemWithCssClass extends BaseTestList {} -@Component({template: ` +@Component({ + template: `

{{item.name}}

{{item.description}}

Some other text

-
`}) -class ListWithDynamicNumberOfLines extends BaseTestList { } - -@Component({template: ` - - - {{item.name}} - - `}) -class ListWithMultipleItems extends BaseTestList { } + `, +}) +class ListWithDynamicNumberOfLines extends BaseTestList {} -// Note the blank `ngSwitch` which we need in order to hit the bug that we're testing. @Component({ template: ` - -

{{item.name}}

-

{{item.description}}

-
+ {{item.name}}
-
` + `, }) -class ListWithIndirectDescendantLines extends BaseTestList { -} +class ListWithMultipleItems extends BaseTestList {} - -@Component({template: ` +@Component({ + template: ` One Two Three - `}) + `, +}) class ListWithDisabledItems { firstItemDisabled = false; listDisabled = false; diff --git a/src/material/list/list.ts b/src/material/list/list.ts index 45bd8538687e..4c54050a5405 100644 --- a/src/material/list/list.ts +++ b/src/material/list/list.ts @@ -27,9 +27,7 @@ import { } from '@angular/core'; import { CanDisable, - CanDisableCtor, CanDisableRipple, - CanDisableRippleCtor, MatLine, setLines, mixinDisableRipple, @@ -40,15 +38,11 @@ import {takeUntil} from 'rxjs/operators'; // Boilerplate for applying mixins to MatList. /** @docs-private */ -class MatListBase {} -const _MatListMixinBase: CanDisableRippleCtor & CanDisableCtor & typeof MatListBase = - mixinDisabled(mixinDisableRipple(MatListBase)); +const _MatListBase = mixinDisabled(mixinDisableRipple(class {})); // Boilerplate for applying mixins to MatListItem. /** @docs-private */ -class MatListItemBase {} -const _MatListItemMixinBase: CanDisableRippleCtor & typeof MatListItemBase = - mixinDisableRipple(MatListItemBase); +const _MatListItemMixinBase = mixinDisableRipple(class {}); /** * Injection token that can be used to inject instances of `MatList`. It serves as @@ -69,7 +63,7 @@ export const MAT_NAV_LIST = new InjectionToken('MatNavList'); exportAs: 'matNavList', host: { 'role': 'navigation', - 'class': 'mat-nav-list mat-list-base' + 'class': 'mat-nav-list mat-list-base', }, templateUrl: 'list.html', styleUrls: ['list.css'], @@ -78,10 +72,12 @@ export const MAT_NAV_LIST = new InjectionToken('MatNavList'); changeDetection: ChangeDetectionStrategy.OnPush, providers: [{provide: MAT_NAV_LIST, useExisting: MatNavList}], }) -export class MatNavList extends _MatListMixinBase implements CanDisable, CanDisableRipple, - OnChanges, OnDestroy { +export class MatNavList + extends _MatListBase + implements CanDisable, CanDisableRipple, OnChanges, OnDestroy +{ /** Emits when the state of the list changes. */ - _stateChanges = new Subject(); + readonly _stateChanges = new Subject(); ngOnChanges() { this._stateChanges.next(); @@ -90,9 +86,6 @@ export class MatNavList extends _MatListMixinBase implements CanDisable, CanDisa ngOnDestroy() { this._stateChanges.complete(); } - - static ngAcceptInputType_disableRipple: BooleanInput; - static ngAcceptInputType_disabled: BooleanInput; } @Component({ @@ -100,7 +93,7 @@ export class MatNavList extends _MatListMixinBase implements CanDisable, CanDisa exportAs: 'matList', templateUrl: 'list.html', host: { - 'class': 'mat-list mat-list-base' + 'class': 'mat-list mat-list-base', }, styleUrls: ['list.css'], inputs: ['disableRipple', 'disabled'], @@ -108,10 +101,12 @@ export class MatNavList extends _MatListMixinBase implements CanDisable, CanDisa changeDetection: ChangeDetectionStrategy.OnPush, providers: [{provide: MAT_LIST, useExisting: MatList}], }) -export class MatList extends _MatListMixinBase implements CanDisable, CanDisableRipple, OnChanges, - OnDestroy { +export class MatList + extends _MatListBase + implements CanDisable, CanDisableRipple, OnChanges, OnDestroy +{ /** Emits when the state of the list changes. */ - _stateChanges = new Subject(); + readonly _stateChanges = new Subject(); constructor(private _elementRef: ElementRef) { super(); @@ -142,9 +137,6 @@ export class MatList extends _MatListMixinBase implements CanDisable, CanDisable ngOnDestroy() { this._stateChanges.complete(); } - - static ngAcceptInputType_disableRipple: BooleanInput; - static ngAcceptInputType_disabled: BooleanInput; } /** @@ -153,7 +145,7 @@ export class MatList extends _MatListMixinBase implements CanDisable, CanDisable */ @Directive({ selector: '[mat-list-avatar], [matListAvatar]', - host: {'class': 'mat-list-avatar'} + host: {'class': 'mat-list-avatar'}, }) export class MatListAvatarCssMatStyler {} @@ -163,7 +155,7 @@ export class MatListAvatarCssMatStyler {} */ @Directive({ selector: '[mat-list-icon], [matListIcon]', - host: {'class': 'mat-list-icon'} + host: {'class': 'mat-list-icon'}, }) export class MatListIconCssMatStyler {} @@ -173,7 +165,7 @@ export class MatListIconCssMatStyler {} */ @Directive({ selector: '[mat-subheader], [matSubheader]', - host: {'class': 'mat-subheader'} + host: {'class': 'mat-subheader'}, }) export class MatListSubheaderCssMatStyler {} @@ -193,20 +185,24 @@ export class MatListSubheaderCssMatStyler {} encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) -export class MatListItem extends _MatListItemMixinBase implements AfterContentInit, - CanDisableRipple, OnDestroy { +export class MatListItem + extends _MatListItemMixinBase + implements AfterContentInit, CanDisableRipple, OnDestroy +{ private _isInteractiveList: boolean = false; private _list?: MatNavList | MatList; - private _destroyed = new Subject(); + private readonly _destroyed = new Subject(); @ContentChildren(MatLine, {descendants: true}) _lines: QueryList; @ContentChild(MatListAvatarCssMatStyler) _avatar: MatListAvatarCssMatStyler; @ContentChild(MatListIconCssMatStyler) _icon: MatListIconCssMatStyler; - constructor(private _element: ElementRef, - _changeDetectorRef: ChangeDetectorRef, - @Optional() @Inject(MAT_NAV_LIST) navList?: MatNavList, - @Optional() @Inject(MAT_LIST) list?: MatList) { + constructor( + private _element: ElementRef, + _changeDetectorRef: ChangeDetectorRef, + @Optional() @Inject(MAT_NAV_LIST) navList?: MatNavList, + @Optional() @Inject(MAT_LIST) list?: MatList, + ) { super(); this._isInteractiveList = !!(navList || (list && list._getListType() === 'action-list')); this._list = navList || list; @@ -230,8 +226,10 @@ export class MatListItem extends _MatListItemMixinBase implements AfterContentIn /** Whether the option is disabled. */ @Input() - get disabled() { return this._disabled || !!(this._list && this._list.disabled); } - set disabled(value: boolean) { + get disabled(): boolean { + return this._disabled || !!(this._list && this._list.disabled); + } + set disabled(value: BooleanInput) { this._disabled = coerceBooleanProperty(value); } private _disabled = false; @@ -247,15 +245,13 @@ export class MatListItem extends _MatListItemMixinBase implements AfterContentIn /** Whether this list item should show a ripple effect when clicked. */ _isRippleDisabled() { - return !this._isInteractiveList || this.disableRipple || - !!(this._list && this._list.disableRipple); + return ( + !this._isInteractiveList || this.disableRipple || !!(this._list && this._list.disableRipple) + ); } /** Retrieves the DOM element of the component host. */ _getHostElement(): HTMLElement { return this._element.nativeElement; } - - static ngAcceptInputType_disableRipple: BooleanInput; - static ngAcceptInputType_disabled: BooleanInput; } diff --git a/src/material/list/public-api.ts b/src/material/list/public-api.ts index 294c4d765b7b..48e73ad07f08 100644 --- a/src/material/list/public-api.ts +++ b/src/material/list/public-api.ts @@ -9,4 +9,3 @@ export * from './list-module'; export * from './list'; export * from './selection-list'; - diff --git a/src/material/list/selection-list.spec.ts b/src/material/list/selection-list.spec.ts index 270368ba7c71..99b05a308cbf 100644 --- a/src/material/list/selection-list.spec.ts +++ b/src/material/list/selection-list.spec.ts @@ -5,7 +5,7 @@ import { dispatchEvent, dispatchKeyboardEvent, dispatchMouseEvent, -} from '@angular/cdk/testing/private'; +} from '../../cdk/testing/private'; import { Component, DebugElement, @@ -24,12 +24,7 @@ import { } from '@angular/core/testing'; import {MatRipple, defaultRippleAnimationConfig, ThemePalette} from '@angular/material/core'; import {By} from '@angular/platform-browser'; -import { - MatListModule, - MatListOption, - MatSelectionList, - MatSelectionListChange -} from './index'; +import {MatListModule, MatListOption, MatSelectionList, MatSelectionListChange} from './index'; import {FormControl, FormsModule, NgModel, ReactiveFormsModule} from '@angular/forms'; import {FocusMonitor} from '@angular/cdk/a11y'; @@ -39,31 +34,33 @@ describe('MatSelectionList without forms', () => { let listOptions: DebugElement[]; let selectionList: DebugElement; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatListModule], - declarations: [ - SelectionListWithListOptions, - SelectionListWithCheckboxPositionAfter, - SelectionListWithListDisabled, - SelectionListWithOnlyOneOption, - SelectionListWithIndirectChildOptions, - SelectionListWithSelectedOptionAndValue, - SelectionListWithIndirectDescendantLines, - ], - }); - - TestBed.compileComponents(); - })); - - - beforeEach(waitForAsync(() => { - fixture = TestBed.createComponent(SelectionListWithListOptions); - fixture.detectChanges(); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatListModule], + declarations: [ + SelectionListWithListOptions, + SelectionListWithCheckboxPositionAfter, + SelectionListWithListDisabled, + SelectionListWithOnlyOneOption, + SelectionListWithIndirectChildOptions, + SelectionListWithSelectedOptionAndValue, + ], + }); + + TestBed.compileComponents(); + }), + ); + + beforeEach( + waitForAsync(() => { + fixture = TestBed.createComponent(SelectionListWithListOptions); + fixture.detectChanges(); - listOptions = fixture.debugElement.queryAll(By.directive(MatListOption)); - selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!; - })); + listOptions = fixture.debugElement.queryAll(By.directive(MatListOption)); + selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!; + }), + ); it('should be able to set a value on a list option', () => { const optionValues = ['inbox', 'starred', 'sent-mail', 'archive', 'drafts']; @@ -98,7 +95,7 @@ describe('MatSelectionList without forms', () => { it('should be able to dispatch one selected item', () => { let testListItem = listOptions[2].injector.get(MatListOption); let selectList = - selectionList.injector.get(MatSelectionList).selectedOptions; + selectionList.injector.get(MatSelectionList).selectedOptions; expect(selectList.selected.length).toBe(0); expect(listOptions[2].nativeElement.getAttribute('aria-selected')).toBe('false'); @@ -115,7 +112,7 @@ describe('MatSelectionList without forms', () => { let testListItem = listOptions[2].injector.get(MatListOption); let testListItem2 = listOptions[1].injector.get(MatListOption); let selectList = - selectionList.injector.get(MatSelectionList).selectedOptions; + selectionList.injector.get(MatSelectionList).selectedOptions; expect(selectList.selected.length).toBe(0); expect(listOptions[2].nativeElement.getAttribute('aria-selected')).toBe('false'); @@ -137,19 +134,23 @@ describe('MatSelectionList without forms', () => { it('should be able to specify a color for list options', () => { const optionNativeElements = listOptions.map(option => option.nativeElement); - expect(optionNativeElements.every(option => !option.classList.contains('mat-primary'))) - .toBe(true); - expect(optionNativeElements.every(option => !option.classList.contains('mat-warn'))) - .toBe(true); + expect(optionNativeElements.every(option => !option.classList.contains('mat-primary'))).toBe( + true, + ); + expect(optionNativeElements.every(option => !option.classList.contains('mat-warn'))).toBe( + true, + ); // All options will be set to the "warn" color. fixture.componentInstance.selectionListColor = 'warn'; fixture.detectChanges(); - expect(optionNativeElements.every(option => !option.classList.contains('mat-primary'))) - .toBe(true); - expect(optionNativeElements.every(option => option.classList.contains('mat-warn'))) - .toBe(true); + expect(optionNativeElements.every(option => !option.classList.contains('mat-primary'))).toBe( + true, + ); + expect(optionNativeElements.every(option => option.classList.contains('mat-warn'))).toBe( + true, + ); // Color will be set explicitly for an option and should take precedence. fixture.componentInstance.firstOptionColor = 'primary'; @@ -157,8 +158,9 @@ describe('MatSelectionList without forms', () => { expect(optionNativeElements[0].classList).toContain('mat-primary'); expect(optionNativeElements[0].classList).not.toContain('mat-warn'); - expect(optionNativeElements.slice(1).every(option => option.classList.contains('mat-warn'))) - .toBe(true); + expect( + optionNativeElements.slice(1).every(option => option.classList.contains('mat-warn')), + ).toBe(true); }); it('should explicitly set the `accent` color', () => { @@ -182,7 +184,7 @@ describe('MatSelectionList without forms', () => { it('should be able to deselect an option', () => { let testListItem = listOptions[2].injector.get(MatListOption); let selectList = - selectionList.injector.get(MatSelectionList).selectedOptions; + selectionList.injector.get(MatSelectionList).selectedOptions; expect(selectList.selected.length).toBe(0); @@ -203,14 +205,15 @@ describe('MatSelectionList without forms', () => { testListItem._handleClick(); fixture.detectChanges(); - expect(listOptions[2].nativeElement.classList.contains('mat-list-single-selected-option')) - .toBe(false); + expect( + listOptions[2].nativeElement.classList.contains('mat-list-single-selected-option'), + ).toBe(false); }); it('should not allow selection of disabled items', () => { let testListItem = listOptions[0].injector.get(MatListOption); let selectList = - selectionList.injector.get(MatSelectionList).selectedOptions; + selectionList.injector.get(MatSelectionList).selectedOptions; expect(selectList.selected.length).toBe(0); expect(listOptions[0].nativeElement.getAttribute('aria-disabled')).toBe('true'); @@ -236,7 +239,7 @@ describe('MatSelectionList without forms', () => { const testListItem = listOptions[1].nativeElement as HTMLElement; const SPACE_EVENT = createKeyboardEvent('keydown', SPACE); const selectList = - selectionList.injector.get(MatSelectionList).selectedOptions; + selectionList.injector.get(MatSelectionList).selectedOptions; expect(selectList.selected.length).toBe(0); dispatchFakeEvent(testListItem, 'focus'); @@ -252,7 +255,7 @@ describe('MatSelectionList without forms', () => { const testListItem = listOptions[1].nativeElement as HTMLElement; const ENTER_EVENT = createKeyboardEvent('keydown', ENTER); const selectList = - selectionList.injector.get(MatSelectionList).selectedOptions; + selectionList.injector.get(MatSelectionList).selectedOptions; expect(selectList.selected.length).toBe(0); dispatchFakeEvent(testListItem, 'focus'); @@ -267,7 +270,7 @@ describe('MatSelectionList without forms', () => { it('should not be able to toggle an item when pressing a modifier key', () => { const testListItem = listOptions[1].nativeElement as HTMLElement; const selectList = - selectionList.injector.get(MatSelectionList).selectedOptions; + selectionList.injector.get(MatSelectionList).selectedOptions; expect(selectList.selected.length).toBe(0); @@ -311,8 +314,8 @@ describe('MatSelectionList without forms', () => { expect(listOptions[0].componentInstance.focus).toHaveBeenCalled(); }); - it('should not move focus to the first item if focus originated from a mouse interaction', - fakeAsync(inject([FocusMonitor], (focusMonitor: FocusMonitor) => { + it('should not move focus to the first item if focus originated from a mouse interaction', fakeAsync( + inject([FocusMonitor], (focusMonitor: FocusMonitor) => { spyOn(listOptions[0].componentInstance, 'focus').and.callThrough(); const manager = selectionList.componentInstance._keyManager; @@ -324,36 +327,40 @@ describe('MatSelectionList without forms', () => { expect(manager.activeItemIndex).toBe(-1); expect(listOptions[0].componentInstance.focus).not.toHaveBeenCalled(); - }))); + }), + )); - it('should focus the previously focused option when the list takes focus a second time', () => { - spyOn(listOptions[1].componentInstance, 'focus').and.callThrough(); + it('should focus the first selected option when list receives focus', () => { + spyOn(listOptions[2].componentInstance, 'focus').and.callThrough(); const manager = selectionList.componentInstance._keyManager; expect(manager.activeItemIndex).toBe(-1); - // Focus and blur the option to move the active item index. This option is now the previously - // focused option. - listOptions[1].componentInstance._handleFocus(); - listOptions[1].componentInstance._handleBlur(); + dispatchMouseEvent(listOptions[2].nativeElement, 'click'); + fixture.detectChanges(); + + dispatchMouseEvent(listOptions[3].nativeElement, 'click'); + fixture.detectChanges(); dispatchFakeEvent(selectionList.nativeElement, 'focus'); fixture.detectChanges(); - expect(manager.activeItemIndex).toBe(1); - expect(listOptions[1].componentInstance.focus).toHaveBeenCalled(); + expect(manager.activeItemIndex).toBe(2); + expect(listOptions[2].componentInstance.focus).toHaveBeenCalled(); }); it('should allow focus to escape when tabbing away', fakeAsync(() => { selectionList.componentInstance._keyManager.onKeydown(createKeyboardEvent('keydown', TAB)); expect(selectionList.componentInstance._tabIndex) - .toBe(-1, 'Expected tabIndex to be set to -1 temporarily.'); + .withContext('Expected tabIndex to be set to -1 temporarily.') + .toBe(-1); tick(); expect(selectionList.componentInstance._tabIndex) - .toBe(0, 'Expected tabIndex to be reset back to 0'); + .withContext('Expected tabIndex to be reset back to 0') + .toBe(0); })); it('should restore focus if active option is destroyed', () => { @@ -371,24 +378,23 @@ describe('MatSelectionList without forms', () => { expect(listOptions[3].componentInstance.focus).toHaveBeenCalled(); }); - it('should not attempt to focus the next option when the destroyed option was not focused', - () => { - const manager = selectionList.componentInstance._keyManager; + it('should not attempt to focus the next option when the destroyed option was not focused', () => { + const manager = selectionList.componentInstance._keyManager; - // Focus and blur the option to move the active item index. - listOptions[4].componentInstance._handleFocus(); - listOptions[4].componentInstance._handleBlur(); + // Focus and blur the option to move the active item index. + listOptions[4].componentInstance._handleFocus(); + listOptions[4].componentInstance._handleBlur(); - spyOn(listOptions[3].componentInstance, 'focus').and.callThrough(); + spyOn(listOptions[3].componentInstance, 'focus').and.callThrough(); - expect(manager.activeItemIndex).toBe(4); + expect(manager.activeItemIndex).toBe(4); - fixture.componentInstance.showLastOption = false; - fixture.detectChanges(); + fixture.componentInstance.showLastOption = false; + fixture.detectChanges(); - expect(manager.activeItemIndex).toBe(3); - expect(listOptions[3].componentInstance.focus).not.toHaveBeenCalled(); - }); + expect(manager.activeItemIndex).toBe(3); + expect(listOptions[3].componentInstance.focus).not.toHaveBeenCalled(); + }); it('should focus previous item when press UP ARROW', () => { let UP_EVENT = createKeyboardEvent('keydown', UP_ARROW); @@ -511,7 +517,7 @@ describe('MatSelectionList without forms', () => { }); it('should select all items using ctrl + a', () => { - listOptions.forEach(option => option.componentInstance.disabled = false); + listOptions.forEach(option => (option.componentInstance.disabled = false)); const event = createKeyboardEvent('keydown', A, undefined, {control: true}); expect(listOptions.some(option => option.componentInstance.selected)).toBe(false); @@ -525,23 +531,33 @@ describe('MatSelectionList without forms', () => { it('should not select disabled items when pressing ctrl + a', () => { const event = createKeyboardEvent('keydown', A, undefined, {control: true}); - listOptions.slice(0, 2).forEach(option => option.componentInstance.disabled = true); + listOptions.slice(0, 2).forEach(option => (option.componentInstance.disabled = true)); fixture.detectChanges(); - expect(listOptions.map(option => option.componentInstance.selected)) - .toEqual([false, false, false, false, false]); + expect(listOptions.map(option => option.componentInstance.selected)).toEqual([ + false, + false, + false, + false, + false, + ]); dispatchEvent(selectionList.nativeElement, event); fixture.detectChanges(); - expect(listOptions.map(option => option.componentInstance.selected)) - .toEqual([false, false, true, true, true]); + expect(listOptions.map(option => option.componentInstance.selected)).toEqual([ + false, + false, + true, + true, + true, + ]); }); it('should select all items using ctrl + a if some items are selected', () => { const event = createKeyboardEvent('keydown', A, undefined, {control: true}); - listOptions.slice(0, 2).forEach(option => option.componentInstance.selected = true); + listOptions.slice(0, 2).forEach(option => (option.componentInstance.selected = true)); fixture.detectChanges(); expect(listOptions.some(option => option.componentInstance.selected)).toBe(true); @@ -555,7 +571,7 @@ describe('MatSelectionList without forms', () => { it('should deselect all with ctrl + a if all options are selected', () => { const event = createKeyboardEvent('keydown', A, undefined, {control: true}); - listOptions.forEach(option => option.componentInstance.selected = true); + listOptions.forEach(option => (option.componentInstance.selected = true)); fixture.detectChanges(); expect(listOptions.every(option => option.componentInstance.selected)).toBe(true); @@ -568,16 +584,18 @@ describe('MatSelectionList without forms', () => { it('should dispatch the selectionChange event when selecting via ctrl + a', () => { const spy = spyOn(fixture.componentInstance, 'onSelectionChange'); - listOptions.forEach(option => option.componentInstance.disabled = false); + listOptions.forEach(option => (option.componentInstance.disabled = false)); const event = createKeyboardEvent('keydown', A, undefined, {control: true}); dispatchEvent(selectionList.nativeElement, event); fixture.detectChanges(); expect(spy).toHaveBeenCalledTimes(1); - expect(spy).toHaveBeenCalledWith(jasmine.objectContaining({ - options: listOptions.map(option => option.componentInstance) - })); + expect(spy).toHaveBeenCalledWith( + jasmine.objectContaining({ + options: listOptions.map(option => option.componentInstance), + }), + ); }); it('should be able to jump focus down to an item by typing', fakeAsync(() => { @@ -629,8 +647,7 @@ describe('MatSelectionList without forms', () => { it('should not select items while using the typeahead', fakeAsync(() => { const manager = selectionList.componentInstance._keyManager; const testListItem = listOptions[1].nativeElement as HTMLElement; - const model = - selectionList.injector.get(MatSelectionList).selectedOptions; + const model = selectionList.injector.get(MatSelectionList).selectedOptions; dispatchFakeEvent(testListItem, 'focus'); fixture.detectChanges(); @@ -655,16 +672,17 @@ describe('MatSelectionList without forms', () => { expect(list.options.toArray().every(option => option.selected)).toBe(false); - list.selectAll(); + const result = list.selectAll(); fixture.detectChanges(); expect(list.options.toArray().every(option => option.selected)).toBe(true); + expect(result).toEqual(list.options.toArray()); }); it('should be able to select all options, even if they are disabled', () => { const list: MatSelectionList = selectionList.componentInstance; - list.options.forEach(option => option.disabled = true); + list.options.forEach(option => (option.disabled = true)); fixture.detectChanges(); expect(list.options.toArray().every(option => option.selected)).toBe(false); @@ -681,10 +699,11 @@ describe('MatSelectionList without forms', () => { list.options.forEach(option => option.toggle()); expect(list.options.toArray().every(option => option.selected)).toBe(true); - list.deselectAll(); + const result = list.deselectAll(); fixture.detectChanges(); expect(list.options.toArray().every(option => option.selected)).toBe(false); + expect(result).toEqual(list.options.toArray()); }); it('should be able to deselect all options, even if they are disabled', () => { @@ -693,7 +712,7 @@ describe('MatSelectionList without forms', () => { list.options.forEach(option => option.toggle()); expect(list.options.toArray().every(option => option.selected)).toBe(true); - list.options.forEach(option => option.disabled = true); + list.options.forEach(option => (option.disabled = true)); fixture.detectChanges(); list.deselectAll(); @@ -747,33 +766,36 @@ describe('MatSelectionList without forms', () => { expect(list.options.toArray().every(option => option.selected)).toBe(true); }); - it('should disable list item ripples when the ripples on the list have been disabled', - fakeAsync(() => { - const rippleTarget = fixture.nativeElement - .querySelector('.mat-list-option:not(.mat-list-item-disabled) .mat-list-item-content'); - const {enterDuration, exitDuration} = defaultRippleAnimationConfig; + it('should disable list item ripples when the ripples on the list have been disabled', fakeAsync(() => { + const rippleTarget = fixture.nativeElement.querySelector( + '.mat-list-option:not(.mat-list-item-disabled) .mat-list-item-content', + ); + const {enterDuration, exitDuration} = defaultRippleAnimationConfig; - dispatchMouseEvent(rippleTarget, 'mousedown'); - dispatchMouseEvent(rippleTarget, 'mouseup'); + dispatchMouseEvent(rippleTarget, 'mousedown'); + dispatchMouseEvent(rippleTarget, 'mouseup'); - expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) - .toBe(1, 'Expected ripples to be enabled by default.'); + expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) + .withContext('Expected ripples to be enabled by default.') + .toBe(1); - // Wait for the ripples to go away. - tick(enterDuration + exitDuration); - expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) - .toBe(0, 'Expected ripples to go away.'); + // Wait for the ripples to go away. + tick(enterDuration + exitDuration); + expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) + .withContext('Expected ripples to go away.') + .toBe(0); - fixture.componentInstance.listRippleDisabled = true; - fixture.detectChanges(); + fixture.componentInstance.listRippleDisabled = true; + fixture.detectChanges(); - dispatchMouseEvent(rippleTarget, 'mousedown'); - dispatchMouseEvent(rippleTarget, 'mouseup'); - flush(); + dispatchMouseEvent(rippleTarget, 'mousedown'); + dispatchMouseEvent(rippleTarget, 'mouseup'); + flush(); - expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) - .toBe(0, 'Expected no ripples after list ripples are disabled.'); - })); + expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) + .withContext('Expected no ripples after list ripples are disabled.') + .toBe(0); + })); it('can bind both selected and value at the same time', () => { const componentFixture = TestBed.createComponent(SelectionListWithSelectedOptionAndValue); @@ -783,21 +805,13 @@ describe('MatSelectionList without forms', () => { expect(listItemEl.componentInstance.value).toBe(componentFixture.componentInstance.itemValue); }); - it('should pick up indirect descendant lines', () => { - const componentFixture = TestBed.createComponent(SelectionListWithIndirectDescendantLines); - componentFixture.detectChanges(); - - const option = componentFixture.nativeElement.querySelector('mat-list-option'); - expect(option.classList).toContain('mat-2-line'); - }); - it('should have a focus indicator', () => { const optionNativeElements = listOptions.map(option => option.nativeElement); - expect(optionNativeElements - .every(element => element.classList.contains('mat-focus-indicator'))).toBe(true); - }); - + expect( + optionNativeElements.every(element => element.classList.contains('mat-focus-indicator')), + ).toBe(true); + }); }); describe('with list option selected', () => { @@ -805,21 +819,25 @@ describe('MatSelectionList without forms', () => { let listItemEl: DebugElement; let selectionList: DebugElement; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatListModule], - declarations: [SelectionListWithSelectedOption], - }); - - TestBed.compileComponents(); - })); - - beforeEach(waitForAsync(() => { - fixture = TestBed.createComponent(SelectionListWithSelectedOption); - listItemEl = fixture.debugElement.query(By.directive(MatListOption))!; - selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!; - fixture.detectChanges(); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatListModule], + declarations: [SelectionListWithSelectedOption], + }); + + TestBed.compileComponents(); + }), + ); + + beforeEach( + waitForAsync(() => { + fixture = TestBed.createComponent(SelectionListWithSelectedOption); + listItemEl = fixture.debugElement.query(By.directive(MatListOption))!; + selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!; + fixture.detectChanges(); + }), + ); it('should set its initial selected state in the selectedOptions', () => { let optionEl = listItemEl.injector.get(MatListOption); @@ -833,14 +851,16 @@ describe('MatSelectionList without forms', () => { let selectionList: MatSelectionList; let listOption: MatListOption; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatListModule], - declarations: [SelectionListWithChangingOptionValue], - }); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatListModule], + declarations: [SelectionListWithChangingOptionValue], + }); - TestBed.compileComponents(); - })); + TestBed.compileComponents(); + }), + ); beforeEach(() => { fixture = TestBed.createComponent(SelectionListWithChangingOptionValue); @@ -866,35 +886,41 @@ describe('MatSelectionList without forms', () => { let listOptionEl: HTMLElement; let listOption: MatListOption; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatListModule], - declarations: [SelectionListWithDisabledOption] - }); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatListModule], + declarations: [SelectionListWithDisabledOption], + }); - TestBed.compileComponents(); - })); + TestBed.compileComponents(); + }), + ); - beforeEach(waitForAsync(() => { - fixture = TestBed.createComponent(SelectionListWithDisabledOption); + beforeEach( + waitForAsync(() => { + fixture = TestBed.createComponent(SelectionListWithDisabledOption); - const listOptionDebug = fixture.debugElement.query(By.directive(MatListOption))!; + const listOptionDebug = fixture.debugElement.query(By.directive(MatListOption))!; - listOption = listOptionDebug.componentInstance; - listOptionEl = listOptionDebug.nativeElement; + listOption = listOptionDebug.componentInstance; + listOptionEl = listOptionDebug.nativeElement; - fixture.detectChanges(); - })); + fixture.detectChanges(); + }), + ); it('should disable ripples for disabled option', () => { expect(listOption._isRippleDisabled()) - .toBe(false, 'Expected ripples to be enabled by default'); + .withContext('Expected ripples to be enabled by default') + .toBe(false); fixture.componentInstance.disableItem = true; fixture.detectChanges(); expect(listOption._isRippleDisabled()) - .toBe(true, 'Expected ripples to be disabled if option is disabled'); + .withContext('Expected ripples to be disabled if option is disabled') + .toBe(true); }); it('should apply the "mat-list-item-disabled" class properly', () => { @@ -912,31 +938,35 @@ describe('MatSelectionList without forms', () => { let listOption: DebugElement[]; let selectionList: DebugElement; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatListModule], - declarations: [ - SelectionListWithListOptions, - SelectionListWithCheckboxPositionAfter, - SelectionListWithListDisabled, - SelectionListWithOnlyOneOption - ], - }); - - TestBed.compileComponents(); - })); - - beforeEach(waitForAsync(() => { - fixture = TestBed.createComponent(SelectionListWithListDisabled); - listOption = fixture.debugElement.queryAll(By.directive(MatListOption)); - selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!; - fixture.detectChanges(); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatListModule], + declarations: [ + SelectionListWithListOptions, + SelectionListWithCheckboxPositionAfter, + SelectionListWithListDisabled, + SelectionListWithOnlyOneOption, + ], + }); + + TestBed.compileComponents(); + }), + ); + + beforeEach( + waitForAsync(() => { + fixture = TestBed.createComponent(SelectionListWithListDisabled); + listOption = fixture.debugElement.queryAll(By.directive(MatListOption)); + selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!; + fixture.detectChanges(); + }), + ); it('should not allow selection on disabled selection-list', () => { let testListItem = listOption[2].injector.get(MatListOption); let selectList = - selectionList.injector.get(MatSelectionList).selectedOptions; + selectionList.injector.get(MatSelectionList).selectedOptions; expect(selectList.selected.length).toBe(0); @@ -951,41 +981,48 @@ describe('MatSelectionList without forms', () => { // property of the selection list has been updated, the ripple directive can be used. // Inspecting the host classes of the options doesn't work because those update as part // of the parent template (of the selection-list). - const listOptionRipple = listOption[2].query(By.directive(MatRipple))! - .injector.get(MatRipple); + const listOptionRipple = listOption[2] + .query(By.directive(MatRipple))! + .injector.get(MatRipple); expect(listOptionRipple.disabled) - .toBe(true, 'Expected ripples of list option to be disabled'); + .withContext('Expected ripples of list option to be disabled') + .toBe(true); fixture.componentInstance.disabled = false; fixture.detectChanges(); expect(listOptionRipple.disabled) - .toBe(false, 'Expected ripples of list option to be enabled'); + .withContext('Expected ripples of list option to be enabled') + .toBe(false); }); }); describe('with checkbox position after', () => { let fixture: ComponentFixture; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatListModule], - declarations: [ - SelectionListWithListOptions, - SelectionListWithCheckboxPositionAfter, - SelectionListWithListDisabled, - SelectionListWithOnlyOneOption - ], - }); - - TestBed.compileComponents(); - })); - - beforeEach(waitForAsync(() => { - fixture = TestBed.createComponent(SelectionListWithCheckboxPositionAfter); - fixture.detectChanges(); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatListModule], + declarations: [ + SelectionListWithListOptions, + SelectionListWithCheckboxPositionAfter, + SelectionListWithListDisabled, + SelectionListWithOnlyOneOption, + ], + }); + + TestBed.compileComponents(); + }), + ); + + beforeEach( + waitForAsync(() => { + fixture = TestBed.createComponent(SelectionListWithCheckboxPositionAfter); + fixture.detectChanges(); + }), + ); it('should be able to customize checkbox position', () => { let listItemContent = fixture.debugElement.query(By.css('.mat-list-item-content'))!; @@ -994,15 +1031,14 @@ describe('MatSelectionList without forms', () => { }); describe('with list item elements', () => { - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatListModule], - declarations: [ - SelectionListWithAvatar, - SelectionListWithIcon, - ], - }).compileComponents(); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatListModule], + declarations: [SelectionListWithAvatar, SelectionListWithIcon], + }).compileComponents(); + }), + ); it('should add a class to reflect that it has an avatar', () => { const fixture = TestBed.createComponent(SelectionListWithIcon); @@ -1026,26 +1062,26 @@ describe('MatSelectionList without forms', () => { let listOptions: DebugElement[]; let selectionList: DebugElement; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatListModule], - declarations: [ - SelectionListWithListOptions, - ], - }).compileComponents(); - - fixture = TestBed.createComponent(SelectionListWithListOptions); - fixture.componentInstance.multiple = false; - listOptions = fixture.debugElement.queryAll(By.directive(MatListOption)); - selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!; - fixture.detectChanges(); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatListModule], + declarations: [SelectionListWithListOptions], + }).compileComponents(); + + fixture = TestBed.createComponent(SelectionListWithListOptions); + fixture.componentInstance.multiple = false; + listOptions = fixture.debugElement.queryAll(By.directive(MatListOption)); + selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!; + fixture.detectChanges(); + }), + ); it('should select one option at a time', () => { const testListItem1 = listOptions[1].injector.get(MatListOption); const testListItem2 = listOptions[2].injector.get(MatListOption); const selectList = - selectionList.injector.get(MatSelectionList).selectedOptions; + selectionList.injector.get(MatSelectionList).selectedOptions; expect(selectList.selected.length).toBe(0); @@ -1053,17 +1089,20 @@ describe('MatSelectionList without forms', () => { fixture.detectChanges(); expect(selectList.selected).toEqual([testListItem1]); - expect(listOptions[1].nativeElement.classList.contains('mat-list-single-selected-option')) - .toBe(true); + expect( + listOptions[1].nativeElement.classList.contains('mat-list-single-selected-option'), + ).toBe(true); dispatchFakeEvent(testListItem2._getHostElement(), 'click'); fixture.detectChanges(); expect(selectList.selected).toEqual([testListItem2]); - expect(listOptions[1].nativeElement.classList.contains('mat-list-single-selected-option')) - .toBe(false); - expect(listOptions[2].nativeElement.classList.contains('mat-list-single-selected-option')) - .toBe(true); + expect( + listOptions[1].nativeElement.classList.contains('mat-list-single-selected-option'), + ).toBe(false); + expect( + listOptions[2].nativeElement.classList.contains('mat-list-single-selected-option'), + ).toBe(true); }); it('should not show check boxes', () => { @@ -1073,7 +1112,7 @@ describe('MatSelectionList without forms', () => { it('should not deselect the target option on click', () => { const testListItem1 = listOptions[1].injector.get(MatListOption); const selectList = - selectionList.injector.get(MatSelectionList).selectedOptions; + selectionList.injector.get(MatSelectionList).selectedOptions; expect(selectList.selected.length).toBe(0); @@ -1090,8 +1129,9 @@ describe('MatSelectionList without forms', () => { it('throws an exception when toggling single/multiple mode after bootstrap', () => { fixture.componentInstance.multiple = true; - expect(() => fixture.detectChanges()).toThrow(new Error( - 'Cannot change `multiple` mode of mat-selection-list after initialization.')); + expect(() => fixture.detectChanges()).toThrow( + new Error('Cannot change `multiple` mode of mat-selection-list after initialization.'), + ); }); it('should do nothing when pressing ctrl + a', () => { @@ -1105,8 +1145,10 @@ describe('MatSelectionList without forms', () => { expect(listOptions.every(option => !option.componentInstance.selected)).toBe(true); }); - it('should focus, but not toggle, the next item when pressing SHIFT + UP_ARROW in single ' + - 'selection mode', () => { + it( + 'should focus, but not toggle, the next item when pressing SHIFT + UP_ARROW in single ' + + 'selection mode', + () => { const manager = selectionList.componentInstance._keyManager; const upKeyEvent = createKeyboardEvent('keydown', UP_ARROW, undefined, {shift: true}); @@ -1121,10 +1163,13 @@ describe('MatSelectionList without forms', () => { expect(listOptions[1].componentInstance.selected).toBe(false); expect(listOptions[2].componentInstance.selected).toBe(false); - }); + }, + ); - it('should focus, but not toggle, the next item when pressing SHIFT + DOWN_ARROW ' + - 'in single selection mode', () => { + it( + 'should focus, but not toggle, the next item when pressing SHIFT + DOWN_ARROW ' + + 'in single selection mode', + () => { const manager = selectionList.componentInstance._keyManager; const downKeyEvent = createKeyboardEvent('keydown', DOWN_ARROW, undefined, {shift: true}); @@ -1139,28 +1184,68 @@ describe('MatSelectionList without forms', () => { expect(listOptions[1].componentInstance.selected).toBe(false); expect(listOptions[2].componentInstance.selected).toBe(false); - }); + }, + ); + }); + + describe('with single selection', () => { + let fixture: ComponentFixture; + let optionElement: HTMLElement; + let option: MatListOption; + + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatListModule], + declarations: [ListOptionWithTwoWayBinding], + }).compileComponents(); + + fixture = TestBed.createComponent(ListOptionWithTwoWayBinding); + fixture.detectChanges(); + const optionDebug = fixture.debugElement.query(By.directive(MatListOption)); + option = optionDebug.componentInstance; + optionElement = optionDebug.nativeElement; + }), + ); + + it('should sync the value from the view to the option', () => { + expect(option.selected).toBe(false); + + fixture.componentInstance.selected = true; + fixture.detectChanges(); + + expect(option.selected).toBe(true); + }); + + it('should sync the value from the option to the view', () => { + expect(fixture.componentInstance.selected).toBe(false); + optionElement.click(); + fixture.detectChanges(); + + expect(fixture.componentInstance.selected).toBe(true); + }); }); }); describe('MatSelectionList with forms', () => { + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatListModule, FormsModule, ReactiveFormsModule], + declarations: [ + SelectionListWithModel, + SelectionListWithFormControl, + SelectionListWithPreselectedOption, + SelectionListWithPreselectedOptionAndModel, + SelectionListWithPreselectedFormControlOnPush, + SelectionListWithCustomComparator, + ], + }); - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatListModule, FormsModule, ReactiveFormsModule], - declarations: [ - SelectionListWithModel, - SelectionListWithFormControl, - SelectionListWithPreselectedOption, - SelectionListWithPreselectedOptionAndModel, - SelectionListWithPreselectedFormControlOnPush, - SelectionListWithCustomComparator, - ] - }); - - TestBed.compileComponents(); - })); + TestBed.compileComponents(); + }), + ); describe('and ngModel', () => { let fixture: ComponentFixture; @@ -1174,13 +1259,15 @@ describe('MatSelectionList with forms', () => { selectionListDebug = fixture.debugElement.query(By.directive(MatSelectionList))!; ngModel = selectionListDebug.injector.get(NgModel); - listOptions = fixture.debugElement.queryAll(By.directive(MatListOption)) + listOptions = fixture.debugElement + .queryAll(By.directive(MatListOption)) .map(optionDebugEl => optionDebugEl.componentInstance); }); it('should update the model if an option got selected programmatically', fakeAsync(() => { expect(fixture.componentInstance.selectedOptions.length) - .toBe(0, 'Expected no options to be selected by default'); + .withContext('Expected no options to be selected by default') + .toBe(0); listOptions[0].toggle(); fixture.detectChanges(); @@ -1188,12 +1275,14 @@ describe('MatSelectionList with forms', () => { tick(); expect(fixture.componentInstance.selectedOptions.length) - .toBe(1, 'Expected first list option to be selected'); + .withContext('Expected first list option to be selected') + .toBe(1); })); it('should update the model if an option got clicked', fakeAsync(() => { expect(fixture.componentInstance.selectedOptions.length) - .toBe(0, 'Expected no options to be selected by default'); + .withContext('Expected no options to be selected by default') + .toBe(0); dispatchFakeEvent(listOptions[0]._getHostElement(), 'click'); fixture.detectChanges(); @@ -1201,12 +1290,14 @@ describe('MatSelectionList with forms', () => { tick(); expect(fixture.componentInstance.selectedOptions.length) - .toBe(1, 'Expected first list option to be selected'); + .withContext('Expected first list option to be selected') + .toBe(1); })); it('should update the options if a model value is set', fakeAsync(() => { expect(fixture.componentInstance.selectedOptions.length) - .toBe(0, 'Expected no options to be selected by default'); + .withContext('Expected no options to be selected by default') + .toBe(0); fixture.componentInstance.selectedOptions = ['opt3']; fixture.detectChanges(); @@ -1214,30 +1305,36 @@ describe('MatSelectionList with forms', () => { tick(); expect(fixture.componentInstance.selectedOptions.length) - .toBe(1, 'Expected first list option to be selected'); + .withContext('Expected first list option to be selected') + .toBe(1); })); it('should not mark the model as touched when the list is blurred', fakeAsync(() => { expect(ngModel.touched) - .toBe(false, 'Expected the selection-list to be untouched by default.'); + .withContext('Expected the selection-list to be untouched by default.') + .toBe(false); dispatchFakeEvent(selectionListDebug.nativeElement, 'blur'); fixture.detectChanges(); tick(); - expect(ngModel.touched).toBe(false, 'Expected the selection-list to remain untouched.'); + expect(ngModel.touched) + .withContext('Expected the selection-list to remain untouched.') + .toBe(false); })); it('should mark the model as touched when a list item is blurred', fakeAsync(() => { expect(ngModel.touched) - .toBe(false, 'Expected the selection-list to be untouched by default.'); + .withContext('Expected the selection-list to be untouched by default.') + .toBe(false); dispatchFakeEvent(fixture.nativeElement.querySelector('.mat-list-option'), 'blur'); fixture.detectChanges(); tick(); expect(ngModel.touched) - .toBe(true, 'Expected the selection-list to be touched after an item is blurred.'); + .withContext('Expected the selection-list to be touched after an item is blurred.') + .toBe(true); })); it('should be pristine by default', fakeAsync(() => { @@ -1245,9 +1342,11 @@ describe('MatSelectionList with forms', () => { fixture.componentInstance.selectedOptions = ['opt2']; fixture.detectChanges(); - ngModel = - fixture.debugElement.query(By.directive(MatSelectionList))!.injector.get(NgModel); - listOptions = fixture.debugElement.queryAll(By.directive(MatListOption)) + ngModel = fixture.debugElement + .query(By.directive(MatSelectionList))! + .injector.get(NgModel); + listOptions = fixture.debugElement + .queryAll(By.directive(MatListOption)) .map(optionDebugEl => optionDebugEl.componentInstance); // Flush the initial tick to ensure that every action from the ControlValueAccessor @@ -1255,7 +1354,8 @@ describe('MatSelectionList with forms', () => { tick(); expect(ngModel.pristine) - .toBe(true, 'Expected the selection-list to be pristine by default.'); + .withContext('Expected the selection-list to be pristine by default.') + .toBe(true); listOptions[1].toggle(); fixture.detectChanges(); @@ -1263,7 +1363,8 @@ describe('MatSelectionList with forms', () => { tick(); expect(ngModel.pristine) - .toBe(false, 'Expected the selection-list to be dirty after state change.'); + .withContext('Expected the selection-list to be dirty after state change.') + .toBe(false); })); it('should remove a selected option from the value on destroy', fakeAsync(() => { @@ -1319,8 +1420,9 @@ describe('MatSelectionList with forms', () => { fixture.detectChanges(); tick(); - listOptions = fixture.debugElement.queryAll(By.directive(MatListOption)) - .map(optionDebugEl => optionDebugEl.componentInstance); + listOptions = fixture.debugElement + .queryAll(By.directive(MatListOption)) + .map(optionDebugEl => optionDebugEl.componentInstance); fixture.componentInstance.selectedOptions = ['one', 'two', 'two']; fixture.detectChanges(); @@ -1339,6 +1441,32 @@ describe('MatSelectionList with forms', () => { expect(selectionListDebug.nativeElement.tabIndex).toBe(-1); }); + it('should dispatch one change event per change when updating a single-selection list', fakeAsync(() => { + fixture.destroy(); + fixture = TestBed.createComponent(SelectionListWithModel); + fixture.componentInstance.multiple = false; + fixture.componentInstance.selectedOptions = ['opt3']; + fixture.detectChanges(); + const options = fixture.debugElement + .queryAll(By.directive(MatListOption)) + .map(optionDebugEl => optionDebugEl.nativeElement); + + expect(fixture.componentInstance.modelChangeSpy).not.toHaveBeenCalled(); + + options[0].click(); + fixture.detectChanges(); + tick(); + + expect(fixture.componentInstance.modelChangeSpy).toHaveBeenCalledTimes(1); + expect(fixture.componentInstance.selectedOptions).toEqual(['opt1']); + + options[1].click(); + fixture.detectChanges(); + tick(); + + expect(fixture.componentInstance.modelChangeSpy).toHaveBeenCalledTimes(2); + expect(fixture.componentInstance.selectedOptions).toEqual(['opt2']); + })); }); describe('and formControl', () => { @@ -1351,34 +1479,41 @@ describe('MatSelectionList with forms', () => { fixture.detectChanges(); selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!.componentInstance; - listOptions = fixture.debugElement.queryAll(By.directive(MatListOption)) + listOptions = fixture.debugElement + .queryAll(By.directive(MatListOption)) .map(optionDebugEl => optionDebugEl.componentInstance); }); it('should be able to disable options from the control', () => { expect(selectionList.disabled) - .toBe(false, 'Expected the selection list to be enabled.'); + .withContext('Expected the selection list to be enabled.') + .toBe(false); expect(listOptions.every(option => !option.disabled)) - .toBe(true, 'Expected every list option to be enabled.'); + .withContext('Expected every list option to be enabled.') + .toBe(true); fixture.componentInstance.formControl.disable(); fixture.detectChanges(); expect(selectionList.disabled) - .toBe(true, 'Expected the selection list to be disabled.'); + .withContext('Expected the selection list to be disabled.') + .toBe(true); expect(listOptions.every(option => option.disabled)) - .toBe(true, 'Expected every list option to be disabled.'); + .withContext('Expected every list option to be disabled.') + .toBe(true); }); it('should be able to update the disabled property after form control disabling', () => { expect(listOptions.every(option => !option.disabled)) - .toBe(true, 'Expected every list option to be enabled.'); + .withContext('Expected every list option to be enabled.') + .toBe(true); fixture.componentInstance.formControl.disable(); fixture.detectChanges(); expect(listOptions.every(option => option.disabled)) - .toBe(true, 'Expected every list option to be disabled.'); + .withContext('Expected every list option to be disabled.') + .toBe(true); // Previously the selection list has been disabled through FormControl#disable. Now we // want to verify that we can still change the disabled state through updating the disabled @@ -1388,24 +1523,31 @@ describe('MatSelectionList with forms', () => { fixture.detectChanges(); expect(listOptions.every(option => !option.disabled)) - .toBe(true, 'Expected every list option to be enabled.'); + .withContext('Expected every list option to be enabled.') + .toBe(true); }); it('should be able to set the value through the form control', () => { expect(listOptions.every(option => !option.selected)) - .toBe(true, 'Expected every list option to be unselected.'); + .withContext('Expected every list option to be unselected.') + .toBe(true); fixture.componentInstance.formControl.setValue(['opt2', 'opt3']); fixture.detectChanges(); - expect(listOptions[1].selected).toBe(true, 'Expected second option to be selected.'); - expect(listOptions[2].selected).toBe(true, 'Expected third option to be selected.'); + expect(listOptions[1].selected) + .withContext('Expected second option to be selected.') + .toBe(true); + expect(listOptions[2].selected) + .withContext('Expected third option to be selected.') + .toBe(true); fixture.componentInstance.formControl.setValue(null); fixture.detectChanges(); expect(listOptions.every(option => !option.selected)) - .toBe(true, 'Expected every list option to be unselected.'); + .withContext('Expected every list option to be unselected.') + .toBe(true); }); it('should deselect option whose value no longer matches', () => { @@ -1414,12 +1556,12 @@ describe('MatSelectionList with forms', () => { fixture.componentInstance.formControl.setValue(['opt2']); fixture.detectChanges(); - expect(option.selected).toBe(true, 'Expected option to be selected.'); + expect(option.selected).withContext('Expected option to be selected.').toBe(true); option.value = 'something-different'; fixture.detectChanges(); - expect(option.selected).toBe(false, 'Expected option not to be selected.'); + expect(option.selected).withContext('Expected option not to be selected.').toBe(false); expect(fixture.componentInstance.formControl.value).toEqual([]); }); @@ -1430,11 +1572,16 @@ describe('MatSelectionList with forms', () => { fixture.componentInstance.formControl.setValue(['opt2', 'opt3']); fixture.detectChanges(); - listOptions = fixture.debugElement.queryAll(By.directive(MatListOption)) + listOptions = fixture.debugElement + .queryAll(By.directive(MatListOption)) .map(optionDebugEl => optionDebugEl.componentInstance); - expect(listOptions[1].selected).toBe(true, 'Expected second option to be selected.'); - expect(listOptions[2].selected).toBe(true, 'Expected third option to be selected.'); + expect(listOptions[1].selected) + .withContext('Expected second option to be selected.') + .toBe(true); + expect(listOptions[2].selected) + .withContext('Expected third option to be selected.') + .toBe(true); }); it('should not clear the form control when the list is destroyed', fakeAsync(() => { @@ -1460,20 +1607,21 @@ describe('MatSelectionList with forms', () => { fixture.componentInstance.renderExtraOption = true; fixture.detectChanges(); - listOptions = fixture.debugElement.queryAll(By.directive(MatListOption)) + listOptions = fixture.debugElement + .queryAll(By.directive(MatListOption)) .map(optionDebugEl => optionDebugEl.componentInstance); expect(listOptions.length).toBe(4); expect(listOptions[3].selected).toBe(true); }); - }); describe('preselected values', () => { it('should add preselected options to the model value', fakeAsync(() => { const fixture = TestBed.createComponent(SelectionListWithPreselectedOption); - const listOptions = fixture.debugElement.queryAll(By.directive(MatListOption)) - .map(optionDebugEl => optionDebugEl.componentInstance); + const listOptions = fixture.debugElement + .queryAll(By.directive(MatListOption)) + .map(optionDebugEl => optionDebugEl.componentInstance); fixture.detectChanges(); tick(); @@ -1484,8 +1632,9 @@ describe('MatSelectionList with forms', () => { it('should handle preselected option both through the model and the view', fakeAsync(() => { const fixture = TestBed.createComponent(SelectionListWithPreselectedOptionAndModel); - const listOptions = fixture.debugElement.queryAll(By.directive(MatListOption)) - .map(optionDebugEl => optionDebugEl.componentInstance); + const listOptions = fixture.debugElement + .queryAll(By.directive(MatListOption)) + .map(optionDebugEl => optionDebugEl.componentInstance); fixture.detectChanges(); tick(); @@ -1508,7 +1657,6 @@ describe('MatSelectionList with forms', () => { expect(option.componentInstance.selected).toBe(true); expect(option.nativeElement.querySelector('.mat-pseudo-checkbox-checked')).toBeTruthy(); })); - }); describe('with custom compare function', () => { @@ -1516,9 +1664,11 @@ describe('MatSelectionList with forms', () => { const fixture = TestBed.createComponent(SelectionListWithCustomComparator); const testComponent = fixture.componentInstance; - testComponent.compareWith = jasmine.createSpy('comparator', (o1: any, o2: any) => { - return o1 && o2 && o1.id === o2.id; - }).and.callThrough(); + testComponent.compareWith = jasmine + .createSpy('comparator', (o1: any, o2: any) => { + return o1 && o2 && o1.id === o2.id; + }) + .and.callThrough(); testComponent.selectedOptions = [{id: 2, label: 'Two'}]; fixture.detectChanges(); @@ -1530,8 +1680,8 @@ describe('MatSelectionList with forms', () => { }); }); - -@Component({template: ` +@Component({ + template: ` { Drafts - `}) + `, +}) class SelectionListWithListOptions { showLastOption = true; listRippleDisabled = false; @@ -1566,7 +1717,8 @@ class SelectionListWithListOptions { onSelectionChange(_change: MatSelectionListChange) {} } -@Component({template: ` +@Component({ + template: ` Inbox (disabled selection-option) @@ -1580,11 +1732,12 @@ class SelectionListWithListOptions { Drafts - `}) -class SelectionListWithCheckboxPositionAfter { -} + `, +}) +class SelectionListWithCheckboxPositionAfter {} -@Component({template: ` +@Component({ + template: ` Inbox (disabled selection-option) @@ -1598,55 +1751,64 @@ class SelectionListWithCheckboxPositionAfter { Drafts - `}) + `, +}) class SelectionListWithListDisabled { disabled: boolean = true; } -@Component({template: ` +@Component({ + template: ` Item - `}) + `, +}) class SelectionListWithDisabledOption { disableItem: boolean = false; } -@Component({template: ` +@Component({ + template: ` Item - `}) -class SelectionListWithSelectedOption { -} + `, +}) +class SelectionListWithSelectedOption {} @Component({ template: ` Item - ` + `, }) class SelectionListWithSelectedOptionAndValue { itemValue = 'item1'; } -@Component({template: ` +@Component({ + template: ` Inbox - `}) -class SelectionListWithOnlyOneOption { -} + `, +}) +class SelectionListWithOnlyOneOption {} @Component({ template: ` - + {{option}} - ` + `, }) class SelectionListWithModel { modelChangeSpy = jasmine.createSpy('model change spy'); selectedOptions: string[] = []; + multiple = true; options = ['opt1', 'opt2', 'opt3']; } @@ -1658,7 +1820,7 @@ class SelectionListWithModel { Option 3 Option 4 - ` + `, }) class SelectionListWithFormControl { formControl = new FormControl(); @@ -1666,79 +1828,73 @@ class SelectionListWithFormControl { renderExtraOption = false; } - @Component({ template: ` Option 1 Option 2 - ` + `, }) class SelectionListWithPreselectedOption { selectedOptions: string[]; } - @Component({ template: ` Option 1 Option 2 - ` + `, }) class SelectionListWithPreselectedOptionAndModel { selectedOptions = ['opt1']; } - @Component({ changeDetection: ChangeDetectionStrategy.OnPush, template: ` {{opt}} - ` + `, }) class SelectionListWithPreselectedFormControlOnPush { opts = ['opt1', 'opt2', 'opt3']; formControl = new FormControl(['opt2']); } - @Component({ template: ` {{option.label}} - ` + `, }) class SelectionListWithCustomComparator { @ViewChildren(MatListOption) optionInstances: QueryList; - selectedOptions: {id: number, label: string}[] = []; + selectedOptions: {id: number; label: string}[] = []; compareWith?: (o1: any, o2: any) => boolean; options = [ {id: 1, label: 'One'}, {id: 2, label: 'Two'}, - {id: 3, label: 'Three'} + {id: 3, label: 'Three'}, ]; } - @Component({ template: ` One - ` + `, }) class SelectionListWithChangingOptionValue { compareWith = (o1: any, o2: any) => o1 && o2 && o1.id === o2.id; value = {id: 1}; } - @Component({ template: ` @@ -1747,10 +1903,9 @@ class SelectionListWithChangingOptionValue { Inbox - ` + `, }) -class SelectionListWithAvatar { -} +class SelectionListWithAvatar {} @Component({ template: ` @@ -1760,11 +1915,9 @@ class SelectionListWithAvatar { Inbox - ` + `, }) -class SelectionListWithIcon { -} - +class SelectionListWithIcon {} @Component({ // Note the blank `ngSwitch` which we need in order to hit the bug that we're testing. @@ -1774,23 +1927,19 @@ class SelectionListWithIcon { One Two - ` + `, }) class SelectionListWithIndirectChildOptions { @ViewChildren(MatListOption) optionInstances: QueryList; } -// Note the blank `ngSwitch` which we need in order to hit the bug that we're testing. @Component({ template: ` - - -

Item

-

Item description

-
-
-
` + Item + +`, }) -class SelectionListWithIndirectDescendantLines { +class ListOptionWithTwoWayBinding { + selected = false; } diff --git a/src/material/list/selection-list.ts b/src/material/list/selection-list.ts index 384a71d12ac4..fa5e22aa078b 100644 --- a/src/material/list/selection-list.ts +++ b/src/material/list/selection-list.ts @@ -9,14 +9,7 @@ import {FocusableOption, FocusKeyManager, FocusMonitor} from '@angular/cdk/a11y'; import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion'; import {SelectionModel} from '@angular/cdk/collections'; -import { - A, - DOWN_ARROW, - ENTER, - hasModifierKey, - SPACE, - UP_ARROW, -} from '@angular/cdk/keycodes'; +import {A, DOWN_ARROW, ENTER, hasModifierKey, SPACE, UP_ARROW} from '@angular/cdk/keycodes'; import { AfterContentInit, Attribute, @@ -42,7 +35,6 @@ import { import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import { CanDisableRipple, - CanDisableRippleCtor, MatLine, mixinDisableRipple, setLines, @@ -52,19 +44,14 @@ import {Subject} from 'rxjs'; import {startWith, takeUntil} from 'rxjs/operators'; import {MatListAvatarCssMatStyler, MatListIconCssMatStyler} from './list'; -class MatSelectionListBase {} -const _MatSelectionListMixinBase: CanDisableRippleCtor & typeof MatSelectionListBase = - mixinDisableRipple(MatSelectionListBase); - -class MatListOptionBase {} -const _MatListOptionMixinBase: CanDisableRippleCtor & typeof MatListOptionBase = - mixinDisableRipple(MatListOptionBase); +const _MatSelectionListBase = mixinDisableRipple(class {}); +const _MatListOptionBase = mixinDisableRipple(class {}); /** @docs-private */ export const MAT_SELECTION_LIST_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MatSelectionList), - multi: true + multi: true, }; /** Change event that is being fired whenever the selected state of an option changes. */ @@ -79,14 +66,15 @@ export class MatSelectionListChange { */ public option: MatListOption, /** Reference to the options that have been changed. */ - public options: MatListOption[]) {} + public options: MatListOption[], + ) {} } /** * Type describing possible positions of a checkbox in a list option * with respect to the list item's text. */ -export type MatListOptionCheckboxPosition = 'before'|'after'; +export type MatListOptionCheckboxPosition = 'before' | 'after'; /** * Component for list-options of selection-list. Each list-option can automatically @@ -122,9 +110,10 @@ export type MatListOptionCheckboxPosition = 'before'|'after'; encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) -export class MatListOption extends _MatListOptionMixinBase implements AfterContentInit, OnDestroy, - OnInit, FocusableOption, - CanDisableRipple { +export class MatListOption + extends _MatListOptionBase + implements AfterContentInit, OnDestroy, OnInit, FocusableOption, CanDisableRipple +{ private _selected = false; private _disabled = false; private _hasFocus = false; @@ -133,6 +122,14 @@ export class MatListOption extends _MatListOptionMixinBase implements AfterConte @ContentChild(MatListIconCssMatStyler) _icon: MatListIconCssMatStyler; @ContentChildren(MatLine, {descendants: true}) _lines: QueryList; + /** + * Emits when the selected state of the option has changed. + * Use to facilitate two-data binding to the `selected` property. + * @docs-private + */ + @Output() + readonly selectedChange: EventEmitter = new EventEmitter(); + /** DOM element containing the item's text. */ @ViewChild('text') _text: ElementRef; @@ -141,8 +138,12 @@ export class MatListOption extends _MatListOptionMixinBase implements AfterConte /** Theme color of the list option. This sets the color of the checkbox. */ @Input() - get color(): ThemePalette { return this._color || this.selectionList.color; } - set color(newValue: ThemePalette) { this._color = newValue; } + get color(): ThemePalette { + return this._color || this.selectionList.color; + } + set color(newValue: ThemePalette) { + this._color = newValue; + } private _color: ThemePalette; /** @@ -152,7 +153,9 @@ export class MatListOption extends _MatListOptionMixinBase implements AfterConte private _inputsInitialized = false; /** Value of the option */ @Input() - get value(): any { return this._value; } + get value(): any { + return this._value; + } set value(newValue: any) { if ( this.selected && @@ -168,8 +171,10 @@ export class MatListOption extends _MatListOptionMixinBase implements AfterConte /** Whether the option is disabled. */ @Input() - get disabled() { return this._disabled || (this.selectionList && this.selectionList.disabled); } - set disabled(value: any) { + get disabled(): boolean { + return this._disabled || (this.selectionList && this.selectionList.disabled); + } + set disabled(value: BooleanInput) { const newValue = coerceBooleanProperty(value); if (newValue !== this._disabled) { @@ -180,20 +185,27 @@ export class MatListOption extends _MatListOptionMixinBase implements AfterConte /** Whether the option is selected. */ @Input() - get selected(): boolean { return this.selectionList.selectedOptions.isSelected(this); } - set selected(value: boolean) { + get selected(): boolean { + return this.selectionList.selectedOptions.isSelected(this); + } + set selected(value: BooleanInput) { const isSelected = coerceBooleanProperty(value); if (isSelected !== this._selected) { this._setSelected(isSelected); - this.selectionList._reportValueChange(); + + if (isSelected || this.selectionList.multiple) { + this.selectionList._reportValueChange(); + } } } - constructor(private _element: ElementRef, - private _changeDetector: ChangeDetectorRef, - /** @docs-private */ - @Inject(forwardRef(() => MatSelectionList)) public selectionList: MatSelectionList) { + constructor( + private _element: ElementRef, + private _changeDetector: ChangeDetectorRef, + /** @docs-private */ + @Inject(forwardRef(() => MatSelectionList)) public selectionList: MatSelectionList, + ) { super(); } @@ -257,7 +269,7 @@ export class MatListOption extends _MatListOptionMixinBase implements AfterConte * @docs-private */ getLabel() { - return this._text ? (this._text.nativeElement.textContent || '') : ''; + return this._text ? this._text.nativeElement.textContent || '' : ''; } /** Whether this list item should show a ripple effect when clicked. */ @@ -303,6 +315,7 @@ export class MatListOption extends _MatListOptionMixinBase implements AfterConte this.selectionList.selectedOptions.deselect(this); } + this.selectedChange.emit(selected); this._changeDetector.markForCheck(); return true; } @@ -315,13 +328,8 @@ export class MatListOption extends _MatListOptionMixinBase implements AfterConte _markForCheck() { this._changeDetector.markForCheck(); } - - static ngAcceptInputType_disabled: BooleanInput; - static ngAcceptInputType_selected: BooleanInput; - static ngAcceptInputType_disableRipple: BooleanInput; } - /** * Material Design list component where each item is a selectable option. Behaves as a listbox. */ @@ -341,10 +349,12 @@ export class MatListOption extends _MatListOptionMixinBase implements AfterConte styleUrls: ['list.css'], encapsulation: ViewEncapsulation.None, providers: [MAT_SELECTION_LIST_VALUE_ACCESSOR], - changeDetection: ChangeDetectionStrategy.OnPush + changeDetection: ChangeDetectionStrategy.OnPush, }) -export class MatSelectionList extends _MatSelectionListMixinBase implements CanDisableRipple, - AfterContentInit, ControlValueAccessor, OnDestroy, OnChanges { +export class MatSelectionList + extends _MatSelectionListBase + implements CanDisableRipple, AfterContentInit, ControlValueAccessor, OnDestroy, OnChanges +{ private _multiple = true; private _contentInitialized = false; @@ -356,7 +366,7 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD /** Emits a change event whenever the selected state of an option changes. */ @Output() readonly selectionChange: EventEmitter = - new EventEmitter(); + new EventEmitter(); /** * Tabindex of the selection list. @@ -376,8 +386,10 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD /** Whether the selection list is disabled. */ @Input() - get disabled(): boolean { return this._disabled; } - set disabled(value: boolean) { + get disabled(): boolean { + return this._disabled; + } + set disabled(value: BooleanInput) { this._disabled = coerceBooleanProperty(value); // The `MatSelectionList` and `MatListOption` are using the `OnPush` change detection @@ -390,14 +402,17 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD /** Whether selection is limited to one or multiple items (default multiple). */ @Input() - get multiple(): boolean { return this._multiple; } - set multiple(value: boolean) { + get multiple(): boolean { + return this._multiple; + } + set multiple(value: BooleanInput) { const newValue = coerceBooleanProperty(value); if (newValue !== this._multiple) { if (this._contentInitialized && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw new Error( - 'Cannot change `multiple` mode of mat-selection-list after initialization.'); + 'Cannot change `multiple` mode of mat-selection-list after initialization.', + ); } this._multiple = newValue; @@ -415,10 +430,10 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD private _onChange: (value: any) => void = (_: any) => {}; /** Keeps track of the currently-selected value. */ - _value: string[]|null; + _value: string[] | null; /** Emits when the list has been destroyed. */ - private _destroyed = new Subject(); + private readonly _destroyed = new Subject(); /** View to model callback that should be called if the list or its options lost focus. */ _onTouched: () => void = () => {}; @@ -426,12 +441,14 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD /** Whether the list has been destroyed. */ private _isDestroyed: boolean; - constructor(private _element: ElementRef, + constructor( + private _element: ElementRef, // @breaking-change 11.0.0 Remove `tabIndex` parameter. @Attribute('tabindex') tabIndex: string, private _changeDetector: ChangeDetectorRef, // @breaking-change 11.0.0 `_focusMonitor` parameter to become required. - private _focusMonitor?: FocusMonitor) { + private _focusMonitor?: FocusMonitor, + ) { super(); } @@ -477,19 +494,19 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD }); // @breaking-change 11.0.0 Remove null assertion once _focusMonitor is required. - this._focusMonitor?.monitor(this._element) + this._focusMonitor + ?.monitor(this._element) .pipe(takeUntil(this._destroyed)) .subscribe(origin => { if (origin === 'keyboard' || origin === 'program') { - const activeIndex = this._keyManager.activeItemIndex; - - if (!activeIndex || activeIndex === -1) { - // If there is no active index, set focus to the first option. - this._keyManager.setFirstItemActive(); - } else { - // Otherwise, set focus to the active option. - this._keyManager.setActiveItem(activeIndex); + let toFocus = 0; + for (let i = 0; i < this.options.length; i++) { + if (this.options.get(i)?.selected) { + toFocus = i; + break; + } } + this._keyManager.setActiveItem(toFocus); } }); } @@ -498,8 +515,10 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD const disableRippleChanges = changes['disableRipple']; const colorChanges = changes['color']; - if ((disableRippleChanges && !disableRippleChanges.firstChange) || - (colorChanges && !colorChanges.firstChange)) { + if ( + (disableRippleChanges && !disableRippleChanges.firstChange) || + (colorChanges && !colorChanges.firstChange) + ) { this._markOptionsForCheck(); } } @@ -517,14 +536,14 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD this._element.nativeElement.focus(options); } - /** Selects all of the options. */ - selectAll() { - this._setAllOptionsSelected(true); + /** Selects all of the options. Returns the options that changed as a result. */ + selectAll(): MatListOption[] { + return this._setAllOptionsSelected(true); } - /** Deselects all of the options. */ - deselectAll() { - this._setAllOptionsSelected(false); + /** Deselects all of the options. Returns the options that changed as a result. */ + deselectAll(): MatListOption[] { + return this._setAllOptionsSelected(false); } /** Sets the focused option of the selection-list. */ @@ -569,8 +588,12 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD break; default: // The "A" key gets special treatment, because it's used for the "select all" functionality. - if (keyCode === A && this.multiple && hasModifierKey(event, 'ctrlKey') && - !manager.isTyping()) { + if ( + keyCode === A && + this.multiple && + hasModifierKey(event, 'ctrlKey') && + !manager.isTyping() + ) { const shouldSelect = this.options.some(option => !option.disabled && !option.selected); this._setAllOptionsSelected(shouldSelect, true, true); event.preventDefault(); @@ -579,8 +602,12 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD } } - if (this.multiple && (keyCode === UP_ARROW || keyCode === DOWN_ARROW) && event.shiftKey && - manager.activeItemIndex !== previousFocusIndex) { + if ( + this.multiple && + (keyCode === UP_ARROW || keyCode === DOWN_ARROW) && + event.shiftKey && + manager.activeItemIndex !== previousFocusIndex + ) { this._toggleFocusedOption(); } } @@ -672,7 +699,8 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD private _setAllOptionsSelected( isSelected: boolean, skipDisabled?: boolean, - isUserInput?: boolean) { + isUserInput?: boolean, + ): MatListOption[] { // Keep track of whether anything changed, because we only want to // emit the changed event when something actually changed. const changedOptions: MatListOption[] = []; @@ -690,6 +718,8 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD this._emitChangeEvent(changedOptions); } } + + return changedOptions; } /** @@ -729,10 +759,6 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD /** Updates the tabindex based upon if the selection list is empty. */ private _updateTabIndex(): void { - this._tabIndex = (this.options.length === 0) ? -1 : 0; + this._tabIndex = this.options.length === 0 ? -1 : 0; } - - static ngAcceptInputType_disabled: BooleanInput; - static ngAcceptInputType_disableRipple: BooleanInput; - static ngAcceptInputType_multiple: BooleanInput; } diff --git a/src/material/list/testing/BUILD.bazel b/src/material/list/testing/BUILD.bazel index 8c2137384fc9..7f084da7816d 100644 --- a/src/material/list/testing/BUILD.bazel +++ b/src/material/list/testing/BUILD.bazel @@ -8,7 +8,6 @@ ts_library( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material/list/testing", deps = [ "//src/cdk/coercion", "//src/cdk/testing", diff --git a/src/material/list/testing/action-list-harness.ts b/src/material/list/testing/action-list-harness.ts index 20d98c10c5d1..88e1013fb1e3 100644 --- a/src/material/list/testing/action-list-harness.ts +++ b/src/material/list/testing/action-list-harness.ts @@ -13,7 +13,10 @@ import {getListItemPredicate, MatListItemHarnessBase} from './list-item-harness- /** Harness for interacting with a standard mat-action-list in tests. */ export class MatActionListHarness extends MatListHarnessBase< - typeof MatActionListItemHarness, MatActionListItemHarness, ActionListItemHarnessFilters> { + typeof MatActionListItemHarness, + MatActionListItemHarness, + ActionListItemHarnessFilters +> { /** The selector for the host element of a `MatActionList` instance. */ static hostSelector = 'mat-action-list.mat-list'; @@ -27,7 +30,7 @@ export class MatActionListHarness extends MatListHarnessBase< return new HarnessPredicate(MatActionListHarness, options); } - _itemHarness = MatActionListItemHarness; + override _itemHarness = MatActionListItemHarness; } /** Harness for interacting with an action list item. */ @@ -41,8 +44,9 @@ export class MatActionListItemHarness extends MatListItemHarnessBase { * @param options Options for filtering which action list item instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ - static with(options: ActionListItemHarnessFilters = {}): - HarnessPredicate { + static with( + options: ActionListItemHarnessFilters = {}, + ): HarnessPredicate { return getListItemPredicate(MatActionListItemHarness, options); } diff --git a/src/material/list/testing/list-harness-base.ts b/src/material/list/testing/list-harness-base.ts index 17fe629bd2d1..a56a91e2ef99 100644 --- a/src/material/list/testing/list-harness-base.ts +++ b/src/material/list/testing/list-harness-base.ts @@ -10,7 +10,7 @@ import { ComponentHarness, ComponentHarnessConstructor, HarnessPredicate, - parallel + parallel, } from '@angular/cdk/testing'; import {DividerHarnessFilters, MatDividerHarness} from '@angular/material/divider/testing'; import {BaseListItemHarnessFilters, SubheaderHarnessFilters} from './list-harness-filters'; @@ -32,12 +32,11 @@ export interface ListSection { * @template F The filter type used filter list item harness of type `C`. * @docs-private */ -export abstract class MatListHarnessBase - < - T extends (ComponentHarnessConstructor & {with: (options?: F) => HarnessPredicate}), - C extends ComponentHarness, - F extends BaseListItemHarnessFilters - > extends ComponentHarness { +export abstract class MatListHarnessBase< + T extends ComponentHarnessConstructor & {with: (options?: F) => HarnessPredicate}, + C extends ComponentHarness, + F extends BaseListItemHarnessFilters, +> extends ComponentHarness { protected _itemHarness: T; /** @@ -56,11 +55,13 @@ export abstract class MatListHarnessBase * @return The list of items matching the given filters, grouped into sections by subheader. */ async getItemsGroupedBySubheader(filters?: F): Promise[]> { - type Section = {items: C[], heading?: Promise}; + type Section = {items: C[]; heading?: Promise}; const listSections: Section[] = []; let currentSection: Section = {items: []}; - const itemsAndSubheaders = - await this.getItemsWithSubheadersAndDividers({item: filters, divider: false}); + const itemsAndSubheaders = await this.getItemsWithSubheadersAndDividers({ + item: filters, + divider: false, + }); for (const itemOrSubheader of itemsAndSubheaders) { if (itemOrSubheader instanceof MatSubheaderHarness) { if (currentSection.heading !== undefined || currentSection.items.length) { @@ -71,14 +72,18 @@ export abstract class MatListHarnessBase currentSection.items.push(itemOrSubheader); } } - if (currentSection.heading !== undefined || currentSection.items.length || - !listSections.length) { + if ( + currentSection.heading !== undefined || + currentSection.items.length || + !listSections.length + ) { listSections.push(currentSection); } // Concurrently wait for all sections to resolve their heading if present. - return parallel(() => listSections.map(async (s) => - ({items: s.items, heading: await s.heading}))); + return parallel(() => + listSections.map(async s => ({items: s.items, heading: await s.heading})), + ); } /** @@ -89,8 +94,10 @@ export abstract class MatListHarnessBase */ async getItemsGroupedByDividers(filters?: F): Promise { const listSections: C[][] = [[]]; - const itemsAndDividers = - await this.getItemsWithSubheadersAndDividers({item: filters, subheader: false}); + const itemsAndDividers = await this.getItemsWithSubheadersAndDividers({ + item: filters, + subheader: false, + }); for (const itemOrDivider of itemsAndDividers) { if (itemOrDivider instanceof MatDividerHarness) { listSections.push([]); @@ -112,53 +119,55 @@ export abstract class MatListHarnessBase * given filters. */ getItemsWithSubheadersAndDividers(filters: { - item: false, - subheader: false, - divider: false + item: false; + subheader: false; + divider: false; }): Promise<[]>; getItemsWithSubheadersAndDividers(filters: { - item?: F | false, - subheader: false, - divider: false + item?: F | false; + subheader: false; + divider: false; }): Promise; getItemsWithSubheadersAndDividers(filters: { - item: false, - subheader?: SubheaderHarnessFilters | false, - divider: false + item: false; + subheader?: SubheaderHarnessFilters | false; + divider: false; }): Promise; getItemsWithSubheadersAndDividers(filters: { - item: false, - subheader: false, - divider?: DividerHarnessFilters | false + item: false; + subheader: false; + divider?: DividerHarnessFilters | false; }): Promise; getItemsWithSubheadersAndDividers(filters: { - item?: F | false, - subheader?: SubheaderHarnessFilters | false, - divider: false + item?: F | false; + subheader?: SubheaderHarnessFilters | false; + divider: false; }): Promise<(C | MatSubheaderHarness)[]>; getItemsWithSubheadersAndDividers(filters: { - item?: F | false, - subheader: false, - divider?: false | DividerHarnessFilters + item?: F | false; + subheader: false; + divider?: false | DividerHarnessFilters; }): Promise<(C | MatDividerHarness)[]>; getItemsWithSubheadersAndDividers(filters: { - item: false, - subheader?: false | SubheaderHarnessFilters, - divider?: false | DividerHarnessFilters + item: false; + subheader?: false | SubheaderHarnessFilters; + divider?: false | DividerHarnessFilters; }): Promise<(MatSubheaderHarness | MatDividerHarness)[]>; getItemsWithSubheadersAndDividers(filters?: { - item?: F | false, - subheader?: SubheaderHarnessFilters | false, - divider?: DividerHarnessFilters | false + item?: F | false; + subheader?: SubheaderHarnessFilters | false; + divider?: DividerHarnessFilters | false; }): Promise<(C | MatSubheaderHarness | MatDividerHarness)[]>; - async getItemsWithSubheadersAndDividers(filters: { - item?: F | false, - subheader?: SubheaderHarnessFilters | false, - divider?: DividerHarnessFilters | false - } = {}): Promise<(C | MatSubheaderHarness | MatDividerHarness)[]> { + async getItemsWithSubheadersAndDividers( + filters: { + item?: F | false; + subheader?: SubheaderHarnessFilters | false; + divider?: DividerHarnessFilters | false; + } = {}, + ): Promise<(C | MatSubheaderHarness | MatDividerHarness)[]> { const query = []; if (filters.item !== false) { - query.push(this._itemHarness.with(filters.item || {} as F)); + query.push(this._itemHarness.with(filters.item || ({} as F))); } if (filters.subheader !== false) { query.push(MatSubheaderHarness.with(filters.subheader)); diff --git a/src/material/list/testing/list-harness.spec.ts b/src/material/list/testing/list-harness.spec.ts index 8c1a1ca9338e..de1f580cdd7a 100644 --- a/src/material/list/testing/list-harness.spec.ts +++ b/src/material/list/testing/list-harness.spec.ts @@ -7,13 +7,20 @@ import {MatSelectionListHarness} from './selection-list-harness'; import { MatListItemHarnessBase, MatListItemSection, - MatSubheaderHarness + MatSubheaderHarness, } from './list-item-harness-base'; import {runHarnessTests} from './shared.spec'; describe('Non-MDC-based list harnesses', () => { runHarnessTests( - MatListModule, MatListHarness, MatActionListHarness, MatNavListHarness, - MatSelectionListHarness, MatListItemHarnessBase, MatSubheaderHarness, MatDividerHarness, - {content: MatListItemSection.CONTENT}); + MatListModule, + MatListHarness, + MatActionListHarness, + MatNavListHarness, + MatSelectionListHarness, + MatListItemHarnessBase, + MatSubheaderHarness, + MatDividerHarness, + {content: MatListItemSection.CONTENT}, + ); }); diff --git a/src/material/list/testing/list-harness.ts b/src/material/list/testing/list-harness.ts index 1ced30f39c9d..0f5f2dd5ed5a 100644 --- a/src/material/list/testing/list-harness.ts +++ b/src/material/list/testing/list-harness.ts @@ -12,8 +12,11 @@ import {ListHarnessFilters, ListItemHarnessFilters} from './list-harness-filters import {getListItemPredicate, MatListItemHarnessBase} from './list-item-harness-base'; /** Harness for interacting with a standard mat-list in tests. */ -export class MatListHarness extends - MatListHarnessBase { +export class MatListHarness extends MatListHarnessBase< + typeof MatListItemHarness, + MatListItemHarness, + ListItemHarnessFilters +> { /** The selector for the host element of a `MatList` instance. */ static hostSelector = '.mat-list:not(mat-action-list)'; @@ -27,7 +30,7 @@ export class MatListHarness extends return new HarnessPredicate(MatListHarness, options); } - _itemHarness = MatListItemHarness; + override _itemHarness = MatListItemHarness; } /** Harness for interacting with a list item. */ diff --git a/src/material/list/testing/list-item-harness-base.ts b/src/material/list/testing/list-item-harness-base.ts index ac8543075371..b600a2c96c01 100644 --- a/src/material/list/testing/list-item-harness-base.ts +++ b/src/material/list/testing/list-item-harness-base.ts @@ -28,11 +28,14 @@ const avatarSelector = '.mat-list-avatar'; * @return A `HarnessPredicate` for the given harness type with the given options applied. */ export function getListItemPredicate( - harnessType: ComponentHarnessConstructor, - options: BaseListItemHarnessFilters): HarnessPredicate { - return new HarnessPredicate(harnessType, options) - .addOption('text', options.text, - (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text)); + harnessType: ComponentHarnessConstructor, + options: BaseListItemHarnessFilters, +): HarnessPredicate { + return new HarnessPredicate(harnessType, options).addOption( + 'text', + options.text, + (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text), + ); } /** Harness for interacting with a list subheader. */ @@ -40,9 +43,11 @@ export class MatSubheaderHarness extends ComponentHarness { static hostSelector = '.mat-subheader'; static with(options: SubheaderHarnessFilters = {}): HarnessPredicate { - return new HarnessPredicate(MatSubheaderHarness, options) - .addOption('text', options.text, - (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text)); + return new HarnessPredicate(MatSubheaderHarness, options).addOption( + 'text', + options.text, + (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text), + ); } /** Gets the full text content of the list item (including text from any font icons). */ @@ -53,7 +58,7 @@ export class MatSubheaderHarness extends ComponentHarness { /** Selectors for the various list item sections that may contain user content. */ export const enum MatListItemSection { - CONTENT = '.mat-list-item-content' + CONTENT = '.mat-list-item-content', // TODO(mmalerba): consider adding sections for leading/trailing icons. } @@ -61,9 +66,7 @@ export const enum MatListItemSection { * Shared behavior among the harnesses for the various `MatListItem` flavors. * @docs-private */ -export abstract class MatListItemHarnessBase - extends ContentContainerComponentHarness { - +export abstract class MatListItemHarnessBase extends ContentContainerComponentHarness { private _lines = this.locatorForAll('.mat-line'); private _avatar = this.locatorForOptional(avatarSelector); private _icon = this.locatorForOptional(iconSelector); @@ -81,12 +84,12 @@ export abstract class MatListItemHarnessBase /** Whether this list item has an avatar. */ async hasAvatar(): Promise { - return !!await this._avatar(); + return !!(await this._avatar()); } /** Whether this list item has an icon. */ async hasIcon(): Promise { - return !!await this._icon(); + return !!(await this._icon()); } /** diff --git a/src/material/list/testing/nav-list-harness.ts b/src/material/list/testing/nav-list-harness.ts index dac531dded15..50db93aeac38 100644 --- a/src/material/list/testing/nav-list-harness.ts +++ b/src/material/list/testing/nav-list-harness.ts @@ -13,7 +13,10 @@ import {getListItemPredicate, MatListItemHarnessBase} from './list-item-harness- /** Harness for interacting with a standard mat-nav-list in tests. */ export class MatNavListHarness extends MatListHarnessBase< - typeof MatNavListItemHarness, MatNavListItemHarness, NavListItemHarnessFilters> { + typeof MatNavListItemHarness, + MatNavListItemHarness, + NavListItemHarnessFilters +> { /** The selector for the host element of a `MatNavList` instance. */ static hostSelector = '.mat-nav-list'; @@ -27,7 +30,7 @@ export class MatNavListHarness extends MatListHarnessBase< return new HarnessPredicate(MatNavListHarness, options); } - _itemHarness = MatNavListItemHarness; + override _itemHarness = MatNavListItemHarness; } /** Harness for interacting with a nav list item. */ @@ -42,9 +45,11 @@ export class MatNavListItemHarness extends MatListItemHarnessBase { * @return a `HarnessPredicate` configured with the given options. */ static with(options: NavListItemHarnessFilters = {}): HarnessPredicate { - return getListItemPredicate(MatNavListItemHarness, options) - .addOption('href', options.href, - async (harness, href) => HarnessPredicate.stringMatches(harness.getHref(), href)); + return getListItemPredicate(MatNavListItemHarness, options).addOption( + 'href', + options.href, + async (harness, href) => HarnessPredicate.stringMatches(harness.getHref(), href), + ); } /** Gets the href for this nav list item. */ diff --git a/src/material/list/testing/selection-list-harness.ts b/src/material/list/testing/selection-list-harness.ts index 3178174358f8..e60e66e98c4b 100644 --- a/src/material/list/testing/selection-list-harness.ts +++ b/src/material/list/testing/selection-list-harness.ts @@ -12,13 +12,16 @@ import {MatListHarnessBase} from './list-harness-base'; import { ListItemHarnessFilters, ListOptionHarnessFilters, - SelectionListHarnessFilters + SelectionListHarnessFilters, } from './list-harness-filters'; import {getListItemPredicate, MatListItemHarnessBase} from './list-item-harness-base'; /** Harness for interacting with a standard mat-selection-list in tests. */ export class MatSelectionListHarness extends MatListHarnessBase< - typeof MatListOptionHarness, MatListOptionHarness, ListOptionHarnessFilters> { + typeof MatListOptionHarness, + MatListOptionHarness, + ListOptionHarnessFilters +> { /** The selector for the host element of a `MatSelectionList` instance. */ static hostSelector = '.mat-selection-list'; @@ -28,16 +31,17 @@ export class MatSelectionListHarness extends MatListHarnessBase< * @param options Options for filtering which selection list instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ - static with(options: SelectionListHarnessFilters = {}): - HarnessPredicate { + static with( + options: SelectionListHarnessFilters = {}, + ): HarnessPredicate { return new HarnessPredicate(MatSelectionListHarness, options); } - _itemHarness = MatListOptionHarness; + override _itemHarness = MatListOptionHarness; /** Whether the selection list is disabled. */ async isDisabled(): Promise { - return await (await this.host()).getAttribute('aria-disabled') === 'true'; + return (await (await this.host()).getAttribute('aria-disabled')) === 'true'; } /** @@ -82,27 +86,30 @@ export class MatListOptionHarness extends MatListItemHarnessBase { * @return a `HarnessPredicate` configured with the given options. */ static with(options: ListOptionHarnessFilters = {}): HarnessPredicate { - return getListItemPredicate(MatListOptionHarness, options) - .addOption('is selected', options.selected, - async (harness, selected) => await harness.isSelected() === selected); + return getListItemPredicate(MatListOptionHarness, options).addOption( + 'is selected', + options.selected, + async (harness, selected) => (await harness.isSelected()) === selected, + ); } private _itemContent = this.locatorFor('.mat-list-item-content'); /** Gets the position of the checkbox relative to the list option content. */ async getCheckboxPosition(): Promise { - return await (await this._itemContent()).hasClass('mat-list-item-content-reverse') ? - 'after' : 'before'; + return (await (await this._itemContent()).hasClass('mat-list-item-content-reverse')) + ? 'after' + : 'before'; } /** Whether the list option is selected. */ async isSelected(): Promise { - return await (await this.host()).getAttribute('aria-selected') === 'true'; + return (await (await this.host()).getAttribute('aria-selected')) === 'true'; } /** Whether the list option is disabled. */ async isDisabled(): Promise { - return await (await this.host()).getAttribute('aria-disabled') === 'true'; + return (await (await this.host()).getAttribute('aria-disabled')) === 'true'; } /** Focuses the list option. */ @@ -130,7 +137,7 @@ export class MatListOptionHarness extends MatListItemHarnessBase { * nothing if it is already checked. */ async select() { - if (!await this.isSelected()) { + if (!(await this.isSelected())) { return this.toggle(); } } diff --git a/src/material/list/testing/shared.spec.ts b/src/material/list/testing/shared.spec.ts index d4234cd75bcc..73a9ed4478d9 100644 --- a/src/material/list/testing/shared.spec.ts +++ b/src/material/list/testing/shared.spec.ts @@ -3,7 +3,7 @@ import { ComponentHarness, ComponentHarnessConstructor, HarnessPredicate, - parallel + parallel, } from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {Component, Type} from '@angular/core'; @@ -17,29 +17,30 @@ import {BaseListItemHarnessFilters} from './list-harness-filters'; import { MatListItemHarnessBase, MatListItemSection, - MatSubheaderHarness + MatSubheaderHarness, } from './list-item-harness-base'; import {MatNavListHarness, MatNavListItemHarness} from './nav-list-harness'; import {MatListOptionHarness, MatSelectionListHarness} from './selection-list-harness'; /** Tests that apply to all types of mat-list. */ function runBaseListFunctionalityTests< - L extends MatListHarnessBase< - ComponentHarnessConstructor & {with: (x?: any) => HarnessPredicate}, - I, - BaseListItemHarnessFilters - >, - I extends MatListItemHarnessBase, + L extends MatListHarnessBase< + ComponentHarnessConstructor & {with: (x?: any) => HarnessPredicate}, + I, + BaseListItemHarnessFilters + >, + I extends MatListItemHarnessBase, >( - testComponent: Type<{}>, - listModule: typeof MatListModule, - listHarness: ComponentHarnessConstructor & { - with: (config?: BaseHarnessFilters) => HarnessPredicate - }, - listItemHarnessBase: typeof MatListItemHarnessBase, - subheaderHarness: typeof MatSubheaderHarness, - dividerHarness: typeof MatDividerHarness, - selectors: {content: string}) { + testComponent: Type<{}>, + listModule: typeof MatListModule, + listHarness: ComponentHarnessConstructor & { + with: (config?: BaseHarnessFilters) => HarnessPredicate; + }, + listItemHarnessBase: typeof MatListItemHarnessBase, + subheaderHarness: typeof MatSubheaderHarness, + dividerHarness: typeof MatDividerHarness, + selectors: {content: string}, +) { describe('base list functionality', () => { let simpleListHarness: L; let emptyListHarness: L; @@ -54,15 +55,19 @@ function runBaseListFunctionalityTests< fixture = TestBed.createComponent(testComponent); fixture.detectChanges(); const loader = TestbedHarnessEnvironment.loader(fixture); - simpleListHarness = - await loader.getHarness(listHarness.with({selector: '.test-base-list-functionality'})); + simpleListHarness = await loader.getHarness( + listHarness.with({selector: '.test-base-list-functionality'}), + ); emptyListHarness = await loader.getHarness(listHarness.with({selector: '.test-empty'})); }); it('should get all items', async () => { const items = await simpleListHarness.getItems(); - expect(await parallel(() => items.map(i => i.getText()))) - .toEqual(['Item 1', 'Item 2', 'Item 3']); + expect(await parallel(() => items.map(i => i.getText()))).toEqual([ + 'Item 1', + 'Item 2', + 'Item 3', + ]); }); it('should get all items matching text', async () => { @@ -80,8 +85,10 @@ function runBaseListFunctionalityTests< expect(sections[0].heading).toBeUndefined(); expect(await parallel(() => sections[0].items.map(i => i.getText()))).toEqual(['Item 1']); expect(sections[1].heading).toBe('Section 1'); - expect(await parallel(() => sections[1].items.map(i => i.getText()))) - .toEqual(['Item 2', 'Item 3']); + expect(await parallel(() => sections[1].items.map(i => i.getText()))).toEqual([ + 'Item 2', + 'Item 3', + ]); expect(sections[2].heading).toBe('Section 2'); expect(sections[2].items.length).toEqual(0); }); @@ -109,55 +116,75 @@ function runBaseListFunctionalityTests< it('should get all items, subheaders, and dividers', async () => { const itemsSubheadersAndDividers = - await simpleListHarness.getItemsWithSubheadersAndDividers(); + await simpleListHarness.getItemsWithSubheadersAndDividers(); expect(itemsSubheadersAndDividers.length).toBe(7); expect(itemsSubheadersAndDividers[0] instanceof listItemHarnessBase).toBe(true); - expect(await (itemsSubheadersAndDividers[0] as MatListItemHarnessBase).getText()) - .toBe('Item 1'); + expect(await (itemsSubheadersAndDividers[0] as MatListItemHarnessBase).getText()).toBe( + 'Item 1', + ); expect(itemsSubheadersAndDividers[1] instanceof subheaderHarness).toBe(true); - expect(await (itemsSubheadersAndDividers[1] as MatSubheaderHarness).getText()) - .toBe('Section 1'); + expect(await (itemsSubheadersAndDividers[1] as MatSubheaderHarness).getText()).toBe( + 'Section 1', + ); expect(itemsSubheadersAndDividers[2] instanceof dividerHarness).toBe(true); expect(itemsSubheadersAndDividers[3] instanceof listItemHarnessBase).toBe(true); - expect(await (itemsSubheadersAndDividers[3] as MatListItemHarnessBase).getText()) - .toBe('Item 2'); + expect(await (itemsSubheadersAndDividers[3] as MatListItemHarnessBase).getText()).toBe( + 'Item 2', + ); expect(itemsSubheadersAndDividers[4] instanceof listItemHarnessBase).toBe(true); - expect(await (itemsSubheadersAndDividers[4] as MatListItemHarnessBase).getText()) - .toBe('Item 3'); + expect(await (itemsSubheadersAndDividers[4] as MatListItemHarnessBase).getText()).toBe( + 'Item 3', + ); expect(itemsSubheadersAndDividers[5] instanceof subheaderHarness).toBe(true); - expect(await (itemsSubheadersAndDividers[5] as MatSubheaderHarness).getText()) - .toBe('Section 2'); + expect(await (itemsSubheadersAndDividers[5] as MatSubheaderHarness).getText()).toBe( + 'Section 2', + ); expect(itemsSubheadersAndDividers[6] instanceof dividerHarness).toBe(true); }); it('should get all items, subheaders, and dividers excluding some harness types', async () => { - const items = await simpleListHarness.getItemsWithSubheadersAndDividers( - {subheader: false, divider: false}); - const subheaders = await simpleListHarness.getItemsWithSubheadersAndDividers( - {item: false, divider: false}); - const dividers = await simpleListHarness.getItemsWithSubheadersAndDividers( - {item: false, subheader: false}); - expect(await parallel(() => items.map(i => i.getText()))) - .toEqual(['Item 1', 'Item 2', 'Item 3']); - expect(await parallel(() => subheaders.map(s => s.getText()))) - .toEqual(['Section 1', 'Section 2']); - expect(await parallel(() => dividers.map(d => d.getOrientation()))) - .toEqual(['horizontal', 'horizontal']); + const items = await simpleListHarness.getItemsWithSubheadersAndDividers({ + subheader: false, + divider: false, + }); + const subheaders = await simpleListHarness.getItemsWithSubheadersAndDividers({ + item: false, + divider: false, + }); + const dividers = await simpleListHarness.getItemsWithSubheadersAndDividers({ + item: false, + subheader: false, + }); + expect(await parallel(() => items.map(i => i.getText()))).toEqual([ + 'Item 1', + 'Item 2', + 'Item 3', + ]); + expect(await parallel(() => subheaders.map(s => s.getText()))).toEqual([ + 'Section 1', + 'Section 2', + ]); + expect(await parallel(() => dividers.map(d => d.getOrientation()))).toEqual([ + 'horizontal', + 'horizontal', + ]); }); it('should get all items, subheaders, and dividers with filters', async () => { const itemsSubheadersAndDividers = await simpleListHarness.getItemsWithSubheadersAndDividers({ item: {text: /1/}, - subheader: {text: /2/} + subheader: {text: /2/}, }); expect(itemsSubheadersAndDividers.length).toBe(4); expect(itemsSubheadersAndDividers[0] instanceof listItemHarnessBase).toBe(true); - expect(await (itemsSubheadersAndDividers[0] as MatListItemHarnessBase).getText()) - .toBe('Item 1'); + expect(await (itemsSubheadersAndDividers[0] as MatListItemHarnessBase).getText()).toBe( + 'Item 1', + ); expect(itemsSubheadersAndDividers[1] instanceof dividerHarness).toBe(true); expect(itemsSubheadersAndDividers[2] instanceof subheaderHarness).toBe(true); - expect(await (itemsSubheadersAndDividers[2] as MatSubheaderHarness).getText()) - .toBe('Section 2'); + expect(await (itemsSubheadersAndDividers[2] as MatSubheaderHarness).getText()).toBe( + 'Section 2', + ); expect(itemsSubheadersAndDividers[3] instanceof dividerHarness).toBe(true); }); @@ -199,31 +226,43 @@ function runBaseListFunctionalityTests< }); } - /** * Function that can be used to run the shared tests for either the non-MDC or MDC based list * harness. */ export function runHarnessTests( - listModule: typeof MatListModule, - listHarness: typeof MatListHarness, - actionListHarness: typeof MatActionListHarness, - navListHarness: typeof MatNavListHarness, - selectionListHarness: typeof MatSelectionListHarness, - listItemHarnessBase: typeof MatListItemHarnessBase, - subheaderHarness: typeof MatSubheaderHarness, - dividerHarness: typeof MatDividerHarness, - selectors: {content: string}) { + listModule: typeof MatListModule, + listHarness: typeof MatListHarness, + actionListHarness: typeof MatActionListHarness, + navListHarness: typeof MatNavListHarness, + selectionListHarness: typeof MatSelectionListHarness, + listItemHarnessBase: typeof MatListItemHarnessBase, + subheaderHarness: typeof MatSubheaderHarness, + dividerHarness: typeof MatDividerHarness, + selectors: {content: string}, +) { describe('MatListHarness', () => { runBaseListFunctionalityTests( - ListHarnessTest, listModule, listHarness, listItemHarnessBase, subheaderHarness, - dividerHarness, selectors); + ListHarnessTest, + listModule, + listHarness, + listItemHarnessBase, + subheaderHarness, + dividerHarness, + selectors, + ); }); describe('MatActionListHarness', () => { runBaseListFunctionalityTests( - ActionListHarnessTest, listModule, actionListHarness, listItemHarnessBase, subheaderHarness, - dividerHarness, selectors); + ActionListHarnessTest, + listModule, + actionListHarness, + listItemHarnessBase, + subheaderHarness, + dividerHarness, + selectors, + ); describe('additional functionality', () => { let harness: MatActionListHarness; @@ -239,7 +278,8 @@ export function runHarnessTests( fixture.detectChanges(); const loader = TestbedHarnessEnvironment.loader(fixture); harness = await loader.getHarness( - actionListHarness.with({selector: '.test-base-list-functionality'})); + actionListHarness.with({selector: '.test-base-list-functionality'}), + ); }); it('should click items', async () => { @@ -257,8 +297,14 @@ export function runHarnessTests( describe('MatNavListHarness', () => { runBaseListFunctionalityTests( - NavListHarnessTest, listModule, navListHarness, listItemHarnessBase, subheaderHarness, - dividerHarness, selectors); + NavListHarnessTest, + listModule, + navListHarness, + listItemHarnessBase, + subheaderHarness, + dividerHarness, + selectors, + ); describe('additional functionality', () => { let harness: MatNavListHarness; @@ -274,7 +320,8 @@ export function runHarnessTests( fixture.detectChanges(); const loader = TestbedHarnessEnvironment.loader(fixture); harness = await loader.getHarness( - navListHarness.with({selector: '.test-base-list-functionality'})); + navListHarness.with({selector: '.test-base-list-functionality'}), + ); }); it('should click items', async () => { @@ -303,8 +350,14 @@ export function runHarnessTests( describe('MatSelectionListHarness', () => { runBaseListFunctionalityTests( - SelectionListHarnessTest, listModule, selectionListHarness, listItemHarnessBase, - subheaderHarness, dividerHarness, selectors); + SelectionListHarnessTest, + listModule, + selectionListHarness, + listItemHarnessBase, + subheaderHarness, + dividerHarness, + selectors, + ); describe('additional functionality', () => { let harness: MatSelectionListHarness; @@ -321,9 +374,11 @@ export function runHarnessTests( fixture.detectChanges(); const loader = TestbedHarnessEnvironment.loader(fixture); harness = await loader.getHarness( - selectionListHarness.with({selector: '.test-base-list-functionality'})); - emptyHarness = - await loader.getHarness(selectionListHarness.with({selector: '.test-empty'})); + selectionListHarness.with({selector: '.test-base-list-functionality'}), + ); + emptyHarness = await loader.getHarness( + selectionListHarness.with({selector: '.test-empty'}), + ); }); it('should check disabled state of list', async () => { @@ -342,8 +397,10 @@ export function runHarnessTests( expect((await harness.getItems({selected: true})).length).toBe(0); await harness.selectItems({text: /1/}, {text: /3/}); const selected = await harness.getItems({selected: true}); - expect(await parallel(() => selected.map(item => item.getText()))) - .toEqual(['Item 1', 'Item 3']); + expect(await parallel(() => selected.map(item => item.getText()))).toEqual([ + 'Item 1', + 'Item 3', + ]); }); it('should uncheck multiple options', async () => { @@ -423,7 +480,7 @@ export function runHarnessTests( - ` + `, }) class ListHarnessTest {} @@ -447,7 +504,7 @@ class ListHarnessTest {} - ` + `, }) class ActionListHarnessTest { lastClicked: string; @@ -473,7 +530,7 @@ class ActionListHarnessTest { - ` + `, }) class NavListHarnessTest { lastClicked: string; @@ -504,7 +561,7 @@ class NavListHarnessTest { - ` + `, }) class SelectionListHarnessTest { disableItem3 = false; diff --git a/src/material/menu/BUILD.bazel b/src/material/menu/BUILD.bazel index c51259eecb86..2c2c792fa63f 100644 --- a/src/material/menu/BUILD.bazel +++ b/src/material/menu/BUILD.bazel @@ -19,7 +19,6 @@ ng_module( exclude = ["**/*.spec.ts"], ), assets = [":menu.css"] + glob(["**/*.html"]), - module_name = "@angular/material/menu", deps = [ "//src:dev_mode_types", "//src/cdk/a11y", diff --git a/src/material/menu/_menu-legacy-index.scss b/src/material/menu/_menu-legacy-index.scss new file mode 100644 index 000000000000..ba7bb2f503f2 --- /dev/null +++ b/src/material/menu/_menu-legacy-index.scss @@ -0,0 +1,2 @@ +@forward 'menu-theme' hide color, theme, typography; +@forward 'menu-theme' as mat-menu-* hide mat-menu-density; diff --git a/src/material/menu/_menu-theme.import.scss b/src/material/menu/_menu-theme.import.scss new file mode 100644 index 000000000000..f1c9e9cdcb28 --- /dev/null +++ b/src/material/menu/_menu-theme.import.scss @@ -0,0 +1,10 @@ +@forward '../core/style/private.import'; +@forward '../core/theming/theming.import'; +@forward '../core/typography/typography-utils.import'; +@forward 'menu-theme' hide color, theme, typography; +@forward 'menu-theme' as mat-menu-* hide mat-menu-density; + +@import '../core/style/private'; +@import '../core/theming/palette'; +@import '../core/theming/theming'; +@import '../core/typography/typography-utils'; diff --git a/src/material/menu/_menu-theme.scss b/src/material/menu/_menu-theme.scss index f4d982b29283..4985ba5807a8 100644 --- a/src/material/menu/_menu-theme.scss +++ b/src/material/menu/_menu-theme.scss @@ -1,35 +1,36 @@ -@import '../core/style/private'; -@import '../core/theming/palette'; -@import '../core/theming/theming'; -@import '../core/typography/typography-utils'; +@use 'sass:map'; +@use '../core/style/private'; +@use '../core/theming/theming'; +@use '../core/typography/typography'; +@use '../core/typography/typography-utils'; -@mixin mat-menu-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $background: map-get($config, background); - $foreground: map-get($config, foreground); +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $background: map.get($config, background); + $foreground: map.get($config, foreground); .mat-menu-panel { - @include mat-private-theme-overridable-elevation(4, $config); - background: mat-color($background, 'card'); + @include private.private-theme-overridable-elevation(4, $config); + background: theming.get-color-from-palette($background, 'card'); } .mat-menu-item { background: transparent; - color: mat-color($foreground, 'text'); + color: theming.get-color-from-palette($foreground, 'text'); &[disabled] { &, - &::after, + .mat-menu-submenu-icon, .mat-icon-no-color { - color: mat-color($foreground, 'disabled'); + color: theming.get-color-from-palette($foreground, 'disabled'); } } } .mat-menu-item .mat-icon-no-color, - .mat-menu-item-submenu-trigger::after { - color: mat-color($foreground, 'icon'); + .mat-menu-submenu-icon { + color: theming.get-color-from-palette($foreground, 'icon'); } .mat-menu-item:hover, @@ -37,39 +38,40 @@ .mat-menu-item.cdk-keyboard-focused, .mat-menu-item-highlighted { &:not([disabled]) { - background: mat-color($background, 'hover'); + background: theming.get-color-from-palette($background, 'hover'); } } } -@mixin mat-menu-typography($config-or-theme) { - $config: mat-get-typography-config($config-or-theme); +@mixin typography($config-or-theme) { + $config: typography.private-typography-to-2014-config( + theming.get-typography-config($config-or-theme)); .mat-menu-item { font: { - family: mat-font-family($config, body-1); - size: mat-font-size($config, body-1); - weight: mat-font-weight($config, body-1); + family: typography-utils.font-family($config, body-1); + size: typography-utils.font-size($config, body-1); + weight: typography-utils.font-weight($config, body-1); } } } -@mixin _mat-menu-density($config-or-theme) {} +@mixin _density($config-or-theme) {} -@mixin mat-menu-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-menu') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-menu') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); @if $color != null { - @include mat-menu-color($color); + @include color($color); } @if $density != null { - @include _mat-menu-density($density); + @include _density($density); } @if $typography != null { - @include mat-menu-typography($typography); + @include typography($typography); } } } diff --git a/src/material/menu/menu-animations.ts b/src/material/menu/menu-animations.ts index 790682f501d9..5cf62c6e1f65 100644 --- a/src/material/menu/menu-animations.ts +++ b/src/material/menu/menu-animations.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import{ +import { trigger, state, style, @@ -34,18 +34,26 @@ export const matMenuAnimations: { * delay to display the ripple. */ transformMenu: trigger('transformMenu', [ - state('void', style({ - opacity: 0, - transform: 'scale(0.8)' - })), - transition('void => enter', animate('120ms cubic-bezier(0, 0, 0.2, 1)', style({ - opacity: 1, - transform: 'scale(1)' - }))), - transition('* => void', animate('100ms 25ms linear', style({opacity: 0}))) + state( + 'void', + style({ + opacity: 0, + transform: 'scale(0.8)', + }), + ), + transition( + 'void => enter', + animate( + '120ms cubic-bezier(0, 0, 0.2, 1)', + style({ + opacity: 1, + transform: 'scale(1)', + }), + ), + ), + transition('* => void', animate('100ms 25ms linear', style({opacity: 0}))), ]), - /** * This animation fades in the background color and content of the menu panel * after its containing element is scaled in. @@ -56,9 +64,9 @@ export const matMenuAnimations: { state('showing', style({opacity: 1})), transition('void => *', [ style({opacity: 0}), - animate('400ms 100ms cubic-bezier(0.55, 0, 0.55, 0.2)') - ]) - ]) + animate('400ms 100ms cubic-bezier(0.55, 0, 0.55, 0.2)'), + ]), + ]), }; /** diff --git a/src/material/menu/menu-content.ts b/src/material/menu/menu-content.ts index be4281eee281..1510ec0e9c55 100644 --- a/src/material/menu/menu-content.ts +++ b/src/material/menu/menu-content.ts @@ -29,19 +29,13 @@ import {Subject} from 'rxjs'; */ export const MAT_MENU_CONTENT = new InjectionToken('MatMenuContent'); -/** - * Menu content that will be rendered lazily once the menu is opened. - */ -@Directive({ - selector: 'ng-template[matMenuContent]', - providers: [{provide: MAT_MENU_CONTENT, useExisting: MatMenuContent}], -}) -export class MatMenuContent implements OnDestroy { +@Directive() +export abstract class _MatMenuContentBase implements OnDestroy { private _portal: TemplatePortal; private _outlet: DomPortalOutlet; /** Emits when the menu content has been attached. */ - _attached = new Subject(); + readonly _attached = new Subject(); constructor( private _template: TemplateRef, @@ -50,7 +44,8 @@ export class MatMenuContent implements OnDestroy { private _injector: Injector, private _viewContainerRef: ViewContainerRef, @Inject(DOCUMENT) private _document: any, - private _changeDetectorRef?: ChangeDetectorRef) {} + private _changeDetectorRef?: ChangeDetectorRef, + ) {} /** * Attaches the content with a particular context. @@ -64,8 +59,12 @@ export class MatMenuContent implements OnDestroy { this.detach(); if (!this._outlet) { - this._outlet = new DomPortalOutlet(this._document.createElement('div'), - this._componentFactoryResolver, this._appRef, this._injector); + this._outlet = new DomPortalOutlet( + this._document.createElement('div'), + this._componentFactoryResolver, + this._appRef, + this._injector, + ); } const element: HTMLElement = this._template.elementRef.nativeElement; @@ -105,3 +104,12 @@ export class MatMenuContent implements OnDestroy { } } } + +/** + * Menu content that will be rendered lazily once the menu is opened. + */ +@Directive({ + selector: 'ng-template[matMenuContent]', + providers: [{provide: MAT_MENU_CONTENT, useExisting: MatMenuContent}], +}) +export class MatMenuContent extends _MatMenuContentBase {} diff --git a/src/material/menu/menu-errors.ts b/src/material/menu/menu-errors.ts index d9773926a51b..16a855a38e75 100644 --- a/src/material/menu/menu-errors.ts +++ b/src/material/menu/menu-errors.ts @@ -38,13 +38,14 @@ export function throwMatMenuInvalidPositionY() { Example: `); } - /** * Throws an exception for the case when a menu is assigned * to a trigger that is placed inside the same menu. * @docs-private */ export function throwMatMenuRecursiveError() { - throw Error(`matMenuTriggerFor: menu cannot contain its own trigger. Assign a menu that is ` + - `not a parent of the trigger or move the trigger outside of the menu.`); + throw Error( + `matMenuTriggerFor: menu cannot contain its own trigger. Assign a menu that is ` + + `not a parent of the trigger or move the trigger outside of the menu.`, + ); } diff --git a/src/material/menu/menu-item.html b/src/material/menu/menu-item.html index a025ff57a01e..8073c518f777 100644 --- a/src/material/menu/menu-item.html +++ b/src/material/menu/menu-item.html @@ -3,3 +3,9 @@ [matRippleDisabled]="disableRipple || disabled" [matRippleTrigger]="_getHostElement()">
+ + diff --git a/src/material/menu/menu-item.ts b/src/material/menu/menu-item.ts index 79df14589031..63bb1ce25852 100644 --- a/src/material/menu/menu-item.ts +++ b/src/material/menu/menu-item.ts @@ -7,7 +7,6 @@ */ import {FocusableOption, FocusMonitor, FocusOrigin} from '@angular/cdk/a11y'; -import {BooleanInput} from '@angular/cdk/coercion'; import { ChangeDetectionStrategy, Component, @@ -17,12 +16,12 @@ import { Inject, Optional, Input, - HostListener, AfterViewInit, + ChangeDetectorRef, } from '@angular/core'; import { - CanDisable, CanDisableCtor, - CanDisableRipple, CanDisableRippleCtor, + CanDisable, + CanDisableRipple, mixinDisabled, mixinDisableRipple, } from '@angular/material/core'; @@ -32,9 +31,7 @@ import {MAT_MENU_PANEL, MatMenuPanel} from './menu-panel'; // Boilerplate for applying mixins to MatMenuItem. /** @docs-private */ -class MatMenuItemBase {} -const _MatMenuItemMixinBase: CanDisableRippleCtor & CanDisableCtor & typeof MatMenuItemBase = - mixinDisableRipple(mixinDisabled(MatMenuItemBase)); +const _MatMenuItemBase = mixinDisableRipple(mixinDisabled(class {})); /** * Single item inside of a `mat-menu`. Provides the menu item styling and accessibility treatment. @@ -52,14 +49,17 @@ const _MatMenuItemMixinBase: CanDisableRippleCtor & CanDisableCtor & typeof MatM '[attr.aria-disabled]': 'disabled.toString()', '[attr.disabled]': 'disabled || null', 'class': 'mat-focus-indicator', + '(click)': '_checkDisabled($event)', + '(mouseenter)': '_handleMouseEnter()', }, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, templateUrl: 'menu-item.html', }) -export class MatMenuItem extends _MatMenuItemMixinBase - implements FocusableOption, CanDisable, CanDisableRipple, AfterViewInit, OnDestroy { - +export class MatMenuItem + extends _MatMenuItemBase + implements FocusableOption, CanDisable, CanDisableRipple, AfterViewInit, OnDestroy +{ /** ARIA role for the menu item. */ @Input() role: 'menuitem' | 'menuitemradio' | 'menuitemcheckbox' = 'menuitem'; @@ -83,8 +83,13 @@ export class MatMenuItem extends _MatMenuItemMixinBase */ @Inject(DOCUMENT) _document?: any, private _focusMonitor?: FocusMonitor, - @Inject(MAT_MENU_PANEL) @Optional() public _parentMenu?: MatMenuPanel) { - + @Inject(MAT_MENU_PANEL) @Optional() public _parentMenu?: MatMenuPanel, + /** + * @deprecated `_changeDetectorRef` to become a required parameter. + * @breaking-change 14.0.0 + */ + private _changeDetectorRef?: ChangeDetectorRef, + ) { // @breaking-change 8.0.0 make `_focusMonitor` and `document` required params. super(); @@ -137,12 +142,6 @@ export class MatMenuItem extends _MatMenuItemMixinBase } /** Prevents the default element actions if it is disabled. */ - // We have to use a `HostListener` here in order to support both Ivy and ViewEngine. - // In Ivy the `host` bindings will be merged when this class is extended, whereas in - // ViewEngine they're overwritten. - // TODO(crisbeto): we move this back into `host` once Ivy is turned on by default. - // tslint:disable-next-line:no-host-decorator-in-concrete - @HostListener('click', ['$event']) _checkDisabled(event: Event): void { if (this.disabled) { event.preventDefault(); @@ -151,12 +150,6 @@ export class MatMenuItem extends _MatMenuItemMixinBase } /** Emits to the hover stream. */ - // We have to use a `HostListener` here in order to support both Ivy and ViewEngine. - // In Ivy the `host` bindings will be merged when this class is extended, whereas in - // ViewEngine they're overwritten. - // TODO(crisbeto): we move this back into `host` once Ivy is turned on by default. - // tslint:disable-next-line:no-host-decorator-in-concrete - @HostListener('mouseenter') _handleMouseEnter() { this._hovered.next(this); } @@ -168,13 +161,18 @@ export class MatMenuItem extends _MatMenuItemMixinBase // Strip away icons so they don't show up in the text. for (let i = 0; i < icons.length; i++) { - const icon = icons[i]; - icon.parentNode?.removeChild(icon); + icons[i].remove(); } return clone.textContent?.trim() || ''; } - static ngAcceptInputType_disabled: BooleanInput; - static ngAcceptInputType_disableRipple: BooleanInput; + _setHighlighted(isHighlighted: boolean) { + // We need to mark this for check for the case where the content is coming from a + // `matMenuContent` whose change detection tree is at the declaration position, + // not the insertion position. See #23175. + // @breaking-change 14.0.0 Remove null check for `_changeDetectorRef`. + this._highlighted = isHighlighted; + this._changeDetectorRef?.markForCheck(); + } } diff --git a/src/material/menu/menu-module.ts b/src/material/menu/menu-module.ts index c95636d2d622..a5e04822933b 100644 --- a/src/material/menu/menu-module.ts +++ b/src/material/menu/menu-module.ts @@ -16,30 +16,17 @@ import {MatMenuContent} from './menu-content'; import {MatMenuItem} from './menu-item'; import {MAT_MENU_SCROLL_STRATEGY_FACTORY_PROVIDER, MatMenuTrigger} from './menu-trigger'; -/** - * Used by both the current `MatMenuModule` and the MDC `MatMenuModule` - * to declare the menu-related directives. - */ @NgModule({ - exports: [MatMenuTrigger, MatMenuContent, MatCommonModule], - declarations: [ + imports: [CommonModule, MatCommonModule, MatRippleModule, OverlayModule], + exports: [ + CdkScrollableModule, + MatCommonModule, + MatMenu, + MatMenuItem, MatMenuTrigger, MatMenuContent, ], - providers: [MAT_MENU_SCROLL_STRATEGY_FACTORY_PROVIDER] -}) -export class _MatMenuDirectivesModule {} - -@NgModule({ - imports: [ - CommonModule, - MatCommonModule, - MatRippleModule, - OverlayModule, - _MatMenuDirectivesModule, - ], - exports: [CdkScrollableModule, MatCommonModule, MatMenu, MatMenuItem, _MatMenuDirectivesModule], - declarations: [MatMenu, MatMenuItem], - providers: [MAT_MENU_SCROLL_STRATEGY_FACTORY_PROVIDER] + declarations: [MatMenu, MatMenuItem, MatMenuTrigger, MatMenuContent], + providers: [MAT_MENU_SCROLL_STRATEGY_FACTORY_PROVIDER], }) export class MatMenuModule {} diff --git a/src/material/menu/menu-panel.ts b/src/material/menu/menu-panel.ts index a5f0f1732a46..795dac077480 100644 --- a/src/material/menu/menu-panel.ts +++ b/src/material/menu/menu-panel.ts @@ -27,7 +27,7 @@ export interface MatMenuPanel { yPosition: MenuPositionY; overlapTrigger: boolean; templateRef: TemplateRef; - close: EventEmitter; + readonly close: EventEmitter; parentMenu?: MatMenuPanel | undefined; direction?: Direction; focusFirstItem: (origin?: FocusOrigin) => void; @@ -36,7 +36,7 @@ export interface MatMenuPanel { setElevation?(depth: number): void; lazyContent?: MatMenuContent; backdropClass?: string; - overlayPanelClass?: string|string[]; + overlayPanelClass?: string | string[]; hasBackdrop?: boolean; readonly panelId?: string; diff --git a/src/material/menu/menu-trigger.ts b/src/material/menu/menu-trigger.ts index 06de01f4fb1d..0456a2e79ac5 100644 --- a/src/material/menu/menu-trigger.ts +++ b/src/material/menu/menu-trigger.ts @@ -6,17 +6,22 @@ * found in the LICENSE file at https://angular.io/license */ -import {FocusMonitor, FocusOrigin, isFakeMousedownFromScreenReader} from '@angular/cdk/a11y'; +import { + FocusMonitor, + FocusOrigin, + isFakeMousedownFromScreenReader, + isFakeTouchstartFromScreenReader, +} from '@angular/cdk/a11y'; import {Direction, Directionality} from '@angular/cdk/bidi'; -import {LEFT_ARROW, RIGHT_ARROW} from '@angular/cdk/keycodes'; +import {ENTER, LEFT_ARROW, RIGHT_ARROW, SPACE} from '@angular/cdk/keycodes'; import { FlexibleConnectedPositionStrategy, HorizontalConnectionPos, Overlay, OverlayConfig, OverlayRef, - VerticalConnectionPos, ScrollStrategy, + VerticalConnectionPos, } from '@angular/cdk/overlay'; import {TemplatePortal} from '@angular/cdk/portal'; import { @@ -34,17 +39,18 @@ import { ViewContainerRef, } from '@angular/core'; import {normalizePassiveListenerOptions} from '@angular/cdk/platform'; -import {asapScheduler, merge, of as observableOf, Subscription} from 'rxjs'; +import {asapScheduler, merge, Observable, of as observableOf, Subscription} from 'rxjs'; import {delay, filter, take, takeUntil} from 'rxjs/operators'; -import {_MatMenuBase} from './menu'; +import {_MatMenuBase, MenuCloseReason} from './menu'; import {throwMatMenuMissingError, throwMatMenuRecursiveError} from './menu-errors'; import {MatMenuItem} from './menu-item'; -import {MatMenuPanel, MAT_MENU_PANEL} from './menu-panel'; +import {MAT_MENU_PANEL, MatMenuPanel} from './menu-panel'; import {MenuPositionX, MenuPositionY} from './menu-positions'; /** Injection token that determines the scroll handling while the menu is open. */ -export const MAT_MENU_SCROLL_STRATEGY = - new InjectionToken<() => ScrollStrategy>('mat-menu-scroll-strategy'); +export const MAT_MENU_SCROLL_STRATEGY = new InjectionToken<() => ScrollStrategy>( + 'mat-menu-scroll-strategy', +); /** @docs-private */ export function MAT_MENU_SCROLL_STRATEGY_FACTORY(overlay: Overlay): () => ScrollStrategy { @@ -66,21 +72,17 @@ const passiveEventListenerOptions = normalizePassiveListenerOptions({passive: tr // TODO(andrewseguin): Remove the kebab versions in favor of camelCased attribute selectors -/** Directive applied to an element that should trigger a `mat-menu`. */ @Directive({ - selector: `[mat-menu-trigger-for], [matMenuTriggerFor]`, host: { - 'class': 'mat-menu-trigger', 'aria-haspopup': 'true', '[attr.aria-expanded]': 'menuOpen || null', '[attr.aria-controls]': 'menuOpen ? menu.panelId : null', + '(click)': '_handleClick($event)', '(mousedown)': '_handleMousedown($event)', '(keydown)': '_handleKeydown($event)', - '(click)': '_handleClick($event)', }, - exportAs: 'matMenuTrigger' }) -export class MatMenuTrigger implements AfterContentInit, OnDestroy { +export abstract class _MatMenuTriggerBase implements AfterContentInit, OnDestroy { private _portal: TemplatePortal; private _overlayRef: OverlayRef | null = null; private _menuOpen: boolean = false; @@ -99,25 +101,33 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { * Handles touch start events on the trigger. * Needs to be an arrow function so we can easily use addEventListener and removeEventListener. */ - private _handleTouchStart = () => this._openedBy = 'touch'; + private _handleTouchStart = (event: TouchEvent) => { + if (!isFakeTouchstartFromScreenReader(event)) { + this._openedBy = 'touch'; + } + }; // Tracking input type is necessary so it's possible to only auto-focus // the first item of the list when the menu is opened via the keyboard - _openedBy: 'mouse' | 'touch' | null = null; + _openedBy: Exclude | undefined = undefined; /** * @deprecated * @breaking-change 8.0.0 */ @Input('mat-menu-trigger-for') - get _deprecatedMatMenuTriggerFor(): MatMenuPanel { return this.menu; } + get _deprecatedMatMenuTriggerFor(): MatMenuPanel { + return this.menu; + } set _deprecatedMatMenuTriggerFor(v: MatMenuPanel) { this.menu = v; } /** References the menu instance that the trigger is associated with. */ @Input('matMenuTriggerFor') - get menu() { return this._menu; } + get menu() { + return this._menu; + } set menu(menu: MatMenuPanel) { if (menu === this._menu) { return; @@ -131,15 +141,14 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { throwMatMenuRecursiveError(); } - this._menuCloseSubscription = menu.close.subscribe( - (reason: 'click' | 'tab' | 'keydown' | undefined) => { - this._destroyMenu(); + this._menuCloseSubscription = menu.close.subscribe((reason: MenuCloseReason) => { + this._destroyMenu(reason); - // If a click closed the menu, we should close the entire chain of nested menus. - if ((reason === 'click' || reason === 'tab') && this._parentMaterialMenu) { - this._parentMaterialMenu.closed.emit(reason); - } - }); + // If a click closed the menu, we should close the entire chain of nested menus. + if ((reason === 'click' || reason === 'tab') && this._parentMaterialMenu) { + this._parentMaterialMenu.closed.emit(reason); + } + }); } } private _menu: MatMenuPanel; @@ -176,23 +185,28 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { // tslint:disable-next-line:no-output-on-prefix @Output() readonly onMenuClose: EventEmitter = this.menuClosed; - constructor(private _overlay: Overlay, - private _element: ElementRef, - private _viewContainerRef: ViewContainerRef, - @Inject(MAT_MENU_SCROLL_STRATEGY) scrollStrategy: any, - @Inject(MAT_MENU_PANEL) @Optional() parentMenu: MatMenuPanel, - // `MatMenuTrigger` is commonly used in combination with a `MatMenuItem`. - // tslint:disable-next-line: lightweight-tokens - @Optional() @Self() private _menuItemInstance: MatMenuItem, - @Optional() private _dir: Directionality, - // TODO(crisbeto): make the _focusMonitor required when doing breaking changes. - // @breaking-change 8.0.0 - private _focusMonitor?: FocusMonitor) { + constructor( + private _overlay: Overlay, + private _element: ElementRef, + private _viewContainerRef: ViewContainerRef, + @Inject(MAT_MENU_SCROLL_STRATEGY) scrollStrategy: any, + @Inject(MAT_MENU_PANEL) @Optional() parentMenu: MatMenuPanel, + // `MatMenuTrigger` is commonly used in combination with a `MatMenuItem`. + // tslint:disable-next-line: lightweight-tokens + @Optional() @Self() private _menuItemInstance: MatMenuItem, + @Optional() private _dir: Directionality, + // TODO(crisbeto): make the _focusMonitor required when doing breaking changes. + // @breaking-change 8.0.0 + private _focusMonitor?: FocusMonitor, + ) { this._scrollStrategy = scrollStrategy; this._parentMaterialMenu = parentMenu instanceof _MatMenuBase ? parentMenu : undefined; - _element.nativeElement.addEventListener('touchstart', this._handleTouchStart, - passiveEventListenerOptions); + _element.nativeElement.addEventListener( + 'touchstart', + this._handleTouchStart, + passiveEventListenerOptions, + ); if (_menuItemInstance) { _menuItemInstance._triggersSubmenu = this.triggersSubmenu(); @@ -210,8 +224,11 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { this._overlayRef = null; } - this._element.nativeElement.removeEventListener('touchstart', this._handleTouchStart, - passiveEventListenerOptions); + this._element.nativeElement.removeEventListener( + 'touchstart', + this._handleTouchStart, + passiveEventListenerOptions, + ); this._menuCloseSubscription.unsubscribe(); this._closingActionsSubscription.unsubscribe(); @@ -250,8 +267,8 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { const overlayConfig = overlayRef.getConfig(); this._setPosition(overlayConfig.positionStrategy as FlexibleConnectedPositionStrategy); - overlayConfig.hasBackdrop = this.menu.hasBackdrop == null ? !this.triggersSubmenu() : - this.menu.hasBackdrop; + overlayConfig.hasBackdrop = + this.menu.hasBackdrop == null ? !this.triggersSubmenu() : this.menu.hasBackdrop; overlayRef.attach(this._getPortal()); if (this.menu.lazyContent) { @@ -283,8 +300,15 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { } } + /** + * Updates the position of the menu to ensure that it fits all options within the viewport. + */ + updatePosition(): void { + this._overlayRef?.updatePosition(); + } + /** Closes the menu and does the necessary cleanup. */ - private _destroyMenu() { + private _destroyMenu(reason: MenuCloseReason) { if (!this._overlayRef || !this.menuOpen) { return; } @@ -292,7 +316,16 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { const menu = this.menu; this._closingActionsSubscription.unsubscribe(); this._overlayRef.detach(); - this._restoreFocus(); + + // Always restore focus if the user is navigating using the keyboard or the menu was opened + // programmatically. We don't restore for non-root triggers, because it can prevent focus + // from making it back to the root trigger when closing a long chain of menus by clicking + // on the backdrop. + if (this.restoreFocus && (reason === 'keydown' || !this._openedBy || !this.triggersSubmenu())) { + this.focus(this._openedBy); + } + + this._openedBy = undefined; if (menu instanceof _MatMenuBase) { menu._resetAnimation(); @@ -304,12 +337,12 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { filter(event => event.toState === 'void'), take(1), // Interrupt if the content got re-attached. - takeUntil(menu.lazyContent._attached) + takeUntil(menu.lazyContent._attached), ) .subscribe({ next: () => menu.lazyContent!.detach(), // No matter whether the content got re-attached, reset the menu. - complete: () => this._setIsMenuOpen(false) + complete: () => this._setIsMenuOpen(false), }); } else { this._setIsMenuOpen(false); @@ -331,8 +364,8 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { this.menu.parentMenu = this.triggersSubmenu() ? this._parentMaterialMenu : undefined; this.menu.direction = this.dir; this._setMenuElevation(); - this._setIsMenuOpen(true); this.menu.focusFirstItem(this._openedBy || 'program'); + this._setIsMenuOpen(true); } /** Updates the menu elevation based on the amount of parent menus that it has. */ @@ -350,31 +383,13 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { } } - /** Restores focus to the element that was focused before the menu was open. */ - private _restoreFocus() { - // We should reset focus if the user is navigating using a keyboard or - // if we have a top-level trigger which might cause focus to be lost - // when clicking on the backdrop. - if (this.restoreFocus) { - if (!this._openedBy) { - // Note that the focus style will show up both for `program` and - // `keyboard` so we don't have to specify which one it is. - this.focus(); - } else if (!this.triggersSubmenu()) { - this.focus(this._openedBy); - } - } - - this._openedBy = null; - } - // set state rather than toggle to support triggers sharing a menu private _setIsMenuOpen(isOpen: boolean): void { this._menuOpen = isOpen; this._menuOpen ? this.menuOpened.emit() : this.menuClosed.emit(); if (this.triggersSubmenu()) { - this._menuItemInstance._highlighted = isOpen; + this._menuItemInstance._setHighlighted(isOpen); } } @@ -413,14 +428,16 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { */ private _getOverlayConfig(): OverlayConfig { return new OverlayConfig({ - positionStrategy: this._overlay.position() - .flexibleConnectedTo(this._element) - .withLockedPosition() - .withTransformOriginOn('.mat-menu-panel, .mat-mdc-menu-panel'), + positionStrategy: this._overlay + .position() + .flexibleConnectedTo(this._element) + .withLockedPosition() + .withGrowAfterOpen() + .withTransformOriginOn('.mat-menu-panel, .mat-mdc-menu-panel'), backdropClass: this.menu.backdropClass || 'cdk-overlay-transparent-backdrop', panelClass: this.menu.overlayPanelClass, scrollStrategy: this._scrollStrategy(), - direction: this._dir + direction: this._dir, }); } @@ -447,10 +464,10 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { */ private _setPosition(positionStrategy: FlexibleConnectedPositionStrategy) { let [originX, originFallbackX]: HorizontalConnectionPos[] = - this.menu.xPosition === 'before' ? ['end', 'start'] : ['start', 'end']; + this.menu.xPosition === 'before' ? ['end', 'start'] : ['start', 'end']; let [overlayY, overlayFallbackY]: VerticalConnectionPos[] = - this.menu.yPosition === 'above' ? ['bottom', 'top'] : ['top', 'bottom']; + this.menu.yPosition === 'above' ? ['bottom', 'top'] : ['top', 'bottom']; let [originY, originFallbackY] = [overlayY, overlayFallbackY]; let [overlayX, overlayFallbackX] = [originX, originFallbackX]; @@ -475,15 +492,15 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { originY: originFallbackY, overlayX, overlayY: overlayFallbackY, - offsetY: -offsetY + offsetY: -offsetY, }, { originX: originFallbackX, originY: originFallbackY, overlayX: overlayFallbackX, overlayY: overlayFallbackY, - offsetY: -offsetY - } + offsetY: -offsetY, + }, ]); } @@ -492,12 +509,14 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { const backdrop = this._overlayRef!.backdropClick(); const detachments = this._overlayRef!.detachments(); const parentClose = this._parentMaterialMenu ? this._parentMaterialMenu.closed : observableOf(); - const hover = this._parentMaterialMenu ? this._parentMaterialMenu._hovered().pipe( - filter(active => active !== this._menuItemInstance), - filter(() => this._menuOpen) - ) : observableOf(); - - return merge(backdrop, parentClose, hover, detachments); + const hover = this._parentMaterialMenu + ? this._parentMaterialMenu._hovered().pipe( + filter(active => active !== this._menuItemInstance), + filter(() => this._menuOpen), + ) + : observableOf(); + + return merge(backdrop, parentClose as Observable, hover, detachments); } /** Handles mouse presses on the trigger. */ @@ -505,7 +524,7 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { if (!isFakeMousedownFromScreenReader(event)) { // Since right or middle button clicks won't trigger the `click` event, // we shouldn't consider the menu as opened by mouse in those cases. - this._openedBy = event.button === 0 ? 'mouse' : null; + this._openedBy = event.button === 0 ? 'mouse' : undefined; // Since clicking on the trigger won't close the menu if it opens a sub-menu, // we should prevent focus from moving onto it via click to avoid the @@ -520,9 +539,17 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { _handleKeydown(event: KeyboardEvent): void { const keyCode = event.keyCode; - if (this.triggersSubmenu() && ( - (keyCode === RIGHT_ARROW && this.dir === 'ltr') || - (keyCode === LEFT_ARROW && this.dir === 'rtl'))) { + // Pressing enter on the trigger will trigger the click handler later. + if (keyCode === ENTER || keyCode === SPACE) { + this._openedBy = 'keyboard'; + } + + if ( + this.triggersSubmenu() && + ((keyCode === RIGHT_ARROW && this.dir === 'ltr') || + (keyCode === LEFT_ARROW && this.dir === 'rtl')) + ) { + this._openedBy = 'keyboard'; this.openMenu(); } } @@ -545,13 +572,14 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { return; } - this._hoverSubscription = this._parentMaterialMenu._hovered() + this._hoverSubscription = this._parentMaterialMenu + ._hovered() // Since we might have multiple competing triggers for the same menu (e.g. a sub-menu // with different data and triggers), we have to delay it by a tick to ensure that // it won't be closed immediately after it is opened. .pipe( filter(active => active === this._menuItemInstance && !active.disabled), - delay(0, asapScheduler) + delay(0, asapScheduler), ) .subscribe(() => { this._openedBy = 'mouse'; @@ -582,5 +610,14 @@ export class MatMenuTrigger implements AfterContentInit, OnDestroy { return this._portal; } - } + +/** Directive applied to an element that should trigger a `mat-menu`. */ +@Directive({ + selector: `[mat-menu-trigger-for], [matMenuTriggerFor]`, + host: { + 'class': 'mat-menu-trigger', + }, + exportAs: 'matMenuTrigger', +}) +export class MatMenuTrigger extends _MatMenuTriggerBase {} diff --git a/src/material/menu/menu.e2e.spec.ts b/src/material/menu/menu.e2e.spec.ts index c34f56ccec9c..45e5466798fe 100644 --- a/src/material/menu/menu.e2e.spec.ts +++ b/src/material/menu/menu.e2e.spec.ts @@ -5,7 +5,7 @@ import { expectLocation, expectToExist, pressKeys, -} from '@angular/cdk/testing/private/e2e'; +} from '../../cdk/testing/private/e2e'; const presenceOf = ExpectedConditions.presenceOf; const not = ExpectedConditions.not; @@ -158,11 +158,9 @@ describe('menu', () => { await pressKeys(shiftTab, Key.ENTER, shiftTab); await expectFocusOn(page.start()); }); - }); describe('position - ', () => { - it('should default menu alignment to "after below" when not set', async () => { await page.trigger().click(); @@ -203,6 +201,5 @@ describe('menu', () => { // trigger.y (top corner) - 44px (menu above trigger) = expected menu.y await expectLocation(page.combinedMenu(), {x: trigger.x - 52, y: trigger.y - 44}); }); - }); }); diff --git a/src/material/menu/menu.md b/src/material/menu/menu.md index 93cf0a7d1127..a11581ee3c5d 100644 --- a/src/material/menu/menu.md +++ b/src/material/menu/menu.md @@ -90,13 +90,28 @@ with a different set of data, depending on the trigger that opened it: ``` ### Keyboard interaction -- DOWN_ARROW: Focuses the next menu item -- UP_ARROW: Focuses previous menu item -- RIGHT_ARROW: Opens the menu item's sub-menu -- LEFT_ARROW: Closes the current menu, if it is a sub-menu -- ENTER: Activates the focused menu item -- ESCAPE: Closes the menu +| Keyboard shortcut | Action | +|------------------------|---------------------------------------------| +| Down Arrow | Focus the next menu item. | +| Up Arrow | Focus the previous menu item. | +| Left Arrow | Close the current menu if it is a sub-menu. | +| Right Arrow | Opens the current menu item's sub-menu. | +| Enter | Activate the focused menu item. | +| Escape | Close all open menus. | ### Accessibility -Menu triggers or menu items without text or labels should be given a meaningful label via -`aria-label` or `aria-labelledby`. + +Angular Material's menu component consists of two connected parts: the trigger and the pop-up menu. + +The menu trigger is a standard button element augmented with `aria-haspopup`, `aria-expanded`, and +`aria-controls` to create the relationship to the pop-up panel. + +The pop-up menu implements the `role="menu"` pattern, handling keyboard interaction and focus +management. Upon opening, the trigger will focus the first focusable menu item. Upon close, the menu +will return focus to its trigger. Avoid creating a menu in which all items are disabled, instead +hiding or disabling the menu trigger. + +Angular Material does not support the `menuitemcheckbox` or `menuitemradio` roles. + +Always provide an accessible label via `aria-label` or `aria-labelledby` for any menu +triggers or menu items without descriptive text content. diff --git a/src/material/menu/menu.scss b/src/material/menu/menu.scss index afcd241fc5ee..353986269014 100644 --- a/src/material/menu/menu.scss +++ b/src/material/menu/menu.scss @@ -1,21 +1,26 @@ // TODO(kara): update vars for desktop when MD team responds -@import '../core/style/button-common'; -@import '../core/style/menu-common'; -@import '../../cdk/a11y/a11y'; +@use '../core/style/button-common'; +@use '../core/style/menu-common'; +@use '../../cdk/a11y'; -$mat-menu-vertical-padding: 8px !default; -$mat-menu-border-radius: 4px !default; -$mat-menu-submenu-indicator-size: 10px !default; +$vertical-padding: 8px !default; +$border-radius: 4px !default; +$submenu-indicator-size: 10px !default; + +// Prevent rendering mat-menu as it can affect the flex layout. +mat-menu { + display: none; +} .mat-menu-panel { - @include mat-menu-base(); - max-height: calc(100vh - #{$mat-menu-item-height}); - border-radius: $mat-menu-border-radius; + @include menu-common.base(); + max-height: calc(100vh - #{menu-common.$item-height}); + border-radius: $border-radius; outline: 0; // Give the menu a minimum height so that the user can't // collapse it to zero when they scroll away. - min-height: $mat-menu-item-height + $mat-menu-vertical-padding * 2; + min-height: menu-common.$item-height + $vertical-padding * 2; // Prevent users from interacting with the panel while it's animating. Note that // people won't be able to click through it, because the overlay pane will catch the click. @@ -28,20 +33,20 @@ $mat-menu-submenu-indicator-size: 10px !default; pointer-events: none; } - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { outline: solid 1px; } } // `:not(:empty)` allows for the menu to collapse to 0x0 when it doesn't have content. .mat-menu-content:not(:empty) { - padding-top: $mat-menu-vertical-padding; - padding-bottom: $mat-menu-vertical-padding; + padding-top: $vertical-padding; + padding-bottom: $vertical-padding; } .mat-menu-item { - @include mat-button-reset(); - @include mat-menu-item-base(); + @include button-common.reset(); + @include menu-common.item-base(); position: relative; &[disabled] { @@ -53,17 +58,27 @@ $mat-menu-submenu-indicator-size: 10px !default; pointer-events: none; } - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { + $outline-width: 1px; + + // We need to move the item 1px down, because Firefox seems to have + // an issue rendering the top part of the outline (see #21524). + margin-top: $outline-width; + &.cdk-program-focused, &.cdk-keyboard-focused, &-highlighted { - outline: dotted 1px; + outline: dotted $outline-width; } } } .mat-menu-item-submenu-trigger { - @include mat-menu-item-submenu-trigger($mat-menu-side-padding); + @include menu-common.item-submenu-trigger(menu-common.$side-padding); +} + +.mat-menu-submenu-icon { + @include menu-common.item-submenu-icon(menu-common.$side-padding); } button.mat-menu-item { @@ -73,5 +88,5 @@ button.mat-menu-item { // Increase specificity because ripple styles are part of the `mat-core` mixin and can // potentially overwrite the absolute position of the container. .mat-menu-item .mat-menu-ripple { - @include mat-menu-item-ripple; + @include menu-common.item-ripple; } diff --git a/src/material/menu/menu.spec.ts b/src/material/menu/menu.spec.ts index 388005dc6a38..0848e63c9a29 100644 --- a/src/material/menu/menu.spec.ts +++ b/src/material/menu/menu.spec.ts @@ -1,6 +1,15 @@ import {FocusMonitor} from '@angular/cdk/a11y'; import {Direction, Directionality} from '@angular/cdk/bidi'; -import {DOWN_ARROW, END, ESCAPE, HOME, LEFT_ARROW, RIGHT_ARROW, TAB} from '@angular/cdk/keycodes'; +import { + DOWN_ARROW, + END, + ENTER, + ESCAPE, + HOME, + LEFT_ARROW, + RIGHT_ARROW, + TAB, +} from '@angular/cdk/keycodes'; import {Overlay, OverlayContainer} from '@angular/cdk/overlay'; import {ScrollDispatcher} from '@angular/cdk/scrolling'; import { @@ -12,7 +21,7 @@ import { dispatchMouseEvent, MockNgZone, patchElementFocus, -} from '@angular/cdk/testing/private'; +} from '../../cdk/testing/private'; import { ChangeDetectionStrategy, Component, @@ -28,7 +37,7 @@ import { ViewChild, ViewChildren, } from '@angular/core'; -import {ComponentFixture, fakeAsync, flush, inject, TestBed, tick} from '@angular/core/testing'; +import {ComponentFixture, fakeAsync, flush, TestBed, tick} from '@angular/core/testing'; import {MatRipple} from '@angular/material/core'; import {By} from '@angular/platform-browser'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; @@ -45,47 +54,40 @@ import { } from './index'; import {MAT_MENU_SCROLL_STRATEGY, MENU_PANEL_TOP_PADDING} from './menu-trigger'; - describe('MatMenu', () => { - let overlayContainer: OverlayContainer; let overlayContainerElement: HTMLElement; let focusMonitor: FocusMonitor; - function createComponent(component: Type, - providers: Provider[] = [], - declarations: any[] = []): ComponentFixture { + function createComponent( + component: Type, + providers: Provider[] = [], + declarations: any[] = [], + ): ComponentFixture { TestBed.configureTestingModule({ imports: [MatMenuModule, NoopAnimationsModule], declarations: [component, ...declarations], - providers + providers, }).compileComponents(); - inject([OverlayContainer, FocusMonitor], (oc: OverlayContainer, fm: FocusMonitor) => { - overlayContainer = oc; - overlayContainerElement = oc.getContainerElement(); - focusMonitor = fm; - })(); - - return TestBed.createComponent(component); + overlayContainerElement = TestBed.inject(OverlayContainer).getContainerElement(); + focusMonitor = TestBed.inject(FocusMonitor); + const fixture = TestBed.createComponent(component); + window.scroll(0, 0); + return fixture; } - afterEach(inject([OverlayContainer], (currentOverlayContainer: OverlayContainer) => { - // Since we're resetting the testing module in some of the tests, - // we can potentially have multiple overlay containers. - currentOverlayContainer.ngOnDestroy(); - overlayContainer.ngOnDestroy(); - })); - - it('should aria-controls the menu panel', () => { + it('should aria-controls the menu panel', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); - expect(fixture.componentInstance.triggerEl.nativeElement.getAttribute('aria-controls')) - .toBe(fixture.componentInstance.menu.panelId); - }); + tick(500); + expect(fixture.componentInstance.triggerEl.nativeElement.getAttribute('aria-controls')).toBe( + fixture.componentInstance.menu.panelId, + ); + })); - it('should open the menu as an idempotent operation', () => { + it('should open the menu as an idempotent operation', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); expect(overlayContainerElement.textContent).toBe(''); @@ -93,11 +95,12 @@ describe('MatMenu', () => { fixture.componentInstance.trigger.openMenu(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); expect(overlayContainerElement.textContent).toContain('Item'); expect(overlayContainerElement.textContent).toContain('Disabled'); }).not.toThrowError(); - }); + })); it('should close the menu when a click occurs outside the menu', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); @@ -208,11 +211,11 @@ describe('MatMenu', () => { tick(500); expect(document.activeElement).toBe(button); - document.body.removeChild(button); + button.remove(); subscription.unsubscribe(); })); - it('should restore focus to the trigger immediately once the menu is closed', () => { + it('should restore focus to the trigger immediately once the menu is closed', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); const triggerEl = fixture.componentInstance.triggerEl.nativeElement; @@ -220,6 +223,7 @@ describe('MatMenu', () => { // A click without a mousedown before it is considered a keyboard open. triggerEl.click(); fixture.detectChanges(); + tick(500); expect(overlayContainerElement.querySelector('.mat-menu-panel')).toBeTruthy(); @@ -229,7 +233,8 @@ describe('MatMenu', () => { // that focus is restored before the animation is done. expect(document.activeElement).toBe(triggerEl); - }); + tick(500); + })); it('should be able to set a custom class on the backdrop', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); @@ -246,9 +251,9 @@ describe('MatMenu', () => { })); it('should be able to set a custom class on the overlay panel', fakeAsync(() => { - const optionsProvider = { + const optionsProvider = { provide: MAT_MENU_DEFAULT_OPTIONS, - useValue: {overlayPanelClass: 'custom-panel-class'} + useValue: {overlayPanelClass: 'custom-panel-class'}, }; const fixture = createComponent(SimpleMenu, [optionsProvider], [FakeIcon]); @@ -263,9 +268,9 @@ describe('MatMenu', () => { })); it('should be able to set a custom classes on the overlay panel', fakeAsync(() => { - const optionsProvider = { + const optionsProvider = { provide: MAT_MENU_DEFAULT_OPTIONS, - useValue: {overlayPanelClass: ['custom-panel-class-1', 'custom-panel-class-2']} + useValue: {overlayPanelClass: ['custom-panel-class-1', 'custom-panel-class-2']}, }; const fixture = createComponent(SimpleMenu, [optionsProvider], [FakeIcon]); @@ -335,90 +340,86 @@ describe('MatMenu', () => { expect(overlayContainerElement.querySelector('.mat-menu-panel')!.scrollTop).toBe(0); })); - it('should set the proper focus origin when restoring focus after opening by keyboard', - fakeAsync(() => { - const fixture = createComponent(SimpleMenu, [], [FakeIcon]); - fixture.detectChanges(); - const triggerEl = fixture.componentInstance.triggerEl.nativeElement; + it('should set the proper focus origin when restoring focus after opening by keyboard', fakeAsync(() => { + const fixture = createComponent(SimpleMenu, [], [FakeIcon]); + fixture.detectChanges(); + const triggerEl = fixture.componentInstance.triggerEl.nativeElement; - patchElementFocus(triggerEl); - focusMonitor.monitor(triggerEl, false); - triggerEl.click(); // A click without a mousedown before it is considered a keyboard open. - fixture.detectChanges(); - fixture.componentInstance.trigger.closeMenu(); - fixture.detectChanges(); - tick(500); - fixture.detectChanges(); + patchElementFocus(triggerEl); + focusMonitor.monitor(triggerEl, false); + triggerEl.click(); // A click without a mousedown before it is considered a keyboard open. + fixture.detectChanges(); + fixture.componentInstance.trigger.closeMenu(); + fixture.detectChanges(); + tick(500); + fixture.detectChanges(); - expect(triggerEl.classList).toContain('cdk-program-focused'); - focusMonitor.stopMonitoring(triggerEl); - })); + expect(triggerEl.classList).toContain('cdk-program-focused'); + focusMonitor.stopMonitoring(triggerEl); + })); - it('should set the proper focus origin when restoring focus after opening by mouse', - fakeAsync(() => { - const fixture = createComponent(SimpleMenu, [], [FakeIcon]); - fixture.detectChanges(); - const triggerEl = fixture.componentInstance.triggerEl.nativeElement; + it('should set the proper focus origin when restoring focus after opening by mouse', fakeAsync(() => { + const fixture = createComponent(SimpleMenu, [], [FakeIcon]); + fixture.detectChanges(); + const triggerEl = fixture.componentInstance.triggerEl.nativeElement; - dispatchMouseEvent(triggerEl, 'mousedown'); - triggerEl.click(); - fixture.detectChanges(); - patchElementFocus(triggerEl); - focusMonitor.monitor(triggerEl, false); - fixture.componentInstance.trigger.closeMenu(); - fixture.detectChanges(); - tick(500); - fixture.detectChanges(); + dispatchMouseEvent(triggerEl, 'mousedown'); + triggerEl.click(); + fixture.detectChanges(); + patchElementFocus(triggerEl); + focusMonitor.monitor(triggerEl, false); + fixture.componentInstance.trigger.closeMenu(); + fixture.detectChanges(); + tick(500); + fixture.detectChanges(); - expect(triggerEl.classList).toContain('cdk-mouse-focused'); - focusMonitor.stopMonitoring(triggerEl); - })); + expect(triggerEl.classList).toContain('cdk-mouse-focused'); + focusMonitor.stopMonitoring(triggerEl); + })); - it('should set proper focus origin when right clicking on trigger, before opening by keyboard', - fakeAsync(() => { - const fixture = createComponent(SimpleMenu, [], [FakeIcon]); - fixture.detectChanges(); - const triggerEl = fixture.componentInstance.triggerEl.nativeElement; + it('should set proper focus origin when right clicking on trigger, before opening by keyboard', fakeAsync(() => { + const fixture = createComponent(SimpleMenu, [], [FakeIcon]); + fixture.detectChanges(); + const triggerEl = fixture.componentInstance.triggerEl.nativeElement; - patchElementFocus(triggerEl); - focusMonitor.monitor(triggerEl, false); + patchElementFocus(triggerEl); + focusMonitor.monitor(triggerEl, false); - // Trigger a fake right click. - dispatchEvent(triggerEl, createMouseEvent('mousedown', 50, 100, 2)); + // Trigger a fake right click. + dispatchEvent(triggerEl, createMouseEvent('mousedown', 50, 100, 2)); - // A click without a left button mousedown before it is considered a keyboard open. - triggerEl.click(); - fixture.detectChanges(); + // A click without a left button mousedown before it is considered a keyboard open. + triggerEl.click(); + fixture.detectChanges(); - fixture.componentInstance.trigger.closeMenu(); - fixture.detectChanges(); - tick(500); - fixture.detectChanges(); + fixture.componentInstance.trigger.closeMenu(); + fixture.detectChanges(); + tick(500); + fixture.detectChanges(); - expect(triggerEl.classList).toContain('cdk-program-focused'); - focusMonitor.stopMonitoring(triggerEl); - })); + expect(triggerEl.classList).toContain('cdk-program-focused'); + focusMonitor.stopMonitoring(triggerEl); + })); - it('should set the proper focus origin when restoring focus after opening by touch', - fakeAsync(() => { - const fixture = createComponent(SimpleMenu, [], [FakeIcon]); - fixture.detectChanges(); - const triggerEl = fixture.componentInstance.triggerEl.nativeElement; - - dispatchMouseEvent(triggerEl, 'touchstart'); - triggerEl.click(); - fixture.detectChanges(); - patchElementFocus(triggerEl); - focusMonitor.monitor(triggerEl, false); - fixture.componentInstance.trigger.closeMenu(); - fixture.detectChanges(); - tick(500); - fixture.detectChanges(); - flush(); + it('should set the proper focus origin when restoring focus after opening by touch', fakeAsync(() => { + const fixture = createComponent(SimpleMenu, [], [FakeIcon]); + fixture.detectChanges(); + const triggerEl = fixture.componentInstance.triggerEl.nativeElement; - expect(triggerEl.classList).toContain('cdk-touch-focused'); - focusMonitor.stopMonitoring(triggerEl); - })); + dispatchMouseEvent(triggerEl, 'touchstart'); + triggerEl.click(); + fixture.detectChanges(); + patchElementFocus(triggerEl); + focusMonitor.monitor(triggerEl, false); + fixture.componentInstance.trigger.closeMenu(); + fixture.detectChanges(); + tick(500); + fixture.detectChanges(); + flush(); + + expect(triggerEl.classList).toContain('cdk-touch-focused'); + focusMonitor.stopMonitoring(triggerEl); + })); it('should close the menu when pressing ESCAPE', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); @@ -452,7 +453,7 @@ describe('MatMenu', () => { expect(event.defaultPrevented).toBe(false); })); - it('should open a custom menu', () => { + it('should open a custom menu', fakeAsync(() => { const fixture = createComponent(CustomMenu, [], [CustomMenuPanel]); fixture.detectChanges(); expect(overlayContainerElement.textContent).toBe(''); @@ -463,55 +464,77 @@ describe('MatMenu', () => { expect(overlayContainerElement.textContent).toContain('Custom Menu header'); expect(overlayContainerElement.textContent).toContain('Custom Content'); }).not.toThrowError(); - }); + })); - it('should set the panel direction based on the trigger direction', () => { - const fixture = createComponent(SimpleMenu, [{ - provide: Directionality, useFactory: () => ({value: 'rtl'})} - ], [FakeIcon]); + it('should set the panel direction based on the trigger direction', fakeAsync(() => { + const fixture = createComponent( + SimpleMenu, + [ + { + provide: Directionality, + useFactory: () => ({value: 'rtl'}), + }, + ], + [FakeIcon], + ); fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); - const boundingBox = - overlayContainerElement.querySelector('.cdk-overlay-connected-position-bounding-box')!; + const boundingBox = overlayContainerElement.querySelector( + '.cdk-overlay-connected-position-bounding-box', + )!; expect(boundingBox.getAttribute('dir')).toEqual('rtl'); - }); + })); - it('should update the panel direction if the trigger direction changes', () => { + it('should update the panel direction if the trigger direction changes', fakeAsync(() => { const dirProvider = {value: 'rtl'}; - const fixture = createComponent(SimpleMenu, [{ - provide: Directionality, useFactory: () => dirProvider} - ], [FakeIcon]); + const fixture = createComponent( + SimpleMenu, + [ + { + provide: Directionality, + useFactory: () => dirProvider, + }, + ], + [FakeIcon], + ); fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); - let boundingBox = - overlayContainerElement.querySelector('.cdk-overlay-connected-position-bounding-box')!; + let boundingBox = overlayContainerElement.querySelector( + '.cdk-overlay-connected-position-bounding-box', + )!; expect(boundingBox.getAttribute('dir')).toEqual('rtl'); fixture.componentInstance.trigger.closeMenu(); fixture.detectChanges(); + tick(500); dirProvider.value = 'ltr'; fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); - boundingBox = - overlayContainerElement.querySelector('.cdk-overlay-connected-position-bounding-box')!; + boundingBox = overlayContainerElement.querySelector( + '.cdk-overlay-connected-position-bounding-box', + )!; expect(boundingBox.getAttribute('dir')).toEqual('ltr'); - }); + })); - it('should transfer any custom classes from the host to the overlay', () => { + it('should transfer any custom classes from the host to the overlay', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.componentInstance.panelClass = 'custom-one custom-two'; fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); const menuEl = fixture.debugElement.query(By.css('mat-menu'))!.nativeElement; const panel = overlayContainerElement.querySelector('.mat-menu-panel')!; @@ -521,15 +544,16 @@ describe('MatMenu', () => { expect(panel.classList).toContain('custom-one'); expect(panel.classList).toContain('custom-two'); - }); + })); - it('should not remove mat-elevation class from overlay when panelClass is changed', () => { + it('should not remove mat-elevation class from overlay when panelClass is changed', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.componentInstance.panelClass = 'custom-one'; fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); const panel = overlayContainerElement.querySelector('.mat-menu-panel')!; @@ -542,29 +566,32 @@ describe('MatMenu', () => { expect(panel.classList).not.toContain('custom-one'); expect(panel.classList).toContain('custom-two'); expect(panel.classList) - .toContain('mat-elevation-z4', 'Expected mat-elevation-z4 not to be removed'); - }); + .withContext('Expected mat-elevation-z4 not to be removed') + .toContain('mat-elevation-z4'); + })); - it('should set the "menu" role on the overlay panel', () => { + it('should set the "menu" role on the overlay panel', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); const menuPanel = overlayContainerElement.querySelector('.mat-menu-panel'); - expect(menuPanel).toBeTruthy('Expected to find a menu panel.'); + expect(menuPanel).withContext('Expected to find a menu panel.').toBeTruthy(); const role = menuPanel ? menuPanel.getAttribute('role') : ''; - expect(role).toBe('menu', 'Expected panel to have the "menu" role.'); - }); + expect(role).withContext('Expected panel to have the "menu" role.').toBe('menu'); + })); - it('should forward ARIA attributes to the menu panel', () => { + it('should forward ARIA attributes to the menu panel', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); const instance = fixture.componentInstance; fixture.detectChanges(); instance.trigger.openMenu(); fixture.detectChanges(); + tick(500); const menuPanel = overlayContainerElement.querySelector('.mat-menu-panel')!; expect(menuPanel.hasAttribute('aria-label')).toBe(false); @@ -589,40 +616,44 @@ describe('MatMenu', () => { expect(menuPanel.hasAttribute('aria-label')).toBe(false); expect(menuPanel.hasAttribute('aria-labelledby')).toBe(false); expect(menuPanel.hasAttribute('aria-describedby')).toBe(false); - }); + })); - it('should set the "menuitem" role on the items by default', () => { + it('should set the "menuitem" role on the items by default', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); const items = Array.from(overlayContainerElement.querySelectorAll('.mat-menu-item')); expect(items.length).toBeGreaterThan(0); expect(items.every(item => item.getAttribute('role') === 'menuitem')).toBe(true); - }); + })); - it('should be able to set an alternate role on the menu items', () => { + it('should be able to set an alternate role on the menu items', fakeAsync(() => { const fixture = createComponent(MenuWithCheckboxItems); fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); const items = Array.from(overlayContainerElement.querySelectorAll('.mat-menu-item')); expect(items.length).toBeGreaterThan(0); expect(items.every(item => item.getAttribute('role') === 'menuitemcheckbox')).toBe(true); - }); + })); - it('should not change focus origin if origin not specified for menu items', () => { + it('should not change focus origin if origin not specified for menu items', fakeAsync(() => { const fixture = createComponent(MenuWithCheckboxItems); fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); - let [firstMenuItemDebugEl, secondMenuItemDebugEl] = - fixture.debugElement.queryAll(By.css('.mat-menu-item'))!; + let [firstMenuItemDebugEl, secondMenuItemDebugEl] = fixture.debugElement.queryAll( + By.css('.mat-menu-item'), + )!; const firstMenuItemInstance = firstMenuItemDebugEl.componentInstance as MatMenuItem; const secondMenuItemInstance = secondMenuItemDebugEl.componentInstance as MatMenuItem; @@ -631,35 +662,36 @@ describe('MatMenu', () => { firstMenuItemInstance.focus('mouse'); secondMenuItemDebugEl.nativeElement.blur(); secondMenuItemInstance.focus(); + tick(500); expect(secondMenuItemDebugEl.nativeElement.classList).toContain('cdk-focused'); expect(secondMenuItemDebugEl.nativeElement.classList).toContain('cdk-mouse-focused'); - }); + })); - it('should not throw an error on destroy', () => { + it('should not throw an error on destroy', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); expect(fixture.destroy.bind(fixture)).not.toThrow(); - }); + })); - it('should be able to extract the menu item text', () => { + it('should be able to extract the menu item text', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); expect(fixture.componentInstance.items.first.getLabel()).toBe('Item'); - }); + })); - it('should filter out icon nodes when figuring out the label', () => { + it('should filter out icon nodes when figuring out the label', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); const items = fixture.componentInstance.items.toArray(); expect(items[2].getLabel()).toBe('Item with an icon'); - }); + })); - it('should get the label of an item if the text is not in a direct descendant node', () => { + it('should get the label of an item if the text is not in a direct descendant node', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); const items = fixture.componentInstance.items.toArray(); expect(items[3].getLabel()).toBe('Item with text inside span'); - }); + })); it('should set the proper focus origin when opening by mouse', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); @@ -693,14 +725,18 @@ describe('MatMenu', () => { it('should close the menu when using the CloseScrollStrategy', fakeAsync(() => { const scrolledSubject = new Subject(); - const fixture = createComponent(SimpleMenu, [ - {provide: ScrollDispatcher, useFactory: () => ({scrolled: () => scrolledSubject})}, - { - provide: MAT_MENU_SCROLL_STRATEGY, - deps: [Overlay], - useFactory: (overlay: Overlay) => () => overlay.scrollStrategies.close() - } - ], [FakeIcon]); + const fixture = createComponent( + SimpleMenu, + [ + {provide: ScrollDispatcher, useFactory: () => ({scrolled: () => scrolledSubject})}, + { + provide: MAT_MENU_SCROLL_STRATEGY, + deps: [Overlay], + useFactory: (overlay: Overlay) => () => overlay.scrollStrategies.close(), + }, + ], + [FakeIcon], + ); fixture.detectChanges(); const trigger = fixture.componentInstance.trigger; @@ -715,37 +751,59 @@ describe('MatMenu', () => { expect(trigger.menuOpen).toBe(false); })); - it('should switch to keyboard focus when using the keyboard after opening using the mouse', - fakeAsync(() => { - const fixture = createComponent(SimpleMenu, [], [FakeIcon]); + it('should switch to keyboard focus when using the keyboard after opening using the mouse', fakeAsync(() => { + const fixture = createComponent(SimpleMenu, [], [FakeIcon]); - fixture.detectChanges(); - fixture.componentInstance.triggerEl.nativeElement.click(); - fixture.detectChanges(); + fixture.detectChanges(); + fixture.componentInstance.triggerEl.nativeElement.click(); + fixture.detectChanges(); - const panel = document.querySelector('.mat-menu-panel')! as HTMLElement; - const items: HTMLElement[] = - Array.from(panel.querySelectorAll('.mat-menu-panel [mat-menu-item]')); + const panel = document.querySelector('.mat-menu-panel')! as HTMLElement; + const items: HTMLElement[] = Array.from( + panel.querySelectorAll('.mat-menu-panel [mat-menu-item]'), + ); - items.forEach(item => patchElementFocus(item)); + items.forEach(item => patchElementFocus(item)); - tick(500); - tick(); - fixture.detectChanges(); - expect(items.some(item => item.classList.contains('cdk-keyboard-focused'))).toBe(false); + tick(500); + tick(); + fixture.detectChanges(); + expect(items.some(item => item.classList.contains('cdk-keyboard-focused'))).toBe(false); - dispatchKeyboardEvent(panel, 'keydown', DOWN_ARROW); - fixture.detectChanges(); + dispatchKeyboardEvent(panel, 'keydown', DOWN_ARROW); + fixture.detectChanges(); - // Flush due to the additional tick that is necessary for the FocusMonitor. - flush(); + // Flush due to the additional tick that is necessary for the FocusMonitor. + flush(); - // We skip to the third item, because the second one is disabled. - expect(items[2].classList).toContain('cdk-focused'); - expect(items[2].classList).toContain('cdk-keyboard-focused'); - })); + // We skip to the third item, because the second one is disabled. + expect(items[2].classList).toContain('cdk-focused'); + expect(items[2].classList).toContain('cdk-keyboard-focused'); + })); + + it('should set the keyboard focus origin when opened using the keyboard', fakeAsync(() => { + const fixture = createComponent(SimpleMenu, [], [FakeIcon]); + fixture.detectChanges(); + const trigger = fixture.componentInstance.triggerEl.nativeElement; + + // Note that we dispatch both a `click` and a `keydown` to imitate the browser behavior. + dispatchKeyboardEvent(trigger, 'keydown', ENTER); + trigger.click(); + fixture.detectChanges(); + + const items = Array.from( + document.querySelectorAll('.mat-menu-panel [mat-menu-item]'), + ); + + items.forEach(item => patchElementFocus(item)); + tick(500); + tick(); + fixture.detectChanges(); - it('should toggle the aria-expanded attribute on the trigger', () => { + expect(items[0].classList).toContain('cdk-keyboard-focused'); + })); + + it('should toggle the aria-expanded attribute on the trigger', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); const triggerEl = fixture.componentInstance.triggerEl.nativeElement; @@ -754,16 +812,18 @@ describe('MatMenu', () => { fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); expect(triggerEl.getAttribute('aria-expanded')).toBe('true'); fixture.componentInstance.trigger.closeMenu(); fixture.detectChanges(); + tick(500); expect(triggerEl.hasAttribute('aria-expanded')).toBe(false); - }); + })); - it('should throw the correct error if the menu is not defined after init', () => { + it('should throw the correct error if the menu is not defined after init', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); @@ -773,15 +833,17 @@ describe('MatMenu', () => { expect(() => { fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); }).toThrowError(/must pass in an mat-menu instance/); - }); + })); - it('should throw if assigning a menu that contains the trigger', () => { + it('should throw if assigning a menu that contains the trigger', fakeAsync(() => { expect(() => { const fixture = createComponent(InvalidRecursiveMenu, [], [FakeIcon]); fixture.detectChanges(); + tick(500); }).toThrowError(/menu cannot contain its own trigger/); - }); + })); it('should be able to swap out a menu after the first time it is opened', fakeAsync(() => { const fixture = createComponent(DynamicPanelMenu); @@ -915,9 +977,96 @@ describe('MatMenu', () => { flush(); })); + it( + 'should respect the DOM order, rather than insertion order, when moving focus using ' + + 'the arrow keys', + fakeAsync(() => { + let fixture = createComponent(SimpleMenuWithRepeater); + + fixture.detectChanges(); + fixture.componentInstance.trigger.openMenu(); + fixture.detectChanges(); + tick(500); + + let menuPanel = document.querySelector('.mat-menu-panel')!; + let items = menuPanel.querySelectorAll('.mat-menu-panel [mat-menu-item]'); + + expect(document.activeElement) + .withContext('Expected first item to be focused on open') + .toBe(items[0]); + + // Add a new item after the first one. + fixture.componentInstance.items.splice(1, 0, {label: 'Calzone', disabled: false}); + fixture.detectChanges(); + + items = menuPanel.querySelectorAll('.mat-menu-panel [mat-menu-item]'); + dispatchKeyboardEvent(menuPanel, 'keydown', DOWN_ARROW); + fixture.detectChanges(); + tick(); + + expect(document.activeElement) + .withContext('Expected second item to be focused') + .toBe(items[1]); + flush(); + }), + ); + + it('should sync the focus order when an item is focused programmatically', fakeAsync(() => { + const fixture = createComponent(SimpleMenuWithRepeater); + + // Add some more items to work with. + for (let i = 0; i < 5; i++) { + fixture.componentInstance.items.push({label: `Extra ${i}`, disabled: false}); + } + + fixture.detectChanges(); + fixture.componentInstance.trigger.openMenu(); + fixture.detectChanges(); + tick(500); + + const menuPanel = document.querySelector('.mat-menu-panel')!; + const items = menuPanel.querySelectorAll('.mat-menu-panel [mat-menu-item]'); + + expect(document.activeElement) + .withContext('Expected first item to be focused on open') + .toBe(items[0]); + + fixture.componentInstance.itemInstances.toArray()[3].focus(); + fixture.detectChanges(); + + expect(document.activeElement).withContext('Expected fourth item to be focused').toBe(items[3]); + + dispatchKeyboardEvent(menuPanel, 'keydown', DOWN_ARROW); + fixture.detectChanges(); + tick(); + + expect(document.activeElement).withContext('Expected fifth item to be focused').toBe(items[4]); + flush(); + })); + + it('should open submenus when the menu is inside an OnPush component', fakeAsync(() => { + const fixture = createComponent(LazyMenuWithOnPush); + fixture.detectChanges(); + + // Open the top-level menu + fixture.componentInstance.rootTrigger.nativeElement.click(); + fixture.detectChanges(); + flush(); + + // Dispatch a `mouseenter` on the menu item to open the submenu. + // This will only work if the top-level menu is aware the this menu item exists. + dispatchMouseEvent(fixture.componentInstance.menuItemWithSubmenu.nativeElement, 'mouseenter'); + fixture.detectChanges(); + flush(); + + expect(overlayContainerElement.querySelectorAll('.mat-menu-item').length) + .withContext('Expected two open menus') + .toBe(2); + })); + it('should focus the menu panel if all items are disabled', fakeAsync(() => { const fixture = createComponent(SimpleMenuWithRepeater, [], [FakeIcon]); - fixture.componentInstance.items.forEach(item => item.disabled = true); + fixture.componentInstance.items.forEach(item => (item.disabled = true)); fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); @@ -928,7 +1077,7 @@ describe('MatMenu', () => { it('should focus the menu panel if all items are disabled inside lazy content', fakeAsync(() => { const fixture = createComponent(SimpleMenuWithRepeaterInLazyContent, [], [FakeIcon]); - fixture.componentInstance.items.forEach(item => item.disabled = true); + fixture.componentInstance.items.forEach(item => (item.disabled = true)); fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); @@ -937,25 +1086,54 @@ describe('MatMenu', () => { expect(document.activeElement).toBe(overlayContainerElement.querySelector('.mat-menu-panel')); })); - it('should clear the static aria-label from the menu host', () => { + it('should clear the static aria-label from the menu host', fakeAsync(() => { const fixture = createComponent(StaticAriaLabelMenu); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('mat-menu').hasAttribute('aria-label')).toBe(false); - }); + })); - it('should clear the static aria-labelledby from the menu host', () => { + it('should clear the static aria-labelledby from the menu host', fakeAsync(() => { const fixture = createComponent(StaticAriaLabelledByMenu); fixture.detectChanges(); - expect(fixture.nativeElement.querySelector('mat-menu').hasAttribute('aria-labelledby')) - .toBe(false); - }); + expect(fixture.nativeElement.querySelector('mat-menu').hasAttribute('aria-labelledby')).toBe( + false, + ); + })); - it('should clear the static aria-describedby from the menu host', () => { + it('should clear the static aria-describedby from the menu host', fakeAsync(() => { const fixture = createComponent(StaticAriaDescribedbyMenu); fixture.detectChanges(); - expect(fixture.nativeElement.querySelector('mat-menu').hasAttribute('aria-describedby')) - .toBe(false); - }); + expect(fixture.nativeElement.querySelector('mat-menu').hasAttribute('aria-describedby')).toBe( + false, + ); + })); + + it('should be able to move focus inside the `open` event', fakeAsync(() => { + const fixture = createComponent(SimpleMenu, [], [FakeIcon]); + fixture.detectChanges(); + + fixture.componentInstance.trigger.menuOpened.subscribe(() => { + (document.querySelectorAll('.mat-menu-panel [mat-menu-item]')[3] as HTMLElement).focus(); + }); + fixture.componentInstance.trigger.openMenu(); + fixture.detectChanges(); + tick(500); + + const items = document.querySelectorAll('.mat-menu-panel [mat-menu-item]'); + expect(document.activeElement).withContext('Expected fourth item to be focused').toBe(items[3]); + })); + + it('should default to the "below" and "after" positions', fakeAsync(() => { + const fixture = createComponent(SimpleMenu, [], [FakeIcon]); + fixture.detectChanges(); + fixture.componentInstance.trigger.openMenu(); + fixture.detectChanges(); + tick(500); + const panel = overlayContainerElement.querySelector('.mat-menu-panel') as HTMLElement; + + expect(panel.classList).toContain('mat-menu-below'); + expect(panel.classList).toContain('mat-menu-after'); + })); describe('lazy rendering', () => { it('should be able to render the menu content lazily', fakeAsync(() => { @@ -968,9 +1146,13 @@ describe('MatMenu', () => { const panel = overlayContainerElement.querySelector('.mat-menu-panel')!; - expect(panel).toBeTruthy('Expected panel to be defined'); - expect(panel.textContent).toContain('Another item', 'Expected panel to have correct content'); - expect(fixture.componentInstance.trigger.menuOpen).toBe(true, 'Expected menu to be open'); + expect(panel).withContext('Expected panel to be defined').toBeTruthy(); + expect(panel.textContent) + .withContext('Expected panel to have correct content') + .toContain('Another item'); + expect(fixture.componentInstance.trigger.menuOpen) + .withContext('Expected menu to be open') + .toBe(true); })); it('should detach the lazy content when the menu is closed', fakeAsync(() => { @@ -991,36 +1173,39 @@ describe('MatMenu', () => { expect(fixture.componentInstance.items.length).toBe(0); })); - it('should wait for the close animation to finish before considering the panel as closed', - fakeAsync(() => { - const fixture = createComponent(SimpleLazyMenu); - fixture.detectChanges(); - const trigger = fixture.componentInstance.trigger; + it('should wait for the close animation to finish before considering the panel as closed', fakeAsync(() => { + const fixture = createComponent(SimpleLazyMenu); + fixture.detectChanges(); + const trigger = fixture.componentInstance.trigger; - expect(trigger.menuOpen).toBe(false, 'Expected menu to start off closed'); + expect(trigger.menuOpen).withContext('Expected menu to start off closed').toBe(false); - trigger.openMenu(); - fixture.detectChanges(); - tick(500); + trigger.openMenu(); + fixture.detectChanges(); + tick(500); - expect(trigger.menuOpen).toBe(true, 'Expected menu to be open'); + expect(trigger.menuOpen).withContext('Expected menu to be open').toBe(true); - trigger.closeMenu(); - fixture.detectChanges(); + trigger.closeMenu(); + fixture.detectChanges(); - expect(trigger.menuOpen) - .toBe(true, 'Expected menu to be considered open while the close animation is running'); - tick(500); - fixture.detectChanges(); + expect(trigger.menuOpen) + .withContext('Expected menu to be considered open while the close animation is running') + .toBe(true); + tick(500); + fixture.detectChanges(); - expect(trigger.menuOpen).toBe(false, 'Expected menu to be closed'); - })); + expect(trigger.menuOpen).withContext('Expected menu to be closed').toBe(false); + })); it('should focus the first menu item when opening a lazy menu via keyboard', fakeAsync(() => { let zone: MockNgZone; - let fixture = createComponent(SimpleLazyMenu, [{ - provide: NgZone, useFactory: () => zone = new MockNgZone() - }]); + let fixture = createComponent(SimpleLazyMenu, [ + { + provide: NgZone, + useFactory: () => (zone = new MockNgZone()), + }, + ]); fixture.detectChanges(); @@ -1035,7 +1220,7 @@ describe('MatMenu', () => { const item = document.querySelector('.mat-menu-panel [mat-menu-item]')!; - expect(document.activeElement).toBe(item, 'Expected first item to be focused'); + expect(document.activeElement).withContext('Expected first item to be focused').toBe(item); })); it('should be able to open the same menu with a different context', fakeAsync(() => { @@ -1061,90 +1246,13 @@ describe('MatMenu', () => { expect(item.textContent!.trim()).toBe('two'); })); - - it('should respect the DOM order, rather than insertion order, when moving focus using ' + - 'the arrow keys', fakeAsync(() => { - let fixture = createComponent(SimpleMenuWithRepeater); - - fixture.detectChanges(); - fixture.componentInstance.trigger.openMenu(); - fixture.detectChanges(); - tick(500); - - let menuPanel = document.querySelector('.mat-menu-panel')!; - let items = menuPanel.querySelectorAll('.mat-menu-panel [mat-menu-item]'); - - expect(document.activeElement).toBe(items[0], 'Expected first item to be focused on open'); - - // Add a new item after the first one. - fixture.componentInstance.items.splice(1, 0, {label: 'Calzone', disabled: false}); - fixture.detectChanges(); - - items = menuPanel.querySelectorAll('.mat-menu-panel [mat-menu-item]'); - dispatchKeyboardEvent(menuPanel, 'keydown', DOWN_ARROW); - fixture.detectChanges(); - tick(); - - expect(document.activeElement).toBe(items[1], 'Expected second item to be focused'); - flush(); - })); - - it('should sync the focus order when an item is focused programmatically', fakeAsync(() => { - const fixture = createComponent(SimpleMenuWithRepeater); - - // Add some more items to work with. - for (let i = 0; i < 5; i++) { - fixture.componentInstance.items.push({label: `Extra ${i}`, disabled: false}); - } - - fixture.detectChanges(); - fixture.componentInstance.trigger.openMenu(); - fixture.detectChanges(); - tick(500); - - const menuPanel = document.querySelector('.mat-menu-panel')!; - const items = menuPanel.querySelectorAll('.mat-menu-panel [mat-menu-item]'); - - expect(document.activeElement).toBe(items[0], 'Expected first item to be focused on open'); - - fixture.componentInstance.itemInstances.toArray()[3].focus(); - fixture.detectChanges(); - - expect(document.activeElement).toBe(items[3], 'Expected fourth item to be focused'); - - dispatchKeyboardEvent(menuPanel, 'keydown', DOWN_ARROW); - fixture.detectChanges(); - tick(); - - expect(document.activeElement).toBe(items[4], 'Expected fifth item to be focused'); - flush(); - })); - - it('should open submenus when the menu is inside an OnPush component', fakeAsync(() => { - const fixture = createComponent(LazyMenuWithOnPush); - fixture.detectChanges(); - - // Open the top-level menu - fixture.componentInstance.rootTrigger.nativeElement.click(); - fixture.detectChanges(); - flush(); - - // Dispatch a `mouseenter` on the menu item to open the submenu. - // This will only work if the top-level menu is aware the this menu item exists. - dispatchMouseEvent(fixture.componentInstance.menuItemWithSubmenu.nativeElement, 'mouseenter'); - fixture.detectChanges(); - flush(); - - expect(overlayContainerElement.querySelectorAll('.mat-menu-item').length) - .toBe(2, 'Expected two open menus'); - })); }); describe('positions', () => { let fixture: ComponentFixture; let trigger: HTMLElement; - beforeEach(() => { + beforeEach(fakeAsync(() => { fixture = createComponent(PositionedMenu); fixture.detectChanges(); @@ -1156,11 +1264,12 @@ describe('MatMenu', () => { // Push trigger to the right, so it has space to open "before" trigger.style.left = '100px'; - }); + })); - it('should append mat-menu-before if the x position is changed', () => { + it('should append mat-menu-before if the x position is changed', fakeAsync(() => { fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); const panel = overlayContainerElement.querySelector('.mat-menu-panel') as HTMLElement; @@ -1172,11 +1281,12 @@ describe('MatMenu', () => { expect(panel.classList).toContain('mat-menu-after'); expect(panel.classList).not.toContain('mat-menu-before'); - }); + })); - it('should append mat-menu-above if the y position is changed', () => { + it('should append mat-menu-above if the y position is changed', fakeAsync(() => { fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); const panel = overlayContainerElement.querySelector('.mat-menu-panel') as HTMLElement; @@ -1188,25 +1298,9 @@ describe('MatMenu', () => { expect(panel.classList).toContain('mat-menu-below'); expect(panel.classList).not.toContain('mat-menu-above'); - }); - - it('should default to the "below" and "after" positions', () => { - overlayContainer.ngOnDestroy(); - fixture.destroy(); - TestBed.resetTestingModule(); - - const newFixture = createComponent(SimpleMenu, [], [FakeIcon]); - - newFixture.detectChanges(); - newFixture.componentInstance.trigger.openMenu(); - newFixture.detectChanges(); - const panel = overlayContainerElement.querySelector('.mat-menu-panel') as HTMLElement; - - expect(panel.classList).toContain('mat-menu-below'); - expect(panel.classList).toContain('mat-menu-after'); - }); + })); - it('should be able to update the position after the first open', () => { + it('should be able to update the position after the first open', fakeAsync(() => { trigger.style.position = 'fixed'; trigger.style.top = '200px'; @@ -1215,31 +1309,38 @@ describe('MatMenu', () => { fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); let panel = overlayContainerElement.querySelector('.mat-menu-panel') as HTMLElement; expect(Math.floor(panel.getBoundingClientRect().bottom)) - .toBe(Math.floor(trigger.getBoundingClientRect().top), 'Expected menu to open above'); + .withContext('Expected menu to open above') + .toBe(Math.floor(trigger.getBoundingClientRect().top)); fixture.componentInstance.trigger.closeMenu(); fixture.detectChanges(); + tick(500); fixture.componentInstance.yPosition = 'below'; fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); panel = overlayContainerElement.querySelector('.mat-menu-panel') as HTMLElement; expect(Math.floor(panel.getBoundingClientRect().top)) - .toBe(Math.floor(trigger.getBoundingClientRect().bottom), 'Expected menu to open below'); - }); + .withContext('Expected menu to open below') + .toBe(Math.floor(trigger.getBoundingClientRect().bottom)); + })); + it('should not throw if a menu reposition is requested while the menu is closed', fakeAsync(() => { + expect(() => fixture.componentInstance.trigger.updatePosition()).not.toThrow(); + })); }); describe('fallback positions', () => { - - it('should fall back to "before" mode if "after" mode would not fit on screen', () => { + it('should fall back to "before" mode if "after" mode would not fit on screen', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); const trigger = fixture.componentInstance.triggerEl.nativeElement; @@ -1252,6 +1353,7 @@ describe('MatMenu', () => { fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); const overlayPane = getOverlayPane(); const triggerRect = trigger.getBoundingClientRect(); const overlayRect = overlayPane.getBoundingClientRect(); @@ -1259,17 +1361,20 @@ describe('MatMenu', () => { // In "before" position, the right sides of the overlay and the origin are aligned. // To find the overlay left, subtract the menu width from the origin's right side. const expectedLeft = triggerRect.right - overlayRect.width; - expect(Math.abs(Math.floor(overlayRect.left) - Math.floor(expectedLeft))) - .toBeLessThanOrEqual(1, - `Expected menu to open in "before" position if "after" position wouldn't fit.`); + expect(Math.floor(overlayRect.left)) + .withContext( + `Expected menu to open in "before" position if "after" position ` + `wouldn't fit.`, + ) + .toBe(Math.floor(expectedLeft)); + // The y-position of the overlay should be unaffected, as it can already fit vertically // The y-position of the overlay should be unaffected, as it can already fit vertically expect(Math.floor(overlayRect.top)) - .toBe(Math.floor(triggerRect.bottom), - `Expected menu top position to be unchanged if it can fit in the viewport.`); - }); + .withContext(`Expected menu top position to be unchanged if it can fit in the viewport.`) + .toBe(Math.floor(triggerRect.bottom)); + })); - it('should fall back to "above" mode if "below" mode would not fit on screen', () => { + it('should fall back to "above" mode if "below" mode would not fit on screen', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); const trigger = fixture.componentInstance.triggerEl.nativeElement; @@ -1281,21 +1386,23 @@ describe('MatMenu', () => { fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); const overlayPane = getOverlayPane(); const triggerRect = trigger.getBoundingClientRect(); const overlayRect = overlayPane.getBoundingClientRect(); expect(Math.floor(overlayRect.bottom)) - .toBe(Math.floor(triggerRect.top), - `Expected menu to open in "above" position if "below" position wouldn't fit.`); + .withContext(`Expected menu to open in "above" position if "below" position wouldn't fit.`) + .toBe(Math.floor(triggerRect.top)); + // The x-position of the overlay should be unaffected, as it can already fit horizontally // The x-position of the overlay should be unaffected, as it can already fit horizontally expect(Math.floor(overlayRect.left)) - .toBe(Math.floor(triggerRect.left), - `Expected menu x position to be unchanged if it can fit in the viewport.`); - }); + .withContext(`Expected menu x position to be unchanged if it can fit in the viewport.`) + .toBe(Math.floor(triggerRect.left)); + })); - it('should re-position menu on both axes if both defaults would not fit', () => { + it('should re-position menu on both axes if both defaults would not fit', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); const trigger = fixture.componentInstance.triggerEl.nativeElement; @@ -1308,44 +1415,50 @@ describe('MatMenu', () => { fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); const overlayPane = getOverlayPane(); const triggerRect = trigger.getBoundingClientRect(); const overlayRect = overlayPane.getBoundingClientRect(); const expectedLeft = triggerRect.right - overlayRect.width; - expect(Math.abs(Math.floor(overlayRect.left) - Math.floor(expectedLeft))) - .toBeLessThanOrEqual(1, - `Expected menu to open in "before" position if "after" position wouldn't fit.`); + expect(Math.floor(overlayRect.left)) + .withContext(`Expected menu to open in "before" position if "after" position wouldn't fit.`) + .toBe(Math.floor(expectedLeft)); expect(Math.floor(overlayRect.bottom)) - .toBe(Math.floor(triggerRect.top), - `Expected menu to open in "above" position if "below" position wouldn't fit.`); - }); + .withContext(`Expected menu to open in "above" position if "below" position wouldn't fit.`) + .toBe(Math.floor(triggerRect.top)); + })); - it('should re-position a menu with custom position set', () => { + it('should re-position a menu with custom position set', fakeAsync(() => { const fixture = createComponent(PositionedMenu); fixture.detectChanges(); const trigger = fixture.componentInstance.triggerEl.nativeElement; fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); const overlayPane = getOverlayPane(); const triggerRect = trigger.getBoundingClientRect(); const overlayRect = overlayPane.getBoundingClientRect(); + // As designated "before" position won't fit on screen, the menu should fall back + // to "after" mode, where the left sides of the overlay and trigger are aligned. // As designated "before" position won't fit on screen, the menu should fall back // to "after" mode, where the left sides of the overlay and trigger are aligned. expect(Math.floor(overlayRect.left)) - .toBe(Math.floor(triggerRect.left), - `Expected menu to open in "after" position if "before" position wouldn't fit.`); + .withContext(`Expected menu to open in "after" position if "before" position wouldn't fit.`) + .toBe(Math.floor(triggerRect.left)); + // As designated "above" position won't fit on screen, the menu should fall back + // to "below" mode, where the top edges of the overlay and trigger are aligned. // As designated "above" position won't fit on screen, the menu should fall back // to "below" mode, where the top edges of the overlay and trigger are aligned. expect(Math.floor(overlayRect.top)) - .toBe(Math.floor(triggerRect.bottom), - `Expected menu to open in "below" position if "above" position wouldn't fit.`); - }); + .withContext(`Expected menu to open in "below" position if "above" position wouldn't fit.`) + .toBe(Math.floor(triggerRect.bottom)); + })); function getOverlayPane(): HTMLElement { return overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; @@ -1367,10 +1480,11 @@ describe('MatMenu', () => { readonly fixture: ComponentFixture; readonly trigger: HTMLElement; - constructor(ctor: {new(): T; }, inputs: {[key: string]: any} = {}) { + constructor(ctor: {new (): T}, inputs: {[key: string]: any} = {}) { this.fixture = createComponent(ctor); - Object.keys(inputs) - .forEach(key => (this.fixture.componentInstance as any)[key] = inputs[key]); + Object.keys(inputs).forEach( + key => ((this.fixture.componentInstance as any)[key] = inputs[key]), + ); this.fixture.detectChanges(); this.trigger = this.fixture.componentInstance.triggerEl.nativeElement; } @@ -1378,6 +1492,7 @@ describe('MatMenu', () => { openMenu() { this.fixture.componentInstance.trigger.openMenu(); this.fixture.detectChanges(); + tick(500); } get overlayRect() { @@ -1399,151 +1514,165 @@ describe('MatMenu', () => { let subject: OverlapSubject; describe('explicitly overlapping', () => { - beforeEach(() => { + beforeEach(fakeAsync(() => { subject = new OverlapSubject(OverlapMenu, {overlapTrigger: true}); - }); + })); - it('positions the overlay below the trigger', () => { + it('positions the overlay below the trigger', fakeAsync(() => { subject.openMenu(); + // Since the menu is overlaying the trigger, the overlay top should be the trigger top. // Since the menu is overlaying the trigger, the overlay top should be the trigger top. expect(Math.floor(subject.overlayRect.top)) - .toBe(Math.floor(subject.triggerRect.top), - `Expected menu to open in default "below" position.`); - }); + .withContext(`Expected menu to open in default "below" position.`) + .toBe(Math.floor(subject.triggerRect.top)); + })); }); describe('not overlapping', () => { - beforeEach(() => { + beforeEach(fakeAsync(() => { subject = new OverlapSubject(OverlapMenu, {overlapTrigger: false}); - }); + })); - it('positions the overlay below the trigger', () => { + it('positions the overlay below the trigger', fakeAsync(() => { subject.openMenu(); + // Since the menu is below the trigger, the overlay top should be the trigger bottom. // Since the menu is below the trigger, the overlay top should be the trigger bottom. expect(Math.floor(subject.overlayRect.top)) - .toBe(Math.floor(subject.triggerRect.bottom), - `Expected menu to open directly below the trigger.`); - }); + .withContext(`Expected menu to open directly below the trigger.`) + .toBe(Math.floor(subject.triggerRect.bottom)); + })); - it('supports above position fall back', () => { + it('supports above position fall back', fakeAsync(() => { // Push trigger to the bottom part of viewport, so it doesn't have space to open // in its default "below" position below the trigger. subject.trigger.style.position = 'fixed'; subject.trigger.style.bottom = '0'; subject.openMenu(); + // Since the menu is above the trigger, the overlay bottom should be the trigger top. // Since the menu is above the trigger, the overlay bottom should be the trigger top. expect(Math.floor(subject.overlayRect.bottom)) - .toBe(Math.floor(subject.triggerRect.top), - `Expected menu to open in "above" position if "below" position wouldn't fit.`); - }); + .withContext( + `Expected menu to open in "above" position if "below" position ` + `wouldn't fit.`, + ) + .toBe(Math.floor(subject.triggerRect.top)); + })); - it('repositions the origin to be below, so the menu opens from the trigger', () => { + it('repositions the origin to be below, so the menu opens from the trigger', fakeAsync(() => { subject.openMenu(); subject.fixture.detectChanges(); expect(subject.menuPanel!.classList).toContain('mat-menu-below'); expect(subject.menuPanel!.classList).not.toContain('mat-menu-above'); - }); + })); }); }); describe('animations', () => { - it('should enable ripples on items by default', () => { + it('should enable ripples on items by default', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); const item = fixture.debugElement.query(By.css('.mat-menu-item'))!; const ripple = item.query(By.css('.mat-ripple'))!.injector.get(MatRipple); expect(ripple.disabled).toBe(false); - }); + })); - it('should disable ripples on disabled items', () => { + it('should disable ripples on disabled items', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); const items = fixture.debugElement.queryAll(By.css('.mat-menu-item')); const ripple = items[1].query(By.css('.mat-ripple'))!.injector.get(MatRipple); expect(ripple.disabled).toBe(true); - }); + })); - it('should disable ripples if disableRipple is set', () => { + it('should disable ripples if disableRipple is set', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); + tick(500); // The third menu item in the `SimpleMenu` component has ripples disabled. const items = fixture.debugElement.queryAll(By.css('.mat-menu-item')); const ripple = items[2].query(By.css('.mat-ripple'))!.injector.get(MatRipple); expect(ripple.disabled).toBe(true); - }); + })); }); describe('close event', () => { let fixture: ComponentFixture; - beforeEach(() => { + beforeEach(fakeAsync(() => { fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); - }); + tick(500); + })); - it('should emit an event when a menu item is clicked', () => { + it('should emit an event when a menu item is clicked', fakeAsync(() => { const menuItem = overlayContainerElement.querySelector('[mat-menu-item]') as HTMLElement; menuItem.click(); fixture.detectChanges(); + tick(500); expect(fixture.componentInstance.closeCallback).toHaveBeenCalledWith('click'); expect(fixture.componentInstance.closeCallback).toHaveBeenCalledTimes(1); - }); + })); - it('should emit a close event when the backdrop is clicked', () => { - const backdrop = overlayContainerElement - .querySelector('.cdk-overlay-backdrop') as HTMLElement; + it('should emit a close event when the backdrop is clicked', fakeAsync(() => { + const backdrop = overlayContainerElement.querySelector( + '.cdk-overlay-backdrop', + ) as HTMLElement; backdrop.click(); fixture.detectChanges(); + tick(500); expect(fixture.componentInstance.closeCallback).toHaveBeenCalledWith(undefined); expect(fixture.componentInstance.closeCallback).toHaveBeenCalledTimes(1); - }); + })); - it('should emit an event when pressing ESCAPE', () => { + it('should emit an event when pressing ESCAPE', fakeAsync(() => { const menu = overlayContainerElement.querySelector('.mat-menu-panel') as HTMLElement; dispatchKeyboardEvent(menu, 'keydown', ESCAPE); fixture.detectChanges(); + tick(500); expect(fixture.componentInstance.closeCallback).toHaveBeenCalledWith('keydown'); expect(fixture.componentInstance.closeCallback).toHaveBeenCalledTimes(1); - }); + })); - it('should complete the callback when the menu is destroyed', () => { + it('should complete the callback when the menu is destroyed', fakeAsync(() => { const emitCallback = jasmine.createSpy('emit callback'); const completeCallback = jasmine.createSpy('complete callback'); fixture.componentInstance.menu.closed.subscribe(emitCallback, null, completeCallback); fixture.destroy(); + tick(500); expect(emitCallback).toHaveBeenCalledWith(undefined); expect(emitCallback).toHaveBeenCalledTimes(1); expect(completeCallback).toHaveBeenCalled(); - }); + })); }); describe('nested menu', () => { @@ -1551,58 +1680,67 @@ describe('MatMenu', () => { let instance: NestedMenu; let overlay: HTMLElement; let compileTestComponent = (direction: Direction = 'ltr') => { - fixture = createComponent(NestedMenu, [{ - provide: Directionality, useFactory: () => ({value: direction}) - }]); + fixture = createComponent(NestedMenu, [ + { + provide: Directionality, + useFactory: () => ({value: direction}), + }, + ]); fixture.detectChanges(); instance = fixture.componentInstance; overlay = overlayContainerElement; }; - it('should set the `triggersSubmenu` flags on the triggers', () => { + it('should set the `triggersSubmenu` flags on the triggers', fakeAsync(() => { compileTestComponent(); expect(instance.rootTrigger.triggersSubmenu()).toBe(false); expect(instance.levelOneTrigger.triggersSubmenu()).toBe(true); expect(instance.levelTwoTrigger.triggersSubmenu()).toBe(true); - }); + })); - it('should set the `parentMenu` on the sub-menu instances', () => { + it('should set the `parentMenu` on the sub-menu instances', fakeAsync(() => { compileTestComponent(); instance.rootTriggerEl.nativeElement.click(); fixture.detectChanges(); + tick(500); instance.levelOneTrigger.openMenu(); fixture.detectChanges(); + tick(500); instance.levelTwoTrigger.openMenu(); fixture.detectChanges(); + tick(500); expect(instance.rootMenu.parentMenu).toBeFalsy(); expect(instance.levelOneMenu.parentMenu).toBe(instance.rootMenu); expect(instance.levelTwoMenu.parentMenu).toBe(instance.levelOneMenu); - }); + })); - it('should pass the layout direction the nested menus', () => { + it('should pass the layout direction the nested menus', fakeAsync(() => { compileTestComponent('rtl'); instance.rootTriggerEl.nativeElement.click(); fixture.detectChanges(); instance.levelOneTrigger.openMenu(); fixture.detectChanges(); + tick(500); instance.levelTwoTrigger.openMenu(); fixture.detectChanges(); + tick(500); expect(instance.rootMenu.direction).toBe('rtl'); expect(instance.levelOneMenu.direction).toBe('rtl'); expect(instance.levelTwoMenu.direction).toBe('rtl'); - }); + })); - it('should emit an event when the hover state of the menu items changes', () => { + it('should emit an event when the hover state of the menu items changes', fakeAsync(() => { compileTestComponent(); instance.rootTrigger.openMenu(); fixture.detectChanges(); + tick(500); const spy = jasmine.createSpy('hover spy'); const subscription = instance.rootMenu._hovered().subscribe(spy); @@ -1610,22 +1748,26 @@ describe('MatMenu', () => { dispatchMouseEvent(menuItems[0], 'mouseenter'); fixture.detectChanges(); + tick(500); expect(spy).toHaveBeenCalledTimes(1); dispatchMouseEvent(menuItems[1], 'mouseenter'); fixture.detectChanges(); + tick(500); expect(spy).toHaveBeenCalledTimes(2); subscription.unsubscribe(); - }); + })); it('should toggle a nested menu when its trigger is hovered', fakeAsync(() => { compileTestComponent(); instance.rootTriggerEl.nativeElement.click(); fixture.detectChanges(); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(1, 'Expected one open menu'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected one open menu') + .toBe(1); const items = Array.from(overlay.querySelectorAll('.mat-menu-panel [mat-menu-item]')); const levelOneTrigger = overlay.querySelector('#level-one-trigger')!; @@ -1636,73 +1778,83 @@ describe('MatMenu', () => { fixture.detectChanges(); expect(levelOneTrigger.classList) - .toContain('mat-menu-item-highlighted', 'Expected the trigger to be highlighted'); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(2, 'Expected two open menus'); + .withContext('Expected the trigger to be highlighted') + .toContain('mat-menu-item-highlighted'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected two open menus') + .toBe(2); dispatchMouseEvent(items[items.indexOf(levelOneTrigger) + 1], 'mouseenter'); fixture.detectChanges(); tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(1, 'Expected one open menu'); - expect(levelOneTrigger.classList) - .not.toContain('mat-menu-item-highlighted', 'Expected the trigger to not be highlighted'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected one open menu') + .toBe(1); + expect(levelOneTrigger.classList).not.toContain( + 'mat-menu-item-highlighted', + 'Expected the trigger to not be highlighted', + ); })); - it('should close all the open sub-menus when the hover state is changed at the root', - fakeAsync(() => { - compileTestComponent(); - instance.rootTriggerEl.nativeElement.click(); - fixture.detectChanges(); + it('should close all the open sub-menus when the hover state is changed at the root', fakeAsync(() => { + compileTestComponent(); + instance.rootTriggerEl.nativeElement.click(); + fixture.detectChanges(); - const items = Array.from(overlay.querySelectorAll('.mat-menu-panel [mat-menu-item]')); - const levelOneTrigger = overlay.querySelector('#level-one-trigger')!; + const items = Array.from(overlay.querySelectorAll('.mat-menu-panel [mat-menu-item]')); + const levelOneTrigger = overlay.querySelector('#level-one-trigger')!; - dispatchMouseEvent(levelOneTrigger, 'mouseenter'); - fixture.detectChanges(); - tick(); + dispatchMouseEvent(levelOneTrigger, 'mouseenter'); + fixture.detectChanges(); + tick(); - const levelTwoTrigger = overlay.querySelector('#level-two-trigger')! as HTMLElement; - dispatchMouseEvent(levelTwoTrigger, 'mouseenter'); - fixture.detectChanges(); - tick(); + const levelTwoTrigger = overlay.querySelector('#level-two-trigger')! as HTMLElement; + dispatchMouseEvent(levelTwoTrigger, 'mouseenter'); + fixture.detectChanges(); + tick(); - expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(3, 'Expected three open menus'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected three open menus') + .toBe(3); - dispatchMouseEvent(items[items.indexOf(levelOneTrigger) + 1], 'mouseenter'); - fixture.detectChanges(); - tick(500); + dispatchMouseEvent(items[items.indexOf(levelOneTrigger) + 1], 'mouseenter'); + fixture.detectChanges(); + tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(1, 'Expected one open menu'); - })); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected one open menu') + .toBe(1); + })); - it('should close submenu when hovering over disabled sibling item', fakeAsync(() => { - compileTestComponent(); - instance.rootTriggerEl.nativeElement.click(); - fixture.detectChanges(); - tick(500); + it('should close submenu when hovering over disabled sibling item', fakeAsync(() => { + compileTestComponent(); + instance.rootTriggerEl.nativeElement.click(); + fixture.detectChanges(); + tick(500); - const items = fixture.debugElement.queryAll(By.directive(MatMenuItem)); + const items = fixture.debugElement.queryAll(By.directive(MatMenuItem)); - dispatchFakeEvent(items[0].nativeElement, 'mouseenter'); - fixture.detectChanges(); - tick(500); + dispatchFakeEvent(items[0].nativeElement, 'mouseenter'); + fixture.detectChanges(); + tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(2, 'Expected two open menus'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected two open menus') + .toBe(2); - items[1].componentInstance.disabled = true; - fixture.detectChanges(); + items[1].componentInstance.disabled = true; + fixture.detectChanges(); - // Invoke the handler directly since the fake events are flaky on disabled elements. - items[1].componentInstance._handleMouseEnter(); - fixture.detectChanges(); - tick(500); + // Invoke the handler directly since the fake events are flaky on disabled elements. + items[1].componentInstance._handleMouseEnter(); + fixture.detectChanges(); + tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(1, 'Expected one open menu'); - })); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected one open menu') + .toBe(1); + })); it('should not open submenu when hovering over disabled trigger', fakeAsync(() => { compileTestComponent(); @@ -1711,7 +1863,8 @@ describe('MatMenu', () => { tick(500); expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(1, 'Expected one open menu'); + .withContext('Expected one open menu') + .toBe(1); const item = fixture.debugElement.query(By.directive(MatMenuItem))!; @@ -1724,33 +1877,42 @@ describe('MatMenu', () => { tick(500); expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(1, 'Expected to remain at one open menu'); + .withContext('Expected to remain at one open menu') + .toBe(1); })); - - it('should open a nested menu when its trigger is clicked', () => { + it('should open a nested menu when its trigger is clicked', fakeAsync(() => { compileTestComponent(); instance.rootTriggerEl.nativeElement.click(); fixture.detectChanges(); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(1, 'Expected one open menu'); + tick(500); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected one open menu') + .toBe(1); const levelOneTrigger = overlay.querySelector('#level-one-trigger')! as HTMLElement; levelOneTrigger.click(); fixture.detectChanges(); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(2, 'Expected two open menus'); + tick(500); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected two open menus') + .toBe(2); levelOneTrigger.click(); fixture.detectChanges(); expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(2, 'Expected repeat clicks not to close the menu.'); - }); + .withContext('Expected repeat clicks not to close the menu.') + .toBe(2); + })); it('should open and close a nested menu with arrow keys in ltr', fakeAsync(() => { compileTestComponent(); instance.rootTriggerEl.nativeElement.click(); fixture.detectChanges(); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(1, 'Expected one open menu'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected one open menu') + .toBe(1); const levelOneTrigger = overlay.querySelector('#level-one-trigger')! as HTMLElement; @@ -1759,7 +1921,7 @@ describe('MatMenu', () => { const panels = overlay.querySelectorAll('.mat-menu-panel'); - expect(panels.length).toBe(2, 'Expected two open menus'); + expect(panels.length).withContext('Expected two open menus').toBe(2); dispatchKeyboardEvent(panels[1], 'keydown', LEFT_ARROW); fixture.detectChanges(); tick(500); @@ -1771,7 +1933,9 @@ describe('MatMenu', () => { compileTestComponent('rtl'); instance.rootTriggerEl.nativeElement.click(); fixture.detectChanges(); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(1, 'Expected one open menu'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected one open menu') + .toBe(1); const levelOneTrigger = overlay.querySelector('#level-one-trigger')! as HTMLElement; @@ -1780,7 +1944,7 @@ describe('MatMenu', () => { const panels = overlay.querySelectorAll('.mat-menu-panel'); - expect(panels.length).toBe(2, 'Expected two open menus'); + expect(panels.length).withContext('Expected two open menus').toBe(2); dispatchKeyboardEvent(panels[1], 'keydown', RIGHT_ARROW); fixture.detectChanges(); tick(500); @@ -1788,135 +1952,181 @@ describe('MatMenu', () => { expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(1); })); - it('should not do anything with the arrow keys for a top-level menu', () => { + it('should not do anything with the arrow keys for a top-level menu', fakeAsync(() => { compileTestComponent(); instance.rootTriggerEl.nativeElement.click(); fixture.detectChanges(); + tick(500); const menu = overlay.querySelector('.mat-menu-panel')!; dispatchKeyboardEvent(menu, 'keydown', RIGHT_ARROW); fixture.detectChanges(); + tick(500); expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(1, 'Expected one menu to remain open'); + .withContext('Expected one menu to remain open') + .toBe(1); dispatchKeyboardEvent(menu, 'keydown', LEFT_ARROW); fixture.detectChanges(); + tick(500); expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(1, 'Expected one menu to remain open'); - }); + .withContext('Expected one menu to remain open') + .toBe(1); + })); it('should close all of the menus when the backdrop is clicked', fakeAsync(() => { compileTestComponent(); instance.rootTriggerEl.nativeElement.click(); fixture.detectChanges(); + tick(500); instance.levelOneTrigger.openMenu(); fixture.detectChanges(); + tick(500); instance.levelTwoTrigger.openMenu(); fixture.detectChanges(); + tick(500); expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(3, 'Expected three open menus'); + .withContext('Expected three open menus') + .toBe(3); expect(overlay.querySelectorAll('.cdk-overlay-backdrop').length) - .toBe(1, 'Expected one backdrop element'); + .withContext('Expected one backdrop element') + .toBe(1); expect(overlay.querySelectorAll('.mat-menu-panel, .cdk-overlay-backdrop')[0].classList) - .toContain('cdk-overlay-backdrop', 'Expected backdrop to be beneath all of the menus'); + .withContext('Expected backdrop to be beneath all of the menus') + .toContain('cdk-overlay-backdrop'); (overlay.querySelector('.cdk-overlay-backdrop')! as HTMLElement).click(); fixture.detectChanges(); tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(0, 'Expected no open menus'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected no open menus') + .toBe(0); })); - it('should shift focus between the sub-menus', () => { + it('should shift focus between the sub-menus', fakeAsync(() => { compileTestComponent(); instance.rootTrigger.openMenu(); fixture.detectChanges(); + tick(500); expect(overlay.querySelector('.mat-menu-panel')!.contains(document.activeElement)) - .toBe(true, 'Expected focus to be inside the root menu'); + .withContext('Expected focus to be inside the root menu') + .toBe(true); instance.levelOneTrigger.openMenu(); fixture.detectChanges(); + tick(500); expect(overlay.querySelectorAll('.mat-menu-panel')[1].contains(document.activeElement)) - .toBe(true, 'Expected focus to be inside the first nested menu'); + .withContext('Expected focus to be inside the first nested menu') + .toBe(true); instance.levelTwoTrigger.openMenu(); fixture.detectChanges(); + tick(500); expect(overlay.querySelectorAll('.mat-menu-panel')[2].contains(document.activeElement)) - .toBe(true, 'Expected focus to be inside the second nested menu'); + .withContext('Expected focus to be inside the second nested menu') + .toBe(true); instance.levelTwoTrigger.closeMenu(); fixture.detectChanges(); + tick(500); expect(overlay.querySelectorAll('.mat-menu-panel')[1].contains(document.activeElement)) - .toBe(true, 'Expected focus to be back inside the first nested menu'); + .withContext('Expected focus to be back inside the first nested menu') + .toBe(true); instance.levelOneTrigger.closeMenu(); fixture.detectChanges(); + tick(500); expect(overlay.querySelector('.mat-menu-panel')!.contains(document.activeElement)) - .toBe(true, 'Expected focus to be back inside the root menu'); - }); + .withContext('Expected focus to be back inside the root menu') + .toBe(true); + })); + + it('should restore focus to a nested trigger when navgating via the keyboard', fakeAsync(() => { + compileTestComponent(); + instance.rootTriggerEl.nativeElement.click(); + fixture.detectChanges(); + + const levelOneTrigger = overlay.querySelector('#level-one-trigger')! as HTMLElement; + dispatchKeyboardEvent(levelOneTrigger, 'keydown', RIGHT_ARROW); + fixture.detectChanges(); + + const spy = spyOn(levelOneTrigger, 'focus').and.callThrough(); + dispatchKeyboardEvent(overlay.querySelectorAll('.mat-menu-panel')[1], 'keydown', LEFT_ARROW); + fixture.detectChanges(); + tick(500); - it('should position the sub-menu to the right edge of the trigger in ltr', () => { + expect(spy).toHaveBeenCalled(); + })); + + it('should position the sub-menu to the right edge of the trigger in ltr', fakeAsync(() => { compileTestComponent(); instance.rootTriggerEl.nativeElement.style.position = 'fixed'; instance.rootTriggerEl.nativeElement.style.left = '50px'; instance.rootTriggerEl.nativeElement.style.top = '50px'; instance.rootTrigger.openMenu(); fixture.detectChanges(); + tick(500); instance.levelOneTrigger.openMenu(); fixture.detectChanges(); + tick(500); const triggerRect = overlay.querySelector('#level-one-trigger')!.getBoundingClientRect(); const panelRect = overlay.querySelectorAll('.cdk-overlay-pane')[1].getBoundingClientRect(); expect(Math.round(triggerRect.right)).toBe(Math.round(panelRect.left)); expect(Math.round(triggerRect.top)).toBe(Math.round(panelRect.top) + MENU_PANEL_TOP_PADDING); - }); + })); - it('should fall back to aligning to the left edge of the trigger in ltr', () => { + it('should fall back to aligning to the left edge of the trigger in ltr', fakeAsync(() => { compileTestComponent(); instance.rootTriggerEl.nativeElement.style.position = 'fixed'; instance.rootTriggerEl.nativeElement.style.right = '10px'; instance.rootTriggerEl.nativeElement.style.top = '50%'; instance.rootTrigger.openMenu(); fixture.detectChanges(); + tick(500); instance.levelOneTrigger.openMenu(); fixture.detectChanges(); + tick(500); const triggerRect = overlay.querySelector('#level-one-trigger')!.getBoundingClientRect(); const panelRect = overlay.querySelectorAll('.cdk-overlay-pane')[1].getBoundingClientRect(); expect(Math.round(triggerRect.left)).toBe(Math.round(panelRect.right)); expect(Math.round(triggerRect.top)).toBe(Math.round(panelRect.top) + MENU_PANEL_TOP_PADDING); - }); + })); - it('should position the sub-menu to the left edge of the trigger in rtl', () => { + it('should position the sub-menu to the left edge of the trigger in rtl', fakeAsync(() => { compileTestComponent('rtl'); instance.rootTriggerEl.nativeElement.style.position = 'fixed'; instance.rootTriggerEl.nativeElement.style.left = '50%'; instance.rootTriggerEl.nativeElement.style.top = '50%'; instance.rootTrigger.openMenu(); fixture.detectChanges(); + tick(500); instance.levelOneTrigger.openMenu(); fixture.detectChanges(); + tick(500); const triggerRect = overlay.querySelector('#level-one-trigger')!.getBoundingClientRect(); const panelRect = overlay.querySelectorAll('.cdk-overlay-pane')[1].getBoundingClientRect(); expect(Math.round(triggerRect.left)).toBe(Math.round(panelRect.right)); expect(Math.round(triggerRect.top)).toBe(Math.round(panelRect.top) + MENU_PANEL_TOP_PADDING); - }); + })); it('should fall back to aligning to the right edge of the trigger in rtl', fakeAsync(() => { compileTestComponent('rtl'); @@ -1951,13 +2161,15 @@ describe('MatMenu', () => { const menus = overlay.querySelectorAll('.mat-menu-panel'); - expect(menus.length).toBe(3, 'Expected three open menus'); + expect(menus.length).withContext('Expected three open menus').toBe(3); (menus[2].querySelector('.mat-menu-item')! as HTMLElement).click(); fixture.detectChanges(); tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(0, 'Expected no open menus'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected no open menus') + .toBe(0); })); it('should close all of the menus when the user tabs away', fakeAsync(() => { @@ -1973,117 +2185,137 @@ describe('MatMenu', () => { const menus = overlay.querySelectorAll('.mat-menu-panel'); - expect(menus.length).toBe(3, 'Expected three open menus'); + expect(menus.length).withContext('Expected three open menus').toBe(3); dispatchKeyboardEvent(menus[menus.length - 1], 'keydown', TAB); fixture.detectChanges(); tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(0, 'Expected no open menus'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected no open menus') + .toBe(0); })); - it('should set a class on the menu items that trigger a sub-menu', () => { + it('should set a class on the menu items that trigger a sub-menu', fakeAsync(() => { compileTestComponent(); instance.rootTrigger.openMenu(); fixture.detectChanges(); + tick(500); const menuItems = overlay.querySelectorAll('[mat-menu-item]'); expect(menuItems[0].classList).toContain('mat-menu-item-submenu-trigger'); + expect(menuItems[0].querySelector('.mat-menu-submenu-icon')).toBeTruthy(); expect(menuItems[1].classList).not.toContain('mat-menu-item-submenu-trigger'); - }); + expect(menuItems[1].querySelector('.mat-menu-submenu-icon')).toBeFalsy(); + })); - it('should increase the sub-menu elevation based on its depth', () => { + it('should increase the sub-menu elevation based on its depth', fakeAsync(() => { compileTestComponent(); instance.rootTrigger.openMenu(); fixture.detectChanges(); + tick(500); instance.levelOneTrigger.openMenu(); fixture.detectChanges(); + tick(500); instance.levelTwoTrigger.openMenu(); fixture.detectChanges(); + tick(500); const menus = overlay.querySelectorAll('.mat-menu-panel'); expect(menus[0].classList) - .toContain('mat-elevation-z4', 'Expected root menu to have base elevation.'); + .withContext('Expected root menu to have base elevation.') + .toContain('mat-elevation-z4'); expect(menus[1].classList) - .toContain('mat-elevation-z5', 'Expected first sub-menu to have base elevation + 1.'); + .withContext('Expected first sub-menu to have base elevation + 1.') + .toContain('mat-elevation-z5'); expect(menus[2].classList) - .toContain('mat-elevation-z6', 'Expected second sub-menu to have base elevation + 2.'); - }); + .withContext('Expected second sub-menu to have base elevation + 2.') + .toContain('mat-elevation-z6'); + })); - it('should update the elevation when the same menu is opened at a different depth', - fakeAsync(() => { - compileTestComponent(); - instance.rootTrigger.openMenu(); - fixture.detectChanges(); + it('should update the elevation when the same menu is opened at a different depth', fakeAsync(() => { + compileTestComponent(); + instance.rootTrigger.openMenu(); + fixture.detectChanges(); - instance.levelOneTrigger.openMenu(); - fixture.detectChanges(); + instance.levelOneTrigger.openMenu(); + fixture.detectChanges(); - instance.levelTwoTrigger.openMenu(); - fixture.detectChanges(); + instance.levelTwoTrigger.openMenu(); + fixture.detectChanges(); - let lastMenu = overlay.querySelectorAll('.mat-menu-panel')[2]; + let lastMenu = overlay.querySelectorAll('.mat-menu-panel')[2]; - expect(lastMenu.classList) - .toContain('mat-elevation-z6', 'Expected menu to have the base elevation plus two.'); + expect(lastMenu.classList) + .withContext('Expected menu to have the base elevation plus two.') + .toContain('mat-elevation-z6'); - (overlay.querySelector('.cdk-overlay-backdrop')! as HTMLElement).click(); - fixture.detectChanges(); - tick(500); + (overlay.querySelector('.cdk-overlay-backdrop')! as HTMLElement).click(); + fixture.detectChanges(); + tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(0, 'Expected no open menus'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected no open menus') + .toBe(0); - instance.alternateTrigger.openMenu(); - fixture.detectChanges(); - tick(500); + instance.alternateTrigger.openMenu(); + fixture.detectChanges(); + tick(500); - lastMenu = overlay.querySelector('.mat-menu-panel') as HTMLElement; + lastMenu = overlay.querySelector('.mat-menu-panel') as HTMLElement; - expect(lastMenu.classList) - .not.toContain('mat-elevation-z6', 'Expected menu not to maintain old elevation.'); - expect(lastMenu.classList) - .toContain('mat-elevation-z4', 'Expected menu to have the proper updated elevation.'); - })); + expect(lastMenu.classList) + .not.withContext('Expected menu not to maintain old elevation.') + .toContain('mat-elevation-z6'); + expect(lastMenu.classList) + .withContext('Expected menu to have the proper updated elevation.') + .toContain('mat-elevation-z4'); + })); - it('should not change focus origin if origin not specified for trigger', fakeAsync(() => { - compileTestComponent(); + it('should not change focus origin if origin not specified for trigger', fakeAsync(() => { + compileTestComponent(); - instance.levelOneTrigger.openMenu(); - instance.levelOneTrigger.focus('mouse'); - fixture.detectChanges(); + instance.levelOneTrigger.openMenu(); + fixture.detectChanges(); + tick(500); + instance.levelOneTrigger.focus('mouse'); + fixture.detectChanges(); - instance.levelTwoTrigger.focus(); - fixture.detectChanges(); - tick(500); + instance.levelTwoTrigger.focus(); + fixture.detectChanges(); + tick(500); - const levelTwoTrigger = overlay.querySelector('#level-two-trigger')! as HTMLElement; + const levelTwoTrigger = overlay.querySelector('#level-two-trigger')! as HTMLElement; - expect(levelTwoTrigger.classList).toContain('cdk-focused'); - expect(levelTwoTrigger.classList).toContain('cdk-mouse-focused'); - })); + expect(levelTwoTrigger.classList).toContain('cdk-focused'); + expect(levelTwoTrigger.classList).toContain('cdk-mouse-focused'); + })); - it('should not increase the elevation if the user specified a custom one', () => { + it('should not increase the elevation if the user specified a custom one', fakeAsync(() => { const elevationFixture = createComponent(NestedMenuCustomElevation); elevationFixture.detectChanges(); elevationFixture.componentInstance.rootTrigger.openMenu(); elevationFixture.detectChanges(); + tick(500); elevationFixture.componentInstance.levelOneTrigger.openMenu(); elevationFixture.detectChanges(); + tick(500); const menuClasses = overlayContainerElement.querySelectorAll('.mat-menu-panel')[1].classList; expect(menuClasses) - .toContain('mat-elevation-z24', 'Expected user elevation to be maintained'); + .withContext('Expected user elevation to be maintained') + .toContain('mat-elevation-z24'); expect(menuClasses) - .not.toContain('mat-elevation-z3', 'Expected no stacked elevation.'); - }); + .not.withContext('Expected no stacked elevation.') + .toContain('mat-elevation-z3'); + })); it('should close all of the menus when the root is closed programmatically', fakeAsync(() => { compileTestComponent(); @@ -2098,13 +2330,15 @@ describe('MatMenu', () => { const menus = overlay.querySelectorAll('.mat-menu-panel'); - expect(menus.length).toBe(3, 'Expected three open menus'); + expect(menus.length).withContext('Expected three open menus').toBe(3); instance.rootTrigger.closeMenu(); fixture.detectChanges(); tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(0, 'Expected no open menus'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected no open menus') + .toBe(0); })); it('should toggle a nested menu when its trigger is added after init', fakeAsync(() => { @@ -2112,7 +2346,9 @@ describe('MatMenu', () => { instance.rootTriggerEl.nativeElement.click(); fixture.detectChanges(); tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(1, 'Expected one open menu'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected one open menu') + .toBe(1); instance.showLazy = true; fixture.detectChanges(); @@ -2125,23 +2361,29 @@ describe('MatMenu', () => { fixture.detectChanges(); expect(lazyTrigger.classList) - .toContain('mat-menu-item-highlighted', 'Expected the trigger to be highlighted'); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(2, 'Expected two open menus'); + .withContext('Expected the trigger to be highlighted') + .toContain('mat-menu-item-highlighted'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected two open menus') + .toBe(2); })); - it('should prevent the default mousedown action if the menu item opens a sub-menu', () => { + it('should prevent the default mousedown action if the menu item opens a sub-menu', fakeAsync(() => { compileTestComponent(); instance.rootTrigger.openMenu(); fixture.detectChanges(); + tick(500); const event = createMouseEvent('mousedown'); - Object.defineProperty(event, 'buttons', {get: () => 1}); event.preventDefault = jasmine.createSpy('preventDefault spy'); dispatchEvent(overlay.querySelector('[mat-menu-item]')!, event); + fixture.detectChanges(); + tick(500); + expect(event.preventDefault).toHaveBeenCalled(); - }); + })); it('should handle the items being rendered in a repeater', fakeAsync(() => { const repeaterFixture = createComponent(NestedMenuRepeater); @@ -2152,12 +2394,16 @@ describe('MatMenu', () => { repeaterFixture.componentInstance.rootTriggerEl.nativeElement.click(); repeaterFixture.detectChanges(); tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(1, 'Expected one open menu'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected one open menu') + .toBe(1); dispatchMouseEvent(overlay.querySelector('.level-one-trigger')!, 'mouseenter'); repeaterFixture.detectChanges(); tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(2, 'Expected two open menus'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected two open menus') + .toBe(2); })); it('should be able to trigger the same nested menu from different triggers', fakeAsync(() => { @@ -2168,20 +2414,26 @@ describe('MatMenu', () => { repeaterFixture.componentInstance.rootTriggerEl.nativeElement.click(); repeaterFixture.detectChanges(); tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(1, 'Expected one open menu'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected one open menu') + .toBe(1); const triggers = overlay.querySelectorAll('.level-one-trigger'); dispatchMouseEvent(triggers[0], 'mouseenter'); repeaterFixture.detectChanges(); tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(2, 'Expected two open menus'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected two open menus') + .toBe(2); dispatchMouseEvent(triggers[1], 'mouseenter'); repeaterFixture.detectChanges(); tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(2, 'Expected two open menus'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected two open menus') + .toBe(2); })); it('should close the initial menu if the user moves away while animating', fakeAsync(() => { @@ -2192,7 +2444,9 @@ describe('MatMenu', () => { repeaterFixture.componentInstance.rootTriggerEl.nativeElement.click(); repeaterFixture.detectChanges(); tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(1, 'Expected one open menu'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected one open menu') + .toBe(1); const triggers = overlay.querySelectorAll('.level-one-trigger'); @@ -2203,11 +2457,15 @@ describe('MatMenu', () => { repeaterFixture.detectChanges(); tick(500); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(2, 'Expected two open menus'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected two open menus') + .toBe(2); })); - it('should be able to open a submenu through an item that is not a direct descendant ' + - 'of the panel', fakeAsync(() => { + it( + 'should be able to open a submenu through an item that is not a direct descendant ' + + 'of the panel', + fakeAsync(() => { const nestedFixture = createComponent(SubmenuDeclaredInsideParentMenu); overlay = overlayContainerElement; @@ -2216,18 +2474,23 @@ describe('MatMenu', () => { nestedFixture.detectChanges(); tick(500); expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(1, 'Expected one open menu'); + .withContext('Expected one open menu') + .toBe(1); dispatchMouseEvent(overlay.querySelector('.level-one-trigger')!, 'mouseenter'); nestedFixture.detectChanges(); tick(500); expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(2, 'Expected two open menus'); - })); - - it('should not close when hovering over a menu item inside a sub-menu panel that is declared' + - 'inside the root menu', fakeAsync(() => { + .withContext('Expected two open menus') + .toBe(2); + }), + ); + + it( + 'should not close when hovering over a menu item inside a sub-menu panel that is declared' + + 'inside the root menu', + fakeAsync(() => { const nestedFixture = createComponent(SubmenuDeclaredInsideParentMenu); overlay = overlayContainerElement; @@ -2236,22 +2499,26 @@ describe('MatMenu', () => { nestedFixture.detectChanges(); tick(500); expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(1, 'Expected one open menu'); + .withContext('Expected one open menu') + .toBe(1); dispatchMouseEvent(overlay.querySelector('.level-one-trigger')!, 'mouseenter'); nestedFixture.detectChanges(); tick(500); expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(2, 'Expected two open menus'); + .withContext('Expected two open menus') + .toBe(2); dispatchMouseEvent(overlay.querySelector('.level-two-item')!, 'mouseenter'); nestedFixture.detectChanges(); tick(500); expect(overlay.querySelectorAll('.mat-menu-panel').length) - .toBe(2, 'Expected two open menus to remain'); - })); + .withContext('Expected two open menus to remain') + .toBe(2); + }), + ); it('should not re-focus a child menu trigger when hovering another trigger', fakeAsync(() => { compileTestComponent(); @@ -2266,29 +2533,35 @@ describe('MatMenu', () => { dispatchMouseEvent(levelOneTrigger, 'mouseenter'); fixture.detectChanges(); tick(); - expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(2, 'Expected two open menus'); + expect(overlay.querySelectorAll('.mat-menu-panel').length) + .withContext('Expected two open menus') + .toBe(2); dispatchMouseEvent(items[items.indexOf(levelOneTrigger) + 1], 'mouseenter'); fixture.detectChanges(); tick(500); - expect(document.activeElement) - .not.toBe(levelOneTrigger, 'Expected focus not to be returned to the initial trigger.'); + expect(document.activeElement).not.toBe( + levelOneTrigger, + 'Expected focus not to be returned to the initial trigger.', + ); })); - }); - it('should have a focus indicator', () => { + it('should have a focus indicator', fakeAsync(() => { const fixture = createComponent(SimpleMenu, [], [FakeIcon]); fixture.detectChanges(); fixture.componentInstance.trigger.openMenu(); fixture.detectChanges(); - const menuItemNativeElements = - Array.from(overlayContainerElement.querySelectorAll('.mat-menu-item')); + tick(500); + const menuItemNativeElements = Array.from( + overlayContainerElement.querySelectorAll('.mat-menu-item'), + ); - expect(menuItemNativeElements - .every(element => element.classList.contains('mat-focus-indicator'))).toBe(true); - }); + expect( + menuItemNativeElements.every(element => element.classList.contains('mat-focus-indicator')), + ).toBe(true); + })); }); describe('MatMenu default overrides', () => { @@ -2296,14 +2569,16 @@ describe('MatMenu default overrides', () => { TestBed.configureTestingModule({ imports: [MatMenuModule, NoopAnimationsModule], declarations: [SimpleMenu, FakeIcon], - providers: [{ - provide: MAT_MENU_DEFAULT_OPTIONS, - useValue: {overlapTrigger: true, xPosition: 'before', yPosition: 'above'}, - }], + providers: [ + { + provide: MAT_MENU_DEFAULT_OPTIONS, + useValue: {overlapTrigger: true, xPosition: 'before', yPosition: 'above'}, + }, + ], }).compileComponents(); })); - it('should allow for the default menu options to be overridden', () => { + it('should allow for the default menu options to be overridden', fakeAsync(() => { const fixture = TestBed.createComponent(SimpleMenu); fixture.detectChanges(); const menu = fixture.componentInstance.menu; @@ -2311,7 +2586,7 @@ describe('MatMenu default overrides', () => { expect(menu.overlapTrigger).toBe(true); expect(menu.xPosition).toBe('before'); expect(menu.yPosition).toBe('above'); - }); + })); }); @Component({ @@ -2340,7 +2615,7 @@ describe('MatMenu default overrides', () => { - ` + `, }) class SimpleMenu { @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; @@ -2363,7 +2638,7 @@ class SimpleMenu { - ` + `, }) class PositionedMenu { @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; @@ -2382,7 +2657,7 @@ interface TestableMenu { - ` + `, }) class OverlapMenu implements TestableMenu { @Input() overlapTrigger: boolean; @@ -2398,7 +2673,7 @@ class OverlapMenu implements TestableMenu { `, - exportAs: 'matCustomMenu' + exportAs: 'matCustomMenu', }) class CustomMenuPanel implements MatMenuPanel { direction: Direction; @@ -2408,7 +2683,7 @@ class CustomMenuPanel implements MatMenuPanel { parentMenu: MatMenuPanel; @ViewChild(TemplateRef) templateRef: TemplateRef; - @Output() close = new EventEmitter(); + @Output() readonly close = new EventEmitter(); focusFirstItem = () => {}; resetActiveItem = () => {}; setPositionClasses = () => {}; @@ -2420,13 +2695,12 @@ class CustomMenuPanel implements MatMenuPanel { - ` + `, }) class CustomMenu { @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; } - @Component({ template: ` - ` + `, }) class NestedMenu { @ViewChild('root') rootMenu: MatMenu; @@ -2506,14 +2780,13 @@ class NestedMenu { - ` + `, }) class NestedMenuCustomElevation { @ViewChild('rootTrigger') rootTrigger: MatMenuTrigger; @ViewChild('levelOneTrigger') levelOneTrigger: MatMenuTrigger; } - @Component({ template: ` @@ -2529,7 +2802,7 @@ class NestedMenuCustomElevation { - ` + `, }) class NestedMenuRepeater { @ViewChild('rootTriggerEl') rootTriggerEl: ElementRef; @@ -2538,7 +2811,6 @@ class NestedMenuRepeater { items = ['one', 'two', 'three']; } - @Component({ template: ` @@ -2550,20 +2822,18 @@ class NestedMenuRepeater { - ` + `, }) class SubmenuDeclaredInsideParentMenu { @ViewChild('rootTriggerEl') rootTriggerEl: ElementRef; } - @Component({ selector: 'mat-icon', - template: '' + template: '', }) class FakeIcon {} - @Component({ template: ` @@ -2574,7 +2844,7 @@ class FakeIcon {} - ` + `, }) class SimpleLazyMenu { @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; @@ -2582,7 +2852,6 @@ class SimpleLazyMenu { @ViewChildren(MatMenuItem) items: QueryList; } - @Component({ template: ` - ` + `, }) class LazyMenuWithContext { @ViewChild('triggerOne') triggerOne: MatMenuTrigger; @ViewChild('triggerTwo') triggerTwo: MatMenuTrigger; } - @Component({ template: ` @@ -2618,7 +2886,7 @@ class LazyMenuWithContext { - ` + `, }) class DynamicPanelMenu { @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; @@ -2626,7 +2894,6 @@ class DynamicPanelMenu { @ViewChild('two') secondMenu: MatMenu; } - @Component({ template: ` @@ -2635,13 +2902,12 @@ class DynamicPanelMenu { - ` + `, }) class MenuWithCheckboxItems { @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; } - @Component({ template: ` @@ -2651,13 +2917,16 @@ class MenuWithCheckboxItems { [disabled]="item.disabled" mat-menu-item>{{item.label}} - ` + `, }) class SimpleMenuWithRepeater { @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; @ViewChild(MatMenu) menu: MatMenu; @ViewChildren(MatMenuItem) itemInstances: QueryList; - items = [{label: 'Pizza', disabled: false}, {label: 'Pasta', disabled: false}]; + items = [ + {label: 'Pizza', disabled: false}, + {label: 'Pasta', disabled: false}, + ]; } @Component({ @@ -2671,12 +2940,15 @@ class SimpleMenuWithRepeater { mat-menu-item>{{item.label}} - ` + `, }) class SimpleMenuWithRepeaterInLazyContent { @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; @ViewChild(MatMenu) menu: MatMenu; - items = [{label: 'Pizza', disabled: false}, {label: 'Pasta', disabled: false}]; + items = [ + {label: 'Pizza', disabled: false}, + {label: 'Pasta', disabled: false}, + ]; } @Component({ @@ -2702,31 +2974,26 @@ class LazyMenuWithOnPush { @ViewChild('menuItem', {read: ElementRef}) menuItemWithSubmenu: ElementRef; } - @Component({ template: ` - ` + `, }) -class InvalidRecursiveMenu { -} - +class InvalidRecursiveMenu {} @Component({ - template: '' + template: '', }) class StaticAriaLabelMenu {} - @Component({ - template: '' + template: '', }) class StaticAriaLabelledByMenu {} - @Component({ - template: '' + template: '', }) class StaticAriaDescribedbyMenu {} diff --git a/src/material/menu/menu.ts b/src/material/menu/menu.ts index b33a4409df47..c7718eddfa1d 100644 --- a/src/material/menu/menu.ts +++ b/src/material/menu/menu.ts @@ -70,11 +70,13 @@ export interface MatMenuDefaultOptions { } /** Injection token to be used to override the default options for `mat-menu`. */ -export const MAT_MENU_DEFAULT_OPTIONS = - new InjectionToken('mat-menu-default-options', { - providedIn: 'root', - factory: MAT_MENU_DEFAULT_OPTIONS_FACTORY - }); +export const MAT_MENU_DEFAULT_OPTIONS = new InjectionToken( + 'mat-menu-default-options', + { + providedIn: 'root', + factory: MAT_MENU_DEFAULT_OPTIONS_FACTORY, + }, +); /** @docs-private */ export function MAT_MENU_DEFAULT_OPTIONS_FACTORY(): MatMenuDefaultOptions { @@ -85,22 +87,23 @@ export function MAT_MENU_DEFAULT_OPTIONS_FACTORY(): MatMenuDefaultOptions { backdropClass: 'cdk-overlay-transparent-backdrop', }; } -/** - * Start elevation for the menu panel. - * @docs-private - */ -const MAT_MENU_BASE_ELEVATION = 4; let menuPanelUid = 0; +/** Reason why the menu was closed. */ +export type MenuCloseReason = void | 'click' | 'keydown' | 'tab'; + /** Base class with all of the `MatMenu` functionality. */ @Directive() -export class _MatMenuBase implements AfterContentInit, MatMenuPanel, OnInit, - OnDestroy { +export class _MatMenuBase + implements AfterContentInit, MatMenuPanel, OnInit, OnDestroy +{ private _keyManager: FocusKeyManager; private _xPosition: MenuPositionX = this._defaultOptions.xPosition; private _yPosition: MenuPositionY = this._defaultOptions.yPosition; private _previousElevation: string; + protected _elevationPrefix: string; + protected _baseElevation: number; /** All items inside the menu. Includes items nested inside another menu. */ @ContentChildren(MatMenuItem, {descendants: true}) _allItems: QueryList; @@ -118,7 +121,7 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel _panelAnimationState: 'void' | 'enter' = 'void'; /** Emits whenever an animation on the menu completes. */ - _animationDone = new Subject(); + readonly _animationDone = new Subject(); /** Whether the menu is animating. */ _isAnimating: boolean; @@ -130,7 +133,7 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel direction: Direction; /** Class or list of classes to be added to the overlay panel. */ - overlayPanelClass: string|string[] = this._defaultOptions.overlayPanelClass || ''; + overlayPanelClass: string | string[] = this._defaultOptions.overlayPanelClass || ''; /** Class to be added to the backdrop element. */ @Input() backdropClass: string = this._defaultOptions.backdropClass; @@ -146,10 +149,15 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel /** Position of the menu in the X axis. */ @Input() - get xPosition(): MenuPositionX { return this._xPosition; } + get xPosition(): MenuPositionX { + return this._xPosition; + } set xPosition(value: MenuPositionX) { - if (value !== 'before' && value !== 'after' && - (typeof ngDevMode === 'undefined' || ngDevMode)) { + if ( + value !== 'before' && + value !== 'after' && + (typeof ngDevMode === 'undefined' || ngDevMode) + ) { throwMatMenuInvalidPositionX(); } this._xPosition = value; @@ -158,7 +166,9 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel /** Position of the menu in the Y axis. */ @Input() - get yPosition(): MenuPositionY { return this._yPosition; } + get yPosition(): MenuPositionY { + return this._yPosition; + } set yPosition(value: MenuPositionY) { if (value !== 'above' && value !== 'below' && (typeof ngDevMode === 'undefined' || ngDevMode)) { throwMatMenuInvalidPositionY(); @@ -185,16 +195,20 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel /** Whether the menu should overlap its trigger. */ @Input() - get overlapTrigger(): boolean { return this._overlapTrigger; } - set overlapTrigger(value: boolean) { + get overlapTrigger(): boolean { + return this._overlapTrigger; + } + set overlapTrigger(value: BooleanInput) { this._overlapTrigger = coerceBooleanProperty(value); } private _overlapTrigger: boolean = this._defaultOptions.overlapTrigger; /** Whether the menu has a backdrop. */ @Input() - get hasBackdrop(): boolean | undefined { return this._hasBackdrop; } - set hasBackdrop(value: boolean | undefined) { + get hasBackdrop(): boolean | undefined { + return this._hasBackdrop; + } + set hasBackdrop(value: BooleanInput) { this._hasBackdrop = coerceBooleanProperty(value); } private _hasBackdrop: boolean | undefined = this._defaultOptions.hasBackdrop; @@ -235,26 +249,30 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel * @breaking-change 8.0.0 */ @Input() - get classList(): string { return this.panelClass; } - set classList(classes: string) { this.panelClass = classes; } + get classList(): string { + return this.panelClass; + } + set classList(classes: string) { + this.panelClass = classes; + } /** Event emitted when the menu is closed. */ - @Output() readonly closed: EventEmitter = - new EventEmitter(); + @Output() readonly closed: EventEmitter = new EventEmitter(); /** * Event emitted when the menu is closed. * @deprecated Switch to `closed` instead * @breaking-change 8.0.0 */ - @Output() close: EventEmitter = this.closed; + @Output() readonly close: EventEmitter = this.closed; readonly panelId = `mat-menu-panel-${menuPanelUid++}`; constructor( private _elementRef: ElementRef, private _ngZone: NgZone, - @Inject(MAT_MENU_DEFAULT_OPTIONS) private _defaultOptions: MatMenuDefaultOptions) { } + @Inject(MAT_MENU_DEFAULT_OPTIONS) private _defaultOptions: MatMenuDefaultOptions, + ) {} ngOnInit() { this.setPositionClasses(); @@ -268,13 +286,15 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel .withHomeAndEnd(); this._tabSubscription = this._keyManager.tabOut.subscribe(() => this.closed.emit('tab')); - // If a user manually (programatically) focuses a menu item, we need to reflect that focus + // If a user manually (programmatically) focuses a menu item, we need to reflect that focus // change back to the key manager. Note that we don't need to unsubscribe here because _focused // is internal and we know that it gets completed on destroy. - this._directDescendantItems.changes.pipe( - startWith(this._directDescendantItems), - switchMap(items => merge(...items.map((item: MatMenuItem) => item._focused))) - ).subscribe(focusedItem => this._keyManager.updateActiveItem(focusedItem)); + this._directDescendantItems.changes + .pipe( + startWith(this._directDescendantItems), + switchMap(items => merge(...items.map((item: MatMenuItem) => item._focused))), + ) + .subscribe(focusedItem => this._keyManager.updateActiveItem(focusedItem as MatMenuItem)); } ngOnDestroy() { @@ -289,7 +309,7 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel const itemChanges = this._directDescendantItems.changes as Observable>; return itemChanges.pipe( startWith(this._directDescendantItems), - switchMap(items => merge(...items.map((item: MatMenuItem) => item._hovered))) + switchMap(items => merge(...items.map((item: MatMenuItem) => item._hovered))), ) as Observable; } @@ -320,17 +340,17 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel event.preventDefault(); this.closed.emit('keydown'); } - break; + break; case LEFT_ARROW: if (this.parentMenu && this.direction === 'ltr') { this.closed.emit('keydown'); } - break; + break; case RIGHT_ARROW: if (this.parentMenu && this.direction === 'rtl') { this.closed.emit('keydown'); } - break; + break; default: if (keyCode === UP_ARROW || keyCode === DOWN_ARROW) { manager.setFocusOrigin('keyboard'); @@ -347,9 +367,7 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel focusFirstItem(origin: FocusOrigin = 'program'): void { // When the content is rendered lazily, it takes a bit before the items are inside the DOM. if (this.lazyContent) { - this._ngZone.onStable - .pipe(take(1)) - .subscribe(() => this._focusFirstItem(origin)); + this._ngZone.onStable.pipe(take(1)).subscribe(() => this._focusFirstItem(origin)); } else { this._focusFirstItem(origin); } @@ -368,7 +386,7 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel // Move focus to the menu panel so keyboard events like Escape still work. Also this will // give _some_ feedback to screen readers. if (!manager.activeItem && this._directDescendantItems.length) { - let element = this._directDescendantItems.first._getHostElement().parentElement; + let element = this._directDescendantItems.first!._getHostElement().parentElement; // Because the `mat-menu` is at the DOM insertion point, not inside the overlay, we don't // have a nice way of getting a hold of the menu panel. We can't use a `ViewChild` either @@ -400,9 +418,11 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel setElevation(depth: number): void { // The elevation starts at the base and increases by one for each level. // Capped at 24 because that's the maximum elevation defined in the Material design spec. - const elevation = Math.min(MAT_MENU_BASE_ELEVATION + depth, 24); - const newElevation = `mat-elevation-z${elevation}`; - const customElevation = Object.keys(this._classList).find(c => c.startsWith('mat-elevation-z')); + const elevation = Math.min(this._baseElevation + depth, 24); + const newElevation = `${this._elevationPrefix}${elevation}`; + const customElevation = Object.keys(this._classList).find(className => { + return className.startsWith(this._elevationPrefix); + }); if (!customElevation || customElevation === this._previousElevation) { if (this._previousElevation) { @@ -475,9 +495,6 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel this._directDescendantItems.notifyOnChanges(); }); } - - static ngAcceptInputType_overlapTrigger: BooleanInput; - static ngAcceptInputType_hasBackdrop: BooleanInput; } /** @docs-public MatMenu */ @@ -493,17 +510,18 @@ export class _MatMenuBase implements AfterContentInit, MatMenuPanel '[attr.aria-labelledby]': 'null', '[attr.aria-describedby]': 'null', }, - animations: [ - matMenuAnimations.transformMenu, - matMenuAnimations.fadeInItems - ], - providers: [ - {provide: MAT_MENU_PANEL, useExisting: MatMenu}, - ] + animations: [matMenuAnimations.transformMenu, matMenuAnimations.fadeInItems], + providers: [{provide: MAT_MENU_PANEL, useExisting: MatMenu}], }) export class MatMenu extends _MatMenuBase { - constructor(elementRef: ElementRef, ngZone: NgZone, - @Inject(MAT_MENU_DEFAULT_OPTIONS) defaultOptions: MatMenuDefaultOptions) { + protected override _elevationPrefix = 'mat-elevation-z'; + protected override _baseElevation = 4; + + constructor( + elementRef: ElementRef, + ngZone: NgZone, + @Inject(MAT_MENU_DEFAULT_OPTIONS) defaultOptions: MatMenuDefaultOptions, + ) { super(elementRef, ngZone, defaultOptions); } } diff --git a/src/material/menu/public-api.ts b/src/material/menu/public-api.ts index 1b18cfe39ff1..91803b62837c 100644 --- a/src/material/menu/public-api.ts +++ b/src/material/menu/public-api.ts @@ -6,14 +6,9 @@ * found in the LICENSE file at https://angular.io/license */ -export { - MatMenuDefaultOptions, - MAT_MENU_DEFAULT_OPTIONS, - MatMenu, - _MatMenuBase, -} from './menu'; +export {MatMenuDefaultOptions, MAT_MENU_DEFAULT_OPTIONS, MatMenu, _MatMenuBase} from './menu'; export {MatMenuItem} from './menu-item'; -export {MatMenuTrigger, MAT_MENU_SCROLL_STRATEGY} from './menu-trigger'; +export {MatMenuTrigger, MAT_MENU_SCROLL_STRATEGY, _MatMenuTriggerBase} from './menu-trigger'; export {MatMenuPanel, MAT_MENU_PANEL} from './menu-panel'; export * from './menu-module'; export * from './menu-animations'; diff --git a/src/material/menu/testing/BUILD.bazel b/src/material/menu/testing/BUILD.bazel index 3f91520e6701..51d7ab7768ab 100644 --- a/src/material/menu/testing/BUILD.bazel +++ b/src/material/menu/testing/BUILD.bazel @@ -8,7 +8,6 @@ ts_library( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material/menu/testing", deps = [ "//src/cdk/coercion", "//src/cdk/testing", diff --git a/src/material/menu/testing/menu-harness.ts b/src/material/menu/testing/menu-harness.ts index 978b3521278d..74b4f2f6e043 100644 --- a/src/material/menu/testing/menu-harness.ts +++ b/src/material/menu/testing/menu-harness.ts @@ -7,6 +7,9 @@ */ import { + BaseHarnessFilters, + ComponentHarness, + ComponentHarnessConstructor, ContentContainerComponentHarness, HarnessLoader, HarnessPredicate, @@ -16,27 +19,21 @@ import { import {coerceBooleanProperty} from '@angular/cdk/coercion'; import {MenuHarnessFilters, MenuItemHarnessFilters} from './menu-harness-filters'; -/** Harness for interacting with a standard mat-menu in tests. */ -export class MatMenuHarness extends ContentContainerComponentHarness { - /** The selector for the host element of a `MatMenu` instance. */ - static hostSelector = '.mat-menu-trigger'; - +export abstract class _MatMenuHarnessBase< + ItemType extends ComponentHarnessConstructor & { + with: (options?: ItemFilters) => HarnessPredicate; + }, + Item extends ComponentHarness & { + click(): Promise; + getSubmenu(): Promise<_MatMenuHarnessBase | null>; + }, + ItemFilters extends BaseHarnessFilters, +> extends ContentContainerComponentHarness { private _documentRootLocator = this.documentRootLocatorFactory(); + protected abstract _itemClass: ItemType; // TODO: potentially extend MatButtonHarness - /** - * Gets a `HarnessPredicate` that can be used to search for a `MatMenuHarness` that meets certain - * criteria. - * @param options Options for filtering which menu instances are considered a match. - * @return a `HarnessPredicate` configured with the given options. - */ - static with(options: MenuHarnessFilters = {}): HarnessPredicate { - return new HarnessPredicate(MatMenuHarness, options) - .addOption('triggerText', options.triggerText, - (harness, text) => HarnessPredicate.stringMatches(harness.getTriggerText(), text)); - } - /** Whether the menu is disabled. */ async isDisabled(): Promise { const disabled = (await this.host()).getAttribute('disabled'); @@ -70,7 +67,7 @@ export class MatMenuHarness extends ContentContainerComponentHarness { /** Opens the menu. */ async open(): Promise { - if (!await this.isOpen()) { + if (!(await this.isOpen())) { return (await this.host()).click(); } } @@ -87,12 +84,15 @@ export class MatMenuHarness extends ContentContainerComponentHarness { * Gets a list of `MatMenuItemHarness` representing the items in the menu. * @param filters Optionally filters which menu items are included. */ - async getItems(filters: Omit = {}): - Promise { + async getItems(filters?: Omit): Promise { const panelId = await this._getPanelId(); if (panelId) { return this._documentRootLocator.locatorForAll( - MatMenuItemHarness.with({...filters, ancestor: `#${panelId}`}))(); + this._itemClass.with({ + ...(filters || {}), + ancestor: `#${panelId}`, + } as ItemFilters), + )(); } return []; } @@ -106,8 +106,9 @@ export class MatMenuHarness extends ContentContainerComponentHarness { * `subItemFilters` will be clicked. */ async clickItem( - itemFilter: Omit, - ...subItemFilters: Omit[]): Promise { + itemFilter: Omit, + ...subItemFilters: Omit[] + ): Promise { await this.open(); const items = await this.getItems(itemFilter); if (!items.length) { @@ -122,10 +123,10 @@ export class MatMenuHarness extends ContentContainerComponentHarness { if (!menu) { throw Error(`Item matching ${JSON.stringify(itemFilter)} does not have a submenu`); } - return menu.clickItem(...subItemFilters as [Omit]); + return menu.clickItem(...(subItemFilters as [Omit])); } - protected async getRootHarnessLoader(): Promise { + protected override async getRootHarnessLoader(): Promise { const panelId = await this._getPanelId(); return this.documentRootLocatorFactory().harnessLoaderFor(`#${panelId}`); } @@ -143,25 +144,11 @@ export class MatMenuHarness extends ContentContainerComponentHarness { } } - -/** Harness for interacting with a standard mat-menu-item in tests. */ -export class MatMenuItemHarness extends ContentContainerComponentHarness { - /** The selector for the host element of a `MatMenuItem` instance. */ - static hostSelector = '.mat-menu-item'; - - /** - * Gets a `HarnessPredicate` that can be used to search for a `MatMenuItemHarness` that meets - * certain criteria. - * @param options Options for filtering which menu item instances are considered a match. - * @return a `HarnessPredicate` configured with the given options. - */ - static with(options: MenuItemHarnessFilters = {}): HarnessPredicate { - return new HarnessPredicate(MatMenuItemHarness, options) - .addOption('text', options.text, - (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text)) - .addOption('hasSubmenu', options.hasSubmenu, - async (harness, hasSubmenu) => (await harness.hasSubmenu()) === hasSubmenu); - } +export abstract class _MatMenuItemHarnessBase< + MenuType extends ComponentHarnessConstructor, + Menu extends ComponentHarness, +> extends ContentContainerComponentHarness { + protected abstract _menuClass: MenuType; /** Whether the menu is disabled. */ async isDisabled(): Promise { @@ -196,14 +183,67 @@ export class MatMenuItemHarness extends ContentContainerComponentHarness /** Whether this item has a submenu. */ async hasSubmenu(): Promise { - return (await this.host()).matchesSelector(MatMenuHarness.hostSelector); + return (await this.host()).matchesSelector(this._menuClass.hostSelector); } /** Gets the submenu associated with this menu item, or null if none. */ - async getSubmenu(): Promise { + async getSubmenu(): Promise { if (await this.hasSubmenu()) { - return new MatMenuHarness(this.locatorFactory); + return new this._menuClass(this.locatorFactory); } return null; } } + +/** Harness for interacting with a standard mat-menu in tests. */ +export class MatMenuHarness extends _MatMenuHarnessBase< + typeof MatMenuItemHarness, + MatMenuItemHarness, + MenuItemHarnessFilters +> { + /** The selector for the host element of a `MatMenu` instance. */ + static hostSelector = '.mat-menu-trigger'; + protected _itemClass = MatMenuItemHarness; + + /** + * Gets a `HarnessPredicate` that can be used to search for a `MatMenuHarness` that meets certain + * criteria. + * @param options Options for filtering which menu instances are considered a match. + * @return a `HarnessPredicate` configured with the given options. + */ + static with(options: MenuHarnessFilters = {}): HarnessPredicate { + return new HarnessPredicate(MatMenuHarness, options).addOption( + 'triggerText', + options.triggerText, + (harness, text) => HarnessPredicate.stringMatches(harness.getTriggerText(), text), + ); + } +} + +/** Harness for interacting with a standard mat-menu-item in tests. */ +export class MatMenuItemHarness extends _MatMenuItemHarnessBase< + typeof MatMenuHarness, + MatMenuHarness +> { + /** The selector for the host element of a `MatMenuItem` instance. */ + static hostSelector = '.mat-menu-item'; + protected _menuClass = MatMenuHarness; + + /** + * Gets a `HarnessPredicate` that can be used to search for a `MatMenuItemHarness` that meets + * certain criteria. + * @param options Options for filtering which menu item instances are considered a match. + * @return a `HarnessPredicate` configured with the given options. + */ + static with(options: MenuItemHarnessFilters = {}): HarnessPredicate { + return new HarnessPredicate(MatMenuItemHarness, options) + .addOption('text', options.text, (harness, text) => + HarnessPredicate.stringMatches(harness.getText(), text), + ) + .addOption( + 'hasSubmenu', + options.hasSubmenu, + async (harness, hasSubmenu) => (await harness.hasSubmenu()) === hasSubmenu, + ); + } +} diff --git a/src/material/menu/testing/shared.spec.ts b/src/material/menu/testing/shared.spec.ts index 9f1abfec1e7f..366b02feae89 100644 --- a/src/material/menu/testing/shared.spec.ts +++ b/src/material/menu/testing/shared.spec.ts @@ -1,17 +1,16 @@ -import {OverlayContainer} from '@angular/cdk/overlay'; import {HarnessLoader} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {Component} from '@angular/core'; -import {ComponentFixture, inject, TestBed} from '@angular/core/testing'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; import {MatMenuModule} from '@angular/material/menu'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {MatMenuHarness} from './menu-harness'; /** Shared tests to run on both the original and MDC-based menues. */ export function runHarnessTests( - menuModule: typeof MatMenuModule, menuHarness: typeof MatMenuHarness) { - let overlayContainer: OverlayContainer; - + menuModule: typeof MatMenuModule, + menuHarness: typeof MatMenuHarness, +) { describe('single-level menu', () => { let fixture: ComponentFixture; let loader: HarnessLoader; @@ -22,10 +21,6 @@ export function runHarnessTests( declarations: [MenuHarnessTest], }).compileComponents(); - inject([OverlayContainer], (oc: OverlayContainer) => { - overlayContainer = oc; - })(); - fixture = TestBed.createComponent(MenuHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); @@ -107,21 +102,11 @@ export function runHarnessTests( declarations: [NestedMenuHarnessTest], }).compileComponents(); - inject([OverlayContainer], (oc: OverlayContainer) => { - overlayContainer = oc; - })(); - fixture = TestBed.createComponent(NestedMenuHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); - afterEach(() => { - // Angular won't call this for us so we need to do it ourselves to avoid leaks. - overlayContainer.ngOnDestroy(); - overlayContainer = null!; - }); - it('should get submenus', async () => { const menu1 = await loader.getHarness(menuHarness.with({triggerText: 'Menu 1'})); @@ -155,7 +140,8 @@ export function runHarnessTests( it('should throw when item is not found', async () => { const menu1 = await loader.getHarness(menuHarness.with({triggerText: 'Menu 1'})); await expectAsync(menu1.clickItem({text: 'Fake Item'})).toBeRejectedWithError( - /Could not find item matching {"text":"Fake Item"}/); + /Could not find item matching {"text":"Fake Item"}/, + ); }); it('should select item in nested menu', async () => { @@ -167,7 +153,8 @@ export function runHarnessTests( it('should throw when intermediate item does not have submenu', async () => { const menu1 = await loader.getHarness(menuHarness.with({triggerText: 'Menu 1'})); await expectAsync(menu1.clickItem({text: 'Leaf Item 1'}, {})).toBeRejectedWithError( - /Item matching {"text":"Leaf Item 1"} does not have a submenu/); + /Item matching {"text":"Leaf Item 1"} does not have a submenu/, + ); }); }); } @@ -181,9 +168,9 @@ export function runHarnessTests( Profile Account - ` + `, }) -class MenuHarnessTest { } +class MenuHarnessTest {} @Component({ template: ` @@ -206,7 +193,7 @@ class MenuHarnessTest { } - ` + `, }) class NestedMenuHarnessTest { lastClickedLeaf = 0; diff --git a/src/material/package.json b/src/material/package.json index 297c92229400..49e931621e16 100644 --- a/src/material/package.json +++ b/src/material/package.json @@ -17,12 +17,39 @@ "url": "https://github.com/angular/components/issues" }, "homepage": "https://github.com/angular/components#readme", + "exports": { + ".": { + "sass": "./_index.scss" + }, + "./theming": { + "sass": "./_theming.scss" + }, + "./_theming": { + "sass": "./_theming.scss" + }, + "./prebuilt-themes/indigo-pink.css": { + "style": "./prebuilt-themes/indigo-pink.css" + }, + "./prebuilt-themes/deeppurple-amber.css": { + "style": "./prebuilt-themes/deeppurple-amber.css" + }, + "./prebuilt-themes/pink-bluegrey.css": { + "style": "./prebuilt-themes/pink-bluegrey.css" + }, + "./prebuilt-themes/purple-green.css": { + "style": "./prebuilt-themes/purple-green.css" + }, + "./prebuilt-themes/*": { + "style": "./prebuilt-themes/*.css" + } + }, "peerDependencies": { "@angular/animations": "0.0.0-NG", "@angular/cdk": "0.0.0-PLACEHOLDER", "@angular/core": "0.0.0-NG", "@angular/common": "0.0.0-NG", - "@angular/forms": "0.0.0-NG" + "@angular/forms": "0.0.0-NG", + "rxjs": "0.0.0-RXJS" }, "dependencies": { "tslib": "0.0.0-TSLIB" @@ -33,12 +60,11 @@ "packageGroup": [ "@angular/material", "@angular/cdk", - "@angular/material-moment-adapter" + "@angular/material-moment-adapter", + "@angular/material-luxon-adapter", + "@angular/material-date-fns-adapter" ] }, - "sideEffects": false, - "publishConfig":{ - "registry":"https://wombat-dressing-room.appspot.com" - } + "sideEffects": false } diff --git a/src/material/paginator/BUILD.bazel b/src/material/paginator/BUILD.bazel index 3e2e3b04a9b5..d7e0493b0345 100644 --- a/src/material/paginator/BUILD.bazel +++ b/src/material/paginator/BUILD.bazel @@ -17,7 +17,6 @@ ng_module( exclude = ["**/*.spec.ts"], ), assets = [":paginator.css"] + glob(["**/*.html"]), - module_name = "@angular/material/paginator", deps = [ "//src/cdk/coercion", "//src/material/button", @@ -42,6 +41,9 @@ sass_library( sass_binary( name = "paginator_scss", src = "paginator.scss", + deps = [ + "//src/cdk/a11y:a11y_scss_lib", + ], ) ng_test_library( diff --git a/src/material/paginator/_paginator-legacy-index.scss b/src/material/paginator/_paginator-legacy-index.scss new file mode 100644 index 000000000000..a1994c7a10f4 --- /dev/null +++ b/src/material/paginator/_paginator-legacy-index.scss @@ -0,0 +1,2 @@ +@forward 'paginator-variables' as mat-paginator-*; +@forward 'paginator-theme' as mat-paginator-*; diff --git a/src/material/paginator/_paginator-theme.import.scss b/src/material/paginator/_paginator-theme.import.scss new file mode 100644 index 000000000000..3bdfabf4fc91 --- /dev/null +++ b/src/material/paginator/_paginator-theme.import.scss @@ -0,0 +1,11 @@ +@forward '../core/theming/theming.import'; +@forward '../core/density/private/compatibility.import'; +@forward 'paginator-variables' as mat-paginator-*; +@forward '../core/typography/typography-utils.import'; +@forward 'paginator-theme' as mat-paginator-*; + +@import '../core/theming/palette'; +@import '../core/theming/theming'; +@import '../core/typography/typography-utils'; +@import '../core/density/private/compatibility'; +@import './paginator-variables'; diff --git a/src/material/paginator/_paginator-theme.scss b/src/material/paginator/_paginator-theme.scss index 8ca4570552d9..561ebd2cfcbd 100644 --- a/src/material/paginator/_paginator-theme.scss +++ b/src/material/paginator/_paginator-theme.scss @@ -1,32 +1,33 @@ -@import '../core/theming/palette'; -@import '../core/theming/theming'; -@import '../core/typography/typography-utils'; -@import '../core/density/private/compatibility'; -@import './paginator-variables'; +@use 'sass:map'; +@use '../core/theming/theming'; +@use '../core/typography/typography'; +@use '../core/typography/typography-utils'; +@use '../core/density/private/compatibility'; +@use './paginator-variables'; -@mixin mat-paginator-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $foreground: map-get($config, foreground); - $background: map-get($config, background); +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $foreground: map.get($config, foreground); + $background: map.get($config, background); .mat-paginator { - background: mat-color($background, 'card'); + background: theming.get-color-from-palette($background, 'card'); } .mat-paginator, .mat-paginator-page-size .mat-select-trigger { - color: mat-color($foreground, secondary-text); + color: theming.get-color-from-palette($foreground, secondary-text); } .mat-paginator-decrement, .mat-paginator-increment { - border-top: 2px solid mat-color($foreground, 'icon'); - border-right: 2px solid mat-color($foreground, 'icon'); + border-top: 2px solid theming.get-color-from-palette($foreground, 'icon'); + border-right: 2px solid theming.get-color-from-palette($foreground, 'icon'); } .mat-paginator-first, .mat-paginator-last { - border-top: 2px solid mat-color($foreground, 'icon'); + border-top: 2px solid theming.get-color-from-palette($foreground, 'icon'); } .mat-icon-button[disabled] { @@ -34,48 +35,50 @@ .mat-paginator-increment, .mat-paginator-first, .mat-paginator-last { - border-color: mat-color($foreground, 'disabled'); + border-color: theming.get-color-from-palette($foreground, 'disabled'); } } } -@mixin mat-paginator-typography($config-or-theme) { - $config: mat-get-typography-config($config-or-theme); +@mixin typography($config-or-theme) { + $config: typography.private-typography-to-2014-config( + theming.get-typography-config($config-or-theme)); .mat-paginator, .mat-paginator-page-size .mat-select-trigger { font: { - family: mat-font-family($config, caption); - size: mat-font-size($config, caption); + family: typography-utils.font-family($config, caption); + size: typography-utils.font-size($config, caption); } } } -@mixin mat-paginator-density($config-or-theme) { - $density-scale: mat-get-density-config($config-or-theme); - $height: mat-private-density-prop-value($mat-paginator-density-config, $density-scale, height); +@mixin density($config-or-theme) { + $density-scale: theming.get-density-config($config-or-theme); + $height: compatibility.private-density-prop-value(paginator-variables.$density-config, + $density-scale, height); - @include mat-private-density-legacy-compatibility() { + @include compatibility.private-density-legacy-compatibility() { .mat-paginator-container { min-height: $height; } } } -@mixin mat-paginator-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-paginator') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-paginator') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); @if $color != null { - @include mat-paginator-color($color); + @include color($color); } @if $density != null { - @include mat-paginator-density($density); + @include density($density); } @if $typography != null { - @include mat-paginator-typography($typography); + @include typography($typography); } } } diff --git a/src/material/paginator/_paginator-variables.import.scss b/src/material/paginator/_paginator-variables.import.scss new file mode 100644 index 000000000000..8db448343fec --- /dev/null +++ b/src/material/paginator/_paginator-variables.import.scss @@ -0,0 +1 @@ +@forward 'paginator-variables' as mat-paginator-*; diff --git a/src/material/paginator/_paginator-variables.scss b/src/material/paginator/_paginator-variables.scss index 1625dcc5eb33..0b41a650c2f0 100644 --- a/src/material/paginator/_paginator-variables.scss +++ b/src/material/paginator/_paginator-variables.scss @@ -1,13 +1,13 @@ -$mat-paginator-height: 56px !default; +$height: 56px !default; // Minimum height for paginator's in the highest density is determined based on how // much the paginator can shrink until the content exceeds (i.e. navigation buttons). -$mat-paginator-minimum-height: 40px !default; -$mat-paginator-maximum-height: $mat-paginator-height !default; +$minimum-height: 40px !default; +$maximum-height: $height !default; -$mat-paginator-density-config: ( +$density-config: ( height: ( - default: $mat-paginator-height, - maximum: $mat-paginator-maximum-height, - minimum: $mat-paginator-minimum-height, + default: $height, + maximum: $maximum-height, + minimum: $minimum-height, ) ) !default; diff --git a/src/material/paginator/paginator-intl.ts b/src/material/paginator/paginator-intl.ts index 68a4b9d2ce00..fa3136375325 100644 --- a/src/material/paginator/paginator-intl.ts +++ b/src/material/paginator/paginator-intl.ts @@ -9,7 +9,6 @@ import {Injectable, Optional, SkipSelf} from '@angular/core'; import {Subject} from 'rxjs'; - /** * To modify the labels and text displayed, create a new instance of MatPaginatorIntl and * include it in a custom provider @@ -38,21 +37,25 @@ export class MatPaginatorIntl { lastPageLabel: string = 'Last page'; /** A label for the range of items within the current page and the length of the whole list. */ - getRangeLabel: (page: number, pageSize: number, length: number) => string = - (page: number, pageSize: number, length: number) => { - if (length == 0 || pageSize == 0) { return `0 of ${length}`; } + getRangeLabel: (page: number, pageSize: number, length: number) => string = ( + page: number, + pageSize: number, + length: number, + ) => { + if (length == 0 || pageSize == 0) { + return `0 of ${length}`; + } - length = Math.max(length, 0); + length = Math.max(length, 0); - const startIndex = page * pageSize; + const startIndex = page * pageSize; - // If the start index exceeds the list length, do not try and fix the end index to the end. - const endIndex = startIndex < length ? - Math.min(startIndex + pageSize, length) : - startIndex + pageSize; + // If the start index exceeds the list length, do not try and fix the end index to the end. + const endIndex = + startIndex < length ? Math.min(startIndex + pageSize, length) : startIndex + pageSize; - return `${startIndex + 1} – ${endIndex} of ${length}`; - } + return `${startIndex + 1} – ${endIndex} of ${length}`; + }; } /** @docs-private */ @@ -65,5 +68,5 @@ export const MAT_PAGINATOR_INTL_PROVIDER = { // If there is already an MatPaginatorIntl available, use that. Otherwise, provide a new one. provide: MatPaginatorIntl, deps: [[new Optional(), new SkipSelf(), MatPaginatorIntl]], - useFactory: MAT_PAGINATOR_INTL_PROVIDER_FACTORY + useFactory: MAT_PAGINATOR_INTL_PROVIDER_FACTORY, }; diff --git a/src/material/paginator/paginator-module.ts b/src/material/paginator/paginator-module.ts index ccd5bf3cb265..4428ecbb4fa4 100644 --- a/src/material/paginator/paginator-module.ts +++ b/src/material/paginator/paginator-module.ts @@ -15,15 +15,8 @@ import {MatTooltipModule} from '@angular/material/tooltip'; import {MatPaginator} from './paginator'; import {MAT_PAGINATOR_INTL_PROVIDER} from './paginator-intl'; - @NgModule({ - imports: [ - CommonModule, - MatButtonModule, - MatSelectModule, - MatTooltipModule, - MatCommonModule, - ], + imports: [CommonModule, MatButtonModule, MatSelectModule, MatTooltipModule, MatCommonModule], exports: [MatPaginator], declarations: [MatPaginator], providers: [MAT_PAGINATOR_INTL_PROVIDER], diff --git a/src/material/paginator/paginator.md b/src/material/paginator/paginator.md index 4359b57dc7a1..e824c26d1679 100644 --- a/src/material/paginator/paginator.md +++ b/src/material/paginator/paginator.md @@ -26,4 +26,9 @@ This will allow you to change the following: 3. The tooltip messages on the navigation buttons. ### Accessibility -The `aria-label`s for next page, previous page, first page and last page buttons can be set in `MatPaginatorIntl`. +The paginator uses `role="group"` to semantically group its child controls. You must add an +`aria-label` or `aria-labelledby` attribute to `` with a label that describes +the content controlled by the pagination control. + +You can set the `aria-label` attributes for the button and select controls within the paginator in +`MatPaginatorIntl`. diff --git a/src/material/paginator/paginator.scss b/src/material/paginator/paginator.scss index f60a3bfff6c0..f007ac52639a 100644 --- a/src/material/paginator/paginator.scss +++ b/src/material/paginator/paginator.scss @@ -1,14 +1,16 @@ -$mat-paginator-padding: 0 8px; -$mat-paginator-page-size-margin-right: 8px; +@use '../../cdk/a11y'; -$mat-paginator-items-per-page-label-margin: 0 4px; -$mat-paginator-selector-margin: 6px 4px 0 4px; -$mat-paginator-selector-trigger-width: 56px; -$mat-paginator-selector-trigger-outline-width: 64px; -$mat-paginator-selector-trigger-fill-width: 64px; +$padding: 0 8px; +$page-size-margin-right: 8px; -$mat-paginator-range-label-margin: 0 32px 0 24px; -$mat-paginator-button-icon-size: 28px; +$items-per-page-label-margin: 0 4px; +$selector-margin: 6px 4px 0 4px; +$selector-trigger-width: 56px; +$selector-trigger-outline-width: 64px; +$selector-trigger-fill-width: 64px; + +$range-label-margin: 0 32px 0 24px; +$button-icon-size: 28px; .mat-paginator { display: block; @@ -24,7 +26,7 @@ $mat-paginator-button-icon-size: 28px; display: flex; align-items: center; justify-content: flex-end; - padding: $mat-paginator-padding; + padding: $padding; flex-wrap: wrap-reverse; width: 100%; } @@ -32,33 +34,33 @@ $mat-paginator-button-icon-size: 28px; .mat-paginator-page-size { display: flex; align-items: baseline; - margin-right: $mat-paginator-page-size-margin-right; + margin-right: $page-size-margin-right; [dir='rtl'] & { margin-right: 0; - margin-left: $mat-paginator-page-size-margin-right; + margin-left: $page-size-margin-right; } } .mat-paginator-page-size-label { - margin: $mat-paginator-items-per-page-label-margin; + margin: $items-per-page-label-margin; } .mat-paginator-page-size-select { - margin: $mat-paginator-selector-margin; - width: $mat-paginator-selector-trigger-width; + margin: $selector-margin; + width: $selector-trigger-width; &.mat-form-field-appearance-outline { - width: $mat-paginator-selector-trigger-outline-width; + width: $selector-trigger-outline-width; } &.mat-form-field-appearance-fill { - width: $mat-paginator-selector-trigger-fill-width; + width: $selector-trigger-fill-width; } } .mat-paginator-range-label { - margin: $mat-paginator-range-label-margin; + margin: $range-label-margin; } .mat-paginator-range-actions { @@ -67,10 +69,16 @@ $mat-paginator-button-icon-size: 28px; } .mat-paginator-icon { - width: $mat-paginator-button-icon-size; + width: $button-icon-size; fill: currentColor; [dir='rtl'] & { transform: rotate(180deg); } + + @include a11y.high-contrast(active, off) { + // On Chromium browsers the `currentColor` blends in with the + // background for SVGs so we have to fall back to `CanvasText`. + fill: CanvasText; + } } diff --git a/src/material/paginator/paginator.spec.ts b/src/material/paginator/paginator.spec.ts index dcef79b6c055..84bdb4e64b68 100644 --- a/src/material/paginator/paginator.spec.ts +++ b/src/material/paginator/paginator.spec.ts @@ -1,20 +1,19 @@ -import {ComponentFixture, TestBed, tick, fakeAsync} from '@angular/core/testing'; -import {Component, ViewChild, Type, Provider} from '@angular/core'; +import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; +import {Component, Provider, Type, ViewChild} from '@angular/core'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; -import {dispatchMouseEvent} from '@angular/cdk/testing/private'; +import {dispatchMouseEvent} from '../../cdk/testing/private'; import {ThemePalette} from '@angular/material/core'; import {MatSelect} from '@angular/material/select'; import {By} from '@angular/platform-browser'; -import {MatPaginatorModule, MatPaginator, MatPaginatorIntl} from './index'; +import {MatPaginator, MatPaginatorIntl, MatPaginatorModule} from './index'; import {MAT_PAGINATOR_DEFAULT_OPTIONS, MatPaginatorDefaultOptions} from './paginator'; - describe('MatPaginator', () => { function createComponent(type: Type, providers: Provider[] = []): ComponentFixture { TestBed.configureTestingModule({ imports: [MatPaginatorModule, NoopAnimationsModule], declarations: [type], - providers: [MatPaginatorIntl, ...providers] + providers: [MatPaginatorIntl, ...providers], }).compileComponents(); const fixture = TestBed.createComponent(type); @@ -23,52 +22,72 @@ describe('MatPaginator', () => { } describe('with the default internationalization provider', () => { - it('should show the right range text', () => { - const fixture = createComponent(MatPaginatorApp); - const component = fixture.componentInstance; - const rangeElement = fixture.nativeElement.querySelector('.mat-paginator-range-label'); - - // View second page of list of 100, each page contains 10 items. - component.length = 100; - component.pageSize = 10; - component.pageIndex = 1; - fixture.detectChanges(); - expect(rangeElement.innerText.trim()).toBe('11 – 20 of 100'); - - // View third page of list of 200, each page contains 20 items. - component.length = 200; - component.pageSize = 20; - component.pageIndex = 2; - fixture.detectChanges(); - expect(rangeElement.innerText.trim()).toBe('41 – 60 of 200'); - - // View first page of list of 0, each page contains 5 items. - component.length = 0; - component.pageSize = 5; - component.pageIndex = 2; - fixture.detectChanges(); - expect(rangeElement.innerText.trim()).toBe('0 of 0'); - - // View third page of list of 12, each page contains 5 items. - component.length = 12; - component.pageSize = 5; - component.pageIndex = 2; - fixture.detectChanges(); - expect(rangeElement.innerText.trim()).toBe('11 – 12 of 12'); - - // View third page of list of 10, each page contains 5 items. - component.length = 10; - component.pageSize = 5; - component.pageIndex = 2; - fixture.detectChanges(); - expect(rangeElement.innerText.trim()).toBe('11 – 15 of 10'); - - // View third page of list of -5, each page contains 5 items. - component.length = -5; - component.pageSize = 5; - component.pageIndex = 2; - fixture.detectChanges(); - expect(rangeElement.innerText.trim()).toBe('11 – 15 of 0'); + describe('showing the right range text', () => { + it('should show second page of list of 100, each page contains 10 items', () => { + const fixture = createComponent(MatPaginatorApp); + const component = fixture.componentInstance; + const rangeElement = fixture.nativeElement.querySelector('.mat-paginator-range-label'); + component.length = 100; + component.pageSize = 10; + component.pageIndex = 1; + fixture.detectChanges(); + expect(rangeElement.textContent!.trim()).toBe('11 – 20 of 100'); + }); + + it('should show third page of list of 200, each page contains 20 items', () => { + const fixture = createComponent(MatPaginatorApp); + const component = fixture.componentInstance; + const rangeElement = fixture.nativeElement.querySelector('.mat-paginator-range-label'); + component.length = 200; + component.pageSize = 20; + component.pageIndex = 2; + fixture.detectChanges(); + expect(rangeElement.textContent!.trim()).toBe('41 – 60 of 200'); + }); + + it('should show first page of list of 0, each page contains 5 items', () => { + const fixture = createComponent(MatPaginatorApp); + const component = fixture.componentInstance; + const rangeElement = fixture.nativeElement.querySelector('.mat-paginator-range-label'); + component.length = 0; + component.pageSize = 5; + component.pageIndex = 2; + fixture.detectChanges(); + expect(rangeElement.textContent!.trim()).toBe('0 of 0'); + }); + + it('should show third page of list of 12, each page contains 5 items', () => { + const fixture = createComponent(MatPaginatorApp); + const component = fixture.componentInstance; + const rangeElement = fixture.nativeElement.querySelector('.mat-paginator-range-label'); + component.length = 12; + component.pageSize = 5; + component.pageIndex = 2; + fixture.detectChanges(); + expect(rangeElement.textContent!.trim()).toBe('11 – 12 of 12'); + }); + + it('should show third page of list of 10, each page contains 5 items', () => { + const fixture = createComponent(MatPaginatorApp); + const component = fixture.componentInstance; + const rangeElement = fixture.nativeElement.querySelector('.mat-paginator-range-label'); + component.length = 10; + component.pageSize = 5; + component.pageIndex = 2; + fixture.detectChanges(); + expect(rangeElement.textContent!.trim()).toBe('11 – 15 of 10'); + }); + + it('should show third page of list of -5, each page contains 5 items', () => { + const fixture = createComponent(MatPaginatorApp); + const component = fixture.componentInstance; + const rangeElement = fixture.nativeElement.querySelector('.mat-paginator-range-label'); + component.length = -5; + component.pageSize = 5; + component.pageIndex = 2; + fixture.detectChanges(); + expect(rangeElement.textContent!.trim()).toBe('11 – 15 of 0'); + }); }); it('should show right aria-labels for select and buttons', () => { @@ -83,7 +102,7 @@ describe('MatPaginator', () => { it('should re-render when the i18n labels change', () => { const fixture = createComponent(MatPaginatorApp); const label = fixture.nativeElement.querySelector('.mat-paginator-page-size-label'); - const intl = TestBed.get(MatPaginatorIntl); + const intl = TestBed.inject(MatPaginatorIntl); intl.itemsPerPageLabel = '1337 items per page'; intl.changes.next(); @@ -103,10 +122,12 @@ describe('MatPaginator', () => { dispatchMouseEvent(getNextButton(fixture), 'click'); expect(paginator.pageIndex).toBe(1); - expect(component.pageEvent).toHaveBeenCalledWith(jasmine.objectContaining({ - previousPageIndex: 0, - pageIndex: 1 - })); + expect(component.pageEvent).toHaveBeenCalledWith( + jasmine.objectContaining({ + previousPageIndex: 0, + pageIndex: 1, + }), + ); }); it('should be able to go to the previous page', () => { @@ -120,29 +141,29 @@ describe('MatPaginator', () => { dispatchMouseEvent(getPreviousButton(fixture), 'click'); expect(paginator.pageIndex).toBe(0); - expect(component.pageEvent).toHaveBeenCalledWith(jasmine.objectContaining({ - previousPageIndex: 1, - pageIndex: 0 - })); + expect(component.pageEvent).toHaveBeenCalledWith( + jasmine.objectContaining({ + previousPageIndex: 1, + pageIndex: 0, + }), + ); }); }); it('should be able to show the first/last buttons', () => { const fixture = createComponent(MatPaginatorApp); - expect(getFirstButton(fixture)) - .toBeNull('Expected first button to not exist.'); + expect(getFirstButton(fixture)).withContext('Expected first button to not exist.').toBeNull(); - expect(getLastButton(fixture)) - .toBeNull('Expected last button to not exist.'); + expect(getLastButton(fixture)).withContext('Expected last button to not exist.').toBeNull(); fixture.componentInstance.showFirstLastButtons = true; fixture.detectChanges(); expect(getFirstButton(fixture)) - .toBeTruthy('Expected first button to be rendered.'); + .withContext('Expected first button to be rendered.') + .toBeTruthy(); - expect(getLastButton(fixture)) - .toBeTruthy('Expected last button to be rendered.'); + expect(getLastButton(fixture)).withContext('Expected last button to be rendered.').toBeTruthy(); }); it('should mark itself as initialized', fakeAsync(() => { @@ -150,7 +171,7 @@ describe('MatPaginator', () => { const component = fixture.componentInstance; const paginator = component.paginator; let isMarkedInitialized = false; - paginator.initialized.subscribe(() => isMarkedInitialized = true); + paginator.initialized.subscribe(() => (isMarkedInitialized = true)); tick(); expect(isMarkedInitialized).toBeTruthy(); @@ -213,10 +234,12 @@ describe('MatPaginator', () => { dispatchMouseEvent(getLastButton(fixture), 'click'); expect(paginator.pageIndex).toBe(9); - expect(component.pageEvent).toHaveBeenCalledWith(jasmine.objectContaining({ - previousPageIndex: 0, - pageIndex: 9 - })); + expect(component.pageEvent).toHaveBeenCalledWith( + jasmine.objectContaining({ + previousPageIndex: 0, + pageIndex: 9, + }), + ); }); it('should be able to go to the first page via the first page button', () => { @@ -227,10 +250,12 @@ describe('MatPaginator', () => { dispatchMouseEvent(getFirstButton(fixture), 'click'); expect(paginator.pageIndex).toBe(0); - expect(component.pageEvent).toHaveBeenCalledWith(jasmine.objectContaining({ - previousPageIndex: 3, - pageIndex: 0 - })); + expect(component.pageEvent).toHaveBeenCalledWith( + jasmine.objectContaining({ + previousPageIndex: 3, + pageIndex: 0, + }), + ); }); it('should disable navigating to the next page if at last page', () => { @@ -256,7 +281,6 @@ describe('MatPaginator', () => { expect(component.pageEvent).not.toHaveBeenCalled(); expect(paginator.pageIndex).toBe(0); }); - }); it('should mark for check when inputs are changed directly', () => { @@ -336,30 +360,36 @@ describe('MatPaginator', () => { component.pageEvent.calls.reset(); paginator._changePageSize(25); - expect(component.pageEvent).toHaveBeenCalledWith(jasmine.objectContaining({ - pageIndex: 1, - pageSize: 25 - })); + expect(component.pageEvent).toHaveBeenCalledWith( + jasmine.objectContaining({ + pageIndex: 1, + pageSize: 25, + }), + ); // The first item on the page is still 25. Change the page size to 8 so that we should now be // on the fourth page where the top item is index 24. component.pageEvent.calls.reset(); paginator._changePageSize(8); - expect(component.pageEvent).toHaveBeenCalledWith(jasmine.objectContaining({ - pageIndex: 3, - pageSize: 8 - })); + expect(component.pageEvent).toHaveBeenCalledWith( + jasmine.objectContaining({ + pageIndex: 3, + pageSize: 8, + }), + ); // The first item on the page is 24. Change the page size to 16 so that we should now be // on the first page where the top item is index 0. component.pageEvent.calls.reset(); paginator._changePageSize(25); - expect(component.pageEvent).toHaveBeenCalledWith(jasmine.objectContaining({ - pageIndex: 0, - pageSize: 25 - })); + expect(component.pageEvent).toHaveBeenCalledWith( + jasmine.objectContaining({ + pageIndex: 0, + pageSize: 25, + }), + ); }); it('should keep track of the right number of pages', () => { @@ -414,19 +444,22 @@ describe('MatPaginator', () => { const element = fixture.nativeElement; expect(element.querySelector('.mat-paginator-page-size')) - .toBeTruthy('Expected select to be rendered.'); + .withContext('Expected select to be rendered.') + .toBeTruthy(); fixture.componentInstance.hidePageSize = true; fixture.detectChanges(); expect(element.querySelector('.mat-paginator-page-size')) - .toBeNull('Expected select to be removed.'); + .withContext('Expected select to be removed.') + .toBeNull(); }); it('should be able to disable all the controls in the paginator via the binding', () => { const fixture = createComponent(MatPaginatorApp); - const select: MatSelect = - fixture.debugElement.query(By.directive(MatSelect))!.componentInstance; + const select: MatSelect = fixture.debugElement.query( + By.directive(MatSelect), + )!.componentInstance; fixture.componentInstance.pageIndex = 1; fixture.componentInstance.showFirstLastButtons = true; @@ -448,17 +481,18 @@ describe('MatPaginator', () => { expect(getLastButton(fixture).hasAttribute('disabled')).toBe(true); }); - it('should be able to configure the default options via a provider', () => { - const fixture = createComponent(MatPaginatorWithoutInputsApp, [{ - provide: MAT_PAGINATOR_DEFAULT_OPTIONS, - useValue: { - pageSize: 7, - pageSizeOptions: [7, 14, 21], - hidePageSize: true, - showFirstLastButtons: true - } as MatPaginatorDefaultOptions - }]); + const fixture = createComponent(MatPaginatorWithoutInputsApp, [ + { + provide: MAT_PAGINATOR_DEFAULT_OPTIONS, + useValue: { + pageSize: 7, + pageSizeOptions: [7, 14, 21], + hidePageSize: true, + showFirstLastButtons: true, + } as MatPaginatorDefaultOptions, + }, + ]); const paginator = fixture.componentInstance.paginator; expect(paginator.pageSize).toBe(7); @@ -467,6 +501,11 @@ describe('MatPaginator', () => { expect(paginator.showFirstLastButtons).toBe(true); }); + it('should set `role="group"` on the host element', () => { + const fixture = createComponent(MatPaginatorApp); + const hostElement = fixture.nativeElement.querySelector('mat-paginator'); + expect(hostElement.getAttribute('role')).toBe('group'); + }); }); function getPreviousButton(fixture: ComponentFixture) { @@ -551,8 +590,8 @@ class MatPaginatorWithoutOptionsApp { [pageSizeOptions]="['5', '10', '25', '100']" length="100"> - ` - }) + `, +}) class MatPaginatorWithStringValues { @ViewChild(MatPaginator) paginator: MatPaginator; } diff --git a/src/material/paginator/paginator.ts b/src/material/paginator/paginator.ts index 1dbab2c2a19f..894fcbb6ee37 100644 --- a/src/material/paginator/paginator.ts +++ b/src/material/paginator/paginator.ts @@ -10,7 +10,7 @@ import { coerceNumberProperty, coerceBooleanProperty, BooleanInput, - NumberInput + NumberInput, } from '@angular/cdk/coercion'; import { ChangeDetectionStrategy, @@ -31,11 +31,9 @@ import {Subscription} from 'rxjs'; import {MatPaginatorIntl} from './paginator-intl'; import { HasInitialized, - HasInitializedCtor, mixinInitialized, ThemePalette, mixinDisabled, - CanDisableCtor, CanDisable, } from '@angular/material/core'; import {MatFormFieldAppearance} from '@angular/material/form-field'; @@ -64,7 +62,6 @@ export class PageEvent { length: number; } - /** Object that can be used to configure the default options for the paginator module. */ export interface MatPaginatorDefaultOptions { /** Number of items to display on a page. By default set to 50. */ @@ -84,27 +81,30 @@ export interface MatPaginatorDefaultOptions { } /** Injection token that can be used to provide the default options for the paginator module. */ -export const MAT_PAGINATOR_DEFAULT_OPTIONS = - new InjectionToken('MAT_PAGINATOR_DEFAULT_OPTIONS'); +export const MAT_PAGINATOR_DEFAULT_OPTIONS = new InjectionToken( + 'MAT_PAGINATOR_DEFAULT_OPTIONS', +); // Boilerplate for applying mixins to _MatPaginatorBase. /** @docs-private */ -class MatPaginatorMixinBase {} -const _MatPaginatorMixinBase: CanDisableCtor & HasInitializedCtor & typeof MatPaginatorMixinBase = - mixinDisabled(mixinInitialized(MatPaginatorMixinBase)); +const _MatPaginatorMixinBase = mixinDisabled(mixinInitialized(class {})); /** * Base class with all of the `MatPaginator` functionality. * @docs-private */ @Directive() -export abstract class _MatPaginatorBase extends _MatPaginatorMixinBase implements OnInit, OnDestroy, - CanDisable, HasInitialized { +export abstract class _MatPaginatorBase< + O extends { + pageSize?: number; + pageSizeOptions?: number[]; + hidePageSize?: boolean; + showFirstLastButtons?: boolean; + }, + > + extends _MatPaginatorMixinBase + implements OnInit, OnDestroy, CanDisable, HasInitialized +{ private _initialized: boolean; private _intlChanges: Subscription; @@ -113,8 +113,10 @@ export abstract class _MatPaginatorBase coerceNumberProperty(p)); this._updateDisplayedPageSizeOptions(); @@ -149,17 +157,20 @@ export abstract class _MatPaginatorBase this._changeDetectorRef.markForCheck()); if (defaults) { - const { - pageSize, - pageSizeOptions, - hidePageSize, - showFirstLastButtons, - } = defaults; + const {pageSize, pageSizeOptions, hidePageSize, showFirstLastButtons} = defaults; if (pageSize != null) { this._pageSize = pageSize; @@ -214,26 +222,32 @@ export abstract class _MatPaginatorBase /** If set, styles the "page size" form field with the designated style. */ _formFieldAppearance?: MatFormFieldAppearance; - constructor(intl: MatPaginatorIntl, + constructor( + intl: MatPaginatorIntl, changeDetectorRef: ChangeDetectorRef, - @Optional() @Inject(MAT_PAGINATOR_DEFAULT_OPTIONS) defaults?: MatPaginatorDefaultOptions) { + @Optional() @Inject(MAT_PAGINATOR_DEFAULT_OPTIONS) defaults?: MatPaginatorDefaultOptions, + ) { super(intl, changeDetectorRef, defaults); if (defaults && defaults.formFieldAppearance != null) { diff --git a/src/material/paginator/public-api.ts b/src/material/paginator/public-api.ts index 78f1e9a6b329..6de0c623f876 100644 --- a/src/material/paginator/public-api.ts +++ b/src/material/paginator/public-api.ts @@ -9,4 +9,3 @@ export * from './paginator-module'; export * from './paginator'; export * from './paginator-intl'; - diff --git a/src/material/paginator/testing/BUILD.bazel b/src/material/paginator/testing/BUILD.bazel index 79a99f1d97e4..6da51f668753 100644 --- a/src/material/paginator/testing/BUILD.bazel +++ b/src/material/paginator/testing/BUILD.bazel @@ -8,7 +8,6 @@ ts_library( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material/paginator/testing", deps = [ "//src/cdk/coercion", "//src/cdk/testing", diff --git a/src/material/paginator/testing/paginator-harness-filters.ts b/src/material/paginator/testing/paginator-harness-filters.ts index 6d5ad9dcdb7a..18fe1edea09c 100644 --- a/src/material/paginator/testing/paginator-harness-filters.ts +++ b/src/material/paginator/testing/paginator-harness-filters.ts @@ -9,5 +9,4 @@ import {BaseHarnessFilters} from '@angular/cdk/testing'; /** A set of criteria that can be used to filter a list of `MatPaginatorHarness` instances. */ -export interface PaginatorHarnessFilters extends BaseHarnessFilters { -} +export interface PaginatorHarnessFilters extends BaseHarnessFilters {} diff --git a/src/material/paginator/testing/paginator-harness.ts b/src/material/paginator/testing/paginator-harness.ts index ff68876b8848..9e641bf93c81 100644 --- a/src/material/paginator/testing/paginator-harness.ts +++ b/src/material/paginator/testing/paginator-harness.ts @@ -6,35 +6,30 @@ * found in the LICENSE file at https://angular.io/license */ -import {ComponentHarness, HarnessPredicate} from '@angular/cdk/testing'; +import { + AsyncFactoryFn, + ComponentHarness, + HarnessPredicate, + TestElement, +} from '@angular/cdk/testing'; import {MatSelectHarness} from '@angular/material/select/testing'; import {coerceNumberProperty} from '@angular/cdk/coercion'; import {PaginatorHarnessFilters} from './paginator-harness-filters'; - -/** Harness for interacting with a standard mat-paginator in tests. */ -export class MatPaginatorHarness extends ComponentHarness { - /** Selector used to find paginator instances. */ - static hostSelector = '.mat-paginator'; - private _nextButton = this.locatorFor('.mat-paginator-navigation-next'); - private _previousButton = this.locatorFor('.mat-paginator-navigation-previous'); - private _firstPageButton = this.locatorForOptional('.mat-paginator-navigation-first'); - private _lastPageButton = this.locatorForOptional('.mat-paginator-navigation-last'); - private _select = this.locatorForOptional(MatSelectHarness.with({ - ancestor: '.mat-paginator-page-size' - })); - private _pageSizeFallback = this.locatorFor('.mat-paginator-page-size-value'); - private _rangeLabel = this.locatorFor('.mat-paginator-range-label'); - - /** - * Gets a `HarnessPredicate` that can be used to search for a `MatPaginatorHarness` that meets - * certain criteria. - * @param options Options for filtering which paginator instances are considered a match. - * @return a `HarnessPredicate` configured with the given options. - */ - static with(options: PaginatorHarnessFilters = {}): HarnessPredicate { - return new HarnessPredicate(MatPaginatorHarness, options); - } +export abstract class _MatPaginatorHarnessBase extends ComponentHarness { + protected abstract _nextButton: AsyncFactoryFn; + protected abstract _previousButton: AsyncFactoryFn; + protected abstract _firstPageButton: AsyncFactoryFn; + protected abstract _lastPageButton: AsyncFactoryFn; + protected abstract _select: AsyncFactoryFn< + | (ComponentHarness & { + getValueText(): Promise; + clickOptions(...filters: unknown[]): Promise; + }) + | null + >; + protected abstract _pageSizeFallback: AsyncFactoryFn; + protected abstract _rangeLabel: AsyncFactoryFn; /** Goes to the next page in the paginator. */ async goToNextPage(): Promise { @@ -52,8 +47,10 @@ export class MatPaginatorHarness extends ComponentHarness { // The first page button isn't enabled by default so we need to check for it. if (!button) { - throw Error('Could not find first page button inside paginator. ' + - 'Make sure that `showFirstLastButtons` is enabled.'); + throw Error( + 'Could not find first page button inside paginator. ' + + 'Make sure that `showFirstLastButtons` is enabled.', + ); } return button.click(); @@ -65,8 +62,10 @@ export class MatPaginatorHarness extends ComponentHarness { // The last page button isn't enabled by default so we need to check for it. if (!button) { - throw Error('Could not find last page button inside paginator. ' + - 'Make sure that `showFirstLastButtons` is enabled.'); + throw Error( + 'Could not find last page button inside paginator. ' + + 'Make sure that `showFirstLastButtons` is enabled.', + ); } return button.click(); @@ -82,8 +81,10 @@ export class MatPaginatorHarness extends ComponentHarness { // The select is only available if the `pageSizeOptions` are // set to an array with more than one item. if (!select) { - throw Error('Cannot find page size selector in paginator. ' + - 'Make sure that the `pageSizeOptions` have been configured.'); + throw Error( + 'Cannot find page size selector in paginator. ' + + 'Make sure that the `pageSizeOptions` have been configured.', + ); } return select.clickOptions({text: `${size}`}); @@ -101,3 +102,30 @@ export class MatPaginatorHarness extends ComponentHarness { return (await this._rangeLabel()).text(); } } + +/** Harness for interacting with a standard mat-paginator in tests. */ +export class MatPaginatorHarness extends _MatPaginatorHarnessBase { + /** Selector used to find paginator instances. */ + static hostSelector = '.mat-paginator'; + protected _nextButton = this.locatorFor('.mat-paginator-navigation-next'); + protected _previousButton = this.locatorFor('.mat-paginator-navigation-previous'); + protected _firstPageButton = this.locatorForOptional('.mat-paginator-navigation-first'); + protected _lastPageButton = this.locatorForOptional('.mat-paginator-navigation-last'); + protected _select = this.locatorForOptional( + MatSelectHarness.with({ + ancestor: '.mat-paginator-page-size', + }), + ); + protected _pageSizeFallback = this.locatorFor('.mat-paginator-page-size-value'); + protected _rangeLabel = this.locatorFor('.mat-paginator-range-label'); + + /** + * Gets a `HarnessPredicate` that can be used to search for a `MatPaginatorHarness` that meets + * certain criteria. + * @param options Options for filtering which paginator instances are considered a match. + * @return a `HarnessPredicate` configured with the given options. + */ + static with(options: PaginatorHarnessFilters = {}): HarnessPredicate { + return new HarnessPredicate(MatPaginatorHarness, options); + } +} diff --git a/src/material/paginator/testing/shared.spec.ts b/src/material/paginator/testing/shared.spec.ts index 31c8fb504088..626f97a7255e 100644 --- a/src/material/paginator/testing/shared.spec.ts +++ b/src/material/paginator/testing/shared.spec.ts @@ -8,7 +8,9 @@ import {MatPaginatorHarness} from './paginator-harness'; /** Shared tests to run on both the original and MDC-based paginator. */ export function runHarnessTests( - paginatorModule: typeof MatPaginatorModule, paginatorHarness: typeof MatPaginatorHarness) { + paginatorModule: typeof MatPaginatorModule, + paginatorHarness: typeof MatPaginatorHarness, +) { let fixture: ComponentFixture; let loader: HarnessLoader; let instance: PaginatorHarnessTest; @@ -91,7 +93,8 @@ export function runHarnessTests( fixture.detectChanges(); await expectAsync(paginator.goToFirstPage()).toBeRejectedWithError( - /Could not find first page button inside paginator/); + /Could not find first page button inside paginator/, + ); }); it('should throw an error if the last page button is not available', async () => { @@ -101,7 +104,8 @@ export function runHarnessTests( fixture.detectChanges(); await expectAsync(paginator.goToLastPage()).toBeRejectedWithError( - /Could not find last page button inside paginator/); + /Could not find last page button inside paginator/, + ); }); it('should throw an error if the page size selector is not available', async () => { @@ -111,7 +115,8 @@ export function runHarnessTests( fixture.detectChanges(); await expectAsync(paginator.setPageSize(10)).toBeRejectedWithError( - /Cannot find page size selector in paginator/); + /Cannot find page size selector in paginator/, + ); }); } @@ -125,7 +130,7 @@ export function runHarnessTests( [pageSizeOptions]="pageSizeOptions" [pageIndex]="pageIndex"> - ` + `, }) class PaginatorHarnessTest { length = 500; @@ -140,4 +145,3 @@ class PaginatorHarnessTest { this.pageIndex = event.pageIndex; } } - diff --git a/src/material/prebuilt-themes/BUILD.bazel b/src/material/prebuilt-themes/BUILD.bazel index 501d69e7af9a..d6dda6de86c3 100644 --- a/src/material/prebuilt-themes/BUILD.bazel +++ b/src/material/prebuilt-themes/BUILD.bazel @@ -4,6 +4,9 @@ package(default_visibility = ["//visibility:public"]) # package in the right spot. The *right* thing to do would be to move them, but # we would need to update references for Google apps. +## **NOTE**: When adding/removing prebuilt themes from here, make sure to update +# the `material/package.json` exports field. + genrule( name = "indigo-pink", srcs = ["//src/material/core:theming/prebuilt/indigo-pink.css"], diff --git a/src/material/progress-bar/BUILD.bazel b/src/material/progress-bar/BUILD.bazel index f8bc5021a402..7c08ea2337e3 100644 --- a/src/material/progress-bar/BUILD.bazel +++ b/src/material/progress-bar/BUILD.bazel @@ -19,7 +19,6 @@ ng_module( exclude = ["**/*.spec.ts"], ), assets = [":progress-bar.css"] + glob(["**/*.html"]), - module_name = "@angular/material/progress-bar", deps = [ "//src/material/core", "@npm//@angular/animations", diff --git a/src/material/progress-bar/_progress-bar-legacy-index.scss b/src/material/progress-bar/_progress-bar-legacy-index.scss new file mode 100644 index 000000000000..34a313f57369 --- /dev/null +++ b/src/material/progress-bar/_progress-bar-legacy-index.scss @@ -0,0 +1,2 @@ +@forward 'progress-bar-theme' hide color, theme, typography; +@forward 'progress-bar-theme' as mat-progress-bar-* hide mat-progress-bar-density; diff --git a/src/material/progress-bar/_progress-bar-theme.import.scss b/src/material/progress-bar/_progress-bar-theme.import.scss new file mode 100644 index 000000000000..7fe2df21b04e --- /dev/null +++ b/src/material/progress-bar/_progress-bar-theme.import.scss @@ -0,0 +1,6 @@ +@forward '../core/theming/theming.import'; +@forward 'progress-bar-theme' hide color, theme, typography; +@forward 'progress-bar-theme' as mat-progress-bar-* hide mat-progress-bar-density; + +@import '../core/theming/palette'; +@import '../core/theming/theming'; diff --git a/src/material/progress-bar/_progress-bar-theme.scss b/src/material/progress-bar/_progress-bar-theme.scss index 9b1c3ff854ab..356ff8639a10 100644 --- a/src/material/progress-bar/_progress-bar-theme.scss +++ b/src/material/progress-bar/_progress-bar-theme.scss @@ -1,72 +1,86 @@ -@import '../core/theming/palette'; -@import '../core/theming/theming'; +@use 'sass:map'; +@use 'sass:meta'; +@use 'sass:color'; +@use '../core/theming/theming'; -@mixin mat-progress-bar-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $primary: map-get($config, primary); - $accent: map-get($config, accent); - $warn: map-get($config, warn); +// Approximates the correct buffer color by using a mix between the theme color +// and the theme's background color. +@function _get-buffer-color($theme, $background) { + $theme-color: theming.get-color-from-palette($theme); + // Return fallback color if the theme uses variables to define colors. + @if (meta.type-of($theme-color) != 'color' or meta.type-of($background) != 'color') { + @return theming.get-color-from-palette($theme, lighter); + } + @return color.mix($theme-color, $background, $weight: 25%); +} + +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $primary: map.get($config, primary); + $accent: map.get($config, accent); + $warn: map.get($config, warn); + $background: map.get(map.get($config, background), background); .mat-progress-bar-background { - fill: mat-color($primary, lighter); + fill: _get-buffer-color($primary, $background); } .mat-progress-bar-buffer { - background-color: mat-color($primary, lighter); + background-color: _get-buffer-color($primary, $background); } .mat-progress-bar-fill::after { - background-color: mat-color($primary); + background-color: theming.get-color-from-palette($primary); } .mat-progress-bar.mat-accent { .mat-progress-bar-background { - fill: mat-color($accent, lighter); + fill: _get-buffer-color($accent, $background); } .mat-progress-bar-buffer { - background-color: mat-color($accent, lighter); + background-color: _get-buffer-color($accent, $background); } .mat-progress-bar-fill::after { - background-color: mat-color($accent); + background-color: theming.get-color-from-palette($accent); } } .mat-progress-bar.mat-warn { .mat-progress-bar-background { - fill: mat-color($warn, lighter); + fill: _get-buffer-color($warn, $background); } .mat-progress-bar-buffer { - background-color: mat-color($warn, lighter); + background-color: _get-buffer-color($warn, $background); } .mat-progress-bar-fill::after { - background-color: mat-color($warn); + background-color: theming.get-color-from-palette($warn); } } } -@mixin mat-progress-bar-typography($config-or-theme) {} +@mixin typography($config-or-theme) {} -@mixin _mat-progress-bar-density($config-or-theme) {} +@mixin _density($config-or-theme) {} -@mixin mat-progress-bar-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-progress-bar') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-progress-bar') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); @if $color != null { - @include mat-progress-bar-color($color); + @include color($color); } @if $density != null { - @include _mat-progress-bar-density($density); + @include _density($density); } @if $typography != null { - @include mat-progress-bar-typography($typography); + @include typography($typography); } } } diff --git a/src/material/progress-bar/progress-bar-module.ts b/src/material/progress-bar/progress-bar-module.ts index 5295cc84f591..9b9461cd7a29 100644 --- a/src/material/progress-bar/progress-bar-module.ts +++ b/src/material/progress-bar/progress-bar-module.ts @@ -11,7 +11,6 @@ import {CommonModule} from '@angular/common'; import {MatCommonModule} from '@angular/material/core'; import {MatProgressBar} from './progress-bar'; - @NgModule({ imports: [CommonModule, MatCommonModule], exports: [MatProgressBar, MatCommonModule], diff --git a/src/material/progress-bar/progress-bar.e2e.spec.ts b/src/material/progress-bar/progress-bar.e2e.spec.ts index 9ef964f6a077..518df86e6628 100644 --- a/src/material/progress-bar/progress-bar.e2e.spec.ts +++ b/src/material/progress-bar/progress-bar.e2e.spec.ts @@ -1,5 +1,5 @@ import {browser} from 'protractor'; -import {expectToExist} from '@angular/cdk/testing/private/e2e'; +import {expectToExist} from '../../cdk/testing/private/e2e'; describe('progress-bar', () => { beforeEach(async () => await browser.get('/progress-bar')); diff --git a/src/material/progress-bar/progress-bar.html b/src/material/progress-bar/progress-bar.html index 8d394133c4b3..c546ed2712f8 100644 --- a/src/material/progress-bar/progress-bar.html +++ b/src/material/progress-bar/progress-bar.html @@ -1,15 +1,21 @@ - - - - - - - - -
-
-
+ diff --git a/src/material/progress-bar/progress-bar.md b/src/material/progress-bar/progress-bar.md index 096747473063..3a909d265521 100644 --- a/src/material/progress-bar/progress-bar.md +++ b/src/material/progress-bar/progress-bar.md @@ -42,4 +42,9 @@ The color of a progress-bar can be changed by using the `color` property. By def use the theme's primary color. This can be changed to `'accent'` or `'warn'`. ### Accessibility -Each progress bar should be given a meaningful label via `aria-label` or `aria-labelledby`. + +`MatProgressBar` implements the ARIA `role="progressbar"` pattern. By default, the progress bar +sets `aria-valuemin` to `0` and `aria-valuemax` to `100`. Avoid changing these values, as this may +cause incompatiblity with some assitive technology. + +Always provide an accessible label via `aria-label` or `aria-labelledby` for each progress bar. diff --git a/src/material/progress-bar/progress-bar.scss b/src/material/progress-bar/progress-bar.scss index 43fc8af8077e..1b109cce480f 100644 --- a/src/material/progress-bar/progress-bar.scss +++ b/src/material/progress-bar/progress-bar.scss @@ -1,21 +1,20 @@ -@import '../core/style/variables'; -@import '../core/style/vendor-prefixes'; -@import '../core/style/private'; -@import '../../cdk/a11y/a11y'; +@use '../core/style/vendor-prefixes'; +@use '../core/style/private'; +@use '../../cdk/a11y'; -$mat-progress-bar-height: 4px !default; -$mat-progress-bar-full-animation-duration: 2000ms !default; -$mat-progress-bar-piece-animation-duration: 250ms !default; +$height: 4px !default; +$full-animation-duration: 2000ms !default; +$piece-animation-duration: 250ms !default; .mat-progress-bar { - @include mat-private-animation-noop(); + @include private.private-animation-noop(); display: block; // Height is provided for mat-progress-bar to act as a default. - height: $mat-progress-bar-height; + height: $height; overflow: hidden; position: relative; - transition: opacity $mat-progress-bar-piece-animation-duration linear; + transition: opacity $piece-animation-duration linear; width: 100%; // Base styles that are re-used across all of the progress bar children. @@ -32,7 +31,7 @@ $mat-progress-bar-piece-animation-duration: 250ms !default; // during the background scroll animation. width: calc(100% + 10px); - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { display: none; } } @@ -41,9 +40,9 @@ $mat-progress-bar-piece-animation-duration: 250ms !default; // beyond the current value of the primary progress bar. .mat-progress-bar-buffer { transform-origin: top left; - transition: transform $mat-progress-bar-piece-animation-duration ease; + transition: transform $piece-animation-duration ease; - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { border-top: solid 5px; opacity: 0.5; } @@ -59,10 +58,10 @@ $mat-progress-bar-piece-animation-duration: 250ms !default; .mat-progress-bar-fill { animation: none; transform-origin: top left; - transition: transform $mat-progress-bar-piece-animation-duration ease; + transition: transform $piece-animation-duration ease; - @include cdk-high-contrast(active, off) { - border-top: solid $mat-progress-bar-height; + @include a11y.high-contrast(active, off) { + border-top: solid $height; } } @@ -96,39 +95,39 @@ $mat-progress-bar-piece-animation-duration: 250ms !default; } .mat-progress-bar-primary { // Avoids stacked animation tearing in Firefox >= 57. - @include backface-visibility(hidden); + @include vendor-prefixes.backface-visibility(hidden); animation: mat-progress-bar-primary-indeterminate-translate - $mat-progress-bar-full-animation-duration infinite linear; + $full-animation-duration infinite linear; left: -145.166611%; } .mat-progress-bar-primary.mat-progress-bar-fill::after { // Avoids stacked animation tearing in Firefox >= 57. - @include backface-visibility(hidden); + @include vendor-prefixes.backface-visibility(hidden); animation: mat-progress-bar-primary-indeterminate-scale - $mat-progress-bar-full-animation-duration infinite linear; + $full-animation-duration infinite linear; } .mat-progress-bar-secondary { // Avoids stacked animation tearing in Firefox >= 57. - @include backface-visibility(hidden); + @include vendor-prefixes.backface-visibility(hidden); animation: mat-progress-bar-secondary-indeterminate-translate - $mat-progress-bar-full-animation-duration infinite linear; + $full-animation-duration infinite linear; left: -54.888891%; display: block; } .mat-progress-bar-secondary.mat-progress-bar-fill::after { // Avoids stacked animation tearing in Firefox >= 57. - @include backface-visibility(hidden); + @include vendor-prefixes.backface-visibility(hidden); animation: mat-progress-bar-secondary-indeterminate-scale - $mat-progress-bar-full-animation-duration infinite linear; + $full-animation-duration infinite linear; } } &[mode='buffer'] { .mat-progress-bar-background { // Avoids stacked animation tearing in Firefox >= 57. - @include backface-visibility(hidden); + @include vendor-prefixes.backface-visibility(hidden); animation: mat-progress-bar-background-scroll - $mat-progress-bar-piece-animation-duration infinite linear; + $piece-animation-duration infinite linear; // Needs to be explicit here so it can overwrite the `display: none` // in all other variants in high contrast mode. @@ -180,32 +179,32 @@ $mat-progress-bar-piece-animation-duration: 250ms !default; // Progress Bar Timing functions: // $mat-progress-bar-primary-indeterminate-translate-step-1 has no timing function. -$mat-progress-bar-primary-indeterminate-translate-step-2: +$primary-indeterminate-translate-step-2: cubic-bezier(0.5, 0, 0.701732, 0.495819) !default; -$mat-progress-bar-primary-indeterminate-translate-step-3: +$primary-indeterminate-translate-step-3: cubic-bezier(0.302435, 0.381352, 0.55, 0.956352) !default; // $mat-progress-bar-primary-indeterminate-translate-step-4 has no timing function. // $mat-progress-bar-primary-indeterminate-scale-step-1 has no timing function -$mat-progress-bar-primary-indeterminate-scale-step-2: +$primary-indeterminate-scale-step-2: cubic-bezier(0.334731, 0.12482, 0.785844, 1) !default; -$mat-progress-bar-primary-indeterminate-scale-step-3: +$primary-indeterminate-scale-step-3: cubic-bezier(0.06, 0.11, 0.6, 1) !default; // $mat-progress-bar-primary-indeterminate-scale-step-4 has no timing function -$mat-progress-bar-secondary-indeterminate-translate-step-1: +$secondary-indeterminate-translate-step-1: cubic-bezier(0.15, 0, 0.515058, 0.409685) !default; -$mat-progress-bar-secondary-indeterminate-translate-step-2: +$secondary-indeterminate-translate-step-2: cubic-bezier(0.31033, 0.284058, 0.8, 0.733712) !default; -$mat-progress-bar-secondary-indeterminate-translate-step-3: +$secondary-indeterminate-translate-step-3: cubic-bezier(0.4, 0.627035, 0.6, 0.902026) !default; // $mat-progress-bar-secondary-indeterminate-translate-step-4 has no timing function -$mat-progress-bar-secondary-indeterminate-scale-step-1: +$secondary-indeterminate-scale-step-1: cubic-bezier(0.15, 0, 0.515058, 0.409685) !default; -$mat-progress-bar-secondary-indeterminate-scale-step-2: +$secondary-indeterminate-scale-step-2: cubic-bezier(0.31033, 0.284058, 0.8, 0.733712) !default; -$mat-progress-bar-secondary-indeterminate-scale-step-3: +$secondary-indeterminate-scale-step-3: cubic-bezier(0.4, 0.627035, 0.6, 0.902026) !default; // $mat-progress-bar-secondary-indeterminate-scale-step-4 has no timing function @@ -218,11 +217,11 @@ $mat-progress-bar-secondary-indeterminate-scale-step-3: transform: translateX(0); } 20% { - animation-timing-function: $mat-progress-bar-primary-indeterminate-translate-step-2; + animation-timing-function: $primary-indeterminate-translate-step-2; transform: translateX(0); } 59.15% { - animation-timing-function: $mat-progress-bar-primary-indeterminate-translate-step-3; + animation-timing-function: $primary-indeterminate-translate-step-3; transform: translateX(83.67142%); } 100% { @@ -235,11 +234,11 @@ $mat-progress-bar-secondary-indeterminate-scale-step-3: transform: scaleX(0.08); } 36.65% { - animation-timing-function: $mat-progress-bar-primary-indeterminate-scale-step-2; + animation-timing-function: $primary-indeterminate-scale-step-2; transform: scaleX(0.08); } 69.15% { - animation-timing-function: $mat-progress-bar-primary-indeterminate-scale-step-3; + animation-timing-function: $primary-indeterminate-scale-step-3; transform: scaleX(0.661479); } 100% { @@ -250,16 +249,16 @@ $mat-progress-bar-secondary-indeterminate-scale-step-3: // Secondary indicator. @keyframes mat-progress-bar-secondary-indeterminate-translate { 0% { - animation-timing-function: $mat-progress-bar-secondary-indeterminate-translate-step-1; + animation-timing-function: $secondary-indeterminate-translate-step-1; transform: translateX(0); } 25% { - animation-timing-function: $mat-progress-bar-secondary-indeterminate-translate-step-2; + animation-timing-function: $secondary-indeterminate-translate-step-2; transform: translateX(37.651913%); } 48.35% { - animation-timing-function: $mat-progress-bar-secondary-indeterminate-translate-step-3; + animation-timing-function: $secondary-indeterminate-translate-step-3; transform: translateX(84.386165%); } 100% { @@ -269,15 +268,15 @@ $mat-progress-bar-secondary-indeterminate-scale-step-3: @keyframes mat-progress-bar-secondary-indeterminate-scale { 0% { - animation-timing-function: $mat-progress-bar-secondary-indeterminate-scale-step-1; + animation-timing-function: $secondary-indeterminate-scale-step-1; transform: scaleX(0.08); } 19.15% { - animation-timing-function: $mat-progress-bar-secondary-indeterminate-scale-step-2; + animation-timing-function: $secondary-indeterminate-scale-step-2; transform: scaleX(0.457104); } 44.15% { - animation-timing-function: $mat-progress-bar-secondary-indeterminate-scale-step-3; + animation-timing-function: $secondary-indeterminate-scale-step-3; transform: scaleX(0.72796); } 100% { @@ -289,6 +288,6 @@ $mat-progress-bar-secondary-indeterminate-scale-step-3: @keyframes mat-progress-bar-background-scroll { to { // Needs to be in multiples of the size of the buffer circles. - transform: translateX(-$mat-progress-bar-height * 2); + transform: translateX(-$height * 2); } } diff --git a/src/material/progress-bar/progress-bar.spec.ts b/src/material/progress-bar/progress-bar.spec.ts index f6ede897d157..c80cb1120613 100644 --- a/src/material/progress-bar/progress-bar.spec.ts +++ b/src/material/progress-bar/progress-bar.spec.ts @@ -1,30 +1,47 @@ import {TestBed, ComponentFixture} from '@angular/core/testing'; -import {Component, DebugElement, Type} from '@angular/core'; +import {Component, DebugElement, Provider, Type} from '@angular/core'; import {By} from '@angular/platform-browser'; -import {dispatchFakeEvent} from '@angular/cdk/testing/private'; +import {dispatchFakeEvent} from '../../cdk/testing/private'; import {MatProgressBarModule, MAT_PROGRESS_BAR_LOCATION} from './index'; -import {MatProgressBar} from './progress-bar'; - +import {MatProgressBar, MAT_PROGRESS_BAR_DEFAULT_OPTIONS} from './progress-bar'; describe('MatProgressBar', () => { let fakePath: string; - function createComponent(componentType: Type, - imports?: Type<{}>[]): ComponentFixture { + function createComponent( + componentType: Type, + providers: Provider[] = [], + ): ComponentFixture { fakePath = '/fake-path'; TestBed.configureTestingModule({ - imports: imports || [MatProgressBarModule], + imports: [MatProgressBarModule], declarations: [componentType], - providers: [{ - provide: MAT_PROGRESS_BAR_LOCATION, - useValue: {getPathname: () => fakePath} - }] + providers: [ + { + provide: MAT_PROGRESS_BAR_LOCATION, + useValue: {getPathname: () => fakePath}, + }, + ...providers, + ], }).compileComponents(); return TestBed.createComponent(componentType); } + // All children need to be hidden for screen readers in order to support ChromeVox. + // More context in the issue: https://github.com/angular/components/issues/22165. + it('should have elements wrapped in aria-hidden div', () => { + const fixture = createComponent(BasicProgressBar); + const host = fixture.nativeElement as Element; + const element = host.children[0]; + expect(element.children.length).toBe(1); + + const div = element.querySelector('div')!; + expect(div).toBeTruthy(); + expect(div.getAttribute('aria-hidden')).toBe('true'); + }); + describe('with animation', () => { describe('basic progress-bar', () => { it('should apply a mode of "determinate" if no mode is provided.', () => { @@ -91,7 +108,6 @@ describe('MatProgressBar', () => { expect(progressComponent._primaryTransform()).toEqual({transform: 'scale3d(0.35, 1, 1)'}); expect(progressComponent._bufferTransform()).toEqual({transform: 'scale3d(0.55, 1, 1)'}); - progressComponent.value = 60; progressComponent.bufferValue = 60; expect(progressComponent._primaryTransform()).toEqual({transform: 'scale3d(0.6, 1, 1)'}); @@ -153,13 +169,15 @@ describe('MatProgressBar', () => { fixture.detectChanges(); expect(progressElement.nativeElement.getAttribute('aria-valuenow')) - .toBe('50', 'Expected aria-valuenow to be set in determinate mode.'); + .withContext('Expected aria-valuenow to be set in determinate mode.') + .toBe('50'); progressComponent.mode = 'indeterminate'; fixture.detectChanges(); expect(progressElement.nativeElement.hasAttribute('aria-valuenow')) - .toBe(false, 'Expect aria-valuenow to be cleared in indeterminate mode.'); + .withContext('Expect aria-valuenow to be cleared in indeterminate mode.') + .toBe(false); }); it('should remove the `aria-valuenow` attribute in query mode', () => { @@ -174,15 +192,32 @@ describe('MatProgressBar', () => { fixture.detectChanges(); expect(progressElement.nativeElement.getAttribute('aria-valuenow')) - .toBe('50', 'Expected aria-valuenow to be set in determinate mode.'); + .withContext('Expected aria-valuenow to be set in determinate mode.') + .toBe('50'); progressComponent.mode = 'query'; fixture.detectChanges(); expect(progressElement.nativeElement.hasAttribute('aria-valuenow')) - .toBe(false, 'Expect aria-valuenow to be cleared in query mode.'); + .withContext('Expect aria-valuenow to be cleared in query mode.') + .toBe(false); }); + it('should be able to configure the default progress bar options via DI', () => { + const fixture = createComponent(BasicProgressBar, [ + { + provide: MAT_PROGRESS_BAR_DEFAULT_OPTIONS, + useValue: { + mode: 'buffer', + color: 'warn', + }, + }, + ]); + fixture.detectChanges(); + const progressElement = fixture.debugElement.query(By.css('mat-progress-bar'))!; + expect(progressElement.componentInstance.mode).toBe('buffer'); + expect(progressElement.componentInstance.color).toBe('warn'); + }); }); describe('animation trigger on determinate setting', () => { @@ -207,7 +242,7 @@ describe('MatProgressBar', () => { // On animation end, output should be emitted. dispatchFakeEvent(primaryValueBar.nativeElement, 'transitionend'); - expect(progressComponent.animationEnd.next).toHaveBeenCalledWith({ value: 40 }); + expect(progressComponent.animationEnd.next).toHaveBeenCalledWith({value: 40}); }); }); @@ -229,8 +264,9 @@ describe('MatProgressBar', () => { fixture.detectChanges(); expect(primaryValueBar.nativeElement.addEventListener).toHaveBeenCalled(); - expect(primaryValueBar.nativeElement.addEventListener - .calls.mostRecent().args[0]).toBe('transitionend'); + expect(primaryValueBar.nativeElement.addEventListener.calls.mostRecent().args[0]).toBe( + 'transitionend', + ); }); it('should trigger output event on primary value bar animation end', () => { @@ -242,7 +278,7 @@ describe('MatProgressBar', () => { // On animation end, output should be emitted. dispatchFakeEvent(primaryValueBar.nativeElement, 'transitionend'); - expect(progressComponent.animationEnd.next).toHaveBeenCalledWith({ value: 40 }); + expect(progressComponent.animationEnd.next).toHaveBeenCalledWith({value: 40}); }); it('should trigger output event with value not bufferValue', () => { @@ -255,15 +291,14 @@ describe('MatProgressBar', () => { // On animation end, output should be emitted. dispatchFakeEvent(primaryValueBar.nativeElement, 'transitionend'); - expect(progressComponent.animationEnd.next).toHaveBeenCalledWith({ value: 40 }); + expect(progressComponent.animationEnd.next).toHaveBeenCalledWith({value: 40}); }); }); }); - }); @Component({template: ''}) -class BasicProgressBar { } +class BasicProgressBar {} @Component({template: ''}) -class BufferProgressBar { } +class BufferProgressBar {} diff --git a/src/material/progress-bar/progress-bar.ts b/src/material/progress-bar/progress-bar.ts index a402e47ac2a0..3614ac0576a9 100644 --- a/src/material/progress-bar/progress-bar.ts +++ b/src/material/progress-bar/progress-bar.ts @@ -24,12 +24,11 @@ import { ViewChild, ViewEncapsulation, } from '@angular/core'; -import {CanColor, CanColorCtor, mixinColor} from '@angular/material/core'; +import {CanColor, mixinColor, ThemePalette} from '@angular/material/core'; import {ANIMATION_MODULE_TYPE} from '@angular/platform-browser/animations'; import {fromEvent, Observable, Subscription} from 'rxjs'; import {filter} from 'rxjs/operators'; - // TODO(josephperrott): Benchpress tests. // TODO(josephperrott): Add ARIA attributes for progress bar "for". @@ -40,12 +39,12 @@ export interface ProgressAnimationEnd { // Boilerplate for applying mixins to MatProgressBar. /** @docs-private */ -class MatProgressBarBase { - constructor(public _elementRef: ElementRef) { } -} - -const _MatProgressBarMixinBase: CanColorCtor & typeof MatProgressBarBase = - mixinColor(MatProgressBarBase, 'primary'); +const _MatProgressBarBase = mixinColor( + class { + constructor(public _elementRef: ElementRef) {} + }, + 'primary', +); /** * Injection token used to provide the current location to `MatProgressBar`. @@ -54,7 +53,7 @@ const _MatProgressBarMixinBase: CanColorCtor & typeof MatProgressBarBase = */ export const MAT_PROGRESS_BAR_LOCATION = new InjectionToken( 'mat-progress-bar-location', - {providedIn: 'root', factory: MAT_PROGRESS_BAR_LOCATION_FACTORY} + {providedIn: 'root', factory: MAT_PROGRESS_BAR_LOCATION_FACTORY}, ); /** @@ -73,12 +72,26 @@ export function MAT_PROGRESS_BAR_LOCATION_FACTORY(): MatProgressBarLocation { return { // Note that this needs to be a function, rather than a property, because Angular // will only resolve it once, but we want the current path on each call. - getPathname: () => _location ? (_location.pathname + _location.search) : '' + getPathname: () => (_location ? _location.pathname + _location.search : ''), }; } export type ProgressBarMode = 'determinate' | 'indeterminate' | 'buffer' | 'query'; +/** Default `mat-progress-bar` options that can be overridden. */ +export interface MatProgressBarDefaultOptions { + /** Default color of the progress bar. */ + color?: ThemePalette; + + /** Default mode of the progress bar. */ + mode?: ProgressBarMode; +} + +/** Injection token to be used to override the default options for `mat-progress-bar`. */ +export const MAT_PROGRESS_BAR_DEFAULT_OPTIONS = new InjectionToken( + 'MAT_PROGRESS_BAR_DEFAULT_OPTIONS', +); + /** Counter used to generate unique IDs for progress bars. */ let progressbarId = 0; @@ -92,6 +105,9 @@ let progressbarId = 0; 'role': 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100', + // set tab index to -1 so screen readers will read the aria-label + // Note: there is a known issue with JAWS that does not read progressbar aria labels on FireFox + 'tabindex': '-1', '[attr.aria-valuenow]': '(mode === "indeterminate" || mode === "query") ? null : value', '[attr.mode]': 'mode', 'class': 'mat-progress-bar', @@ -103,16 +119,24 @@ let progressbarId = 0; changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) -export class MatProgressBar extends _MatProgressBarMixinBase implements CanColor, - AfterViewInit, OnDestroy { - constructor(public _elementRef: ElementRef, private _ngZone: NgZone, - @Optional() @Inject(ANIMATION_MODULE_TYPE) public _animationMode?: string, - /** - * @deprecated `location` parameter to be made required. - * @breaking-change 8.0.0 - */ - @Optional() @Inject(MAT_PROGRESS_BAR_LOCATION) location?: MatProgressBarLocation) { - super(_elementRef); +export class MatProgressBar + extends _MatProgressBarBase + implements CanColor, AfterViewInit, OnDestroy +{ + constructor( + elementRef: ElementRef, + private _ngZone: NgZone, + @Optional() @Inject(ANIMATION_MODULE_TYPE) public _animationMode?: string, + /** + * @deprecated `location` parameter to be made required. + * @breaking-change 8.0.0 + */ + @Optional() @Inject(MAT_PROGRESS_BAR_LOCATION) location?: MatProgressBarLocation, + @Optional() + @Inject(MAT_PROGRESS_BAR_DEFAULT_OPTIONS) + defaults?: MatProgressBarDefaultOptions, + ) { + super(elementRef); // We need to prefix the SVG reference with the current path, otherwise they won't work // in Safari if the page has a `` tag. Note that we need quotes inside the `url()`, @@ -124,6 +148,14 @@ export class MatProgressBar extends _MatProgressBarMixinBase implements CanColor const path = location ? location.getPathname().split('#')[0] : ''; this._rectangleFillValue = `url('${path}#${this.progressbarId}')`; this._isNoopAnimation = _animationMode === 'NoopAnimations'; + + if (defaults) { + if (defaults.color) { + this.color = this.defaultColor = defaults.color; + } + + this.mode = defaults.mode || this.mode; + } } /** Flag that indicates whether NoopAnimations mode is set to true. */ @@ -131,16 +163,22 @@ export class MatProgressBar extends _MatProgressBarMixinBase implements CanColor /** Value of the progress bar. Defaults to zero. Mirrored to aria-valuenow. */ @Input() - get value(): number { return this._value; } - set value(v: number) { + get value(): number { + return this._value; + } + set value(v: NumberInput) { this._value = clamp(coerceNumberProperty(v) || 0); } private _value: number = 0; /** Buffer value of the progress bar. Defaults to zero. */ @Input() - get bufferValue(): number { return this._bufferValue; } - set bufferValue(v: number) { this._bufferValue = clamp(v || 0); } + get bufferValue(): number { + return this._bufferValue; + } + set bufferValue(v: number) { + this._bufferValue = clamp(v || 0); + } private _bufferValue: number = 0; @ViewChild('primaryValueBar') _primaryValueBar: ElementRef; @@ -150,7 +188,7 @@ export class MatProgressBar extends _MatProgressBarMixinBase implements CanColor * be emitted when animations are disabled, nor will it be emitted for modes with continuous * animations (indeterminate and query). */ - @Output() animationEnd = new EventEmitter(); + @Output() readonly animationEnd = new EventEmitter(); /** Reference to animation end subscription to be unsubscribed on destroy. */ private _animationEndSubscription: Subscription = Subscription.EMPTY; @@ -193,25 +231,24 @@ export class MatProgressBar extends _MatProgressBarMixinBase implements CanColor ngAfterViewInit() { // Run outside angular so change detection didn't get triggered on every transition end // instead only on the animation that we care about (primary value bar's transitionend) - this._ngZone.runOutsideAngular((() => { + this._ngZone.runOutsideAngular(() => { const element = this._primaryValueBar.nativeElement; - this._animationEndSubscription = - (fromEvent(element, 'transitionend') as Observable) - .pipe(filter(((e: TransitionEvent) => e.target === element))) - .subscribe(() => { - if (this.mode === 'determinate' || this.mode === 'buffer') { - this._ngZone.run(() => this.animationEnd.next({value: this.value})); - } - }); - })); + this._animationEndSubscription = ( + fromEvent(element, 'transitionend') as Observable + ) + .pipe(filter((e: TransitionEvent) => e.target === element)) + .subscribe(() => { + if (this.mode === 'determinate' || this.mode === 'buffer') { + this._ngZone.run(() => this.animationEnd.next({value: this.value})); + } + }); + }); } ngOnDestroy() { this._animationEndSubscription.unsubscribe(); } - - static ngAcceptInputType_value: NumberInput; } /** Clamps a value to be between two numbers, by default 0 and 100. */ diff --git a/src/material/progress-bar/public-api.ts b/src/material/progress-bar/public-api.ts index 739a6192faea..d45f6d0ac4f5 100644 --- a/src/material/progress-bar/public-api.ts +++ b/src/material/progress-bar/public-api.ts @@ -8,4 +8,3 @@ export * from './progress-bar-module'; export * from './progress-bar'; - diff --git a/src/material/progress-bar/testing/BUILD.bazel b/src/material/progress-bar/testing/BUILD.bazel index c79c0b04ba06..52bc200f4cf0 100644 --- a/src/material/progress-bar/testing/BUILD.bazel +++ b/src/material/progress-bar/testing/BUILD.bazel @@ -8,7 +8,6 @@ ts_library( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material/progress-bar/testing", deps = [ "//src/cdk/coercion", "//src/cdk/testing", diff --git a/src/material/progress-bar/testing/progress-bar-harness.ts b/src/material/progress-bar/testing/progress-bar-harness.ts index 722dd9288515..f745e009b4e1 100644 --- a/src/material/progress-bar/testing/progress-bar-harness.ts +++ b/src/material/progress-bar/testing/progress-bar-harness.ts @@ -26,14 +26,14 @@ export class MatProgressBarHarness extends ComponentHarness { } /** Gets the progress bar's value. */ - async getValue(): Promise { + async getValue(): Promise { const host = await this.host(); const ariaValue = await host.getAttribute('aria-valuenow'); return ariaValue ? coerceNumberProperty(ariaValue) : null; } /** Gets the progress bar's mode. */ - async getMode(): Promise { + async getMode(): Promise { return (await this.host()).getAttribute('mode'); } } diff --git a/src/material/progress-bar/testing/shared.spec.ts b/src/material/progress-bar/testing/shared.spec.ts index ffbcbefcbe2e..052285d503bc 100644 --- a/src/material/progress-bar/testing/shared.spec.ts +++ b/src/material/progress-bar/testing/shared.spec.ts @@ -5,18 +5,18 @@ import {ComponentFixture, TestBed} from '@angular/core/testing'; import {MatProgressBarModule} from '@angular/material/progress-bar'; import {MatProgressBarHarness} from './progress-bar-harness'; -export function runHarnessTests(progressBarModule: typeof MatProgressBarModule, - progressBarHarness: typeof MatProgressBarHarness) { +export function runHarnessTests( + progressBarModule: typeof MatProgressBarModule, + progressBarHarness: typeof MatProgressBarHarness, +) { let fixture: ComponentFixture; let loader: HarnessLoader; beforeEach(async () => { - await TestBed - .configureTestingModule({ - imports: [progressBarModule], - declarations: [ProgressBarHarnessTest], - }) - .compileComponents(); + await TestBed.configureTestingModule({ + imports: [progressBarModule], + declarations: [ProgressBarHarnessTest], + }).compileComponents(); fixture = TestBed.createComponent(ProgressBarHarnessTest); fixture.detectChanges(); @@ -47,7 +47,7 @@ export function runHarnessTests(progressBarModule: typeof MatProgressBarModule, template: ` - ` + `, }) class ProgressBarHarnessTest { value: number; diff --git a/src/material/progress-spinner/BUILD.bazel b/src/material/progress-spinner/BUILD.bazel index b35ff506febe..c1535578c6e0 100644 --- a/src/material/progress-spinner/BUILD.bazel +++ b/src/material/progress-spinner/BUILD.bazel @@ -19,7 +19,6 @@ ng_module( exclude = ["**/*.spec.ts"], ), assets = [":progress-spinner.css"] + glob(["**/*.html"]), - module_name = "@angular/material/progress-spinner", deps = [ "//src/cdk/coercion", "//src/cdk/platform", diff --git a/src/material/progress-spinner/_progress-spinner-legacy-index.scss b/src/material/progress-spinner/_progress-spinner-legacy-index.scss new file mode 100644 index 000000000000..8a2ba2a328e9 --- /dev/null +++ b/src/material/progress-spinner/_progress-spinner-legacy-index.scss @@ -0,0 +1,2 @@ +@forward 'progress-spinner-theme' hide color, theme, typography; +@forward 'progress-spinner-theme' as mat-progress-spinner-* hide mat-progress-spinner-density; diff --git a/src/material/progress-spinner/_progress-spinner-theme.import.scss b/src/material/progress-spinner/_progress-spinner-theme.import.scss new file mode 100644 index 000000000000..647ca3b87e02 --- /dev/null +++ b/src/material/progress-spinner/_progress-spinner-theme.import.scss @@ -0,0 +1,6 @@ +@forward '../core/theming/theming.import'; +@forward 'progress-spinner-theme' hide color, theme, typography; +@forward 'progress-spinner-theme' as mat-progress-spinner-* hide mat-progress-spinner-density; + +@import '../core/theming/palette'; +@import '../core/theming/theming'; diff --git a/src/material/progress-spinner/_progress-spinner-theme.scss b/src/material/progress-spinner/_progress-spinner-theme.scss index d92b92521d02..b81da47945c9 100644 --- a/src/material/progress-spinner/_progress-spinner-theme.scss +++ b/src/material/progress-spinner/_progress-spinner-theme.scss @@ -1,46 +1,46 @@ -@import '../core/theming/palette'; -@import '../core/theming/theming'; +@use 'sass:map'; +@use '../core/theming/theming'; -@mixin mat-progress-spinner-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $primary: map-get($config, primary); - $accent: map-get($config, accent); - $warn: map-get($config, warn); +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $primary: map.get($config, primary); + $accent: map.get($config, accent); + $warn: map.get($config, warn); .mat-progress-spinner, .mat-spinner { circle { - stroke: mat-color($primary); + stroke: theming.get-color-from-palette($primary); } &.mat-accent circle { - stroke: mat-color($accent); + stroke: theming.get-color-from-palette($accent); } &.mat-warn circle { - stroke: mat-color($warn); + stroke: theming.get-color-from-palette($warn); } } } -@mixin mat-progress-spinner-typography($config-or-theme) {} +@mixin typography($config-or-theme) {} -@mixin _mat-progress-spinner-density($config-or-theme) {} +@mixin _density($config-or-theme) {} -@mixin mat-progress-spinner-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-progress-spinner') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-progress-spinner') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); @if $color != null { - @include mat-progress-spinner-color($color); + @include color($color); } @if $density != null { - @include _mat-progress-spinner-density($density); + @include _density($density); } @if $typography != null { - @include mat-progress-spinner-typography($typography); + @include typography($typography); } } } diff --git a/src/material/progress-spinner/progress-spinner-module.ts b/src/material/progress-spinner/progress-spinner-module.ts index 4f511216921d..50e2fddd90ef 100644 --- a/src/material/progress-spinner/progress-spinner-module.ts +++ b/src/material/progress-spinner/progress-spinner-module.ts @@ -10,17 +10,9 @@ import {CommonModule} from '@angular/common'; import {MatCommonModule} from '@angular/material/core'; import {MatProgressSpinner, MatSpinner} from './progress-spinner'; - @NgModule({ imports: [MatCommonModule, CommonModule], - exports: [ - MatProgressSpinner, - MatSpinner, - MatCommonModule - ], - declarations: [ - MatProgressSpinner, - MatSpinner - ], + exports: [MatProgressSpinner, MatSpinner, MatCommonModule], + declarations: [MatProgressSpinner, MatSpinner], }) export class MatProgressSpinnerModule {} diff --git a/src/material/progress-spinner/progress-spinner.e2e.spec.ts b/src/material/progress-spinner/progress-spinner.e2e.spec.ts index 28f8eed9b6d9..f1862bb6efbb 100644 --- a/src/material/progress-spinner/progress-spinner.e2e.spec.ts +++ b/src/material/progress-spinner/progress-spinner.e2e.spec.ts @@ -8,8 +8,9 @@ describe('progress-spinner', () => { }); it('should render an indeterminate progress spinner', async () => { - expect(await element(by.css('mat-progress-spinner[mode="indeterminate"]')).isPresent()) - .toBe(true); + expect(await element(by.css('mat-progress-spinner[mode="indeterminate"]')).isPresent()).toBe( + true, + ); }); it('should render a spinner', async () => { diff --git a/src/material/progress-spinner/progress-spinner.html b/src/material/progress-spinner/progress-spinner.html index aa194cc04328..29c093050abd 100644 --- a/src/material/progress-spinner/progress-spinner.html +++ b/src/material/progress-spinner/progress-spinner.html @@ -1,17 +1,20 @@ + - + [ngSwitch]="mode === 'indeterminate'" + aria-hidden="true"> - `); + `, + ); const {logOutput} = await runMigration(); expect(logOutput).toContain( - 'The HammerJS v9 migration for Angular Components migrated the project to ' + + 'The HammerJS v9 migration for Angular Components migrated the project to ' + 'keep HammerJS installed, but detected ambiguous usage of HammerJS. Please manually ' + - 'check if you can remove HammerJS from your application.'); + 'check if you can remove HammerJS from your application.', + ); }); it('should create gesture config file if used in template and programmatically', async () => { - writeFile('/projects/cdk-testing/src/app/app.component.html', ` + writeFile( + '/projects/cdk-testing/src/app/app.component.html', + ` - `); + `, + ); - writeFile('/projects/cdk-testing/src/app/hammer.ts', ` + writeFile( + '/projects/cdk-testing/src/app/hammer.ts', + ` export function createHammerInstance(el: HTMLElement) { return new (window as any).Hammer(el); } - `); + `, + ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(true); - expect(tree.readContent('/projects/cdk-testing/src/gesture-config.ts')) - .toBe(readFileSync(GESTURE_CONFIG_TEMPLATE_PATH, 'utf8')); + expect(tree.readContent('/projects/cdk-testing/src/gesture-config.ts')).toBe( + readFileSync(GESTURE_CONFIG_TEMPLATE_PATH, 'utf8'), + ); }); it('should create gesture config file with different name if it would conflict', async () => { - writeFile('/projects/cdk-testing/src/app/app.component.html', ` + writeFile( + '/projects/cdk-testing/src/app/app.component.html', + ` - `); + `, + ); // unlikely case that someone has a file named "gesture-config" in the // project sources root. Though we want to perform the migration @@ -568,16 +705,22 @@ describe('v9 HammerJS removal', () => { expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(tree.exists('/projects/cdk-testing/src/gesture-config-1.ts')).toBe(true); - expect(tree.readContent('/projects/cdk-testing/src/gesture-config-1.ts')) - .toBe(readFileSync(GESTURE_CONFIG_TEMPLATE_PATH, 'utf8')); + expect(tree.readContent('/projects/cdk-testing/src/gesture-config-1.ts')).toBe( + readFileSync(GESTURE_CONFIG_TEMPLATE_PATH, 'utf8'), + ); }); it('should rewrite references to gesture config', async () => { - writeFile('/projects/cdk-testing/src/app/app.component.html', ` + writeFile( + '/projects/cdk-testing/src/app/app.component.html', + ` - `); + `, + ); - writeFile('/projects/cdk-testing/src/nested/test.module.ts', dedent` + writeFile( + '/projects/cdk-testing/src/nested/test.module.ts', + dedent` import {NgModule} from '@angular/core'; import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {GestureConfig} from '@angular/material/core'; // some-comment @@ -589,7 +732,8 @@ describe('v9 HammerJS removal', () => { ] }) export class TestModule {} - `); + `, + ); await runMigration(); @@ -610,11 +754,16 @@ describe('v9 HammerJS removal', () => { }); it('should rewrite references to gesture config without causing conflicts', async () => { - writeFile('/projects/cdk-testing/src/app/app.component.html', ` + writeFile( + '/projects/cdk-testing/src/app/app.component.html', + ` - `); + `, + ); - writeFile('/projects/cdk-testing/src/test.module.ts', dedent` + writeFile( + '/projects/cdk-testing/src/test.module.ts', + dedent` import {NgModule} from '@angular/core'; import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {GestureConfig} from 'ngx-hammer-events'; @@ -626,7 +775,8 @@ describe('v9 HammerJS removal', () => { ] }) export class TestModule {} - `); + `, + ); await runMigration(); @@ -648,14 +798,19 @@ describe('v9 HammerJS removal', () => { }); it('should set up Hammer gestures in app module', async () => { - writeFile('/projects/cdk-testing/src/app/app.component.html', ` + writeFile( + '/projects/cdk-testing/src/app/app.component.html', + ` - `); + `, + ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(true); + + // tslint:disable:max-line-length expect(tree.readContent('/projects/cdk-testing/src/app/app.module.ts')).toContain(dedent`\ import { NgModule } from '@angular/core'; import { BrowserModule, HAMMER_GESTURE_CONFIG, HammerModule } from '@angular/platform-browser'; @@ -675,15 +830,23 @@ describe('v9 HammerJS removal', () => { bootstrap: [AppComponent] }) export class AppModule { }`); + // tslint:enable:max-line-length }); - it('should add gesture config provider to app module if module is referenced through ' + - 're-exports in bootstrap', async () => { - writeFile('/projects/cdk-testing/src/app/app.component.html', ` + it( + 'should add gesture config provider to app module if module is referenced through ' + + 're-exports in bootstrap', + async () => { + writeFile( + '/projects/cdk-testing/src/app/app.component.html', + ` - `); + `, + ); - writeFile('/projects/cdk-testing/src/main.ts', ` + writeFile( + '/projects/cdk-testing/src/main.ts', + ` import 'hammerjs'; import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; @@ -697,15 +860,20 @@ describe('v9 HammerJS removal', () => { platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err)); - `); + `, + ); - writeFile('/projects/cdk-testing/src/app/index.ts', `export * from './app.module';`); + writeFile('/projects/cdk-testing/src/app/index.ts', `export * from './app.module';`); - await runMigration(); + await runMigration(); - expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); - expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(true); - expect(tree.readContent('/projects/cdk-testing/src/app/app.module.ts')).toContain(dedent`\ + expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain( + `import 'hammerjs';`, + ); + expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(true); + + // tslint:disable:max-line-length + expect(tree.readContent('/projects/cdk-testing/src/app/app.module.ts')).toContain(dedent`\ import { NgModule } from '@angular/core'; import { BrowserModule, HAMMER_GESTURE_CONFIG, HammerModule } from '@angular/platform-browser'; @@ -724,14 +892,21 @@ describe('v9 HammerJS removal', () => { bootstrap: [AppComponent] }) export class AppModule { }`); - }); + // tslint:enable:max-line-length + }, + ); it('should not add gesture config provider multiple times if already provided', async () => { - writeFile('/projects/cdk-testing/src/app/app.component.html', ` + writeFile( + '/projects/cdk-testing/src/app/app.component.html', + ` - `); + `, + ); - writeFile('/projects/cdk-testing/src/app/app.module.ts', dedent` + writeFile( + '/projects/cdk-testing/src/app/app.module.ts', + dedent` import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {GestureConfig} from '@angular/material/core'; @@ -745,7 +920,8 @@ describe('v9 HammerJS removal', () => { ], }) export class AppModule {} - `); + `, + ); await runMigration(); @@ -769,11 +945,16 @@ describe('v9 HammerJS removal', () => { }); it('should not add HammerModule multiple times if already provided', async () => { - writeFile('/projects/cdk-testing/src/app/app.component.html', ` + writeFile( + '/projects/cdk-testing/src/app/app.component.html', + ` - `); + `, + ); - writeFile('/projects/cdk-testing/src/app/app.module.ts', dedent` + writeFile( + '/projects/cdk-testing/src/app/app.module.ts', + dedent` import {HammerModule as myHammerModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; @@ -781,12 +962,14 @@ describe('v9 HammerJS removal', () => { imports: [myHammerModule], }) export class AppModule {} - `); + `, + ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(true); + // tslint:disable:max-line-length expect(tree.readContent('/projects/cdk-testing/src/app/app.module.ts')).toContain(dedent` import { HammerModule as myHammerModule, HAMMER_GESTURE_CONFIG } from '@angular/platform-browser'; import {NgModule} from '@angular/core'; @@ -797,52 +980,66 @@ describe('v9 HammerJS removal', () => { providers: [{ provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig }], }) export class AppModule {}`); + // tslint:enable:max-line-length }); }); - it('should not remove hammerjs if test target compilation scope does not contain hammerjs usage', - async () => { - addPackageToPackageJson(tree, 'hammerjs', '0.0.0'); - expect(JSON.parse(tree.readContent('/package.json')).dependencies['hammerjs']).toBe('0.0.0'); - - // we simulate a case where a component does not have any tests for. In that case, - // the test target compilation scope does not include "test.component.ts" and the - // migration would detect **no** usage of HammerJS, hence removing it. This is - // something we avoid by just ignoring test target compilation scopes. - writeFile('/projects/cdk-testing/src/app/test.component.ts', ` + it('should not remove hammerjs if test target compilation scope does not contain hammerjs usage', async () => { + addPackageToPackageJson(tree, 'hammerjs', '0.0.0'); + expect(getDependencyVersion('hammerjs')).toBe('0.0.0'); + + // we simulate a case where a component does not have any tests for. In that case, + // the test target compilation scope does not include "test.component.ts" and the + // migration would detect **no** usage of HammerJS, hence removing it. This is + // something we avoid by just ignoring test target compilation scopes. + writeFile( + '/projects/cdk-testing/src/app/test.component.ts', + ` import {Component} from '@angular/core'; @Component({ template: \`\` }) export class TestComponent {} - `); - - await runMigration(); + `, + ); - expect(JSON.parse(tree.readContent('/package.json')).dependencies['hammerjs']).toBe('0.0.0'); - }); - - it('should not remove hammerjs from "package.json" file if used in one project while ' + - 'unused in other project', async () => { - addPackageToPackageJson(tree, 'hammerjs', '0.0.0'); + await runMigration(); - expect(JSON.parse(tree.readContent('/package.json')).dependencies['hammerjs']).toBe('0.0.0'); + expect(getDependencyVersion('hammerjs')).toBe('0.0.0'); + }); - await runner.runExternalSchematicAsync('@schematics/angular', 'application', - {name: 'second-project'}, tree).toPromise(); + it( + 'should not remove hammerjs from "package.json" file if used in one project while ' + + 'unused in other project', + async () => { + addPackageToPackageJson(tree, 'hammerjs', '0.0.0'); - // Ensure the "second-project" will be detected with using HammerJS. - writeFile('/projects/second-project/src/main.ts', ` + expect(getDependencyVersion('hammerjs')).toBe('0.0.0'); + + await runner + .runExternalSchematicAsync( + '@schematics/angular', + 'application', + {name: 'second-project'}, + tree, + ) + .toPromise(); + + // Ensure the "second-project" will be detected with using HammerJS. + writeFile( + '/projects/second-project/src/main.ts', + ` new (window as any).Hammer(document.body); - `); + `, + ); - await runMigration(); + await runMigration(); - expect(runner.tasks.some(t => t.name === 'node-package')).toBe(false); - expect(JSON.parse(tree.readContent('/package.json')).dependencies['hammerjs']) - .toBe('0.0.0'); - }); + expect(runner.tasks.some(t => t.name === 'node-package')).toBe(false); + expect(getDependencyVersion('hammerjs')).toBe('0.0.0'); + }, + ); describe('with custom gesture config', () => { beforeEach(() => { @@ -851,7 +1048,9 @@ describe('v9 HammerJS removal', () => { }); it('should not setup copied gesture config if hammer is used in template', async () => { - writeFile('/projects/cdk-testing/src/test.component.ts', dedent` + writeFile( + '/projects/cdk-testing/src/test.component.ts', + dedent` import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {CustomGestureConfig} from "../gesture-config"; @@ -865,11 +1064,15 @@ describe('v9 HammerJS removal', () => { ], }) export class TestModule {} - `); + `, + ); - writeFile('/projects/cdk-testing/src/app/app.component.html', ` + writeFile( + '/projects/cdk-testing/src/app/app.component.html', + ` - `); + `, + ); await runMigration(); @@ -892,9 +1095,13 @@ describe('v9 HammerJS removal', () => { export class TestModule {}`); }); - it('should warn if hammer is used in template and references to Material gesture config ' + - 'were detected', async () => { - writeFile('/projects/cdk-testing/src/test.component.ts', dedent` + it( + 'should warn if hammer is used in template and references to Material gesture config ' + + 'were detected', + async () => { + writeFile( + '/projects/cdk-testing/src/test.component.ts', + dedent` import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {CustomGestureConfig} from "../gesture-config"; @@ -908,7 +1115,8 @@ describe('v9 HammerJS removal', () => { ], }) export class TestModule {} - `); + `, + ); const subModuleFileContent = dedent` import {NgModule} from '@angular/core'; @@ -927,17 +1135,21 @@ describe('v9 HammerJS removal', () => { `; writeFile('/projects/cdk-testing/src/sub.module.ts', subModuleFileContent); - writeFile('/projects/cdk-testing/src/app/app.component.html', ` + writeFile( + '/projects/cdk-testing/src/app/app.component.html', + ` - `); + `, + ); const {logOutput} = await runMigration(); - expect(logOutput).toContain( - 'This target cannot be migrated completely. Please manually remove references ' + - 'to the deprecated Angular Material gesture config.'); - expect(runner.tasks.some(t => t.name === 'node-package')).toBe(false); - expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain('hammerjs'); + expect(logOutput).toContain( + 'This target cannot be migrated completely. Please manually remove references ' + + 'to the deprecated Angular Material gesture config.', + ); + expect(runner.tasks.some(t => t.name === 'node-package')).toBe(false); + expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain('hammerjs'); expect(tree.readContent('/projects/cdk-testing/src/test.component.ts')).toContain(dedent` import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; @@ -952,12 +1164,16 @@ describe('v9 HammerJS removal', () => { ], }) export class TestModule {}`); - expect(tree.readContent('/projects/cdk-testing/src/sub.module.ts')) - .toBe(subModuleFileContent); - }); + expect(tree.readContent('/projects/cdk-testing/src/sub.module.ts')).toBe( + subModuleFileContent, + ); + }, + ); it('should not remove hammerjs if no usage could be detected', async () => { - writeFile('/projects/cdk-testing/src/test.component.ts', dedent` + writeFile( + '/projects/cdk-testing/src/test.component.ts', + dedent` import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {CustomGestureConfig} from "../gesture-config"; @@ -971,9 +1187,12 @@ describe('v9 HammerJS removal', () => { ], }) export class TestModule {} - `); + `, + ); - writeFile('/projects/cdk-testing/src/sub.component.ts', dedent` + writeFile( + '/projects/cdk-testing/src/sub.component.ts', + dedent` import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {GestureConfig} from '@angular/material/core'; @@ -987,13 +1206,15 @@ describe('v9 HammerJS removal', () => { ], }) export class SubModule {} - `); + `, + ); const {logOutput} = await runMigration(); expect(logOutput).toContain( 'This target cannot be migrated completely, but all references to the ' + - 'deprecated Angular Material gesture have been removed.'); + 'deprecated Angular Material gesture have been removed.', + ); expect(runner.tasks.some(t => t.name === 'node-package')).toBe(false); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain('hammerjs'); expect(tree.readContent('/projects/cdk-testing/src/test.component.ts')).toContain(dedent` diff --git a/src/material/schematics/ng-update/test-cases/v9/misc/material-imports.spec.ts b/src/material/schematics/ng-update/test-cases/v9/misc/material-imports.spec.ts index 4cac96d67697..5ce27da652ed 100644 --- a/src/material/schematics/ng-update/test-cases/v9/misc/material-imports.spec.ts +++ b/src/material/schematics/ng-update/test-cases/v9/misc/material-imports.spec.ts @@ -1,19 +1,26 @@ -import {createTestCaseSetup, readFileContent, resolveBazelPath} from '@angular/cdk/schematics/testing'; -import {MIGRATION_PATH} from '../../../../index.spec'; +import { + createTestCaseSetup, + readFileContent, + resolveBazelPath, +} from '@angular/cdk/schematics/testing'; +import {MIGRATION_PATH} from '../../../../paths'; describe('v9 material imports', () => { - it('should re-map top-level material imports to the proper entry points when top-level ' + - '@angular/material package does not exist', async () => { - const {runFixers, appTree} = await createTestCaseSetup( - 'migration-v9', MIGRATION_PATH, - [resolveBazelPath(__dirname, './material-imports_input.ts')]); + it( + 'should re-map top-level material imports to the proper entry points when top-level ' + + '@angular/material package does not exist', + async () => { + const {runFixers, appTree} = await createTestCaseSetup('migration-v9', MIGRATION_PATH, [ + resolveBazelPath(__dirname, './material-imports_input.ts'), + ]); // Note: don't create a fake @angular/material package here, because // we're testing what would happen if it doesn't exist anymore. await runFixers(); - expect(appTree.readContent('/projects/cdk-testing/src/test-cases/material-imports_input.ts')) - .toBe(readFileContent( - resolveBazelPath(__dirname, './material-imports_expected_output.ts'))); - }); + expect( + appTree.readContent('/projects/cdk-testing/src/test-cases/material-imports_input.ts'), + ).toBe(readFileContent(resolveBazelPath(__dirname, './material-imports_expected_output.ts'))); + }, + ); }); diff --git a/src/material/schematics/ng-update/typescript/module-specifiers.ts b/src/material/schematics/ng-update/typescript/module-specifiers.ts index 37f95390b317..e0c5c2227844 100644 --- a/src/material/schematics/ng-update/typescript/module-specifiers.ts +++ b/src/material/schematics/ng-update/typescript/module-specifiers.ts @@ -26,12 +26,14 @@ export function isMaterialExportDeclaration(node: ts.Node) { } /** Whether the declaration is part of Angular Material. */ -function isMaterialDeclaration(declaration: ts.ImportDeclaration|ts.ExportDeclaration) { +function isMaterialDeclaration(declaration: ts.ImportDeclaration | ts.ExportDeclaration) { if (!declaration.moduleSpecifier) { return false; } const moduleSpecifier = declaration.moduleSpecifier.getText(); - return moduleSpecifier.indexOf(materialModuleSpecifier) !== -1 || - moduleSpecifier.indexOf(cdkModuleSpecifier) !== -1; + return ( + moduleSpecifier.indexOf(materialModuleSpecifier) !== -1 || + moduleSpecifier.indexOf(cdkModuleSpecifier) !== -1 + ); } diff --git a/src/material/schematics/ng-update/upgrade-data.ts b/src/material/schematics/ng-update/upgrade-data.ts index 58e8096f23de..5265d41fbb2f 100644 --- a/src/material/schematics/ng-update/upgrade-data.ts +++ b/src/material/schematics/ng-update/upgrade-data.ts @@ -17,6 +17,7 @@ import { methodCallChecks, outputNames, propertyNames, + symbolRemoval, } from './data'; /** Upgrade data that will be used for the Angular Material ng-update schematic. */ @@ -30,4 +31,5 @@ export const materialUpgradeData: UpgradeData = { methodCallChecks, outputNames, propertyNames, + symbolRemoval, }; diff --git a/src/material/schematics/package.json b/src/material/schematics/package.json new file mode 100644 index 000000000000..5bbefffbabee --- /dev/null +++ b/src/material/schematics/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/src/material/schematics/paths.ts b/src/material/schematics/paths.ts new file mode 100644 index 000000000000..30a13660cc2d --- /dev/null +++ b/src/material/schematics/paths.ts @@ -0,0 +1,15 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {join} from 'path'; + +/** Path to the schematic collection for non-migration schematics. */ +export const COLLECTION_PATH = join(__dirname, 'collection.json'); + +/** Path to the schematic collection that includes the migrations. */ +export const MIGRATION_PATH = join(__dirname, 'migration.json'); diff --git a/src/material/schematics/tsconfig.json b/src/material/schematics/tsconfig.json index edf4d3099ae4..d029d9ed59d1 100644 --- a/src/material/schematics/tsconfig.json +++ b/src/material/schematics/tsconfig.json @@ -6,10 +6,15 @@ "outDir": "../../../dist/packages/material/schematics", "noEmitOnError": false, "strictNullChecks": true, + "noImplicitOverride": true, + "noImplicitAny": true, + "noFallthroughCasesInSwitch": true, + "noImplicitThis": true, "noImplicitReturns": true, "skipDefaultLibCheck": true, "noUnusedLocals": false, "noUnusedParameters": false, + "strictFunctionTypes": true, "skipLibCheck": true, "sourceMap": true, "declaration": true, diff --git a/src/material/select/BUILD.bazel b/src/material/select/BUILD.bazel index aab394c625df..36b7feb82c8f 100644 --- a/src/material/select/BUILD.bazel +++ b/src/material/select/BUILD.bazel @@ -17,7 +17,6 @@ ng_module( exclude = ["**/*.spec.ts"], ), assets = [":select.css"] + glob(["**/*.html"]), - module_name = "@angular/material/select", deps = [ "//src:dev_mode_types", "//src/cdk/a11y", diff --git a/src/material/select/_select-legacy-index.scss b/src/material/select/_select-legacy-index.scss new file mode 100644 index 000000000000..c91010b78935 --- /dev/null +++ b/src/material/select/_select-legacy-index.scss @@ -0,0 +1,2 @@ +@forward 'select-theme' hide color, theme, typography; +@forward 'select-theme' as mat-select-* hide mat-select-density; diff --git a/src/material/select/_select-theme.import.scss b/src/material/select/_select-theme.import.scss new file mode 100644 index 000000000000..2a042325d99b --- /dev/null +++ b/src/material/select/_select-theme.import.scss @@ -0,0 +1,11 @@ +@forward '../core/style/form-common.import'; +@forward '../core/style/private.import'; +@forward '../core/typography/typography-utils.import'; +@forward 'select-theme' hide color, theme, typography; +@forward 'select-theme' as mat-select-* hide mat-select-density; + +@import '../core/theming/palette'; +@import '../core/theming/theming'; +@import '../core/style/private'; +@import '../core/style/form-common'; +@import '../core/typography/typography-utils'; diff --git a/src/material/select/_select-theme.scss b/src/material/select/_select-theme.scss index c64a029f682d..80fa5f54d4e7 100644 --- a/src/material/select/_select-theme.scss +++ b/src/material/select/_select-theme.scss @@ -1,99 +1,101 @@ -@import '../core/theming/palette'; -@import '../core/theming/theming'; -@import '../core/style/private'; -@import '../core/style/form-common'; -@import '../core/typography/typography-utils'; - - -@mixin mat-select-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $foreground: map-get($config, foreground); - $background: map-get($config, background); - $primary: map-get($config, primary); - $accent: map-get($config, accent); - $warn: map-get($config, warn); +@use 'sass:map'; +@use '../core/theming/theming'; +@use '../core/style/private'; +@use '../core/style/form-common'; +@use '../core/typography/typography'; +@use '../core/typography/typography-utils'; + + +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $foreground: map.get($config, foreground); + $background: map.get($config, background); + $primary: map.get($config, primary); + $accent: map.get($config, accent); + $warn: map.get($config, warn); .mat-select-value { - color: mat-color($foreground, text); + color: theming.get-color-from-palette($foreground, text); } .mat-select-placeholder { - color: mat-private-control-placeholder-color($config); + color: form-common.private-control-placeholder-color($config); } .mat-select-disabled .mat-select-value { - color: mat-color($foreground, disabled-text); + color: theming.get-color-from-palette($foreground, disabled-text); } .mat-select-arrow { - color: mat-color($foreground, secondary-text); + color: theming.get-color-from-palette($foreground, secondary-text); } .mat-select-panel { - background: mat-color($background, card); - @include mat-private-theme-overridable-elevation(4, $config); + background: theming.get-color-from-palette($background, card); + @include private.private-theme-overridable-elevation(4, $config); .mat-option.mat-selected:not(.mat-option-multiple) { - background: mat-color($background, hover, 0.12); + background: theming.get-color-from-palette($background, hover, 0.12); } } .mat-form-field { &.mat-focused { &.mat-primary .mat-select-arrow { - color: mat-color($primary, text); + color: theming.get-color-from-palette($primary, text); } &.mat-accent .mat-select-arrow { - color: mat-color($accent, text); + color: theming.get-color-from-palette($accent, text); } &.mat-warn .mat-select-arrow { - color: mat-color($warn, text); + color: theming.get-color-from-palette($warn, text); } } .mat-select.mat-select-invalid .mat-select-arrow { - color: mat-color($warn, text); + color: theming.get-color-from-palette($warn, text); } .mat-select.mat-select-disabled .mat-select-arrow { - color: mat-color($foreground, disabled-text); + color: theming.get-color-from-palette($foreground, disabled-text); } } } -@mixin mat-select-typography($config-or-theme) { - $config: mat-get-typography-config($config-or-theme); +@mixin typography($config-or-theme) { + $config: typography.private-typography-to-2014-config( + theming.get-typography-config($config-or-theme)); // The unit-less line-height from the font config. - $line-height: mat-line-height($config, input); + $line-height: typography-utils.line-height($config, input); .mat-select { - font-family: mat-font-family($config); + font-family: typography-utils.font-family($config); } .mat-select-trigger { - height: $line-height * 1em; + height: typography-utils.private-coerce-unitless-to-em($line-height); } } -@mixin _mat-select-density($config-or-theme) {} +@mixin _density($config-or-theme) {} -@mixin mat-select-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-select') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-select') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); @if $color != null { - @include mat-select-color($color); + @include color($color); } @if $density != null { - @include _mat-select-density($density); + @include _density($density); } @if $typography != null { - @include mat-select-typography($typography); + @include typography($typography); } } } diff --git a/src/material/select/public-api.ts b/src/material/select/public-api.ts index a89d7fe23e80..c8ffac72b453 100644 --- a/src/material/select/public-api.ts +++ b/src/material/select/public-api.ts @@ -7,5 +7,16 @@ */ export * from './select-module'; -export * from './select'; export * from './select-animations'; +export { + MAT_SELECT_SCROLL_STRATEGY, + MAT_SELECT_SCROLL_STRATEGY_PROVIDER_FACTORY, + MatSelectConfig, + MAT_SELECT_CONFIG, + MAT_SELECT_SCROLL_STRATEGY_PROVIDER, + MatSelectChange, + MAT_SELECT_TRIGGER, + _MatSelectBase, + MatSelect, + MatSelectTrigger, +} from './select'; diff --git a/src/material/select/select-animations.ts b/src/material/select/select-animations.ts index 88e30eff7262..127628c3609a 100644 --- a/src/material/select/select-animations.ts +++ b/src/material/select/select-animations.ts @@ -34,8 +34,7 @@ export const matSelectAnimations: { * This is needed due to https://github.com/angular/angular/issues/23302 */ transformPanelWrap: trigger('transformPanelWrap', [ - transition('* => void', query('@transformPanel', [animateChild()], - {optional: true})) + transition('* => void', query('@transformPanel', [animateChild()], {optional: true})), ]), /** @@ -48,22 +47,31 @@ export const matSelectAnimations: { * When the panel is removed from the DOM, it simply fades out linearly. */ transformPanel: trigger('transformPanel', [ - state('void', style({ - transform: 'scaleY(0.8)', - minWidth: '100%', - opacity: 0 - })), - state('showing', style({ - opacity: 1, - minWidth: 'calc(100% + 32px)', // 32px = 2 * 16px padding - transform: 'scaleY(1)' - })), - state('showing-multiple', style({ - opacity: 1, - minWidth: 'calc(100% + 64px)', // 64px = 48px padding on the left + 16px padding on the right - transform: 'scaleY(1)' - })), + state( + 'void', + style({ + transform: 'scaleY(0.8)', + minWidth: '100%', + opacity: 0, + }), + ), + state( + 'showing', + style({ + opacity: 1, + minWidth: 'calc(100% + 32px)', // 32px = 2 * 16px padding + transform: 'scaleY(1)', + }), + ), + state( + 'showing-multiple', + style({ + opacity: 1, + minWidth: 'calc(100% + 64px)', // 64px = 48px padding on the left + 16px padding on the right + transform: 'scaleY(1)', + }), + ), transition('void => *', animate('120ms cubic-bezier(0, 0, 0.2, 1)')), - transition('* => void', animate('100ms 25ms linear', style({opacity: 0}))) - ]) + transition('* => void', animate('100ms 25ms linear', style({opacity: 0}))), + ]), }; diff --git a/src/material/select/select-module.ts b/src/material/select/select-module.ts index 994ff0115841..9f8158100dc1 100644 --- a/src/material/select/select-module.ts +++ b/src/material/select/select-module.ts @@ -14,23 +14,17 @@ import {MatFormFieldModule} from '@angular/material/form-field'; import {CdkScrollableModule} from '@angular/cdk/scrolling'; import {MAT_SELECT_SCROLL_STRATEGY_PROVIDER, MatSelect, MatSelectTrigger} from './select'; - @NgModule({ - imports: [ - CommonModule, - OverlayModule, - MatOptionModule, - MatCommonModule, - ], + imports: [CommonModule, OverlayModule, MatOptionModule, MatCommonModule], exports: [ CdkScrollableModule, MatFormFieldModule, MatSelect, MatSelectTrigger, MatOptionModule, - MatCommonModule + MatCommonModule, ], declarations: [MatSelect, MatSelectTrigger], - providers: [MAT_SELECT_SCROLL_STRATEGY_PROVIDER] + providers: [MAT_SELECT_SCROLL_STRATEGY_PROVIDER], }) export class MatSelectModule {} diff --git a/src/material/select/select.html b/src/material/select/select.html index a0c66b30ac8d..196aa483ccef 100644 --- a/src/material/select/select.html +++ b/src/material/select/select.html @@ -14,9 +14,9 @@ #origin="cdkOverlayOrigin" #trigger>
- {{placeholder || '\u00A0'}} + {{placeholder}} - {{triggerValue || '\u00A0'}} + {{triggerValue}}
diff --git a/src/material/select/select.md b/src/material/select/select.md index 6193bb2b521b..ea4b172ff4e9 100644 --- a/src/material/select/select.md +++ b/src/material/select/select.md @@ -13,8 +13,8 @@ Angular Material also supports use of the native `` element. +To use a native select inside ``, import `MatInputModule` and add the +`matNativeControl` attribute to the `` offers the best accessibility because it is supported directly by screen-readers. +When possible, prefer a native ` - if (!manager.isTyping() && (isOpenKey && !hasModifierKey(event)) || - ((this.multiple || event.altKey) && isArrowKey)) { + if ( + (!manager.isTyping() && isOpenKey && !hasModifierKey(event)) || + ((this.multiple || event.altKey) && isArrowKey) + ) { event.preventDefault(); // prevents the page from scrolling down when pressing space this.open(); } else if (!this.multiple) { @@ -734,8 +752,12 @@ export abstract class _MatSelectBase extends _MatSelectMixinBase implements A this.close(); // Don't do anything in this case if the user is typing, // because the typing sequence can include the space key. - } else if (!isTyping && (keyCode === ENTER || keyCode === SPACE) && manager.activeItem && - !hasModifierKey(event)) { + } else if ( + !isTyping && + (keyCode === ENTER || keyCode === SPACE) && + manager.activeItem && + !hasModifierKey(event) + ) { event.preventDefault(); manager.activeItem._selectViaInteraction(); } else if (!isTyping && this._multiple && keyCode === A && event.ctrlKey) { @@ -752,8 +774,13 @@ export abstract class _MatSelectBase extends _MatSelectMixinBase implements A manager.onKeydown(event); - if (this._multiple && isArrowKey && event.shiftKey && manager.activeItem && - manager.activeItemIndex !== previouslyFocusedIndex) { + if ( + this._multiple && + isArrowKey && + event.shiftKey && + manager.activeItem && + manager.activeItemIndex !== previouslyFocusedIndex + ) { manager.activeItem._selectViaInteraction(); } } @@ -784,7 +811,7 @@ export abstract class _MatSelectBase extends _MatSelectMixinBase implements A * Callback that is invoked when the overlay panel has been attached. */ _onAttached(): void { - this.overlayDir.positionChange.pipe(take(1)).subscribe(() => { + this._overlayDir.positionChange.pipe(take(1)).subscribe(() => { this._changeDetectorRef.detectChanges(); this._positioningSettled(); }); @@ -847,9 +874,15 @@ export abstract class _MatSelectBase extends _MatSelectMixinBase implements A */ private _selectValue(value: any): MatOption | undefined { const correspondingOption = this.options.find((option: MatOption) => { + // Skip options that are already in the model. This allows us to handle cases + // where the same primitive value is selected multiple times. + if (this._selectionModel.isSelected(option)) { + return false; + } + try { // Treat null as a special reset value. - return option.value != null && this._compareWith(option.value, value); + return option.value != null && this._compareWith(option.value, value); } catch (error) { if (typeof ngDevMode === 'undefined' || ngDevMode) { // Notify developers of errors in their comparator. @@ -935,8 +968,9 @@ export abstract class _MatSelectBase extends _MatSelectMixinBase implements A } } else { if (wasSelected !== option.selected) { - option.selected ? this._selectionModel.select(option) : - this._selectionModel.deselect(option); + option.selected + ? this._selectionModel.select(option) + : this._selectionModel.deselect(option); } if (isUserInput) { @@ -969,8 +1003,9 @@ export abstract class _MatSelectBase extends _MatSelectMixinBase implements A const options = this.options.toArray(); this._selectionModel.sort((a, b) => { - return this.sortComparator ? this.sortComparator(a, b, options) : - options.indexOf(a) - options.indexOf(b); + return this.sortComparator + ? this.sortComparator(a, b, options) + : options.indexOf(a) - options.indexOf(b); }); this.stateChanges.next(); } @@ -1023,8 +1058,9 @@ export abstract class _MatSelectBase extends _MatSelectMixinBase implements A return null; } - const labelId = this._getLabelId(); - return this.ariaLabelledby ? labelId + ' ' + this.ariaLabelledby : labelId; + const labelId = this._parentFormField?.getLabelId(); + const labelExpression = labelId ? labelId + ' ' : ''; + return this.ariaLabelledby ? labelExpression + this.ariaLabelledby : labelId; } /** Determines the `aria-activedescendant` to be set on the host. */ @@ -1036,18 +1072,14 @@ export abstract class _MatSelectBase extends _MatSelectMixinBase implements A return null; } - /** Gets the ID of the element that is labelling the select. */ - private _getLabelId(): string { - return this._parentFormField?.getLabelId() || ''; - } - /** Gets the aria-labelledby of the select component trigger. */ private _getTriggerAriaLabelledby(): string | null { if (this.ariaLabel) { return null; } - let value = this._getLabelId() + ' ' + this._valueId; + const labelId = this._parentFormField?.getLabelId(); + let value = (labelId ? labelId + ' ' : '') + this._valueId; if (this.ariaLabelledby) { value += ' ' + this.ariaLabelledby; @@ -1083,16 +1115,8 @@ export abstract class _MatSelectBase extends _MatSelectMixinBase implements A * @docs-private */ get shouldLabelFloat(): boolean { - return this._panelOpen || !this.empty; + return this._panelOpen || !this.empty || (this._focused && !!this._placeholder); } - - static ngAcceptInputType_required: BooleanInput; - static ngAcceptInputType_multiple: BooleanInput; - static ngAcceptInputType_disableOptionCentering: BooleanInput; - static ngAcceptInputType_typeaheadDebounceInterval: NumberInput; - static ngAcceptInputType_disabled: BooleanInput; - static ngAcceptInputType_disableRipple: BooleanInput; - static ngAcceptInputType_tabIndex: NumberInput; } @Component({ @@ -1130,13 +1154,10 @@ export abstract class _MatSelectBase extends _MatSelectMixinBase implements A '(focus)': '_onFocus()', '(blur)': '_onBlur()', }, - animations: [ - matSelectAnimations.transformPanelWrap, - matSelectAnimations.transformPanel - ], + animations: [matSelectAnimations.transformPanelWrap, matSelectAnimations.transformPanel], providers: [ {provide: MatFormFieldControl, useExisting: MatSelect}, - {provide: MAT_OPTION_PARENT_COMPONENT, useExisting: MatSelect} + {provide: MAT_OPTION_PARENT_COMPONENT, useExisting: MatSelect}, ], }) export class MatSelect extends _MatSelectBase implements OnInit { @@ -1187,8 +1208,7 @@ export class MatSelect extends _MatSelectBase implements OnInit * too high or too low in the panel to be scrolled to the center, it clamps the * scroll position to the min or max scroll positions respectively. */ - _calculateOverlayScroll(selectedIndex: number, scrollBuffer: number, - maxScroll: number): number { + _calculateOverlayScroll(selectedIndex: number, scrollBuffer: number, maxScroll: number): number { const itemHeight = this._getItemHeight(); const optionOffsetFromScrollTop = itemHeight * selectedIndex; const halfOptionHeight = itemHeight / 2; @@ -1201,31 +1221,38 @@ export class MatSelect extends _MatSelectBase implements OnInit return Math.min(Math.max(0, optimalScrollPosition), maxScroll); } - ngOnInit() { + override ngOnInit() { super.ngOnInit(); - this._viewportRuler.change().pipe(takeUntil(this._destroy)).subscribe(() => { - if (this.panelOpen) { - this._triggerRect = this.trigger.nativeElement.getBoundingClientRect(); - this._changeDetectorRef.markForCheck(); - } - }); + this._viewportRuler + .change() + .pipe(takeUntil(this._destroy)) + .subscribe(() => { + if (this.panelOpen) { + this._triggerRect = this.trigger.nativeElement.getBoundingClientRect(); + this._changeDetectorRef.markForCheck(); + } + }); } - open(): void { + override open(): void { if (super._canOpen()) { super.open(); this._triggerRect = this.trigger.nativeElement.getBoundingClientRect(); // Note: The computed font-size will be a string pixel value (e.g. "16px"). // `parseInt` ignores the trailing 'px' and converts this to a number. - this._triggerFontSize = - parseInt(getComputedStyle(this.trigger.nativeElement).fontSize || '0'); + this._triggerFontSize = parseInt( + getComputedStyle(this.trigger.nativeElement).fontSize || '0', + ); this._calculateOverlayPosition(); // Set the font size on the panel element once it exists. this._ngZone.onStable.pipe(take(1)).subscribe(() => { - if (this._triggerFontSize && this.overlayDir.overlayRef && - this.overlayDir.overlayRef.overlayElement) { - this.overlayDir.overlayRef.overlayElement.style.fontSize = `${this._triggerFontSize}px`; + if ( + this._triggerFontSize && + this._overlayDir.overlayRef && + this._overlayDir.overlayRef.overlayElement + ) { + this._overlayDir.overlayRef.overlayElement.style.fontSize = `${this._triggerFontSize}px`; } }); } @@ -1236,12 +1263,19 @@ export class MatSelect extends _MatSelectBase implements OnInit const labelCount = _countGroupLabelsBeforeOption(index, this.options, this.optionGroups); const itemHeight = this._getItemHeight(); - this.panel.nativeElement.scrollTop = _getOptionScrollPosition( - (index + labelCount) * itemHeight, - itemHeight, - this.panel.nativeElement.scrollTop, - SELECT_PANEL_MAX_HEIGHT - ); + if (index === 0 && labelCount === 1) { + // If we've got one group label before the option and we're at the top option, + // scroll the list to the top. This is better UX than scrolling the list to the + // top of the option, because it allows the user to read the top group's label. + this.panel.nativeElement.scrollTop = 0; + } else { + this.panel.nativeElement.scrollTop = _getOptionScrollPosition( + (index + labelCount) * itemHeight, + itemHeight, + this.panel.nativeElement.scrollTop, + SELECT_PANEL_MAX_HEIGHT, + ); + } } protected _positioningSettled() { @@ -1249,11 +1283,11 @@ export class MatSelect extends _MatSelectBase implements OnInit this.panel.nativeElement.scrollTop = this._scrollTop; } - protected _panelDoneAnimating(isOpen: boolean) { + protected override _panelDoneAnimating(isOpen: boolean) { if (this.panelOpen) { this._scrollTop = 0; } else { - this.overlayDir.offsetX = 0; + this._overlayDir.offsetX = 0; this._changeDetectorRef.markForCheck(); } @@ -1272,16 +1306,19 @@ export class MatSelect extends _MatSelectBase implements OnInit * content width in order to constrain the panel within the viewport. */ private _calculateOverlayOffsetX(): void { - const overlayRect = this.overlayDir.overlayRef.overlayElement.getBoundingClientRect(); + const overlayRect = this._overlayDir.overlayRef.overlayElement.getBoundingClientRect(); const viewportSize = this._viewportRuler.getViewportSize(); const isRtl = this._isRtl(); - const paddingWidth = this.multiple ? SELECT_MULTIPLE_PANEL_PADDING_X + SELECT_PANEL_PADDING_X : - SELECT_PANEL_PADDING_X * 2; + const paddingWidth = this.multiple + ? SELECT_MULTIPLE_PANEL_PADDING_X + SELECT_PANEL_PADDING_X + : SELECT_PANEL_PADDING_X * 2; let offsetX: number; // Adjust the offset, depending on the option padding. if (this.multiple) { offsetX = SELECT_MULTIPLE_PANEL_PADDING_X; + } else if (this.disableOptionCentering) { + offsetX = SELECT_PANEL_PADDING_X; } else { let selected = this._selectionModel.selected[0] || this.options.first; offsetX = selected && selected.group ? SELECT_PANEL_INDENT_PADDING_X : SELECT_PANEL_PADDING_X; @@ -1294,8 +1331,8 @@ export class MatSelect extends _MatSelectBase implements OnInit // Determine how much the select overflows on each side. const leftOverflow = 0 - (overlayRect.left + offsetX - (isRtl ? paddingWidth : 0)); - const rightOverflow = overlayRect.right + offsetX - viewportSize.width - + (isRtl ? 0 : paddingWidth); + const rightOverflow = + overlayRect.right + offsetX - viewportSize.width + (isRtl ? 0 : paddingWidth); // If the element overflows on either side, reduce the offset to allow it to fit. if (leftOverflow > 0) { @@ -1307,8 +1344,8 @@ export class MatSelect extends _MatSelectBase implements OnInit // Set the offset directly in order to avoid having to go through change detection and // potentially triggering "changed after it was checked" errors. Round the value to avoid // blurry content in some browsers. - this.overlayDir.offsetX = Math.round(offsetX); - this.overlayDir.overlayRef.updatePosition(); + this._overlayDir.offsetX = Math.round(offsetX); + this._overlayDir.overlayRef.updatePosition(); } /** @@ -1316,8 +1353,11 @@ export class MatSelect extends _MatSelectBase implements OnInit * top start corner of the trigger. It has to be adjusted in order for the * selected option to be aligned over the trigger when the panel opens. */ - private _calculateOverlayOffsetY(selectedIndex: number, scrollBuffer: number, - maxScroll: number): number { + private _calculateOverlayOffsetY( + selectedIndex: number, + scrollBuffer: number, + maxScroll: number, + ): number { const itemHeight = this._getItemHeight(); const optionHeightAdjustment = (itemHeight - this._triggerRect.height) / 2; const maxOptionsDisplayed = Math.floor(SELECT_PANEL_MAX_HEIGHT / itemHeight); @@ -1337,7 +1377,7 @@ export class MatSelect extends _MatSelectBase implements OnInit // The first item is partially out of the viewport. Therefore we need to calculate what // portion of it is shown in the viewport and account for it in our offset. let partialItemHeight = - itemHeight - (this._getItemCount() * itemHeight - SELECT_PANEL_MAX_HEIGHT) % itemHeight; + itemHeight - ((this._getItemCount() * itemHeight - SELECT_PANEL_MAX_HEIGHT) % itemHeight); // Because the panel height is longer than the height of the options alone, // there is always extra padding at the top or bottom of the panel. When @@ -1369,17 +1409,16 @@ export class MatSelect extends _MatSelectBase implements OnInit const topSpaceAvailable = this._triggerRect.top - SELECT_PANEL_VIEWPORT_PADDING; const bottomSpaceAvailable = - viewportSize.height - this._triggerRect.bottom - SELECT_PANEL_VIEWPORT_PADDING; + viewportSize.height - this._triggerRect.bottom - SELECT_PANEL_VIEWPORT_PADDING; const panelHeightTop = Math.abs(this._offsetY); - const totalPanelHeight = - Math.min(this._getItemCount() * itemHeight, SELECT_PANEL_MAX_HEIGHT); + const totalPanelHeight = Math.min(this._getItemCount() * itemHeight, SELECT_PANEL_MAX_HEIGHT); const panelHeightBottom = totalPanelHeight - panelHeightTop - this._triggerRect.height; if (panelHeightBottom > bottomSpaceAvailable) { this._adjustPanelUp(panelHeightBottom, bottomSpaceAvailable); } else if (panelHeightTop > topSpaceAvailable) { - this._adjustPanelDown(panelHeightTop, topSpaceAvailable, maxScroll); + this._adjustPanelDown(panelHeightTop, topSpaceAvailable, maxScroll); } else { this._transformOrigin = this._getOriginBasedOnOption(); } @@ -1407,8 +1446,7 @@ export class MatSelect extends _MatSelectBase implements OnInit } /** Adjusts the overlay panel down to fit in the viewport. */ - private _adjustPanelDown(panelHeightTop: number, topSpaceAvailable: number, - maxScroll: number) { + private _adjustPanelDown(panelHeightTop: number, topSpaceAvailable: number, maxScroll: number) { // Browsers ignore fractional scroll offsets, so we need to round. const distanceAboveViewport = Math.round(panelHeightTop - topSpaceAvailable); @@ -1445,12 +1483,17 @@ export class MatSelect extends _MatSelectBase implements OnInit if (this.empty) { selectedOptionOffset = 0; } else { - selectedOptionOffset = - Math.max(this.options.toArray().indexOf(this._selectionModel.selected[0]), 0); + selectedOptionOffset = Math.max( + this.options.toArray().indexOf(this._selectionModel.selected[0]), + 0, + ); } - selectedOptionOffset += _countGroupLabelsBeforeOption(selectedOptionOffset, this.options, - this.optionGroups); + selectedOptionOffset += _countGroupLabelsBeforeOption( + selectedOptionOffset, + this.options, + this.optionGroups, + ); // We must maintain a scroll buffer so the selected option will be scrolled to the // center of the overlay panel rather than the top. @@ -1478,5 +1521,4 @@ export class MatSelect extends _MatSelectBase implements OnInit private _getItemCount(): number { return this.options.length + this.optionGroups.length; } - } diff --git a/src/material/select/testing/BUILD.bazel b/src/material/select/testing/BUILD.bazel index de9dbd5ed71c..7e6c42c6131a 100644 --- a/src/material/select/testing/BUILD.bazel +++ b/src/material/select/testing/BUILD.bazel @@ -8,7 +8,6 @@ ts_library( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material/select/testing", deps = [ "//src/cdk/coercion", "//src/cdk/testing", diff --git a/src/material/select/testing/select-harness.ts b/src/material/select/testing/select-harness.ts index 910bd31fdd27..3054a84b83d7 100644 --- a/src/material/select/testing/select-harness.ts +++ b/src/material/select/testing/select-harness.ts @@ -6,7 +6,13 @@ * found in the LICENSE file at https://angular.io/license */ -import {HarnessPredicate, parallel} from '@angular/cdk/testing'; +import { + HarnessPredicate, + parallel, + ComponentHarness, + BaseHarnessFilters, + ComponentHarnessConstructor, +} from '@angular/cdk/testing'; import {MatFormFieldControlHarness} from '@angular/material/form-field/testing/control'; import { MatOptionHarness, @@ -16,29 +22,27 @@ import { } from '@angular/material/core/testing'; import {SelectHarnessFilters} from './select-harness-filters'; - -/** Harness for interacting with a standard mat-select in tests. */ -export class MatSelectHarness extends MatFormFieldControlHarness { +export abstract class _MatSelectHarnessBase< + OptionType extends ComponentHarnessConstructor - ` + `, }) class SelectHarnessTest { formControl = new FormControl(undefined, [Validators.required]); @@ -292,8 +302,8 @@ class SelectHarnessTest { {code: 'KS', name: 'Kansas'}, {code: 'KY', name: 'Kentucky'}, {code: 'LA', name: 'Louisiana'}, - {code: 'ME', name: 'Maine'} - ] + {code: 'ME', name: 'Maine'}, + ], }, { name: 'Two', @@ -303,7 +313,7 @@ class SelectHarnessTest { {code: 'SD', name: 'South Dakota'}, {code: 'TN', name: 'Tennessee'}, {code: 'TX', name: 'Texas'}, - ] + ], }, { name: 'Three', @@ -311,8 +321,8 @@ class SelectHarnessTest { {code: 'UT', name: 'Utah'}, {code: 'WA', name: 'Washington'}, {code: 'WV', name: 'West Virginia'}, - {code: 'WI', name: 'Wisconsin'} - ] - } + {code: 'WI', name: 'Wisconsin'}, + ], + }, ]; } diff --git a/src/material/sidenav/BUILD.bazel b/src/material/sidenav/BUILD.bazel index 9e56904f7a8c..4f155023f5f5 100644 --- a/src/material/sidenav/BUILD.bazel +++ b/src/material/sidenav/BUILD.bazel @@ -19,7 +19,6 @@ ng_module( exclude = ["**/*.spec.ts"], ), assets = [":drawer.css"] + glob(["**/*.html"]), - module_name = "@angular/material/sidenav", deps = [ "//src:dev_mode_types", "//src/cdk/a11y", diff --git a/src/material/sidenav/_sidenav-legacy-index.scss b/src/material/sidenav/_sidenav-legacy-index.scss new file mode 100644 index 000000000000..a33c0cc10330 --- /dev/null +++ b/src/material/sidenav/_sidenav-legacy-index.scss @@ -0,0 +1,2 @@ +@forward 'sidenav-theme' hide color, theme, typography; +@forward 'sidenav-theme' as mat-sidenav-* hide mat-sidenav-density; diff --git a/src/material/sidenav/_sidenav-theme.import.scss b/src/material/sidenav/_sidenav-theme.import.scss new file mode 100644 index 000000000000..7280dbcf548a --- /dev/null +++ b/src/material/sidenav/_sidenav-theme.import.scss @@ -0,0 +1,8 @@ +@forward '../core/style/private.import'; +@forward '../core/theming/theming.import'; +@forward 'sidenav-theme' hide color, theme, typography; +@forward 'sidenav-theme' as mat-sidenav-* hide mat-sidenav-density; + +@import '../core/style/private'; +@import '../core/theming/palette'; +@import '../core/theming/theming'; diff --git a/src/material/sidenav/_sidenav-theme.scss b/src/material/sidenav/_sidenav-theme.scss index 6360584afad1..a0b2726c6e9b 100644 --- a/src/material/sidenav/_sidenav-theme.scss +++ b/src/material/sidenav/_sidenav-theme.scss @@ -1,28 +1,30 @@ -@import '../core/style/private'; -@import '../core/theming/palette'; -@import '../core/theming/theming'; - -@mixin mat-sidenav-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $primary: map-get($config, primary); - $accent: map-get($config, accent); - $warn: map-get($config, warn); - $background: map-get($config, background); - $foreground: map-get($config, foreground); - - $drawer-background-color: mat-color($background, dialog); - $drawer-container-background-color: mat-color($background, background); - $drawer-push-background-color: mat-color($background, dialog); - $drawer-side-border: solid 1px mat-color($foreground, divider); +@use 'sass:color'; +@use 'sass:map'; +@use 'sass:meta'; +@use '../core/style/private'; +@use '../core/theming/theming'; + +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $primary: map.get($config, primary); + $accent: map.get($config, accent); + $warn: map.get($config, warn); + $background: map.get($config, background); + $foreground: map.get($config, foreground); + + $drawer-background-color: theming.get-color-from-palette($background, dialog); + $drawer-container-background-color: theming.get-color-from-palette($background, background); + $drawer-push-background-color: theming.get-color-from-palette($background, dialog); + $drawer-side-border: solid 1px theming.get-color-from-palette($foreground, divider); .mat-drawer-container { background-color: $drawer-container-background-color; - color: mat-color($foreground, text); + color: theming.get-color-from-palette($foreground, text); } .mat-drawer { background-color: $drawer-background-color; - color: mat-color($foreground, text); + color: theming.get-color-from-palette($foreground, text); &.mat-drawer-push { background-color: $drawer-push-background-color; @@ -31,7 +33,7 @@ &:not(.mat-drawer-side) { // The elevation of z-16 is noted in the design specifications. // See https://material.io/design/components/navigation-drawer.html - @include mat-private-theme-elevation(16, $config); + @include private.private-theme-elevation(16, $config); } } @@ -56,13 +58,13 @@ .mat-drawer-backdrop.mat-drawer-shown { $opacity: 0.6; - $backdrop-color: mat-color($background, card, $opacity); + $backdrop-color: theming.get-color-from-palette($background, card, $opacity); - @if (type-of($backdrop-color) == color) { + @if (meta.type-of($backdrop-color) == color) { // We use invert() here to have the darken the background color expected to be used. If the // background is light, we use a dark backdrop. If the background is dark, // we use a light backdrop. - background-color: invert($backdrop-color); + background-color: color.invert($backdrop-color); } @else { // If we couldn't resolve the backdrop color to a color value, fall back to using @@ -73,25 +75,25 @@ } } -@mixin mat-sidenav-typography($config-or-theme) {} +@mixin typography($config-or-theme) {} -@mixin _mat-sidenav-density($config-or-theme) {} +@mixin _density($config-or-theme) {} -@mixin mat-sidenav-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-sidenav') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-sidenav') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); @if $color != null { - @include mat-sidenav-color($color); + @include color($color); } @if $density != null { - @include _mat-sidenav-density($density); + @include _density($density); } @if $typography != null { - @include mat-sidenav-typography($typography); + @include typography($typography); } } } diff --git a/src/material/sidenav/drawer-animations.ts b/src/material/sidenav/drawer-animations.ts index 2efa2d7390cc..a321d515e73f 100644 --- a/src/material/sidenav/drawer-animations.ts +++ b/src/material/sidenav/drawer-animations.ts @@ -27,17 +27,25 @@ export const matDrawerAnimations: { // 1. Having a transform can cause elements with ripples or an animated // transform to shift around in Chrome with an RTL layout (see #10023). // 2. 3d transforms causes text to appear blurry on IE and Edge. - state('open, open-instant', style({ - 'transform': 'none', - 'visibility': 'visible', - })), - state('void', style({ - // Avoids the shadow showing up when closed in SSR. - 'box-shadow': 'none', - 'visibility': 'hidden', - })), + state( + 'open, open-instant', + style({ + 'transform': 'none', + 'visibility': 'visible', + }), + ), + state( + 'void', + style({ + // Avoids the shadow showing up when closed in SSR. + 'box-shadow': 'none', + 'visibility': 'hidden', + }), + ), transition('void => open-instant', animate('0ms')), - transition('void <=> open, open-instant => void', - animate('400ms cubic-bezier(0.25, 0.8, 0.25, 1)')) - ]) + transition( + 'void <=> open, open-instant => void', + animate('400ms cubic-bezier(0.25, 0.8, 0.25, 1)'), + ), + ]), }; diff --git a/src/material/sidenav/drawer.html b/src/material/sidenav/drawer.html index 3ff215408cf7..9e7cb52395ba 100644 --- a/src/material/sidenav/drawer.html +++ b/src/material/sidenav/drawer.html @@ -1,3 +1,3 @@ -
+
diff --git a/src/material/sidenav/drawer.scss b/src/material/sidenav/drawer.scss index 97f859122245..01ed6fcf94ed 100644 --- a/src/material/sidenav/drawer.scss +++ b/src/material/sidenav/drawer.scss @@ -1,18 +1,15 @@ -@import '../core/style/variables'; -@import '../core/style/layout-common'; -@import '../core/style/vendor-prefixes'; -@import '../../cdk/a11y/a11y'; +@use '../core/style/variables'; +@use '../core/style/layout-common'; +@use '../../cdk/a11y'; -$mat-drawer-content-z-index: 1; -$mat-drawer-side-drawer-z-index: 2; -$mat-drawer-backdrop-z-index: 3; -$mat-drawer-over-drawer-z-index: 4; +$drawer-content-z-index: 1; +$drawer-side-drawer-z-index: 2; +$drawer-backdrop-z-index: 3; +$drawer-over-drawer-z-index: 4; -// stylelint-disable max-line-length // Mixin that creates a new stacking context. // see https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context -// stylelint-enable -@mixin mat-drawer-stacking-context($z-index: 1) { +@mixin drawer-stacking-context($z-index: 1) { position: relative; // Use a z-index to create a new stacking context. (We can't use transform because it breaks fixed @@ -25,7 +22,7 @@ $mat-drawer-over-drawer-z-index: 4; // MatDrawerContainer. This creates a new z-index stack so we use low numbered z-indices. // We create another stacking context in the '.mat-drawer-content' and in each drawer so that // the application content does not get messed up with our own CSS. - @include mat-drawer-stacking-context(); + @include drawer-stacking-context(); box-sizing: border-box; -webkit-overflow-scrolling: touch; @@ -38,7 +35,7 @@ $mat-drawer-over-drawer-z-index: 4; // TODO(hansl): Update this with a more robust solution. &[fullscreen] { - @include mat-fill(); + @include layout-common.fill(); &.mat-drawer-container-has-open { overflow: hidden; @@ -48,7 +45,7 @@ $mat-drawer-over-drawer-z-index: 4; // When the consumer explicitly enabled the backdrop, // we have to pull the side drawers above it. &.mat-drawer-container-explicit-backdrop .mat-drawer-side { - z-index: $mat-drawer-backdrop-z-index; + z-index: $drawer-backdrop-z-index; } // Note that the `NoopAnimationsModule` is being handled inside of the component code. @@ -60,13 +57,13 @@ $mat-drawer-over-drawer-z-index: 4; } .mat-drawer-backdrop { - @include mat-fill(); + @include layout-common.fill(); display: block; // Because of the new stacking context, the z-index stack is new and we can use our own // numbers. - z-index: $mat-drawer-backdrop-z-index; + z-index: $drawer-backdrop-z-index; // We use 'visibility: hidden | visible' because 'display: none' will not animate any // transitions, while visibility will interpolate transitions properly. @@ -80,19 +77,19 @@ $mat-drawer-over-drawer-z-index: 4; .mat-drawer-transition & { transition: { - duration: $swift-ease-out-duration; - timing-function: $swift-ease-out-timing-function; + duration: variables.$swift-ease-out-duration; + timing-function: variables.$swift-ease-out-timing-function; property: background-color, visibility; } } - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { opacity: 0.5; } } .mat-drawer-content { - @include mat-drawer-stacking-context($mat-drawer-content-z-index); + @include drawer-stacking-context($drawer-content-z-index); display: block; height: 100%; @@ -100,8 +97,8 @@ $mat-drawer-over-drawer-z-index: 4; .mat-drawer-transition & { transition: { - duration: $swift-ease-out-duration; - timing-function: $swift-ease-out-timing-function; + duration: variables.$swift-ease-out-duration; + timing-function: variables.$swift-ease-out-timing-function; property: transform, margin-left, margin-right; } } @@ -110,7 +107,7 @@ $mat-drawer-over-drawer-z-index: 4; .mat-drawer { $high-contrast-border: solid 1px currentColor; - @include mat-drawer-stacking-context($mat-drawer-over-drawer-z-index); + @include drawer-stacking-context($drawer-over-drawer-z-index); display: block; position: absolute; @@ -123,20 +120,20 @@ $mat-drawer-over-drawer-z-index: 4; transform: translate3d(-100%, 0, 0); &, [dir='rtl'] &.mat-drawer-end { - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { border-right: $high-contrast-border; } } [dir='rtl'] &, &.mat-drawer-end { - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { border-left: $high-contrast-border; border-right: none; } } &.mat-drawer-side { - z-index: $mat-drawer-side-drawer-z-index; + z-index: $drawer-side-drawer-z-index; } &.mat-drawer-end { diff --git a/src/material/sidenav/drawer.spec.ts b/src/material/sidenav/drawer.spec.ts index 892a0cb69fc1..5417122de04e 100644 --- a/src/material/sidenav/drawer.spec.ts +++ b/src/material/sidenav/drawer.spec.ts @@ -16,35 +16,32 @@ import {Direction} from '@angular/cdk/bidi'; import {A11yModule} from '@angular/cdk/a11y'; import {PlatformModule, Platform} from '@angular/cdk/platform'; import {ESCAPE} from '@angular/cdk/keycodes'; -import { - dispatchKeyboardEvent, - createKeyboardEvent, - dispatchEvent, -} from '@angular/cdk/testing/private'; +import {dispatchKeyboardEvent, createKeyboardEvent, dispatchEvent} from '../../cdk/testing/private'; import {CdkScrollable} from '@angular/cdk/scrolling'; import {CommonModule} from '@angular/common'; - describe('MatDrawer', () => { - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatSidenavModule, A11yModule, PlatformModule, NoopAnimationsModule, CommonModule], - declarations: [ - BasicTestApp, - DrawerContainerNoDrawerTestApp, - DrawerSetToOpenedFalse, - DrawerSetToOpenedTrue, - DrawerDynamicPosition, - DrawerWithFocusableElements, - DrawerOpenBinding, - DrawerWithoutFocusableElements, - IndirectDescendantDrawer, - NestedDrawerContainers, - ], - }); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatSidenavModule, A11yModule, PlatformModule, NoopAnimationsModule, CommonModule], + declarations: [ + BasicTestApp, + DrawerContainerNoDrawerTestApp, + DrawerSetToOpenedFalse, + DrawerSetToOpenedTrue, + DrawerDynamicPosition, + DrawerWithFocusableElements, + DrawerOpenBinding, + DrawerWithoutFocusableElements, + IndirectDescendantDrawer, + NestedDrawerContainers, + ], + }); - TestBed.compileComponents(); - })); + TestBed.compileComponents(); + }), + ); describe('methods', () => { it('should be able to open', fakeAsync(() => { @@ -101,8 +98,9 @@ describe('MatDrawer', () => { it('should resolve the open method promise with the new state of the drawer', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); - const drawer: MatDrawer = - fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; + const drawer: MatDrawer = fixture.debugElement.query( + By.directive(MatDrawer), + )!.componentInstance; drawer.open().then(result => expect(result).toBe('open')); fixture.detectChanges(); @@ -151,18 +149,18 @@ describe('MatDrawer', () => { it('does not throw when created without a drawer', fakeAsync(() => { expect(() => { - let fixture = TestBed.createComponent(BasicTestApp); + const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); tick(); }).not.toThrow(); })); it('should emit the backdropClick event when the backdrop is clicked', fakeAsync(() => { - let fixture = TestBed.createComponent(BasicTestApp); + const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); - let testComponent: BasicTestApp = fixture.debugElement.componentInstance; - let openButtonElement = fixture.debugElement.query(By.css('.open'))!.nativeElement; + const testComponent: BasicTestApp = fixture.debugElement.componentInstance; + const openButtonElement = fixture.debugElement.query(By.css('.open'))!.nativeElement; openButtonElement.click(); fixture.detectChanges(); @@ -188,58 +186,60 @@ describe('MatDrawer', () => { })); it('should close when pressing escape', fakeAsync(() => { - let fixture = TestBed.createComponent(BasicTestApp); + const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); - let testComponent: BasicTestApp = fixture.debugElement.componentInstance; - let drawer = fixture.debugElement.query(By.directive(MatDrawer))!; + const testComponent: BasicTestApp = fixture.debugElement.componentInstance; + const drawer = fixture.debugElement.query(By.directive(MatDrawer))!; drawer.componentInstance.open(); fixture.detectChanges(); tick(); - expect(testComponent.openCount).toBe(1, 'Expected one open event.'); - expect(testComponent.openStartCount).toBe(1, 'Expected one open start event.'); - expect(testComponent.closeCount).toBe(0, 'Expected no close events.'); - expect(testComponent.closeStartCount).toBe(0, 'Expected no close start events.'); + expect(testComponent.openCount).withContext('Expected one open event.').toBe(1); + expect(testComponent.openStartCount).withContext('Expected one open start event.').toBe(1); + expect(testComponent.closeCount).withContext('Expected no close events.').toBe(0); + expect(testComponent.closeStartCount).withContext('Expected no close start events.').toBe(0); const event = dispatchKeyboardEvent(drawer.nativeElement, 'keydown', ESCAPE); fixture.detectChanges(); flush(); - expect(testComponent.closeCount).toBe(1, 'Expected one close event.'); - expect(testComponent.closeStartCount).toBe(1, 'Expected one close start event.'); + expect(testComponent.closeCount).withContext('Expected one close event.').toBe(1); + expect(testComponent.closeStartCount).withContext('Expected one close start event.').toBe(1); expect(event.defaultPrevented).toBe(true); })); it('should not close when pressing escape with a modifier', fakeAsync(() => { - let fixture = TestBed.createComponent(BasicTestApp); + const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); - let testComponent: BasicTestApp = fixture.debugElement.componentInstance; - let drawer = fixture.debugElement.query(By.directive(MatDrawer))!; + const testComponent: BasicTestApp = fixture.debugElement.componentInstance; + const drawer = fixture.debugElement.query(By.directive(MatDrawer))!; drawer.componentInstance.open(); fixture.detectChanges(); tick(); - expect(testComponent.closeCount).toBe(0, 'Expected no close events.'); - expect(testComponent.closeStartCount).toBe(0, 'Expected no close start events.'); + expect(testComponent.closeCount).withContext('Expected no close events.').toBe(0); + expect(testComponent.closeStartCount).withContext('Expected no close start events.').toBe(0); const event = createKeyboardEvent('keydown', ESCAPE, undefined, {alt: true}); dispatchEvent(drawer.nativeElement, event); fixture.detectChanges(); flush(); - expect(testComponent.closeCount).toBe(0, 'Expected still no close events.'); - expect(testComponent.closeStartCount).toBe(0, 'Expected still no close start events.'); + expect(testComponent.closeCount).withContext('Expected still no close events.').toBe(0); + expect(testComponent.closeStartCount) + .withContext('Expected still no close start events.') + .toBe(0); expect(event.defaultPrevented).toBe(false); })); it('should fire the open event when open on init', fakeAsync(() => { - let fixture = TestBed.createComponent(DrawerSetToOpenedTrue); + const fixture = TestBed.createComponent(DrawerSetToOpenedTrue); fixture.detectChanges(); tick(); @@ -248,9 +248,9 @@ describe('MatDrawer', () => { })); it('should not close by pressing escape when disableClose is set', fakeAsync(() => { - let fixture = TestBed.createComponent(BasicTestApp); - let testComponent = fixture.debugElement.componentInstance; - let drawer = fixture.debugElement.query(By.directive(MatDrawer))!; + const fixture = TestBed.createComponent(BasicTestApp); + const testComponent = fixture.debugElement.componentInstance; + const drawer = fixture.debugElement.query(By.directive(MatDrawer))!; drawer.componentInstance.disableClose = true; drawer.componentInstance.open(); @@ -266,9 +266,9 @@ describe('MatDrawer', () => { })); it('should not close by clicking on the backdrop when disableClose is set', fakeAsync(() => { - let fixture = TestBed.createComponent(BasicTestApp); - let testComponent = fixture.debugElement.componentInstance; - let drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; + const fixture = TestBed.createComponent(BasicTestApp); + const testComponent = fixture.debugElement.componentInstance; + const drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; drawer.disableClose = true; drawer.open(); @@ -309,17 +309,18 @@ describe('MatDrawer', () => { flush(); expect(document.activeElement) - .toBe(openButton, 'Expected focus to be restored to the open button on close.'); + .withContext('Expected focus to be restored to the open button on close.') + .toBe(openButton); })); it('should restore focus on close if focus is on drawer', fakeAsync(() => { - let fixture = TestBed.createComponent(BasicTestApp); + const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); - let drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; - let openButton = fixture.componentInstance.openButton.nativeElement; - let drawerButton = fixture.componentInstance.drawerButton.nativeElement; + const drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; + const openButton = fixture.componentInstance.openButton.nativeElement; + const drawerButton = fixture.componentInstance.drawerButton.nativeElement; openButton.focus(); drawer.open(); @@ -332,7 +333,8 @@ describe('MatDrawer', () => { flush(); expect(document.activeElement) - .toBe(openButton, 'Expected focus to be restored to the open button on close.'); + .withContext('Expected focus to be restored to the open button on close.') + .toBe(openButton); })); it('should restore focus to an SVG element', fakeAsync(() => { @@ -354,17 +356,19 @@ describe('MatDrawer', () => { flush(); expect(document.activeElement) - .toBe(svg, 'Expected focus to be restored to the SVG element on close.'); + .withContext('Expected focus to be restored to the SVG element on close.') + .toBe(svg); })); it('should not restore focus on close if focus is outside drawer', fakeAsync(() => { - let fixture = TestBed.createComponent(BasicTestApp); - let drawer: MatDrawer = fixture.debugElement - .query(By.directive(MatDrawer))!.componentInstance; + const fixture = TestBed.createComponent(BasicTestApp); + const drawer: MatDrawer = fixture.debugElement.query( + By.directive(MatDrawer), + )!.componentInstance; fixture.detectChanges(); - let openButton = fixture.componentInstance.openButton.nativeElement; - let closeButton = fixture.componentInstance.closeButton.nativeElement; + const openButton = fixture.componentInstance.openButton.nativeElement; + const closeButton = fixture.componentInstance.closeButton.nativeElement; openButton.focus(); drawer.open(); @@ -378,7 +382,8 @@ describe('MatDrawer', () => { tick(); expect(document.activeElement) - .toBe(closeButton, 'Expected focus not to be restored to the open button on close.'); + .withContext('Expected focus not to be restored to the open button on close.') + .toBe(closeButton); })); it('should pick up drawers that are not direct descendants', fakeAsync(() => { @@ -419,26 +424,25 @@ describe('MatDrawer', () => { expect(instance.outerDrawer.opened).toBe(true); expect(instance.innerDrawer.opened).toBe(true); })); - }); describe('attributes', () => { it('should correctly parse opened="false"', () => { - let fixture = TestBed.createComponent(DrawerSetToOpenedFalse); + const fixture = TestBed.createComponent(DrawerSetToOpenedFalse); fixture.detectChanges(); - let drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; + const drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; expect((drawer as MatDrawer).opened).toBe(false); }); it('should correctly parse opened="true"', () => { - let fixture = TestBed.createComponent(DrawerSetToOpenedTrue); + const fixture = TestBed.createComponent(DrawerSetToOpenedTrue); fixture.detectChanges(); - let drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; + const drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; expect((drawer as MatDrawer).opened).toBe(true); }); @@ -449,7 +453,8 @@ describe('MatDrawer', () => { const drawerEl = fixture.debugElement.query(By.css('mat-drawer'))!.nativeElement; expect(drawerEl.hasAttribute('align')) - .toBe(false, 'Expected drawer not to have a native align attribute.'); + .withContext('Expected drawer not to have a native align attribute.') + .toBe(false); }); it('should throw when multiple drawers have the same position', fakeAsync(() => { @@ -485,8 +490,9 @@ describe('MatDrawer', () => { const fixture = TestBed.createComponent(DrawerOpenBinding); fixture.detectChanges(); - let drawer: MatDrawer = fixture.debugElement - .query(By.directive(MatDrawer))!.componentInstance; + const drawer: MatDrawer = fixture.debugElement.query( + By.directive(MatDrawer), + )!.componentInstance; drawer.open(); fixture.detectChanges(); @@ -495,36 +501,33 @@ describe('MatDrawer', () => { expect(fixture.componentInstance.isOpen).toBe(true); })); - it('should not throw when a two-way binding is toggled quickly while animating', - fakeAsync(() => { - TestBed - .resetTestingModule() - .configureTestingModule({ - imports: [MatSidenavModule, BrowserAnimationsModule], - declarations: [DrawerOpenBinding], - }) - .compileComponents(); - - const fixture = TestBed.createComponent(DrawerOpenBinding); - fixture.detectChanges(); + it('should not throw when a two-way binding is toggled quickly while animating', fakeAsync(() => { + TestBed.resetTestingModule() + .configureTestingModule({ + imports: [MatSidenavModule, BrowserAnimationsModule], + declarations: [DrawerOpenBinding], + }) + .compileComponents(); + + const fixture = TestBed.createComponent(DrawerOpenBinding); + fixture.detectChanges(); + + // Note that we need actual timeouts and the `BrowserAnimationsModule` + // in order to test it correctly. + setTimeout(() => { + fixture.componentInstance.isOpen = !fixture.componentInstance.isOpen; + expect(() => fixture.detectChanges()).not.toThrow(); - // Note that we need actual timeouts and the `BrowserAnimationsModule` - // in order to test it correctly. setTimeout(() => { fixture.componentInstance.isOpen = !fixture.componentInstance.isOpen; expect(() => fixture.detectChanges()).not.toThrow(); - - setTimeout(() => { - fixture.componentInstance.isOpen = !fixture.componentInstance.isOpen; - expect(() => fixture.detectChanges()).not.toThrow(); - }, 1); - - tick(1); }, 1); tick(1); - })); + }, 1); + tick(1); + })); }); describe('focus trapping behavior', () => { @@ -580,18 +583,22 @@ describe('MatDrawer', () => { expect(document.activeElement).toBe(lastFocusableElement); })); - it('should auto-focus when opened in "side" mode when enabled explicitly', fakeAsync(() => { - drawer.autoFocus = true; - testComponent.mode = 'side'; - fixture.detectChanges(); - lastFocusableElement.focus(); + it( + 'should auto-focus to first tabbable element when opened in "side" mode' + + 'when enabled explicitly', + fakeAsync(() => { + drawer.autoFocus = 'first-tabbable'; + testComponent.mode = 'side'; + fixture.detectChanges(); + lastFocusableElement.focus(); - drawer.open(); - fixture.detectChanges(); - tick(); + drawer.open(); + fixture.detectChanges(); + tick(); - expect(document.activeElement).toBe(firstFocusableElement); - })); + expect(document.activeElement).toBe(firstFocusableElement); + }), + ); it('should focus the drawer if there are no focusable elements', fakeAsync(() => { fixture.destroy(); @@ -608,7 +615,7 @@ describe('MatDrawer', () => { })); it('should be able to disable auto focus', fakeAsync(() => { - drawer.autoFocus = false; + drawer.autoFocus = 'dialog'; testComponent.mode = 'push'; fixture.detectChanges(); lastFocusableElement.focus(); @@ -628,47 +635,60 @@ describe('MatDrawer', () => { fixture.detectChanges(); tick(); - const anchors = - Array.from(fixture.nativeElement.querySelectorAll('.cdk-focus-trap-anchor')); + const anchors = Array.from( + fixture.nativeElement.querySelectorAll('.cdk-focus-trap-anchor'), + ); expect(anchors.every(anchor => !anchor.hasAttribute('tabindex'))) - .toBe(true, 'Expected focus trap anchors to be disabled in side mode.'); + .withContext('Expected focus trap anchors to be disabled in side mode.') + .toBe(true); testComponent.mode = 'over'; fixture.detectChanges(); expect(anchors.every(anchor => anchor.getAttribute('tabindex') === '0')) - .toBe(true, 'Expected focus trap anchors to be enabled in over mode.'); + .withContext('Expected focus trap anchors to be enabled in over mode.') + .toBe(true); })); + }); + it('should mark the drawer content as scrollable', () => { + const fixture = TestBed.createComponent(BasicTestApp); + fixture.detectChanges(); + + const content = fixture.debugElement.query(By.css('.mat-drawer-inner-container')); + const scrollable = content.injector.get(CdkScrollable); + expect(scrollable).toBeTruthy(); + expect(scrollable.getElementRef().nativeElement).toBe(content.nativeElement); }); }); describe('MatDrawerContainer', () => { - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatSidenavModule, A11yModule, PlatformModule, NoopAnimationsModule], - declarations: [ - DrawerContainerTwoDrawerTestApp, - DrawerDelayed, - DrawerSetToOpenedTrue, - DrawerContainerStateChangesTestApp, - AutosizeDrawer, - BasicTestApp, - DrawerContainerWithContent, - ], - }); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatSidenavModule, A11yModule, PlatformModule, NoopAnimationsModule], + declarations: [ + DrawerContainerTwoDrawerTestApp, + DrawerDelayed, + DrawerSetToOpenedTrue, + DrawerContainerStateChangesTestApp, + AutosizeDrawer, + BasicTestApp, + DrawerContainerWithContent, + ], + }); - TestBed.compileComponents(); - })); + TestBed.compileComponents(); + }), + ); it('should be able to open and close all drawers', fakeAsync(() => { const fixture = TestBed.createComponent(DrawerContainerTwoDrawerTestApp); fixture.detectChanges(); - const testComponent: DrawerContainerTwoDrawerTestApp = - fixture.debugElement.componentInstance; + const testComponent: DrawerContainerTwoDrawerTestApp = fixture.debugElement.componentInstance; const drawers = fixture.debugElement.queryAll(By.directive(MatDrawer)); expect(drawers.every(drawer => drawer.componentInstance.opened)).toBe(false); @@ -769,8 +789,7 @@ describe('MatDrawerContainer', () => { })); it('should not animate when the sidenav is open on load', fakeAsync(() => { - TestBed - .resetTestingModule() + TestBed.resetTestingModule() .configureTestingModule({ imports: [MatSidenavModule, BrowserAnimationsModule], declarations: [DrawerSetToOpenedTrue], @@ -787,8 +806,8 @@ describe('MatDrawerContainer', () => { expect(container.classList).not.toContain('mat-drawer-transition'); })); - it('should recalculate the margin if a drawer changes size while open in autosize mode', - fakeAsync(inject([Platform], (platform: Platform) => { + it('should recalculate the margin if a drawer changes size while open in autosize mode', fakeAsync( + inject([Platform], (platform: Platform) => { const fixture = TestBed.createComponent(AutosizeDrawer); fixture.detectChanges(); @@ -821,116 +840,120 @@ describe('MatDrawerContainer', () => { } discardPeriodicTasks(); - }))); + }), + )); it('should not set a style property if it would be zero', fakeAsync(() => { - const fixture = TestBed.createComponent(AutosizeDrawer); - fixture.detectChanges(); + const fixture = TestBed.createComponent(AutosizeDrawer); + fixture.detectChanges(); - const content = fixture.debugElement.nativeElement.querySelector('.mat-drawer-content'); - expect(content.style.marginLeft).toBe('', 'Margin should be omitted when drawer is closed'); + const content = fixture.debugElement.nativeElement.querySelector('.mat-drawer-content'); + expect(content.style.marginLeft) + .withContext('Margin should be omitted when drawer is closed') + .toBe(''); - // Open the drawer and resolve the open animation. - fixture.componentInstance.drawer.open(); - fixture.detectChanges(); - tick(); - fixture.detectChanges(); + // Open the drawer and resolve the open animation. + fixture.componentInstance.drawer.open(); + fixture.detectChanges(); + tick(); + fixture.detectChanges(); - expect(content.style.marginLeft).not.toBe('', 'Margin should be present when drawer is open'); + expect(content.style.marginLeft).not.toBe('', 'Margin should be present when drawer is open'); - // Close the drawer and resolve the close animation. - fixture.componentInstance.drawer.close(); - fixture.detectChanges(); - flush(); - fixture.detectChanges(); + // Close the drawer and resolve the close animation. + fixture.componentInstance.drawer.close(); + fixture.detectChanges(); + flush(); + fixture.detectChanges(); - expect(content.style.marginLeft).toBe('', 'Margin should be removed after drawer close.'); + expect(content.style.marginLeft) + .withContext('Margin should be removed after drawer close.') + .toBe(''); - discardPeriodicTasks(); - })); + discardPeriodicTasks(); + })); - it('should be able to toggle whether the container has a backdrop', fakeAsync(() => { - const fixture = TestBed.createComponent(BasicTestApp); - fixture.detectChanges(); + it('should be able to toggle whether the container has a backdrop', fakeAsync(() => { + const fixture = TestBed.createComponent(BasicTestApp); + fixture.detectChanges(); - expect(fixture.nativeElement.querySelector('.mat-drawer-backdrop')).toBeTruthy(); + expect(fixture.nativeElement.querySelector('.mat-drawer-backdrop')).toBeTruthy(); - fixture.componentInstance.hasBackdrop = false; - fixture.detectChanges(); + fixture.componentInstance.hasBackdrop = false; + fixture.detectChanges(); - expect(fixture.nativeElement.querySelector('.mat-drawer-backdrop')).toBeFalsy(); - })); + expect(fixture.nativeElement.querySelector('.mat-drawer-backdrop')).toBeFalsy(); + })); - it('should be able to explicitly enable the backdrop in `side` mode', fakeAsync(() => { - const fixture = TestBed.createComponent(BasicTestApp); - const root = fixture.nativeElement; - fixture.detectChanges(); + it('should be able to explicitly enable the backdrop in `side` mode', fakeAsync(() => { + const fixture = TestBed.createComponent(BasicTestApp); + const root = fixture.nativeElement; + fixture.detectChanges(); - fixture.componentInstance.drawer.mode = 'side'; - fixture.detectChanges(); - fixture.componentInstance.drawer.open(); - fixture.detectChanges(); - tick(); - fixture.detectChanges(); + fixture.componentInstance.drawer.mode = 'side'; + fixture.detectChanges(); + fixture.componentInstance.drawer.open(); + fixture.detectChanges(); + tick(); + fixture.detectChanges(); - let backdrop = root.querySelector('.mat-drawer-backdrop.mat-drawer-shown'); + let backdrop = root.querySelector('.mat-drawer-backdrop.mat-drawer-shown'); - expect(backdrop).toBeFalsy(); + expect(backdrop).toBeFalsy(); - fixture.componentInstance.hasBackdrop = true; - fixture.detectChanges(); - backdrop = root.querySelector('.mat-drawer-backdrop.mat-drawer-shown'); + fixture.componentInstance.hasBackdrop = true; + fixture.detectChanges(); + backdrop = root.querySelector('.mat-drawer-backdrop.mat-drawer-shown'); - expect(backdrop).toBeTruthy(); - expect(fixture.componentInstance.drawer.opened).toBe(true); + expect(backdrop).toBeTruthy(); + expect(fixture.componentInstance.drawer.opened).toBe(true); - backdrop.click(); - fixture.detectChanges(); - tick(); + backdrop.click(); + fixture.detectChanges(); + tick(); - expect(fixture.componentInstance.drawer.opened).toBe(false); - })); + expect(fixture.componentInstance.drawer.opened).toBe(false); + })); - it('should expose a scrollable when the consumer has not specified drawer content', - fakeAsync(() => { - const fixture = TestBed.createComponent(DrawerContainerTwoDrawerTestApp); + it('should expose a scrollable when the consumer has not specified drawer content', fakeAsync(() => { + const fixture = TestBed.createComponent(DrawerContainerTwoDrawerTestApp); - fixture.detectChanges(); + fixture.detectChanges(); - expect(fixture.componentInstance.drawerContainer.scrollable instanceof CdkScrollable) - .toBe(true); - })); + expect(fixture.componentInstance.drawerContainer.scrollable instanceof CdkScrollable).toBe( + true, + ); + })); - it('should expose a scrollable when the consumer has specified drawer content', - fakeAsync(() => { - const fixture = TestBed.createComponent(DrawerContainerWithContent); + it('should expose a scrollable when the consumer has specified drawer content', fakeAsync(() => { + const fixture = TestBed.createComponent(DrawerContainerWithContent); - fixture.detectChanges(); + fixture.detectChanges(); - expect(fixture.componentInstance.drawerContainer.scrollable instanceof CdkScrollable) - .toBe(true); - })); + expect(fixture.componentInstance.drawerContainer.scrollable instanceof CdkScrollable).toBe( + true, + ); + })); - it('should clean up the drawers stream on destroy', fakeAsync(() => { - const fixture = TestBed.createComponent(DrawerContainerTwoDrawerTestApp); - fixture.detectChanges(); + it('should clean up the drawers stream on destroy', fakeAsync(() => { + const fixture = TestBed.createComponent(DrawerContainerTwoDrawerTestApp); + fixture.detectChanges(); - const spy = jasmine.createSpy('complete spy'); - const subscription = fixture.componentInstance.drawerContainer._drawers.changes.subscribe({ - complete: spy - }); + const spy = jasmine.createSpy('complete spy'); + const subscription = fixture.componentInstance.drawerContainer._drawers.changes.subscribe({ + complete: spy, + }); - fixture.destroy(); + fixture.destroy(); - expect(spy).toHaveBeenCalled(); - subscription.unsubscribe(); - })); + expect(spy).toHaveBeenCalled(); + subscription.unsubscribe(); + })); }); - /** Test component that contains an MatDrawerContainer but no MatDrawer. */ @Component({template: ``}) -class DrawerContainerNoDrawerTestApp { } +class DrawerContainerNoDrawerTestApp {} /** Test component that contains an MatDrawerContainer and 2 MatDrawer in the same position. */ @Component({ @@ -1010,7 +1033,7 @@ class BasicTestApp { `, }) -class DrawerSetToOpenedFalse { } +class DrawerSetToOpenedFalse {} @Component({ template: ` @@ -1085,7 +1108,6 @@ class DrawerDelayed { showDrawer = false; } - @Component({ template: ` @@ -1101,7 +1123,6 @@ class DrawerContainerStateChangesTestApp { renderDrawer = true; } - @Component({ template: ` @@ -1117,7 +1138,6 @@ class AutosizeDrawer { fillerWidth = 0; } - @Component({ template: ` @@ -1130,7 +1150,6 @@ class DrawerContainerWithContent { @ViewChild(MatDrawerContainer) drawerContainer: MatDrawerContainer; } - @Component({ // Note that we need the `ng-container` with the `ngSwitch` so that // there's a directive between the container and the drawer. diff --git a/src/material/sidenav/drawer.ts b/src/material/sidenav/drawer.ts index 171a486d81c1..425c9d9d9ed8 100644 --- a/src/material/sidenav/drawer.ts +++ b/src/material/sidenav/drawer.ts @@ -6,7 +6,13 @@ * found in the LICENSE file at https://angular.io/license */ import {AnimationEvent} from '@angular/animations'; -import {FocusMonitor, FocusOrigin, FocusTrap, FocusTrapFactory} from '@angular/cdk/a11y'; +import { + FocusMonitor, + FocusOrigin, + FocusTrap, + FocusTrapFactory, + InteractivityChecker, +} from '@angular/cdk/a11y'; import {Directionality} from '@angular/cdk/bidi'; import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion'; import {ESCAPE, hasModifierKey} from '@angular/cdk/keycodes'; @@ -35,8 +41,6 @@ import { QueryList, ViewChild, ViewEncapsulation, - HostListener, - HostBinding, } from '@angular/core'; import {fromEvent, merge, Observable, Subject} from 'rxjs'; import { @@ -52,7 +56,6 @@ import { import {matDrawerAnimations} from './drawer-animations'; import {ANIMATION_MODULE_TYPE} from '@angular/platform-browser/animations'; - /** * Throws an exception when two MatDrawer are matching the same position. * @docs-private @@ -61,6 +64,8 @@ export function throwMatDuplicatedDrawerError(position: string) { throw Error(`A drawer was already declared for 'position="${position}"'`); } +/** Options for where to set focus to automatically on dialog open */ +export type AutoFocusTarget = 'dialog' | 'first-tabbable' | 'first-heading'; /** Result of the toggle promise that indicates the state of the drawer. */ export type MatDrawerToggleResult = 'open' | 'close'; @@ -69,12 +74,13 @@ export type MatDrawerToggleResult = 'open' | 'close'; export type MatDrawerMode = 'over' | 'push' | 'side'; /** Configures whether drawers should use auto sizing by default. */ -export const MAT_DRAWER_DEFAULT_AUTOSIZE = - new InjectionToken('MAT_DRAWER_DEFAULT_AUTOSIZE', { - providedIn: 'root', - factory: MAT_DRAWER_DEFAULT_AUTOSIZE_FACTORY, - }); - +export const MAT_DRAWER_DEFAULT_AUTOSIZE = new InjectionToken( + 'MAT_DRAWER_DEFAULT_AUTOSIZE', + { + providedIn: 'root', + factory: MAT_DRAWER_DEFAULT_AUTOSIZE_FACTORY, + }, +); /** * Used to provide a drawer container to a drawer while avoiding circular references. @@ -100,11 +106,12 @@ export function MAT_DRAWER_DEFAULT_AUTOSIZE_FACTORY(): boolean { }) export class MatDrawerContent extends CdkScrollable implements AfterContentInit { constructor( - private _changeDetectorRef: ChangeDetectorRef, - @Inject(forwardRef(() => MatDrawerContainer)) public _container: MatDrawerContainer, - elementRef: ElementRef, - scrollDispatcher: ScrollDispatcher, - ngZone: NgZone) { + private _changeDetectorRef: ChangeDetectorRef, + @Inject(forwardRef(() => MatDrawerContainer)) public _container: MatDrawerContainer, + elementRef: ElementRef, + scrollDispatcher: ScrollDispatcher, + ngZone: NgZone, + ) { super(elementRef, scrollDispatcher, ngZone); } @@ -115,7 +122,6 @@ export class MatDrawerContent extends CdkScrollable implements AfterContentInit } } - /** * This component corresponds to a drawer that can be opened on the drawer container. */ @@ -134,6 +140,9 @@ export class MatDrawerContent extends CdkScrollable implements AfterContentInit '[class.mat-drawer-side]': 'mode === "side"', '[class.mat-drawer-opened]': 'opened', 'tabIndex': '-1', + '[@transform]': '_animationState', + '(@transform.start)': '_animationStarted.next($event)', + '(@transform.done)': '_animationEnd.next($event)', }, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, @@ -147,7 +156,9 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr /** The side that the drawer is attached to. */ @Input() - get position(): 'start' | 'end' { return this._position; } + get position(): 'start' | 'end' { + return this._position; + } set position(value: 'start' | 'end') { // Make sure we have a valid value. value = value === 'end' ? 'end' : 'start'; @@ -160,7 +171,9 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr /** Mode of the drawer; one of 'over', 'push' or 'side'. */ @Input() - get mode(): MatDrawerMode { return this._mode; } + get mode(): MatDrawerMode { + return this._mode; + } set mode(value: MatDrawerMode) { this._mode = value; this._updateFocusTrapState(); @@ -170,78 +183,101 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr /** Whether the drawer can be closed with the escape key or by clicking on the backdrop. */ @Input() - get disableClose(): boolean { return this._disableClose; } - set disableClose(value: boolean) { this._disableClose = coerceBooleanProperty(value); } + get disableClose(): boolean { + return this._disableClose; + } + set disableClose(value: BooleanInput) { + this._disableClose = coerceBooleanProperty(value); + } private _disableClose: boolean = false; /** * Whether the drawer should focus the first focusable element automatically when opened. * Defaults to false in when `mode` is set to `side`, otherwise defaults to `true`. If explicitly * enabled, focus will be moved into the sidenav in `side` mode as well. + * @breaking-change 14.0.0 Remove boolean option from autoFocus. Use string or AutoFocusTarget + * instead. */ @Input() - get autoFocus(): boolean { + get autoFocus(): AutoFocusTarget | string | boolean { const value = this._autoFocus; - // Note that usually we disable auto focusing in `side` mode, because we don't know how the - // sidenav is being used, but in some cases it still makes sense to do it. If the consumer - // explicitly enabled `autoFocus`, we take it as them always wanting to enable it. - return value == null ? this.mode !== 'side' : value; + // Note that usually we don't allow autoFocus to be set to `first-tabbable` in `side` mode, + // because we don't know how the sidenav is being used, but in some cases it still makes + // sense to do it. The consumer can explicitly set `autoFocus`. + if (value == null) { + if (this.mode === 'side') { + return 'dialog'; + } else { + return 'first-tabbable'; + } + } + return value; } - set autoFocus(value: boolean) { this._autoFocus = coerceBooleanProperty(value); } - private _autoFocus: boolean | undefined; + set autoFocus(value: AutoFocusTarget | string | BooleanInput) { + if (value === 'true' || value === 'false' || value == null) { + value = coerceBooleanProperty(value); + } + this._autoFocus = value; + } + private _autoFocus: AutoFocusTarget | string | boolean | undefined; /** * Whether the drawer is opened. We overload this because we trigger an event when it * starts or end. */ @Input() - get opened(): boolean { return this._opened; } - set opened(value: boolean) { this.toggle(coerceBooleanProperty(value)); } + get opened(): boolean { + return this._opened; + } + set opened(value: BooleanInput) { + this.toggle(coerceBooleanProperty(value)); + } private _opened: boolean = false; /** How the sidenav was opened (keypress, mouse click etc.) */ private _openedVia: FocusOrigin | null; /** Emits whenever the drawer has started animating. */ - _animationStarted = new Subject(); + readonly _animationStarted = new Subject(); /** Emits whenever the drawer is done animating. */ - _animationEnd = new Subject(); + readonly _animationEnd = new Subject(); /** Current state of the sidenav animation. */ - // @HostBinding is used in the class as it is expected to be extended. Since @Component decorator - // metadata is not inherited by child classes, instead the host binding data is defined in a way - // that can be inherited. - // tslint:disable:no-host-decorator-in-concrete - @HostBinding('@transform') _animationState: 'open-instant' | 'open' | 'void' = 'void'; /** Event emitted when the drawer open state is changed. */ @Output() readonly openedChange: EventEmitter = - // Note this has to be async in order to avoid some issues with two-bindings (see #8872). - new EventEmitter(/* isAsync */true); + // Note this has to be async in order to avoid some issues with two-bindings (see #8872). + new EventEmitter(/* isAsync */ true); /** Event emitted when the drawer has been opened. */ @Output('opened') - _openedStream = this.openedChange.pipe(filter(o => o), map(() => {})); + readonly _openedStream = this.openedChange.pipe( + filter(o => o), + map(() => {}), + ); /** Event emitted when the drawer has started opening. */ @Output() readonly openedStart: Observable = this._animationStarted.pipe( filter(e => e.fromState !== e.toState && e.toState.indexOf('open') === 0), - mapTo(undefined) + mapTo(undefined), ); /** Event emitted when the drawer has been closed. */ @Output('closed') - _closedStream = this.openedChange.pipe(filter(o => !o), map(() => {})); + readonly _closedStream = this.openedChange.pipe( + filter(o => !o), + map(() => {}), + ); /** Event emitted when the drawer has started closing. */ @Output() readonly closedStart: Observable = this._animationStarted.pipe( filter(e => e.fromState !== e.toState && e.toState === 'void'), - mapTo(undefined) + mapTo(undefined), ); /** Emits when the component is destroyed. */ @@ -249,7 +285,7 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr /** Event emitted when the drawer's position changes. */ // tslint:disable-next-line:no-output-on-prefix - @Output('positionChanged') onPositionChanged: EventEmitter = new EventEmitter(); + @Output('positionChanged') readonly onPositionChanged = new EventEmitter(); /** * An observable that emits when the drawer mode changes. This is used by the drawer container to @@ -257,14 +293,16 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr */ readonly _modeChanged = new Subject(); - constructor(private _elementRef: ElementRef, - private _focusTrapFactory: FocusTrapFactory, - private _focusMonitor: FocusMonitor, - private _platform: Platform, - private _ngZone: NgZone, - @Optional() @Inject(DOCUMENT) private _doc: any, - @Optional() @Inject(MAT_DRAWER_CONTAINER) public _container?: MatDrawerContainer) { - + constructor( + private _elementRef: ElementRef, + private _focusTrapFactory: FocusTrapFactory, + private _focusMonitor: FocusMonitor, + private _platform: Platform, + private _ngZone: NgZone, + private readonly _interactivityChecker: InteractivityChecker, + @Optional() @Inject(DOCUMENT) private _doc: any, + @Optional() @Inject(MAT_DRAWER_CONTAINER) public _container?: MatDrawerContainer, + ) { this.openedChange.subscribe((opened: boolean) => { if (opened) { if (this._doc) { @@ -273,7 +311,7 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr this._takeFocus(); } else if (this._isFocusWithinDrawer()) { - this._restoreFocus(); + this._restoreFocus(this._openedVia || 'program'); } }); @@ -283,30 +321,70 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr * and we don't have close disabled. */ this._ngZone.runOutsideAngular(() => { - (fromEvent(this._elementRef.nativeElement, 'keydown') as Observable).pipe( - filter(event => { - return event.keyCode === ESCAPE && !this.disableClose && !hasModifierKey(event); - }), - takeUntil(this._destroyed) - ).subscribe(event => this._ngZone.run(() => { + (fromEvent(this._elementRef.nativeElement, 'keydown') as Observable) + .pipe( + filter(event => { + return event.keyCode === ESCAPE && !this.disableClose && !hasModifierKey(event); + }), + takeUntil(this._destroyed), + ) + .subscribe(event => + this._ngZone.run(() => { this.close(); event.stopPropagation(); event.preventDefault(); - })); + }), + ); }); // We need a Subject with distinctUntilChanged, because the `done` event // fires twice on some browsers. See https://github.com/angular/angular/issues/24084 - this._animationEnd.pipe(distinctUntilChanged((x, y) => { - return x.fromState === y.fromState && x.toState === y.toState; - })).subscribe((event: AnimationEvent) => { - const {fromState, toState} = event; - - if ((toState.indexOf('open') === 0 && fromState === 'void') || - (toState === 'void' && fromState.indexOf('open') === 0)) { - this.openedChange.emit(this._opened); - } - }); + this._animationEnd + .pipe( + distinctUntilChanged((x, y) => { + return x.fromState === y.fromState && x.toState === y.toState; + }), + ) + .subscribe((event: AnimationEvent) => { + const {fromState, toState} = event; + + if ( + (toState.indexOf('open') === 0 && fromState === 'void') || + (toState === 'void' && fromState.indexOf('open') === 0) + ) { + this.openedChange.emit(this._opened); + } + }); + } + + /** + * Focuses the provided element. If the element is not focusable, it will add a tabIndex + * attribute to forcefully focus it. The attribute is removed after focus is moved. + * @param element The element to focus. + */ + private _forceFocus(element: HTMLElement, options?: FocusOptions) { + if (!this._interactivityChecker.isFocusable(element)) { + element.tabIndex = -1; + // The tabindex attribute should be removed to avoid navigating to that element again + this._ngZone.runOutsideAngular(() => { + element.addEventListener('blur', () => element.removeAttribute('tabindex')); + element.addEventListener('mousedown', () => element.removeAttribute('tabindex')); + }); + } + element.focus(options); + } + + /** + * Focuses the first element that matches the given selector within the focus trap. + * @param selector The CSS selector for the element to set focus to. + */ + private _focusByCssSelector(selector: string, options?: FocusOptions) { + let elementToFocus = this._elementRef.nativeElement.querySelector( + selector, + ) as HTMLElement | null; + if (elementToFocus) { + this._forceFocus(elementToFocus, options); + } } /** @@ -314,37 +392,52 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr * the focus trap is disabled in `side` mode. */ private _takeFocus() { - if (!this.autoFocus || !this._focusTrap) { + if (!this._focusTrap) { return; } - this._focusTrap.focusInitialElementWhenReady().then(hasMovedFocus => { - // If there were no focusable elements, focus the sidenav itself so the keyboard navigation - // still works. We need to check that `focus` is a function due to Universal. - if (!hasMovedFocus && typeof this._elementRef.nativeElement.focus === 'function') { - this._elementRef.nativeElement.focus(); - } - }); + const element = this._elementRef.nativeElement; + + // When autoFocus is not on the sidenav, if the element cannot be focused or does + // not exist, focus the sidenav itself so the keyboard navigation still works. + // We need to check that `focus` is a function due to Universal. + switch (this.autoFocus) { + case false: + case 'dialog': + return; + case true: + case 'first-tabbable': + this._focusTrap.focusInitialElementWhenReady().then(hasMovedFocus => { + if (!hasMovedFocus && typeof this._elementRef.nativeElement.focus === 'function') { + element.focus(); + } + }); + break; + case 'first-heading': + this._focusByCssSelector('h1, h2, h3, h4, h5, h6, [role="heading"]'); + break; + default: + this._focusByCssSelector(this.autoFocus!); + break; + } } /** * Restores focus to the element that was originally focused when the drawer opened. * If no element was focused at that time, the focus will be restored to the drawer. */ - private _restoreFocus() { - if (!this.autoFocus) { + private _restoreFocus(focusOrigin: Exclude) { + if (this.autoFocus === 'dialog') { return; } - // Note that we don't check via `instanceof HTMLElement` so that we can cover SVGs as well. if (this._elementFocusedBeforeDrawerWasOpened) { - this._focusMonitor.focusVia(this._elementFocusedBeforeDrawerWasOpened, this._openedVia); + this._focusMonitor.focusVia(this._elementFocusedBeforeDrawerWasOpened, focusOrigin); } else { this._elementRef.nativeElement.blur(); } this._elementFocusedBeforeDrawerWasOpened = null; - this._openedVia = null; } /** Whether focus is currently within the drawer. */ @@ -398,8 +491,8 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr _closeViaBackdropClick(): Promise { // If the drawer is closed upon a backdrop click, we always want to restore focus. We // don't need to check whether focus is currently in the drawer, as clicking on the - // backdrop causes blurring of the active element. - return this._setOpen(/* isOpen */ false, /* restoreFocus */ true); + // backdrop causes blurs the active element. + return this._setOpen(/* isOpen */ false, /* restoreFocus */ true, 'mouse'); } /** @@ -408,32 +501,45 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr * @param openedVia Whether the drawer was opened by a key press, mouse click or programmatically. * Used for focus management after the sidenav is closed. */ - toggle(isOpen: boolean = !this.opened, openedVia?: FocusOrigin) - : Promise { + toggle(isOpen: boolean = !this.opened, openedVia?: FocusOrigin): Promise { // If the focus is currently inside the drawer content and we are closing the drawer, // restore the focus to the initially focused element (when the drawer opened). - return this._setOpen( - isOpen, /* restoreFocus */ !isOpen && this._isFocusWithinDrawer(), openedVia); + if (isOpen && openedVia) { + this._openedVia = openedVia; + } + + const result = this._setOpen( + isOpen, + /* restoreFocus */ !isOpen && this._isFocusWithinDrawer(), + this._openedVia || 'program', + ); + + if (!isOpen) { + this._openedVia = null; + } + + return result; } /** * Toggles the opened state of the drawer. * @param isOpen Whether the drawer should open or close. * @param restoreFocus Whether focus should be restored on close. - * @param openedVia Focus origin that can be optionally set when opening a drawer. The - * origin will be used later when focus is restored on drawer close. + * @param focusOrigin Origin to use when restoring focus. */ - private _setOpen(isOpen: boolean, restoreFocus: boolean, openedVia: FocusOrigin = 'program') - : Promise { + private _setOpen( + isOpen: boolean, + restoreFocus: boolean, + focusOrigin: Exclude, + ): Promise { this._opened = isOpen; if (isOpen) { this._animationState = this._enableAnimations ? 'open' : 'open-instant'; - this._openedVia = openedVia; } else { this._animationState = 'void'; if (restoreFocus) { - this._restoreFocus(); + this._restoreFocus(focusOrigin); } } @@ -445,7 +551,7 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr } _getWidth(): number { - return this._elementRef.nativeElement ? (this._elementRef.nativeElement.offsetWidth || 0) : 0; + return this._elementRef.nativeElement ? this._elementRef.nativeElement.offsetWidth || 0 : 0; } /** Updates the enabled state of the focus trap. */ @@ -455,33 +561,8 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr this._focusTrap.enabled = this.opened && this.mode !== 'side'; } } - - // We have to use a `HostListener` here in order to support both Ivy and ViewEngine. - // In Ivy the `host` bindings will be merged when this class is extended, whereas in - // ViewEngine they're overwritten. - // TODO(crisbeto): we move this back into `host` once Ivy is turned on by default. - // tslint:disable-next-line:no-host-decorator-in-concrete - @HostListener('@transform.start', ['$event']) - _animationStartListener(event: AnimationEvent) { - this._animationStarted.next(event); - } - - // We have to use a `HostListener` here in order to support both Ivy and ViewEngine. - // In Ivy the `host` bindings will be merged when this class is extended, whereas in - // ViewEngine they're overwritten. - // TODO(crisbeto): we move this back into `host` once Ivy is turned on by default. - // tslint:disable-next-line:no-host-decorator-in-concrete - @HostListener('@transform.done', ['$event']) - _animationDoneListener(event: AnimationEvent) { - this._animationEnd.next(event); - } - - static ngAcceptInputType_disableClose: BooleanInput; - static ngAcceptInputType_autoFocus: BooleanInput; - static ngAcceptInputType_opened: BooleanInput; } - /** * `` component. * @@ -499,17 +580,19 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr }, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, - providers: [{ - provide: MAT_DRAWER_CONTAINER, - useExisting: MatDrawerContainer - }] + providers: [ + { + provide: MAT_DRAWER_CONTAINER, + useExisting: MatDrawerContainer, + }, + ], }) export class MatDrawerContainer implements AfterContentInit, DoCheck, OnDestroy { /** All drawers in the container. Includes drawers from inside nested containers. */ @ContentChildren(MatDrawer, { // We need to use `descendants: true`, because Ivy will no longer match // indirect descendants if it's left as false. - descendants: true + descendants: true, }) _allDrawers: QueryList; @@ -520,10 +603,14 @@ export class MatDrawerContainer implements AfterContentInit, DoCheck, OnDestroy @ViewChild(MatDrawerContent) _userContent: MatDrawerContent; /** The drawer child with the `start` position. */ - get start(): MatDrawer | null { return this._start; } + get start(): MatDrawer | null { + return this._start; + } /** The drawer child with the `end` position. */ - get end(): MatDrawer | null { return this._end; } + get end(): MatDrawer | null { + return this._end; + } /** * Whether to automatically resize the container whenever @@ -534,8 +621,12 @@ export class MatDrawerContainer implements AfterContentInit, DoCheck, OnDestroy * `MAT_DRAWER_DEFAULT_AUTOSIZE` token. */ @Input() - get autosize(): boolean { return this._autosize; } - set autosize(value: boolean) { this._autosize = coerceBooleanProperty(value); } + get autosize(): boolean { + return this._autosize; + } + set autosize(value: BooleanInput) { + this._autosize = coerceBooleanProperty(value); + } private _autosize: boolean; /** @@ -544,14 +635,14 @@ export class MatDrawerContainer implements AfterContentInit, DoCheck, OnDestroy * mode as well. */ @Input() - get hasBackdrop() { + get hasBackdrop(): boolean { if (this._backdropOverride == null) { return !this._start || this._start.mode !== 'side' || !this._end || this._end.mode !== 'side'; } return this._backdropOverride; } - set hasBackdrop(value: any) { + set hasBackdrop(value: BooleanInput) { this._backdropOverride = value == null ? null : coerceBooleanProperty(value); } _backdropOverride: boolean | null; @@ -583,23 +674,24 @@ export class MatDrawerContainer implements AfterContentInit, DoCheck, OnDestroy * drawer is open. We use margin rather than transform even for push mode because transform breaks * fixed position elements inside of the transformed element. */ - _contentMargins: {left: number|null, right: number|null} = {left: null, right: null}; + _contentMargins: {left: number | null; right: number | null} = {left: null, right: null}; - readonly _contentMarginChanges = new Subject<{left: number|null, right: number|null}>(); + readonly _contentMarginChanges = new Subject<{left: number | null; right: number | null}>(); /** Reference to the CdkScrollable instance that wraps the scrollable content. */ get scrollable(): CdkScrollable { return this._userContent || this._content; } - constructor(@Optional() private _dir: Directionality, - private _element: ElementRef, - private _ngZone: NgZone, - private _changeDetectorRef: ChangeDetectorRef, - viewportRuler: ViewportRuler, - @Inject(MAT_DRAWER_DEFAULT_AUTOSIZE) defaultAutosize = false, - @Optional() @Inject(ANIMATION_MODULE_TYPE) private _animationMode?: string) { - + constructor( + @Optional() private _dir: Directionality, + private _element: ElementRef, + private _ngZone: NgZone, + private _changeDetectorRef: ChangeDetectorRef, + viewportRuler: ViewportRuler, + @Inject(MAT_DRAWER_DEFAULT_AUTOSIZE) defaultAutosize = false, + @Optional() @Inject(ANIMATION_MODULE_TYPE) private _animationMode?: string, + ) { // If a `Dir` directive exists up the tree, listen direction changes // and update the left/right properties to point to the proper start/end. if (_dir) { @@ -611,7 +703,8 @@ export class MatDrawerContainer implements AfterContentInit, DoCheck, OnDestroy // Since the minimum width of the sidenav depends on the viewport width, // we need to recompute the margins if the viewport changes. - viewportRuler.change() + viewportRuler + .change() .pipe(takeUntil(this._destroyed)) .subscribe(() => this.updateContentMargins()); @@ -635,9 +728,11 @@ export class MatDrawerContainer implements AfterContentInit, DoCheck, OnDestroy this._watchDrawerMode(drawer); }); - if (!this._drawers.length || - this._isDrawerOpen(this._start) || - this._isDrawerOpen(this._end)) { + if ( + !this._drawers.length || + this._isDrawerOpen(this._start) || + this._isDrawerOpen(this._end) + ) { this.updateContentMargins(); } @@ -646,10 +741,12 @@ export class MatDrawerContainer implements AfterContentInit, DoCheck, OnDestroy // Avoid hitting the NgZone through the debounce timeout. this._ngZone.runOutsideAngular(() => { - this._doCheckSubject.pipe( - debounceTime(10), // Arbitrary debounce time, less than a frame at 60fps - takeUntil(this._destroyed) - ).subscribe(() => this.updateContentMargins()); + this._doCheckSubject + .pipe( + debounceTime(10), // Arbitrary debounce time, less than a frame at 60fps + takeUntil(this._destroyed), + ) + .subscribe(() => this.updateContentMargins()); }); } @@ -735,24 +832,26 @@ export class MatDrawerContainer implements AfterContentInit, DoCheck, OnDestroy * is properly hidden. */ private _watchDrawerToggle(drawer: MatDrawer): void { - drawer._animationStarted.pipe( - filter((event: AnimationEvent) => event.fromState !== event.toState), - takeUntil(this._drawers.changes), - ) - .subscribe((event: AnimationEvent) => { - // Set the transition class on the container so that the animations occur. This should not - // be set initially because animations should only be triggered via a change in state. - if (event.toState !== 'open-instant' && this._animationMode !== 'NoopAnimations') { - this._element.nativeElement.classList.add('mat-drawer-transition'); - } + drawer._animationStarted + .pipe( + filter((event: AnimationEvent) => event.fromState !== event.toState), + takeUntil(this._drawers.changes), + ) + .subscribe((event: AnimationEvent) => { + // Set the transition class on the container so that the animations occur. This should not + // be set initially because animations should only be triggered via a change in state. + if (event.toState !== 'open-instant' && this._animationMode !== 'NoopAnimations') { + this._element.nativeElement.classList.add('mat-drawer-transition'); + } - this.updateContentMargins(); - this._changeDetectorRef.markForCheck(); - }); + this.updateContentMargins(); + this._changeDetectorRef.markForCheck(); + }); if (drawer.mode !== 'side') { - drawer.openedChange.pipe(takeUntil(this._drawers.changes)).subscribe(() => - this._setContainerClass(drawer.opened)); + drawer.openedChange + .pipe(takeUntil(this._drawers.changes)) + .subscribe(() => this._setContainerClass(drawer.opened)); } } @@ -776,7 +875,8 @@ export class MatDrawerContainer implements AfterContentInit, DoCheck, OnDestroy /** Subscribes to changes in drawer mode so we can run change detection. */ private _watchDrawerMode(drawer: MatDrawer): void { if (drawer) { - drawer._modeChanged.pipe(takeUntil(merge(this._drawers.changes, this._destroyed))) + drawer._modeChanged + .pipe(takeUntil(merge(this._drawers.changes, this._destroyed))) .subscribe(() => { this.updateContentMargins(); this._changeDetectorRef.markForCheck(); @@ -829,8 +929,10 @@ export class MatDrawerContainer implements AfterContentInit, DoCheck, OnDestroy /** Whether the container is being pushed to the side by one of the drawers. */ private _isPushed() { - return (this._isDrawerOpen(this._start) && this._start.mode != 'over') || - (this._isDrawerOpen(this._end) && this._end.mode != 'over'); + return ( + (this._isDrawerOpen(this._start) && this._start.mode != 'over') || + (this._isDrawerOpen(this._end) && this._end.mode != 'over') + ); } _onBackdropClicked() { @@ -846,8 +948,10 @@ export class MatDrawerContainer implements AfterContentInit, DoCheck, OnDestroy } _isShowingBackdrop(): boolean { - return (this._isDrawerOpen(this._start) && this._canHaveBackdrop(this._start)) || - (this._isDrawerOpen(this._end) && this._canHaveBackdrop(this._end)); + return ( + (this._isDrawerOpen(this._start) && this._canHaveBackdrop(this._start)) || + (this._isDrawerOpen(this._end) && this._canHaveBackdrop(this._end)) + ); } private _canHaveBackdrop(drawer: MatDrawer): boolean { @@ -857,7 +961,4 @@ export class MatDrawerContainer implements AfterContentInit, DoCheck, OnDestroy private _isDrawerOpen(drawer: MatDrawer | null): drawer is MatDrawer { return drawer != null && drawer.opened; } - - static ngAcceptInputType_autosize: BooleanInput; - static ngAcceptInputType_hasBackdrop: BooleanInput; } diff --git a/src/material/sidenav/sidenav-module.ts b/src/material/sidenav/sidenav-module.ts index ed51ac5a8ccc..f43299397e0f 100644 --- a/src/material/sidenav/sidenav-module.ts +++ b/src/material/sidenav/sidenav-module.ts @@ -13,14 +13,8 @@ import {MatCommonModule} from '@angular/material/core'; import {MatDrawer, MatDrawerContainer, MatDrawerContent} from './drawer'; import {MatSidenav, MatSidenavContainer, MatSidenavContent} from './sidenav'; - @NgModule({ - imports: [ - CommonModule, - MatCommonModule, - PlatformModule, - CdkScrollableModule, - ], + imports: [CommonModule, MatCommonModule, PlatformModule, CdkScrollableModule], exports: [ CdkScrollableModule, MatCommonModule, diff --git a/src/material/sidenav/sidenav.spec.ts b/src/material/sidenav/sidenav.spec.ts index 3f4cb0bf7075..6f11f8e8cd50 100644 --- a/src/material/sidenav/sidenav.spec.ts +++ b/src/material/sidenav/sidenav.spec.ts @@ -5,16 +5,21 @@ import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {By} from '@angular/platform-browser'; import {CommonModule} from '@angular/common'; - describe('MatSidenav', () => { - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatSidenavModule, NoopAnimationsModule, CommonModule], - declarations: [SidenavWithFixedPosition, IndirectDescendantSidenav, NestedSidenavContainers], - }); - - TestBed.compileComponents(); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatSidenavModule, NoopAnimationsModule, CommonModule], + declarations: [ + SidenavWithFixedPosition, + IndirectDescendantSidenav, + NestedSidenavContainers, + ], + }); + + TestBed.compileComponents(); + }), + ); it('should be fixed position when in fixed mode', () => { const fixture = TestBed.createComponent(SidenavWithFixedPosition); @@ -82,10 +87,8 @@ describe('MatSidenav', () => { expect(instance.outerSidenav.opened).toBe(true); expect(instance.innerSidenav.opened).toBe(true); })); - }); - @Component({ template: ` @@ -107,7 +110,6 @@ class SidenavWithFixedPosition { fixedBottom = 30; } - @Component({ // Note that we need the `ng-container` with the `ngSwitch` so that // there's a directive between the container and the sidenav. diff --git a/src/material/sidenav/sidenav.ts b/src/material/sidenav/sidenav.ts index 1461f832429c..a18b6d682e37 100644 --- a/src/material/sidenav/sidenav.ts +++ b/src/material/sidenav/sidenav.ts @@ -26,11 +26,10 @@ import { BooleanInput, coerceBooleanProperty, coerceNumberProperty, - NumberInput + NumberInput, } from '@angular/cdk/coercion'; import {ScrollDispatcher} from '@angular/cdk/scrolling'; - @Component({ selector: 'mat-sidenav-content', template: '', @@ -44,16 +43,16 @@ import {ScrollDispatcher} from '@angular/cdk/scrolling'; }) export class MatSidenavContent extends MatDrawerContent { constructor( - changeDetectorRef: ChangeDetectorRef, - @Inject(forwardRef(() => MatSidenavContainer)) container: MatSidenavContainer, - elementRef: ElementRef, - scrollDispatcher: ScrollDispatcher, - ngZone: NgZone) { + changeDetectorRef: ChangeDetectorRef, + @Inject(forwardRef(() => MatSidenavContainer)) container: MatSidenavContainer, + elementRef: ElementRef, + scrollDispatcher: ScrollDispatcher, + ngZone: NgZone, + ) { super(changeDetectorRef, container, elementRef, scrollDispatcher, ngZone); } } - @Component({ selector: 'mat-sidenav', exportAs: 'matSidenav', @@ -79,8 +78,12 @@ export class MatSidenavContent extends MatDrawerContent { export class MatSidenav extends MatDrawer { /** Whether the sidenav is fixed in the viewport. */ @Input() - get fixedInViewport(): boolean { return this._fixedInViewport; } - set fixedInViewport(value) { this._fixedInViewport = coerceBooleanProperty(value); } + get fixedInViewport(): boolean { + return this._fixedInViewport; + } + set fixedInViewport(value: BooleanInput) { + this._fixedInViewport = coerceBooleanProperty(value); + } private _fixedInViewport = false; /** @@ -88,8 +91,12 @@ export class MatSidenav extends MatDrawer { * mode. */ @Input() - get fixedTopGap(): number { return this._fixedTopGap; } - set fixedTopGap(value) { this._fixedTopGap = coerceNumberProperty(value); } + get fixedTopGap(): number { + return this._fixedTopGap; + } + set fixedTopGap(value: NumberInput) { + this._fixedTopGap = coerceNumberProperty(value); + } private _fixedTopGap = 0; /** @@ -97,16 +104,15 @@ export class MatSidenav extends MatDrawer { * fixed mode. */ @Input() - get fixedBottomGap(): number { return this._fixedBottomGap; } - set fixedBottomGap(value) { this._fixedBottomGap = coerceNumberProperty(value); } + get fixedBottomGap(): number { + return this._fixedBottomGap; + } + set fixedBottomGap(value: NumberInput) { + this._fixedBottomGap = coerceNumberProperty(value); + } private _fixedBottomGap = 0; - - static ngAcceptInputType_fixedInViewport: BooleanInput; - static ngAcceptInputType_fixedTopGap: NumberInput; - static ngAcceptInputType_fixedBottomGap: NumberInput; } - @Component({ selector: 'mat-sidenav-container', exportAs: 'matSidenavContainer', @@ -118,20 +124,20 @@ export class MatSidenav extends MatDrawer { }, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, - providers: [{ - provide: MAT_DRAWER_CONTAINER, - useExisting: MatSidenavContainer - }] - + providers: [ + { + provide: MAT_DRAWER_CONTAINER, + useExisting: MatSidenavContainer, + }, + ], }) export class MatSidenavContainer extends MatDrawerContainer { @ContentChildren(MatSidenav, { // We need to use `descendants: true`, because Ivy will no longer match // indirect descendants if it's left as false. - descendants: true + descendants: true, }) - _allDrawers: QueryList; + override _allDrawers: QueryList; - @ContentChild(MatSidenavContent) _content: MatSidenavContent; - static ngAcceptInputType_hasBackdrop: BooleanInput; + @ContentChild(MatSidenavContent) override _content: MatSidenavContent; } diff --git a/src/material/sidenav/testing/BUILD.bazel b/src/material/sidenav/testing/BUILD.bazel index e457315ba9d9..4067849ac7d9 100644 --- a/src/material/sidenav/testing/BUILD.bazel +++ b/src/material/sidenav/testing/BUILD.bazel @@ -8,7 +8,6 @@ ts_library( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material/sidenav/testing", deps = [ "//src/cdk/coercion", "//src/cdk/testing", diff --git a/src/material/sidenav/testing/drawer-container-harness.ts b/src/material/sidenav/testing/drawer-container-harness.ts index cf3a95f36e90..8d095bc1eb23 100644 --- a/src/material/sidenav/testing/drawer-container-harness.ts +++ b/src/material/sidenav/testing/drawer-container-harness.ts @@ -22,8 +22,9 @@ export class MatDrawerContainerHarness extends ContentContainerComponentHarness< * @param options Options for filtering which container instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ - static with(options: DrawerContainerHarnessFilters = {}): - HarnessPredicate { + static with( + options: DrawerContainerHarnessFilters = {}, + ): HarnessPredicate { return new HarnessPredicate(MatDrawerContainerHarness, options); } diff --git a/src/material/sidenav/testing/drawer-content-harness.ts b/src/material/sidenav/testing/drawer-content-harness.ts index 416b0195ee00..bb7286337fb1 100644 --- a/src/material/sidenav/testing/drawer-content-harness.ts +++ b/src/material/sidenav/testing/drawer-content-harness.ts @@ -20,8 +20,9 @@ export class MatDrawerContentHarness extends ContentContainerComponentHarness { + static with( + options: DrawerContentHarnessFilters = {}, + ): HarnessPredicate { return new HarnessPredicate(MatDrawerContentHarness, options); } } diff --git a/src/material/sidenav/testing/drawer-harness.ts b/src/material/sidenav/testing/drawer-harness.ts index f5604b48eece..6b6318760286 100644 --- a/src/material/sidenav/testing/drawer-harness.ts +++ b/src/material/sidenav/testing/drawer-harness.ts @@ -20,13 +20,13 @@ export class MatDrawerHarnessBase extends ContentContainerComponentHarness { + async getPosition(): Promise<'start' | 'end'> { const host = await this.host(); return (await host.hasClass('mat-drawer-end')) ? 'end' : 'start'; } /** Gets the mode that the drawer is in. */ - async getMode(): Promise<'over'|'push'|'side'> { + async getMode(): Promise<'over' | 'push' | 'side'> { const host = await this.host(); if (await host.hasClass('mat-drawer-push')) { @@ -53,8 +53,10 @@ export class MatDrawerHarness extends MatDrawerHarnessBase { * @return a `HarnessPredicate` configured with the given options. */ static with(options: DrawerHarnessFilters = {}): HarnessPredicate { - return new HarnessPredicate(MatDrawerHarness, options) - .addOption('position', options.position, - async (harness, position) => (await harness.getPosition()) === position); + return new HarnessPredicate(MatDrawerHarness, options).addOption( + 'position', + options.position, + async (harness, position) => (await harness.getPosition()) === position, + ); } } diff --git a/src/material/sidenav/testing/shared.spec.ts b/src/material/sidenav/testing/shared.spec.ts index 85f56ad97401..95fb39709b08 100644 --- a/src/material/sidenav/testing/shared.spec.ts +++ b/src/material/sidenav/testing/shared.spec.ts @@ -12,13 +12,15 @@ import {MatSidenavContentHarness} from './sidenav-content-harness'; import {MatSidenavHarness} from './sidenav-harness'; /** Shared tests to run on both the original and MDC-based drawer & sidenav. */ -export function runHarnessTests(sidenavModule: typeof MatSidenavModule, - drawerHarness: typeof MatDrawerHarness, - drawerContainerHarness: typeof MatDrawerContainerHarness, - drawerContentHarness: typeof MatDrawerContentHarness, - sidenavHarness: typeof MatSidenavHarness, - sidenavContainerHarness: typeof MatSidenavContainerHarness, - sidenavContentHarness: typeof MatSidenavContentHarness) { +export function runHarnessTests( + sidenavModule: typeof MatSidenavModule, + drawerHarness: typeof MatDrawerHarness, + drawerContainerHarness: typeof MatDrawerContainerHarness, + drawerContentHarness: typeof MatDrawerContentHarness, + sidenavHarness: typeof MatSidenavHarness, + sidenavContainerHarness: typeof MatSidenavContainerHarness, + sidenavContentHarness: typeof MatSidenavContentHarness, +) { describe('drawer', () => { let fixture: ComponentFixture; let loader: HarnessLoader; @@ -87,13 +89,17 @@ export function runHarnessTests(sidenavModule: typeof MatSidenavModule, return containers.map(container => container.getDrawers()); }); - expect(await parallel(() => { - return firstContainerDrawers.map(async container => (await container.host()).text()); - })).toEqual(['One', 'Two']); + expect( + await parallel(() => { + return firstContainerDrawers.map(async container => (await container.host()).text()); + }), + ).toEqual(['One', 'Two']); - expect(await parallel(() => { - return secondContainerDrawers.map(async container => (await container.host()).text()); - })).toEqual(['Three']); + expect( + await parallel(() => { + return secondContainerDrawers.map(async container => (await container.host()).text()); + }), + ).toEqual(['Three']); }); it('should get the content of a container', async () => { @@ -106,7 +112,6 @@ export function runHarnessTests(sidenavModule: typeof MatSidenavModule, const contentElements = await loader.getAllHarnesses(drawerContentHarness); expect(contentElements.length).toBe(2); }); - }); describe('sidenav', () => { @@ -143,13 +148,17 @@ export function runHarnessTests(sidenavModule: typeof MatSidenavModule, return containers.map(container => container.getSidenavs()); }); - expect(await parallel(() => { - return firstContainerSidenavs.map(async container => (await container.host()).text()); - })).toEqual(['One', 'Two']); + expect( + await parallel(() => { + return firstContainerSidenavs.map(async container => (await container.host()).text()); + }), + ).toEqual(['One', 'Two']); - expect(await parallel(() => { - return secondContainerSidenavs.map(async container => (await container.host()).text()); - })).toEqual(['Three']); + expect( + await parallel(() => { + return secondContainerSidenavs.map(async container => (await container.host()).text()); + }), + ).toEqual(['Three']); }); it('should get the content of a container', async () => { @@ -162,7 +171,6 @@ export function runHarnessTests(sidenavModule: typeof MatSidenavModule, const contentElements = await loader.getAllHarnesses(sidenavContentHarness); expect(contentElements.length).toBe(2); }); - }); } @@ -178,7 +186,7 @@ export function runHarnessTests(sidenavModule: typeof MatSidenavModule, Three Content - ` + `, }) class DrawerHarnessTest { threeOpened = true; @@ -196,6 +204,6 @@ class DrawerHarnessTest { Three Content - ` + `, }) class SidenavHarnessTest {} diff --git a/src/material/sidenav/testing/sidenav-container-harness.ts b/src/material/sidenav/testing/sidenav-container-harness.ts index 897bb43b8e78..c2b905df4f3e 100644 --- a/src/material/sidenav/testing/sidenav-container-harness.ts +++ b/src/material/sidenav/testing/sidenav-container-harness.ts @@ -22,8 +22,9 @@ export class MatSidenavContainerHarness extends ContentContainerComponentHarness * @param options Options for filtering which container instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ - static with(options: DrawerContainerHarnessFilters = {}): - HarnessPredicate { + static with( + options: DrawerContainerHarnessFilters = {}, + ): HarnessPredicate { return new HarnessPredicate(MatSidenavContainerHarness, options); } diff --git a/src/material/sidenav/testing/sidenav-content-harness.ts b/src/material/sidenav/testing/sidenav-content-harness.ts index 06aebfa6703f..1b3b0328e8cf 100644 --- a/src/material/sidenav/testing/sidenav-content-harness.ts +++ b/src/material/sidenav/testing/sidenav-content-harness.ts @@ -20,8 +20,9 @@ export class MatSidenavContentHarness extends ContentContainerComponentHarness { + static with( + options: DrawerContentHarnessFilters = {}, + ): HarnessPredicate { return new HarnessPredicate(MatSidenavContentHarness, options); } } diff --git a/src/material/sidenav/testing/sidenav-harness.spec.ts b/src/material/sidenav/testing/sidenav-harness.spec.ts index 7c3e45c407a4..a0288cc039f4 100644 --- a/src/material/sidenav/testing/sidenav-harness.spec.ts +++ b/src/material/sidenav/testing/sidenav-harness.spec.ts @@ -15,6 +15,6 @@ describe('Non-MDC-based', () => { MatDrawerContentHarness, MatSidenavHarness, MatSidenavContainerHarness, - MatSidenavContentHarness + MatSidenavContentHarness, ); }); diff --git a/src/material/sidenav/testing/sidenav-harness.ts b/src/material/sidenav/testing/sidenav-harness.ts index fee959706de5..41178466053f 100644 --- a/src/material/sidenav/testing/sidenav-harness.ts +++ b/src/material/sidenav/testing/sidenav-harness.ts @@ -22,9 +22,11 @@ export class MatSidenavHarness extends MatDrawerHarnessBase { * @return a `HarnessPredicate` configured with the given options. */ static with(options: DrawerHarnessFilters = {}): HarnessPredicate { - return new HarnessPredicate(MatSidenavHarness, options) - .addOption('position', options.position, - async (harness, position) => (await harness.getPosition()) === position); + return new HarnessPredicate(MatSidenavHarness, options).addOption( + 'position', + options.position, + async (harness, position) => (await harness.getPosition()) === position, + ); } /** Whether the sidenav is fixed in the viewport. */ diff --git a/src/material/slide-toggle/BUILD.bazel b/src/material/slide-toggle/BUILD.bazel index 837c84e28d98..c64542e7706a 100644 --- a/src/material/slide-toggle/BUILD.bazel +++ b/src/material/slide-toggle/BUILD.bazel @@ -19,7 +19,6 @@ ng_module( exclude = ["**/*.spec.ts"], ), assets = [":slide-toggle.css"] + glob(["**/*.html"]), - module_name = "@angular/material/slide-toggle", deps = [ "//src/cdk/a11y", "//src/cdk/coercion", diff --git a/src/material/slide-toggle/_slide-toggle-legacy-index.scss b/src/material/slide-toggle/_slide-toggle-legacy-index.scss new file mode 100644 index 000000000000..4ed8c0b37161 --- /dev/null +++ b/src/material/slide-toggle/_slide-toggle-legacy-index.scss @@ -0,0 +1,3 @@ +@forward 'slide-toggle-theme' hide color, theme, typography; +@forward 'slide-toggle-theme' as mat-slide-toggle-* hide mat-slide-toggle-checked, +mat-slide-toggle-density; diff --git a/src/material/slide-toggle/_slide-toggle-theme.import.scss b/src/material/slide-toggle/_slide-toggle-theme.import.scss new file mode 100644 index 000000000000..bfda867ea93d --- /dev/null +++ b/src/material/slide-toggle/_slide-toggle-theme.import.scss @@ -0,0 +1,11 @@ +@forward '../core/style/private.import'; +@forward '../core/theming/theming.import'; +@forward '../core/typography/typography-utils.import'; +@forward 'slide-toggle-theme' hide color, theme, typography; +@forward 'slide-toggle-theme' as mat-slide-toggle-* hide mat-slide-toggle-checked, +mat-slide-toggle-density; + +@import '../core/style/private'; +@import '../core/theming/palette'; +@import '../core/theming/theming'; +@import '../core/typography/typography-utils'; diff --git a/src/material/slide-toggle/_slide-toggle-theme.scss b/src/material/slide-toggle/_slide-toggle-theme.scss index 9d45d46078ca..e8ade454af1b 100644 --- a/src/material/slide-toggle/_slide-toggle-theme.scss +++ b/src/material/slide-toggle/_slide-toggle-theme.scss @@ -1,36 +1,38 @@ -@import '../core/style/private'; -@import '../core/theming/palette'; -@import '../core/theming/theming'; -@import '../core/typography/typography-utils'; - -@mixin _mat-slide-toggle-checked($palette, $thumb-checked-hue) { +@use 'sass:map'; +@use '../core/style/private'; +@use '../core/theming/palette'; +@use '../core/theming/theming'; +@use '../core/typography/typography'; +@use '../core/typography/typography-utils'; + +@mixin _checked-color($palette, $thumb-checked-hue) { &.mat-checked { .mat-slide-toggle-thumb { - background-color: mat-color($palette, $thumb-checked-hue); + background-color: theming.get-color-from-palette($palette, $thumb-checked-hue); } .mat-slide-toggle-bar { // Opacity is determined from the specs for the selection controls. // See: https://material.io/design/components/selection-controls.html#specs - background-color: mat-color($palette, $thumb-checked-hue, 0.54); + background-color: theming.get-color-from-palette($palette, $thumb-checked-hue, 0.54); } .mat-ripple-element { // Set no opacity for the ripples because the ripple opacity will be adjusted dynamically // based on the type of interaction with the slide-toggle (e.g. for hover, focus) - background-color: mat-color($palette, $thumb-checked-hue); + background-color: theming.get-color-from-palette($palette, $thumb-checked-hue); } } } -@mixin mat-slide-toggle-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $is-dark: map-get($config, is-dark); - $primary: map-get($config, primary); - $accent: map-get($config, accent); - $warn: map-get($config, warn); - $background: map-get($config, background); - $foreground: map-get($config, foreground); +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $is-dark: map.get($config, is-dark); + $primary: map.get($config, primary); + $accent: map.get($config, accent); + $warn: map.get($config, warn); + $background: map.get($config, background); + $foreground: map.get($config, foreground); // Color hues are based on the specs which briefly show the hues that are applied to a switch. // The 2018 specs no longer describe how dark switches should look like. Due to the lack of @@ -41,18 +43,18 @@ $thumb-unchecked-hue: if($is-dark, 400, 50); $thumb-checked-hue: default; - $bar-unchecked-color: mat-color($foreground, disabled); - $ripple-unchecked-color: mat-color($foreground, base); + $bar-unchecked-color: theming.get-color-from-palette($foreground, disabled); + $ripple-unchecked-color: theming.get-color-from-palette($foreground, base); .mat-slide-toggle { - @include _mat-slide-toggle-checked($accent, $thumb-checked-hue); + @include _checked-color($accent, $thumb-checked-hue); &.mat-primary { - @include _mat-slide-toggle-checked($primary, $thumb-checked-hue); + @include _checked-color($primary, $thumb-checked-hue); } &.mat-warn { - @include _mat-slide-toggle-checked($warn, $thumb-checked-hue); + @include _checked-color($warn, $thumb-checked-hue); } &:not(.mat-checked) .mat-ripple-element { @@ -63,8 +65,8 @@ } .mat-slide-toggle-thumb { - @include mat-private-theme-elevation(1, $config); - background-color: mat-color($mat-grey, $thumb-unchecked-hue); + @include private.private-theme-elevation(1, $config); + background-color: theming.get-color-from-palette(palette.$grey-palette, $thumb-unchecked-hue); } .mat-slide-toggle-bar { @@ -72,30 +74,31 @@ } } -@mixin mat-slide-toggle-typography($config-or-theme) { - $config: mat-get-typography-config($config-or-theme); +@mixin typography($config-or-theme) { + $config: typography.private-typography-to-2014-config( + theming.get-typography-config($config-or-theme)); .mat-slide-toggle-content { - font-family: mat-font-family($config); + font-family: typography-utils.font-family($config); } } -@mixin _mat-slide-toggle-density($config-or-theme) {} +@mixin _density($config-or-theme) {} -@mixin mat-slide-toggle-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-slide-toggle') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-slide-toggle') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); @if $color != null { - @include mat-slide-toggle-color($color); + @include color($color); } @if $density != null { - @include _mat-slide-toggle-density($density); + @include _density($density); } @if $typography != null { - @include mat-slide-toggle-typography($typography); + @include typography($typography); } } } diff --git a/src/material/slide-toggle/slide-toggle-config.ts b/src/material/slide-toggle/slide-toggle-config.ts index 641acc0d8102..30ae3cf64623 100644 --- a/src/material/slide-toggle/slide-toggle-config.ts +++ b/src/material/slide-toggle/slide-toggle-config.ts @@ -6,17 +6,22 @@ * found in the LICENSE file at https://angular.io/license */ import {InjectionToken} from '@angular/core'; - +import {ThemePalette} from '@angular/material/core'; /** Default `mat-slide-toggle` options that can be overridden. */ export interface MatSlideToggleDefaultOptions { /** Whether toggle action triggers value changes in slide toggle. */ disableToggleValue?: boolean; + + /** Default color for slide toggles. */ + color?: ThemePalette; } /** Injection token to be used to override the default options for `mat-slide-toggle`. */ -export const MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS = - new InjectionToken('mat-slide-toggle-default-options', { +export const MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS = new InjectionToken( + 'mat-slide-toggle-default-options', + { providedIn: 'root', - factory: () => ({disableToggleValue: false}) - }); + factory: () => ({disableToggleValue: false}), + }, +); diff --git a/src/material/slide-toggle/slide-toggle-module.ts b/src/material/slide-toggle/slide-toggle-module.ts index c79c3dbcbb6c..4b9163822a58 100644 --- a/src/material/slide-toggle/slide-toggle-module.ts +++ b/src/material/slide-toggle/slide-toggle-module.ts @@ -26,11 +26,7 @@ export class _MatSlideToggleRequiredValidatorModule {} MatCommonModule, ObserversModule, ], - exports: [ - _MatSlideToggleRequiredValidatorModule, - MatSlideToggle, - MatCommonModule - ], + exports: [_MatSlideToggleRequiredValidatorModule, MatSlideToggle, MatCommonModule], declarations: [MatSlideToggle], }) export class MatSlideToggleModule {} diff --git a/src/material/slide-toggle/slide-toggle-required-validator.ts b/src/material/slide-toggle/slide-toggle-required-validator.ts index 768881e7d7c7..e17c59e12fac 100644 --- a/src/material/slide-toggle/slide-toggle-required-validator.ts +++ b/src/material/slide-toggle/slide-toggle-required-validator.ts @@ -6,20 +6,13 @@ * found in the LICENSE file at https://angular.io/license */ -import { - Directive, - forwardRef, - Provider, -} from '@angular/core'; -import { - CheckboxRequiredValidator, - NG_VALIDATORS, -} from '@angular/forms'; +import {Directive, forwardRef, Provider} from '@angular/core'; +import {CheckboxRequiredValidator, NG_VALIDATORS} from '@angular/forms'; export const MAT_SLIDE_TOGGLE_REQUIRED_VALIDATOR: Provider = { provide: NG_VALIDATORS, useExisting: forwardRef(() => MatSlideToggleRequiredValidator), - multi: true + multi: true, }; /** diff --git a/src/material/slide-toggle/slide-toggle.e2e.spec.ts b/src/material/slide-toggle/slide-toggle.e2e.spec.ts index fd3544187b49..615590383467 100644 --- a/src/material/slide-toggle/slide-toggle.e2e.spec.ts +++ b/src/material/slide-toggle/slide-toggle.e2e.spec.ts @@ -1,6 +1,5 @@ import {browser, element, by, Key} from 'protractor'; -import {expectToExist} from '@angular/cdk/testing/private/e2e'; - +import {expectToExist} from '../../cdk/testing/private/e2e'; describe('slide-toggle', () => { const getInput = () => element(by.css('#normal-slide-toggle input')); @@ -15,37 +14,31 @@ describe('slide-toggle', () => { it('should change the checked state on click', async () => { const inputEl = getInput(); - expect(await inputEl.getAttribute('checked')) - .toBeFalsy('Expect slide-toggle to be unchecked'); + expect(await inputEl.getAttribute('checked')).toBeFalsy('Expect slide-toggle to be unchecked'); await getNormalToggle().click(); - expect(await inputEl.getAttribute('checked')) - .toBeTruthy('Expect slide-toggle to be checked'); + expect(await inputEl.getAttribute('checked')).toBeTruthy('Expect slide-toggle to be checked'); }); it('should change the checked state on click', async () => { const inputEl = getInput(); - expect(await inputEl.getAttribute('checked')) - .toBeFalsy('Expect slide-toggle to be unchecked'); + expect(await inputEl.getAttribute('checked')).toBeFalsy('Expect slide-toggle to be unchecked'); await getNormalToggle().click(); - expect(await inputEl.getAttribute('checked')) - .toBeTruthy('Expect slide-toggle to be checked'); + expect(await inputEl.getAttribute('checked')).toBeTruthy('Expect slide-toggle to be checked'); }); it('should not change the checked state on click when disabled', async () => { const inputEl = getInput(); - expect(await inputEl.getAttribute('checked')) - .toBeFalsy('Expect slide-toggle to be unchecked'); + expect(await inputEl.getAttribute('checked')).toBeFalsy('Expect slide-toggle to be unchecked'); await element(by.css('#disabled-slide-toggle')).click(); - expect(await inputEl.getAttribute('checked')) - .toBeFalsy('Expect slide-toggle to be unchecked'); + expect(await inputEl.getAttribute('checked')).toBeFalsy('Expect slide-toggle to be unchecked'); }); it('should move the thumb on state change', async () => { @@ -63,13 +56,10 @@ describe('slide-toggle', () => { it('should toggle the slide-toggle on space key', async () => { const inputEl = getInput(); - expect(await inputEl.getAttribute('checked')) - .toBeFalsy('Expect slide-toggle to be unchecked'); + expect(await inputEl.getAttribute('checked')).toBeFalsy('Expect slide-toggle to be unchecked'); await inputEl.sendKeys(Key.SPACE); - expect(await inputEl.getAttribute('checked')) - .toBeTruthy('Expect slide-toggle to be checked'); + expect(await inputEl.getAttribute('checked')).toBeTruthy('Expect slide-toggle to be checked'); }); - }); diff --git a/src/material/slide-toggle/slide-toggle.html b/src/material/slide-toggle/slide-toggle.html index 6cac9b59b378..d1ee1a490523 100644 --- a/src/material/slide-toggle/slide-toggle.html +++ b/src/material/slide-toggle/slide-toggle.html @@ -13,6 +13,7 @@ [attr.aria-checked]="checked.toString()" [attr.aria-label]="ariaLabel" [attr.aria-labelledby]="ariaLabelledby" + [attr.aria-describedby]="ariaDescribedby" (change)="_onChangeEvent($event)" (click)="_onInputClick($event)"> @@ -23,7 +24,7 @@ [matRippleDisabled]="disableRipple || disabled" [matRippleCentered]="true" [matRippleRadius]="20" - [matRippleAnimation]="{enterDuration: 150}"> + [matRippleAnimation]="{enterDuration: _noopAnimations ? 0 : 150}">
diff --git a/src/material/slide-toggle/slide-toggle.md b/src/material/slide-toggle/slide-toggle.md index 4f6aefe7482a..fb51508ef55c 100644 --- a/src/material/slide-toggle/slide-toggle.md +++ b/src/material/slide-toggle/slide-toggle.md @@ -22,9 +22,18 @@ The color of a `` can be changed by using the `color` property slide-toggles use the theme's accent color. This can be changed to `'primary'` or `'warn'`. ### Accessibility -The `` uses an internal `` to provide an accessible -experience. This internal checkbox receives focus and is automatically labelled by the text content -of the `` element. -Slide toggles without text or labels should be given a meaningful label via `aria-label` or -`aria-labelledby`. +`MatSlideToggle` uses an internal `` with `role="switch"` to provide an +accessible experience. This internal checkbox receives focus and is automatically labelled by the +text content of the `` element. Avoid adding other interactive controls into the +content of ``, as this degrades the experience for users of assistive technology. + +Always provide an accessible label via `aria-label` or `aria-labelledby` for toggles without +descriptive text content. For dynamic labels, `MatSlideToggle` provides input properties for binding +`aria-label` and `aria-labelledby`. This means that you should not use the `attr.` prefix when +binding these properties, as demonstrated below. + +```html + + +``` diff --git a/src/material/slide-toggle/slide-toggle.scss b/src/material/slide-toggle/slide-toggle.scss index 70c673a64003..5a68bf0df822 100644 --- a/src/material/slide-toggle/slide-toggle.scss +++ b/src/material/slide-toggle/slide-toggle.scss @@ -1,24 +1,26 @@ -@import '../core/style/variables'; -@import '../core/ripple/ripple'; -@import '../core/style/list-common'; -@import '../../cdk/a11y/a11y'; - -$mat-slide-toggle-thumb-size: 20px !default; -$mat-slide-toggle-bar-border-radius: 8px !default; -$mat-slide-toggle-height: 24px !default; -$mat-slide-toggle-spacing: 8px !default; -$mat-slide-toggle-ripple-radius: 20px !default; -$mat-slide-toggle-bar-width: 36px !default; -$mat-slide-toggle-bar-height: 14px !default; -$mat-slide-toggle-bar-track-width: $mat-slide-toggle-bar-width - $mat-slide-toggle-thumb-size; +@use 'sass:math'; +@use '../core/style/vendor-prefixes'; +@use '../core/style/variables'; +@use '../core/ripple/ripple'; +@use '../core/style/list-common'; +@use '../../cdk/a11y'; + +$thumb-size: 20px !default; +$bar-border-radius: 8px !default; +$height: 24px !default; +$spacing: 8px !default; +$ripple-radius: 20px !default; +$bar-width: 36px !default; +$bar-height: 14px !default; +$bar-track-width: $bar-width - $thumb-size; .mat-slide-toggle { display: inline-block; - height: $mat-slide-toggle-height; + height: $height; max-width: 100%; - line-height: $mat-slide-toggle-height; + line-height: $height; white-space: nowrap; outline: none; @@ -26,10 +28,10 @@ $mat-slide-toggle-bar-track-width: $mat-slide-toggle-bar-width - $mat-slide-togg &.mat-checked { .mat-slide-toggle-thumb-container { - transform: translate3d($mat-slide-toggle-bar-track-width, 0, 0); + transform: translate3d($bar-track-width, 0, 0); [dir='rtl'] & { - transform: translate3d(-$mat-slide-toggle-bar-track-width, 0, 0); + transform: translate3d(-$bar-track-width, 0, 0); } } } @@ -47,6 +49,7 @@ $mat-slide-toggle-bar-track-width: $mat-slide-toggle-bar-width - $mat-slide-togg // The label element is our root container for the slide-toggle / switch indicator and label text. // It has to be a label, to support accessibility for the visual hidden input. .mat-slide-toggle-label { + @include vendor-prefixes.user-select(none); display: flex; flex: 1; flex-direction: row; @@ -56,10 +59,10 @@ $mat-slide-toggle-bar-track-width: $mat-slide-toggle-bar-width - $mat-slide-togg } .mat-slide-toggle-content { - @include mat-truncate-line(); + @include list-common.truncate-line(); } -/* If the label should be placed before the thumb then we just change the orders. */ +// If the label should be placed before the thumb then we just change the orders. .mat-slide-toggle-label-before { .mat-slide-toggle-label { order: 1; } .mat-slide-toggle-bar { order: 2; } @@ -68,7 +71,7 @@ $mat-slide-toggle-bar-track-width: $mat-slide-toggle-bar-width - $mat-slide-togg // Apply the margin for slide-toggles and revert it for RTL toggles with labelPosition before. [dir='rtl'] .mat-slide-toggle-label-before .mat-slide-toggle-bar, .mat-slide-toggle-bar { - margin-right: $mat-slide-toggle-spacing; + margin-right: $spacing; margin-left: 0; } @@ -76,7 +79,7 @@ $mat-slide-toggle-bar-track-width: $mat-slide-toggle-bar-width - $mat-slide-togg [dir='rtl'], .mat-slide-toggle-label-before { .mat-slide-toggle-bar { - margin-left: $mat-slide-toggle-spacing; + margin-left: $spacing; margin-right: 0; } } @@ -88,18 +91,18 @@ $mat-slide-toggle-bar-track-width: $mat-slide-toggle-bar-width - $mat-slide-togg // The container includes the visual thumb and the ripple container element. .mat-slide-toggle-thumb-container { - $thumb-bar-vertical-padding: ($mat-slide-toggle-thumb-size - $mat-slide-toggle-bar-height) / 2; + $thumb-bar-vertical-padding: math.div($thumb-size - $bar-height, 2); position: absolute; z-index: 1; - width: $mat-slide-toggle-thumb-size; - height: $mat-slide-toggle-thumb-size; + width: $thumb-size; + height: $thumb-size; top: -$thumb-bar-vertical-padding; left: 0; transform: translate3d(0, 0, 0); - transition: $swift-linear; + transition: variables.$swift-linear; transition-property: transform; ._mat-animation-noopable & { @@ -115,8 +118,8 @@ $mat-slide-toggle-bar-track-width: $mat-slide-toggle-bar-width - $mat-slide-togg // The visual thumb element that moves inside of the thumb bar. // The parent thumb-container container is responsible for the movement of the visual thumb. .mat-slide-toggle-thumb { - height: $mat-slide-toggle-thumb-size; - width: $mat-slide-toggle-thumb-size; + height: $thumb-size; + width: $thumb-size; border-radius: 50%; } @@ -125,14 +128,14 @@ $mat-slide-toggle-bar-track-width: $mat-slide-toggle-bar-width - $mat-slide-togg .mat-slide-toggle-bar { position: relative; - width: $mat-slide-toggle-bar-width; - height: $mat-slide-toggle-bar-height; + width: $bar-width; + height: $bar-height; // Prevent shrinking of the bar container. It can happen that the content is long enough to // shrink the bar and the thumb. flex-shrink: 0; - border-radius: $mat-slide-toggle-bar-border-radius; + border-radius: $bar-border-radius; } // The slide toggle shows a visually hidden input inside of the component, which is used @@ -140,7 +143,7 @@ $mat-slide-toggle-bar-track-width: $mat-slide-toggle-bar-width - $mat-slide-togg .mat-slide-toggle-input { // Move the input to the bottom and in the middle of the thumb. // Visual improvement to properly show browser popups when being required. - $horizontal-offset: $mat-slide-toggle-thumb-size / 2; + $horizontal-offset: math.div($thumb-size, 2); bottom: 0; left: $horizontal-offset; @@ -153,7 +156,7 @@ $mat-slide-toggle-bar-track-width: $mat-slide-toggle-bar-width - $mat-slide-togg .mat-slide-toggle-bar, .mat-slide-toggle-thumb { - transition: $swift-linear; + transition: variables.$swift-linear; transition-property: background-color; transition-delay: 50ms; @@ -167,10 +170,10 @@ $mat-slide-toggle-bar-track-width: $mat-slide-toggle-bar-width - $mat-slide-togg // potentially overwrite the absolute position of the container. .mat-slide-toggle .mat-slide-toggle-ripple { position: absolute; - top: calc(50% - #{$mat-slide-toggle-ripple-radius}); - left: calc(50% - #{$mat-slide-toggle-ripple-radius}); - height: $mat-slide-toggle-ripple-radius * 2; - width: $mat-slide-toggle-ripple-radius * 2; + top: calc(50% - #{$ripple-radius}); + left: calc(50% - #{$ripple-radius}); + height: $ripple-radius * 2; + width: $ripple-radius * 2; z-index: 1; pointer-events: none; @@ -216,8 +219,8 @@ $mat-slide-toggle-bar-track-width: $mat-slide-toggle-bar-width - $mat-slide-togg } } -/** Custom styling to make the slide-toggle usable in high contrast mode. */ -@include cdk-high-contrast(active, off) { +// Custom styling to make the slide-toggle usable in high contrast mode. +@include a11y.high-contrast(active, off) { .mat-slide-toggle-thumb, .mat-slide-toggle-bar { border: 1px solid; @@ -228,6 +231,6 @@ $mat-slide-toggle-bar-track-width: $mat-slide-toggle-bar-width - $mat-slide-togg // because otherwise the opaque thumb element will hide the outline. .mat-slide-toggle.cdk-keyboard-focused .mat-slide-toggle-bar { outline: 2px dotted; - outline-offset: ($mat-slide-toggle-height - $mat-slide-toggle-bar-height) / 2; + outline-offset: math.div($height - $bar-height, 2); } } diff --git a/src/material/slide-toggle/slide-toggle.spec.ts b/src/material/slide-toggle/slide-toggle.spec.ts index d37a2710e2c1..fd6e137bed9f 100644 --- a/src/material/slide-toggle/slide-toggle.spec.ts +++ b/src/material/slide-toggle/slide-toggle.spec.ts @@ -1,5 +1,5 @@ import {MutationObserverFactory} from '@angular/cdk/observers'; -import {dispatchFakeEvent} from '@angular/cdk/testing/private'; +import {dispatchFakeEvent} from '../../cdk/testing/private'; import {Component, DebugElement} from '@angular/core'; import { ComponentFixture, @@ -40,10 +40,10 @@ describe('MatSlideToggle without forms', () => { create: (callback: Function) => { mutationObserverCallbacks.push(callback); return {observe: () => {}, disconnect: () => {}}; - } - } - } - ] + }, + }, + }, + ], }); TestBed.compileComponents(); @@ -78,7 +78,7 @@ describe('MatSlideToggle without forms', () => { labelElement = fixture.debugElement.query(By.css('label'))!.nativeElement; })); - it('should apply class based on color attribute', () => { + it('should apply class based on color attribute', fakeAsync(() => { testComponent.slideColor = 'primary'; fixture.detectChanges(); @@ -88,18 +88,18 @@ describe('MatSlideToggle without forms', () => { fixture.detectChanges(); expect(slideToggleElement.classList).toContain('mat-accent'); - }); + })); - it('should correctly update the disabled property', () => { + it('should correctly update the disabled property', fakeAsync(() => { expect(inputElement.disabled).toBeFalsy(); testComponent.isDisabled = true; fixture.detectChanges(); expect(inputElement.disabled).toBeTruthy(); - }); + })); - it('should correctly update the checked property', () => { + it('should correctly update the checked property', fakeAsync(() => { expect(slideToggle.checked).toBeFalsy(); expect(inputElement.getAttribute('aria-checked')).toBe('false'); @@ -108,22 +108,23 @@ describe('MatSlideToggle without forms', () => { expect(inputElement.checked).toBeTruthy(); expect(inputElement.getAttribute('aria-checked')).toBe('true'); - }); + })); - it('should set the toggle to checked on click', () => { + it('should set the toggle to checked on click', fakeAsync(() => { expect(slideToggle.checked).toBe(false); expect(inputElement.getAttribute('aria-checked')).toBe('false'); expect(slideToggleElement.classList).not.toContain('mat-checked'); labelElement.click(); fixture.detectChanges(); + flush(); expect(slideToggleElement.classList).toContain('mat-checked'); expect(slideToggle.checked).toBe(true); expect(inputElement.getAttribute('aria-checked')).toBe('true'); - }); + })); - it('should not trigger the click event multiple times', () => { + it('should not trigger the click event multiple times', fakeAsync(() => { // By default, when clicking on a label element, a generated click will be dispatched // on the associated input element. // Since we're using a label element and a visual hidden input, this behavior can led @@ -134,23 +135,25 @@ describe('MatSlideToggle without forms', () => { labelElement.click(); fixture.detectChanges(); + flush(); expect(slideToggleElement.classList).toContain('mat-checked'); expect(slideToggle.checked).toBe(true); expect(testComponent.onSlideClick).toHaveBeenCalledTimes(1); - }); + })); - it('should trigger the change event properly', () => { + it('should trigger the change event properly', fakeAsync(() => { expect(inputElement.checked).toBe(false); expect(slideToggleElement.classList).not.toContain('mat-checked'); labelElement.click(); fixture.detectChanges(); + flush(); expect(inputElement.checked).toBe(true); expect(slideToggleElement.classList).toContain('mat-checked'); expect(testComponent.onSlideChange).toHaveBeenCalledTimes(1); - }); + })); it('should not trigger the change event by changing the native value', fakeAsync(() => { expect(inputElement.checked).toBe(false); @@ -180,7 +183,7 @@ describe('MatSlideToggle without forms', () => { expect(testComponent.onSlideChange).not.toHaveBeenCalled(); })); - it('should add a suffix to the inputs id', () => { + it('should add a suffix to the element id', fakeAsync(() => { testComponent.slideId = 'myId'; fixture.detectChanges(); @@ -198,9 +201,9 @@ describe('MatSlideToggle without forms', () => { // Once the id binding is set to null, the id property should auto-generate a unique id. expect(inputElement.id).toMatch(/mat-slide-toggle-\d+-input/); - }); + })); - it('should forward the tabIndex to the underlying input', () => { + it('should forward the tabIndex to the underlying element', fakeAsync(() => { fixture.detectChanges(); expect(inputElement.tabIndex).toBe(0); @@ -209,9 +212,9 @@ describe('MatSlideToggle without forms', () => { fixture.detectChanges(); expect(inputElement.tabIndex).toBe(4); - }); + })); - it('should forward the specified name to the input', () => { + it('should forward the specified name to the element', fakeAsync(() => { testComponent.slideName = 'myName'; fixture.detectChanges(); @@ -226,9 +229,9 @@ describe('MatSlideToggle without forms', () => { fixture.detectChanges(); expect(inputElement.name).toBe(''); - }); + })); - it('should forward the aria-label attribute to the input', () => { + it('should forward the aria-label attribute to the element', fakeAsync(() => { testComponent.slideLabel = 'ariaLabel'; fixture.detectChanges(); @@ -238,9 +241,9 @@ describe('MatSlideToggle without forms', () => { fixture.detectChanges(); expect(inputElement.hasAttribute('aria-label')).toBeFalsy(); - }); + })); - it('should forward the aria-labelledby attribute to the input', () => { + it('should forward the aria-labelledby attribute to the element', fakeAsync(() => { testComponent.slideLabelledBy = 'ariaLabelledBy'; fixture.detectChanges(); @@ -250,13 +253,25 @@ describe('MatSlideToggle without forms', () => { fixture.detectChanges(); expect(inputElement.hasAttribute('aria-labelledby')).toBeFalsy(); - }); + })); + + it('should forward the aria-describedby attribute to the element', fakeAsync(() => { + testComponent.slideAriaDescribedBy = 'some-element'; + fixture.detectChanges(); - it('should set the `for` attribute to the id of the input element', () => { + expect(inputElement.getAttribute('aria-describedby')).toBe('some-element'); + + testComponent.slideAriaDescribedBy = null; + fixture.detectChanges(); + + expect(inputElement.hasAttribute('aria-describedby')).toBe(false); + })); + + it('should set the `for` attribute to the id of the element', fakeAsync(() => { expect(labelElement.getAttribute('for')).toBeTruthy(); expect(inputElement.getAttribute('id')).toBeTruthy(); expect(labelElement.getAttribute('for')).toBe(inputElement.getAttribute('id')); - }); + })); it('should emit the new values properly', fakeAsync(() => { labelElement.click(); @@ -281,7 +296,7 @@ describe('MatSlideToggle without forms', () => { subscription.unsubscribe(); })); - it('should forward the required attribute', () => { + it('should forward the required attribute', fakeAsync(() => { testComponent.isRequired = true; fixture.detectChanges(); @@ -291,28 +306,21 @@ describe('MatSlideToggle without forms', () => { fixture.detectChanges(); expect(inputElement.required).toBe(false); - }); + })); - it('should focus on underlying input element when focus() is called', () => { + it('should focus on underlying element when focus() is called', fakeAsync(() => { expect(document.activeElement).not.toBe(inputElement); slideToggle.focus(); fixture.detectChanges(); + flush(); expect(document.activeElement).toBe(inputElement); - }); - - it('should focus on underlying input element when the host is focused', () => { - expect(document.activeElement).not.toBe(inputElement); - - slideToggleElement.focus(); - fixture.detectChanges(); - - expect(document.activeElement).toBe(inputElement); - }); + })); - it('should not manually move focus to underlying input when focus comes from mouse or touch', - inject([FocusMonitor], (focusMonitor: FocusMonitor) => { + it('should not manually move focus to underlying when focus comes from mouse or touch', inject( + [FocusMonitor], + (focusMonitor: FocusMonitor) => { expect(document.activeElement).not.toBe(inputElement); focusMonitor.focusVia(slideToggleElement, 'mouse'); @@ -322,18 +330,19 @@ describe('MatSlideToggle without forms', () => { focusMonitor.focusVia(slideToggleElement, 'touch'); fixture.detectChanges(); expect(document.activeElement).not.toBe(inputElement); - })); + }, + )); - it('should set a element class if labelPosition is set to before', () => { + it('should set a element class if labelPosition is set to before', fakeAsync(() => { expect(slideToggleElement.classList).not.toContain('mat-slide-toggle-label-before'); testComponent.labelPosition = 'before'; fixture.detectChanges(); expect(slideToggleElement.classList).toContain('mat-slide-toggle-label-before'); - }); + })); - it('should show ripples', () => { + it('should show ripples', fakeAsync(() => { const rippleSelector = '.mat-ripple-element:not(.mat-slide-toggle-persistent-ripple)'; expect(slideToggleElement.querySelectorAll(rippleSelector).length).toBe(0); @@ -342,9 +351,10 @@ describe('MatSlideToggle without forms', () => { dispatchFakeEvent(labelElement, 'mouseup'); expect(slideToggleElement.querySelectorAll(rippleSelector).length).toBe(1); - }); + flush(); + })); - it('should not show ripples when disableRipple is set', () => { + it('should not show ripples when disableRipple is set', fakeAsync(() => { const rippleSelector = '.mat-ripple-element:not(.mat-slide-toggle-persistent-ripple)'; testComponent.disableRipple = true; fixture.detectChanges(); @@ -355,14 +365,16 @@ describe('MatSlideToggle without forms', () => { dispatchFakeEvent(labelElement, 'mouseup'); expect(slideToggleElement.querySelectorAll(rippleSelector).length).toBe(0); - }); + flush(); + })); - it('should have a focus indicator', () => { - const slideToggleRippleNativeElement = - slideToggleElement.querySelector('.mat-slide-toggle-ripple')!; + it('should have a focus indicator', fakeAsync(() => { + const slideToggleRippleNativeElement = slideToggleElement.querySelector( + '.mat-slide-toggle-ripple', + )!; expect(slideToggleRippleNativeElement.classList.contains('mat-focus-indicator')).toBe(true); - }); + })); }); describe('custom template', () => { @@ -380,20 +392,21 @@ describe('MatSlideToggle without forms', () => { fixture.detectChanges(); - const slideToggle = fixture.debugElement - .query(By.directive(MatSlideToggle))!.componentInstance as MatSlideToggle; + const slideToggle = fixture.debugElement.query(By.directive(MatSlideToggle))! + .componentInstance as MatSlideToggle; expect(slideToggle.tabIndex) - .toBe(5, 'Expected tabIndex property to have been set based on the native attribute'); + .withContext('Expected tabIndex property to have been set based on the native attribute') + .toBe(5); })); - it('should set the tabindex of the host element to -1', fakeAsync(() => { + it('should remove the tabindex from the host node', fakeAsync(() => { const fixture = TestBed.createComponent(SlideToggleWithTabindexAttr); fixture.detectChanges(); const slideToggle = fixture.debugElement.query(By.directive(MatSlideToggle))!.nativeElement; - expect(slideToggle.getAttribute('tabindex')).toBe('-1'); + expect(slideToggle.hasAttribute('tabindex')).toBe(false); })); it('should remove the tabindex from the host element when disabled', fakeAsync(() => { @@ -407,47 +420,67 @@ describe('MatSlideToggle without forms', () => { })); }); - describe('custom action configuration', () => { - it('should not change value on click when click action is noop when using custom a ' + - 'action configuration', () => { - TestBed - .resetTestingModule() - .configureTestingModule({ + describe('default options', () => { + it( + 'should not change value on click when click action is noop when using custom a ' + + 'action configuration', + fakeAsync(() => { + TestBed.resetTestingModule().configureTestingModule({ imports: [MatSlideToggleModule], declarations: [SlideToggleBasic], providers: [ {provide: MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS, useValue: {disableToggleValue: true}}, - ] + ], }); - const fixture = TestBed.createComponent(SlideToggleBasic); - fixture.detectChanges(); + const fixture = TestBed.createComponent(SlideToggleBasic); + fixture.detectChanges(); - const testComponent = fixture.debugElement.componentInstance; - const slideToggleDebug = fixture.debugElement.query(By.css('mat-slide-toggle'))!; + const testComponent = fixture.debugElement.componentInstance; + const slideToggleDebug = fixture.debugElement.query(By.css('mat-slide-toggle'))!; - const slideToggle = slideToggleDebug.componentInstance; - const inputElement = fixture.debugElement.query(By.css('input'))!.nativeElement; - const labelElement = fixture.debugElement.query(By.css('label'))!.nativeElement; + const slideToggle = slideToggleDebug.componentInstance; + const inputElement = fixture.debugElement.query(By.css('input'))!.nativeElement; + const labelElement = fixture.debugElement.query(By.css('label'))!.nativeElement; - expect(testComponent.toggleTriggered).toBe(0); - expect(testComponent.dragTriggered).toBe(0); - expect(slideToggle.checked).toBe(false, 'Expect slide toggle value not changed'); + expect(testComponent.toggleTriggered).toBe(0); + expect(testComponent.dragTriggered).toBe(0); + expect(slideToggle.checked) + .withContext('Expect slide toggle value not changed') + .toBe(false); - labelElement.click(); - fixture.detectChanges(); - - expect(slideToggle.checked).toBe(false, 'Expect slide toggle value not changed'); - expect(testComponent.toggleTriggered).toBe(1, 'Expect toggle once'); - expect(testComponent.dragTriggered).toBe(0); + labelElement.click(); + fixture.detectChanges(); + flush(); - inputElement.click(); - fixture.detectChanges(); + expect(slideToggle.checked) + .withContext('Expect slide toggle value not changed') + .toBe(false); + expect(testComponent.toggleTriggered).withContext('Expect toggle once').toBe(1); + expect(testComponent.dragTriggered).toBe(0); - expect(slideToggle.checked).toBe(false, 'Expect slide toggle value not changed'); - expect(testComponent.toggleTriggered).toBe(2, 'Expect toggle twice'); - expect(testComponent.dragTriggered).toBe(0); - }); + inputElement.click(); + fixture.detectChanges(); + flush(); + expect(slideToggle.checked) + .withContext('Expect slide toggle value not changed') + .toBe(false); + expect(testComponent.toggleTriggered).withContext('Expect toggle twice').toBe(2); + expect(testComponent.dragTriggered).toBe(0); + }), + ); + + it('should be able to change the default color', fakeAsync(() => { + TestBed.resetTestingModule().configureTestingModule({ + imports: [MatSlideToggleModule], + declarations: [SlideToggleWithForm], + providers: [{provide: MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS, useValue: {color: 'warn'}}], + }); + const fixture = TestBed.createComponent(SlideToggleWithForm); + fixture.detectChanges(); + const slideToggle = fixture.nativeElement.querySelector('.mat-slide-toggle'); + expect(slideToggle.classList).toContain('mat-warn'); + })); }); describe('without label', () => { @@ -455,44 +488,41 @@ describe('MatSlideToggle without forms', () => { let testComponent: SlideToggleWithoutLabel; let slideToggleBarElement: HTMLElement; - beforeEach(() => { + beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(SlideToggleWithoutLabel); const slideToggleDebugEl = fixture.debugElement.query(By.directive(MatSlideToggle))!; testComponent = fixture.componentInstance; - slideToggleBarElement = slideToggleDebugEl - .query(By.css('.mat-slide-toggle-bar'))!.nativeElement; - }); + slideToggleBarElement = slideToggleDebugEl.query( + By.css('.mat-slide-toggle-bar'), + )!.nativeElement; + })); - it('should remove margin for slide-toggle without a label', () => { + it('should remove margin for slide-toggle without a label', fakeAsync(() => { fixture.detectChanges(); - expect(slideToggleBarElement.classList) - .toContain('mat-slide-toggle-bar-no-side-margin'); - }); + expect(slideToggleBarElement.classList).toContain('mat-slide-toggle-bar-no-side-margin'); + })); it('should not remove margin if initial label is set through binding', fakeAsync(() => { testComponent.label = 'Some content'; fixture.detectChanges(); - expect(slideToggleBarElement.classList) - .not.toContain('mat-slide-toggle-bar-no-side-margin'); + expect(slideToggleBarElement.classList).not.toContain('mat-slide-toggle-bar-no-side-margin'); })); it('should re-add margin if label is added asynchronously', fakeAsync(() => { fixture.detectChanges(); - expect(slideToggleBarElement.classList) - .toContain('mat-slide-toggle-bar-no-side-margin'); + expect(slideToggleBarElement.classList).toContain('mat-slide-toggle-bar-no-side-margin'); testComponent.label = 'Some content'; fixture.detectChanges(); flushMutationObserver(); fixture.detectChanges(); - expect(slideToggleBarElement.classList) - .not.toContain('mat-slide-toggle-bar-no-side-margin'); + expect(slideToggleBarElement.classList).not.toContain('mat-slide-toggle-bar-no-side-margin'); })); }); @@ -500,37 +530,36 @@ describe('MatSlideToggle without forms', () => { let fixture: ComponentFixture; let slideToggleBarElement: HTMLElement; - beforeEach(() => { + beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(SlideToggleProjectedLabel); - slideToggleBarElement = fixture.debugElement - .query(By.css('.mat-slide-toggle-bar'))!.nativeElement; + slideToggleBarElement = fixture.debugElement.query( + By.css('.mat-slide-toggle-bar'), + )!.nativeElement; fixture.detectChanges(); - }); + })); - it('should properly update margin if label content is projected', () => { + it('should properly update margin if label content is projected', fakeAsync(() => { // Do not run the change detection for the fixture manually because we want to verify // that the slide-toggle properly toggles the margin class even if the observe content // output fires outside of the zone. flushMutationObserver(); - expect(slideToggleBarElement.classList).not - .toContain('mat-slide-toggle-bar-no-side-margin'); - }); + expect(slideToggleBarElement.classList).not.toContain('mat-slide-toggle-bar-no-side-margin'); + })); }); - it('should clear static aria attributes from the host node', () => { + it('should clear static aria attributes from the host node', fakeAsync(() => { const fixture = TestBed.createComponent(SlideToggleWithStaticAriaAttributes); fixture.detectChanges(); const host: HTMLElement = fixture.nativeElement.querySelector('mat-slide-toggle'); expect(host.hasAttribute('aria-label')).toBe(false); expect(host.hasAttribute('aria-labelledby')).toBe(false); - }); + })); }); describe('MatSlideToggle with forms', () => { - beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [MatSlideToggleModule, FormsModule, ReactiveFormsModule], @@ -539,7 +568,7 @@ describe('MatSlideToggle with forms', () => { SlideToggleWithModel, SlideToggleWithFormControl, SlideToggleWithModelAndChangeEvent, - ] + ], }); TestBed.compileComponents(); @@ -570,10 +599,10 @@ describe('MatSlideToggle with forms', () => { labelElement = fixture.debugElement.query(By.css('label'))!.nativeElement; })); - it('should be initially set to ng-pristine', () => { + it('should be initially set to ng-pristine', fakeAsync(() => { expect(slideToggleElement.classList).toContain('ng-pristine'); expect(slideToggleElement.classList).not.toContain('ng-dirty'); - }); + })); it('should update the model programmatically', fakeAsync(() => { expect(slideToggleElement.classList).not.toContain('mat-checked'); @@ -632,9 +661,7 @@ describe('MatSlideToggle with forms', () => { }).not.toThrow(); })); - it('should not set the control to touched when changing the state programmatically', - fakeAsync(() => { - + it('should not set the control to touched when changing the state programmatically', fakeAsync(() => { // The control should start off with being untouched. expect(slideToggleModel.touched).toBe(false); @@ -689,14 +716,16 @@ describe('MatSlideToggle with forms', () => { fixture.detectChanges(); expect(slideToggle.checked) - .toBe(true, 'Expected slide-toggle to be checked initially'); + .withContext('Expected slide-toggle to be checked initially') + .toBe(true); labelElement.click(); fixture.detectChanges(); tick(); expect(slideToggle.checked) - .toBe(false, 'Expected slide-toggle to be no longer checked after label click.'); + .withContext('Expected slide-toggle to be no longer checked after label click.') + .toBe(false); })); it('should be pristine if initial value is set from NgModel', fakeAsync(() => { @@ -724,7 +753,6 @@ describe('MatSlideToggle with forms', () => { fixture.detectChanges(); expect(testComponent.modelValue).toBe(true); })); - }); describe('with a FormControl', () => { @@ -735,7 +763,7 @@ describe('MatSlideToggle with forms', () => { let slideToggle: MatSlideToggle; let inputElement: HTMLInputElement; - beforeEach(() => { + beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(SlideToggleWithFormControl); fixture.detectChanges(); @@ -744,9 +772,9 @@ describe('MatSlideToggle with forms', () => { testComponent = fixture.debugElement.componentInstance; slideToggle = slideToggleDebug.componentInstance; inputElement = fixture.debugElement.query(By.css('input'))!.nativeElement; - }); + })); - it('should toggle the disabled state', () => { + it('should toggle the disabled state', fakeAsync(() => { expect(slideToggle.disabled).toBe(false); expect(inputElement.disabled).toBe(false); @@ -761,16 +789,17 @@ describe('MatSlideToggle with forms', () => { expect(slideToggle.disabled).toBe(false); expect(inputElement.disabled).toBe(false); - }); + })); - it('should not change focus origin if origin not specified', () => { + it('should not change focus origin if origin not specified', fakeAsync(() => { slideToggle.focus(undefined, 'mouse'); slideToggle.focus(); fixture.detectChanges(); + flush(); expect(slideToggleDebug.nativeElement.classList).toContain('cdk-focused'); expect(slideToggleDebug.nativeElement.classList).toContain('cdk-mouse-focused'); - }); + })); }); describe('with form element', () => { @@ -789,7 +818,7 @@ describe('MatSlideToggle with forms', () => { inputElement = fixture.debugElement.query(By.css('input'))!.nativeElement; })); - it('should prevent the form from submit when being required', () => { + it('should prevent the form from submit when being required', fakeAsync(() => { if (typeof (inputElement as any).reportValidity === 'undefined') { // If the browser does not report the validity then the tests will break. // e.g Safari 8 on Mobile. @@ -802,6 +831,7 @@ describe('MatSlideToggle with forms', () => { buttonElement.click(); fixture.detectChanges(); + flush(); expect(testComponent.isSubmitted).toBe(false); @@ -810,11 +840,12 @@ describe('MatSlideToggle with forms', () => { buttonElement.click(); fixture.detectChanges(); + flush(); expect(testComponent.isSubmitted).toBe(true); - }); + })); - it('should have proper invalid state if unchecked', () => { + it('should have proper invalid state if unchecked', fakeAsync(() => { testComponent.isRequired = true; fixture.detectChanges(); @@ -827,6 +858,7 @@ describe('MatSlideToggle with forms', () => { // should become valid. inputElement.click(); fixture.detectChanges(); + flush(); expect(slideToggleEl.classList).not.toContain('ng-invalid'); expect(slideToggleEl.classList).toContain('ng-valid'); @@ -835,14 +867,15 @@ describe('MatSlideToggle with forms', () => { // should become invalid. inputElement.click(); fixture.detectChanges(); + flush(); expect(slideToggleEl.classList).toContain('ng-invalid'); expect(slideToggleEl.classList).not.toContain('ng-valid'); - }); + })); }); describe('with model and change event', () => { - it('should report changes to NgModel before emitting change event', () => { + it('should report changes to NgModel before emitting change event', fakeAsync(() => { const fixture = TestBed.createComponent(SlideToggleWithModelAndChangeEvent); fixture.detectChanges(); @@ -850,13 +883,15 @@ describe('MatSlideToggle with forms', () => { spyOn(fixture.componentInstance, 'onChange').and.callFake(() => { expect(fixture.componentInstance.checked) - .toBe(true, 'Expected the model value to have changed before the change event fired.'); + .withContext('Expected the model value to have changed before the change event fired.') + .toBe(true); }); labelEl.click(); + flush(); expect(fixture.componentInstance.onChange).toHaveBeenCalledTimes(1); - }); + })); }); }); @@ -870,6 +905,7 @@ describe('MatSlideToggle with forms', () => { [name]="slideName" [aria-label]="slideLabel" [aria-labelledby]="slideLabelledBy" + [aria-describedby]="slideAriaDescribedBy" [tabIndex]="slideTabindex" [labelPosition]="labelPosition" [disableRipple]="disableRipple" @@ -890,6 +926,7 @@ class SlideToggleBasic { slideName: string | null; slideLabel: string | null; slideLabelledBy: string | null; + slideAriaDescribedBy: string | null; slideTabindex: number; lastEvent: MatSlideToggleChange; labelPosition: string; @@ -897,7 +934,7 @@ class SlideToggleBasic { dragTriggered: number = 0; onSlideClick: (event?: Event) => void = () => {}; - onSlideChange = (event: MatSlideToggleChange) => this.lastEvent = event; + onSlideChange = (event: MatSlideToggleChange) => (this.lastEvent = event); onSlideToggleChange = () => this.toggleTriggered++; onSlideDragChange = () => this.dragTriggered++; } @@ -907,7 +944,7 @@ class SlideToggleBasic {
Required -
` + `, }) class SlideToggleWithForm { isSubmitted: boolean = false; @@ -915,7 +952,7 @@ class SlideToggleWithForm { } @Component({ - template: `` + template: ``, }) class SlideToggleWithModel { modelValue = false; @@ -937,14 +974,14 @@ class SlideToggleWithTabindexAttr { } @Component({ - template: `{{label}}` + template: `{{label}}`, }) class SlideToggleWithoutLabel { label: string; } @Component({ - template: `` + template: ``, }) class SlideToggleWithModelAndChangeEvent { checked: boolean; @@ -952,13 +989,13 @@ class SlideToggleWithModelAndChangeEvent { } @Component({ - template: `` + template: ``, }) class SlideToggleProjectedLabel {} @Component({ selector: 'some-text', - template: `{{text}}` + template: `{{text}}`, }) class TextBindingComponent { text: string = 'Some text'; @@ -967,6 +1004,6 @@ class TextBindingComponent { @Component({ template: ` - ` + `, }) class SlideToggleWithStaticAriaAttributes {} diff --git a/src/material/slide-toggle/slide-toggle.ts b/src/material/slide-toggle/slide-toggle.ts index a3aec7a0ebd4..426a9a26ada0 100644 --- a/src/material/slide-toggle/slide-toggle.ts +++ b/src/material/slide-toggle/slide-toggle.ts @@ -7,7 +7,7 @@ */ import {FocusMonitor, FocusOrigin} from '@angular/cdk/a11y'; -import {BooleanInput, coerceBooleanProperty, NumberInput} from '@angular/cdk/coercion'; +import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion'; import { AfterContentInit, Attribute, @@ -27,10 +27,10 @@ import { } from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import { - CanColor, CanColorCtor, - CanDisable, CanDisableCtor, - CanDisableRipple, CanDisableRippleCtor, - HasTabIndex, HasTabIndexCtor, + CanColor, + CanDisable, + CanDisableRipple, + HasTabIndex, mixinColor, mixinDisabled, mixinDisableRipple, @@ -39,7 +39,7 @@ import { import {ANIMATION_MODULE_TYPE} from '@angular/platform-browser/animations'; import { MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS, - MatSlideToggleDefaultOptions + MatSlideToggleDefaultOptions, } from './slide-toggle-config'; // Increasing integer for generating unique ids for slide-toggle components. @@ -49,7 +49,7 @@ let nextUniqueId = 0; export const MAT_SLIDE_TOGGLE_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MatSlideToggle), - multi: true + multi: true, }; /** Change event object emitted by a MatSlideToggle. */ @@ -58,21 +58,23 @@ export class MatSlideToggleChange { /** The source MatSlideToggle of the event. */ public source: MatSlideToggle, /** The new `checked` value of the MatSlideToggle. */ - public checked: boolean) { } + public checked: boolean, + ) {} } // Boilerplate for applying mixins to MatSlideToggle. /** @docs-private */ -class MatSlideToggleBase { - constructor(public _elementRef: ElementRef) {} -} -const _MatSlideToggleMixinBase: - HasTabIndexCtor & - CanColorCtor & - CanDisableRippleCtor & - CanDisableCtor & - typeof MatSlideToggleBase = - mixinTabIndex(mixinColor(mixinDisableRipple(mixinDisabled(MatSlideToggleBase)), 'accent')); +const _MatSlideToggleBase = mixinTabIndex( + mixinColor( + mixinDisableRipple( + mixinDisabled( + class { + constructor(public _elementRef: ElementRef) {} + }, + ), + ), + ), +); /** Represents a slidable "switch" toggle that can be moved between on and off. */ @Component({ @@ -81,14 +83,14 @@ const _MatSlideToggleMixinBase: host: { 'class': 'mat-slide-toggle', '[id]': 'id', - // Needs to be `-1` so it can still receive programmatic focus. - '[attr.tabindex]': 'disabled ? null : -1', + // Needs to be removed since it causes some a11y issues (see #21266). + '[attr.tabindex]': 'null', '[attr.aria-label]': 'null', '[attr.aria-labelledby]': 'null', '[class.mat-checked]': 'checked', '[class.mat-disabled]': 'disabled', '[class.mat-slide-toggle-label-before]': 'labelPosition == "before"', - '[class._mat-animation-noopable]': '_animationMode === "NoopAnimations"', + '[class._mat-animation-noopable]': '_noopAnimations', }, templateUrl: 'slide-toggle.html', styleUrls: ['slide-toggle.css'], @@ -97,11 +99,17 @@ const _MatSlideToggleMixinBase: encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) -export class MatSlideToggle extends _MatSlideToggleMixinBase implements OnDestroy, AfterContentInit, - ControlValueAccessor, - CanDisable, CanColor, - HasTabIndex, - CanDisableRipple { +export class MatSlideToggle + extends _MatSlideToggleBase + implements + OnDestroy, + AfterContentInit, + ControlValueAccessor, + CanDisable, + CanColor, + HasTabIndex, + CanDisableRipple +{ private _onChange = (_: any) => {}; private _onTouched = () => {}; @@ -109,6 +117,9 @@ export class MatSlideToggle extends _MatSlideToggleMixinBase implements OnDestro private _required: boolean = false; private _checked: boolean = false; + /** Whether noop animations are enabled. */ + _noopAnimations: boolean; + /** Reference to the thumb HTMLElement. */ @ViewChild('thumbContainer') _thumbEl: ElementRef; @@ -130,21 +141,30 @@ export class MatSlideToggle extends _MatSlideToggleMixinBase implements OnDestro /** Used to set the aria-labelledby attribute on the underlying input element. */ @Input('aria-labelledby') ariaLabelledby: string | null = null; + /** Used to set the aria-describedby attribute on the underlying input element. */ + @Input('aria-describedby') ariaDescribedby: string; + /** Whether the slide-toggle is required. */ @Input() - get required(): boolean { return this._required; } - set required(value) { this._required = coerceBooleanProperty(value); } + get required(): boolean { + return this._required; + } + set required(value: BooleanInput) { + this._required = coerceBooleanProperty(value); + } /** Whether the slide-toggle element is checked or not. */ @Input() - get checked(): boolean { return this._checked; } - set checked(value) { + get checked(): boolean { + return this._checked; + } + set checked(value: BooleanInput) { this._checked = coerceBooleanProperty(value); this._changeDetectorRef.markForCheck(); } /** An event will be dispatched each time the slide-toggle changes its value. */ @Output() readonly change: EventEmitter = - new EventEmitter(); + new EventEmitter(); /** * An event will be dispatched each time the slide-toggle input is toggled. @@ -154,41 +174,39 @@ export class MatSlideToggle extends _MatSlideToggleMixinBase implements OnDestro @Output() readonly toggleChange: EventEmitter = new EventEmitter(); /** Returns the unique id for the visual hidden input. */ - get inputId(): string { return `${this.id || this._uniqueId}-input`; } + get inputId(): string { + return `${this.id || this._uniqueId}-input`; + } /** Reference to the underlying input element. */ @ViewChild('input') _inputElement: ElementRef; - constructor(elementRef: ElementRef, - private _focusMonitor: FocusMonitor, - private _changeDetectorRef: ChangeDetectorRef, - @Attribute('tabindex') tabIndex: string, - @Inject(MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS) - public defaults: MatSlideToggleDefaultOptions, - @Optional() @Inject(ANIMATION_MODULE_TYPE) public _animationMode?: string) { + constructor( + elementRef: ElementRef, + private _focusMonitor: FocusMonitor, + private _changeDetectorRef: ChangeDetectorRef, + @Attribute('tabindex') tabIndex: string, + @Inject(MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS) + public defaults: MatSlideToggleDefaultOptions, + @Optional() @Inject(ANIMATION_MODULE_TYPE) animationMode?: string, + ) { super(elementRef); this.tabIndex = parseInt(tabIndex) || 0; + this.color = this.defaultColor = defaults.color || 'accent'; + this._noopAnimations = animationMode === 'NoopAnimations'; } ngAfterContentInit() { - this._focusMonitor - .monitor(this._elementRef, true) - .subscribe(focusOrigin => { - // Only forward focus manually when it was received programmatically or through the - // keyboard. We should not do this for mouse/touch focus for two reasons: - // 1. It can prevent clicks from landing in Chrome (see #18269). - // 2. They're already handled by the wrapping `label` element. - if (focusOrigin === 'keyboard' || focusOrigin === 'program') { - this._inputElement.nativeElement.focus(); - } else if (!focusOrigin) { - // When a focused element becomes disabled, the browser *immediately* fires a blur event. - // Angular does not expect events to be raised during change detection, so any state - // change (such as a form control's 'ng-touched') will cause a changed-after-checked - // error. See https://github.com/angular/angular/issues/17793. To work around this, - // we defer telling the form control it has been touched until the next tick. - Promise.resolve().then(() => this._onTouched()); - } - }); + this._focusMonitor.monitor(this._elementRef, true).subscribe(focusOrigin => { + if (!focusOrigin) { + // When a focused element becomes disabled, the browser *immediately* fires a blur event. + // Angular does not expect events to be raised during change detection, so any state + // change (such as a form control's 'ng-touched') will cause a changed-after-checked + // error. See https://github.com/angular/angular/issues/17793. To work around this, + // we defer telling the form control it has been touched until the next tick. + Promise.resolve().then(() => this._onTouched()); + } + }); } ngOnDestroy() { @@ -284,10 +302,4 @@ export class MatSlideToggle extends _MatSlideToggleMixinBase implements OnDestro // we only trigger an explicit change detection for the slide-toggle view and its children. this._changeDetectorRef.detectChanges(); } - - static ngAcceptInputType_required: BooleanInput; - static ngAcceptInputType_checked: BooleanInput; - static ngAcceptInputType_disabled: BooleanInput; - static ngAcceptInputType_disableRipple: BooleanInput; - static ngAcceptInputType_tabIndex: NumberInput; } diff --git a/src/material/slide-toggle/testing/BUILD.bazel b/src/material/slide-toggle/testing/BUILD.bazel index 16f38dfcad8d..9851dff365ac 100644 --- a/src/material/slide-toggle/testing/BUILD.bazel +++ b/src/material/slide-toggle/testing/BUILD.bazel @@ -8,7 +8,6 @@ ts_library( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material/slide-toggle/testing", deps = [ "//src/cdk/coercion", "//src/cdk/testing", diff --git a/src/material/slide-toggle/testing/shared.spec.ts b/src/material/slide-toggle/testing/shared.spec.ts index b8f7b3dc7da3..bfdb3b98dd34 100644 --- a/src/material/slide-toggle/testing/shared.spec.ts +++ b/src/material/slide-toggle/testing/shared.spec.ts @@ -9,8 +9,9 @@ import {MatSlideToggleHarness} from '@angular/material/slide-toggle/testing/slid /** Shared tests to run on both the original and MDC-based slide-toggles. */ export function runHarnessTests( - slideToggleModule: typeof MatSlideToggleModule, - slideToggleHarness: typeof MatSlideToggleHarness) { + slideToggleModule: typeof MatSlideToggleModule, + slideToggleHarness: typeof MatSlideToggleHarness, +) { let platform: Platform; let fixture: ComponentFixture; let loader: HarnessLoader; @@ -46,7 +47,8 @@ export function runHarnessTests( it('should load slide-toggle with name', async () => { const slideToggles = await loader.getAllHarnesses( - slideToggleHarness.with({name: 'first-name'})); + slideToggleHarness.with({name: 'first-name'}), + ); expect(slideToggles.length).toBe(1); expect(await slideToggles[0].getLabelText()).toBe('First'); }); @@ -71,12 +73,16 @@ export function runHarnessTests( it('should get valid state', async () => { const [requiredToggle, optionalToggle] = await loader.getAllHarnesses(slideToggleHarness); - expect(await optionalToggle.isValid()).toBe(true, 'Expected optional toggle to be valid'); + expect(await optionalToggle.isValid()) + .withContext('Expected optional toggle to be valid') + .toBe(true); expect(await requiredToggle.isValid()) - .toBe(true, 'Expected required checked toggle to be valid'); + .withContext('Expected required checked toggle to be valid') + .toBe(true); await requiredToggle.uncheck(); expect(await requiredToggle.isValid()) - .toBe(false, 'Expected required unchecked toggle to be invalid'); + .withContext('Expected required unchecked toggle to be invalid') + .toBe(false); }); it('should get name', async () => { @@ -144,7 +150,7 @@ export function runHarnessTests( it('should not toggle disabled slide-toggle', async () => { if (platform.FIREFOX) { - // do run this test on firefox as click events on the label of the underlying + // do not run this test on firefox as click events on the label of the underlying // input checkbox cause the value to be changed. Read more in the bug report: // https://bugzilla.mozilla.org/show_bug.cgi?id=1540995 return; @@ -170,10 +176,9 @@ export function runHarnessTests( Second
Second slide-toggle - ` + `, }) class SlideToggleHarnessTest { ctrl = new FormControl(true); disabled = true; } - diff --git a/src/material/slide-toggle/testing/slide-toggle-harness.ts b/src/material/slide-toggle/testing/slide-toggle-harness.ts index 915e2c7cd022..929ccd457a56 100644 --- a/src/material/slide-toggle/testing/slide-toggle-harness.ts +++ b/src/material/slide-toggle/testing/slide-toggle-harness.ts @@ -6,51 +6,34 @@ * found in the LICENSE file at https://angular.io/license */ -import {ComponentHarness, HarnessPredicate} from '@angular/cdk/testing'; +import { + AsyncFactoryFn, + ComponentHarness, + HarnessPredicate, + TestElement, +} from '@angular/cdk/testing'; import {coerceBooleanProperty} from '@angular/cdk/coercion'; import {SlideToggleHarnessFilters} from './slide-toggle-harness-filters'; - -/** Harness for interacting with a standard mat-slide-toggle in tests. */ -export class MatSlideToggleHarness extends ComponentHarness { - /** The selector for the host element of a `MatSlideToggle` instance. */ - static hostSelector = '.mat-slide-toggle'; - - /** - * Gets a `HarnessPredicate` that can be used to search for a `MatSlideToggleHarness` that meets - * certain criteria. - * @param options Options for filtering which slide toggle instances are considered a match. - * @return a `HarnessPredicate` configured with the given options. - */ - static with(options: SlideToggleHarnessFilters = {}): HarnessPredicate { - return new HarnessPredicate(MatSlideToggleHarness, options) - .addOption('label', options.label, - (harness, label) => HarnessPredicate.stringMatches(harness.getLabelText(), label)) - // We want to provide a filter option for "name" because the name of the slide-toggle is - // only set on the underlying input. This means that it's not possible for developers - // to retrieve the harness of a specific checkbox with name through a CSS selector. - .addOption('name', options.name, async (harness, name) => await harness.getName() === name); - } - +export abstract class _MatSlideToggleHarnessBase extends ComponentHarness { private _label = this.locatorFor('label'); - private _input = this.locatorFor('input'); - private _inputContainer = this.locatorFor('.mat-slide-toggle-bar'); + protected abstract _nativeElement: AsyncFactoryFn; + + /** Toggle the checked state of the slide-toggle. */ + abstract toggle(): Promise; /** Whether the slide-toggle is checked. */ - async isChecked(): Promise { - const checked = (await this._input()).getProperty('checked'); - return coerceBooleanProperty(await checked); - } + abstract isChecked(): Promise; /** Whether the slide-toggle is disabled. */ async isDisabled(): Promise { - const disabled = (await this._input()).getAttribute('disabled'); + const disabled = (await this._nativeElement()).getAttribute('disabled'); return coerceBooleanProperty(await disabled); } /** Whether the slide-toggle is required. */ async isRequired(): Promise { - const required = (await this._input()).getAttribute('required'); + const required = (await this._nativeElement()).getAttribute('required'); return coerceBooleanProperty(await required); } @@ -62,17 +45,17 @@ export class MatSlideToggleHarness extends ComponentHarness { /** Gets the slide-toggle's name. */ async getName(): Promise { - return (await this._input()).getAttribute('name'); + return (await this._nativeElement()).getAttribute('name'); } /** Gets the slide-toggle's aria-label. */ async getAriaLabel(): Promise { - return (await this._input()).getAttribute('aria-label'); + return (await this._nativeElement()).getAttribute('aria-label'); } /** Gets the slide-toggle's aria-labelledby. */ async getAriaLabelledby(): Promise { - return (await this._input()).getAttribute('aria-labelledby'); + return (await this._nativeElement()).getAttribute('aria-labelledby'); } /** Gets the slide-toggle's label text. */ @@ -82,22 +65,17 @@ export class MatSlideToggleHarness extends ComponentHarness { /** Focuses the slide-toggle. */ async focus(): Promise { - return (await this._input()).focus(); + return (await this._nativeElement()).focus(); } /** Blurs the slide-toggle. */ async blur(): Promise { - return (await this._input()).blur(); + return (await this._nativeElement()).blur(); } /** Whether the slide-toggle is focused. */ async isFocused(): Promise { - return (await this._input()).isFocused(); - } - - /** Toggle the checked state of the slide-toggle. */ - async toggle(): Promise { - return (await this._inputContainer()).click(); + return (await this._nativeElement()).isFocused(); } /** @@ -120,3 +98,46 @@ export class MatSlideToggleHarness extends ComponentHarness { } } } + +/** Harness for interacting with a standard mat-slide-toggle in tests. */ +export class MatSlideToggleHarness extends _MatSlideToggleHarnessBase { + private _inputContainer = this.locatorFor('.mat-slide-toggle-bar'); + protected _nativeElement = this.locatorFor('input'); + + /** The selector for the host element of a `MatSlideToggle` instance. */ + static hostSelector = '.mat-slide-toggle'; + + /** + * Gets a `HarnessPredicate` that can be used to search for a `MatSlideToggleHarness` that meets + * certain criteria. + * @param options Options for filtering which slide toggle instances are considered a match. + * @return a `HarnessPredicate` configured with the given options. + */ + static with(options: SlideToggleHarnessFilters = {}): HarnessPredicate { + return ( + new HarnessPredicate(MatSlideToggleHarness, options) + .addOption('label', options.label, (harness, label) => + HarnessPredicate.stringMatches(harness.getLabelText(), label), + ) + // We want to provide a filter option for "name" because the name of the slide-toggle is + // only set on the underlying input. This means that it's not possible for developers + // to retrieve the harness of a specific checkbox with name through a CSS selector. + .addOption( + 'name', + options.name, + async (harness, name) => (await harness.getName()) === name, + ) + ); + } + + /** Toggle the checked state of the slide-toggle. */ + async toggle(): Promise { + return (await this._inputContainer()).click(); + } + + /** Whether the slide-toggle is checked. */ + async isChecked(): Promise { + const checked = (await this._nativeElement()).getProperty('checked'); + return coerceBooleanProperty(await checked); + } +} diff --git a/src/material/slider/BUILD.bazel b/src/material/slider/BUILD.bazel index 600937e7a93b..5f250c7d883c 100644 --- a/src/material/slider/BUILD.bazel +++ b/src/material/slider/BUILD.bazel @@ -17,7 +17,6 @@ ng_module( exclude = ["**/*.spec.ts"], ), assets = [":slider.css"] + glob(["**/*.html"]), - module_name = "@angular/material/slider", deps = [ "//src/cdk/a11y", "//src/cdk/bidi", diff --git a/src/material/slider/_slider-legacy-index.scss b/src/material/slider/_slider-legacy-index.scss new file mode 100644 index 000000000000..6055dcce5d8a --- /dev/null +++ b/src/material/slider/_slider-legacy-index.scss @@ -0,0 +1,2 @@ +@forward 'slider-theme' hide color, theme, typography; +@forward 'slider-theme' as mat-slider-* hide mat-slider-density, mat-slider-inner-content-theme; diff --git a/src/material/slider/_slider-theme.import.scss b/src/material/slider/_slider-theme.import.scss new file mode 100644 index 000000000000..33b2b790d0cb --- /dev/null +++ b/src/material/slider/_slider-theme.import.scss @@ -0,0 +1,8 @@ +@forward '../core/theming/theming.import'; +@forward '../core/typography/typography-utils.import'; +@forward 'slider-theme' hide color, theme, typography; +@forward 'slider-theme' as mat-slider-* hide mat-slider-density, mat-slider-inner-content-theme; + +@import '../core/theming/palette'; +@import '../core/theming/theming'; +@import '../core/typography/typography-utils'; diff --git a/src/material/slider/_slider-theme.scss b/src/material/slider/_slider-theme.scss index facd274e72c0..a916b5d89516 100644 --- a/src/material/slider/_slider-theme.scss +++ b/src/material/slider/_slider-theme.scss @@ -1,46 +1,51 @@ -@import '../core/theming/palette'; -@import '../core/theming/theming'; -@import '../core/typography/typography-utils'; +@use 'sass:map'; +@use 'sass:meta'; +@use '../core/theming/theming'; +@use '../core/typography/typography'; +@use '../core/typography/typography-utils'; -@mixin _mat-slider-inner-content-theme($palette) { +@mixin _inner-content-theme($palette) { .mat-slider-track-fill, .mat-slider-thumb, .mat-slider-thumb-label { - background-color: mat-color($palette); + background-color: theming.get-color-from-palette($palette); } .mat-slider-thumb-label-text { - color: mat-color($palette, default-contrast); + color: theming.get-color-from-palette($palette, default-contrast); } .mat-slider-focus-ring { $opacity: 0.2; - $color: mat-color($palette, default, $opacity); + $color: theming.get-color-from-palette($palette, default, $opacity); background-color: $color; // `mat-color` uses `rgba` for the opacity which won't work with // CSS variables so we need to use `opacity` as a fallback. - @if (type-of($color) != color) { + @if (meta.type-of($color) != color) { opacity: $opacity; } } } -@mixin mat-slider-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $primary: map-get($config, primary); - $accent: map-get($config, accent); - $warn: map-get($config, warn); - $background: map-get($config, background); - $foreground: map-get($config, foreground); - - $mat-slider-off-color: mat-color($foreground, slider-off); - $mat-slider-off-focused-color: mat-color($foreground, slider-off-active); - $mat-slider-disabled-color: mat-color($foreground, slider-off); - $mat-slider-labeled-min-value-thumb-color: mat-color($foreground, slider-min); - $mat-slider-labeled-min-value-thumb-label-color: mat-color($foreground, slider-off); +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $primary: map.get($config, primary); + $accent: map.get($config, accent); + $warn: map.get($config, warn); + $background: map.get($config, background); + $foreground: map.get($config, foreground); + + $mat-slider-off-color: theming.get-color-from-palette($foreground, slider-off); + $mat-slider-off-focused-color: theming.get-color-from-palette($foreground, slider-off-active); + $mat-slider-disabled-color: theming.get-color-from-palette($foreground, slider-off); + $mat-slider-labeled-min-value-thumb-color: + theming.get-color-from-palette($foreground, slider-min); + $mat-slider-labeled-min-value-thumb-label-color: + theming.get-color-from-palette($foreground, slider-off); $mat-slider-tick-opacity: 0.7; - $mat-slider-tick-color: mat-color($foreground, base, $mat-slider-tick-opacity); + $mat-slider-tick-color: + theming.get-color-from-palette($foreground, base, $mat-slider-tick-opacity); $mat-slider-tick-size: 2px; .mat-slider-track-background { @@ -48,19 +53,19 @@ } .mat-primary { - @include _mat-slider-inner-content-theme($primary); + @include _inner-content-theme($primary); } .mat-accent { - @include _mat-slider-inner-content-theme($accent); + @include _inner-content-theme($accent); } .mat-warn { - @include _mat-slider-inner-content-theme($warn); + @include _inner-content-theme($warn); } .mat-slider:hover, - .cdk-focused { + .mat-slider.cdk-focused { .mat-slider-track-background { background-color: $mat-slider-off-focused-color; } @@ -83,12 +88,12 @@ .mat-slider-min-value { .mat-slider-focus-ring { $opacity: 0.12; - $color: mat-color($foreground, base, $opacity); + $color: theming.get-color-from-palette($foreground, base, $opacity); background-color: $color; // `mat-color` uses `rgba` for the opacity which won't work with // CSS variables so we need to use `opacity` as a fallback. - @if (type-of($color) != color) { + @if (meta.type-of($color) != color) { opacity: $opacity; } } @@ -131,7 +136,7 @@ // `mat-color` uses `rgba` for the opacity which won't work with // CSS variables so we need to use `opacity` as a fallback. - @if (type-of($mat-slider-tick-color) != color) { + @if (meta.type-of($mat-slider-tick-color) != color) { opacity: $mat-slider-tick-opacity; } } @@ -146,7 +151,7 @@ // `mat-color` uses `rgba` for the opacity which won't work with // CSS variables so we need to use `opacity` as a fallback. - @if (type-of($mat-slider-tick-color) != color) { + @if (meta.type-of($mat-slider-tick-color) != color) { opacity: $mat-slider-tick-opacity; } } @@ -157,40 +162,41 @@ // `mat-color` uses `rgba` for the opacity which won't work with // CSS variables so we need to use `opacity` as a fallback. - @if (type-of($mat-slider-tick-color) != color) { + @if (meta.type-of($mat-slider-tick-color) != color) { opacity: $mat-slider-tick-opacity; } } } -@mixin mat-slider-typography($config-or-theme) { - $config: mat-get-typography-config($config-or-theme); +@mixin typography($config-or-theme) { + $config: typography.private-typography-to-2014-config( + theming.get-typography-config($config-or-theme)); .mat-slider-thumb-label-text { font: { - family: mat-font-family($config); - size: mat-font-size($config, caption); - weight: mat-font-weight($config, body-2); + family: typography-utils.font-family($config); + size: typography-utils.font-size($config, caption); + weight: typography-utils.font-weight($config, body-2); } } } -@mixin _mat-slider-density($config-or-theme) {} +@mixin _density($config-or-theme) {} -@mixin mat-slider-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-slider') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-slider') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); @if $color != null { - @include mat-slider-color($color); + @include color($color); } @if $density != null { - @include _mat-slider-density($density); + @include _density($density); } @if $typography != null { - @include mat-slider-typography($typography); + @include typography($typography); } } } diff --git a/src/material/slider/public-api.ts b/src/material/slider/public-api.ts index ab7708f1942b..a203c15f18ac 100644 --- a/src/material/slider/public-api.ts +++ b/src/material/slider/public-api.ts @@ -8,4 +8,3 @@ export * from './slider-module'; export * from './slider'; - diff --git a/src/material/slider/slider-module.ts b/src/material/slider/slider-module.ts index 947f2a8aa0d2..04ddd8156dbc 100644 --- a/src/material/slider/slider-module.ts +++ b/src/material/slider/slider-module.ts @@ -11,7 +11,6 @@ import {NgModule} from '@angular/core'; import {MatCommonModule} from '@angular/material/core'; import {MatSlider} from './slider'; - @NgModule({ imports: [CommonModule, MatCommonModule], exports: [MatSlider, MatCommonModule], diff --git a/src/material/slider/slider.md b/src/material/slider/slider.md index f337cc64271c..73be0d40e408 100644 --- a/src/material/slider/slider.md +++ b/src/material/slider/slider.md @@ -54,7 +54,7 @@ displayed, you can do so using the `displayWith` input. ### Tick marks By default, sliders do not show tick marks along the thumb track. This can be enabled using the `tickInterval` attribute. The value of `tickInterval` should be a number representing the number -of steps between between ticks. For example a `tickInterval` of `3` with a `step` of `4` will draw +of steps between ticks. For example a `tickInterval` of `3` with a `step` of `4` will draw tick marks at every `3` steps, which is the same as every `12` values. ```html @@ -92,5 +92,7 @@ The slider has the following keyboard bindings: | Home | Set the value to the minimum possible. | ### Accessibility -Sliders without text or labels should be given a meaningful label via `aria-label` or + +`MatSlider` implements the ARIA `role="slider"` pattern, handling keyboard input and focus +management. Always provide an accessible label for each slider via `aria-label` or `aria-labelledby`. diff --git a/src/material/slider/slider.scss b/src/material/slider/slider.scss index 24f3953ddb2e..b7882b82aba3 100644 --- a/src/material/slider/slider.scss +++ b/src/material/slider/slider.scss @@ -1,48 +1,51 @@ -@import '../core/style/variables'; -@import '../core/style/vendor-prefixes'; -@import '../../cdk/a11y/a11y'; +@use 'sass:math'; +@use '../core/style/variables'; +@use '../core/style/vendor-prefixes'; +@use '../../cdk/a11y'; // This refers to the thickness of the slider. On a horizontal slider this is the height, on a // vertical slider this is the width. -$mat-slider-thickness: 48px !default; -$mat-slider-min-size: 128px !default; -$mat-slider-padding: 8px !default; +$thickness: 48px !default; +$min-size: 128px !default; +$padding: 8px !default; -$mat-slider-track-thickness: 2px !default; -$mat-slider-thumb-size: 20px !default; -$mat-slider-thumb-border-width: 3px !default; -$mat-slider-thumb-border-width-active: 2px !default; -$mat-slider-thumb-border-width-disabled: 4px !default; +$track-thickness: 2px !default; +$thumb-size: 20px !default; +$thumb-border-width: 3px !default; +$thumb-border-width-active: 2px !default; +$thumb-border-width-disabled: 4px !default; -$mat-slider-thumb-default-scale: 0.7 !default; -$mat-slider-thumb-focus-scale: 1 !default; -$mat-slider-thumb-disabled-scale: 0.5 !default; +$thumb-default-scale: 0.7 !default; +$thumb-focus-scale: 1 !default; +$thumb-disabled-scale: 0.5 !default; -$mat-slider-thumb-arrow-gap: 12px !default; +$thumb-arrow-gap: 12px !default; -$mat-slider-thumb-label-size: 28px !default; +$thumb-label-size: 28px !default; -$mat-slider-tick-size: 2px !default; +$tick-size: 2px !default; -$mat-slider-focus-ring-size: 30px !default; +$focus-ring-size: 30px !default; .mat-slider { display: inline-block; position: relative; box-sizing: border-box; - padding: $mat-slider-padding; + padding: $padding; outline: none; vertical-align: middle; &:not(.mat-slider-disabled):active, &.mat-slider-sliding:not(.mat-slider-disabled) { - @include cursor-grabbing; + @include vendor-prefixes.cursor-grabbing; } } .mat-slider-wrapper { + // force browser to show background-color when using the print function + @include vendor-prefixes.private-color-adjust(exact); position: absolute; } @@ -56,15 +59,17 @@ $mat-slider-focus-ring-size: 30px !default; .mat-slider-track-fill { position: absolute; transform-origin: 0 0; - transition: transform $swift-ease-out-duration $swift-ease-out-timing-function, - background-color $swift-ease-out-duration $swift-ease-out-timing-function; + transition: + transform variables.$swift-ease-out-duration variables.$swift-ease-out-timing-function, + background-color variables.$swift-ease-out-duration variables.$swift-ease-out-timing-function; } .mat-slider-track-background { position: absolute; transform-origin: 100% 100%; - transition: transform $swift-ease-out-duration $swift-ease-out-timing-function, - background-color $swift-ease-out-duration $swift-ease-out-timing-function; + transition: + transform variables.$swift-ease-out-duration variables.$swift-ease-out-timing-function, + background-color variables.$swift-ease-out-duration variables.$swift-ease-out-timing-function; } .mat-slider-ticks-container { @@ -75,29 +80,32 @@ $mat-slider-focus-ring-size: 30px !default; } .mat-slider-ticks { + @include vendor-prefixes.private-background-clip(content-box); background-repeat: repeat; - background-clip: content-box; box-sizing: border-box; opacity: 0; - transition: opacity $swift-ease-out-duration $swift-ease-out-timing-function; + transition: opacity variables.$swift-ease-out-duration + variables.$swift-ease-out-timing-function; } .mat-slider-thumb-container { position: absolute; z-index: 1; - transition: transform $swift-ease-out-duration $swift-ease-out-timing-function; + transition: transform variables.$swift-ease-out-duration + variables.$swift-ease-out-timing-function; } .mat-slider-focus-ring { position: absolute; - width: $mat-slider-focus-ring-size; - height: $mat-slider-focus-ring-size; + width: $focus-ring-size; + height: $focus-ring-size; border-radius: 50%; transform: scale(0); opacity: 0; - transition: transform $swift-ease-out-duration $swift-ease-out-timing-function, - background-color $swift-ease-out-duration $swift-ease-out-timing-function, - opacity $swift-ease-out-duration $swift-ease-out-timing-function; + transition: + transform variables.$swift-ease-out-duration variables.$swift-ease-out-timing-function, + background-color variables.$swift-ease-out-duration variables.$swift-ease-out-timing-function, + opacity variables.$swift-ease-out-duration variables.$swift-ease-out-timing-function; .mat-slider.cdk-keyboard-focused &, .mat-slider.cdk-program-focused & { @@ -108,7 +116,7 @@ $mat-slider-focus-ring-size: 30px !default; %_mat-slider-cursor { .mat-slider:not(.mat-slider-disabled):not(.mat-slider-sliding) & { - @include cursor-grab; + @include vendor-prefixes.cursor-grab; } } @@ -116,17 +124,18 @@ $mat-slider-focus-ring-size: 30px !default; @extend %_mat-slider-cursor; position: absolute; - right: -$mat-slider-thumb-size / 2; - bottom: -$mat-slider-thumb-size / 2; + right: math.div(-$thumb-size, 2); + bottom: math.div(-$thumb-size, 2); box-sizing: border-box; - width: $mat-slider-thumb-size; - height: $mat-slider-thumb-size; - border: $mat-slider-thumb-border-width solid transparent; + width: $thumb-size; + height: $thumb-size; + border: $thumb-border-width solid transparent; border-radius: 50%; - transform: scale($mat-slider-thumb-default-scale); - transition: transform $swift-ease-out-duration $swift-ease-out-timing-function, - background-color $swift-ease-out-duration $swift-ease-out-timing-function, - border-color $swift-ease-out-duration $swift-ease-out-timing-function; + transform: scale($thumb-default-scale); + transition: + transform variables.$swift-ease-out-duration variables.$swift-ease-out-timing-function, + background-color variables.$swift-ease-out-duration variables.$swift-ease-out-timing-function, + border-color variables.$swift-ease-out-duration variables.$swift-ease-out-timing-function; } .mat-slider-thumb-label { @@ -136,14 +145,15 @@ $mat-slider-focus-ring-size: 30px !default; align-items: center; justify-content: center; position: absolute; - width: $mat-slider-thumb-label-size; - height: $mat-slider-thumb-label-size; + width: $thumb-label-size; + height: $thumb-label-size; border-radius: 50%; - transition: transform $swift-ease-out-duration $swift-ease-out-timing-function, - border-radius $swift-ease-out-duration $swift-ease-out-timing-function, - background-color $swift-ease-out-duration $swift-ease-out-timing-function; + transition: + transform variables.$swift-ease-out-duration variables.$swift-ease-out-timing-function, + border-radius variables.$swift-ease-out-duration variables.$swift-ease-out-timing-function, + background-color variables.$swift-ease-out-duration variables.$swift-ease-out-timing-function; - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { outline: solid 1px; } } @@ -151,7 +161,7 @@ $mat-slider-focus-ring-size: 30px !default; .mat-slider-thumb-label-text { z-index: 1; opacity: 0; - transition: opacity $swift-ease-out-duration $swift-ease-out-timing-function; + transition: opacity variables.$swift-ease-out-duration variables.$swift-ease-out-timing-function; } @@ -176,7 +186,8 @@ $mat-slider-focus-ring-size: 30px !default; border-width: 0; border-style: solid; opacity: 0; - transition: opacity $swift-ease-out-duration $swift-ease-out-timing-function; + transition: opacity variables.$swift-ease-out-duration + variables.$swift-ease-out-timing-function; } &.cdk-focused, @@ -238,8 +249,8 @@ $mat-slider-focus-ring-size: 30px !default; &.cdk-touch-focused, &.cdk-program-focused { .mat-slider-thumb { - border-width: $mat-slider-thumb-border-width-active; - transform: scale($mat-slider-thumb-focus-scale); + border-width: $thumb-border-width-active; + transform: scale($thumb-focus-scale); } } } @@ -253,8 +264,8 @@ $mat-slider-focus-ring-size: 30px !default; } .mat-slider-thumb { - border-width: $mat-slider-thumb-border-width-disabled; - transform: scale($mat-slider-thumb-disabled-scale); + border-width: $thumb-border-width-disabled; + transform: scale($thumb-disabled-scale); } .mat-slider-thumb-label { @@ -265,53 +276,53 @@ $mat-slider-focus-ring-size: 30px !default; // Horizontal slider. .mat-slider-horizontal { - height: $mat-slider-thickness; - min-width: $mat-slider-min-size; + height: $thickness; + min-width: $min-size; .mat-slider-wrapper { - height: $mat-slider-track-thickness; - top: ($mat-slider-thickness - $mat-slider-track-thickness) / 2; - left: $mat-slider-padding; - right: $mat-slider-padding; + height: $track-thickness; + top: math.div($thickness - $track-thickness, 2); + left: $padding; + right: $padding; } .mat-slider-wrapper::after { - height: $mat-slider-track-thickness; - border-left-width: $mat-slider-tick-size; + height: $track-thickness; + border-left-width: $tick-size; right: 0; top: 0; } .mat-slider-track-wrapper { - height: $mat-slider-track-thickness; + height: $track-thickness; width: 100%; } .mat-slider-track-fill { - height: $mat-slider-track-thickness; + height: $track-thickness; width: 100%; transform: scaleX(0); } .mat-slider-track-background { - height: $mat-slider-track-thickness; + height: $track-thickness; width: 100%; transform: scaleX(1); } .mat-slider-ticks-container { - height: $mat-slider-track-thickness; + height: $track-thickness; width: 100%; - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { height: 0; - outline: solid $mat-slider-track-thickness; - top: $mat-slider-track-thickness / 2; + outline: solid $track-thickness; + top: math.div($track-thickness, 2); } } .mat-slider-ticks { - height: $mat-slider-track-thickness; + height: $track-thickness; width: 100%; } @@ -322,14 +333,14 @@ $mat-slider-focus-ring-size: 30px !default; } .mat-slider-focus-ring { - top: -$mat-slider-focus-ring-size / 2; - right: -$mat-slider-focus-ring-size / 2; + top: math.div(-$focus-ring-size, 2); + right: math.div(-$focus-ring-size, 2); } .mat-slider-thumb-label { - right: -$mat-slider-thumb-label-size / 2; - top: -($mat-slider-thumb-label-size + $mat-slider-thumb-arrow-gap); - transform: translateY($mat-slider-thumb-label-size / 2 + $mat-slider-thumb-arrow-gap) + right: math.div(-$thumb-label-size, 2); + top: -($thumb-label-size + $thumb-arrow-gap); + transform: translateY(math.div($thumb-label-size, 2) + $thumb-arrow-gap) scale(0.01) rotate(45deg); } @@ -343,7 +354,7 @@ $mat-slider-focus-ring-size: 30px !default; transform: rotate(45deg); } - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { .mat-slider-thumb-label, .mat-slider-thumb-label-text { transform: none; @@ -355,58 +366,58 @@ $mat-slider-focus-ring-size: 30px !default; // Vertical slider. .mat-slider-vertical { - width: $mat-slider-thickness; - min-height: $mat-slider-min-size; + width: $thickness; + min-height: $min-size; .mat-slider-wrapper { - width: $mat-slider-track-thickness; - top: $mat-slider-padding; - bottom: $mat-slider-padding; - left: ($mat-slider-thickness - $mat-slider-track-thickness) / 2; + width: $track-thickness; + top: $padding; + bottom: $padding; + left: math.div($thickness - $track-thickness, 2); } .mat-slider-wrapper::after { - width: $mat-slider-track-thickness; - border-top-width: $mat-slider-tick-size; + width: $track-thickness; + border-top-width: $tick-size; bottom: 0; left: 0; } .mat-slider-track-wrapper { height: 100%; - width: $mat-slider-track-thickness; + width: $track-thickness; } .mat-slider-track-fill { height: 100%; - width: $mat-slider-track-thickness; + width: $track-thickness; transform: scaleY(0); } .mat-slider-track-background { height: 100%; - width: $mat-slider-track-thickness; + width: $track-thickness; transform: scaleY(1); } .mat-slider-ticks-container { - width: $mat-slider-track-thickness; + width: $track-thickness; height: 100%; - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { width: 0; - outline: solid $mat-slider-track-thickness; - left: $mat-slider-track-thickness / 2; + outline: solid $track-thickness; + left: math.div($track-thickness, 2); } } .mat-slider-focus-ring { - bottom: -$mat-slider-focus-ring-size / 2; - left: -$mat-slider-focus-ring-size / 2; + bottom: math.div(-$focus-ring-size, 2); + left: math.div(-$focus-ring-size, 2); } .mat-slider-ticks { - width: $mat-slider-track-thickness; + width: $track-thickness; height: 100%; } @@ -417,13 +428,13 @@ $mat-slider-focus-ring-size: 30px !default; } .mat-slider-thumb { - @include backface-visibility(hidden); + @include vendor-prefixes.backface-visibility(hidden); } .mat-slider-thumb-label { - bottom: -$mat-slider-thumb-label-size / 2; - left: -($mat-slider-thumb-label-size + $mat-slider-thumb-arrow-gap); - transform: translateX($mat-slider-thumb-label-size / 2 + $mat-slider-thumb-arrow-gap) + bottom: math.div(-$thumb-label-size, 2); + left: -($thumb-label-size + $thumb-arrow-gap); + transform: translateX(math.div($thumb-label-size, 2) + $thumb-arrow-gap) scale(0.01) rotate(-45deg); } diff --git a/src/material/slider/slider.spec.ts b/src/material/slider/slider.spec.ts index d0bd33f853b4..a9acb3be6232 100644 --- a/src/material/slider/slider.spec.ts +++ b/src/material/slider/slider.spec.ts @@ -9,6 +9,7 @@ import { PAGE_UP, RIGHT_ARROW, UP_ARROW, + A, } from '@angular/cdk/keycodes'; import { createMouseEvent, @@ -17,7 +18,7 @@ import { dispatchKeyboardEvent, dispatchMouseEvent, createKeyboardEvent, -} from '@angular/cdk/testing/private'; +} from '../../cdk/testing/private'; import {Component, DebugElement, Type, ViewChild} from '@angular/core'; import {ComponentFixture, fakeAsync, flush, TestBed} from '@angular/core/testing'; import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms'; @@ -139,6 +140,28 @@ describe('MatSlider', () => { expect(sliderNativeElement.classList).not.toContain('mat-slider-sliding'); }); + it('should not interrupt sliding by pressing a key', () => { + expect(sliderNativeElement.classList).not.toContain('mat-slider-sliding'); + + dispatchSlideStartEvent(sliderNativeElement, 0); + fixture.detectChanges(); + + expect(sliderNativeElement.classList).toContain('mat-slider-sliding'); + + // Any key code will do here. Use A since it isn't associated with other actions. + dispatchKeyboardEvent(sliderNativeElement, 'keydown', A); + fixture.detectChanges(); + dispatchKeyboardEvent(sliderNativeElement, 'keyup', A); + fixture.detectChanges(); + + expect(sliderNativeElement.classList).toContain('mat-slider-sliding'); + + dispatchSlideEndEvent(sliderNativeElement, 0.34); + fixture.detectChanges(); + + expect(sliderNativeElement.classList).not.toContain('mat-slider-sliding'); + }); + it('should stop dragging if the page loses focus', () => { const classlist = sliderNativeElement.classList; @@ -219,7 +242,6 @@ describe('MatSlider', () => { it('should have a focus indicator', () => { expect(sliderNativeElement.classList.contains('mat-focus-indicator')).toBe(true); }); - }); describe('disabled slider', () => { @@ -286,7 +308,7 @@ describe('MatSlider', () => { expect(sliderNativeElement.classList).not.toContain('mat-slider-sliding'); }); - it ('should leave thumb gap', () => { + it('should leave thumb gap', () => { expect(trackFillElement.style.transform).toContain('translateX(-7px)'); }); @@ -314,8 +336,9 @@ describe('MatSlider', () => { sliderNativeElement = sliderDebugElement.nativeElement; sliderInstance = sliderDebugElement.injector.get(MatSlider); trackFillElement = sliderNativeElement.querySelector('.mat-slider-track-fill'); - ticksContainerElement = - sliderNativeElement.querySelector('.mat-slider-ticks-container'); + ticksContainerElement = ( + sliderNativeElement.querySelector('.mat-slider-ticks-container') + ); ticksElement = sliderNativeElement.querySelector('.mat-slider-ticks'); }); @@ -331,7 +354,7 @@ describe('MatSlider', () => { // Computed by multiplying the difference between the min and the max by the percentage from // the mousedown and adding that to the minimum. - let value = Math.round(4 + (0.09 * (6 - 4))); + const value = Math.round(4 + 0.09 * (6 - 4)); expect(sliderInstance.value).toBe(value); }); @@ -341,7 +364,7 @@ describe('MatSlider', () => { // Computed by multiplying the difference between the min and the max by the percentage from // the mousedown and adding that to the minimum. - let value = Math.round(4 + (0.62 * (6 - 4))); + const value = Math.round(4 + 0.62 * (6 - 4)); expect(sliderInstance.value).toBe(value); }); @@ -392,28 +415,29 @@ describe('MatSlider', () => { expect(ticksContainerElement.style.transform).toBe('translateX(-25%)'); }); - it('should be able to set the min and max values when they are more precise ' + - 'than the step', () => { - // Note that we assign min/max with more decimals than the - // step to ensure that the value doesn't get rounded up. - testComponent.step = 0.5; - testComponent.min = 10.15; - testComponent.max = 50.15; - fixture.detectChanges(); - - dispatchSlideEventSequence(sliderNativeElement, 0.5, 0); - fixture.detectChanges(); + it( + 'should be able to set the min and max values when they are more precise ' + 'than the step', + () => { + // Note that we assign min/max with more decimals than the + // step to ensure that the value doesn't get rounded up. + testComponent.step = 0.5; + testComponent.min = 10.15; + testComponent.max = 50.15; + fixture.detectChanges(); - expect(sliderInstance.value).toBe(10.15); - expect(sliderInstance.percent).toBe(0); + dispatchSlideEventSequence(sliderNativeElement, 0.5, 0); + fixture.detectChanges(); - dispatchSlideEventSequence(sliderNativeElement, 0.5, 1); - fixture.detectChanges(); + expect(sliderInstance.value).toBe(10.15); + expect(sliderInstance.percent).toBe(0); - expect(sliderInstance.value).toBe(50.15); - expect(sliderInstance.percent).toBe(1); - }); + dispatchSlideEventSequence(sliderNativeElement, 0.5, 1); + fixture.detectChanges(); + expect(sliderInstance.value).toBe(50.15); + expect(sliderInstance.percent).toBe(1); + }, + ); }); describe('slider with set value', () => { @@ -560,7 +584,6 @@ describe('MatSlider', () => { expect(sliderNativeElement.getAttribute('aria-valuetext')).toBeFalsy(); }); - }); describe('slider with auto ticks', () => { @@ -576,8 +599,9 @@ describe('MatSlider', () => { sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; - ticksContainerElement = - sliderNativeElement.querySelector('.mat-slider-ticks-container'); + ticksContainerElement = ( + sliderNativeElement.querySelector('.mat-slider-ticks-container') + ); ticksElement = sliderNativeElement.querySelector('.mat-slider-ticks'); }); @@ -606,8 +630,9 @@ describe('MatSlider', () => { sliderDebugElement = fixture.debugElement.query(By.directive(MatSlider))!; sliderNativeElement = sliderDebugElement.nativeElement; - ticksContainerElement = - sliderNativeElement.querySelector('.mat-slider-ticks-container'); + ticksContainerElement = ( + sliderNativeElement.querySelector('.mat-slider-ticks-container') + ); ticksElement = sliderNativeElement.querySelector('.mat-slider-ticks'); }); @@ -625,13 +650,16 @@ describe('MatSlider', () => { it('should be able to reset the tick interval after it has been set', () => { expect(sliderNativeElement.classList) - .toContain('mat-slider-has-ticks', 'Expected element to have ticks initially.'); + .withContext('Expected element to have ticks initially.') + .toContain('mat-slider-has-ticks'); fixture.componentInstance.tickInterval = 0; fixture.detectChanges(); - expect(sliderNativeElement.classList) - .not.toContain('mat-slider-has-ticks', 'Expected element not to have ticks after reset.'); + expect(sliderNativeElement.classList).not.toContain( + 'mat-slider-has-ticks', + 'Expected element not to have ticks after reset.', + ); }); }); @@ -846,36 +874,39 @@ describe('MatSlider', () => { expect(testComponent.onChange).toHaveBeenCalledTimes(1); }); - it('should dispatch events when changing back to previously emitted value after ' + - 'programmatically setting value', () => { - expect(testComponent.onChange).not.toHaveBeenCalled(); - expect(testComponent.onInput).not.toHaveBeenCalled(); + it( + 'should dispatch events when changing back to previously emitted value after ' + + 'programmatically setting value', + () => { + expect(testComponent.onChange).not.toHaveBeenCalled(); + expect(testComponent.onInput).not.toHaveBeenCalled(); - dispatchMousedownEventSequence(sliderNativeElement, 0.2); - fixture.detectChanges(); + dispatchMousedownEventSequence(sliderNativeElement, 0.2); + fixture.detectChanges(); - expect(testComponent.onChange).not.toHaveBeenCalled(); - expect(testComponent.onInput).toHaveBeenCalledTimes(1); + expect(testComponent.onChange).not.toHaveBeenCalled(); + expect(testComponent.onInput).toHaveBeenCalledTimes(1); - dispatchSlideEndEvent(sliderNativeElement, 0.2); - fixture.detectChanges(); + dispatchSlideEndEvent(sliderNativeElement, 0.2); + fixture.detectChanges(); - expect(testComponent.onChange).toHaveBeenCalledTimes(1); - expect(testComponent.onInput).toHaveBeenCalledTimes(1); + expect(testComponent.onChange).toHaveBeenCalledTimes(1); + expect(testComponent.onInput).toHaveBeenCalledTimes(1); - testComponent.slider.value = 0; - fixture.detectChanges(); + testComponent.slider.value = 0; + fixture.detectChanges(); - expect(testComponent.onChange).toHaveBeenCalledTimes(1); - expect(testComponent.onInput).toHaveBeenCalledTimes(1); + expect(testComponent.onChange).toHaveBeenCalledTimes(1); + expect(testComponent.onInput).toHaveBeenCalledTimes(1); - dispatchMousedownEventSequence(sliderNativeElement, 0.2); - fixture.detectChanges(); - dispatchSlideEndEvent(sliderNativeElement, 0.2); + dispatchMousedownEventSequence(sliderNativeElement, 0.2); + fixture.detectChanges(); + dispatchSlideEndEvent(sliderNativeElement, 0.2); - expect(testComponent.onChange).toHaveBeenCalledTimes(2); - expect(testComponent.onInput).toHaveBeenCalledTimes(2); - }); + expect(testComponent.onChange).toHaveBeenCalledTimes(2); + expect(testComponent.onInput).toHaveBeenCalledTimes(2); + }, + ); }); describe('slider with input event', () => { @@ -923,7 +954,6 @@ describe('MatSlider', () => { expect(testComponent.onInput).toHaveBeenCalledTimes(1); expect(testComponent.onChange).toHaveBeenCalledTimes(1); }); - }); describe('keyboard support', () => { @@ -1067,21 +1097,19 @@ describe('MatSlider', () => { it('should ignore events modifier keys', () => { sliderInstance.value = 0; - [ - UP_ARROW, DOWN_ARROW, RIGHT_ARROW, - LEFT_ARROW, PAGE_DOWN, PAGE_UP, HOME, END - ].forEach(key => { - const event = createKeyboardEvent('keydown', key, undefined, {alt: true}); - dispatchEvent(sliderNativeElement, event); - fixture.detectChanges(); - expect(event.defaultPrevented).toBe(false); - }); + [UP_ARROW, DOWN_ARROW, RIGHT_ARROW, LEFT_ARROW, PAGE_DOWN, PAGE_UP, HOME, END].forEach( + key => { + const event = createKeyboardEvent('keydown', key, undefined, {alt: true}); + dispatchEvent(sliderNativeElement, event); + fixture.detectChanges(); + expect(event.defaultPrevented).toBe(false); + }, + ); expect(testComponent.onInput).not.toHaveBeenCalled(); expect(testComponent.onChange).not.toHaveBeenCalled(); expect(sliderInstance.value).toBe(0); }); - }); describe('slider with direction and invert', () => { @@ -1136,10 +1164,10 @@ describe('MatSlider', () => { testComponent.dir = 'rtl'; fixture.detectChanges(); - let initialTrackFillStyles = sliderInstance._getTrackFillStyles(); - let initialTicksContainerStyles = sliderInstance._getTicksContainerStyles(); - let initialTicksStyles = sliderInstance._getTicksStyles(); - let initialThumbContainerStyles = sliderInstance._getThumbContainerStyles(); + const initialTrackFillStyles = sliderInstance._getTrackFillStyles(); + const initialTicksContainerStyles = sliderInstance._getTicksContainerStyles(); + const initialTicksStyles = sliderInstance._getTicksStyles(); + const initialThumbContainerStyles = sliderInstance._getThumbContainerStyles(); testComponent.dir = 'ltr'; fixture.detectChanges(); @@ -1220,7 +1248,8 @@ describe('MatSlider', () => { fixture.detectChanges(); expect(sliderNativeElement.classList.contains('mat-slider-hide-last-tick')) - .toBe(true, 'last tick should be hidden'); + .withContext('last tick should be hidden') + .toBe(true); }); }); @@ -1287,19 +1316,20 @@ describe('MatSlider', () => { }); describe('tabindex', () => { - it('should allow setting the tabIndex through binding', () => { const fixture = createComponent(SliderWithTabIndexBinding); fixture.detectChanges(); const slider = fixture.debugElement.query(By.directive(MatSlider))!.componentInstance; - expect(slider.tabIndex).toBe(0, 'Expected the tabIndex to be set to 0 by default.'); + expect(slider.tabIndex) + .withContext('Expected the tabIndex to be set to 0 by default.') + .toBe(0); fixture.componentInstance.tabIndex = 3; fixture.detectChanges(); - expect(slider.tabIndex).toBe(3, 'Expected the tabIndex to have been changed.'); + expect(slider.tabIndex).withContext('Expected the tabIndex to have been changed.').toBe(3); }); it('should detect the native tabindex attribute', () => { @@ -1309,7 +1339,8 @@ describe('MatSlider', () => { const slider = fixture.debugElement.query(By.directive(MatSlider))!.componentInstance; expect(slider.tabIndex) - .toBe(5, 'Expected the tabIndex to be set to the value of the native attribute.'); + .withContext('Expected the tabIndex to be set to the value of the native attribute.') + .toBe(5); }); }); @@ -1372,7 +1403,6 @@ describe('MatSlider', () => { expect(testComponent.slider.value).toBe(0); })); - }); describe('slider as a custom form control', () => { @@ -1449,7 +1479,7 @@ describe('MatSlider', () => { }); it('should have the correct control state initially and after interaction', () => { - let sliderControl = testComponent.control; + const sliderControl = testComponent.control; // The control should start off valid, pristine, and untouched. expect(sliderControl.valid).toBe(true); @@ -1509,7 +1539,6 @@ describe('MatSlider', () => { expect(testComponent.slider.value).toBe(20); }); }); - }); // Disable animations and make the slider an even 100px (+ 8px padding on either side) @@ -1524,13 +1553,13 @@ const styles = ` template: ``, styles: [styles], }) -class StandardSlider { } +class StandardSlider {} @Component({ template: ``, styles: [styles], }) -class DisabledSlider { } +class DisabledSlider {} @Component({ template: ``, @@ -1546,7 +1575,7 @@ class SliderWithMinAndMax { template: ``, styles: [styles], }) -class SliderWithValue { } +class SliderWithValue {} @Component({ template: ``, @@ -1561,7 +1590,7 @@ class SliderWithStep { template: ``, styles: [styles], }) -class SliderWithAutoTickInterval { } +class SliderWithAutoTickInterval {} @Component({ template: ``, @@ -1575,8 +1604,7 @@ class SliderWithSetTickInterval { template: ``, styles: [styles], }) -class SliderWithThumbLabel { } - +class SliderWithThumbLabel {} @Component({ template: ``, @@ -1585,14 +1613,13 @@ class SliderWithThumbLabel { } class SliderWithCustomThumbLabelFormatting { displayWith(value: number) { if (value >= 1000) { - return (value / 1000) + 'k'; + return value / 1000 + 'k'; } return value; } } - @Component({ template: ``, styles: [styles], @@ -1622,21 +1649,21 @@ class SliderWithNgModel { template: ``, styles: [styles], }) -class SliderWithValueSmallerThanMin { } +class SliderWithValueSmallerThanMin {} @Component({ template: ``, styles: [styles], }) -class SliderWithValueGreaterThanMax { } +class SliderWithValueGreaterThanMax {} @Component({ template: ``, styles: [styles], }) class SliderWithChangeHandler { - onChange() { } - onInput() { } + onChange() {} + onInput() {} @ViewChild(MatSlider) slider: MatSlider; } @@ -1691,12 +1718,15 @@ class SliderWithTwoWayBinding { * physical location of the pointer. * @param button Button that should be held down when starting to drag the slider. */ -function dispatchMousedownEventSequence(sliderElement: HTMLElement, percentage: number, - button = 0): void { +function dispatchMousedownEventSequence( + sliderElement: HTMLElement, + percentage: number, + button = 0, +): void { const trackElement = sliderElement.querySelector('.mat-slider-wrapper')!; const dimensions = trackElement.getBoundingClientRect(); - const x = dimensions.left + (dimensions.width * percentage); - const y = dimensions.top + (dimensions.height * percentage); + const x = dimensions.left + dimensions.width * percentage; + const y = dimensions.top + dimensions.height * percentage; dispatchMouseenterEvent(sliderElement); dispatchEvent(sliderElement, createMouseEvent('mousedown', x, y, button)); @@ -1708,8 +1738,11 @@ function dispatchMousedownEventSequence(sliderElement: HTMLElement, percentage: * @param startPercent The percentage of the slider where the slide will begin. * @param endPercent The percentage of the slider where the slide will end. */ -function dispatchSlideEventSequence(sliderElement: HTMLElement, startPercent: number, - endPercent: number): void { +function dispatchSlideEventSequence( + sliderElement: HTMLElement, + startPercent: number, + endPercent: number, +): void { dispatchMouseenterEvent(sliderElement); dispatchSlideStartEvent(sliderElement, startPercent); dispatchSlideEvent(sliderElement, startPercent); @@ -1725,8 +1758,8 @@ function dispatchSlideEventSequence(sliderElement: HTMLElement, startPercent: nu function dispatchSlideEvent(sliderElement: HTMLElement, percent: number): void { const trackElement = sliderElement.querySelector('.mat-slider-wrapper')!; const dimensions = trackElement.getBoundingClientRect(); - const x = dimensions.left + (dimensions.width * percent); - const y = dimensions.top + (dimensions.height * percent); + const x = dimensions.left + dimensions.width * percent; + const y = dimensions.top + dimensions.height * percent; dispatchMouseEvent(document, 'mousemove', x, y); } @@ -1738,8 +1771,8 @@ function dispatchSlideEvent(sliderElement: HTMLElement, percent: number): void { function dispatchSlideStartEvent(sliderElement: HTMLElement, percent: number): void { const trackElement = sliderElement.querySelector('.mat-slider-wrapper')!; const dimensions = trackElement.getBoundingClientRect(); - const x = dimensions.left + (dimensions.width * percent); - const y = dimensions.top + (dimensions.height * percent); + const x = dimensions.left + dimensions.width * percent; + const y = dimensions.top + dimensions.height * percent; dispatchMouseenterEvent(sliderElement); dispatchMouseEvent(sliderElement, 'mousedown', x, y); } @@ -1752,8 +1785,8 @@ function dispatchSlideStartEvent(sliderElement: HTMLElement, percent: number): v function dispatchSlideEndEvent(sliderElement: HTMLElement, percent: number): void { const trackElement = sliderElement.querySelector('.mat-slider-wrapper')!; const dimensions = trackElement.getBoundingClientRect(); - const x = dimensions.left + (dimensions.width * percent); - const y = dimensions.top + (dimensions.height * percent); + const x = dimensions.left + dimensions.width * percent; + const y = dimensions.top + dimensions.height * percent; dispatchMouseEvent(document, 'mouseup', x, y); } diff --git a/src/material/slider/slider.ts b/src/material/slider/slider.ts index 6a2bf4dee9f3..4fb7650df091 100644 --- a/src/material/slider/slider.ts +++ b/src/material/slider/slider.ts @@ -12,7 +12,7 @@ import { BooleanInput, coerceBooleanProperty, coerceNumberProperty, - NumberInput + NumberInput, } from '@angular/cdk/coercion'; import { DOWN_ARROW, @@ -46,11 +46,8 @@ import { import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import { CanColor, - CanColorCtor, CanDisable, - CanDisableCtor, HasTabIndex, - HasTabIndexCtor, mixinColor, mixinDisabled, mixinTabIndex, @@ -85,7 +82,7 @@ const MIN_VALUE_ACTIVE_THUMB_GAP = 10; export const MAT_SLIDER_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MatSlider), - multi: true + multi: true, }; /** A simple change event emitted by the MatSlider component. */ @@ -99,15 +96,16 @@ export class MatSliderChange { // Boilerplate for applying mixins to MatSlider. /** @docs-private */ -class MatSliderBase { - constructor(public _elementRef: ElementRef) {} -} -const _MatSliderMixinBase: - HasTabIndexCtor & - CanColorCtor & - CanDisableCtor & - typeof MatSliderBase = - mixinTabIndex(mixinColor(mixinDisabled(MatSliderBase), 'accent')); +const _MatSliderBase = mixinTabIndex( + mixinColor( + mixinDisabled( + class { + constructor(public _elementRef: ElementRef) {} + }, + ), + 'accent', + ), +); /** * Allows users to select from a range of values by moving the slider thumb. It is similar in @@ -154,7 +152,7 @@ const _MatSliderMixinBase: '[class.mat-slider-vertical]': 'vertical', '[class.mat-slider-min-value]': '_isMinValue()', '[class.mat-slider-hide-last-tick]': - 'disabled || _isMinValue() && _getThumbGap() && _shouldInvertAxis()', + 'disabled || _isMinValue() && _getThumbGap() && _shouldInvertAxis()', '[class._mat-animation-noopable]': '_animationMode === "NoopAnimations"', }, templateUrl: 'slider.html', @@ -163,20 +161,26 @@ const _MatSliderMixinBase: encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) -export class MatSlider extends _MatSliderMixinBase - implements ControlValueAccessor, OnDestroy, CanDisable, CanColor, AfterViewInit, HasTabIndex { +export class MatSlider + extends _MatSliderBase + implements ControlValueAccessor, OnDestroy, CanDisable, CanColor, AfterViewInit, HasTabIndex +{ /** Whether the slider is inverted. */ @Input() - get invert(): boolean { return this._invert; } - set invert(value: boolean) { + get invert(): boolean { + return this._invert; + } + set invert(value: BooleanInput) { this._invert = coerceBooleanProperty(value); } private _invert = false; /** The maximum value that the slider can have. */ @Input() - get max(): number { return this._max; } - set max(v: number) { + get max(): number { + return this._max; + } + set max(v: NumberInput) { this._max = coerceNumberProperty(v, this._max); this._percent = this._calculatePercentage(this._value); @@ -187,14 +191,11 @@ export class MatSlider extends _MatSliderMixinBase /** The minimum value that the slider can have. */ @Input() - get min(): number { return this._min; } - set min(v: number) { + get min(): number { + return this._min; + } + set min(v: NumberInput) { this._min = coerceNumberProperty(v, this._min); - - // If the value wasn't explicitly set by the user, set it to the min. - if (this._value === null) { - this.value = this._min; - } this._percent = this._calculatePercentage(this._value); // Since this also modifies the percentage, we need to let the change detection know. @@ -204,8 +205,10 @@ export class MatSlider extends _MatSliderMixinBase /** The values at which the thumb will snap. */ @Input() - get step(): number { return this._step; } - set step(v: number) { + get step(): number { + return this._step; + } + set step(v: NumberInput) { this._step = coerceNumberProperty(v, this._step); if (this._step % 1 !== 0) { @@ -219,8 +222,12 @@ export class MatSlider extends _MatSliderMixinBase /** Whether or not to show the thumb label. */ @Input() - get thumbLabel(): boolean { return this._thumbLabel; } - set thumbLabel(value: boolean) { this._thumbLabel = coerceBooleanProperty(value); } + get thumbLabel(): boolean { + return this._thumbLabel; + } + set thumbLabel(value: BooleanInput) { + this._thumbLabel = coerceBooleanProperty(value); + } private _thumbLabel: boolean = false; /** @@ -228,8 +235,10 @@ export class MatSlider extends _MatSliderMixinBase * Ex: Tick interval of 4 with a step of 3 will draw a tick every 4 steps (every 12 values). */ @Input() - get tickInterval() { return this._tickInterval; } - set tickInterval(value: 'auto' | number) { + get tickInterval(): 'auto' | number { + return this._tickInterval; + } + set tickInterval(value: 'auto' | NumberInput) { if (value === 'auto') { this._tickInterval = 'auto'; } else if (typeof value === 'number' || typeof value === 'string') { @@ -242,16 +251,16 @@ export class MatSlider extends _MatSliderMixinBase /** Value of the slider. */ @Input() - get value(): number | null { + get value(): number { // If the value needs to be read and it is still uninitialized, initialize it to the min. if (this._value === null) { this.value = this._min; } - return this._value; + return this._value as number; } - set value(v: number | null) { + set value(v: NumberInput) { if (v !== this._value) { - let value = coerceNumberProperty(v); + let value = coerceNumberProperty(v, 0); // While incrementing by a decimal we can end up with values like 33.300000000000004. // Truncate it to ensure that it matches the label and to make it easier to work with. @@ -280,8 +289,10 @@ export class MatSlider extends _MatSliderMixinBase /** Whether the slider is vertical. */ @Input() - get vertical(): boolean { return this._vertical; } - set vertical(value: boolean) { + get vertical(): boolean { + return this._vertical; + } + set vertical(value: BooleanInput) { this._vertical = coerceBooleanProperty(value); } private _vertical = false; @@ -331,14 +342,16 @@ export class MatSlider extends _MatSliderMixinBase onTouched: () => any = () => {}; /** The percentage of the slider that coincides with the value. */ - get percent(): number { return this._clamp(this._percent); } + get percent(): number { + return this._clamp(this._percent); + } private _percent: number = 0; /** - * Whether or not the thumb is sliding. + * Whether or not the thumb is sliding and what the user is using to slide it with. * Used to determine if there should be a transition for the thumb and fill track. */ - _isSliding: boolean = false; + _isSliding: 'keyboard' | 'pointer' | null = null; /** * Whether or not the slider is active (clicked or sliding). @@ -356,7 +369,6 @@ export class MatSlider extends _MatSliderMixinBase return this.vertical ? !this.invert : this.invert; } - /** Whether the slider is at its minimum value. */ _isMinValue() { return this.percent === 0; @@ -377,19 +389,19 @@ export class MatSlider extends _MatSliderMixinBase } /** CSS styles for the track background element. */ - _getTrackBackgroundStyles(): { [key: string]: string } { + _getTrackBackgroundStyles(): {[key: string]: string} { const axis = this.vertical ? 'Y' : 'X'; const scale = this.vertical ? `1, ${1 - this.percent}, 1` : `${1 - this.percent}, 1, 1`; const sign = this._shouldInvertMouseCoords() ? '-' : ''; return { // scale3d avoids some rendering issues in Chrome. See #12071. - transform: `translate${axis}(${sign}${this._getThumbGap()}px) scale3d(${scale})` + transform: `translate${axis}(${sign}${this._getThumbGap()}px) scale3d(${scale})`, }; } /** CSS styles for the track fill element. */ - _getTrackFillStyles(): { [key: string]: string } { + _getTrackFillStyles(): {[key: string]: string} { const percent = this.percent; const axis = this.vertical ? 'Y' : 'X'; const scale = this.vertical ? `1, ${percent}, 1` : `${percent}, 1, 1`; @@ -402,24 +414,24 @@ export class MatSlider extends _MatSliderMixinBase // something forces a style recalculation on it. Since we'll end up with `scale(0)` when // the value of the slider is 0, we can easily get into this situation. We force a // recalculation by changing the element's `display` when it goes from 0 to any other value. - display: percent === 0 ? 'none' : '' + display: percent === 0 ? 'none' : '', }; } /** CSS styles for the ticks container element. */ - _getTicksContainerStyles(): { [key: string]: string } { + _getTicksContainerStyles(): {[key: string]: string} { let axis = this.vertical ? 'Y' : 'X'; // For a horizontal slider in RTL languages we push the ticks container off the left edge // instead of the right edge to avoid causing a horizontal scrollbar to appear. let sign = !this.vertical && this._getDirection() == 'rtl' ? '' : '-'; - let offset = this._tickIntervalPercent / 2 * 100; + let offset = (this._tickIntervalPercent / 2) * 100; return { - 'transform': `translate${axis}(${sign}${offset}%)` + 'transform': `translate${axis}(${sign}${offset}%)`, }; } /** CSS styles for the ticks element. */ - _getTicksStyles(): { [key: string]: string } { + _getTicksStyles(): {[key: string]: string} { let tickSize = this._tickIntervalPercent * 100; let backgroundSize = this.vertical ? `2px ${tickSize}%` : `${tickSize}% 2px`; let axis = this.vertical ? 'Y' : 'X'; @@ -428,10 +440,10 @@ export class MatSlider extends _MatSliderMixinBase // ticks 180 degrees so we're really cutting off the end edge abd not the start. let sign = !this.vertical && this._getDirection() == 'rtl' ? '-' : ''; let rotate = !this.vertical && this._getDirection() == 'rtl' ? ' rotate(180deg)' : ''; - let styles: { [key: string]: string } = { + let styles: {[key: string]: string} = { 'backgroundSize': backgroundSize, // Without translateZ ticks sometimes jitter as the slider moves on Chrome & Firefox. - 'transform': `translateZ(0) translate${axis}(${sign}${tickSize / 2}%)${rotate}` + 'transform': `translateZ(0) translate${axis}(${sign}${tickSize / 2}%)${rotate}`, }; if (this._isMinValue() && this._getThumbGap()) { @@ -450,16 +462,16 @@ export class MatSlider extends _MatSliderMixinBase return styles; } - _getThumbContainerStyles(): { [key: string]: string } { + _getThumbContainerStyles(): {[key: string]: string} { const shouldInvertAxis = this._shouldInvertAxis(); let axis = this.vertical ? 'Y' : 'X'; // For a horizontal slider in RTL languages we push the thumb container off the left edge // instead of the right edge to avoid causing a horizontal scrollbar to appear. let invertOffset = - (this._getDirection() == 'rtl' && !this.vertical) ? !shouldInvertAxis : shouldInvertAxis; + this._getDirection() == 'rtl' && !this.vertical ? !shouldInvertAxis : shouldInvertAxis; let offset = (invertOffset ? this.percent : 1 - this.percent) * 100; return { - 'transform': `translate${axis}(-${offset}%)` + 'transform': `translate${axis}(-${offset}%)`, }; } @@ -489,12 +501,12 @@ export class MatSlider extends _MatSliderMixinBase */ _shouldInvertMouseCoords() { const shouldInvertAxis = this._shouldInvertAxis(); - return (this._getDirection() == 'rtl' && !this.vertical) ? !shouldInvertAxis : shouldInvertAxis; + return this._getDirection() == 'rtl' && !this.vertical ? !shouldInvertAxis : shouldInvertAxis; } /** The language direction for this slider element. */ private _getDirection() { - return (this._dir && this._dir.value == 'rtl') ? 'rtl' : 'ltr'; + return this._dir && this._dir.value == 'rtl' ? 'rtl' : 'ltr'; } /** Keeps track of the last pointer event that was captured by the slider. */ @@ -503,14 +515,25 @@ export class MatSlider extends _MatSliderMixinBase /** Used to subscribe to global move and end events */ protected _document: Document; - constructor(elementRef: ElementRef, - private _focusMonitor: FocusMonitor, - private _changeDetectorRef: ChangeDetectorRef, - @Optional() private _dir: Directionality, - @Attribute('tabindex') tabIndex: string, - private _ngZone: NgZone, - @Inject(DOCUMENT) _document: any, - @Optional() @Inject(ANIMATION_MODULE_TYPE) public _animationMode?: string) { + /** + * Identifier used to attribute a touch event to a particular slider. + * Will be undefined if one of the following conditions is true: + * - The user isn't dragging using a touch device. + * - The browser doesn't support `Touch.identifier`. + * - Dragging hasn't started yet. + */ + private _touchId: number | undefined; + + constructor( + elementRef: ElementRef, + private _focusMonitor: FocusMonitor, + private _changeDetectorRef: ChangeDetectorRef, + @Optional() private _dir: Directionality, + @Attribute('tabindex') tabIndex: string, + private _ngZone: NgZone, + @Inject(DOCUMENT) _document: any, + @Optional() @Inject(ANIMATION_MODULE_TYPE) public _animationMode?: string, + ) { super(elementRef); this._document = _document; this.tabIndex = parseInt(tabIndex) || 0; @@ -523,12 +546,10 @@ export class MatSlider extends _MatSliderMixinBase } ngAfterViewInit() { - this._focusMonitor - .monitor(this._elementRef, true) - .subscribe((origin: FocusOrigin) => { - this._isActive = !!origin && origin !== 'keyboard'; - this._changeDetectorRef.detectChanges(); - }); + this._focusMonitor.monitor(this._elementRef, true).subscribe((origin: FocusOrigin) => { + this._isActive = !!origin && origin !== 'keyboard'; + this._changeDetectorRef.detectChanges(); + }); if (this._dir) { this._dirChangeSubscription = this._dir.change.subscribe(() => { this._changeDetectorRef.markForCheck(); @@ -569,7 +590,11 @@ export class MatSlider extends _MatSliderMixinBase } _onKeydown(event: KeyboardEvent) { - if (this.disabled || hasModifierKey(event)) { + if ( + this.disabled || + hasModifierKey(event) || + (this._isSliding && this._isSliding !== 'keyboard') + ) { return; } @@ -619,12 +644,14 @@ export class MatSlider extends _MatSliderMixinBase this._emitChangeEvent(); } - this._isSliding = true; + this._isSliding = 'keyboard'; event.preventDefault(); } _onKeyup() { - this._isSliding = false; + if (this._isSliding === 'keyboard') { + this._isSliding = null; + } } /** Called when the user has put their pointer down on the slider. */ @@ -636,58 +663,77 @@ export class MatSlider extends _MatSliderMixinBase } this._ngZone.run(() => { - const oldValue = this.value; - const pointerPosition = getPointerPositionOnPage(event); - this._isSliding = true; - this._lastPointerEvent = event; - event.preventDefault(); - this._focusHostElement(); - this._onMouseenter(); // Simulate mouseenter in case this is a mobile device. - this._bindGlobalEvents(event); - this._focusHostElement(); - this._updateValueFromPosition(pointerPosition); - this._valueOnSlideStart = oldValue; - - // Emit a change and input event if the value changed. - if (oldValue != this.value) { - this._emitInputEvent(); + this._touchId = isTouchEvent(event) + ? getTouchIdForSlider(event, this._elementRef.nativeElement) + : undefined; + const pointerPosition = getPointerPositionOnPage(event, this._touchId); + + if (pointerPosition) { + const oldValue = this.value; + this._isSliding = 'pointer'; + this._lastPointerEvent = event; + event.preventDefault(); + this._focusHostElement(); + this._onMouseenter(); // Simulate mouseenter in case this is a mobile device. + this._bindGlobalEvents(event); + this._focusHostElement(); + this._updateValueFromPosition(pointerPosition); + this._valueOnSlideStart = oldValue; + + // Emit a change and input event if the value changed. + if (oldValue != this.value) { + this._emitInputEvent(); + } } }); - } + }; /** * Called when the user has moved their pointer after * starting to drag. Bound on the document level. */ private _pointerMove = (event: TouchEvent | MouseEvent) => { - if (this._isSliding) { - // Prevent the slide from selecting anything else. - event.preventDefault(); - const oldValue = this.value; - this._lastPointerEvent = event; - this._updateValueFromPosition(getPointerPositionOnPage(event)); - - // Native range elements always emit `input` events when the value changed while sliding. - if (oldValue != this.value) { - this._emitInputEvent(); + if (this._isSliding === 'pointer') { + const pointerPosition = getPointerPositionOnPage(event, this._touchId); + + if (pointerPosition) { + // Prevent the slide from selecting anything else. + event.preventDefault(); + const oldValue = this.value; + this._lastPointerEvent = event; + this._updateValueFromPosition(pointerPosition); + + // Native range elements always emit `input` events when the value changed while sliding. + if (oldValue != this.value) { + this._emitInputEvent(); + } } } - } + }; /** Called when the user has lifted their pointer. Bound on the document level. */ private _pointerUp = (event: TouchEvent | MouseEvent) => { - if (this._isSliding) { - event.preventDefault(); - this._removeGlobalEvents(); - this._isSliding = false; - - if (this._valueOnSlideStart != this.value && !this.disabled) { - this._emitChangeEvent(); + if (this._isSliding === 'pointer') { + if ( + !isTouchEvent(event) || + typeof this._touchId !== 'number' || + // Note that we use `changedTouches`, rather than `touches` because it + // seems like in most cases `touches` is empty for `touchend` events. + findMatchingTouch(event.changedTouches, this._touchId) + ) { + event.preventDefault(); + this._removeGlobalEvents(); + this._isSliding = null; + this._touchId = undefined; + + if (this._valueOnSlideStart != this.value && !this.disabled) { + this._emitChangeEvent(); + } + + this._valueOnSlideStart = this._lastPointerEvent = null; } - - this._valueOnSlideStart = this._lastPointerEvent = null; } - } + }; /** Called when the window has lost focus. */ private _windowBlur = () => { @@ -696,7 +742,7 @@ export class MatSlider extends _MatSliderMixinBase if (this._lastPointerEvent) { this._pointerUp(this._lastPointerEvent); } - } + }; /** Use defaultView of injected document if available or fallback to global window reference */ private _getWindow(): Window { @@ -751,7 +797,7 @@ export class MatSlider extends _MatSliderMixinBase } /** Calculate the new value from the new physical location. The value will always be snapped. */ - private _updateValueFromPosition(pos: {x: number, y: number}) { + private _updateValueFromPosition(pos: {x: number; y: number}) { if (!this._sliderDimensions) { return; } @@ -807,12 +853,12 @@ export class MatSlider extends _MatSliderMixinBase if (this.tickInterval == 'auto') { let trackSize = this.vertical ? this._sliderDimensions.height : this._sliderDimensions.width; - let pixelsPerStep = trackSize * this.step / (this.max - this.min); + let pixelsPerStep = (trackSize * this.step) / (this.max - this.min); let stepsPerTick = Math.ceil(MIN_AUTO_TICK_SEPARATION / pixelsPerStep); let pixelsPerTick = stepsPerTick * this.step; this._tickIntervalPercent = pixelsPerTick / trackSize; } else { - this._tickIntervalPercent = this.tickInterval * this.step / (this.max - this.min); + this._tickIntervalPercent = (this.tickInterval * this.step) / (this.max - this.min); } } @@ -897,17 +943,6 @@ export class MatSlider extends _MatSliderMixinBase setDisabledState(isDisabled: boolean) { this.disabled = isDisabled; } - - static ngAcceptInputType_invert: BooleanInput; - static ngAcceptInputType_max: NumberInput; - static ngAcceptInputType_min: NumberInput; - static ngAcceptInputType_step: NumberInput; - static ngAcceptInputType_thumbLabel: BooleanInput; - static ngAcceptInputType_tickInterval: NumberInput; - static ngAcceptInputType_value: NumberInput; - static ngAcceptInputType_vertical: BooleanInput; - static ngAcceptInputType_disabled: BooleanInput; - static ngAcceptInputType_tabIndex: NumberInput; } /** Returns whether an event is a touch event. */ @@ -919,8 +954,46 @@ function isTouchEvent(event: MouseEvent | TouchEvent): event is TouchEvent { } /** Gets the coordinates of a touch or mouse event relative to the viewport. */ -function getPointerPositionOnPage(event: MouseEvent | TouchEvent) { - // `touches` will be empty for start/end events so we have to fall back to `changedTouches`. - const point = isTouchEvent(event) ? (event.touches[0] || event.changedTouches[0]) : event; - return {x: point.clientX, y: point.clientY}; +function getPointerPositionOnPage(event: MouseEvent | TouchEvent, id: number | undefined) { + let point: {clientX: number; clientY: number} | undefined; + + if (isTouchEvent(event)) { + // The `identifier` could be undefined if the browser doesn't support `TouchEvent.identifier`. + // If that's the case, attribute the first touch to all active sliders. This should still cover + // the most common case while only breaking multi-touch. + if (typeof id === 'number') { + point = findMatchingTouch(event.touches, id) || findMatchingTouch(event.changedTouches, id); + } else { + // `touches` will be empty for start/end events so we have to fall back to `changedTouches`. + point = event.touches[0] || event.changedTouches[0]; + } + } else { + point = event; + } + + return point ? {x: point.clientX, y: point.clientY} : undefined; +} + +/** Finds a `Touch` with a specific ID in a `TouchList`. */ +function findMatchingTouch(touches: TouchList, id: number): Touch | undefined { + for (let i = 0; i < touches.length; i++) { + if (touches[i].identifier === id) { + return touches[i]; + } + } + + return undefined; +} + +/** Gets the unique ID of a touch that matches a specific slider. */ +function getTouchIdForSlider(event: TouchEvent, sliderHost: HTMLElement): number | undefined { + for (let i = 0; i < event.touches.length; i++) { + const target = event.touches[i].target as HTMLElement; + + if (sliderHost === target || sliderHost.contains(target)) { + return event.touches[i].identifier; + } + } + + return undefined; } diff --git a/src/material/slider/testing/BUILD.bazel b/src/material/slider/testing/BUILD.bazel index 17fac3501f86..a0bcc1f00d09 100644 --- a/src/material/slider/testing/BUILD.bazel +++ b/src/material/slider/testing/BUILD.bazel @@ -8,7 +8,6 @@ ts_library( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material/slider/testing", deps = [ "//src/cdk/coercion", "//src/cdk/testing", @@ -20,29 +19,18 @@ filegroup( srcs = glob(["**/*.ts"]), ) -ng_test_library( - name = "harness_tests_lib", - srcs = ["shared.spec.ts"], - deps = [ - ":testing", - "//src/cdk/testing", - "//src/cdk/testing/testbed", - "//src/material/slider", - "@npm//@angular/forms", - "@npm//@angular/platform-browser", - ], -) - ng_test_library( name = "unit_tests_lib", srcs = glob( ["**/*.spec.ts"], - exclude = ["shared.spec.ts"], ), deps = [ - ":harness_tests_lib", ":testing", + "//src/cdk/testing", + "//src/cdk/testing/testbed", "//src/material/slider", + "@npm//@angular/forms", + "@npm//@angular/platform-browser", ], ) diff --git a/src/material/slider/testing/shared.spec.ts b/src/material/slider/testing/shared.spec.ts deleted file mode 100644 index 080f873ddf20..000000000000 --- a/src/material/slider/testing/shared.spec.ts +++ /dev/null @@ -1,202 +0,0 @@ -import {HarnessLoader} from '@angular/cdk/testing'; -import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; -import {Component, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; -import {ComponentFixture, TestBed} from '@angular/core/testing'; -import {MatSliderModule} from '@angular/material/slider'; -import {MatSliderHarness} from '@angular/material/slider/testing/slider-harness'; - -/** Shared tests to run on both the original and MDC-based sliders. */ -export function runHarnessTests( - sliderModule: typeof MatSliderModule, - sliderHarness: typeof MatSliderHarness, - options: {supportsVertical: boolean, supportsInvert: boolean}) { - let fixture: ComponentFixture; - let loader: HarnessLoader; - - beforeEach(async () => { - await TestBed - .configureTestingModule({ - imports: [sliderModule], - declarations: [SliderHarnessTest], - // Use custom element schema since some inputs (like vertical or invert) do not - // exist in the MDC implementation of the slider. Though we still want to re-use - // the same test component. - schemas: [CUSTOM_ELEMENTS_SCHEMA], - }) - .compileComponents(); - - fixture = TestBed.createComponent(SliderHarnessTest); - fixture.detectChanges(); - loader = TestbedHarnessEnvironment.loader(fixture); - }); - - it('should load all slider harnesses', async () => { - const sliders = await loader.getAllHarnesses(sliderHarness); - expect(sliders.length).toBe(3); - }); - - it('should load slider harness by id', async () => { - const sliders = await loader.getAllHarnesses(sliderHarness.with({selector: '#my-slider'})); - expect(sliders.length).toBe(1); - }); - - it('should get id of slider', async () => { - const sliders = await loader.getAllHarnesses(sliderHarness); - expect(await sliders[0].getId()).toBe(null); - expect(await sliders[1].getId()).toBe('my-slider'); - expect(await sliders[2].getId()).toBe(null); - }); - - it('should get value of slider', async () => { - const sliders = await loader.getAllHarnesses(sliderHarness); - expect(await sliders[0].getValue()).toBe(50); - expect(await sliders[1].getValue()).toBe(0); - expect(await sliders[2].getValue()).toBe(225); - }); - - it('should get percentage of slider', async () => { - const sliders = await loader.getAllHarnesses(sliderHarness); - expect(await sliders[0].getPercentage()).toBe(0.5); - expect(await sliders[1].getPercentage()).toBe(0); - expect(await sliders[2].getPercentage()).toBe(0.5); - }); - - it('should get max value of slider', async () => { - const sliders = await loader.getAllHarnesses(sliderHarness); - expect(await sliders[0].getMaxValue()).toBe(100); - expect(await sliders[1].getMaxValue()).toBe(100); - expect(await sliders[2].getMaxValue()).toBe(250); - }); - - it('should get min value of slider', async () => { - const sliders = await loader.getAllHarnesses(sliderHarness); - expect(await sliders[0].getMinValue()).toBe(0); - expect(await sliders[1].getMinValue()).toBe(0); - expect(await sliders[2].getMinValue()).toBe(200); - }); - - it('should get display value of slider', async () => { - const sliders = await loader.getAllHarnesses(sliderHarness); - expect(await sliders[0].getDisplayValue()).toBe(null); - expect(await sliders[1].getDisplayValue()).toBe('Null'); - expect(await sliders[2].getDisplayValue()).toBe('#225'); - }); - - it('should get orientation of slider', async () => { - const sliders = await loader.getAllHarnesses(sliderHarness); - expect(await sliders[0].getOrientation()).toBe('horizontal'); - expect(await sliders[1].getOrientation()).toBe('horizontal'); - expect(await sliders[2].getOrientation()).toBe(options.supportsVertical ? - 'vertical' : 'horizontal'); - }); - - it('should be able to focus slider', async () => { - // the first slider is disabled. - const slider = (await loader.getAllHarnesses(sliderHarness))[1]; - expect(await slider.isFocused()).toBe(false); - await slider.focus(); - expect(await slider.isFocused()).toBe(true); - }); - - it('should be able to blur slider', async () => { - // the first slider is disabled. - const slider = (await loader.getAllHarnesses(sliderHarness))[1]; - expect(await slider.isFocused()).toBe(false); - await slider.focus(); - expect(await slider.isFocused()).toBe(true); - await slider.blur(); - expect(await slider.isFocused()).toBe(false); - }); - - it('should be able to set value of slider', async () => { - const sliders = await loader.getAllHarnesses(sliderHarness); - expect(await sliders[1].getValue()).toBe(0); - expect(await sliders[2].getValue()).toBe(225); - - await sliders[1].setValue(33); - await sliders[2].setValue(300); - - expect(await sliders[1].getValue()).toBe(33); - // value should be clamped to the maximum. - expect(await sliders[2].getValue()).toBe(250); - }); - - it('should be able to set value of slider in rtl', async () => { - const sliders = await loader.getAllHarnesses(sliderHarness); - expect(await sliders[1].getValue()).toBe(0); - expect(await sliders[2].getValue()).toBe(225); - - // should not retrieve incorrect values in case slider is inverted - // due to RTL page layout. - fixture.componentInstance.dir = 'rtl'; - fixture.detectChanges(); - - await sliders[1].setValue(80); - expect(await sliders[1].getValue()).toBe(80); - }); - - it('should get disabled state of slider', async () => { - const sliders = await loader.getAllHarnesses(sliderHarness); - expect(await sliders[0].isDisabled()).toBe(true); - expect(await sliders[1].isDisabled()).toBe(false); - expect(await sliders[2].isDisabled()).toBe(false); - }); - - if (options.supportsInvert) { - it('should be able to set value of inverted slider', async () => { - const sliders = await loader.getAllHarnesses(sliderHarness); - expect(await sliders[1].getValue()).toBe(0); - expect(await sliders[2].getValue()).toBe(225); - - fixture.componentInstance.invertSliders = true; - fixture.detectChanges(); - - await sliders[1].setValue(75); - await sliders[2].setValue(210); - - expect(await sliders[1].getValue()).toBe(75); - expect(await sliders[2].getValue()).toBe(210); - }); - - it('should be able to set value of inverted slider in rtl', async () => { - const sliders = await loader.getAllHarnesses(sliderHarness); - expect(await sliders[1].getValue()).toBe(0); - expect(await sliders[2].getValue()).toBe(225); - - fixture.componentInstance.invertSliders = true; - fixture.componentInstance.dir = 'rtl'; - fixture.detectChanges(); - - await sliders[1].setValue(75); - await sliders[2].setValue(210); - - expect(await sliders[1].getValue()).toBe(75); - expect(await sliders[2].getValue()).toBe(210); - }); - } -} - -@Component({ - template: ` - -
- -
- - - `, -}) -class SliderHarnessTest { - sliderId = 'my-slider'; - invertSliders = false; - dir = 'ltr'; - - displayFn(value: number|null) { - if (!value) { - return 'Null'; - } - return `#${value}`; - } -} diff --git a/src/material/slider/testing/slider-harness.spec.ts b/src/material/slider/testing/slider-harness.spec.ts index b11832e8c142..01f568077b5f 100644 --- a/src/material/slider/testing/slider-harness.spec.ts +++ b/src/material/slider/testing/slider-harness.spec.ts @@ -1,10 +1,189 @@ +import {HarnessLoader} from '@angular/cdk/testing'; +import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; +import {Component} from '@angular/core'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; import {MatSliderModule} from '@angular/material/slider'; -import {runHarnessTests} from '@angular/material/slider/testing/shared.spec'; -import {MatSliderHarness} from './slider-harness'; +import {MatSliderHarness} from '@angular/material/slider/testing/slider-harness'; describe('Non-MDC-based MatSliderHarness', () => { - runHarnessTests(MatSliderModule, MatSliderHarness, { - supportsInvert: true, - supportsVertical: true, + let fixture: ComponentFixture; + let loader: HarnessLoader; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [MatSliderModule], + declarations: [SliderHarnessTest], + }).compileComponents(); + + fixture = TestBed.createComponent(SliderHarnessTest); + fixture.detectChanges(); + loader = TestbedHarnessEnvironment.loader(fixture); + }); + + it('should load all slider harnesses', async () => { + const sliders = await loader.getAllHarnesses(MatSliderHarness); + expect(sliders.length).toBe(3); + }); + + it('should load slider harness by id', async () => { + const sliders = await loader.getAllHarnesses(MatSliderHarness.with({selector: '#my-slider'})); + expect(sliders.length).toBe(1); + }); + + it('should get id of slider', async () => { + const sliders = await loader.getAllHarnesses(MatSliderHarness); + expect(await sliders[0].getId()).toBe(null); + expect(await sliders[1].getId()).toBe('my-slider'); + expect(await sliders[2].getId()).toBe(null); + }); + + it('should get value of slider', async () => { + const sliders = await loader.getAllHarnesses(MatSliderHarness); + expect(await sliders[0].getValue()).toBe(50); + expect(await sliders[1].getValue()).toBe(0); + expect(await sliders[2].getValue()).toBe(225); + }); + + it('should get percentage of slider', async () => { + const sliders = await loader.getAllHarnesses(MatSliderHarness); + expect(await sliders[0].getPercentage()).toBe(0.5); + expect(await sliders[1].getPercentage()).toBe(0); + expect(await sliders[2].getPercentage()).toBe(0.5); + }); + + it('should get max value of slider', async () => { + const sliders = await loader.getAllHarnesses(MatSliderHarness); + expect(await sliders[0].getMaxValue()).toBe(100); + expect(await sliders[1].getMaxValue()).toBe(100); + expect(await sliders[2].getMaxValue()).toBe(250); + }); + + it('should get min value of slider', async () => { + const sliders = await loader.getAllHarnesses(MatSliderHarness); + expect(await sliders[0].getMinValue()).toBe(0); + expect(await sliders[1].getMinValue()).toBe(0); + expect(await sliders[2].getMinValue()).toBe(200); + }); + + it('should get display value of slider', async () => { + const sliders = await loader.getAllHarnesses(MatSliderHarness); + expect(await sliders[0].getDisplayValue()).toBe(null); + expect(await sliders[1].getDisplayValue()).toBe('Null'); + expect(await sliders[2].getDisplayValue()).toBe('#225'); + }); + + it('should get orientation of slider', async () => { + const sliders = await loader.getAllHarnesses(MatSliderHarness); + expect(await sliders[0].getOrientation()).toBe('horizontal'); + expect(await sliders[1].getOrientation()).toBe('horizontal'); + expect(await sliders[2].getOrientation()).toBe('vertical'); + }); + + it('should be able to focus slider', async () => { + // the first slider is disabled. + const slider = (await loader.getAllHarnesses(MatSliderHarness))[1]; + expect(await slider.isFocused()).toBe(false); + await slider.focus(); + expect(await slider.isFocused()).toBe(true); + }); + + it('should be able to blur slider', async () => { + // the first slider is disabled. + const slider = (await loader.getAllHarnesses(MatSliderHarness))[1]; + expect(await slider.isFocused()).toBe(false); + await slider.focus(); + expect(await slider.isFocused()).toBe(true); + await slider.blur(); + expect(await slider.isFocused()).toBe(false); + }); + + it('should be able to set value of slider', async () => { + const sliders = await loader.getAllHarnesses(MatSliderHarness); + expect(await sliders[1].getValue()).toBe(0); + expect(await sliders[2].getValue()).toBe(225); + + await sliders[1].setValue(33); + await sliders[2].setValue(300); + + expect(await sliders[1].getValue()).toBe(33); + // value should be clamped to the maximum. + expect(await sliders[2].getValue()).toBe(250); + }); + + it('should be able to set value of slider in rtl', async () => { + const sliders = await loader.getAllHarnesses(MatSliderHarness); + expect(await sliders[1].getValue()).toBe(0); + expect(await sliders[2].getValue()).toBe(225); + + // should not retrieve incorrect values in case slider is inverted + // due to RTL page layout. + fixture.componentInstance.dir = 'rtl'; + fixture.detectChanges(); + + await sliders[1].setValue(80); + expect(await sliders[1].getValue()).toBe(80); + }); + + it('should get disabled state of slider', async () => { + const sliders = await loader.getAllHarnesses(MatSliderHarness); + expect(await sliders[0].isDisabled()).toBe(true); + expect(await sliders[1].isDisabled()).toBe(false); + expect(await sliders[2].isDisabled()).toBe(false); + }); + + it('should be able to set value of inverted slider', async () => { + const sliders = await loader.getAllHarnesses(MatSliderHarness); + expect(await sliders[1].getValue()).toBe(0); + expect(await sliders[2].getValue()).toBe(225); + + fixture.componentInstance.invertSliders = true; + fixture.detectChanges(); + + await sliders[1].setValue(75); + await sliders[2].setValue(210); + + expect(await sliders[1].getValue()).toBe(75); + expect(await sliders[2].getValue()).toBe(210); + }); + + it('should be able to set value of inverted slider in rtl', async () => { + const sliders = await loader.getAllHarnesses(MatSliderHarness); + expect(await sliders[1].getValue()).toBe(0); + expect(await sliders[2].getValue()).toBe(225); + + fixture.componentInstance.invertSliders = true; + fixture.componentInstance.dir = 'rtl'; + fixture.detectChanges(); + + await sliders[1].setValue(75); + await sliders[2].setValue(210); + + expect(await sliders[1].getValue()).toBe(75); + expect(await sliders[2].getValue()).toBe(210); }); }); + +@Component({ + template: ` + +
+ +
+ + + `, +}) +class SliderHarnessTest { + sliderId = 'my-slider'; + invertSliders = false; + dir = 'ltr'; + + displayFn(value: number | null) { + if (!value) { + return 'Null'; + } + return `#${value}`; + } +} diff --git a/src/material/slider/testing/slider-harness.ts b/src/material/slider/testing/slider-harness.ts index 6294204c2bd5..67228145d64c 100644 --- a/src/material/slider/testing/slider-harness.ts +++ b/src/material/slider/testing/slider-harness.ts @@ -29,7 +29,7 @@ export class MatSliderHarness extends ComponentHarness { private _wrapper = this.locatorFor('.mat-slider-wrapper'); /** Gets the slider's id. */ - async getId(): Promise { + async getId(): Promise { const id = await (await this.host()).getAttribute('id'); // In case no id has been specified, the "id" property always returns // an empty string. To make this method more explicit, we return null. @@ -40,7 +40,7 @@ export class MatSliderHarness extends ComponentHarness { * Gets the current display value of the slider. Returns a null promise if the thumb label is * disabled. */ - async getDisplayValue(): Promise { + async getDisplayValue(): Promise { const [host, textLabel] = await parallel(() => [this.host(), this._textLabel()]); if (await host.hasClass('mat-slider-thumb-label-showing')) { return textLabel.text(); @@ -75,7 +75,7 @@ export class MatSliderHarness extends ComponentHarness { } /** Gets the orientation of the slider. */ - async getOrientation(): Promise<'horizontal'|'vertical'> { + async getOrientation(): Promise<'horizontal' | 'vertical'> { // "aria-orientation" will always be set to either "horizontal" or "vertical". return (await this.host()).getAttribute('aria-orientation') as any; } @@ -89,8 +89,11 @@ export class MatSliderHarness extends ComponentHarness { * select the given value or expand the slider's size for a better user experience. */ async setValue(value: number): Promise { - const [sliderEl, wrapperEl, orientation] = - await parallel(() => [this.host(), this._wrapper(), this.getOrientation()]); + const [sliderEl, wrapperEl, orientation] = await parallel(() => [ + this.host(), + this._wrapper(), + this.getOrientation(), + ]); let percentage = await this._calculatePercentage(value); const {height, width} = await wrapperEl.getDimensions(); const isVertical = orientation === 'vertical'; diff --git a/src/material/snack-bar/BUILD.bazel b/src/material/snack-bar/BUILD.bazel index fe9d3b934f17..9ac99696bfde 100644 --- a/src/material/snack-bar/BUILD.bazel +++ b/src/material/snack-bar/BUILD.bazel @@ -20,7 +20,6 @@ ng_module( ":snack-bar-container.css", ":simple-snack-bar.css", ] + glob(["**/*.html"]), - module_name = "@angular/material/snack-bar", deps = [ "//src:dev_mode_types", "//src/cdk/a11y", @@ -52,7 +51,6 @@ sass_binary( sass_binary( name = "simple_snack_bar_scss", src = "simple-snack-bar.scss", - deps = ["//src/material/core:core_scss_lib"], ) ng_test_library( @@ -65,6 +63,7 @@ ng_test_library( ":snack-bar", "//src/cdk/a11y", "//src/cdk/overlay", + "//src/cdk/platform", "@npm//@angular/common", "@npm//@angular/platform-browser", ], diff --git a/src/material/snack-bar/_snack-bar-legacy-index.scss b/src/material/snack-bar/_snack-bar-legacy-index.scss new file mode 100644 index 000000000000..5882682b0b48 --- /dev/null +++ b/src/material/snack-bar/_snack-bar-legacy-index.scss @@ -0,0 +1,2 @@ +@forward 'snack-bar-theme' hide color, theme, typography; +@forward 'snack-bar-theme' as mat-snack-bar-* hide mat-snack-bar-density; diff --git a/src/material/snack-bar/_snack-bar-theme.import.scss b/src/material/snack-bar/_snack-bar-theme.import.scss new file mode 100644 index 000000000000..cb499e497743 --- /dev/null +++ b/src/material/snack-bar/_snack-bar-theme.import.scss @@ -0,0 +1,11 @@ +@forward '../core/theming/palette.import'; +@forward '../core/theming/theming.import'; +@forward '../core/style/private.import'; +@forward '../core/typography/typography-utils.import'; +@forward 'snack-bar-theme' hide color, theme, typography; +@forward 'snack-bar-theme' as mat-snack-bar-* hide mat-snack-bar-density; + +@import '../core/typography/typography-utils'; +@import '../core/theming/theming'; +@import '../core/theming/palette'; +@import '../core/style/private'; diff --git a/src/material/snack-bar/_snack-bar-theme.scss b/src/material/snack-bar/_snack-bar-theme.scss index 7ead10607829..fabb1343d932 100644 --- a/src/material/snack-bar/_snack-bar-theme.scss +++ b/src/material/snack-bar/_snack-bar-theme.scss @@ -1,33 +1,36 @@ -@import '../core/typography/typography-utils'; -@import '../core/theming/theming'; -@import '../core/theming/palette'; -@import '../core/style/private'; +@use 'sass:map'; +@use '../core/typography/typography'; +@use '../core/typography/typography-utils'; +@use '../core/theming/theming'; +@use '../core/theming/palette'; +@use '../core/style/private'; -@mixin mat-snack-bar-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $is-dark-theme: map-get($config, is-dark); - $accent: map-get($config, accent); +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $is-dark-theme: map.get($config, is-dark); + $accent: map.get($config, accent); .mat-snack-bar-container { // Use the primary text on the dark theme, even though the lighter one uses // a secondary, because the contrast on the light primary text is poor. - color: if($is-dark-theme, $dark-primary-text, $light-secondary-text); - background: if($is-dark-theme, map-get($mat-grey, 50), #323232); + color: if($is-dark-theme, palette.$dark-primary-text, palette.$light-secondary-text); + background: if($is-dark-theme, map.get(palette.$grey-palette, 50), #323232); - @include mat-private-theme-elevation(6, $config); + @include private.private-theme-elevation(6, $config); } .mat-simple-snackbar-action { - color: if($is-dark-theme, inherit, mat-color($accent, text)); + color: if($is-dark-theme, inherit, theming.get-color-from-palette($accent, text)); } } -@mixin mat-snack-bar-typography($config-or-theme) { - $config: mat-get-typography-config($config-or-theme); +@mixin typography($config-or-theme) { + $config: typography.private-typography-to-2014-config( + theming.get-typography-config($config-or-theme)); .mat-simple-snackbar { font: { - family: mat-font-family($config, body-1); - size: mat-font-size($config, body-1); + family: typography-utils.font-family($config, body-1); + size: typography-utils.font-size($config, body-1); } } @@ -36,28 +39,28 @@ font: { family: inherit; size: inherit; - weight: mat-font-weight($config, button); + weight: typography-utils.font-weight($config, button); } } } -@mixin _mat-snack-bar-density($config-or-theme) {} +@mixin _density($config-or-theme) {} -@mixin mat-snack-bar-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-snack-bar') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-snack-bar') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); @if $color != null { - @include mat-snack-bar-color($color); + @include color($color); } @if $density != null { - @include _mat-snack-bar-density($density); + @include _density($density); } @if $typography != null { - @include mat-snack-bar-typography($typography); + @include typography($typography); } } } diff --git a/src/material/snack-bar/simple-snack-bar.scss b/src/material/snack-bar/simple-snack-bar.scss index bbfb91fdf58d..50188497237a 100644 --- a/src/material/snack-bar/simple-snack-bar.scss +++ b/src/material/snack-bar/simple-snack-bar.scss @@ -1,35 +1,32 @@ -@import '../core/style/variables'; -@import '../core/style/button-common'; -@import '../core/style/list-common'; +@use 'sass:math'; -$mat-snack-bar-button-horizontal-margin: 8px !default; -$mat-snack-bar-button-height: 36px !default; -$mat-snack-bar-line-height: 20px !default; +$button-horizontal-margin: 8px !default; +$button-height: 36px !default; +$line-height: 20px !default; // Button vertical margin is used to ensure that a button height of 36px, when the containing // space falls below 36px. -$mat-snack-bar-button-vertical-margin: - -(($mat-snack-bar-button-height - $mat-snack-bar-line-height) / 2); +$button-vertical-margin: -(math.div($button-height - $line-height, 2)); .mat-simple-snackbar { display: flex; justify-content: space-between; align-items: center; - line-height: $mat-snack-bar-line-height; + line-height: $line-height; opacity: 1; } .mat-simple-snackbar-action { flex-shrink: 0; - margin: $mat-snack-bar-button-vertical-margin $mat-snack-bar-button-horizontal-margin * -1 - $mat-snack-bar-button-vertical-margin $mat-snack-bar-button-horizontal-margin; + margin: $button-vertical-margin $button-horizontal-margin * -1 + $button-vertical-margin $button-horizontal-margin; button { - max-height: $mat-snack-bar-button-height; + max-height: $button-height; min-width: 0; } [dir='rtl'] & { - margin-left: -$mat-snack-bar-button-horizontal-margin; - margin-right: $mat-snack-bar-button-horizontal-margin; + margin-left: -$button-horizontal-margin; + margin-right: $button-horizontal-margin; } } diff --git a/src/material/snack-bar/simple-snack-bar.ts b/src/material/snack-bar/simple-snack-bar.ts index 7b2e9fb6466f..e2dbef54f863 100644 --- a/src/material/snack-bar/simple-snack-bar.ts +++ b/src/material/snack-bar/simple-snack-bar.ts @@ -10,12 +10,11 @@ import {ChangeDetectionStrategy, Component, Inject, ViewEncapsulation} from '@an import {MAT_SNACK_BAR_DATA} from './snack-bar-config'; import {MatSnackBarRef} from './snack-bar-ref'; - /** * Interface for a simple snack bar component that has a message and a single action. */ export interface TextOnlySnackBar { - data: {message: string, action: string}; + data: {message: string; action: string}; snackBarRef: MatSnackBarRef; action: () => void; hasAction: boolean; @@ -33,15 +32,16 @@ export interface TextOnlySnackBar { changeDetection: ChangeDetectionStrategy.OnPush, host: { 'class': 'mat-simple-snackbar', - } + }, }) export class SimpleSnackBar implements TextOnlySnackBar { /** Data that was injected into the snack bar. */ - data: {message: string, action: string}; + data: {message: string; action: string}; constructor( public snackBarRef: MatSnackBarRef, - @Inject(MAT_SNACK_BAR_DATA) data: any) { + @Inject(MAT_SNACK_BAR_DATA) data: any, + ) { this.data = data; } diff --git a/src/material/snack-bar/snack-bar-animations.ts b/src/material/snack-bar/snack-bar-animations.ts index 2c6295d58efd..1f4cef7c138c 100644 --- a/src/material/snack-bar/snack-bar-animations.ts +++ b/src/material/snack-bar/snack-bar-animations.ts @@ -23,17 +23,29 @@ export const matSnackBarAnimations: { } = { /** Animation that shows and hides a snack bar. */ snackBarState: trigger('state', [ - state('void, hidden', style({ - transform: 'scale(0.8)', - opacity: 0, - })), - state('visible', style({ - transform: 'scale(1)', - opacity: 1, - })), + state( + 'void, hidden', + style({ + transform: 'scale(0.8)', + opacity: 0, + }), + ), + state( + 'visible', + style({ + transform: 'scale(1)', + opacity: 1, + }), + ), transition('* => visible', animate('150ms cubic-bezier(0, 0, 0.2, 1)')), - transition('* => void, * => hidden', animate('75ms cubic-bezier(0.4, 0.0, 1, 1)', style({ - opacity: 0 - }))), - ]) + transition( + '* => void, * => hidden', + animate( + '75ms cubic-bezier(0.4, 0.0, 1, 1)', + style({ + opacity: 0, + }), + ), + ), + ]), }; diff --git a/src/material/snack-bar/snack-bar-container.html b/src/material/snack-bar/snack-bar-container.html index 32a293bba0c7..334df5db9bdb 100644 --- a/src/material/snack-bar/snack-bar-container.html +++ b/src/material/snack-bar/snack-bar-container.html @@ -1,7 +1,7 @@ - + -
+
diff --git a/src/material/snack-bar/snack-bar-container.scss b/src/material/snack-bar/snack-bar-container.scss index 6e3380b46bae..e8cfc313b3ff 100644 --- a/src/material/snack-bar/snack-bar-container.scss +++ b/src/material/snack-bar/snack-bar-container.scss @@ -1,38 +1,36 @@ -@import '../../cdk/a11y/a11y'; +@use '../../cdk/a11y'; -$mat-snack-bar-padding: 14px 16px !default; -$mat-snack-bar-min-height: 48px !default; -$mat-snack-bar-min-width: 344px !default; -$mat-snack-bar-max-width: 33vw !default; -$mat-snack-bar-spacing-margin: 24px !default; -$mat-snack-bar-spacing-margin-handset: 8px !default; +$padding: 14px 16px !default; +$min-height: 48px !default; +$min-width: 344px !default; +$max-width: 33vw !default; +$spacing-margin: 24px !default; +$spacing-margin-handset: 8px !default; .mat-snack-bar-container { border-radius: 4px; box-sizing: border-box; display: block; - margin: $mat-snack-bar-spacing-margin; - max-width: $mat-snack-bar-max-width; - min-width: $mat-snack-bar-min-width; - padding: $mat-snack-bar-padding; - min-height: $mat-snack-bar-min-height; + margin: $spacing-margin; + max-width: $max-width; + min-width: $min-width; + padding: $padding; + min-height: $min-height; transform-origin: center; - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { border: solid 1px; } } -/** - * The mat-snack-bar-handset class will be applied to the overlay - * element causing styling to both it and the snack bar container. - */ +// The mat-snack-bar-handset class will be applied to the overlay +// element causing styling to both it and the snack bar container. .mat-snack-bar-handset { width: 100%; .mat-snack-bar-container { - margin: $mat-snack-bar-spacing-margin-handset; + margin: $spacing-margin-handset; max-width: 100%; min-width: 0; width: 100%; diff --git a/src/material/snack-bar/snack-bar-container.ts b/src/material/snack-bar/snack-bar-container.ts index 9116587a7b37..2bf4a2d901d5 100644 --- a/src/material/snack-bar/snack-bar-container.ts +++ b/src/material/snack-bar/snack-bar-container.ts @@ -39,9 +39,9 @@ import {MatSnackBarConfig} from './snack-bar-config'; */ export interface _SnackBarContainer { snackBarConfig: MatSnackBarConfig; - _onAnnounce: Subject; - _onExit: Subject; - _onEnter: Subject; + readonly _onAnnounce: Subject; + readonly _onExit: Subject; + readonly _onEnter: Subject; enter: () => void; exit: () => Observable; attachTemplatePortal: (portal: TemplatePortal) => EmbeddedViewRef; @@ -66,11 +66,13 @@ export interface _SnackBarContainer { host: { 'class': 'mat-snack-bar-container', '[@state]': '_animationState', - '(@state.done)': 'onAnimationEnd($event)' + '(@state.done)': 'onAnimationEnd($event)', }, }) -export class MatSnackBarContainer extends BasePortalOutlet - implements OnDestroy, _SnackBarContainer { +export class MatSnackBarContainer + extends BasePortalOutlet + implements OnDestroy, _SnackBarContainer +{ /** The number of milliseconds to wait before announcing the snack bar's content. */ private readonly _announceDelay: number = 150; @@ -98,14 +100,20 @@ export class MatSnackBarContainer extends BasePortalOutlet /** aria-live value for the live region. */ _live: AriaLivePoliteness; + /** + * Role of the live region. This is only for Firefox as there is a known issue where Firefox + + * JAWS does not read out aria-live message. + */ + _role?: 'status' | 'alert'; + constructor( private _ngZone: NgZone, private _elementRef: ElementRef, private _changeDetectorRef: ChangeDetectorRef, private _platform: Platform, /** The snack bar configuration. */ - public snackBarConfig: MatSnackBarConfig) { - + public snackBarConfig: MatSnackBarConfig, + ) { super(); // Use aria-live rather than a live role like 'alert' or 'status' @@ -117,6 +125,17 @@ export class MatSnackBarContainer extends BasePortalOutlet } else { this._live = 'polite'; } + + // Only set role for Firefox. Set role based on aria-live because setting role="alert" implies + // aria-live="assertive" which may cause issues if aria-live is set to "polite" above. + if (this._platform.FIREFOX) { + if (this._live === 'polite') { + this._role = 'status'; + } + if (this._live === 'assertive') { + this._role = 'alert'; + } + } } /** Attach a component portal as content to this snack bar container. */ @@ -138,11 +157,11 @@ export class MatSnackBarContainer extends BasePortalOutlet * @deprecated To be turned into a method. * @breaking-change 10.0.0 */ - attachDomPortal = (portal: DomPortal) => { + override attachDomPortal = (portal: DomPortal) => { this._assertNotAttached(); this._applySnackBarClasses(); return this._portalOutlet.attachDomPortal(portal); - } + }; /** Handle end of animations, updating the state of the snackbar. */ onAnimationEnd(event: AnimationEvent) { @@ -254,9 +273,11 @@ export class MatSnackBarContainer extends BasePortalOutlet // If an element in the snack bar content is focused before being moved // track it and restore focus after moving to the live region. let focusedElement: HTMLElement | null = null; - if (this._platform.isBrowser && - document.activeElement instanceof HTMLElement && - inertElement.contains(document.activeElement)) { + if ( + this._platform.isBrowser && + document.activeElement instanceof HTMLElement && + inertElement.contains(document.activeElement) + ) { focusedElement = document.activeElement; } diff --git a/src/material/snack-bar/snack-bar-module.ts b/src/material/snack-bar/snack-bar-module.ts index eb2789b8321c..881c55389909 100644 --- a/src/material/snack-bar/snack-bar-module.ts +++ b/src/material/snack-bar/snack-bar-module.ts @@ -15,17 +15,9 @@ import {MatButtonModule} from '@angular/material/button'; import {SimpleSnackBar} from './simple-snack-bar'; import {MatSnackBarContainer} from './snack-bar-container'; - @NgModule({ - imports: [ - OverlayModule, - PortalModule, - CommonModule, - MatButtonModule, - MatCommonModule, - ], + imports: [OverlayModule, PortalModule, CommonModule, MatButtonModule, MatCommonModule], exports: [MatSnackBarContainer, MatCommonModule], declarations: [MatSnackBarContainer, SimpleSnackBar], - entryComponents: [MatSnackBarContainer, SimpleSnackBar], }) export class MatSnackBarModule {} diff --git a/src/material/snack-bar/snack-bar-ref.ts b/src/material/snack-bar/snack-bar-ref.ts index a25805494915..0d7de41d9706 100644 --- a/src/material/snack-bar/snack-bar-ref.ts +++ b/src/material/snack-bar/snack-bar-ref.ts @@ -10,7 +10,6 @@ import {OverlayRef} from '@angular/cdk/overlay'; import {Observable, Subject} from 'rxjs'; import {_SnackBarContainer} from './snack-bar-container'; - /** Event that is emitted when a snack bar is dismissed. */ export interface MatSnackBarDismiss { /** Whether the snack bar was dismissed using the action button. */ @@ -51,8 +50,7 @@ export class MatSnackBarRef { /** Whether the snack bar was dismissed using the action button. */ private _dismissedByAction = false; - constructor(containerInstance: _SnackBarContainer, - private _overlayRef: OverlayRef) { + constructor(containerInstance: _SnackBarContainer, private _overlayRef: OverlayRef) { this.containerInstance = containerInstance; // Dismiss snackbar on action. this.onAction().subscribe(() => this.dismiss()); @@ -74,9 +72,9 @@ export class MatSnackBarRef { this._onAction.next(); this._onAction.complete(); } + clearTimeout(this._durationTimeoutId); } - /** * Marks the snackbar action clicked. * @deprecated Use `dismissWithAction` instead. diff --git a/src/material/snack-bar/snack-bar.md b/src/material/snack-bar/snack-bar.md index 495d3453a609..ab6a73b6a830 100644 --- a/src/material/snack-bar/snack-bar.md +++ b/src/material/snack-bar/snack-bar.md @@ -2,8 +2,8 @@ -### Opening a snack-bar -A snack-bar can contain either a string message or a given component. +### Opening a snackbar +A snackbar can contain either a string message or a given component. ```ts // Simple message. let snackBarRef = snackBar.open('Message archived'); @@ -11,45 +11,45 @@ let snackBarRef = snackBar.open('Message archived'); // Simple message with an action. let snackBarRef = snackBar.open('Message archived', 'Undo'); -// Load the given component into the snack-bar. +// Load the given component into the snackbar. let snackBarRef = snackbar.openFromComponent(MessageArchivedComponent); ``` -In either case, a `MatSnackBarRef` is returned. This can be used to dismiss the snack-bar or to -receive notification of when the snack-bar is dismissed. For simple messages with an action, the +In either case, a `MatSnackBarRef` is returned. This can be used to dismiss the snackbar or to +receive notification of when the snackbar is dismissed. For simple messages with an action, the `MatSnackBarRef` exposes an observable for when the action is triggered. -If you want to close a custom snack-bar that was opened via `openFromComponent`, from within the +If you want to close a custom snackbar that was opened via `openFromComponent`, from within the component itself, you can inject the `MatSnackBarRef`. ```ts snackBarRef.afterDismissed().subscribe(() => { - console.log('The snack-bar was dismissed'); + console.log('The snackbar was dismissed'); }); snackBarRef.onAction().subscribe(() => { - console.log('The snack-bar action was triggered!'); + console.log('The snackbar action was triggered!'); }); snackBarRef.dismiss(); ``` ### Dismissal -A snack-bar can be dismissed manually by calling the `dismiss` method on the `MatSnackBarRef` +A snackbar can be dismissed manually by calling the `dismiss` method on the `MatSnackBarRef` returned from the call to `open`. -Only one snack-bar can ever be opened at one time. If a new snackbar is opened while a previous +Only one snackbar can ever be opened at one time. If a new snackbar is opened while a previous message is still showing, the older message will be automatically dismissed. -A snack-bar can also be given a duration via the optional configuration object: +A snackbar can also be given a duration via the optional configuration object: ```ts snackbar.open('Message archived', 'Undo', { duration: 3000 }); ``` -### Sharing data with a custom snack-bar -You can share data with the custom snack-bar, that you opened via the `openFromComponent` method, +### Sharing data with a custom snackbar +You can share data with the custom snackbar, that you opened via the `openFromComponent` method, by passing it through the `data` property. ```ts @@ -65,7 +65,7 @@ import {Component, Inject} from '@angular/core'; import {MAT_SNACK_BAR_DATA} from '@angular/material/snack-bar'; @Component({ - selector: 'your-snack-bar', + selector: 'your-snackbar', template: 'passed in {{ data }}', }) export class MessageArchivedComponent { @@ -86,20 +86,19 @@ If you want to override the default snack bar options, you can do so using the ``` ### Accessibility -Snack-bar messages are announced via an `aria-live` region. By default, the `polite` setting is -used. While `polite` is recommended, this can be customized by setting the `politeness` property of -the `MatSnackBarConfig`. - -Focus is not, and should not be, moved to the snack-bar element. Moving the focus would be -disruptive to a user in the middle of a workflow. It is recommended that, for any action offered -in the snack-bar, the application offers the user an alternative way to perform the action. -Alternative interactions are typically keyboard shortcuts or menu options. When the action is -performed in this way, the snack-bar should be dismissed. - -Snack-bars that have an action available should not be given a `duration`, as to accommodate -screen-reader users that want to navigate to the snack-bar element to activate the action. If the -user has manually moved their focus within the snackbar, focus should be placed somewhere sensible -based on the application context when the snack-bar is dismissed. - -Don't use "Dismiss" as a snack-bar-action, instead preferring to use a `duration` when there is -no additional action associated with the notification. + +`MatSnackBar` announces messages via an `aria-live` region. While announcements use the `polite` +setting by default, you can customize this by setting the `politeness` property of +`MatSnackBarConfig`. + +`MatSnackBar` does not move focus to the snackbar element. Moving focus like this would disrupt +users in the middle of a workflow. For any action offered in the snackbar, your application should +provide an alternative way to perform the action. Alternative interactions are typically keyboard +shortcuts or menu options. You should dismiss the snackbar once the user performs its corresponding +action. A snackbar can contain a single action with an additional optional "dismiss" or "cancel" +action. + +Avoid setting a `duration` for snackbars that have an action available, as screen reader users may +want to navigate to the snackbar element to activate the action. If the user has manually moved +their focus within the snackbar, you should return focus somewhere that makes sense in the context +of the user's workflow. diff --git a/src/material/snack-bar/snack-bar.spec.ts b/src/material/snack-bar/snack-bar.spec.ts index bb59a7728584..d1dc01f64606 100644 --- a/src/material/snack-bar/snack-bar.spec.ts +++ b/src/material/snack-bar/snack-bar.spec.ts @@ -5,7 +5,6 @@ import { Component, Directive, Inject, - NgModule, TemplateRef, ViewChild, ViewContainerRef, @@ -22,11 +21,11 @@ import { MatSnackBarRef, SimpleSnackBar, } from './index'; +import {Platform} from '@angular/cdk/platform'; describe('MatSnackBar', () => { let snackBar: MatSnackBar; let liveAnnouncer: LiveAnnouncer; - let overlayContainer: OverlayContainer; let overlayContainerElement: HTMLElement; let testViewContainerRef: ViewContainerRef; @@ -39,22 +38,23 @@ describe('MatSnackBar', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports: [MatSnackBarModule, SnackBarTestModule, NoopAnimationsModule], + imports: [MatSnackBarModule, CommonModule, NoopAnimationsModule], + declarations: [ + ComponentWithChildViewContainer, + BurritosNotification, + DirectiveWithViewContainer, + ], }).compileComponents(); })); - beforeEach(inject([MatSnackBar, LiveAnnouncer, OverlayContainer], + beforeEach(inject( + [MatSnackBar, LiveAnnouncer, OverlayContainer], (sb: MatSnackBar, la: LiveAnnouncer, oc: OverlayContainer) => { - snackBar = sb; - liveAnnouncer = la; - overlayContainer = oc; - overlayContainerElement = oc.getContainerElement(); - })); - - afterEach(() => { - overlayContainer.ngOnDestroy(); - liveAnnouncer.ngOnDestroy(); - }); + snackBar = sb; + liveAnnouncer = la; + overlayContainerElement = oc.getContainerElement(); + }, + )); beforeEach(() => { viewContainerFixture = TestBed.createComponent(ComponentWithChildViewContainer); @@ -71,13 +71,16 @@ describe('MatSnackBar', () => { const inertElement = containerElement.querySelector('[aria-hidden]')!; expect(inertElement.getAttribute('aria-hidden')) - .toBe('true', 'Expected the non-live region to be aria-hidden'); - expect(inertElement.textContent).toContain('Snack time!', - 'Expected non-live region to contain the snack bar content'); + .withContext('Expected the non-live region to be aria-hidden') + .toBe('true'); + expect(inertElement.textContent) + .withContext('Expected non-live region to contain the snack bar content') + .toContain('Snack time!'); const liveElement = containerElement.querySelector('[aria-live]')!; expect(liveElement.childNodes.length) - .toBe(0, 'Expected live region to not contain any content'); + .withContext('Expected live region to not contain any content') + .toBe(0); }); it('should move content to the live region after 150ms', fakeAsync(() => { @@ -88,160 +91,213 @@ describe('MatSnackBar', () => { const liveElement = containerElement.querySelector('[aria-live]')!; tick(announceDelay); - expect(liveElement.textContent).toContain('Snack time!', - 'Expected live region to contain the snack bar content'); + expect(liveElement.textContent) + .withContext('Expected live region to contain the snack bar content') + .toContain('Snack time!'); const inertElement = containerElement.querySelector('[aria-hidden]')!; - expect(inertElement).toBeFalsy('Expected non-live region to not contain any content'); + expect(inertElement) + .withContext('Expected non-live region to not contain any content') + .toBeFalsy(); })); it('should preserve focus when moving content to the live region', fakeAsync(() => { snackBar.open('Snack time!', 'Chew'); viewContainerFixture.detectChanges(); - const actionButton = overlayContainerElement - .querySelector('.mat-simple-snackbar-action > button')! as HTMLElement; + const actionButton = overlayContainerElement.querySelector( + '.mat-simple-snackbar-action > button', + )! as HTMLElement; actionButton.focus(); expect(document.activeElement) - .toBe(actionButton, 'Expected the focus to move to the action button'); + .withContext('Expected the focus to move to the action button') + .toBe(actionButton); flush(); expect(document.activeElement) - .toBe(actionButton, 'Expected the focus to remain on the action button'); + .withContext('Expected the focus to remain on the action button') + .toBe(actionButton); })); - it('should have aria-live of `assertive` with an `assertive` politeness if no announcement ' + - 'message is provided', () => { - snackBar.openFromComponent(BurritosNotification, - {announcementMessage: '', politeness: 'assertive'}); + it( + 'should have aria-live of `assertive` with an `assertive` politeness if no announcement ' + + 'message is provided', + () => { + snackBar.openFromComponent(BurritosNotification, { + announcementMessage: '', + politeness: 'assertive', + }); + + viewContainerFixture.detectChanges(); + + const containerElement = overlayContainerElement.querySelector('snack-bar-container')!; + const liveElement = containerElement.querySelector('[aria-live]')!; + + expect(liveElement.getAttribute('aria-live')) + .withContext('Expected snack bar container live region to have aria-live="assertive"') + .toBe('assertive'); + }, + ); + + it( + 'should have aria-live of `polite` with an `assertive` politeness if an announcement ' + + 'message is provided', + () => { + snackBar.openFromComponent(BurritosNotification, { + announcementMessage: 'Yay Burritos', + politeness: 'assertive', + }); + viewContainerFixture.detectChanges(); + + const containerElement = overlayContainerElement.querySelector('snack-bar-container')!; + const liveElement = containerElement.querySelector('[aria-live]')!; + + expect(liveElement.getAttribute('aria-live')) + .withContext('Expected snack bar container live region to have aria-live="polite"') + .toBe('polite'); + }, + ); + it('should have aria-live of `polite` with a `polite` politeness', () => { + snackBar.openFromComponent(BurritosNotification, {politeness: 'polite'}); viewContainerFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('snack-bar-container')!; const liveElement = containerElement.querySelector('[aria-live]')!; - expect(liveElement.getAttribute('aria-live')).toBe('assertive', - 'Expected snack bar container live region to have aria-live="assertive"'); + expect(liveElement.getAttribute('aria-live')) + .withContext('Expected snack bar container live region to have aria-live="polite"') + .toBe('polite'); }); - it('should have aria-live of `polite` with an `assertive` politeness if an announcement ' + - 'message is provided', () => { - snackBar.openFromComponent(BurritosNotification, - {announcementMessage: 'Yay Burritos', politeness: 'assertive'}); + it('should have aria-live of `off` if the politeness is turned off', () => { + snackBar.openFromComponent(BurritosNotification, {politeness: 'off'}); viewContainerFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('snack-bar-container')!; const liveElement = containerElement.querySelector('[aria-live]')!; expect(liveElement.getAttribute('aria-live')) - .toBe('polite', 'Expected snack bar container live region to have aria-live="polite"'); + .withContext('Expected snack bar container live region to have aria-live="off"') + .toBe('off'); }); - it('should have aria-live of `polite` with a `polite` politeness', () => { - snackBar.openFromComponent(BurritosNotification, {politeness: 'polite'}); + it('should have role of `alert` with an `assertive` politeness (Firefox only)', () => { + const platform = TestBed.inject(Platform); + snackBar.openFromComponent(BurritosNotification, {politeness: 'assertive'}); viewContainerFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('snack-bar-container')!; const liveElement = containerElement.querySelector('[aria-live]')!; - expect(liveElement.getAttribute('aria-live')) - .toBe('polite', 'Expected snack bar container live region to have aria-live="polite"'); + expect(liveElement.getAttribute('role')).toBe(platform.FIREFOX ? 'alert' : null); }); - it('should have aria-live of `off` if the politeness is turned off', () => { - snackBar.openFromComponent(BurritosNotification, {politeness: 'off'}); + it('should have role of `status` with an `polite` politeness (Firefox only)', () => { + const platform = TestBed.inject(Platform); + snackBar.openFromComponent(BurritosNotification, {politeness: 'polite'}); viewContainerFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('snack-bar-container')!; const liveElement = containerElement.querySelector('[aria-live]')!; - expect(liveElement.getAttribute('aria-live')) - .toBe('off', 'Expected snack bar container live region to have aria-live="off"'); + expect(liveElement.getAttribute('role')).toBe(platform.FIREFOX ? 'status' : null); }); it('should open and close a snackbar without a ViewContainerRef', fakeAsync(() => { - let snackBarRef = snackBar.open('Snack time!', 'Chew'); + const snackBarRef = snackBar.open('Snack time!', 'Chew'); viewContainerFixture.detectChanges(); - let messageElement = overlayContainerElement.querySelector('snack-bar-container')!; - expect(messageElement.textContent).toContain('Snack time!', - 'Expected snack bar to show a message without a ViewContainerRef'); + const messageElement = overlayContainerElement.querySelector('snack-bar-container')!; + expect(messageElement.textContent) + .withContext('Expected snack bar to show a message without a ViewContainerRef') + .toContain('Snack time!'); snackBarRef.dismiss(); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.childNodes.length) - .toBe(0, 'Expected snack bar to be dismissed without a ViewContainerRef'); + .withContext('Expected snack bar to be dismissed without a ViewContainerRef') + .toBe(0); })); it('should open a simple message with a button', () => { - let config: MatSnackBarConfig = {viewContainerRef: testViewContainerRef}; - let snackBarRef = snackBar.open(simpleMessage, simpleActionLabel, config); + const config: MatSnackBarConfig = {viewContainerRef: testViewContainerRef}; + const snackBarRef = snackBar.open(simpleMessage, simpleActionLabel, config); viewContainerFixture.detectChanges(); expect(snackBarRef.instance instanceof SimpleSnackBar) - .toBe(true, 'Expected the snack bar content component to be SimpleSnackBar'); + .withContext('Expected the snack bar content component to be SimpleSnackBar') + .toBe(true); expect(snackBarRef.instance.snackBarRef) - .toBe(snackBarRef, - 'Expected the snack bar reference to be placed in the component instance'); + .withContext('Expected the snack bar reference to be placed in the component instance') + .toBe(snackBarRef); - let messageElement = overlayContainerElement.querySelector('snack-bar-container')!; + const messageElement = overlayContainerElement.querySelector('snack-bar-container')!; expect(messageElement.textContent) - .toContain(simpleMessage, `Expected the snack bar message to be '${simpleMessage}'`); + .withContext(`Expected the snack bar message to be '${simpleMessage}'`) + .toContain(simpleMessage); - let buttonElement = overlayContainerElement.querySelector('button.mat-button')!; + const buttonElement = overlayContainerElement.querySelector('button.mat-button')!; expect(buttonElement.tagName) - .toBe('BUTTON', 'Expected snack bar action label to be a
+ mat-sort-header="defaultB" + [sortActionDescription]="secondColumnDescription"> B
- ` + `, }) class SimpleMatSortApp { latestSortEvent: Sort; @@ -481,6 +563,7 @@ class SimpleMatSortApp { disableClear: boolean; disabledColumnSort = false; disableAllSort = false; + secondColumnDescription = 'Sort second column'; @ViewChild(MatSort) matSort: MatSort; @ViewChild('defaultA') defaultA: MatSortHeader; @@ -488,7 +571,7 @@ class SimpleMatSortApp { @ViewChild('overrideStart') overrideStart: MatSortHeader; @ViewChild('overrideDisableClear') overrideDisableClear: MatSortHeader; - constructor (public elementRef: ElementRef) { } + constructor(public elementRef: ElementRef) {} sort(id: SimpleMatSortAppColumnIds) { this.dispatchMouseEvent(id, 'click'); @@ -505,12 +588,13 @@ class SimpleMatSortApp { * states. */ expectViewAndDirectionStates( - viewStates: Map) { + viewStates: Map, + ) { const sortHeaders = new Map([ ['defaultA', this.defaultA], ['defaultB', this.defaultB], ['overrideStart', this.overrideStart], - ['overrideDisableClear', this.overrideDisableClear] + ['overrideDisableClear', this.overrideDisableClear], ]); viewStates.forEach((viewState, id) => { @@ -520,7 +604,6 @@ class SimpleMatSortApp { } } - class FakeDataSource extends DataSource { connect(collectionViewer: CollectionViewer): Observable { return collectionViewer.viewChange.pipe(map(() => [])); @@ -549,7 +632,7 @@ class FakeDataSource extends DataSource { - ` + `, }) class CdkTableMatSortApp { @ViewChild(MatSort) matSort: MatSort; @@ -579,7 +662,7 @@ class CdkTableMatSortApp { - ` + `, }) class MatTableMatSortApp { @ViewChild(MatSort) matSort: MatSort; @@ -588,12 +671,10 @@ class MatTableMatSortApp { columnsToRender = ['column_a', 'column_b', 'column_c']; } - @Component({ - template: `
A
` + template: `
A
`, }) -class MatSortHeaderMissingMatSortApp { } - +class MatSortHeaderMissingMatSortApp {} @Component({ template: ` @@ -601,26 +682,57 @@ class MatSortHeaderMissingMatSortApp { }
A
A
- ` + `, }) -class MatSortDuplicateMatSortableIdsApp { } - +class MatSortDuplicateMatSortableIdsApp {} @Component({ template: `
A
- ` + `, }) -class MatSortableMissingIdApp { } - +class MatSortableMissingIdApp {} @Component({ template: `
A
- ` + `, +}) +class MatSortableInvalidDirection {} + +@Component({ + template: ` +
+
+ A +
+
+ `, }) -class MatSortableInvalidDirection { } +class MatSortWithoutExplicitInputs { + latestSortEvent: Sort; + + active: string; + start: SortDirection = 'asc'; + + @ViewChild(MatSort) matSort: MatSort; + @ViewChild('defaultA') defaultA: MatSortHeader; + + constructor(public elementRef: ElementRef) {} + + sort(id: SimpleMatSortAppColumnIds) { + this.dispatchMouseEvent(id, 'click'); + } + + dispatchMouseEvent(id: SimpleMatSortAppColumnIds, event: string) { + const sortElement = this.elementRef.nativeElement.querySelector(`#${id}`)!; + dispatchMouseEvent(sortElement, event); + } +} diff --git a/src/material/sort/sort.ts b/src/material/sort/sort.ts index ef0e4fd61a28..30e1e223c0d0 100644 --- a/src/material/sort/sort.ts +++ b/src/material/sort/sort.ts @@ -10,20 +10,16 @@ import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion'; import { Directive, EventEmitter, + Inject, + InjectionToken, Input, OnChanges, OnDestroy, OnInit, + Optional, Output, } from '@angular/core'; -import { - CanDisable, - CanDisableCtor, - HasInitialized, - HasInitializedCtor, - mixinDisabled, - mixinInitialized, -} from '@angular/material/core'; +import {CanDisable, HasInitialized, mixinDisabled, mixinInitialized} from '@angular/material/core'; import {Subject} from 'rxjs'; import {SortDirection} from './sort-direction'; import { @@ -53,21 +49,32 @@ export interface Sort { direction: SortDirection; } +/** Default options for `mat-sort`. */ +export interface MatSortDefaultOptions { + /** Whether to disable clearing the sorting state. */ + disableClear?: boolean; +} + +/** Injection token to be used to override the default options for `mat-sort`. */ +export const MAT_SORT_DEFAULT_OPTIONS = new InjectionToken( + 'MAT_SORT_DEFAULT_OPTIONS', +); + // Boilerplate for applying mixins to MatSort. /** @docs-private */ -class MatSortBase {} -const _MatSortMixinBase: HasInitializedCtor & CanDisableCtor & typeof MatSortBase = - mixinInitialized(mixinDisabled(MatSortBase)); +const _MatSortBase = mixinInitialized(mixinDisabled(class {})); /** Container for MatSortables to manage the sort state and provide default sort parameters. */ @Directive({ selector: '[matSort]', exportAs: 'matSort', host: {'class': 'mat-sort'}, - inputs: ['disabled: matSortDisabled'] + inputs: ['disabled: matSortDisabled'], }) -export class MatSort extends _MatSortMixinBase - implements CanDisable, HasInitialized, OnChanges, OnDestroy, OnInit { +export class MatSort + extends _MatSortBase + implements CanDisable, HasInitialized, OnChanges, OnDestroy, OnInit +{ /** Collection of all registered sortables that this directive manages. */ sortables = new Map(); @@ -85,10 +92,16 @@ export class MatSort extends _MatSortMixinBase /** The sort direction of the currently active MatSortable. */ @Input('matSortDirection') - get direction(): SortDirection { return this._direction; } + get direction(): SortDirection { + return this._direction; + } set direction(direction: SortDirection) { - if (direction && direction !== 'asc' && direction !== 'desc' && - (typeof ngDevMode === 'undefined' || ngDevMode)) { + if ( + direction && + direction !== 'asc' && + direction !== 'desc' && + (typeof ngDevMode === 'undefined' || ngDevMode) + ) { throw getSortInvalidDirectionError(direction); } this._direction = direction; @@ -100,13 +113,25 @@ export class MatSort extends _MatSortMixinBase * May be overriden by the MatSortable's disable clear input. */ @Input('matSortDisableClear') - get disableClear(): boolean { return this._disableClear; } - set disableClear(v: boolean) { this._disableClear = coerceBooleanProperty(v); } + get disableClear(): boolean { + return this._disableClear; + } + set disableClear(v: BooleanInput) { + this._disableClear = coerceBooleanProperty(v); + } private _disableClear: boolean; /** Event emitted when the user changes either the active sort or sort direction. */ @Output('matSortChange') readonly sortChange: EventEmitter = new EventEmitter(); + constructor( + @Optional() + @Inject(MAT_SORT_DEFAULT_OPTIONS) + private _defaultOptions?: MatSortDefaultOptions, + ) { + super(); + } + /** * Register function to be used by the contained MatSortables. Adds the MatSortable to the * collection of MatSortables. @@ -147,15 +172,20 @@ export class MatSort extends _MatSortMixinBase /** Returns the next sort direction of the active sortable, checking for potential overrides. */ getNextSortDirection(sortable: MatSortable): SortDirection { - if (!sortable) { return ''; } + if (!sortable) { + return ''; + } // Get the sort direction cycle with the potential sortable overrides. - const disableClear = sortable.disableClear != null ? sortable.disableClear : this.disableClear; + const disableClear = + sortable?.disableClear ?? this.disableClear ?? !!this._defaultOptions?.disableClear; let sortDirectionCycle = getSortDirectionCycle(sortable.start || this.start, disableClear); // Get and return the next direction in the cycle let nextDirectionIndex = sortDirectionCycle.indexOf(this.direction) + 1; - if (nextDirectionIndex >= sortDirectionCycle.length) { nextDirectionIndex = 0; } + if (nextDirectionIndex >= sortDirectionCycle.length) { + nextDirectionIndex = 0; + } return sortDirectionCycle[nextDirectionIndex]; } @@ -170,17 +200,17 @@ export class MatSort extends _MatSortMixinBase ngOnDestroy() { this._stateChanges.complete(); } - - static ngAcceptInputType_disableClear: BooleanInput; - static ngAcceptInputType_disabled: BooleanInput; } /** Returns the sort direction cycle to use given the provided parameters of order and clear. */ -function getSortDirectionCycle(start: 'asc' | 'desc', - disableClear: boolean): SortDirection[] { +function getSortDirectionCycle(start: 'asc' | 'desc', disableClear: boolean): SortDirection[] { let sortOrder: SortDirection[] = ['asc', 'desc']; - if (start == 'desc') { sortOrder.reverse(); } - if (!disableClear) { sortOrder.push(''); } + if (start == 'desc') { + sortOrder.reverse(); + } + if (!disableClear) { + sortOrder.push(''); + } return sortOrder; } diff --git a/src/material/sort/testing/BUILD.bazel b/src/material/sort/testing/BUILD.bazel index 5c41498afa69..46a6a4e69f03 100644 --- a/src/material/sort/testing/BUILD.bazel +++ b/src/material/sort/testing/BUILD.bazel @@ -8,7 +8,6 @@ ts_library( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material/sort/testing", deps = [ "//src/cdk/testing", "//src/material/sort", diff --git a/src/material/sort/testing/shared.spec.ts b/src/material/sort/testing/shared.spec.ts index b18ae40b4b07..680152dc108a 100644 --- a/src/material/sort/testing/shared.spec.ts +++ b/src/material/sort/testing/shared.spec.ts @@ -8,8 +8,9 @@ import {MatSortHarness} from './sort-harness'; /** Shared tests to run on both the original and MDC-based sort. */ export function runHarnessTests( - sortModule: typeof MatSortModule, - sortHarness: typeof MatSortHarness) { + sortModule: typeof MatSortModule, + sortHarness: typeof MatSortHarness, +) { let fixture: ComponentFixture; let loader: HarnessLoader; @@ -138,7 +139,7 @@ export function runHarnessTests( {{dessert.protein}} - ` + `, }) class SortHarnessTest { disableThirdHeader = false; @@ -166,4 +167,3 @@ class SortHarnessTest { } } } - diff --git a/src/material/sort/testing/sort-harness-filters.ts b/src/material/sort/testing/sort-harness-filters.ts index 5a7f9288c264..21cbaa838baf 100644 --- a/src/material/sort/testing/sort-harness-filters.ts +++ b/src/material/sort/testing/sort-harness-filters.ts @@ -8,8 +8,7 @@ import {BaseHarnessFilters} from '@angular/cdk/testing'; import {SortDirection} from '@angular/material/sort'; -export interface SortHarnessFilters extends BaseHarnessFilters { -} +export interface SortHarnessFilters extends BaseHarnessFilters {} export interface SortHeaderHarnessFilters extends BaseHarnessFilters { label?: string | RegExp; diff --git a/src/material/sort/testing/sort-harness.ts b/src/material/sort/testing/sort-harness.ts index 0218a3ab6221..8004f0440e53 100644 --- a/src/material/sort/testing/sort-harness.ts +++ b/src/material/sort/testing/sort-harness.ts @@ -29,7 +29,7 @@ export class MatSortHarness extends ComponentHarness { } /** Gets the selected header in the `mat-sort`. */ - async getActiveHeader(): Promise { + async getActiveHeader(): Promise { const headers = await this.getSortHeaders(); for (let i = 0; i < headers.length; i++) { if (await headers[i].isActive()) { diff --git a/src/material/sort/testing/sort-header-harness.ts b/src/material/sort/testing/sort-header-harness.ts index 8b2b21ff4722..9356cf9a9a97 100644 --- a/src/material/sort/testing/sort-header-harness.ts +++ b/src/material/sort/testing/sort-header-harness.ts @@ -21,11 +21,12 @@ export class MatSortHeaderHarness extends ComponentHarness { */ static with(options: SortHeaderHarnessFilters = {}): HarnessPredicate { return new HarnessPredicate(MatSortHeaderHarness, options) - .addOption('label', options.label, - (harness, label) => HarnessPredicate.stringMatches(harness.getLabel(), label)) - .addOption('sortDirection', options.sortDirection, (harness, sortDirection) => { - return HarnessPredicate.stringMatches(harness.getSortDirection(), sortDirection); - }); + .addOption('label', options.label, (harness, label) => + HarnessPredicate.stringMatches(harness.getLabel(), label), + ) + .addOption('sortDirection', options.sortDirection, (harness, sortDirection) => { + return HarnessPredicate.stringMatches(harness.getSortDirection(), sortDirection); + }); } /** Gets the label of the sort header. */ @@ -47,15 +48,6 @@ export class MatSortHeaderHarness extends ComponentHarness { return ''; } - /** - * Gets the aria-label of the sort header. - * @deprecated The sort header no longer has an `aria-label`. This method will be removed. - * @breaking-change 11.0.0 - */ - async getAriaLabel(): Promise { - return (await this._container()).getAttribute('aria-label'); - } - /** Gets whether the sort header is currently being sorted by. */ async isActive(): Promise { return !!(await this.getSortDirection()); diff --git a/src/material/stepper/BUILD.bazel b/src/material/stepper/BUILD.bazel index e4896e25cfdb..a7c76cf0cb29 100644 --- a/src/material/stepper/BUILD.bazel +++ b/src/material/stepper/BUILD.bazel @@ -22,8 +22,8 @@ ng_module( ":stepper.css", ":step-header.css", ] + glob(["**/*.html"]), - module_name = "@angular/material/stepper", deps = [ + "//src:dev_mode_types", "//src/cdk/a11y", "//src/cdk/bidi", "//src/cdk/portal", @@ -75,6 +75,7 @@ ng_test_library( ":stepper", "//src/cdk/bidi", "//src/cdk/keycodes", + "//src/cdk/platform", "//src/cdk/stepper", "//src/cdk/testing/private", "//src/material/core", diff --git a/src/material/stepper/_stepper-legacy-index.scss b/src/material/stepper/_stepper-legacy-index.scss new file mode 100644 index 000000000000..ed6b4bbebc1b --- /dev/null +++ b/src/material/stepper/_stepper-legacy-index.scss @@ -0,0 +1,7 @@ +@forward 'stepper-variables' as mat-* hide $mat-density-config, $mat-header-height, +$mat-header-maximum-height, $mat-header-minimum-height, $mat-label-header-height, +$mat-label-min-width, $mat-label-position-bottom-top-gap, $mat-line-gap, $mat-line-width, +$mat-side-gap; +@forward 'stepper-variables' as mat-stepper-* hide $mat-stepper-step-header-icon-size, +$mat-stepper-step-sub-label-font-size, $mat-stepper-vertical-stepper-content-margin; +@forward 'stepper-theme' as mat-stepper-*; diff --git a/src/material/stepper/_stepper-theme.import.scss b/src/material/stepper/_stepper-theme.import.scss new file mode 100644 index 000000000000..95dcc2b634f3 --- /dev/null +++ b/src/material/stepper/_stepper-theme.import.scss @@ -0,0 +1,16 @@ +@forward '../core/theming/theming.import'; +@forward '../core/density/private/compatibility.import'; +@forward 'stepper-variables' as mat-* hide $mat-density-config, $mat-header-height, +$mat-header-maximum-height, $mat-header-minimum-height, $mat-label-header-height, +$mat-label-min-width, $mat-label-position-bottom-top-gap, $mat-line-gap, $mat-line-width, +$mat-side-gap; +@forward 'stepper-variables' as mat-stepper-* hide $mat-stepper-step-header-icon-size, +$mat-stepper-step-sub-label-font-size, $mat-stepper-vertical-stepper-content-margin; +@forward '../core/typography/typography-utils.import'; +@forward 'stepper-theme' as mat-stepper-*; + +@import '../core/theming/palette'; +@import '../core/theming/theming'; +@import '../core/typography/typography-utils'; +@import '../core/density/private/compatibility'; +@import './stepper-variables'; diff --git a/src/material/stepper/_stepper-theme.scss b/src/material/stepper/_stepper-theme.scss index e8c197c465b2..6f6fb1c502e3 100644 --- a/src/material/stepper/_stepper-theme.scss +++ b/src/material/stepper/_stepper-theme.scss @@ -1,22 +1,29 @@ -@import '../core/theming/palette'; -@import '../core/theming/theming'; -@import '../core/typography/typography-utils'; -@import '../core/density/private/compatibility'; -@import './stepper-variables'; - -@mixin mat-stepper-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $foreground: map-get($config, foreground); - $background: map-get($config, background); - $primary: map-get($config, primary); - $accent: map-get($config, accent); - $warn: map-get($config, warn); +@use 'sass:map'; +@use 'sass:math'; +@use '../core/theming/theming'; +@use '../core/typography/typography'; +@use '../core/typography/typography-utils'; +@use '../core/density/private/compatibility'; +@use './stepper-variables'; + +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $foreground: map.get($config, foreground); + $background: map.get($config, background); + $primary: map.get($config, primary); + $accent: map.get($config, accent); + $warn: map.get($config, warn); .mat-step-header { &.cdk-keyboard-focused, &.cdk-program-focused, - &:hover { - background-color: mat-color($background, hover); + &:hover:not([aria-disabled]), + &:hover[aria-disabled='false'] { + background-color: theming.get-color-from-palette($background, hover); + } + + &:hover[aria-disabled='true'] { + cursor: default; } // On touch devices the :hover state will linger on the element after a tap. @@ -32,88 +39,89 @@ .mat-step-optional { // TODO(josephperrott): Update to using a corrected disabled-text contrast // instead of secondary-text. - color: mat-color($foreground, secondary-text); + color: theming.get-color-from-palette($foreground, secondary-text); } .mat-step-icon { // TODO(josephperrott): Update to using a corrected disabled-text contrast // instead of secondary-text. - background-color: mat-color($foreground, secondary-text); - color: mat-color($primary, default-contrast); + background-color: theming.get-color-from-palette($foreground, secondary-text); + color: theming.get-color-from-palette($primary, default-contrast); } .mat-step-icon-selected, .mat-step-icon-state-done, .mat-step-icon-state-edit { - background-color: mat-color($primary); - color: mat-color($primary, default-contrast); + background-color: theming.get-color-from-palette($primary); + color: theming.get-color-from-palette($primary, default-contrast); } &.mat-accent { .mat-step-icon { - color: mat-color($accent, default-contrast); + color: theming.get-color-from-palette($accent, default-contrast); } .mat-step-icon-selected, .mat-step-icon-state-done, .mat-step-icon-state-edit { - background-color: mat-color($accent); - color: mat-color($accent, default-contrast); + background-color: theming.get-color-from-palette($accent); + color: theming.get-color-from-palette($accent, default-contrast); } } &.mat-warn { .mat-step-icon { - color: mat-color($warn, default-contrast); + color: theming.get-color-from-palette($warn, default-contrast); } .mat-step-icon-selected, .mat-step-icon-state-done, .mat-step-icon-state-edit { - background-color: mat-color($warn); - color: mat-color($warn, default-contrast); + background-color: theming.get-color-from-palette($warn); + color: theming.get-color-from-palette($warn, default-contrast); } } .mat-step-icon-state-error { background-color: transparent; - color: mat-color($warn, text); + color: theming.get-color-from-palette($warn, text); } .mat-step-label.mat-step-label-active { - color: mat-color($foreground, text); + color: theming.get-color-from-palette($foreground, text); } .mat-step-label.mat-step-label-error { - color: mat-color($warn, text); + color: theming.get-color-from-palette($warn, text); } } .mat-stepper-horizontal, .mat-stepper-vertical { - background-color: mat-color($background, card); + background-color: theming.get-color-from-palette($background, card); } .mat-stepper-vertical-line::before { - border-left-color: mat-color($foreground, divider); + border-left-color: theming.get-color-from-palette($foreground, divider); } .mat-horizontal-stepper-header::before, .mat-horizontal-stepper-header::after, .mat-stepper-horizontal-line { - border-top-color: mat-color($foreground, divider); + border-top-color: theming.get-color-from-palette($foreground, divider); } } -@mixin mat-stepper-typography($config-or-theme) { - $config: mat-get-typography-config($config-or-theme); +@mixin typography($config-or-theme) { + $config: typography.private-typography-to-2014-config( + theming.get-typography-config($config-or-theme)); .mat-stepper-vertical, .mat-stepper-horizontal { - font-family: mat-font-family($config); + font-family: typography-utils.font-family($config); } .mat-step-label { font: { - size: mat-font-size($config, body-1); - weight: mat-font-weight($config, body-1); + size: typography-utils.font-size($config, body-1); + weight: typography-utils.font-weight($config, body-1); }; } @@ -122,68 +130,69 @@ } .mat-step-label-error { - font-size: mat-font-size($config, body-2); + font-size: typography-utils.font-size($config, body-2); } .mat-step-label-selected { font: { - size: mat-font-size($config, body-2); - weight: mat-font-weight($config, body-2); + size: typography-utils.font-size($config, body-2); + weight: typography-utils.font-weight($config, body-2); }; } } -@mixin mat-stepper-density($config-or-theme) { - $density-scale: mat-get-density-config($config-or-theme); - $height: mat-private-density-prop-value($mat-stepper-density-config, $density-scale, height); - $vertical-padding: ($height - $mat-stepper-label-header-height) / 2; +@mixin density($config-or-theme) { + $density-scale: theming.get-density-config($config-or-theme); + $height: compatibility.private-density-prop-value(stepper-variables.$density-config, + $density-scale, height); + $vertical-padding: math.div($height - stepper-variables.$label-header-height, 2); - @include mat-private-density-legacy-compatibility() { + @include compatibility.private-density-legacy-compatibility() { .mat-horizontal-stepper-header { height: $height; } .mat-stepper-label-position-bottom .mat-horizontal-stepper-header, .mat-vertical-stepper-header { - padding: $vertical-padding $mat-stepper-side-gap; + padding: $vertical-padding stepper-variables.$side-gap; } // Ensures that the vertical lines for the step content exceed into the step // headers with a given distance (`$mat-stepper-line-gap`) to the step icon. .mat-stepper-vertical-line::before { - top: $mat-stepper-line-gap - $vertical-padding; - bottom: $mat-stepper-line-gap - $vertical-padding; + top: stepper-variables.$line-gap - $vertical-padding; + bottom: stepper-variables.$line-gap - $vertical-padding; } // Ensures that the horizontal lines for the step header are centered vertically. .mat-stepper-label-position-bottom .mat-horizontal-stepper-header { &::after, &::before { - top: $vertical-padding + $mat-stepper-label-header-height / 2; + top: $vertical-padding + math.div(stepper-variables.$label-header-height, 2); } } // Ensures that the horizontal line for the step content is aligned centered vertically. .mat-stepper-label-position-bottom .mat-stepper-horizontal-line { - top: $vertical-padding + $mat-stepper-label-header-height / 2; + top: $vertical-padding + math.div(stepper-variables.$label-header-height, 2); } } } -@mixin mat-stepper-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-stepper') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-stepper') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); @if $color != null { - @include mat-stepper-color($color); + @include color($color); } @if $density != null { - @include mat-stepper-density($density); + @include density($density); } @if $typography != null { - @include mat-stepper-typography($typography); + @include typography($typography); } } } diff --git a/src/material/stepper/_stepper-variables.import.scss b/src/material/stepper/_stepper-variables.import.scss new file mode 100644 index 000000000000..a4b75d36e49a --- /dev/null +++ b/src/material/stepper/_stepper-variables.import.scss @@ -0,0 +1,6 @@ +@forward 'stepper-variables' as mat-* hide $mat-density-config, $mat-header-height, +$mat-header-maximum-height, $mat-header-minimum-height, $mat-label-header-height, +$mat-label-min-width, $mat-label-position-bottom-top-gap, $mat-line-gap, $mat-line-width, +$mat-side-gap; +@forward 'stepper-variables' as mat-stepper-* hide $mat-stepper-step-header-icon-size, +$mat-stepper-step-sub-label-font-size, $mat-stepper-vertical-stepper-content-margin; diff --git a/src/material/stepper/_stepper-variables.scss b/src/material/stepper/_stepper-variables.scss index 2f03c9fa6aaf..7e3e0bdfe07d 100644 --- a/src/material/stepper/_stepper-variables.scss +++ b/src/material/stepper/_stepper-variables.scss @@ -1,29 +1,29 @@ -$mat-stepper-header-height: 72px !default; +$header-height: 72px !default; // Minimum height for highest density stepper's is determined based on how much // stepper headers can shrink until the step icon or step label exceed. We can't use // a value below `42px` because the optional label for steps would otherwise exceed. -$mat-stepper-header-minimum-height: 42px !default; -$mat-stepper-header-maximum-height: $mat-stepper-header-height !default; +$header-minimum-height: 42px !default; +$header-maximum-height: $header-height !default; -$mat-stepper-density-config: ( +$density-config: ( height: ( - default: $mat-stepper-header-height, - maximum: $mat-stepper-header-maximum-height, - minimum: $mat-stepper-header-minimum-height, + default: $header-height, + maximum: $header-maximum-height, + minimum: $header-minimum-height, ) ) !default; // Note: These variables are not denoted with `!default` because they are used in the non-theme // component styles. Modifying these variables does not have the desired effect for consumers. -$mat-stepper-label-header-height: 24px; -$mat-stepper-label-position-bottom-top-gap: 16px; -$mat-stepper-label-min-width: 50px; +$label-header-height: 24px; +$label-position-bottom-top-gap: 16px; +$label-min-width: 50px; -$mat-vertical-stepper-content-margin: 36px; +$vertical-stepper-content-margin: 36px; -$mat-stepper-side-gap: 24px; -$mat-stepper-line-width: 1px; -$mat-stepper-line-gap: 8px; +$side-gap: 24px; +$line-width: 1px; +$line-gap: 8px; -$mat-step-sub-label-font-size: 12px; -$mat-step-header-icon-size: 16px; +$step-sub-label-font-size: 12px; +$step-header-icon-size: 16px; diff --git a/src/material/stepper/public-api.ts b/src/material/stepper/public-api.ts index de358424ebf7..ff33516856d5 100644 --- a/src/material/stepper/public-api.ts +++ b/src/material/stepper/public-api.ts @@ -6,6 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ +export {StepperOrientation, StepState} from '@angular/cdk/stepper'; export * from './stepper-module'; export * from './step-label'; export * from './stepper'; @@ -14,3 +15,4 @@ export * from './step-header'; export * from './stepper-intl'; export * from './stepper-animations'; export * from './stepper-icon'; +export * from './step-content'; diff --git a/src/material/stepper/step-content.ts b/src/material/stepper/step-content.ts new file mode 100644 index 000000000000..e871330cee9b --- /dev/null +++ b/src/material/stepper/step-content.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {Directive, TemplateRef} from '@angular/core'; + +/** + * Content for a `mat-step` that will be rendered lazily. + */ +@Directive({ + selector: 'ng-template[matStepContent]', +}) +export class MatStepContent { + constructor(public _template: TemplateRef) {} +} diff --git a/src/material/stepper/step-header.html b/src/material/stepper/step-header.html index ae06ac2fbaef..0924af21e7ed 100644 --- a/src/material/stepper/step-header.html +++ b/src/material/stepper/step-header.html @@ -1,4 +1,4 @@ -
@@ -9,8 +9,10 @@ [ngTemplateOutlet]="iconOverrides[state]" [ngTemplateOutletContext]="_getIconContext()"> - {{_getDefaultTextForState(state)}} - {{_getDefaultTextForState(state)}} + + {{_intl.completedLabel}} + {{_intl.editableLabel}} + diff --git a/src/material/stepper/step-header.scss b/src/material/stepper/step-header.scss index a2e700f6dbac..fde2dce109ac 100644 --- a/src/material/stepper/step-header.scss +++ b/src/material/stepper/step-header.scss @@ -1,5 +1,6 @@ -@import '../core/style/layout-common'; -@import './stepper-variables'; +@use '../core/style/layout-common'; +@use './stepper-variables'; +@use '../../cdk/a11y'; .mat-step-header { overflow: hidden; @@ -8,17 +9,30 @@ position: relative; box-sizing: content-box; -webkit-tap-highlight-color: transparent; + + @include a11y.high-contrast(active, off) { + outline: solid 1px; + &.cdk-keyboard-focused, &.cdk-program-focused { + outline: solid 3px; + } + + &[aria-selected='true'] { + .mat-step-label { + text-decoration: underline; + } + } + } } .mat-step-optional, .mat-step-sub-label-error { - font-size: $mat-step-sub-label-font-size; + font-size: stepper-variables.$step-sub-label-font-size; } .mat-step-icon { border-radius: 50%; - height: $mat-stepper-label-header-height; - width: $mat-stepper-label-header-height; + height: stepper-variables.$label-header-height; + width: stepper-variables.$label-header-height; flex-shrink: 0; position: relative; } @@ -33,15 +47,15 @@ } .mat-step-icon .mat-icon { - font-size: $mat-step-header-icon-size; - height: $mat-step-header-icon-size; - width: $mat-step-header-icon-size; + font-size: stepper-variables.$step-header-icon-size; + height: stepper-variables.$step-header-icon-size; + width: stepper-variables.$step-header-icon-size; } .mat-step-icon-state-error .mat-icon { - font-size: $mat-step-header-icon-size + 8; - height: $mat-step-header-icon-size + 8; - width: $mat-step-header-icon-size + 8; + font-size: stepper-variables.$step-header-icon-size + 8; + height: stepper-variables.$step-header-icon-size + 8; + width: stepper-variables.$step-header-icon-size + 8; } .mat-step-label { @@ -49,7 +63,7 @@ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; - min-width: $mat-stepper-label-min-width; + min-width: stepper-variables.$label-min-width; vertical-align: middle; } @@ -61,6 +75,6 @@ // Increase specificity because ripple styles are part of the `mat-core` mixin and can // potentially overwrite the absolute position of the container. .mat-step-header .mat-step-header-ripple { - @include mat-fill; + @include layout-common.fill; pointer-events: none; } diff --git a/src/material/stepper/step-header.ts b/src/material/stepper/step-header.ts index 8431e373e295..4e58c5a35cfe 100644 --- a/src/material/stepper/step-header.ts +++ b/src/material/stepper/step-header.ts @@ -23,19 +23,18 @@ import {MatStepLabel} from './step-label'; import {MatStepperIntl} from './stepper-intl'; import {MatStepperIconContext} from './stepper-icon'; import {CdkStepHeader, StepState} from '@angular/cdk/stepper'; -import {CanColorCtor, mixinColor, CanColor} from '@angular/material/core'; - +import {mixinColor, CanColor} from '@angular/material/core'; // Boilerplate for applying mixins to MatStepHeader. /** @docs-private */ -class MatStepHeaderBase extends CdkStepHeader { - constructor(elementRef: ElementRef) { - super(elementRef); - } -} - -const _MatStepHeaderMixinBase: CanColorCtor & typeof MatStepHeaderBase = - mixinColor(MatStepHeaderBase, 'primary'); +const _MatStepHeaderBase = mixinColor( + class MatStepHeaderBase extends CdkStepHeader { + constructor(elementRef: ElementRef) { + super(elementRef); + } + }, + 'primary', +); @Component({ selector: 'mat-step-header', @@ -43,14 +42,16 @@ const _MatStepHeaderMixinBase: CanColorCtor & typeof MatStepHeaderBase = styleUrls: ['step-header.css'], inputs: ['color'], host: { - 'class': 'mat-step-header mat-focus-indicator', + 'class': 'mat-step-header', 'role': 'tab', }, encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) -export class MatStepHeader extends _MatStepHeaderMixinBase implements AfterViewInit, OnDestroy, - CanColor { +export class MatStepHeader + extends _MatStepHeaderBase + implements AfterViewInit, OnDestroy, CanColor +{ private _intlSubscription: Subscription; /** State of the given step. */ @@ -84,7 +85,8 @@ export class MatStepHeader extends _MatStepHeaderMixinBase implements AfterViewI public _intl: MatStepperIntl, private _focusMonitor: FocusMonitor, _elementRef: ElementRef, - changeDetectorRef: ChangeDetectorRef) { + changeDetectorRef: ChangeDetectorRef, + ) { super(_elementRef); this._intlSubscription = _intl.changes.subscribe(() => changeDetectorRef.markForCheck()); } @@ -99,7 +101,7 @@ export class MatStepHeader extends _MatStepHeaderMixinBase implements AfterViewI } /** Focuses the step header. */ - focus(origin?: FocusOrigin, options?: FocusOptions) { + override focus(origin?: FocusOrigin, options?: FocusOptions) { if (origin) { this._focusMonitor.focusVia(this._elementRef, origin, options); } else { @@ -127,7 +129,7 @@ export class MatStepHeader extends _MatStepHeaderMixinBase implements AfterViewI return { index: this.index, active: this.active, - optional: this.optional + optional: this.optional, }; } diff --git a/src/material/stepper/step.html b/src/material/stepper/step.html index cd48c06b9917..bd5b263e74ae 100644 --- a/src/material/stepper/step.html +++ b/src/material/stepper/step.html @@ -1 +1,4 @@ - + + + + diff --git a/src/material/stepper/stepper-animations.ts b/src/material/stepper/stepper-animations.ts index 71053cb9352c..59ac2c980035 100644 --- a/src/material/stepper/stepper-animations.ts +++ b/src/material/stepper/stepper-animations.ts @@ -23,18 +23,24 @@ export const matStepperAnimations: { readonly verticalStepTransition: AnimationTriggerMetadata; } = { /** Animation that transitions the step along the X axis in a horizontal stepper. */ - horizontalStepTransition: trigger('stepTransition', [ + horizontalStepTransition: trigger('horizontalStepTransition', [ state('previous', style({transform: 'translate3d(-100%, 0, 0)', visibility: 'hidden'})), - state('current', style({transform: 'none', visibility: 'visible'})), + // Transition to `inherit`, rather than `visible`, + // because visibility on a child element the one from the parent, + // making this element focusable inside of a `hidden` element. + state('current', style({transform: 'none', visibility: 'inherit'})), state('next', style({transform: 'translate3d(100%, 0, 0)', visibility: 'hidden'})), - transition('* => *', animate('500ms cubic-bezier(0.35, 0, 0.25, 1)')) + transition('* => *', animate('500ms cubic-bezier(0.35, 0, 0.25, 1)')), ]), /** Animation that transitions the step along the Y axis in a vertical stepper. */ - verticalStepTransition: trigger('stepTransition', [ + verticalStepTransition: trigger('verticalStepTransition', [ state('previous', style({height: '0px', visibility: 'hidden'})), state('next', style({height: '0px', visibility: 'hidden'})), - state('current', style({height: '*', visibility: 'visible'})), - transition('* <=> current', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')) - ]) + // Transition to `inherit`, rather than `visible`, + // because visibility on a child element the one from the parent, + // making this element focusable inside of a `hidden` element. + state('current', style({height: '*', visibility: 'inherit'})), + transition('* <=> current', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')), + ]), }; diff --git a/src/material/stepper/stepper-button.ts b/src/material/stepper/stepper-button.ts index 35eef9ad4a28..bb675b9579f2 100644 --- a/src/material/stepper/stepper-button.ts +++ b/src/material/stepper/stepper-button.ts @@ -16,10 +16,9 @@ import {Directive} from '@angular/core'; 'class': 'mat-stepper-next', '[type]': 'type', }, - inputs: ['type'] + inputs: ['type'], }) -export class MatStepperNext extends CdkStepperNext { -} +export class MatStepperNext extends CdkStepperNext {} /** Button that moves to the previous step in a stepper workflow. */ @Directive({ @@ -28,7 +27,6 @@ export class MatStepperNext extends CdkStepperNext { 'class': 'mat-stepper-previous', '[type]': 'type', }, - inputs: ['type'] + inputs: ['type'], }) -export class MatStepperPrevious extends CdkStepperPrevious { -} +export class MatStepperPrevious extends CdkStepperPrevious {} diff --git a/src/material/stepper/stepper-horizontal.html b/src/material/stepper/stepper-horizontal.html deleted file mode 100644 index bf004776064c..000000000000 --- a/src/material/stepper/stepper-horizontal.html +++ /dev/null @@ -1,39 +0,0 @@ -
- - - -
-
-
- -
-
- -
-
diff --git a/src/material/stepper/stepper-intl.ts b/src/material/stepper/stepper-intl.ts index 9e0dab687036..9517bfcc0837 100644 --- a/src/material/stepper/stepper-intl.ts +++ b/src/material/stepper/stepper-intl.ts @@ -9,7 +9,6 @@ import {Injectable, Optional, SkipSelf} from '@angular/core'; import {Subject} from 'rxjs'; - /** Stepper data that is required for internationalization. */ @Injectable({providedIn: 'root'}) export class MatStepperIntl { @@ -21,8 +20,13 @@ export class MatStepperIntl { /** Label that is rendered below optional steps. */ optionalLabel: string = 'Optional'; -} + /** Label that is used to indicate step as completed to screen readers. */ + completedLabel: string = 'Completed'; + + /** Label that is used to indicate step as editable to screen readers. */ + editableLabel: string = 'Editable'; +} /** @docs-private */ export function MAT_STEPPER_INTL_PROVIDER_FACTORY(parentIntl: MatStepperIntl) { @@ -33,5 +37,5 @@ export function MAT_STEPPER_INTL_PROVIDER_FACTORY(parentIntl: MatStepperIntl) { export const MAT_STEPPER_INTL_PROVIDER = { provide: MatStepperIntl, deps: [[new Optional(), new SkipSelf(), MatStepperIntl]], - useFactory: MAT_STEPPER_INTL_PROVIDER_FACTORY + useFactory: MAT_STEPPER_INTL_PROVIDER_FACTORY, }; diff --git a/src/material/stepper/stepper-module.ts b/src/material/stepper/stepper-module.ts index 163023728172..7618e4776fda 100644 --- a/src/material/stepper/stepper-module.ts +++ b/src/material/stepper/stepper-module.ts @@ -19,7 +19,7 @@ import {MatHorizontalStepper, MatStep, MatStepper, MatVerticalStepper} from './s import {MatStepperNext, MatStepperPrevious} from './stepper-button'; import {MatStepperIcon} from './stepper-icon'; import {MAT_STEPPER_INTL_PROVIDER} from './stepper-intl'; - +import {MatStepContent} from './step-content'; @NgModule({ imports: [ @@ -33,8 +33,6 @@ import {MAT_STEPPER_INTL_PROVIDER} from './stepper-intl'; ], exports: [ MatCommonModule, - MatHorizontalStepper, - MatVerticalStepper, MatStep, MatStepLabel, MatStepper, @@ -42,6 +40,7 @@ import {MAT_STEPPER_INTL_PROVIDER} from './stepper-intl'; MatStepperPrevious, MatStepHeader, MatStepperIcon, + MatStepContent, ], declarations: [ MatHorizontalStepper, @@ -53,6 +52,7 @@ import {MAT_STEPPER_INTL_PROVIDER} from './stepper-intl'; MatStepperPrevious, MatStepHeader, MatStepperIcon, + MatStepContent, ], providers: [MAT_STEPPER_INTL_PROVIDER, ErrorStateMatcher], }) diff --git a/src/material/stepper/stepper-vertical.html b/src/material/stepper/stepper-vertical.html deleted file mode 100644 index 36a5db980a56..000000000000 --- a/src/material/stepper/stepper-vertical.html +++ /dev/null @@ -1,37 +0,0 @@ -
- - - -
-
-
- -
-
-
-
diff --git a/src/material/stepper/stepper.e2e.spec.ts b/src/material/stepper/stepper.e2e.spec.ts index c36497521166..9de157ee57bb 100644 --- a/src/material/stepper/stepper.e2e.spec.ts +++ b/src/material/stepper/stepper.e2e.spec.ts @@ -1,11 +1,11 @@ import {browser, by, element, ElementFinder, ExpectedConditions, Key} from 'protractor'; -import {expectFocusOn, expectToExist, pressKeys} from '@angular/cdk/testing/private/e2e'; +import {expectFocusOn, expectToExist, pressKeys} from '../../cdk/testing/private/e2e'; describe('stepper', () => { beforeEach(async () => await browser.get('/stepper')); it('should render a stepper', async () => { - await expectToExist('mat-horizontal-stepper'); + await expectToExist('mat-stepper'); }); describe('basic behavior', () => { @@ -13,24 +13,33 @@ describe('stepper', () => { const previousButton = element.all(by.buttonText('Back')); const nextButton = element.all(by.buttonText('Next')); - expect(await element(by.css('mat-step-header[aria-selected="true"]')).getText()) - .toBe('1\nFill out your name'); + expect(await element(by.css('mat-step-header[aria-selected="true"]')).getText()).toBe( + '1\nFill out your name', + ); await nextButton.get(0).click(); - expect(await element(by.css('mat-step-header[aria-selected="true"]')).getText()) - .toBe('2\nFill out your address'); + expect(await element(by.css('mat-step-header[aria-selected="true"]')).getText()).toBe( + '2\nFill out your address', + ); - await browser.wait(ExpectedConditions.not( - ExpectedConditions.presenceOf(element(by.css('div.mat-ripple-element'))))); + await browser.wait( + ExpectedConditions.not( + ExpectedConditions.presenceOf(element(by.css('div.mat-ripple-element'))), + ), + ); await previousButton.get(0).click(); - expect(await element(by.css('mat-step-header[aria-selected="true"]')).getText()) - .toBe('1\nFill out your name'); + expect(await element(by.css('mat-step-header[aria-selected="true"]')).getText()).toBe( + '1\nFill out your name', + ); - await browser.wait(ExpectedConditions.not( - ExpectedConditions.presenceOf(element(by.css('div.mat-ripple-element'))))); + await browser.wait( + ExpectedConditions.not( + ExpectedConditions.presenceOf(element(by.css('div.mat-ripple-element'))), + ), + ); }); it('should change focus with keyboard interaction', async () => { @@ -68,8 +77,9 @@ describe('stepper', () => { const nextButton = element.all(by.buttonText('Next')); await nextButton.get(0).click(); - expect(await element(by.css('mat-step-header[aria-selected="true"]')).getText()) - .toBe('1\nFill out your name'); + expect(await element(by.css('mat-step-header[aria-selected="true"]')).getText()).toBe( + '1\nFill out your name', + ); }); }); }); diff --git a/src/material/stepper/stepper.html b/src/material/stepper/stepper.html new file mode 100644 index 000000000000..b074d0c2e6e2 --- /dev/null +++ b/src/material/stepper/stepper.html @@ -0,0 +1,75 @@ + + + +
+ + +
+
+
+ +
+
+ +
+
+
+ + + +
+ +
+
+
+ +
+
+
+
+
+ +
+ + + + + diff --git a/src/material/stepper/stepper.md b/src/material/stepper/stepper.md index 460ef67da1f4..229fb7044498 100644 --- a/src/material/stepper/stepper.md +++ b/src/material/stepper/stepper.md @@ -5,17 +5,13 @@ that drives a stepped workflow. Material stepper extends the CDK stepper and has styling. ### Stepper variants -There are two stepper components: `mat-horizontal-stepper` and `mat-vertical-stepper`. They -can be used the same way. The only difference is the orientation of stepper. +There are two stepper variants: `horizontal` and `vertical`. You can switch between the two using +the `orientation` attribute. -`mat-horizontal-stepper` selector can be used to create a horizontal stepper, and -`mat-vertical-stepper` can be used to create a vertical stepper. `mat-step` components need to be -placed inside either one of the two stepper components. - ### Labels If a step's label is only text, then the `label` attribute can be used. #### Label position -For `mat-horizontal-stepper` it's possible to define the position of the label. `end` is the +For a horizontal `mat-stepper` it's possible to define the position of the label. `end` is the default value, while `bottom` will place it under the step icon instead of at its side. This behaviour is controlled by `labelPosition` property. @@ -45,10 +41,10 @@ There are two button directives to support navigation between different steps: "region": "buttons"}) --> ### Linear stepper -The `linear` attribute can be set on `mat-horizontal-stepper` and `mat-vertical-stepper` to create -a linear stepper that requires the user to complete previous steps before proceeding to following -steps. For each `mat-step`, the `stepControl` attribute can be set to the top level -`AbstractControl` that is used to check the validity of the step. +The `linear` attribute can be set on `mat-stepper` to create a linear stepper that requires the +user to complete previous steps before proceeding to following steps. For each `mat-step`, the +`stepControl` attribute can be set to the top level `AbstractControl` that is used to check the +validity of the step. There are two possible approaches. One is using a single form for stepper, and the other is using a different form for each step. @@ -64,7 +60,7 @@ are completed. ```html
- + ...
@@ -79,13 +75,13 @@ are completed.
... -
+
``` #### Using a different form for each step ```html - +
... @@ -96,7 +92,7 @@ are completed. ...
-
+ ``` ### Types of steps @@ -180,14 +176,27 @@ will not affect steppers marked as `linear`. +### Lazy rendering +By default, the stepper will render all of it's content when it's initialized. If you have some +content that you want to defer until the particular step is opened, you can put it inside +an `ng-template` with the `matStepContent` attribute. + + + +### Responsive stepper +If your app supports a wide variety of screens and a stepper's layout doesn't fit a particular +screen size, you can control its `orientation` dynamically to change the layout based on the +viewport. + + + ### Keyboard interaction -- LEFT_ARROW: Focuses the previous step header -- RIGHT_ARROW: Focuses the next step header -- HOME: Focuses the first step header -- END: Focuses the last step header -- ENTER, SPACE: Selects the step that the focus is currently on -- TAB: Focuses the next tabbable element -- SHIFT+TAB: Focuses the previous tabbable element +| Keyboard shortcut | Action | +|------------------------|---------------------------------| +| Left Arrow | Focus the previous step header. | +| Right Arrow | Focus the next step header. | +| Enter | Select the focused step. | +| Space | Select the focused step. | ### Localizing labels Labels used by the stepper are provided through `MatStepperIntl`. Localization of these messages @@ -203,6 +212,8 @@ can be done by providing a subclass with translated values in your application r export class MyApp {} ``` + + ### Accessibility The stepper is treated as a tabbed view for accessibility purposes, so it is given `role="tablist"` by default. The header of step that can be clicked to select the step @@ -211,3 +222,23 @@ is given `role="tab"`, and the content that can be expanded upon selection is gi step content is automatically set based on step selection change. The stepper and each step should be given a meaningful label via `aria-label` or `aria-labelledby`. + +Prefer verticl steppers when building for small screen sizes, as horizontal +steppers typically take up significantly more horizontal space thus introduce +horizontal scrolling. Applications with multiple scrolling dimensions make +content harder to consume for some users. See the [Responsive Stepper section](#responsive-stepper) +above for an example on building a stepper that adjusts its layout based on +viewport size. + +#### Forms +Steppers often contain forms and form controls. If validation errors inside of a +stepper's form prevents moving to another step, make sure that your form +controls communicate error messages to assistive technology. This helps the user +know why they can't advance to another step. You can accomplish this by using +`` with ``, or by using an ARIA live region. + +When a step contains a forms validation error, `MatStepper` will display the +error in the step's header if specified. See the [Error State section](#error-state) +for an example of a stepper with an error message. For non-linear steppers, you +should use an ARIA live region to announce error messages when users navigate +away from a step with an error message. diff --git a/src/material/stepper/stepper.scss b/src/material/stepper/stepper.scss index 05f080e77edd..1d73e0a0178a 100644 --- a/src/material/stepper/stepper.scss +++ b/src/material/stepper/stepper.scss @@ -1,5 +1,7 @@ -@import '../core/style/variables'; -@import './stepper-variables'; +@use 'sass:math'; +@use '../core/style/variables'; +@use './stepper-variables'; +@use '../../cdk/a11y'; .mat-stepper-vertical, .mat-stepper-horizontal { @@ -17,12 +19,12 @@ } .mat-stepper-horizontal-line { - border-top-width: $mat-stepper-line-width; + border-top-width: stepper-variables.$line-width; border-top-style: solid; flex: auto; height: 0; - margin: 0 $mat-stepper-line-gap - $mat-stepper-side-gap; - min-width: $mat-stepper-line-gap + $mat-stepper-side-gap; + margin: 0 stepper-variables.$line-gap - stepper-variables.$side-gap; + min-width: stepper-variables.$line-gap + stepper-variables.$side-gap; .mat-stepper-label-position-bottom & { margin: 0; @@ -32,29 +34,30 @@ } %mat-header-horizontal-line-label-position-bottom { - border-top-width: $mat-stepper-line-width; + $half-side-gap: math.div(stepper-variables.$side-gap, 2); + border-top-width: stepper-variables.$line-width; border-top-style: solid; content: ''; display: inline-block; height: 0; position: absolute; - width: calc(50% - #{$mat-stepper-side-gap / 2 + $mat-stepper-line-gap}); + width: calc(50% - #{$half-side-gap + stepper-variables.$line-gap}); } .mat-horizontal-stepper-header { display: flex; - height: $mat-stepper-header-height; + height: stepper-variables.$header-height; overflow: hidden; align-items: center; - padding: 0 $mat-stepper-side-gap; + padding: 0 stepper-variables.$side-gap; .mat-step-icon { - margin-right: $mat-stepper-line-gap; + margin-right: stepper-variables.$line-gap; flex: none; [dir='rtl'] & { margin-right: 0; - margin-left: $mat-stepper-line-gap; + margin-left: stepper-variables.$line-gap; } } @@ -89,7 +92,7 @@ } & .mat-step-label { - padding: $mat-stepper-label-position-bottom-top-gap 0 0 0; + padding: stepper-variables.$label-position-bottom-top-gap 0 0 0; text-align: center; width: 100%; } @@ -101,14 +104,14 @@ align-items: center; // We can't use `max-height` here, because it breaks the flexbox centering in IE. - height: $mat-stepper-label-header-height; + height: stepper-variables.$label-header-height; .mat-step-icon { - margin-right: $mat-vertical-stepper-content-margin - $mat-stepper-side-gap; + margin-right: stepper-variables.$vertical-stepper-content-margin - stepper-variables.$side-gap; [dir='rtl'] & { margin-right: 0; - margin-left: $mat-vertical-stepper-content-margin - $mat-stepper-side-gap; + margin-left: stepper-variables.$vertical-stepper-content-margin - stepper-variables.$side-gap; } } } @@ -123,18 +126,26 @@ } .mat-horizontal-content-container { + @include a11y.high-contrast(active, off) { + outline: solid 1px; + } + overflow: hidden; - padding: 0 $mat-stepper-side-gap $mat-stepper-side-gap $mat-stepper-side-gap; + padding: 0 stepper-variables.$side-gap stepper-variables.$side-gap stepper-variables.$side-gap; } .mat-vertical-content-container { - margin-left: $mat-vertical-stepper-content-margin; + @include a11y.high-contrast(active, off) { + outline: solid 1px; + } + + margin-left: stepper-variables.$vertical-stepper-content-margin; border: 0; position: relative; [dir='rtl'] & { margin-left: 0; - margin-right: $mat-vertical-stepper-content-margin; + margin-right: stepper-variables.$vertical-stepper-content-margin; } } @@ -142,7 +153,7 @@ content: ''; position: absolute; left: 0; - border-left-width: $mat-stepper-line-width; + border-left-width: stepper-variables.$line-width; border-left-style: solid; [dir='rtl'] & { @@ -157,7 +168,7 @@ } .mat-vertical-content { - padding: 0 $mat-stepper-side-gap $mat-stepper-side-gap $mat-stepper-side-gap; + padding: 0 stepper-variables.$side-gap stepper-variables.$side-gap stepper-variables.$side-gap; } .mat-step:last-child { diff --git a/src/material/stepper/stepper.spec.ts b/src/material/stepper/stepper.spec.ts index b7657dbb6f3e..d01c71c9ab20 100644 --- a/src/material/stepper/stepper.spec.ts +++ b/src/material/stepper/stepper.spec.ts @@ -13,13 +13,9 @@ import { StepperOrientation, STEPPER_GLOBAL_OPTIONS, STEP_STATE, - CdkStep + CdkStep, } from '@angular/cdk/stepper'; -import { - dispatchKeyboardEvent, - createKeyboardEvent, - dispatchEvent, -} from '@angular/cdk/testing/private'; +import {dispatchKeyboardEvent, createKeyboardEvent, dispatchEvent} from '../../cdk/testing/private'; import { Component, DebugElement, @@ -30,6 +26,7 @@ import { ViewChildren, QueryList, ViewChild, + ViewEncapsulation, } from '@angular/core'; import {ComponentFixture, fakeAsync, flush, inject, TestBed} from '@angular/core/testing'; import { @@ -40,12 +37,13 @@ import { ReactiveFormsModule, ValidationErrors, Validators, - FormBuilder + FormBuilder, } from '@angular/forms'; import {MatRipple, ThemePalette} from '@angular/material/core'; import {By} from '@angular/platform-browser'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; -import {Observable, Subject} from 'rxjs'; +import {_supportsShadowDom} from '@angular/cdk/platform'; +import {merge, Observable, Subject} from 'rxjs'; import {map, take} from 'rxjs/operators'; import {MatStepHeader, MatStepperModule} from './index'; import {MatHorizontalStepper, MatStep, MatStepper, MatVerticalStepper} from './stepper'; @@ -54,15 +52,14 @@ import {MatStepperIntl} from './stepper-intl'; import {MatFormFieldModule} from '@angular/material/form-field'; import {MatInputModule} from '../input/input-module'; - const VALID_REGEX = /valid/; -let dir: {value: Direction, change: EventEmitter}; +let dir: {value: Direction; readonly change: EventEmitter}; describe('MatStepper', () => { beforeEach(() => { dir = { value: 'ltr', - change: new EventEmitter() + change: new EventEmitter(), }; }); @@ -75,14 +72,17 @@ describe('MatStepper', () => { }); it('should default to the first step', () => { - let stepperComponent = fixture.debugElement - .query(By.css('mat-vertical-stepper'))!.componentInstance; + const stepperComponent: MatStepper = fixture.debugElement.query( + By.css('mat-stepper'), + )!.componentInstance; + expect(stepperComponent.selectedIndex).toBe(0); }); it('should throw when a negative `selectedIndex` is assigned', () => { - const stepperComponent: MatVerticalStepper = fixture.debugElement - .query(By.css('mat-vertical-stepper'))!.componentInstance; + const stepperComponent: MatStepper = fixture.debugElement.query( + By.css('mat-stepper'), + )!.componentInstance; expect(() => { stepperComponent.selectedIndex = -10; @@ -91,8 +91,9 @@ describe('MatStepper', () => { }); it('should throw when an out-of-bounds `selectedIndex` is assigned', () => { - const stepperComponent: MatVerticalStepper = fixture.debugElement - .query(By.css('mat-vertical-stepper'))!.componentInstance; + const stepperComponent: MatStepper = fixture.debugElement.query( + By.css('mat-stepper'), + )!.componentInstance; expect(() => { stepperComponent.selectedIndex = 1337; @@ -101,9 +102,10 @@ describe('MatStepper', () => { }); it('should change selected index on header click', () => { - let stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); - let stepperComponent = - fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; + const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); + const stepperComponent = fixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; expect(stepperComponent.selectedIndex).toBe(0); expect(stepperComponent.selected instanceof MatStep).toBe(true); @@ -126,28 +128,30 @@ describe('MatStepper', () => { }); it('should set the "tablist" role on stepper', () => { - let stepperEl = fixture.debugElement.query(By.css('mat-vertical-stepper'))!.nativeElement; + const stepperEl = fixture.debugElement.query(By.css('mat-stepper'))!.nativeElement; expect(stepperEl.getAttribute('role')).toBe('tablist'); }); it('should set aria-expanded of content correctly', () => { - let stepContents = fixture.debugElement.queryAll(By.css(`.mat-vertical-stepper-content`)); - let stepperComponent = - fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; - let firstStepContentEl = stepContents[0].nativeElement; + const stepContents = fixture.debugElement.queryAll(By.css(`.mat-vertical-stepper-content`)); + const stepperComponent = fixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; + const firstStepContentEl = stepContents[0].nativeElement; expect(firstStepContentEl.getAttribute('aria-expanded')).toBe('true'); stepperComponent.selectedIndex = 1; fixture.detectChanges(); expect(firstStepContentEl.getAttribute('aria-expanded')).toBe('false'); - let secondStepContentEl = stepContents[1].nativeElement; + const secondStepContentEl = stepContents[1].nativeElement; expect(secondStepContentEl.getAttribute('aria-expanded')).toBe('true'); }); it('should display the correct label', () => { - let stepperComponent = - fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; + const stepperComponent = fixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; let selectedLabel = fixture.nativeElement.querySelector('[aria-selected="true"]'); expect(selectedLabel.textContent).toMatch('Step 1'); @@ -165,27 +169,28 @@ describe('MatStepper', () => { }); it('should go to next available step when the next button is clicked', () => { - let stepperComponent = - fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; + const stepperComponent = fixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; expect(stepperComponent.selectedIndex).toBe(0); - let nextButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperNext))[0].nativeElement; + let nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] + .nativeElement; nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); - nextButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperNext))[1].nativeElement; + nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[1] + .nativeElement; nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(2); - nextButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperNext))[2].nativeElement; + nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[2] + .nativeElement; nextButtonNativeEl.click(); fixture.detectChanges(); @@ -194,32 +199,36 @@ describe('MatStepper', () => { it('should set the next stepper button type to "submit"', () => { const button = fixture.debugElement.query(By.directive(MatStepperNext))!.nativeElement; - expect(button.type).toBe('submit', `Expected the button to have "submit" set as type.`); + expect(button.type) + .withContext(`Expected the button to have "submit" set as type.`) + .toBe('submit'); }); it('should go to previous available step when the previous button is clicked', () => { - let stepperComponent = - fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; + const stepperComponent = fixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; expect(stepperComponent.selectedIndex).toBe(0); stepperComponent.selectedIndex = 2; - let previousButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperPrevious))[2].nativeElement; + let previousButtonNativeEl = fixture.debugElement.queryAll( + By.directive(MatStepperPrevious), + )[2].nativeElement; previousButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); - previousButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperPrevious))[1].nativeElement; + previousButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperPrevious))[1] + .nativeElement; previousButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(0); - previousButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperPrevious))[0].nativeElement; + previousButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperPrevious))[0] + .nativeElement; previousButtonNativeEl.click(); fixture.detectChanges(); @@ -228,12 +237,15 @@ describe('MatStepper', () => { it('should set the previous stepper button type to "button"', () => { const button = fixture.debugElement.query(By.directive(MatStepperPrevious))!.nativeElement; - expect(button.type).toBe('button', `Expected the button to have "button" set as type.`); + expect(button.type) + .withContext(`Expected the button to have "button" set as type.`) + .toBe('button'); }); it('should set the correct step position for animation', () => { - let stepperComponent = - fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; + const stepperComponent = fixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; expect(stepperComponent._getAnimationDirection(0)).toBe('current'); expect(stepperComponent._getAnimationDirection(1)).toBe('next'); @@ -255,11 +267,13 @@ describe('MatStepper', () => { }); it('should not set focus on header of selected step if header is not clicked', () => { - let stepperComponent = - fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; - let stepHeaderEl = fixture.debugElement.queryAll(By.css('mat-step-header'))[1].nativeElement; - let nextButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperNext))[0].nativeElement; + const stepperComponent = fixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; + const stepHeaderEl = fixture.debugElement.queryAll(By.css('mat-step-header'))[1] + .nativeElement; + const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] + .nativeElement; spyOn(stepHeaderEl, 'focus'); nextButtonNativeEl.click(); fixture.detectChanges(); @@ -269,11 +283,39 @@ describe('MatStepper', () => { }); it('should focus next step header if focus is inside the stepper', () => { - let stepperComponent = - fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; - let stepHeaderEl = fixture.debugElement.queryAll(By.css('mat-step-header'))[1].nativeElement; - let nextButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperNext))[0].nativeElement; + const stepperComponent = fixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; + const stepHeaderEl = fixture.debugElement.queryAll(By.css('mat-step-header'))[1] + .nativeElement; + const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] + .nativeElement; + spyOn(stepHeaderEl, 'focus'); + nextButtonNativeEl.focus(); + nextButtonNativeEl.click(); + fixture.detectChanges(); + + expect(stepperComponent.selectedIndex).toBe(1); + expect(stepHeaderEl.focus).toHaveBeenCalled(); + }); + + it('should focus next step header if focus is inside the stepper with shadow DOM', () => { + if (!_supportsShadowDom()) { + return; + } + + fixture.destroy(); + TestBed.resetTestingModule(); + fixture = createComponent(SimpleMatVerticalStepperApp, [], [], ViewEncapsulation.ShadowDom); + fixture.detectChanges(); + + const stepperComponent = fixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; + const stepHeaderEl = fixture.debugElement.queryAll(By.css('mat-step-header'))[1] + .nativeElement; + const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] + .nativeElement; spyOn(stepHeaderEl, 'focus'); nextButtonNativeEl.focus(); nextButtonNativeEl.click(); @@ -284,13 +326,15 @@ describe('MatStepper', () => { }); it('should only be able to return to a previous step if it is editable', () => { - let stepperComponent = - fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; + const stepperComponent = fixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; stepperComponent.selectedIndex = 1; stepperComponent.steps.toArray()[0].editable = false; - let previousButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperPrevious))[1].nativeElement; + const previousButtonNativeEl = fixture.debugElement.queryAll( + By.directive(MatStepperPrevious), + )[1].nativeElement; previousButtonNativeEl.click(); fixture.detectChanges(); @@ -304,10 +348,11 @@ describe('MatStepper', () => { }); it('should set create icon if step is editable and completed', () => { - let stepperComponent = - fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; - let nextButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperNext))[0].nativeElement; + const stepperComponent = fixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; + const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] + .nativeElement; expect(stepperComponent._getIndicatorType(0)).toBe('number'); stepperComponent.steps.toArray()[0].editable = true; nextButtonNativeEl.click(); @@ -317,10 +362,11 @@ describe('MatStepper', () => { }); it('should set done icon if step is not editable and is completed', () => { - let stepperComponent = - fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; - let nextButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperNext))[0].nativeElement; + const stepperComponent = fixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; + const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] + .nativeElement; expect(stepperComponent._getIndicatorType(0)).toBe('number'); stepperComponent.steps.toArray()[0].editable = false; nextButtonNativeEl.click(); @@ -330,11 +376,11 @@ describe('MatStepper', () => { }); it('should emit an event when the enter animation is done', fakeAsync(() => { - let stepper = fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; - let selectionChangeSpy = jasmine.createSpy('selectionChange spy'); - let animationDoneSpy = jasmine.createSpy('animationDone spy'); - let selectionChangeSubscription = stepper.selectionChange.subscribe(selectionChangeSpy); - let animationDoneSubscription = stepper.animationDone.subscribe(animationDoneSpy); + const stepper = fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; + const selectionChangeSpy = jasmine.createSpy('selectionChange spy'); + const animationDoneSpy = jasmine.createSpy('animationDone spy'); + const selectionChangeSubscription = stepper.selectionChange.subscribe(selectionChangeSpy); + const animationDoneSubscription = stepper.animationDone.subscribe(animationDoneSpy); stepper.selectedIndex = 1; fixture.detectChanges(); @@ -352,16 +398,18 @@ describe('MatStepper', () => { })); it('should set the correct aria-posinset and aria-setsize', () => { - const headers = - Array.from(fixture.nativeElement.querySelectorAll('.mat-step-header')); + const headers = Array.from( + fixture.nativeElement.querySelectorAll('.mat-step-header'), + ); expect(headers.map(header => header.getAttribute('aria-posinset'))).toEqual(['1', '2', '3']); expect(headers.every(header => header.getAttribute('aria-setsize') === '3')).toBe(true); }); it('should adjust the index when removing a step before the current one', () => { - const stepperComponent: MatVerticalStepper = fixture.debugElement - .query(By.css('mat-vertical-stepper'))!.componentInstance; + const stepperComponent: MatStepper = fixture.debugElement.query( + By.css('mat-stepper'), + )!.componentInstance; stepperComponent.selectedIndex = 2; fixture.detectChanges(); @@ -388,20 +436,27 @@ describe('MatStepper', () => { }); it('should have a focus indicator', () => { - const stepHeaderNativeElements = - [...fixture.debugElement.nativeElement.querySelectorAll('.mat-vertical-stepper-header')]; + const stepHeaderNativeElements = [ + ...fixture.debugElement.nativeElement.querySelectorAll('.mat-vertical-stepper-header'), + ]; - expect(stepHeaderNativeElements - .every(element => element.classList.contains('mat-focus-indicator'))).toBe(true); + expect( + stepHeaderNativeElements.every(element => element.querySelector('.mat-focus-indicator')), + ).toBe(true); }); + it('should hide the header icons from assistive technology', () => { + const icon = fixture.nativeElement.querySelector('.mat-step-icon span'); + expect(icon.getAttribute('aria-hidden')).toBe('true'); + }); }); describe('basic stepper when attempting to set the selected step too early', () => { it('should not throw', () => { const fixture = createComponent(SimpleMatVerticalStepperApp); - const stepperComponent: MatVerticalStepper = fixture.debugElement - .query(By.css('mat-vertical-stepper'))!.componentInstance; + const stepperComponent: MatStepper = fixture.debugElement.query( + By.css('mat-stepper'), + )!.componentInstance; expect(() => stepperComponent.selected).not.toThrow(); }); @@ -410,10 +465,11 @@ describe('MatStepper', () => { describe('basic stepper when attempting to set the selected step too early', () => { it('should not throw', () => { const fixture = createComponent(SimpleMatVerticalStepperApp); - const stepperComponent: MatVerticalStepper = fixture.debugElement - .query(By.css('mat-vertical-stepper'))!.componentInstance; + const stepperComponent: MatStepper = fixture.debugElement.query( + By.css('mat-stepper'), + )!.componentInstance; - expect(() => stepperComponent.selected = null!).not.toThrow(); + expect(() => (stepperComponent.selected = null!)).not.toThrow(); expect(stepperComponent.selectedIndex).toBe(-1); }); }); @@ -426,10 +482,11 @@ describe('MatStepper', () => { i18nFixture.detectChanges(); }); - it('should re-render when the i18n labels change', inject([MatStepperIntl], + it('should re-render when the i18n labels change', inject( + [MatStepperIntl], (intl: MatStepperIntl) => { - const header = - i18nFixture.debugElement.queryAll(By.css('mat-step-header'))[2].nativeElement; + const header = i18nFixture.debugElement.queryAll(By.css('mat-step-header'))[2] + .nativeElement; const optionalLabel = header.querySelector('.mat-step-optional'); expect(optionalLabel).toBeTruthy(); @@ -440,7 +497,74 @@ describe('MatStepper', () => { i18nFixture.detectChanges(); expect(optionalLabel.textContent).toBe('Valgfri'); - })); + }, + )); + }); + + describe('basic stepper with completed label change', () => { + let fixture: ComponentFixture; + + beforeEach(() => { + fixture = createComponent(SimpleMatHorizontalStepperApp); + fixture.detectChanges(); + }); + + it('should re-render when the completed labels change', inject( + [MatStepperIntl], + (intl: MatStepperIntl) => { + const stepperDebugElement = fixture.debugElement.query(By.directive(MatStepper))!; + const stepperComponent: MatStepper = stepperDebugElement.componentInstance; + + stepperComponent.steps.toArray()[0].editable = false; + stepperComponent.next(); + fixture.detectChanges(); + + const header = stepperDebugElement.nativeElement.querySelector('mat-step-header'); + const completedLabel = header.querySelector('.cdk-visually-hidden'); + + expect(completedLabel).toBeTruthy(); + expect(completedLabel.textContent).toBe('Completed'); + + intl.completedLabel = 'Completada'; + intl.changes.next(); + fixture.detectChanges(); + + expect(completedLabel.textContent).toBe('Completada'); + }, + )); + }); + + describe('basic stepper with editable label change', () => { + let fixture: ComponentFixture; + + beforeEach(() => { + fixture = createComponent(SimpleMatHorizontalStepperApp); + fixture.detectChanges(); + }); + + it('should re-render when the editable label changes', inject( + [MatStepperIntl], + (intl: MatStepperIntl) => { + const stepperDebugElement = fixture.debugElement.query(By.directive(MatStepper))!; + const stepperComponent: MatStepper = stepperDebugElement.componentInstance; + + stepperComponent.steps.toArray()[0].editable = true; + stepperComponent.next(); + fixture.detectChanges(); + + const header = stepperDebugElement.nativeElement.querySelector('mat-step-header'); + const editableLabel = header.querySelector('.cdk-visually-hidden'); + + expect(editableLabel).toBeTruthy(); + expect(editableLabel.textContent).toBe('Editable'); + + intl.editableLabel = 'Modificabile'; + intl.changes.next(); + fixture.detectChanges(); + + expect(editableLabel.textContent).toBe('Modificabile'); + }, + )); }); describe('icon overrides', () => { @@ -495,8 +619,9 @@ describe('MatStepper', () => { }); it('should reverse animation in RTL mode', () => { - let stepperComponent = - fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; + const stepperComponent = fixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; expect(stepperComponent._getAnimationDirection(0)).toBe('current'); expect(stepperComponent._getAnimationDirection(1)).toBe('previous'); @@ -521,15 +646,14 @@ describe('MatStepper', () => { describe('linear stepper', () => { let fixture: ComponentFixture; let testComponent: LinearMatVerticalStepperApp; - let stepperComponent: MatVerticalStepper; + let stepperComponent: MatStepper; beforeEach(() => { fixture = createComponent(LinearMatVerticalStepperApp); fixture.detectChanges(); testComponent = fixture.componentInstance; - stepperComponent = fixture.debugElement - .query(By.css('mat-vertical-stepper'))!.componentInstance; + stepperComponent = fixture.debugElement.query(By.css('mat-stepper'))!.componentInstance; }); it('should have true linear attribute', () => { @@ -543,16 +667,16 @@ describe('MatStepper', () => { expect(testComponent.oneGroup.invalid).toBe(true); expect(stepperComponent.selectedIndex).toBe(0); - let stepHeaderEl = fixture.debugElement - .queryAll(By.css('.mat-vertical-stepper-header'))[1].nativeElement; + const stepHeaderEl = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header'))[1] + .nativeElement; stepHeaderEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(0); - let nextButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperNext))[0].nativeElement; + const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] + .nativeElement; nextButtonNativeEl.click(); fixture.detectChanges(); @@ -567,11 +691,11 @@ describe('MatStepper', () => { }); it('should not move to next step if current step is pending', () => { - let stepHeaderEl = fixture.debugElement - .queryAll(By.css('.mat-vertical-stepper-header'))[2].nativeElement; + const stepHeaderEl = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header'))[2] + .nativeElement; - let nextButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperNext))[1].nativeElement; + const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[1] + .nativeElement; testComponent.oneGroup.get('oneCtrl')!.setValue('input'); testComponent.twoGroup.get('twoCtrl')!.setValue('input'); @@ -616,7 +740,8 @@ describe('MatStepper', () => { }); it('should be able to focus step header upon click if it is unable to be selected', () => { - let stepHeaderEl = fixture.debugElement.queryAll(By.css('mat-step-header'))[1].nativeElement; + const stepHeaderEl = fixture.debugElement.queryAll(By.css('mat-step-header'))[1] + .nativeElement; fixture.detectChanges(); @@ -636,13 +761,14 @@ describe('MatStepper', () => { expect(stepperComponent.selectedIndex).toBe(2); expect(testComponent.threeGroup.get('threeCtrl')!.valid).toBe(true); - const nextButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperNext))[2].nativeElement; + const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[2] + .nativeElement; nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex) - .toBe(3, 'Expected selectedIndex to change when optional step input is empty.'); + .withContext('Expected selectedIndex to change when optional step input is empty.') + .toBe(3); stepperComponent.selectedIndex = 2; testComponent.threeGroup.get('threeCtrl')!.setValue('input'); @@ -651,7 +777,8 @@ describe('MatStepper', () => { expect(testComponent.threeGroup.get('threeCtrl')!.valid).toBe(false); expect(stepperComponent.selectedIndex) - .toBe(3, 'Expected selectedIndex to change when optional step input is invalid.'); + .withContext('Expected selectedIndex to change when optional step input is invalid.') + .toBe(3); }); it('should be able to reset the stepper to its initial state', () => { @@ -727,14 +854,18 @@ describe('MatStepper', () => { fillOutStepper(); expect(steps[2].completed) - .toBe(true, 'Expected third step to be considered complete after the first run through.'); + .withContext('Expected third step to be considered complete after the first run through.') + .toBe(true); stepperComponent.reset(); fixture.detectChanges(); fillOutStepper(); - expect(steps[2].completed).toBe(true, - 'Expected third step to be considered complete when doing a run after a reset.'); + expect(steps[2].completed) + .withContext( + 'Expected third step to be considered complete when doing a run after ' + 'a reset.', + ) + .toBe(true); }); it('should be able to skip past the current step if a custom `completed` value is set', () => { @@ -743,8 +874,8 @@ describe('MatStepper', () => { expect(testComponent.oneGroup.valid).toBe(false); expect(stepperComponent.selectedIndex).toBe(0); - const nextButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperNext))[0].nativeElement; + const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] + .nativeElement; nextButtonNativeEl.click(); fixture.detectChanges(); @@ -757,17 +888,29 @@ describe('MatStepper', () => { expect(testComponent.oneGroup.valid).toBe(false); expect(stepperComponent.selectedIndex).toBe(1); }); + + it('should set aria-disabled if the user is not able to navigate to a step', () => { + const stepHeaders = Array.from( + fixture.nativeElement.querySelectorAll('.mat-vertical-stepper-header'), + ); + + expect(stepHeaders.map(step => step.getAttribute('aria-disabled'))).toEqual([ + null, + 'true', + 'true', + 'true', + ]); + }); }); describe('linear stepper with a pre-defined selectedIndex', () => { let preselectedFixture: ComponentFixture; - let stepper: MatHorizontalStepper; + let stepper: MatStepper; beforeEach(() => { preselectedFixture = createComponent(SimplePreselectedMatHorizontalStepperApp); preselectedFixture.detectChanges(); - stepper = preselectedFixture.debugElement - .query(By.directive(MatHorizontalStepper))!.componentInstance; + stepper = preselectedFixture.debugElement.query(By.directive(MatStepper))!.componentInstance; }); it('should not throw', () => { @@ -790,11 +933,13 @@ describe('MatStepper', () => { noStepControlFixture.detectChanges(); }); it('should not move to the next step if the current one is not completed ', () => { - const stepper: MatHorizontalStepper = noStepControlFixture.debugElement - .query(By.directive(MatHorizontalStepper))!.componentInstance; + const stepper: MatStepper = noStepControlFixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; - const headers = noStepControlFixture.debugElement - .queryAll(By.css('.mat-horizontal-stepper-header')); + const headers = noStepControlFixture.debugElement.queryAll( + By.css('.mat-horizontal-stepper-header'), + ); expect(stepper.selectedIndex).toBe(0); @@ -808,61 +953,69 @@ describe('MatStepper', () => { describe('linear stepper with `stepControl`', () => { let controlAndBindingFixture: ComponentFixture; beforeEach(() => { - controlAndBindingFixture = - createComponent(SimpleStepperWithStepControlAndCompletedBinding); + controlAndBindingFixture = createComponent(SimpleStepperWithStepControlAndCompletedBinding); controlAndBindingFixture.detectChanges(); }); it('should have the `stepControl` take precedence when `completed` is set', () => { - expect(controlAndBindingFixture.componentInstance.steps[0].control.valid).toBe(true); - expect(controlAndBindingFixture.componentInstance.steps[0].completed).toBe(false); + expect(controlAndBindingFixture.componentInstance.steps[0].control.valid).toBe(true); + expect(controlAndBindingFixture.componentInstance.steps[0].completed).toBe(false); - const stepper: MatHorizontalStepper = controlAndBindingFixture.debugElement - .query(By.directive(MatHorizontalStepper))!.componentInstance; + const stepper: MatStepper = controlAndBindingFixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; - const headers = controlAndBindingFixture.debugElement - .queryAll(By.css('.mat-horizontal-stepper-header')); + const headers = controlAndBindingFixture.debugElement.queryAll( + By.css('.mat-horizontal-stepper-header'), + ); - expect(stepper.selectedIndex).toBe(0); + expect(stepper.selectedIndex).toBe(0); - headers[1].nativeElement.click(); - controlAndBindingFixture.detectChanges(); + headers[1].nativeElement.click(); + controlAndBindingFixture.detectChanges(); - expect(stepper.selectedIndex).toBe(1); - }); + expect(stepper.selectedIndex).toBe(1); + }); }); describe('vertical stepper', () => { + it('should be able to use the legacy classes in queries', () => { + const fixture = createComponent(SimpleMatVerticalStepperApp); + fixture.detectChanges(); + + expect(fixture.componentInstance.legacyTokenStepper).toBeTruthy(); + }); + it('should set the aria-orientation to "vertical"', () => { - let fixture = createComponent(SimpleMatVerticalStepperApp); + const fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); - let stepperEl = fixture.debugElement.query(By.css('mat-vertical-stepper'))!.nativeElement; + const stepperEl = fixture.debugElement.query(By.css('mat-stepper'))!.nativeElement; expect(stepperEl.getAttribute('aria-orientation')).toBe('vertical'); }); it('should support using the left/right arrows to move focus', () => { - let fixture = createComponent(SimpleMatVerticalStepperApp); + const fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); - let stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); + const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); assertCorrectKeyboardInteraction(fixture, stepHeaders, 'horizontal'); }); it('should support using the up/down arrows to move focus', () => { - let fixture = createComponent(SimpleMatVerticalStepperApp); + const fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); - let stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); + const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); assertCorrectKeyboardInteraction(fixture, stepHeaders, 'vertical'); }); it('should reverse arrow key focus in RTL mode', () => { dir.value = 'rtl'; - let fixture = createComponent(SimpleMatVerticalStepperApp); + const fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); - let stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); + const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); assertArrowKeyInteractionInRtl(fixture, stepHeaders); }); @@ -872,7 +1025,8 @@ describe('MatStepper', () => { const stepHeaders = fixture.debugElement.queryAll(By.directive(MatStepHeader)); const headerRipples = stepHeaders.map(headerDebugEl => - headerDebugEl.query(By.directive(MatRipple))!.injector.get(MatRipple)); + headerDebugEl.query(By.directive(MatRipple))!.injector.get(MatRipple), + ); expect(headerRipples.every(ripple => ripple.disabled)).toBe(false); @@ -899,8 +1053,9 @@ describe('MatStepper', () => { const fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); - const headers = - Array.from(fixture.nativeElement.querySelectorAll('.mat-step-header')); + const headers = Array.from( + fixture.nativeElement.querySelectorAll('.mat-step-header'), + ); expect(headers.every(element => element.classList.contains('mat-primary'))).toBe(true); expect(headers.some(element => element.classList.contains('mat-accent'))).toBe(false); @@ -918,8 +1073,9 @@ describe('MatStepper', () => { const fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); - const headers = - Array.from(fixture.nativeElement.querySelectorAll('.mat-step-header')); + const headers = Array.from( + fixture.nativeElement.querySelectorAll('.mat-step-header'), + ); expect(headers.every(element => element.classList.contains('mat-primary'))).toBe(true); @@ -934,36 +1090,53 @@ describe('MatStepper', () => { }); describe('horizontal stepper', () => { + it('should be able to use the legacy classes in queries', () => { + const fixture = createComponent(SimpleMatHorizontalStepperApp); + fixture.detectChanges(); + + expect(fixture.componentInstance.legacyTokenStepper).toBeTruthy(); + }); + it('should set the aria-orientation to "horizontal"', () => { - let fixture = createComponent(SimpleMatHorizontalStepperApp); + const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); - let stepperEl = fixture.debugElement.query(By.css('mat-horizontal-stepper'))!.nativeElement; + const stepperEl = fixture.debugElement.query(By.css('mat-stepper'))!.nativeElement; expect(stepperEl.getAttribute('aria-orientation')).toBe('horizontal'); }); it('should support using the left/right arrows to move focus', () => { - let fixture = createComponent(SimpleMatHorizontalStepperApp); + const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); - let stepHeaders = fixture.debugElement.queryAll(By.css('.mat-horizontal-stepper-header')); + const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-horizontal-stepper-header')); assertCorrectKeyboardInteraction(fixture, stepHeaders, 'horizontal'); }); it('should reverse arrow key focus in RTL mode', () => { dir.value = 'rtl'; - let fixture = createComponent(SimpleMatHorizontalStepperApp); + const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); - let stepHeaders = fixture.debugElement.queryAll(By.css('.mat-horizontal-stepper-header')); + const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-horizontal-stepper-header')); assertArrowKeyInteractionInRtl(fixture, stepHeaders); }); + it('should maintain the correct navigation order when a step is added later on', () => { + const fixture = createComponent(HorizontalStepperWithDelayedStep); + fixture.detectChanges(); + fixture.componentInstance.renderSecondStep = true; + fixture.detectChanges(); + + const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-horizontal-stepper-header')); + assertCorrectKeyboardInteraction(fixture, stepHeaders, 'horizontal'); + }); + it('should reverse arrow key focus when switching into RTL after init', () => { - let fixture = createComponent(SimpleMatHorizontalStepperApp); + const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); - let stepHeaders = fixture.debugElement.queryAll(By.css('.mat-horizontal-stepper-header')); + const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-horizontal-stepper-header')); assertCorrectKeyboardInteraction(fixture, stepHeaders, 'horizontal'); dir.value = 'rtl'; @@ -979,7 +1152,8 @@ describe('MatStepper', () => { const stepHeaders = fixture.debugElement.queryAll(By.directive(MatStepHeader)); const headerRipples = stepHeaders.map(headerDebugEl => - headerDebugEl.query(By.directive(MatRipple))!.injector.get(MatRipple)); + headerDebugEl.query(By.directive(MatRipple))!.injector.get(MatRipple), + ); expect(headerRipples.every(ripple => ripple.disabled)).toBe(false); @@ -993,8 +1167,9 @@ describe('MatStepper', () => { const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); - const headers = - Array.from(fixture.nativeElement.querySelectorAll('.mat-step-header')); + const headers = Array.from( + fixture.nativeElement.querySelectorAll('.mat-step-header'), + ); expect(headers.every(element => element.classList.contains('mat-primary'))).toBe(true); expect(headers.some(element => element.classList.contains('mat-accent'))).toBe(false); @@ -1012,8 +1187,9 @@ describe('MatStepper', () => { const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); - const headers = - Array.from(fixture.nativeElement.querySelectorAll('.mat-step-header')); + const headers = Array.from( + fixture.nativeElement.querySelectorAll('.mat-step-header'), + ); expect(headers.every(element => element.classList.contains('mat-primary'))).toBe(true); @@ -1025,6 +1201,57 @@ describe('MatStepper', () => { expect(headers[2].classList.contains('mat-primary')).toBe(true); expect(headers[1].classList.contains('mat-accent')).toBe(true); }); + + it('should be able to mark all steps as interacted', () => { + const fixture = createComponent(SimpleMatHorizontalStepperApp); + fixture.detectChanges(); + + const stepper: MatStepper = fixture.debugElement.query( + By.directive(MatStepper), + ).componentInstance; + + expect(stepper.steps.map(step => step.interacted)).toEqual([false, false, false]); + + stepper.next(); + fixture.detectChanges(); + expect(stepper.steps.map(step => step.interacted)).toEqual([true, false, false]); + + stepper.next(); + fixture.detectChanges(); + expect(stepper.steps.map(step => step.interacted)).toEqual([true, true, false]); + + stepper.next(); + fixture.detectChanges(); + expect(stepper.steps.map(step => step.interacted)).toEqual([true, true, true]); + }); + + it('should emit when the user has interacted with a step', () => { + const fixture = createComponent(SimpleMatHorizontalStepperApp); + fixture.detectChanges(); + + const stepper: MatStepper = fixture.debugElement.query( + By.directive(MatStepper), + ).componentInstance; + const interactedSteps: number[] = []; + const subscription = merge(...stepper.steps.map(step => step.interactedStream)).subscribe( + step => interactedSteps.push(stepper.steps.toArray().indexOf(step as MatStep)), + ); + + expect(interactedSteps).toEqual([]); + + stepper.next(); + fixture.detectChanges(); + expect(interactedSteps).toEqual([0]); + + stepper.next(); + fixture.detectChanges(); + expect(interactedSteps).toEqual([0, 1]); + + stepper.next(); + fixture.detectChanges(); + expect(interactedSteps).toEqual([0, 1, 2]); + subscription.unsubscribe(); + }); }); describe('linear stepper with valid step', () => { @@ -1037,8 +1264,7 @@ describe('MatStepper', () => { fixture.detectChanges(); testComponent = fixture.componentInstance; - stepper = fixture.debugElement - .query(By.css('mat-horizontal-stepper'))!.componentInstance; + stepper = fixture.debugElement.query(By.css('mat-stepper'))!.componentInstance; }); it('must be visited if not optional', () => { @@ -1101,30 +1327,31 @@ describe('MatStepper', () => { expect(stepHeader.getAttribute('aria-label')).toBe('First step'); expect(stepHeader.hasAttribute('aria-labelledby')).toBe(false); }); - }); describe('stepper with error state', () => { let fixture: ComponentFixture; let stepper: MatStepper; - beforeEach(() => { + function createFixture(showErrorByDefault: boolean | undefined) { fixture = createComponent( MatHorizontalStepperWithErrorsApp, - [{ - provide: STEPPER_GLOBAL_OPTIONS, - useValue: {showError: true} - }], - [MatFormFieldModule, MatInputModule] + [ + { + provide: STEPPER_GLOBAL_OPTIONS, + useValue: {showError: showErrorByDefault}, + }, + ], + [MatFormFieldModule, MatInputModule], ); fixture.detectChanges(); - stepper = fixture.debugElement - .query(By.css('mat-horizontal-stepper'))!.componentInstance; - }); + stepper = fixture.debugElement.query(By.css('mat-stepper'))!.componentInstance; + } it('should show error state', () => { - const nextButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperNext))[0].nativeElement; + createFixture(true); + const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] + .nativeElement; stepper.selectedIndex = 1; stepper.steps.first.hasError = true; @@ -1135,8 +1362,9 @@ describe('MatStepper', () => { }); it('should respect a custom falsy hasError value', () => { - const nextButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperNext))[0].nativeElement; + createFixture(true); + const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] + .nativeElement; stepper.selectedIndex = 1; nextButtonNativeEl.click(); @@ -1150,6 +1378,18 @@ describe('MatStepper', () => { expect(stepper._getIndicatorType(0)).not.toBe(STEP_STATE.ERROR); }); + it('should show error state if explicitly enabled, even when disabled globally', () => { + createFixture(undefined); + const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] + .nativeElement; + + stepper.selectedIndex = 1; + stepper.steps.first.hasError = true; + nextButtonNativeEl.click(); + fixture.detectChanges(); + + expect(stepper._getIndicatorType(0)).toBe(STEP_STATE.ERROR); + }); }); describe('stepper using Material UI Guideline logic', () => { @@ -1159,20 +1399,21 @@ describe('MatStepper', () => { beforeEach(() => { fixture = createComponent( MatHorizontalStepperWithErrorsApp, - [{ - provide: STEPPER_GLOBAL_OPTIONS, - useValue: {displayDefaultIndicatorType: false} - }], - [MatFormFieldModule, MatInputModule] + [ + { + provide: STEPPER_GLOBAL_OPTIONS, + useValue: {displayDefaultIndicatorType: false}, + }, + ], + [MatFormFieldModule, MatInputModule], ); fixture.detectChanges(); - stepper = fixture.debugElement - .query(By.css('mat-horizontal-stepper'))!.componentInstance; + stepper = fixture.debugElement.query(By.css('mat-stepper'))!.componentInstance; }); it('should show done state when step is completed and its not the current step', () => { - let nextButtonNativeEl = fixture.debugElement - .queryAll(By.directive(MatStepperNext))[0].nativeElement; + const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] + .nativeElement; stepper.selectedIndex = 1; stepper.steps.first.completed = true; @@ -1197,8 +1438,9 @@ describe('MatStepper', () => { fixture.detectChanges(); const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); - const stepperComponent = - fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; + const stepperComponent = fixture.debugElement.query( + By.directive(MatStepper), + )!.componentInstance; expect(stepperComponent.selectedIndex).toBe(0); expect(stepperComponent.selected instanceof MatStep).toBe(true); @@ -1261,7 +1503,6 @@ describe('MatStepper', () => { expect(headers[2].textContent).toContain('III'); }); - }); it('should be able to toggle steps via ngIf', () => { @@ -1285,32 +1526,71 @@ describe('MatStepper', () => { expect(steppers[1].steps.length).toBe(2); }); - it('should not throw when trying to change steps after initializing to an out-of-bounds index', - () => { - const fixture = createComponent(StepperWithStaticOutOfBoundsIndex); + it('should not throw when trying to change steps after initializing to an out-of-bounds index', () => { + const fixture = createComponent(StepperWithStaticOutOfBoundsIndex); + fixture.detectChanges(); + const stepper = fixture.componentInstance.stepper; + + expect(stepper.selectedIndex).toBe(0); + expect(stepper.selected).toBeTruthy(); + + expect(() => { + stepper.selectedIndex = 1; fixture.detectChanges(); - const stepper = fixture.componentInstance.stepper; + }).not.toThrow(); - expect(stepper.selectedIndex).toBe(0); - expect(stepper.selected).toBeTruthy(); + expect(stepper.selectedIndex).toBe(1); + expect(stepper.selected).toBeTruthy(); + }); - expect(() => { - stepper.selectedIndex = 1; - fixture.detectChanges(); - }).not.toThrow(); + describe('stepper with lazy content', () => { + it('should render the content of the selected step on init', () => { + const fixture = createComponent(StepperWithLazyContent); + const element = fixture.nativeElement; + fixture.componentInstance.selectedIndex = 1; + fixture.detectChanges(); - expect(stepper.selectedIndex).toBe(1); - expect(stepper.selected).toBeTruthy(); + expect(element.textContent).not.toContain('Step 1 content'); + expect(element.textContent).toContain('Step 2 content'); + expect(element.textContent).not.toContain('Step 3 content'); + }); + + it('should render the content of steps when the user navigates to them', () => { + const fixture = createComponent(StepperWithLazyContent); + const element = fixture.nativeElement; + fixture.componentInstance.selectedIndex = 0; + fixture.detectChanges(); + + expect(element.textContent).toContain('Step 1 content'); + expect(element.textContent).not.toContain('Step 2 content'); + expect(element.textContent).not.toContain('Step 3 content'); + + fixture.componentInstance.selectedIndex = 1; + fixture.detectChanges(); + + expect(element.textContent).toContain('Step 1 content'); + expect(element.textContent).toContain('Step 2 content'); + expect(element.textContent).not.toContain('Step 3 content'); + + fixture.componentInstance.selectedIndex = 2; + fixture.detectChanges(); + + expect(element.textContent).toContain('Step 1 content'); + expect(element.textContent).toContain('Step 2 content'); + expect(element.textContent).toContain('Step 3 content'); }); + }); }); /** Asserts that keyboard interaction works correctly. */ -function assertCorrectKeyboardInteraction(fixture: ComponentFixture, - stepHeaders: DebugElement[], - orientation: StepperOrientation) { - let stepperComponent = fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; - let nextKey = orientation === 'vertical' ? DOWN_ARROW : RIGHT_ARROW; - let prevKey = orientation === 'vertical' ? UP_ARROW : LEFT_ARROW; +function assertCorrectKeyboardInteraction( + fixture: ComponentFixture, + stepHeaders: DebugElement[], + orientation: StepperOrientation, +) { + const stepperComponent = fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; + const nextKey = orientation === 'vertical' ? DOWN_ARROW : RIGHT_ARROW; + const prevKey = orientation === 'vertical' ? UP_ARROW : LEFT_ARROW; expect(stepperComponent._getFocusIndex()).toBe(0); expect(stepperComponent.selectedIndex).toBe(0); @@ -1320,28 +1600,39 @@ function assertCorrectKeyboardInteraction(fixture: ComponentFixture, fixture.detectChanges(); expect(stepperComponent._getFocusIndex()) - .toBe(1, 'Expected index of focused step to increase by 1 after pressing the next key.'); + .withContext('Expected index of focused step to increase by 1 after pressing the next key.') + .toBe(1); expect(stepperComponent.selectedIndex) - .toBe(0, 'Expected index of selected step to remain unchanged after pressing the next key.'); + .withContext('Expected index of selected step to remain unchanged after pressing the next key.') + .toBe(0); stepHeaderEl = stepHeaders[1].nativeElement; dispatchKeyboardEvent(stepHeaderEl, 'keydown', ENTER); fixture.detectChanges(); expect(stepperComponent._getFocusIndex()) - .toBe(1, 'Expected index of focused step to remain unchanged after ENTER event.'); + .withContext('Expected index of focused step to remain unchanged after ENTER event.') + .toBe(1); expect(stepperComponent.selectedIndex) - .toBe(1, - 'Expected index of selected step to change to index of focused step after ENTER event.'); + .withContext( + 'Expected index of selected step to change to index of focused step ' + 'after ENTER event.', + ) + .toBe(1); stepHeaderEl = stepHeaders[1].nativeElement; dispatchKeyboardEvent(stepHeaderEl, 'keydown', prevKey); fixture.detectChanges(); expect(stepperComponent._getFocusIndex()) - .toBe(0, 'Expected index of focused step to decrease by 1 after pressing the previous key.'); - expect(stepperComponent.selectedIndex).toBe(1, - 'Expected index of selected step to remain unchanged after pressing the previous key.'); + .withContext( + 'Expected index of focused step to decrease by 1 after pressing the ' + 'previous key.', + ) + .toBe(0); + expect(stepperComponent.selectedIndex) + .withContext( + 'Expected index of selected step to remain unchanged after pressing the ' + 'previous key.', + ) + .toBe(1); // When the focus is on the last step and right arrow key is pressed, the focus should cycle // through to the first step. @@ -1350,36 +1641,54 @@ function assertCorrectKeyboardInteraction(fixture: ComponentFixture, dispatchKeyboardEvent(stepHeaderEl, 'keydown', nextKey); fixture.detectChanges(); - expect(stepperComponent._getFocusIndex()).toBe(0, - 'Expected index of focused step to cycle through to index 0 after pressing the next key.'); + expect(stepperComponent._getFocusIndex()) + .withContext( + 'Expected index of focused step to cycle through to index 0 after pressing ' + + 'the next key.', + ) + .toBe(0); expect(stepperComponent.selectedIndex) - .toBe(1, 'Expected index of selected step to remain unchanged after pressing the next key.'); + .withContext( + 'Expected index of selected step to remain unchanged after pressing ' + 'the next key.', + ) + .toBe(1); stepHeaderEl = stepHeaders[0].nativeElement; dispatchKeyboardEvent(stepHeaderEl, 'keydown', SPACE); fixture.detectChanges(); expect(stepperComponent._getFocusIndex()) - .toBe(0, 'Expected index of focused to remain unchanged after SPACE event.'); + .withContext('Expected index of focused to remain unchanged after SPACE event.') + .toBe(0); expect(stepperComponent.selectedIndex) - .toBe(0, - 'Expected index of selected step to change to index of focused step after SPACE event.'); + .withContext( + 'Expected index of selected step to change to index of focused step ' + 'after SPACE event.', + ) + .toBe(0); const endEvent = dispatchKeyboardEvent(stepHeaderEl, 'keydown', END); expect(stepperComponent._getFocusIndex()) - .toBe(stepHeaders.length - 1, 'Expected last step to be focused when pressing END.'); - expect(endEvent.defaultPrevented).toBe(true, 'Expected default END action to be prevented.'); + .withContext('Expected last step to be focused when pressing END.') + .toBe(stepHeaders.length - 1); + expect(endEvent.defaultPrevented) + .withContext('Expected default END action to be prevented.') + .toBe(true); const homeEvent = dispatchKeyboardEvent(stepHeaderEl, 'keydown', HOME); expect(stepperComponent._getFocusIndex()) - .toBe(0, 'Expected first step to be focused when pressing HOME.'); - expect(homeEvent.defaultPrevented).toBe(true, 'Expected default HOME action to be prevented.'); + .withContext('Expected first step to be focused when pressing HOME.') + .toBe(0); + expect(homeEvent.defaultPrevented) + .withContext('Expected default HOME action to be prevented.') + .toBe(true); } /** Asserts that arrow key direction works correctly in RTL mode. */ -function assertArrowKeyInteractionInRtl(fixture: ComponentFixture, - stepHeaders: DebugElement[]) { - let stepperComponent = fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; +function assertArrowKeyInteractionInRtl( + fixture: ComponentFixture, + stepHeaders: DebugElement[], +) { + const stepperComponent = fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; expect(stepperComponent._getFocusIndex()).toBe(0); @@ -1397,24 +1706,35 @@ function assertArrowKeyInteractionInRtl(fixture: ComponentFixture, } /** Asserts that keyboard interaction works correctly when the user is pressing a modifier key. */ -function assertSelectKeyWithModifierInteraction(fixture: ComponentFixture, - stepHeaders: DebugElement[], - orientation: StepperOrientation, - selectionKey: number) { +function assertSelectKeyWithModifierInteraction( + fixture: ComponentFixture, + stepHeaders: DebugElement[], + orientation: StepperOrientation, + selectionKey: number, +) { const stepperComponent = fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; const modifiers = ['altKey', 'shiftKey', 'ctrlKey', 'metaKey']; expect(stepperComponent._getFocusIndex()).toBe(0); expect(stepperComponent.selectedIndex).toBe(0); - dispatchKeyboardEvent(stepHeaders[0].nativeElement, 'keydown', - orientation === 'vertical' ? DOWN_ARROW : RIGHT_ARROW); + dispatchKeyboardEvent( + stepHeaders[0].nativeElement, + 'keydown', + orientation === 'vertical' ? DOWN_ARROW : RIGHT_ARROW, + ); fixture.detectChanges(); expect(stepperComponent._getFocusIndex()) - .toBe(1, 'Expected index of focused step to increase by 1 after pressing the next key.'); + .withContext( + 'Expected index of focused step to increase by 1 after pressing ' + 'the next key.', + ) + .toBe(1); expect(stepperComponent.selectedIndex) - .toBe(0, 'Expected index of selected step to remain unchanged after pressing the next key.'); + .withContext( + 'Expected index of selected step to remain unchanged after pressing ' + 'the next key.', + ) + .toBe(0); modifiers.forEach(modifier => { const event = createKeyboardEvent('keydown', selectionKey); @@ -1422,8 +1742,12 @@ function assertSelectKeyWithModifierInteraction(fixture: ComponentFixture, dispatchEvent(stepHeaders[1].nativeElement, event); fixture.detectChanges(); - expect(stepperComponent.selectedIndex).toBe(0, `Expected selected index to remain unchanged ` + - `when pressing the selection key with ${modifier} modifier.`); + expect(stepperComponent.selectedIndex) + .withContext( + `Expected selected index to remain unchanged ` + + `when pressing the selection key with ${modifier} modifier.`, + ) + .toBe(0); expect(event.defaultPrevented).toBe(false); }); } @@ -1431,36 +1755,40 @@ function assertSelectKeyWithModifierInteraction(fixture: ComponentFixture, function asyncValidator(minLength: number, validationTrigger: Subject): AsyncValidatorFn { return (control: AbstractControl): Observable => { return validationTrigger.pipe( - map(() => control.value && control.value.length >= minLength ? null : {asyncValidation: {}}), - take(1) + map(() => + control.value && control.value.length >= minLength ? null : {asyncValidation: {}}, + ), + take(1), ); }; } -function createComponent(component: Type, +function createComponent( + component: Type, providers: Provider[] = [], - imports: any[] = []): ComponentFixture { + imports: any[] = [], + encapsulation?: ViewEncapsulation, +): ComponentFixture { TestBed.configureTestingModule({ - imports: [ - MatStepperModule, - NoopAnimationsModule, - ReactiveFormsModule, - ...imports - ], + imports: [MatStepperModule, NoopAnimationsModule, ReactiveFormsModule, ...imports], declarations: [component], - providers: [ - {provide: Directionality, useFactory: () => dir}, - ...providers - ], - }).compileComponents(); + providers: [{provide: Directionality, useFactory: () => dir}, ...providers], + }); + + if (encapsulation != null) { + TestBed.overrideComponent(component, { + set: {encapsulation}, + }); + } + TestBed.compileComponents(); return TestBed.createComponent(component); } @Component({ template: `
- + Step 1 @@ -1482,14 +1810,14 @@ function createComponent(component: Type, - +
- ` + `, }) class MatHorizontalStepperWithErrorsApp implements OnInit { formGroup: FormGroup; - constructor(private _formBuilder: FormBuilder) { } + constructor(private _formBuilder: FormBuilder) {} ngOnInit() { this.formGroup = this._formBuilder.group({ @@ -1501,7 +1829,7 @@ class MatHorizontalStepperWithErrorsApp implements OnInit { @Component({ template: ` - + Step 1 Content 1 @@ -1525,10 +1853,11 @@ class MatHorizontalStepperWithErrorsApp implements OnInit { - - ` + + `, }) class SimpleMatHorizontalStepperApp { + @ViewChild(MatHorizontalStepper) legacyTokenStepper: MatHorizontalStepper; inputLabel = 'Step 3'; disableRipple = false; stepperTheme: ThemePalette; @@ -1537,7 +1866,7 @@ class SimpleMatHorizontalStepperApp { @Component({ template: ` - + Step 1 Content 1 @@ -1561,10 +1890,11 @@ class SimpleMatHorizontalStepperApp { - - ` + + `, }) class SimpleMatVerticalStepperApp { + @ViewChild(MatVerticalStepper) legacyTokenStepper: MatVerticalStepper; inputLabel = 'Step 3'; showStepTwo = true; disableRipple = false; @@ -1574,7 +1904,7 @@ class SimpleMatVerticalStepperApp { @Component({ template: ` - +
Step one @@ -1608,8 +1938,8 @@ class SimpleMatVerticalStepperApp { Done - - ` + + `, }) class LinearMatVerticalStepperApp implements OnInit { oneGroup: FormGroup; @@ -1620,25 +1950,25 @@ class LinearMatVerticalStepperApp implements OnInit { ngOnInit() { this.oneGroup = new FormGroup({ - oneCtrl: new FormControl('', Validators.required) + oneCtrl: new FormControl('', Validators.required), }); this.twoGroup = new FormGroup({ - twoCtrl: new FormControl('', Validators.required, asyncValidator(3, this.validationTrigger)) + twoCtrl: new FormControl('', Validators.required, asyncValidator(3, this.validationTrigger)), }); this.threeGroup = new FormGroup({ - threeCtrl: new FormControl('', Validators.pattern(VALID_REGEX)) + threeCtrl: new FormControl('', Validators.pattern(VALID_REGEX)), }); } } @Component({ template: ` - + - - ` + + `, }) class SimplePreselectedMatHorizontalStepperApp { index = 0; @@ -1646,44 +1976,44 @@ class SimplePreselectedMatHorizontalStepperApp { @Component({ template: ` - + - - ` + + `, }) class SimpleStepperWithoutStepControl { steps = [ {label: 'One', completed: false}, {label: 'Two', completed: false}, - {label: 'Three', completed: false} + {label: 'Three', completed: false}, ]; } @Component({ template: ` - + - - ` + + `, }) class SimpleStepperWithStepControlAndCompletedBinding { steps = [ {label: 'One', completed: false, control: new FormControl()}, {label: 'Two', completed: false, control: new FormControl()}, - {label: 'Three', completed: false, control: new FormControl()} + {label: 'Three', completed: false, control: new FormControl()}, ]; } @Component({ template: ` - + Custom edit Custom done @@ -1693,8 +2023,8 @@ class SimpleStepperWithStepControlAndCompletedBinding { Content 1 Content 2 Content 3 - -` + +`, }) class IconOverridesStepper { getRomanNumeral(value: number) { @@ -1707,7 +2037,7 @@ class IconOverridesStepper { 6: 'VI', 7: 'VII', 8: 'VIII', - 9: 'IX' + 9: 'IX', }; return numberMap[value]; @@ -1716,7 +2046,7 @@ class IconOverridesStepper { @Component({ template: ` - + Custom edit Custom done @@ -1728,58 +2058,53 @@ class IconOverridesStepper { Content 1 Content 2 Content 3 - -` + +`, }) -class IndirectDescendantIconOverridesStepper extends IconOverridesStepper { -} +class IndirectDescendantIconOverridesStepper extends IconOverridesStepper {} @Component({ template: ` - + - - ` + + `, }) class LinearStepperWithValidOptionalStep { controls = [0, 0, 0].map(() => new FormControl()); step2Optional = false; } - @Component({ template: ` - + - - ` + + `, }) class StepperWithAriaInputs { ariaLabel: string; ariaLabelledby: string; } - @Component({ template: ` - + Content 1 Content 2 Content 3 - - ` + + `, }) -class StepperWithIndirectDescendantSteps { -} - +class StepperWithIndirectDescendantSteps {} @Component({ template: ` - + Step 1 @@ -1787,42 +2112,75 @@ class StepperWithIndirectDescendantSteps { Step 2 - - ` + + `, }) class StepperWithNgIf { showStep2 = false; } - @Component({ template: ` - + Content 1 Content 2 - + Sub-Content 1 Sub-Content 2 - + - - ` + + `, }) class NestedSteppers { @ViewChildren(MatStepper) steppers: QueryList; } - @Component({ template: ` - + Content 1 Content 2 Content 3 - - ` + + `, }) class StepperWithStaticOutOfBoundsIndex { @ViewChild(MatStepper) stepper: MatStepper; } + +@Component({ + template: ` + + + Step 1 + Step 1 content + + + Step 2 + Step 2 content + + + Step 3 + Step 3 content + + + `, +}) +class StepperWithLazyContent { + selectedIndex = 0; +} + +@Component({ + template: ` + + Content 1 + Content 2 + Content 3 + + `, +}) +class HorizontalStepperWithDelayedStep { + renderSecondStep = false; +} diff --git a/src/material/stepper/stepper.ts b/src/material/stepper/stepper.ts index ba64e22ac320..d6e05c314825 100644 --- a/src/material/stepper/stepper.ts +++ b/src/material/stepper/stepper.ts @@ -7,13 +7,12 @@ */ import {Directionality} from '@angular/cdk/bidi'; -import {BooleanInput} from '@angular/cdk/coercion'; import { CdkStep, CdkStepper, StepContentPositionState, STEPPER_GLOBAL_OPTIONS, - StepperOptions + StepperOptions, } from '@angular/cdk/stepper'; import {AnimationEvent} from '@angular/animations'; import { @@ -29,24 +28,28 @@ import { forwardRef, Inject, Input, + OnDestroy, Optional, Output, QueryList, SkipSelf, TemplateRef, ViewChildren, + ViewContainerRef, ViewEncapsulation, } from '@angular/core'; import {FormControl, FormGroupDirective, NgForm} from '@angular/forms'; import {DOCUMENT} from '@angular/common'; import {ErrorStateMatcher, ThemePalette} from '@angular/material/core'; -import {Subject} from 'rxjs'; -import {takeUntil, distinctUntilChanged} from 'rxjs/operators'; +import {TemplatePortal} from '@angular/cdk/portal'; +import {Subject, Subscription} from 'rxjs'; +import {takeUntil, distinctUntilChanged, map, startWith, switchMap} from 'rxjs/operators'; import {MatStepHeader} from './step-header'; import {MatStepLabel} from './step-label'; import {matStepperAnimations} from './stepper-animations'; import {MatStepperIcon, MatStepperIconContext} from './stepper-icon'; +import {MatStepContent} from './step-content'; @Component({ selector: 'mat-step', @@ -59,20 +62,51 @@ import {MatStepperIcon, MatStepperIconContext} from './stepper-icon'; exportAs: 'matStep', changeDetection: ChangeDetectionStrategy.OnPush, }) -export class MatStep extends CdkStep implements ErrorStateMatcher { +export class MatStep extends CdkStep implements ErrorStateMatcher, AfterContentInit, OnDestroy { + private _isSelected = Subscription.EMPTY; + /** Content for step label given by ``. */ - @ContentChild(MatStepLabel) stepLabel: MatStepLabel; + @ContentChild(MatStepLabel) override stepLabel: MatStepLabel; /** Theme color for the particular step. */ @Input() color: ThemePalette; - /** @breaking-change 8.0.0 remove the `?` after `stepperOptions` */ - constructor(@Inject(forwardRef(() => MatStepper)) stepper: MatStepper, - @SkipSelf() private _errorStateMatcher: ErrorStateMatcher, - @Optional() @Inject(STEPPER_GLOBAL_OPTIONS) stepperOptions?: StepperOptions) { + /** Content that will be rendered lazily. */ + @ContentChild(MatStepContent, {static: false}) _lazyContent: MatStepContent; + + /** Currently-attached portal containing the lazy content. */ + _portal: TemplatePortal; + + constructor( + @Inject(forwardRef(() => MatStepper)) stepper: MatStepper, + @SkipSelf() private _errorStateMatcher: ErrorStateMatcher, + private _viewContainerRef: ViewContainerRef, + @Optional() @Inject(STEPPER_GLOBAL_OPTIONS) stepperOptions?: StepperOptions, + ) { super(stepper, stepperOptions); } + ngAfterContentInit() { + this._isSelected = this._stepper.steps.changes + .pipe( + switchMap(() => { + return this._stepper.selectionChange.pipe( + map(event => event.selectedStep === this), + startWith(this._stepper.selected === this), + ); + }), + ) + .subscribe(isSelected => { + if (isSelected && this._lazyContent && !this._portal) { + this._portal = new TemplatePortal(this._lazyContent._template, this._viewContainerRef!); + } + }); + } + + ngOnDestroy() { + this._isSelected.unsubscribe(); + } + /** Custom error state matcher that additionally checks for validity of interacted form. */ isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean { const originalErrorState = this._errorStateMatcher.isErrorState(control, form); @@ -86,17 +120,73 @@ export class MatStep extends CdkStep implements ErrorStateMatcher { } } +/** + * Proxies the public APIs from `MatStepper` to the deprecated `MatHorizontalStepper` and + * `MatVerticalStepper`. + * @deprecated Use `MatStepper` instead. + * @breaking-change 13.0.0 + * @docs-private + */ +@Directive() +abstract class _MatProxyStepperBase extends CdkStepper { + override readonly steps: QueryList; + readonly animationDone: EventEmitter; + disableRipple: boolean; + color: ThemePalette; + labelPosition: 'bottom' | 'end'; +} + +/** + * @deprecated Use `MatStepper` instead. + * @breaking-change 13.0.0 + */ +@Directive({selector: 'mat-horizontal-stepper'}) +export class MatHorizontalStepper extends _MatProxyStepperBase {} -@Directive({selector: '[matStepper]', providers: [{provide: CdkStepper, useExisting: MatStepper}]}) +/** + * @deprecated Use `MatStepper` instead. + * @breaking-change 13.0.0 + */ +@Directive({selector: 'mat-vertical-stepper'}) +export class MatVerticalStepper extends _MatProxyStepperBase {} + +@Component({ + selector: 'mat-stepper, mat-vertical-stepper, mat-horizontal-stepper, [matStepper]', + exportAs: 'matStepper, matVerticalStepper, matHorizontalStepper', + templateUrl: 'stepper.html', + styleUrls: ['stepper.css'], + inputs: ['selectedIndex'], + host: { + '[class.mat-stepper-horizontal]': 'orientation === "horizontal"', + '[class.mat-stepper-vertical]': 'orientation === "vertical"', + '[class.mat-stepper-label-position-end]': + 'orientation === "horizontal" && labelPosition == "end"', + '[class.mat-stepper-label-position-bottom]': + 'orientation === "horizontal" && labelPosition == "bottom"', + '[attr.aria-orientation]': 'orientation', + 'role': 'tablist', + }, + animations: [ + matStepperAnimations.horizontalStepTransition, + matStepperAnimations.verticalStepTransition, + ], + providers: [ + {provide: CdkStepper, useExisting: MatStepper}, + {provide: MatHorizontalStepper, useExisting: MatStepper}, + {provide: MatVerticalStepper, useExisting: MatStepper}, + ], + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, +}) export class MatStepper extends CdkStepper implements AfterContentInit { /** The list of step headers of the steps in the stepper. */ - @ViewChildren(MatStepHeader) _stepHeader: QueryList; + @ViewChildren(MatStepHeader) override _stepHeader: QueryList; /** Full list of steps inside the stepper, including inside nested steppers. */ - @ContentChildren(MatStep, {descendants: true}) _steps: QueryList; + @ContentChildren(MatStep, {descendants: true}) override _steps: QueryList; /** Steps that belong to the current stepper, excluding ones from nested steppers. */ - readonly steps: QueryList = new QueryList(); + override readonly steps: QueryList = new QueryList(); /** Custom icon overrides passed in by the consumer. */ @ContentChildren(MatStepperIcon, {descendants: true}) _icons: QueryList; @@ -110,104 +200,55 @@ export class MatStepper extends CdkStepper implements AfterContentInit { /** Theme color for all of the steps in stepper. */ @Input() color: ThemePalette; + /** + * Whether the label should display in bottom or end position. + * Only applies in the `horizontal` orientation. + */ + @Input() + labelPosition: 'bottom' | 'end' = 'end'; + /** Consumer-specified template-refs to be used to override the header icons. */ - _iconOverrides: {[key: string]: TemplateRef} = {}; + _iconOverrides: Record> = {}; /** Stream of animation `done` events when the body expands/collapses. */ - _animationDone = new Subject(); + readonly _animationDone = new Subject(); - ngAfterContentInit() { + constructor( + @Optional() dir: Directionality, + changeDetectorRef: ChangeDetectorRef, + elementRef: ElementRef, + @Inject(DOCUMENT) _document: any, + ) { + super(dir, changeDetectorRef, elementRef, _document); + const nodeName = elementRef.nativeElement.nodeName.toLowerCase(); + this.orientation = nodeName === 'mat-vertical-stepper' ? 'vertical' : 'horizontal'; + } + + override ngAfterContentInit() { super.ngAfterContentInit(); - this._icons.forEach(({name, templateRef}) => this._iconOverrides[name] = templateRef); + this._icons.forEach(({name, templateRef}) => (this._iconOverrides[name] = templateRef)); // Mark the component for change detection whenever the content children query changes this.steps.changes.pipe(takeUntil(this._destroyed)).subscribe(() => { this._stateChanged(); }); - this._animationDone.pipe( - // This needs a `distinctUntilChanged` in order to avoid emitting the same event twice due - // to a bug in animations where the `.done` callback gets invoked twice on some browsers. - // See https://github.com/angular/angular/issues/24084 - distinctUntilChanged((x, y) => x.fromState === y.fromState && x.toState === y.toState), - takeUntil(this._destroyed) - ).subscribe(event => { - if ((event.toState as StepContentPositionState) === 'current') { - this.animationDone.emit(); - } - }); + this._animationDone + .pipe( + // This needs a `distinctUntilChanged` in order to avoid emitting the same event twice due + // to a bug in animations where the `.done` callback gets invoked twice on some browsers. + // See https://github.com/angular/angular/issues/24084 + distinctUntilChanged((x, y) => x.fromState === y.fromState && x.toState === y.toState), + takeUntil(this._destroyed), + ) + .subscribe(event => { + if ((event.toState as StepContentPositionState) === 'current') { + this.animationDone.emit(); + } + }); } - static ngAcceptInputType_editable: BooleanInput; - static ngAcceptInputType_optional: BooleanInput; - static ngAcceptInputType_completed: BooleanInput; - static ngAcceptInputType_hasError: BooleanInput; -} - -@Component({ - selector: 'mat-horizontal-stepper', - exportAs: 'matHorizontalStepper', - templateUrl: 'stepper-horizontal.html', - styleUrls: ['stepper.css'], - inputs: ['selectedIndex'], - host: { - 'class': 'mat-stepper-horizontal', - '[class.mat-stepper-label-position-end]': 'labelPosition == "end"', - '[class.mat-stepper-label-position-bottom]': 'labelPosition == "bottom"', - 'aria-orientation': 'horizontal', - 'role': 'tablist', - }, - animations: [matStepperAnimations.horizontalStepTransition], - providers: [ - {provide: MatStepper, useExisting: MatHorizontalStepper}, - {provide: CdkStepper, useExisting: MatHorizontalStepper} - ], - encapsulation: ViewEncapsulation.None, - changeDetection: ChangeDetectionStrategy.OnPush, -}) -export class MatHorizontalStepper extends MatStepper { - /** Whether the label should display in bottom or end position. */ - @Input() - labelPosition: 'bottom' | 'end' = 'end'; - - static ngAcceptInputType_editable: BooleanInput; - static ngAcceptInputType_optional: BooleanInput; - static ngAcceptInputType_completed: BooleanInput; - static ngAcceptInputType_hasError: BooleanInput; -} - -@Component({ - selector: 'mat-vertical-stepper', - exportAs: 'matVerticalStepper', - templateUrl: 'stepper-vertical.html', - styleUrls: ['stepper.css'], - inputs: ['selectedIndex'], - host: { - 'class': 'mat-stepper-vertical', - 'aria-orientation': 'vertical', - 'role': 'tablist', - }, - animations: [matStepperAnimations.verticalStepTransition], - providers: [ - {provide: MatStepper, useExisting: MatVerticalStepper}, - {provide: CdkStepper, useExisting: MatVerticalStepper} - ], - encapsulation: ViewEncapsulation.None, - changeDetection: ChangeDetectionStrategy.OnPush, -}) -export class MatVerticalStepper extends MatStepper { - constructor( - @Optional() dir: Directionality, - changeDetectorRef: ChangeDetectorRef, - // @breaking-change 8.0.0 `elementRef` and `_document` parameters to become required. - elementRef?: ElementRef, - @Inject(DOCUMENT) _document?: any) { - super(dir, changeDetectorRef, elementRef, _document); - this._orientation = 'vertical'; + _stepIsNavigable(index: number, step: MatStep): boolean { + return step.completed || this.selectedIndex === index || !this.linear; } - - static ngAcceptInputType_editable: BooleanInput; - static ngAcceptInputType_optional: BooleanInput; - static ngAcceptInputType_completed: BooleanInput; - static ngAcceptInputType_hasError: BooleanInput; } diff --git a/src/material/stepper/testing/BUILD.bazel b/src/material/stepper/testing/BUILD.bazel index f323ef9a2af9..72dd313dcfe4 100644 --- a/src/material/stepper/testing/BUILD.bazel +++ b/src/material/stepper/testing/BUILD.bazel @@ -8,7 +8,6 @@ ts_library( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material/stepper/testing", deps = [ "//src/cdk/testing", ], diff --git a/src/material/stepper/testing/shared.spec.ts b/src/material/stepper/testing/shared.spec.ts index 9d1e88a0d6bb..8f4b3b19deaf 100644 --- a/src/material/stepper/testing/shared.spec.ts +++ b/src/material/stepper/testing/shared.spec.ts @@ -12,10 +12,11 @@ import {StepperOrientation} from './step-harness-filters'; /** Shared tests to run on both the original and MDC-based steppers. */ export function runHarnessTests( - stepperModule: typeof MatStepperModule, - stepperHarness: typeof MatStepperHarness, - stepperNextHarness: typeof MatStepperNextHarness, - stepperPreviousHarness: typeof MatStepperPreviousHarness) { + stepperModule: typeof MatStepperModule, + stepperHarness: typeof MatStepperHarness, + stepperNextHarness: typeof MatStepperNextHarness, + stepperPreviousHarness: typeof MatStepperPreviousHarness, +) { let fixture: ComponentFixture; let loader: HarnessLoader; @@ -23,10 +24,12 @@ export function runHarnessTests( await TestBed.configureTestingModule({ imports: [stepperModule, NoopAnimationsModule, ReactiveFormsModule], declarations: [StepperHarnessTest], - providers: [{ - provide: STEPPER_GLOBAL_OPTIONS, - useValue: {showError: true} // Required so the error state shows up in tests. - }] + providers: [ + { + provide: STEPPER_GLOBAL_OPTIONS, + useValue: {showError: true}, // Required so the error state shows up in tests. + }, + ], }).compileComponents(); fixture = TestBed.createComponent(StepperHarnessTest); @@ -42,7 +45,7 @@ export function runHarnessTests( it('should filter steppers by their orientation', async () => { const [verticalSteppers, horizontalSteppers] = await parallel(() => [ loader.getAllHarnesses(stepperHarness.with({orientation: StepperOrientation.VERTICAL})), - loader.getAllHarnesses(stepperHarness.with({orientation: StepperOrientation.HORIZONTAL})) + loader.getAllHarnesses(stepperHarness.with({orientation: StepperOrientation.HORIZONTAL})), ]); expect(verticalSteppers.length).toBe(2); @@ -55,7 +58,7 @@ export function runHarnessTests( expect(await parallel(() => steppers.map(stepper => stepper.getOrientation()))).toEqual([ StepperOrientation.VERTICAL, StepperOrientation.HORIZONTAL, - StepperOrientation.VERTICAL + StepperOrientation.VERTICAL, ]); }); @@ -79,7 +82,7 @@ export function runHarnessTests( true, false, false, - false + false, ]); await stepper.selectStep({label: 'Three'}); @@ -88,7 +91,7 @@ export function runHarnessTests( false, false, true, - false + false, ]); }); @@ -100,16 +103,18 @@ export function runHarnessTests( 'One', 'Two', 'Three', - 'Four' + 'Four', ]); }); it('should be able to get the template-based label of a step', async () => { const stepper = await loader.getHarness(stepperHarness.with({selector: '#two-stepper'})); const steps = await stepper.getSteps(); - expect(await parallel(() => { - return steps.map(step => step.getLabel()); - })).toEqual(['One', 'Two', 'Three']); + expect( + await parallel(() => { + return steps.map(step => step.getLabel()); + }), + ).toEqual(['One', 'Two', 'Three']); }); it('should be able to get the aria-label of a step', async () => { @@ -119,7 +124,7 @@ export function runHarnessTests( null, null, null, - 'Fourth step' + 'Fourth step', ]); }); @@ -130,7 +135,7 @@ export function runHarnessTests( null, null, 'some-label', - null + null, ]); }); @@ -142,7 +147,7 @@ export function runHarnessTests( true, false, false, - false + false, ]); }); @@ -154,7 +159,7 @@ export function runHarnessTests( true, false, false, - false + false, ]); await steps[2].select(); @@ -163,7 +168,7 @@ export function runHarnessTests( false, false, true, - false + false, ]); }); @@ -178,7 +183,7 @@ export function runHarnessTests( const [step] = await stepper.getSteps({label: 'Two'}); const [nextButton, previousButton] = await parallel(() => [ step.getHarness(stepperNextHarness), - step.getHarness(stepperPreviousHarness) + step.getHarness(stepperPreviousHarness), ]); expect(await nextButton.getText()).toBe('Next'); @@ -197,7 +202,7 @@ export function runHarnessTests( false, true, false, - false + false, ]); await nextButton.click(); @@ -206,7 +211,7 @@ export function runHarnessTests( false, false, true, - false + false, ]); }); @@ -222,7 +227,7 @@ export function runHarnessTests( false, true, false, - false + false, ]); await previousButton.click(); @@ -231,7 +236,7 @@ export function runHarnessTests( true, false, false, - false + false, ]); }); @@ -257,12 +262,11 @@ export function runHarnessTests( expect(await parallel(() => steps.map(step => step.isCompleted()))).toEqual([true, false]); }); - } @Component({ template: ` - + @@ -277,9 +281,9 @@ export function runHarnessTests( - + - + One @@ -289,9 +293,9 @@ export function runHarnessTests( Three - + - + @@ -302,15 +306,15 @@ export function runHarnessTests( - - ` +
+ `, }) class StepperHarnessTest { oneGroup = new FormGroup({ - oneCtrl: new FormControl('', Validators.required) + oneCtrl: new FormControl('', Validators.required), }); twoGroup = new FormGroup({ - twoCtrl: new FormControl('', Validators.required) + twoCtrl: new FormControl('', Validators.required), }); } diff --git a/src/material/stepper/testing/step-harness-filters.ts b/src/material/stepper/testing/step-harness-filters.ts index 7e3c395a5b1b..7b67c56e8bca 100644 --- a/src/material/stepper/testing/step-harness-filters.ts +++ b/src/material/stepper/testing/step-harness-filters.ts @@ -8,7 +8,10 @@ import {BaseHarnessFilters} from '@angular/cdk/testing'; /** Possible orientations for a stepper. */ -export const enum StepperOrientation {HORIZONTAL, VERTICAL} +export const enum StepperOrientation { + HORIZONTAL, + VERTICAL, +} /** A set of criteria that can be used to filter a list of `MatStepHarness` instances. */ export interface StepHarnessFilters extends BaseHarnessFilters { @@ -36,4 +39,3 @@ export interface StepperButtonHarnessFilters extends BaseHarnessFilters { /** Only find instances whose text matches the given value. */ text?: string | RegExp; } - diff --git a/src/material/stepper/testing/step-harness.ts b/src/material/stepper/testing/step-harness.ts index 9568c9af3d0c..682afccde63f 100644 --- a/src/material/stepper/testing/step-harness.ts +++ b/src/material/stepper/testing/step-harness.ts @@ -26,14 +26,24 @@ export class MatStepHarness extends ContentContainerComponentHarness { */ static with(options: StepHarnessFilters = {}): HarnessPredicate { return new HarnessPredicate(MatStepHarness, options) - .addOption('label', options.label, - (harness, label) => HarnessPredicate.stringMatches(harness.getLabel(), label)) - .addOption('selected', options.selected, - async (harness, selected) => (await harness.isSelected()) === selected) - .addOption('completed', options.completed, - async (harness, completed) => (await harness.isCompleted()) === completed) - .addOption('invalid', options.invalid, - async (harness, invalid) => (await harness.hasErrors()) === invalid); + .addOption('label', options.label, (harness, label) => + HarnessPredicate.stringMatches(harness.getLabel(), label), + ) + .addOption( + 'selected', + options.selected, + async (harness, selected) => (await harness.isSelected()) === selected, + ) + .addOption( + 'completed', + options.completed, + async (harness, completed) => (await harness.isCompleted()) === completed, + ) + .addOption( + 'invalid', + options.invalid, + async (harness, invalid) => (await harness.hasErrors()) === invalid, + ); } /** Gets the label of the step. */ @@ -42,12 +52,12 @@ export class MatStepHarness extends ContentContainerComponentHarness { } /** Gets the `aria-label` of the step. */ - async getAriaLabel(): Promise { + async getAriaLabel(): Promise { return (await this.host()).getAttribute('aria-label'); } /** Gets the value of the `aria-labelledby` attribute. */ - async getAriaLabelledby(): Promise { + async getAriaLabelledby(): Promise { return (await this.host()).getAttribute('aria-labelledby'); } @@ -89,7 +99,7 @@ export class MatStepHarness extends ContentContainerComponentHarness { await (await this.host()).click(); } - protected async getRootHarnessLoader(): Promise { + protected override async getRootHarnessLoader(): Promise { const contentId = await (await this.host()).getAttribute('aria-controls'); return this.documentRootLocatorFactory().harnessLoaderFor(`#${contentId}`); } diff --git a/src/material/stepper/testing/stepper-button-harnesses.ts b/src/material/stepper/testing/stepper-button-harnesses.ts index cdac75a2317c..381f17003ad6 100644 --- a/src/material/stepper/testing/stepper-button-harnesses.ts +++ b/src/material/stepper/testing/stepper-button-harnesses.ts @@ -34,13 +34,14 @@ export class MatStepperNextHarness extends StepperButtonHarness { * @return a `HarnessPredicate` configured with the given options. */ static with(options: StepperButtonHarnessFilters = {}): HarnessPredicate { - return new HarnessPredicate(MatStepperNextHarness, options) - .addOption('text', options.text, - (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text)); + return new HarnessPredicate(MatStepperNextHarness, options).addOption( + 'text', + options.text, + (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text), + ); } } - /** Harness for interacting with a standard Angular Material stepper previous button in tests. */ export class MatStepperPreviousHarness extends StepperButtonHarness { /** The selector for the host element of a `MatStep` instance. */ @@ -52,10 +53,13 @@ export class MatStepperPreviousHarness extends StepperButtonHarness { * @param options Options for filtering which steps are considered a match. * @return a `HarnessPredicate` configured with the given options. */ - static with(options: StepperButtonHarnessFilters = {}): - HarnessPredicate { - return new HarnessPredicate(MatStepperPreviousHarness, options) - .addOption('text', options.text, - (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text)); + static with( + options: StepperButtonHarnessFilters = {}, + ): HarnessPredicate { + return new HarnessPredicate(MatStepperPreviousHarness, options).addOption( + 'text', + options.text, + (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text), + ); } } diff --git a/src/material/stepper/testing/stepper-harness.spec.ts b/src/material/stepper/testing/stepper-harness.spec.ts index 2d613ae4a058..2216f26ba7bf 100644 --- a/src/material/stepper/testing/stepper-harness.spec.ts +++ b/src/material/stepper/testing/stepper-harness.spec.ts @@ -4,6 +4,10 @@ import {MatStepperHarness} from './stepper-harness'; import {MatStepperNextHarness, MatStepperPreviousHarness} from './stepper-button-harnesses'; describe('Non-MDC-based MatStepperHarness', () => { - runHarnessTests(MatStepperModule, MatStepperHarness, MatStepperNextHarness, - MatStepperPreviousHarness); + runHarnessTests( + MatStepperModule, + MatStepperHarness, + MatStepperNextHarness, + MatStepperPreviousHarness, + ); }); diff --git a/src/material/stepper/testing/stepper-harness.ts b/src/material/stepper/testing/stepper-harness.ts index 5b50da9080cf..8c8f2842e404 100644 --- a/src/material/stepper/testing/stepper-harness.ts +++ b/src/material/stepper/testing/stepper-harness.ts @@ -26,9 +26,11 @@ export class MatStepperHarness extends ComponentHarness { * @return a `HarnessPredicate` configured with the given options. */ static with(options: StepperHarnessFilters = {}): HarnessPredicate { - return new HarnessPredicate(MatStepperHarness, options) - .addOption('orientation', options.orientation, - async (harness, orientation) => (await harness.getOrientation()) === orientation); + return new HarnessPredicate(MatStepperHarness, options).addOption( + 'orientation', + options.orientation, + async (harness, orientation) => (await harness.getOrientation()) === orientation, + ); } /** @@ -42,8 +44,9 @@ export class MatStepperHarness extends ComponentHarness { /** Gets the orientation of the stepper. */ async getOrientation(): Promise { const host = await this.host(); - return (await host.hasClass('mat-stepper-horizontal')) ? - StepperOrientation.HORIZONTAL : StepperOrientation.VERTICAL; + return (await host.hasClass('mat-stepper-horizontal')) + ? StepperOrientation.HORIZONTAL + : StepperOrientation.VERTICAL; } /** diff --git a/src/material/table/BUILD.bazel b/src/material/table/BUILD.bazel index 64471ffe855d..815bb75835a2 100644 --- a/src/material/table/BUILD.bazel +++ b/src/material/table/BUILD.bazel @@ -17,7 +17,6 @@ ng_module( exclude = ["**/*.spec.ts"], ), assets = [":table.css"], - module_name = "@angular/material/table", deps = [ "@npm//@angular/core", "@npm//rxjs", @@ -31,13 +30,16 @@ ng_module( sass_library( name = "table_scss_lib", - srcs = ["_table-theme.scss"], + srcs = glob(["**/_*.scss"]), deps = ["//src/material/core:core_scss_lib"], ) sass_library( name = "table_flex_scss_lib", - srcs = ["_table-flex-styles.scss"], + srcs = [ + "_table-flex-styles.import.scss", + "_table-flex-styles.scss", + ], deps = ["//src/material/core:core_scss_lib"], ) diff --git a/src/material/table/_table-flex-styles.import.scss b/src/material/table/_table-flex-styles.import.scss new file mode 100644 index 000000000000..ce779389f77e --- /dev/null +++ b/src/material/table/_table-flex-styles.import.scss @@ -0,0 +1 @@ +@forward 'table-flex-styles' as mat-*; diff --git a/src/material/table/_table-flex-styles.scss b/src/material/table/_table-flex-styles.scss index a0bd715e8084..6ae1a79dd5d2 100644 --- a/src/material/table/_table-flex-styles.scss +++ b/src/material/table/_table-flex-styles.scss @@ -1,22 +1,20 @@ -/** - * Flex-based table structure - */ -$mat-header-row-height: 56px; -$mat-row-height: 48px; -$mat-row-horizontal-padding: 24px; +// Flex-based table structure +$header-row-height: 56px; +$row-height: 48px; +$row-horizontal-padding: 24px; // Only use tag name selectors here since the styles are shared between MDC and non-MDC -@mixin mat-private-table-flex-styles { +@mixin private-table-flex-styles { mat-table { display: block; } mat-header-row { - min-height: $mat-header-row-height; + min-height: $header-row-height; } mat-row, mat-footer-row { - min-height: $mat-row-height; + min-height: $row-height; } mat-row, mat-header-row, mat-footer-row { @@ -43,20 +41,20 @@ $mat-row-horizontal-padding: 24px; // Note: we use `first-of-type`/`last-of-type` here in order to prevent extra // elements like ripples or badges from throwing off the layout (see #11165). &:first-of-type { - padding-left: $mat-row-horizontal-padding; + padding-left: $row-horizontal-padding; [dir='rtl'] &:not(:only-of-type) { padding-left: 0; - padding-right: $mat-row-horizontal-padding; + padding-right: $row-horizontal-padding; } } &:last-of-type { - padding-right: $mat-row-horizontal-padding; + padding-right: $row-horizontal-padding; [dir='rtl'] &:not(:only-of-type) { padding-right: 0; - padding-left: $mat-row-horizontal-padding; + padding-left: $row-horizontal-padding; } } } diff --git a/src/material/table/_table-legacy-index.scss b/src/material/table/_table-legacy-index.scss new file mode 100644 index 000000000000..9347678e9e20 --- /dev/null +++ b/src/material/table/_table-legacy-index.scss @@ -0,0 +1,3 @@ +@forward 'table-theme' hide color, theme, typography; +@forward 'table-theme' as mat-table-* hide mat-table-density; +@forward 'table-flex-styles' as mat-*; diff --git a/src/material/table/_table-theme.import.scss b/src/material/table/_table-theme.import.scss new file mode 100644 index 000000000000..8a64a0ef6a7d --- /dev/null +++ b/src/material/table/_table-theme.import.scss @@ -0,0 +1,8 @@ +@forward '../core/theming/theming.import'; +@forward '../core/typography/typography-utils.import'; +@forward 'table-theme' hide color, theme, typography; +@forward 'table-theme' as mat-table-* hide mat-table-density; + +@import '../core/theming/palette'; +@import '../core/theming/theming'; +@import '../core/typography/typography-utils'; diff --git a/src/material/table/_table-theme.scss b/src/material/table/_table-theme.scss index 962f07ca6a13..ade8f26d397f 100644 --- a/src/material/table/_table-theme.scss +++ b/src/material/table/_table-theme.scss @@ -1,14 +1,15 @@ -@import '../core/theming/palette'; -@import '../core/theming/theming'; -@import '../core/typography/typography-utils'; +@use 'sass:map'; +@use '../core/theming/theming'; +@use '../core/typography/typography'; +@use '../core/typography/typography-utils'; -@mixin mat-table-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $background: map-get($config, background); - $foreground: map-get($config, foreground); +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $background: map.get($config, background); + $foreground: map.get($config, foreground); .mat-table { - background: mat-color($background, 'card'); + background: theming.get-color-from-palette($background, 'card'); } .mat-table thead, .mat-table tbody, .mat-table tfoot, @@ -20,51 +21,52 @@ mat-row, mat-header-row, mat-footer-row, th.mat-header-cell, td.mat-cell, td.mat-footer-cell { - border-bottom-color: mat-color($foreground, divider); + border-bottom-color: theming.get-color-from-palette($foreground, divider); } .mat-header-cell { - color: mat-color($foreground, secondary-text); + color: theming.get-color-from-palette($foreground, secondary-text); } .mat-cell, .mat-footer-cell { - color: mat-color($foreground, text); + color: theming.get-color-from-palette($foreground, text); } } -@mixin mat-table-typography($config-or-theme) { - $config: mat-get-typography-config($config-or-theme); +@mixin typography($config-or-theme) { + $config: typography.private-typography-to-2014-config( + theming.get-typography-config($config-or-theme)); .mat-table { - font-family: mat-font-family($config); + font-family: typography-utils.font-family($config); } .mat-header-cell { - font-size: mat-font-size($config, caption); - font-weight: mat-font-weight($config, body-2); + font-size: typography-utils.font-size($config, caption); + font-weight: typography-utils.font-weight($config, body-2); } .mat-cell, .mat-footer-cell { - font-size: mat-font-size($config, body-1); + font-size: typography-utils.font-size($config, body-1); } } -@mixin _mat-table-density($config-or-theme) {} +@mixin _density($config-or-theme) {} -@mixin mat-table-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-table') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-table') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); @if $color != null { - @include mat-table-color($color); + @include color($color); } @if $density != null { - @include _mat-table-density($density); + @include _density($density); } @if $typography != null { - @include mat-table-typography($typography); + @include typography($typography); } } } diff --git a/src/material/table/cell.ts b/src/material/table/cell.ts index ce1c8cc9c8f6..dc2b1cd0ec07 100644 --- a/src/material/table/cell.ts +++ b/src/material/table/cell.ts @@ -6,12 +6,13 @@ * found in the LICENSE file at https://angular.io/license */ -import {BooleanInput} from '@angular/cdk/coercion'; import {Directive, Input} from '@angular/core'; import { CdkCell, CdkCellDef, - CdkColumnDef, CdkFooterCell, CdkFooterCellDef, + CdkColumnDef, + CdkFooterCell, + CdkFooterCellDef, CdkHeaderCell, CdkHeaderCellDef, } from '@angular/cdk/table'; @@ -22,7 +23,7 @@ import { */ @Directive({ selector: '[matCellDef]', - providers: [{provide: CdkCellDef, useExisting: MatCellDef}] + providers: [{provide: CdkCellDef, useExisting: MatCellDef}], }) export class MatCellDef extends CdkCellDef {} @@ -32,7 +33,7 @@ export class MatCellDef extends CdkCellDef {} */ @Directive({ selector: '[matHeaderCellDef]', - providers: [{provide: CdkHeaderCellDef, useExisting: MatHeaderCellDef}] + providers: [{provide: CdkHeaderCellDef, useExisting: MatHeaderCellDef}], }) export class MatHeaderCellDef extends CdkHeaderCellDef {} @@ -42,7 +43,7 @@ export class MatHeaderCellDef extends CdkHeaderCellDef {} */ @Directive({ selector: '[matFooterCellDef]', - providers: [{provide: CdkFooterCellDef, useExisting: MatFooterCellDef}] + providers: [{provide: CdkFooterCellDef, useExisting: MatFooterCellDef}], }) export class MatFooterCellDef extends CdkFooterCellDef {} @@ -55,14 +56,18 @@ export class MatFooterCellDef extends CdkFooterCellDef {} inputs: ['sticky'], providers: [ {provide: CdkColumnDef, useExisting: MatColumnDef}, - {provide: 'MAT_SORT_HEADER_COLUMN_DEF', useExisting: MatColumnDef} + {provide: 'MAT_SORT_HEADER_COLUMN_DEF', useExisting: MatColumnDef}, ], }) export class MatColumnDef extends CdkColumnDef { /** Unique name for this column. */ @Input('matColumnDef') - get name(): string { return this._name; } - set name(name: string) { this._setNameInput(name); } + override get name(): string { + return this._name; + } + override set name(name: string) { + this._setNameInput(name); + } /** * Add "mat-column-" prefix in addition to "cdk-column-" prefix. @@ -70,12 +75,10 @@ export class MatColumnDef extends CdkColumnDef { * will change from type string[] to string. * @docs-private */ - protected _updateColumnCssClassName() { + protected override _updateColumnCssClassName() { super._updateColumnCssClassName(); this._columnCssClassName!.push(`mat-column-${this.cssClassFriendlyName}`); } - - static ngAcceptInputType_sticky: BooleanInput; } /** Header cell template container that adds the right classes and role. */ diff --git a/src/material/table/row.ts b/src/material/table/row.ts index 09b3bda4b2cd..79490b1e7e1b 100644 --- a/src/material/table/row.ts +++ b/src/material/table/row.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {BooleanInput} from '@angular/cdk/coercion'; import { CDK_ROW_TEMPLATE, CdkFooterRow, @@ -15,7 +14,7 @@ import { CdkHeaderRowDef, CdkRow, CdkRowDef, - CdkNoDataRow + CdkNoDataRow, } from '@angular/cdk/table'; import {ChangeDetectionStrategy, Component, Directive, ViewEncapsulation} from '@angular/core'; @@ -28,9 +27,7 @@ import {ChangeDetectionStrategy, Component, Directive, ViewEncapsulation} from ' providers: [{provide: CdkHeaderRowDef, useExisting: MatHeaderRowDef}], inputs: ['columns: matHeaderRowDef', 'sticky: matHeaderRowDefSticky'], }) -export class MatHeaderRowDef extends CdkHeaderRowDef { - static ngAcceptInputType_sticky: BooleanInput; -} +export class MatHeaderRowDef extends CdkHeaderRowDef {} /** * Footer row definition for the mat-table. @@ -41,9 +38,7 @@ export class MatHeaderRowDef extends CdkHeaderRowDef { providers: [{provide: CdkFooterRowDef, useExisting: MatFooterRowDef}], inputs: ['columns: matFooterRowDef', 'sticky: matFooterRowDefSticky'], }) -export class MatFooterRowDef extends CdkFooterRowDef { - static ngAcceptInputType_sticky: BooleanInput; -} +export class MatFooterRowDef extends CdkFooterRowDef {} /** * Data row definition for the mat-table. @@ -55,8 +50,7 @@ export class MatFooterRowDef extends CdkFooterRowDef { providers: [{provide: CdkRowDef, useExisting: MatRowDef}], inputs: ['columns: matRowDefColumns', 'when: matRowDefWhen'], }) -export class MatRowDef extends CdkRowDef { -} +export class MatRowDef extends CdkRowDef {} /** Header template container that contains the cell outlet. Adds the right class and role. */ @Component({ @@ -73,8 +67,7 @@ export class MatRowDef extends CdkRowDef { exportAs: 'matHeaderRow', providers: [{provide: CdkHeaderRow, useExisting: MatHeaderRow}], }) -export class MatHeaderRow extends CdkHeaderRow { -} +export class MatHeaderRow extends CdkHeaderRow {} /** Footer template container that contains the cell outlet. Adds the right class and role. */ @Component({ @@ -91,8 +84,7 @@ export class MatHeaderRow extends CdkHeaderRow { exportAs: 'matFooterRow', providers: [{provide: CdkFooterRow, useExisting: MatFooterRow}], }) -export class MatFooterRow extends CdkFooterRow { -} +export class MatFooterRow extends CdkFooterRow {} /** Data row template container that contains the cell outlet. Adds the right class and role. */ @Component({ @@ -109,8 +101,7 @@ export class MatFooterRow extends CdkFooterRow { exportAs: 'matRow', providers: [{provide: CdkRow, useExisting: MatRow}], }) -export class MatRow extends CdkRow { -} +export class MatRow extends CdkRow {} /** Row that can be used to display a message when no data is shown in the table. */ @Directive({ @@ -118,4 +109,5 @@ export class MatRow extends CdkRow { providers: [{provide: CdkNoDataRow, useExisting: MatNoDataRow}], }) export class MatNoDataRow extends CdkNoDataRow { + override _contentClassName = 'mat-no-data-row'; } diff --git a/src/material/table/table-data-source.spec.ts b/src/material/table/table-data-source.spec.ts index 8bcba15cf3c3..c67fc10f972e 100644 --- a/src/material/table/table-data-source.spec.ts +++ b/src/material/table/table-data-source.spec.ts @@ -5,23 +5,26 @@ import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {Component, ViewChild} from '@angular/core'; describe('MatTableDataSource', () => { - const dataSource = new MatTableDataSource(); - - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatSortModule, NoopAnimationsModule], - declarations: [MatSortApp], - }).compileComponents(); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatSortModule, NoopAnimationsModule], + declarations: [MatSortApp], + }).compileComponents(); + }), + ); describe('sort', () => { + let dataSource: MatTableDataSource; let fixture: ComponentFixture; let sort: MatSort; beforeEach(() => { fixture = TestBed.createComponent(MatSortApp); fixture.detectChanges(); + dataSource = new MatTableDataSource(); sort = fixture.componentInstance.sort; + dataSource.sort = sort; }); /** Test the data source's `sortData` function. */ @@ -51,11 +54,33 @@ describe('MatTableDataSource', () => { it('should be able to correctly sort an array of strings and numbers', () => { testSortWithValues([3, 'apples', 'bananas', 'cherries', 'lemons', 'strawberries']); }); + + it('should unsubscribe from the re-render stream when disconnected', () => { + const spy = spyOn(dataSource._renderChangesSubscription!, 'unsubscribe'); + dataSource.disconnect(); + expect(spy).toHaveBeenCalledTimes(1); + }); + + it('should re-subscribe to the sort stream when re-connecting after being disconnected', () => { + dataSource.disconnect(); + const spy = spyOn(fixture.componentInstance.sort.sortChange, 'subscribe'); + dataSource.connect(); + expect(spy).toHaveBeenCalledTimes(1); + }); + + it('should update filteredData even if the data source is disconnected', () => { + dataSource.data = [1, 2, 3, 4, 5]; + expect(dataSource.filteredData).toEqual([1, 2, 3, 4, 5]); + + dataSource.disconnect(); + dataSource.data = [5, 4, 3, 2, 1]; + expect(dataSource.filteredData).toEqual([5, 4, 3, 2, 1]); + }); }); }); @Component({ - template: `
` + template: `
`, }) class MatSortApp { @ViewChild(MatSort) sort: MatSort; diff --git a/src/material/table/table-data-source.ts b/src/material/table/table-data-source.ts index af29105cec4a..22d01b86e661 100644 --- a/src/material/table/table-data-source.ts +++ b/src/material/table/table-data-source.ts @@ -8,7 +8,7 @@ import {_isNumberValue} from '@angular/cdk/coercion'; import {DataSource} from '@angular/cdk/table'; -import {MatPaginator, PageEvent} from '@angular/material/paginator'; +import {MatPaginator} from '@angular/material/paginator'; import {MatSort, Sort} from '@angular/material/sort'; import { BehaviorSubject, @@ -27,8 +27,22 @@ import {map} from 'rxjs/operators'; */ const MAX_SAFE_INTEGER = 9007199254740991; -interface Paginator { - page: Subject; +/** + * Interface that matches the required API parts for the MatPaginator's PageEvent. + * Decoupled so that users can depend on either the legacy or MDC-based paginator. + */ +export interface MatTableDataSourcePageEvent { + pageIndex: number; + pageSize: number; + length: number; +} + +/** + * Interface that matches the required API parts of the MatPaginator. + * Decoupled so that users can depend on either the legacy or MDC-based paginator. + */ +export interface MatTableDataSourcePaginator { + page: Subject; pageIndex: number; initialized: Observable; pageSize: number; @@ -36,7 +50,10 @@ interface Paginator { } /** Shared base class with MDC-based implementation. */ -export class _MatTableDataSource extends DataSource { +export class _MatTableDataSource< + T, + P extends MatTableDataSourcePaginator = MatTableDataSourcePaginator, +> extends DataSource { /** Stream that emits when a new data array is set on the data source. */ private readonly _data: BehaviorSubject; @@ -53,7 +70,7 @@ export class _MatTableDataSource extends DataSource { * Subscription to the changes that should trigger an update to the table's rendered rows, such * as filtering, sorting, pagination, or base data changes. */ - _renderChangesSubscription = Subscription.EMPTY; + _renderChangesSubscription: Subscription | null = null; /** * The filtered set of data that has been matched by the filter string, or all the data if there @@ -64,26 +81,46 @@ export class _MatTableDataSource extends DataSource { filteredData: T[]; /** Array of data that should be rendered by the table, where each object represents one row. */ - get data() { return this._data.value; } - set data(data: T[]) { this._data.next(data); } + get data() { + return this._data.value; + } + set data(data: T[]) { + this._data.next(data); + // Normally the `filteredData` is updated by the re-render + // subscription, but that won't happen if it's inactive. + if (!this._renderChangesSubscription) { + this._filterData(data); + } + } /** * Filter term that should be used to filter out objects from the data array. To override how * data objects match to this filter string, provide a custom function for filterPredicate. */ - get filter(): string { return this._filter.value; } - set filter(filter: string) { this._filter.next(filter); } + get filter(): string { + return this._filter.value; + } + set filter(filter: string) { + this._filter.next(filter); + // Normally the `filteredData` is updated by the re-render + // subscription, but that won't happen if it's inactive. + if (!this._renderChangesSubscription) { + this._filterData(this.data); + } + } /** * Instance of the MatSort directive used by the table to control its sorting. Sort changes * emitted by the MatSort will trigger an update to the table's rendered data. */ - get sort(): MatSort | null { return this._sort; } - set sort(sort: MatSort|null) { + get sort(): MatSort | null { + return this._sort; + } + set sort(sort: MatSort | null) { this._sort = sort; this._updateChangeSubscription(); } - private _sort: MatSort|null; + private _sort: MatSort | null; /** * Instance of the MatPaginator component used by the table to control what page of the data is @@ -95,7 +132,9 @@ export class _MatTableDataSource extends DataSource { * e.g. `[pageLength]=100` or `[pageIndex]=1`, then be sure that the paginator's view has been * initialized before assigning it to this data source. */ - get paginator(): P | null { return this._paginator; } + get paginator(): P | null { + return this._paginator; + } set paginator(paginator: P | null) { this._paginator = paginator; this._updateChangeSubscription(); @@ -111,8 +150,10 @@ export class _MatTableDataSource extends DataSource { * @param data Data object that is being accessed. * @param sortHeaderId The name of the column that represents the data. */ - sortingDataAccessor: ((data: T, sortHeaderId: string) => string|number) = - (data: T, sortHeaderId: string): string|number => { + sortingDataAccessor: (data: T, sortHeaderId: string) => string | number = ( + data: T, + sortHeaderId: string, + ): string | number => { const value = (data as {[key: string]: any})[sortHeaderId]; if (_isNumberValue(value)) { @@ -124,7 +165,7 @@ export class _MatTableDataSource extends DataSource { } return value; - } + }; /** * Gets a sorted copy of the data array based on the state of the MatSort. Called @@ -135,10 +176,12 @@ export class _MatTableDataSource extends DataSource { * @param data The array of data that should be sorted. * @param sort The connected MatSort that holds the current sort state. */ - sortData: ((data: T[], sort: MatSort) => T[]) = (data: T[], sort: MatSort): T[] => { + sortData: (data: T[], sort: MatSort) => T[] = (data: T[], sort: MatSort): T[] => { const active = sort.active; const direction = sort.direction; - if (!active || direction == '') { return data; } + if (!active || direction == '') { + return data; + } return data.sort((a, b) => { let valueA = this.sortingDataAccessor(a, active); @@ -151,8 +194,12 @@ export class _MatTableDataSource extends DataSource { const valueBType = typeof valueB; if (valueAType !== valueBType) { - if (valueAType === 'number') { valueA += ''; } - if (valueBType === 'number') { valueB += ''; } + if (valueAType === 'number') { + valueA += ''; + } + if (valueBType === 'number') { + valueB += ''; + } } // If both valueA and valueB exist (truthy), then compare the two. Otherwise, check if @@ -175,7 +222,7 @@ export class _MatTableDataSource extends DataSource { return comparatorResult * (direction == 'asc' ? 1 : -1); }); - } + }; /** * Checks if a data object matches the data source's filter string. By default, each data object @@ -187,23 +234,25 @@ export class _MatTableDataSource extends DataSource { * @param filter Filter string that has been set on the data source. * @returns Whether the filter matches against the data */ - filterPredicate: ((data: T, filter: string) => boolean) = (data: T, filter: string): boolean => { + filterPredicate: (data: T, filter: string) => boolean = (data: T, filter: string): boolean => { // Transform the data into a lowercase string of all property values. - const dataStr = Object.keys(data).reduce((currentTerm: string, key: string) => { - // Use an obscure Unicode character to delimit the words in the concatenated string. - // This avoids matches where the values of two columns combined will match the user's query - // (e.g. `Flute` and `Stop` will match `Test`). The character is intended to be something - // that has a very low chance of being typed in by somebody in a text field. This one in - // particular is "White up-pointing triangle with dot" from - // https://en.wikipedia.org/wiki/List_of_Unicode_characters - return currentTerm + (data as {[key: string]: any})[key] + '◬'; - }, '').toLowerCase(); + const dataStr = Object.keys(data) + .reduce((currentTerm: string, key: string) => { + // Use an obscure Unicode character to delimit the words in the concatenated string. + // This avoids matches where the values of two columns combined will match the user's query + // (e.g. `Flute` and `Stop` will match `Test`). The character is intended to be something + // that has a very low chance of being typed in by somebody in a text field. This one in + // particular is "White up-pointing triangle with dot" from + // https://en.wikipedia.org/wiki/List_of_Unicode_characters + return currentTerm + (data as {[key: string]: any})[key] + '◬'; + }, '') + .toLowerCase(); // Transform the filter by converting it to lowercase and removing whitespace. const transformedFilter = filter.trim().toLowerCase(); return dataStr.indexOf(transformedFilter) != -1; - } + }; constructor(initialData: T[] = []) { super(); @@ -223,28 +272,31 @@ export class _MatTableDataSource extends DataSource { // The `sortChange` and `pageChange` acts as a signal to the combineLatests below so that the // pipeline can progress to the next step. Note that the value from these streams are not used, // they purely act as a signal to progress in the pipeline. - const sortChange: Observable = this._sort ? - merge(this._sort.sortChange, this._sort.initialized) as Observable : - observableOf(null); - const pageChange: Observable = this._paginator ? - merge( + const sortChange: Observable = this._sort + ? (merge(this._sort.sortChange, this._sort.initialized) as Observable) + : observableOf(null); + const pageChange: Observable = this._paginator + ? (merge( this._paginator.page, this._internalPageChanges, - this._paginator.initialized - ) as Observable : - observableOf(null); + this._paginator.initialized, + ) as Observable) + : observableOf(null); const dataStream = this._data; // Watch for base data or filter changes to provide a filtered set of data. - const filteredData = combineLatest([dataStream, this._filter]) - .pipe(map(([data]) => this._filterData(data))); + const filteredData = combineLatest([dataStream, this._filter]).pipe( + map(([data]) => this._filterData(data)), + ); // Watch for filtered data or sort changes to provide an ordered set of data. - const orderedData = combineLatest([filteredData, sortChange]) - .pipe(map(([data]) => this._orderData(data))); + const orderedData = combineLatest([filteredData, sortChange]).pipe( + map(([data]) => this._orderData(data)), + ); // Watch for ordered data or page changes to provide a paged set of data. - const paginatedData = combineLatest([orderedData, pageChange]) - .pipe(map(([data]) => this._pageData(data))); + const paginatedData = combineLatest([orderedData, pageChange]).pipe( + map(([data]) => this._pageData(data)), + ); // Watched for paged data changes and send the result to the table to render. - this._renderChangesSubscription.unsubscribe(); + this._renderChangesSubscription?.unsubscribe(); this._renderChangesSubscription = paginatedData.subscribe(data => this._renderData.next(data)); } @@ -257,10 +309,14 @@ export class _MatTableDataSource extends DataSource { // If there is a filter string, filter out data that does not contain it. // Each data object is converted to a string using the function defined by filterTermAccessor. // May be overridden for customization. - this.filteredData = (this.filter == null || this.filter === '') ? data : - data.filter(obj => this.filterPredicate(obj, this.filter)); + this.filteredData = + this.filter == null || this.filter === '' + ? data + : data.filter(obj => this.filterPredicate(obj, this.filter)); - if (this.paginator) { this._updatePaginator(this.filteredData.length); } + if (this.paginator) { + this._updatePaginator(this.filteredData.length); + } return this.filteredData; } @@ -272,7 +328,9 @@ export class _MatTableDataSource extends DataSource { */ _orderData(data: T[]): T[] { // If there is no active sort or direction, return the data without trying to sort. - if (!this.sort) { return data; } + if (!this.sort) { + return data; + } return this.sortData(data.slice(), this.sort); } @@ -282,7 +340,9 @@ export class _MatTableDataSource extends DataSource { * index and length. If there is no paginator provided, returns the data array as provided. */ _pageData(data: T[]): T[] { - if (!this.paginator) { return data; } + if (!this.paginator) { + return data; + } const startIndex = this.paginator.pageIndex * this.paginator.pageSize; return data.slice(startIndex, startIndex + this.paginator.pageSize); @@ -297,7 +357,9 @@ export class _MatTableDataSource extends DataSource { Promise.resolve().then(() => { const paginator = this.paginator; - if (!paginator) { return; } + if (!paginator) { + return; + } paginator.length = filteredDataLength; @@ -321,13 +383,22 @@ export class _MatTableDataSource extends DataSource { * Used by the MatTable. Called when it connects to the data source. * @docs-private */ - connect() { return this._renderData; } + connect() { + if (!this._renderChangesSubscription) { + this._updateChangeSubscription(); + } + + return this._renderData; + } /** - * Used by the MatTable. Called when it is destroyed. No-op. + * Used by the MatTable. Called when it disconnects from the data source. * @docs-private */ - disconnect() { } + disconnect() { + this._renderChangesSubscription?.unsubscribe(); + this._renderChangesSubscription = null; + } } /** diff --git a/src/material/table/table-module.ts b/src/material/table/table-module.ts index 372bff81f11c..986b52ad9019 100644 --- a/src/material/table/table-module.ts +++ b/src/material/table/table-module.ts @@ -7,7 +7,7 @@ */ import {NgModule} from '@angular/core'; -import {MatTable} from './table'; +import {MatRecycleRows, MatTable} from './table'; import {CdkTableModule} from '@angular/cdk/table'; import { MatCell, @@ -16,7 +16,7 @@ import { MatFooterCell, MatFooterCellDef, MatHeaderCell, - MatHeaderCellDef + MatHeaderCellDef, } from './cell'; import { MatFooterRow, @@ -25,7 +25,7 @@ import { MatHeaderRowDef, MatRow, MatRowDef, - MatNoDataRow + MatNoDataRow, } from './row'; import {MatTextColumn} from './text-column'; import {MatCommonModule} from '@angular/material/core'; @@ -33,6 +33,7 @@ import {MatCommonModule} from '@angular/material/core'; const EXPORTED_DECLARATIONS = [ // Table MatTable, + MatRecycleRows, // Template defs MatHeaderCellDef, @@ -58,10 +59,7 @@ const EXPORTED_DECLARATIONS = [ ]; @NgModule({ - imports: [ - CdkTableModule, - MatCommonModule, - ], + imports: [CdkTableModule, MatCommonModule], exports: [MatCommonModule, EXPORTED_DECLARATIONS], declarations: EXPORTED_DECLARATIONS, }) diff --git a/src/material/table/table.md b/src/material/table/table.md index 063c473c02ef..e3f869bcebe0 100644 --- a/src/material/table/table.md +++ b/src/material/table/table.md @@ -106,14 +106,38 @@ automatically trigger an update to the rows each time a new data array is emitte #### DataSource -For most real-world applications, providing the table a DataSource instance will be the best way to -manage data. The DataSource is meant to serve a place to encapsulate any sorting, filtering, +For most real-world applications, providing the table a `DataSource` instance will be the best way to +manage data. The `DataSource` is meant to serve as a place to encapsulate any sorting, filtering, pagination, and data retrieval logic specific to the application. -A DataSource is simply a base class that has two functions: `connect` and `disconnect`. The -`connect` function will be called by the table to receive a stream that emits the data array that -should be rendered. The table will call `disconnect` when the table is destroyed, which may be the -right time to clean up any subscriptions that may have been registered during the connect process. +A `DataSource` is simply a class that has at a minimum the following methods: `connect` and +`disconnect`. The `connect` method will be called by the table to provide an `Observable` that emits +the data array that should be rendered. The table will call `disconnect` when the table is destroyed, +which may be the right time to clean up any subscriptions that may have been registered in the +`connect` method. + +Although Angular Material provides a ready-made table `DataSource` class, `MatTableDataSource`, you may +want to create your own custom `DataSource` class for more complex use cases. This can be done by +extending the abstract `DataSource` class with a custom `DataSource` class that then implements the +`connect` and `disconnect` methods. For use cases where the custom `DataSource` must also inherit +functionality by extending a different base class, the `DataSource` base class can be +implemented instead (`MyCustomDataSource extends SomeOtherBaseClass implements DataSource`) to +respect Typescript's restriction to only implement one base class. + +### Styling Columns + +Each table cell has an automatically generated class based on which column it appears in. The format for this +generated class is `mat-column-NAME`. For example, cells in a column named "symbol" can be targeted with the +selector `.mat-column-symbol`. + + + +### Row Templates + +Event handlers and property binding on the row templates will be applied to each row rendered by the table. For example, +adding a `(click)` handler to the row template will cause each individual row to call the handler when clicked. + + ### Features @@ -352,13 +376,15 @@ to resolve this. When using the `multiTemplateDataRows` directive to support multiple rows for each data object, the context of `*matRowDef` is the same except that the `index` value is replaced by `dataIndex` and `renderIndex`. ### Accessibility -Tables without text or labels should be given a meaningful label via `aria-label` or -`aria-labelledby`. The `aria-readonly` defaults to `true` if it's not set. -Table's default role is `grid`, and it can be changed to `treegrid` through `role` attribute. +By default, `MatTable` applies `role="table"`, assuming the table's contains primarily static +content. You can change the role by explicitly setting `role="grid"` or `role="treegrid"` on the +table element. While changing the role will update child element roles, such as changing +`role="cell"` to `role="gridcell"`, this does _not_ apply additional keyboard input handling or +focus management to the table. -`mat-table` does not manage any focus/keyboard interaction on its own. Users can add desired -focus/keyboard interactions in their application. +Always provide an accessible label for your tables via `aria-label` or `aria-labelledby` on the +table element. ### Tables with `display: flex` @@ -397,3 +423,15 @@ selectors. For example, `` becomes ``; ` Note that this approach means you cannot include certain native-table features such colspan/rowspan or have columns that resize themselves based on their content. + +### Tables with `MatRipple` + +By default, `MatTable` does not set up Material Design ripples for rows. A ripple effect can be +added to table rows by using the `MatRipple` directive from `@angular/material/core`. Due to +limitations in browsers, ripples cannot be applied native `th` or `tr` elements. The recommended +approach for setting up ripples is using the non-native `display: flex` variant of `MatTable`. + + + +More details about ripples on native table rows and their limitations can be found [in this issue](https://github.com/angular/components/issues/11883#issuecomment-634942981). + diff --git a/src/material/table/table.scss b/src/material/table/table.scss index d2b2ef881ade..52d21b53bf49 100644 --- a/src/material/table/table.scss +++ b/src/material/table/table.scss @@ -1,21 +1,19 @@ @use '../core/style/vendor-prefixes'; -@import './table-flex-styles'; +@use './table-flex-styles'; -@include mat-private-table-flex-styles(); +@include table-flex-styles.private-table-flex-styles(); -/** - * Native HTML table structure - */ +// Native HTML table structure table.mat-table { border-spacing: 0; } tr.mat-header-row { - height: $mat-header-row-height; + height: table-flex-styles.$header-row-height; } tr.mat-row, tr.mat-footer-row { - height: $mat-row-height; + height: table-flex-styles.$row-height; } th.mat-header-cell { @@ -34,26 +32,29 @@ th.mat-header-cell, td.mat-cell, td.mat-footer-cell { // Note: we use `first-of-type`/`last-of-type` here in order to prevent extra // elements like ripples or badges from throwing off the layout (see #11165). &:first-of-type { - padding-left: $mat-row-horizontal-padding; + padding-left: table-flex-styles.$row-horizontal-padding; [dir='rtl'] &:not(:only-of-type) { padding-left: 0; - padding-right: $mat-row-horizontal-padding; + padding-right: table-flex-styles.$row-horizontal-padding; } } &:last-of-type { - padding-right: $mat-row-horizontal-padding; + padding-right: table-flex-styles.$row-horizontal-padding; [dir='rtl'] &:not(:only-of-type) { padding-right: 0; - padding-left: $mat-row-horizontal-padding; + padding-left: table-flex-styles.$row-horizontal-padding; } } } .mat-table-sticky { - @include vendor-prefixes.position-sticky; + // Note that the table can either set this class or an inline style to make something sticky. + // We set the style as `!important` so that we get an identical specificity in both cases + // and to avoid cases where user styles have a higher specificity. + @include vendor-prefixes.position-sticky($important: true); } .mat-table-fixed-layout { diff --git a/src/material/table/table.spec.ts b/src/material/table/table.spec.ts index 456c6cd50d80..e47337e73a68 100644 --- a/src/material/table/table.spec.ts +++ b/src/material/table/table.spec.ts @@ -16,28 +16,29 @@ import {MatTableModule} from './index'; import {MatTable} from './table'; import {MatTableDataSource} from './table-data-source'; - describe('MatTable', () => { - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatTableModule, MatPaginatorModule, MatSortModule, NoopAnimationsModule], - declarations: [ - MatTableApp, - MatTableWithWhenRowApp, - ArrayDataSourceMatTableApp, - NativeHtmlTableApp, - MatTableWithSortApp, - MatTableWithPaginatorApp, - StickyTableApp, - TableWithNgContainerRow, - NestedHtmlTableApp, - ], - }).compileComponents(); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatTableModule, MatPaginatorModule, MatSortModule, NoopAnimationsModule], + declarations: [ + MatTableApp, + MatTableWithWhenRowApp, + ArrayDataSourceMatTableApp, + NativeHtmlTableApp, + MatTableWithSortApp, + MatTableWithPaginatorApp, + StickyTableApp, + TableWithNgContainerRow, + NestedHtmlTableApp, + ], + }).compileComponents(); + }), + ); describe('with basic data source', () => { it('should be able to create a table with the right content and without when row', () => { - let fixture = TestBed.createComponent(MatTableApp); + const fixture = TestBed.createComponent(MatTableApp); fixture.detectChanges(); const tableElement = fixture.nativeElement.querySelector('.mat-table')!; @@ -53,7 +54,7 @@ describe('MatTable', () => { }); it('should create a table with special when row', () => { - let fixture = TestBed.createComponent(MatTableWithWhenRowApp); + const fixture = TestBed.createComponent(MatTableWithWhenRowApp); fixture.detectChanges(); const tableElement = fixture.nativeElement.querySelector('.mat-table'); @@ -68,7 +69,7 @@ describe('MatTable', () => { }); it('should create a table with multiTemplateDataRows true', () => { - let fixture = TestBed.createComponent(MatTableWithWhenRowApp); + const fixture = TestBed.createComponent(MatTableWithWhenRowApp); fixture.componentInstance.multiTemplateDataRows = true; fixture.detectChanges(); @@ -91,17 +92,19 @@ describe('MatTable', () => { const table = fixture.nativeElement.querySelector('.mat-table')!; const initialData = fixture.componentInstance.dataSource!.data; - expect(table.textContent.trim()).not.toContain('No data'); + expect(table.querySelector('.mat-no-data-row')).toBeFalsy(); fixture.componentInstance.dataSource!.data = []; fixture.detectChanges(); - expect(table.textContent.trim()).toContain('No data'); + const noDataRow: HTMLElement = table.querySelector('.mat-no-data-row'); + expect(noDataRow).toBeTruthy(); + expect(noDataRow.getAttribute('role')).toBe('row'); fixture.componentInstance.dataSource!.data = initialData; fixture.detectChanges(); - expect(table.textContent.trim()).not.toContain('No data'); + expect(table.querySelector('.mat-no-data-row')).toBeFalsy(); }); it('should show the no data row if there is no data on init', () => { @@ -110,13 +113,12 @@ describe('MatTable', () => { fixture.detectChanges(); const table = fixture.nativeElement.querySelector('.mat-table')!; - expect(table.textContent.trim()).toContain('No data'); + expect(table.querySelector('.mat-no-data-row')).toBeTruthy(); }); - }); it('should be able to render a table correctly with native elements', () => { - let fixture = TestBed.createComponent(NativeHtmlTableApp); + const fixture = TestBed.createComponent(NativeHtmlTableApp); fixture.detectChanges(); const tableElement = fixture.nativeElement.querySelector('table'); @@ -154,21 +156,23 @@ describe('MatTable', () => { const dataSource = fixture.componentInstance.dataSource!; const initialData = dataSource.data; - expect(tbody.textContent.trim()).not.toContain('No data'); + expect(tbody.querySelector('.mat-no-data-row')).toBeFalsy(); dataSource.data = []; fixture.detectChanges(); - expect(tbody.textContent.trim()).toContain('No data'); + const noDataRow: HTMLElement = tbody.querySelector('.mat-no-data-row'); + expect(noDataRow).toBeTruthy(); + expect(noDataRow.getAttribute('role')).toBe('row'); dataSource.data = initialData; fixture.detectChanges(); - expect(tbody.textContent.trim()).not.toContain('No data'); + expect(tbody.querySelector('.mat-no-data-row')).toBeFalsy(); }); it('should render with MatTableDataSource and sort', () => { - let fixture = TestBed.createComponent(MatTableWithSortApp); + const fixture = TestBed.createComponent(MatTableWithSortApp); fixture.detectChanges(); const tableElement = fixture.nativeElement.querySelector('.mat-table')!; @@ -182,7 +186,7 @@ describe('MatTable', () => { }); it('should render with MatTableDataSource and pagination', () => { - let fixture = TestBed.createComponent(MatTableWithPaginatorApp); + const fixture = TestBed.createComponent(MatTableWithPaginatorApp); fixture.detectChanges(); const tableElement = fixture.nativeElement.querySelector('.mat-table')!; @@ -196,7 +200,7 @@ describe('MatTable', () => { }); it('should apply custom sticky CSS class to sticky cells', fakeAsync(() => { - let fixture = TestBed.createComponent(StickyTableApp); + const fixture = TestBed.createComponent(StickyTableApp); fixture.detectChanges(); flushMicrotasks(); @@ -266,32 +270,31 @@ describe('MatTable', () => { ]); }); - it('should update the page index when switching to a smaller data set from a page', - fakeAsync(() => { - // Add 20 rows so we can switch pages. - for (let i = 0; i < 20; i++) { - component.underlyingDataSource.addData(); - fixture.detectChanges(); - tick(); - fixture.detectChanges(); - } - - // Go to the last page. - fixture.componentInstance.paginator.lastPage(); - fixture.detectChanges(); - - // Switch to a smaller data set. - dataSource.data = [{a: 'a_0', b: 'b_0', c: 'c_0'}]; + it('should update the page index when switching to a smaller data set from a page', fakeAsync(() => { + // Add 20 rows so we can switch pages. + for (let i = 0; i < 20; i++) { + component.underlyingDataSource.addData(); fixture.detectChanges(); tick(); fixture.detectChanges(); + } + + // Go to the last page. + fixture.componentInstance.paginator.lastPage(); + fixture.detectChanges(); - expectTableToMatchContent(tableElement, [ - ['Column A', 'Column B', 'Column C'], - ['a_0', 'b_0', 'c_0'], - ['Footer A', 'Footer B', 'Footer C'], - ]); - })); + // Switch to a smaller data set. + dataSource.data = [{a: 'a_0', b: 'b_0', c: 'c_0'}]; + fixture.detectChanges(); + tick(); + fixture.detectChanges(); + + expectTableToMatchContent(tableElement, [ + ['Column A', 'Column B', 'Column C'], + ['a_0', 'b_0', 'c_0'], + ['Footer A', 'Footer B', 'Footer C'], + ]); + })); it('should be able to filter the table contents', fakeAsync(() => { // Change filter to a_1, should match one row @@ -305,7 +308,7 @@ describe('MatTable', () => { ['Footer A', 'Footer B', 'Footer C'], ]); - flushMicrotasks(); // Resolve promise that updates paginator's length + flushMicrotasks(); // Resolve promise that updates paginator's length expect(dataSource.paginator!.length).toBe(1); // Change filter to ' A_2 ', should match one row (ignores case and whitespace) @@ -338,10 +341,17 @@ describe('MatTable', () => { dataSource.filterPredicate = (data, filter) => { let dataStr; switch (data.a) { - case 'a_1': dataStr = 'elephant'; break; - case 'a_2': dataStr = 'zebra'; break; - case 'a_3': dataStr = 'monkey'; break; - default: dataStr = ''; + case 'a_1': + dataStr = 'elephant'; + break; + case 'a_2': + dataStr = 'zebra'; + break; + case 'a_3': + dataStr = 'monkey'; + break; + default: + dataStr = ''; } return dataStr.indexOf(filter) != -1; @@ -401,10 +411,14 @@ describe('MatTable', () => { // Change sort function to customize how it sorts - first column 1, then 3, then 2 dataSource.sortingDataAccessor = data => { switch (data.a) { - case 'a_1': return 'elephant'; - case 'a_2': return 'zebra'; - case 'a_3': return 'monkey'; - default: return ''; + case 'a_1': + return 'elephant'; + case 'a_2': + return 'zebra'; + case 'a_3': + return 'monkey'; + default: + return ''; } }; component.sort.direction = ''; @@ -460,7 +474,6 @@ describe('MatTable', () => { ['Footer A', 'Footer B', 'Footer C'], ]); - // Expect that undefined row comes after the other values component.sort.sort(component.sortHeader); fixture.detectChanges(); @@ -490,7 +503,6 @@ describe('MatTable', () => { ['Footer A', 'Footer B', 'Footer C'], ]); - // Expect that zero comes after the negative numbers and before // the positive ones when switching the sorting direction. component.sort.sort(component.sortHeader); @@ -510,7 +522,7 @@ describe('MatTable', () => { component.underlyingDataSource.addData(); } fixture.detectChanges(); - flushMicrotasks(); // Resolve promise that updates paginator's length + flushMicrotasks(); // Resolve promise that updates paginator's length expectTableToMatchContent(tableElement, [ ['Column A', 'Column B', 'Column C'], ['a_1', 'b_1', 'c_1'], @@ -554,7 +566,6 @@ describe('MatTable', () => { ['Footer A', 'Footer B', 'Footer C'], ]); - component.sort.sort(component.sortHeader); fixture.detectChanges(); expectTableToMatchContent(tableElement, [ @@ -565,24 +576,29 @@ describe('MatTable', () => { ['Footer A', 'Footer B', 'Footer C'], ]); }); - }); }); interface TestData { - a: string|number|undefined; - b: string|number|undefined; - c: string|number|undefined; + a: string | number | undefined; + b: string | number | undefined; + c: string | number | undefined; } class FakeDataSource extends DataSource { _dataChange = new BehaviorSubject([]); - get data() { return this._dataChange.getValue(); } - set data(data: TestData[]) { this._dataChange.next(data); } + get data() { + return this._dataChange.getValue(); + } + set data(data: TestData[]) { + this._dataChange.next(data); + } constructor() { super(); - for (let i = 0; i < 4; i++) { this.addData(); } + for (let i = 0; i < 4; i++) { + this.addData(); + } } connect(): Observable { @@ -598,7 +614,7 @@ class FakeDataSource extends DataSource { copiedData.push({ a: `a_${nextIndex}`, b: `b_${nextIndex}`, - c: `c_${nextIndex}` + c: `c_${nextIndex}`, }); this.data = copiedData; @@ -636,7 +652,7 @@ class FakeDataSource extends DataSource {
No data
- ` + `, }) class MatTableApp { dataSource: FakeDataSource | null = new FakeDataSource(); @@ -670,7 +686,7 @@ class MatTableApp {
No data
- ` + `, }) class NativeHtmlTableApp { dataSource: FakeDataSource | null = new FakeDataSource(); @@ -720,7 +736,7 @@ class NativeHtmlTableApp { - ` + `, }) class NestedHtmlTableApp { dataSource: FakeDataSource | null = new FakeDataSource(); @@ -738,7 +754,7 @@ class NestedHtmlTableApp { - ` + `, }) class StickyTableApp { dataSource = new FakeDataSource(); @@ -747,7 +763,6 @@ class StickyTableApp { @ViewChild(MatTable) table: MatTable; } - @Component({ template: ` @@ -766,7 +781,7 @@ class StickyTableApp { - ` + `, }) class MatTableWithWhenRowApp { multiTemplateDataRows = false; @@ -776,7 +791,6 @@ class MatTableWithWhenRowApp { @ViewChild(MatTable) table: MatTable; } - @Component({ template: ` @@ -804,7 +818,7 @@ class MatTableWithWhenRowApp { - ` + `, }) class ArrayDataSourceMatTableApp implements AfterViewInit { underlyingDataSource = new FakeDataSource(); @@ -835,7 +849,6 @@ class ArrayDataSourceMatTableApp implements AfterViewInit { } } - @Component({ template: ` @@ -857,7 +870,7 @@ class ArrayDataSourceMatTableApp implements AfterViewInit { - ` + `, }) class MatTableWithSortApp implements OnInit { underlyingDataSource = new FakeDataSource(); @@ -908,7 +921,7 @@ class MatTableWithSortApp implements OnInit { - ` + `, }) class MatTableWithPaginatorApp implements OnInit { underlyingDataSource = new FakeDataSource(); @@ -949,14 +962,13 @@ class MatTableWithPaginatorApp implements OnInit { - ` + `, }) class TableWithNgContainerRow { dataSource: FakeDataSource | null = new FakeDataSource(); columnsToRender = ['column_a']; } - function getElements(element: Element, query: string): Element[] { return [].slice.call(element.querySelectorAll(query)); } diff --git a/src/material/table/table.ts b/src/material/table/table.ts index 0f3aa1a0574f..88eba0786409 100644 --- a/src/material/table/table.ts +++ b/src/material/table/table.ts @@ -10,10 +10,26 @@ import { CDK_TABLE_TEMPLATE, CdkTable, CDK_TABLE, - _CoalescedStyleScheduler, _COALESCED_STYLE_SCHEDULER + _CoalescedStyleScheduler, + _COALESCED_STYLE_SCHEDULER, + STICKY_POSITIONING_LISTENER, } from '@angular/cdk/table'; -import {ChangeDetectionStrategy, Component, ViewEncapsulation} from '@angular/core'; -import {_DisposeViewRepeaterStrategy, _VIEW_REPEATER_STRATEGY} from '@angular/cdk/collections'; +import {ChangeDetectionStrategy, Component, Directive, ViewEncapsulation} from '@angular/core'; +import { + _DisposeViewRepeaterStrategy, + _RecycleViewRepeaterStrategy, + _VIEW_REPEATER_STRATEGY, +} from '@angular/cdk/collections'; + +/** + * Enables the recycle view repeater strategy, which reduces rendering latency. Not compatible with + * tables that animate rows. + */ +@Directive({ + selector: 'mat-table[recycleRows], table[mat-table][recycleRows]', + providers: [{provide: _VIEW_REPEATER_STRATEGY, useClass: _RecycleViewRepeaterStrategy}], +}) +export class MatRecycleRows {} /** * Wrapper for the CdkTable with Material design styles. @@ -34,6 +50,8 @@ import {_DisposeViewRepeaterStrategy, _VIEW_REPEATER_STRATEGY} from '@angular/cd {provide: CdkTable, useExisting: MatTable}, {provide: CDK_TABLE, useExisting: MatTable}, {provide: _COALESCED_STYLE_SCHEDULER, useClass: _CoalescedStyleScheduler}, + // Prevent nested tables from seeing this table's StickyPositioningListener. + {provide: STICKY_POSITIONING_LISTENER, useValue: null}, ], encapsulation: ViewEncapsulation.None, // See note on CdkTable for explanation on why this uses the default change detection strategy. @@ -42,8 +60,8 @@ import {_DisposeViewRepeaterStrategy, _VIEW_REPEATER_STRATEGY} from '@angular/cd }) export class MatTable extends CdkTable { /** Overrides the sticky CSS class set by the `CdkTable`. */ - protected stickyCssClass = 'mat-table-sticky'; + protected override stickyCssClass = 'mat-table-sticky'; /** Overrides the need to add position: sticky on every sticky cell element in `CdkTable`. */ - protected needsPositionStickyOnElement = false; + protected override needsPositionStickyOnElement = false; } diff --git a/src/material/table/testing/BUILD.bazel b/src/material/table/testing/BUILD.bazel index 564a2341fc81..53fdbd216d49 100644 --- a/src/material/table/testing/BUILD.bazel +++ b/src/material/table/testing/BUILD.bazel @@ -8,7 +8,6 @@ ts_library( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material/table/testing", deps = [ "//src/cdk/testing", ], diff --git a/src/material/table/testing/cell-harness.ts b/src/material/table/testing/cell-harness.ts index 616ede63ecf6..3eeffe4fea5e 100644 --- a/src/material/table/testing/cell-harness.ts +++ b/src/material/table/testing/cell-harness.ts @@ -9,7 +9,7 @@ import { HarnessPredicate, ComponentHarnessConstructor, - ContentContainerComponentHarness + ContentContainerComponentHarness, } from '@angular/cdk/testing'; import {CellHarnessFilters} from './table-harness-filters'; @@ -24,7 +24,7 @@ export class MatCellHarness extends ContentContainerComponentHarness { * @return a `HarnessPredicate` configured with the given options. */ static with(options: CellHarnessFilters = {}): HarnessPredicate { - return getCellPredicate(MatCellHarness, options); + return MatCellHarness._getCellPredicate(MatCellHarness, options); } /** Gets the cell's text. */ @@ -39,7 +39,10 @@ export class MatCellHarness extends ContentContainerComponentHarness { if (classAttribute) { const prefix = 'mat-column-'; - const name = classAttribute.split(' ').map(c => c.trim()).find(c => c.startsWith(prefix)); + const name = classAttribute + .split(' ') + .map(c => c.trim()) + .find(c => c.startsWith(prefix)); if (name) { return name.split(prefix)[1]; @@ -48,12 +51,25 @@ export class MatCellHarness extends ContentContainerComponentHarness { throw Error('Could not determine column name of cell.'); } + + protected static _getCellPredicate( + type: ComponentHarnessConstructor, + options: CellHarnessFilters, + ): HarnessPredicate { + return new HarnessPredicate(type, options) + .addOption('text', options.text, (harness, text) => + HarnessPredicate.stringMatches(harness.getText(), text), + ) + .addOption('columnName', options.columnName, (harness, name) => + HarnessPredicate.stringMatches(harness.getColumnName(), name), + ); + } } /** Harness for interacting with a standard Angular Material table header cell. */ export class MatHeaderCellHarness extends MatCellHarness { /** The selector for the host element of a `MatHeaderCellHarness` instance. */ - static hostSelector = '.mat-header-cell'; + static override hostSelector = '.mat-header-cell'; /** * Gets a `HarnessPredicate` that can be used to search for @@ -61,15 +77,15 @@ export class MatHeaderCellHarness extends MatCellHarness { * @param options Options for narrowing the search * @return a `HarnessPredicate` configured with the given options. */ - static with(options: CellHarnessFilters = {}): HarnessPredicate { - return getCellPredicate(MatHeaderCellHarness, options); + static override with(options: CellHarnessFilters = {}): HarnessPredicate { + return MatHeaderCellHarness._getCellPredicate(MatHeaderCellHarness, options); } } /** Harness for interacting with a standard Angular Material table footer cell. */ export class MatFooterCellHarness extends MatCellHarness { /** The selector for the host element of a `MatFooterCellHarness` instance. */ - static hostSelector = '.mat-footer-cell'; + static override hostSelector = '.mat-footer-cell'; /** * Gets a `HarnessPredicate` that can be used to search for @@ -77,18 +93,7 @@ export class MatFooterCellHarness extends MatCellHarness { * @param options Options for narrowing the search * @return a `HarnessPredicate` configured with the given options. */ - static with(options: CellHarnessFilters = {}): HarnessPredicate { - return getCellPredicate(MatFooterCellHarness, options); + static override with(options: CellHarnessFilters = {}): HarnessPredicate { + return MatFooterCellHarness._getCellPredicate(MatFooterCellHarness, options); } } - - -function getCellPredicate( - type: ComponentHarnessConstructor, - options: CellHarnessFilters): HarnessPredicate { - return new HarnessPredicate(type, options) - .addOption('text', options.text, - (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text)) - .addOption('columnName', options.columnName, - (harness, name) => HarnessPredicate.stringMatches(harness.getColumnName(), name)); -} diff --git a/src/material/table/testing/row-harness.ts b/src/material/table/testing/row-harness.ts index a9e0f99623bb..c1e5d80224bf 100644 --- a/src/material/table/testing/row-harness.ts +++ b/src/material/table/testing/row-harness.ts @@ -6,7 +6,12 @@ * found in the LICENSE file at https://angular.io/license */ -import {ComponentHarness, HarnessPredicate, parallel} from '@angular/cdk/testing'; +import { + ComponentHarness, + ComponentHarnessConstructor, + HarnessPredicate, + parallel, +} from '@angular/cdk/testing'; import {RowHarnessFilters, CellHarnessFilters} from './table-harness-filters'; import {MatCellHarness, MatHeaderCellHarness, MatFooterCellHarness} from './cell-harness'; @@ -15,10 +20,44 @@ export interface MatRowHarnessColumnsText { [columnName: string]: string; } +export abstract class _MatRowHarnessBase< + CellType extends ComponentHarnessConstructor & { + with: (options?: CellHarnessFilters) => HarnessPredicate; + }, + Cell extends ComponentHarness & {getText(): Promise; getColumnName(): Promise}, +> extends ComponentHarness { + protected abstract _cellHarness: CellType; + + /** Gets a list of `MatCellHarness` for all cells in the row. */ + async getCells(filter: CellHarnessFilters = {}): Promise { + return this.locatorForAll(this._cellHarness.with(filter))(); + } + + /** Gets the text of the cells in the row. */ + async getCellTextByIndex(filter: CellHarnessFilters = {}): Promise { + const cells = await this.getCells(filter); + return parallel(() => cells.map(cell => cell.getText())); + } + + /** Gets the text inside the row organized by columns. */ + async getCellTextByColumnName(): Promise { + const output: MatRowHarnessColumnsText = {}; + const cells = await this.getCells(); + const cellsData = await parallel(() => + cells.map(cell => { + return parallel(() => [cell.getColumnName(), cell.getText()]); + }), + ); + cellsData.forEach(([columnName, text]) => (output[columnName] = text)); + return output; + } +} + /** Harness for interacting with a standard Angular Material table row. */ -export class MatRowHarness extends ComponentHarness { +export class MatRowHarness extends _MatRowHarnessBase { /** The selector for the host element of a `MatRowHarness` instance. */ static hostSelector = '.mat-row'; + protected _cellHarness = MatCellHarness; /** * Gets a `HarnessPredicate` that can be used to search for a table row with specific attributes. @@ -28,27 +67,16 @@ export class MatRowHarness extends ComponentHarness { static with(options: RowHarnessFilters = {}): HarnessPredicate { return new HarnessPredicate(MatRowHarness, options); } - - /** Gets a list of `MatCellHarness` for all cells in the row. */ - async getCells(filter: CellHarnessFilters = {}): Promise { - return this.locatorForAll(MatCellHarness.with(filter))(); - } - - /** Gets the text of the cells in the row. */ - async getCellTextByIndex(filter: CellHarnessFilters = {}): Promise { - return getCellTextByIndex(this, filter); - } - - /** Gets the text inside the row organized by columns. */ - async getCellTextByColumnName(): Promise { - return getCellTextByColumnName(this); - } } /** Harness for interacting with a standard Angular Material table header row. */ -export class MatHeaderRowHarness extends ComponentHarness { +export class MatHeaderRowHarness extends _MatRowHarnessBase< + typeof MatHeaderCellHarness, + MatHeaderCellHarness +> { /** The selector for the host element of a `MatHeaderRowHarness` instance. */ static hostSelector = '.mat-header-row'; + protected _cellHarness = MatHeaderCellHarness; /** * Gets a `HarnessPredicate` that can be used to search for @@ -59,28 +87,16 @@ export class MatHeaderRowHarness extends ComponentHarness { static with(options: RowHarnessFilters = {}): HarnessPredicate { return new HarnessPredicate(MatHeaderRowHarness, options); } - - /** Gets a list of `MatHeaderCellHarness` for all cells in the row. */ - async getCells(filter: CellHarnessFilters = {}): Promise { - return this.locatorForAll(MatHeaderCellHarness.with(filter))(); - } - - /** Gets the text of the cells in the header row. */ - async getCellTextByIndex(filter: CellHarnessFilters = {}): Promise { - return getCellTextByIndex(this, filter); - } - - /** Gets the text inside the header row organized by columns. */ - async getCellTextByColumnName(): Promise { - return getCellTextByColumnName(this); - } } - /** Harness for interacting with a standard Angular Material table footer row. */ -export class MatFooterRowHarness extends ComponentHarness { +export class MatFooterRowHarness extends _MatRowHarnessBase< + typeof MatFooterCellHarness, + MatFooterCellHarness +> { /** The selector for the host element of a `MatFooterRowHarness` instance. */ static hostSelector = '.mat-footer-row'; + protected _cellHarness = MatFooterCellHarness; /** * Gets a `HarnessPredicate` that can be used to search for @@ -91,39 +107,4 @@ export class MatFooterRowHarness extends ComponentHarness { static with(options: RowHarnessFilters = {}): HarnessPredicate { return new HarnessPredicate(MatFooterRowHarness, options); } - - /** Gets a list of `MatFooterCellHarness` for all cells in the row. */ - async getCells(filter: CellHarnessFilters = {}): Promise { - return this.locatorForAll(MatFooterCellHarness.with(filter))(); - } - - /** Gets the text of the cells in the footer row. */ - async getCellTextByIndex(filter: CellHarnessFilters = {}): Promise { - return getCellTextByIndex(this, filter); - } - - /** Gets the text inside the footer row organized by columns. */ - async getCellTextByColumnName(): Promise { - return getCellTextByColumnName(this); - } -} - - -async function getCellTextByIndex(harness: { - getCells: (filter?: CellHarnessFilters) => Promise -}, filter: CellHarnessFilters): Promise { - const cells = await harness.getCells(filter); - return parallel(() => cells.map(cell => cell.getText())); -} - -async function getCellTextByColumnName(harness: { - getCells: () => Promise -}): Promise { - const output: MatRowHarnessColumnsText = {}; - const cells = await harness.getCells(); - const cellsData = await parallel(() => cells.map(cell => { - return parallel(() => [cell.getColumnName(), cell.getText()]); - })); - cellsData.forEach(([columnName, text]) => output[columnName] = text); - return output; } diff --git a/src/material/table/testing/shared.spec.ts b/src/material/table/testing/shared.spec.ts index abbe0dea05f9..b02a1c1cff5d 100644 --- a/src/material/table/testing/shared.spec.ts +++ b/src/material/table/testing/shared.spec.ts @@ -7,8 +7,9 @@ import {MatTableHarness} from './table-harness'; /** Shared tests to run on both the original and MDC-based table. */ export function runHarnessTests( - tableModule: typeof MatTableModule, - tableHarness: typeof MatTableHarness) { + tableModule: typeof MatTableModule, + tableHarness: typeof MatTableHarness, +) { let fixture: ComponentFixture; let loader: HarnessLoader; @@ -43,12 +44,13 @@ export function runHarnessTests( const headerRows = await table.getHeaderRows(); const footerRows = await table.getFooterRows(); const rows = await table.getRows(); - const headerCells = (await parallel(() => headerRows.map(row => row.getCells()))) - .map(row => row.length); - const footerCells = (await parallel(() => footerRows.map(row => row.getCells()))) - .map(row => row.length); - const cells = (await parallel(() => rows.map(row => row.getCells()))) - .map(row => row.length); + const headerCells = (await parallel(() => headerRows.map(row => row.getCells()))).map( + row => row.length, + ); + const footerCells = (await parallel(() => footerRows.map(row => row.getCells()))).map( + row => row.length, + ); + const cells = (await parallel(() => rows.map(row => row.getCells()))).map(row => row.length); expect(headerCells).toEqual([4]); expect(cells).toEqual([4, 4, 4, 4, 4, 4, 4, 4, 4, 4]); @@ -103,29 +105,45 @@ export function runHarnessTests( position: { headerText: ['No.'], footerText: ['Number of the element'], - text: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] + text: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'], }, name: { headerText: ['Name'], footerText: ['Name of the element'], text: [ - 'Hydrogen', 'Helium', 'Lithium', 'Beryllium', 'Boron', - 'Carbon', 'Nitrogen', 'Oxygen', 'Fluorine', 'Neon' - ] + 'Hydrogen', + 'Helium', + 'Lithium', + 'Beryllium', + 'Boron', + 'Carbon', + 'Nitrogen', + 'Oxygen', + 'Fluorine', + 'Neon', + ], }, weight: { headerText: ['Weight'], footerText: ['Weight of the element'], text: [ - '1.0079', '4.0026', '6.941', '9.0122', '10.811', - '12.0107', '14.0067', '15.9994', '18.9984', '20.1797' - ] + '1.0079', + '4.0026', + '6.941', + '9.0122', + '10.811', + '12.0107', + '14.0067', + '15.9994', + '18.9984', + '20.1797', + ], }, symbol: { headerText: ['Symbol'], footerText: ['Symbol of the element'], - text: ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne'] - } + text: ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne'], + }, }); }); @@ -143,7 +161,7 @@ export function runHarnessTests( ['7', 'Nitrogen', '14.0067', 'N'], ['8', 'Oxygen', '15.9994', 'O'], ['9', 'Fluorine', '18.9984', 'F'], - ['10', 'Neon', '20.1797', 'Ne'] + ['10', 'Neon', '20.1797', 'Ne'], ]); }); @@ -164,7 +182,7 @@ export function runHarnessTests( position: '1', name: 'Hydrogen', weight: '1.0079', - symbol: 'H' + symbol: 'H', }); }); } @@ -200,7 +218,7 @@ export function runHarnessTests( - ` + `, }) class TableHarnessTest { displayedColumns: string[] = ['position', 'name', 'weight', 'symbol']; diff --git a/src/material/table/testing/table-harness-filters.ts b/src/material/table/testing/table-harness-filters.ts index 4f8bc415d9a2..ed7cc7281023 100644 --- a/src/material/table/testing/table-harness-filters.ts +++ b/src/material/table/testing/table-harness-filters.ts @@ -17,9 +17,7 @@ export interface CellHarnessFilters extends BaseHarnessFilters { } /** A set of criteria that can be used to filter a list of row harness instances. */ -export interface RowHarnessFilters extends BaseHarnessFilters { -} +export interface RowHarnessFilters extends BaseHarnessFilters {} /** A set of criteria that can be used to filter a list of table harness instances. */ -export interface TableHarnessFilters extends BaseHarnessFilters { -} +export interface TableHarnessFilters extends BaseHarnessFilters {} diff --git a/src/material/table/testing/table-harness.ts b/src/material/table/testing/table-harness.ts index 1739e1b4b360..0bb200be6921 100644 --- a/src/material/table/testing/table-harness.ts +++ b/src/material/table/testing/table-harness.ts @@ -6,7 +6,13 @@ * found in the LICENSE file at https://angular.io/license */ -import {ContentContainerComponentHarness, HarnessPredicate, parallel} from '@angular/cdk/testing'; +import { + ComponentHarness, + ComponentHarnessConstructor, + ContentContainerComponentHarness, + HarnessPredicate, + parallel, +} from '@angular/cdk/testing'; import {TableHarnessFilters, RowHarnessFilters} from './table-harness-filters'; import { MatRowHarness, @@ -24,33 +30,42 @@ export interface MatTableHarnessColumnsText { }; } -/** Harness for interacting with a standard mat-table in tests. */ -export class MatTableHarness extends ContentContainerComponentHarness { - /** The selector for the host element of a `MatTableHarness` instance. */ - static hostSelector = '.mat-table'; +interface RowBase extends ComponentHarness { + getCellTextByColumnName(): Promise; + getCellTextByIndex(): Promise; +} - /** - * Gets a `HarnessPredicate` that can be used to search for a table with specific attributes. - * @param options Options for narrowing the search - * @return a `HarnessPredicate` configured with the given options. - */ - static with(options: TableHarnessFilters = {}): HarnessPredicate { - return new HarnessPredicate(MatTableHarness, options); - } +export abstract class _MatTableHarnessBase< + HeaderRowType extends ComponentHarnessConstructor & { + with: (options?: RowHarnessFilters) => HarnessPredicate; + }, + HeaderRow extends RowBase, + RowType extends ComponentHarnessConstructor & { + with: (options?: RowHarnessFilters) => HarnessPredicate; + }, + Row extends RowBase, + FooterRowType extends ComponentHarnessConstructor & { + with: (options?: RowHarnessFilters) => HarnessPredicate; + }, + FooterRow extends RowBase, +> extends ContentContainerComponentHarness { + protected abstract _headerRowHarness: HeaderRowType; + protected abstract _rowHarness: RowType; + protected abstract _footerRowHarness: FooterRowType; /** Gets all of the header rows in a table. */ - async getHeaderRows(filter: RowHarnessFilters = {}): Promise { - return this.locatorForAll(MatHeaderRowHarness.with(filter))(); + async getHeaderRows(filter: RowHarnessFilters = {}): Promise { + return this.locatorForAll(this._headerRowHarness.with(filter))(); } /** Gets all of the regular data rows in a table. */ - async getRows(filter: RowHarnessFilters = {}): Promise { - return this.locatorForAll(MatRowHarness.with(filter))(); + async getRows(filter: RowHarnessFilters = {}): Promise { + return this.locatorForAll(this._rowHarness.with(filter))(); } /** Gets all of the footer rows in a table. */ - async getFooterRows(filter: RowHarnessFilters = {}): Promise { - return this.locatorForAll(MatFooterRowHarness.with(filter))(); + async getFooterRows(filter: RowHarnessFilters = {}): Promise { + return this.locatorForAll(this._footerRowHarness.with(filter))(); } /** Gets the text inside the entire table organized by rows. */ @@ -64,7 +79,7 @@ export class MatTableHarness extends ContentContainerComponentHarness { const [headerRows, footerRows, dataRows] = await parallel(() => [ this.getHeaderRows(), this.getFooterRows(), - this.getRows() + this.getRows(), ]); const text: MatTableHarnessColumnsText = {}; @@ -82,7 +97,7 @@ export class MatTableHarness extends ContentContainerComponentHarness { text[columnName] = { headerText: getCellTextsByColumn(headerData, columnName), footerText: getCellTextsByColumn(footerData, columnName), - text: [] + text: [], }; } @@ -94,6 +109,31 @@ export class MatTableHarness extends ContentContainerComponentHarness { } } +/** Harness for interacting with a standard mat-table in tests. */ +export class MatTableHarness extends _MatTableHarnessBase< + typeof MatHeaderRowHarness, + MatHeaderRowHarness, + typeof MatRowHarness, + MatRowHarness, + typeof MatFooterRowHarness, + MatFooterRowHarness +> { + /** The selector for the host element of a `MatTableHarness` instance. */ + static hostSelector = '.mat-table'; + protected _headerRowHarness = MatHeaderRowHarness; + protected _rowHarness = MatRowHarness; + protected _footerRowHarness = MatFooterRowHarness; + + /** + * Gets a `HarnessPredicate` that can be used to search for a table with specific attributes. + * @param options Options for narrowing the search + * @return a `HarnessPredicate` configured with the given options. + */ + static with(options: TableHarnessFilters = {}): HarnessPredicate { + return new HarnessPredicate(MatTableHarness, options); + } +} + /** Extracts the text of cells only under a particular column. */ function getCellTextsByColumn(rowsData: MatRowHarnessColumnsText[], column: string): string[] { const columnTexts: string[] = []; diff --git a/src/material/table/text-column.spec.ts b/src/material/table/text-column.spec.ts index daa76423a36f..b8359ae8c84b 100644 --- a/src/material/table/text-column.spec.ts +++ b/src/material/table/text-column.spec.ts @@ -7,14 +7,14 @@ describe('MatTextColumn', () => { let fixture: ComponentFixture; let tableElement: HTMLElement; - beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ - imports: [MatTableModule], - declarations: [ - BasicTextColumnApp, - ], - }).compileComponents(); - })); + beforeEach( + waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [MatTableModule], + declarations: [BasicTextColumnApp], + }).compileComponents(); + }), + ); beforeEach(() => { fixture = TestBed.createComponent(BasicTextColumnApp); @@ -48,7 +48,7 @@ interface TestData { - ` + `, }) class BasicTextColumnApp { displayedColumns = ['propertyA', 'propertyB', 'propertyC']; diff --git a/src/material/table/text-column.ts b/src/material/table/text-column.ts index c970f193ee24..31616aaca24e 100644 --- a/src/material/table/text-column.ts +++ b/src/material/table/text-column.ts @@ -9,17 +9,6 @@ import {CdkTextColumn} from '@angular/cdk/table'; import {ChangeDetectionStrategy, Component, ViewEncapsulation} from '@angular/core'; -export const _MAT_TEXT_COLUMN_TEMPLATE = ` - - - {{headerText}} - - - {{dataAccessor(data, name)}} - - -`; - /** * Column that simply shows text content for the header and row cells. Assumes that the table * is using the native table implementation (``). @@ -31,7 +20,16 @@ export const _MAT_TEXT_COLUMN_TEMPLATE = ` */ @Component({ selector: 'mat-text-column', - template: _MAT_TEXT_COLUMN_TEMPLATE, + template: ` + + + + + `, encapsulation: ViewEncapsulation.None, // Change detection is intentionally not set to OnPush. This component's template will be provided // to the table to be inserted into its view. This is problematic when change detection runs since @@ -41,5 +39,4 @@ export const _MAT_TEXT_COLUMN_TEMPLATE = ` // tslint:disable-next-line:validate-decorators changeDetection: ChangeDetectionStrategy.Default, }) -export class MatTextColumn extends CdkTextColumn { -} +export class MatTextColumn extends CdkTextColumn {} diff --git a/src/material/tabs/BUILD.bazel b/src/material/tabs/BUILD.bazel index eaeb22e681c9..5cf8496dd618 100644 --- a/src/material/tabs/BUILD.bazel +++ b/src/material/tabs/BUILD.bazel @@ -24,7 +24,6 @@ ng_module( ":tab-group.css", ":tab-nav-bar/tab-nav-bar.css", ] + glob(["**/*.html"]), - module_name = "@angular/material/tabs", deps = [ "//src/cdk/a11y", "//src/cdk/bidi", diff --git a/src/material/tabs/_tabs-common.import.scss b/src/material/tabs/_tabs-common.import.scss new file mode 100644 index 000000000000..71662e338162 --- /dev/null +++ b/src/material/tabs/_tabs-common.import.scss @@ -0,0 +1,11 @@ +@forward '../core/style/private.import'; +@forward '../core/style/vendor-prefixes.import'; +@forward '../../cdk/a11y/index.import'; +@forward 'tabs-common' hide $tab-animation-duration, $tab-bar-height; +@forward 'tabs-common' as mat-* hide mat-ink-bar, mat-paginated-tab-header, +mat-paginated-tab-header-container, mat-paginated-tab-header-item-wrapper, mat-tab-label; + +@import '../core/style/variables'; +@import '../core/style/private'; +@import '../core/style/vendor-prefixes'; +@import '../../cdk/a11y'; diff --git a/src/material/tabs/_tabs-common.scss b/src/material/tabs/_tabs-common.scss index e227c182239d..5ab9cdede41a 100644 --- a/src/material/tabs/_tabs-common.scss +++ b/src/material/tabs/_tabs-common.scss @@ -1,14 +1,14 @@ -@import '../core/style/variables'; -@import '../core/style/private'; -@import '../core/style/vendor-prefixes'; -@import '../../cdk/a11y/a11y'; +@use '../core/style/variables'; +@use '../core/style/private'; +@use '../core/style/vendor-prefixes'; +@use '../../cdk/a11y'; -$mat-tab-bar-height: 48px !default; -$mat-tab-animation-duration: 500ms !default; +$tab-bar-height: 48px !default; +$tab-animation-duration: 500ms !default; // Mixin styles for labels that are contained within the tab header. @mixin tab-label { - height: $mat-tab-bar-height; + height: $tab-bar-height; padding: 0 24px; cursor: pointer; box-sizing: border-box; @@ -27,7 +27,7 @@ $mat-tab-animation-duration: 500ms !default; opacity: 1; } - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { $outline-width: 2px; outline: dotted $outline-width; outline-offset: -$outline-width; // Not supported on IE, but looks better everywhere else. @@ -37,7 +37,7 @@ $mat-tab-animation-duration: 500ms !default; &.mat-tab-disabled { cursor: default; - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { opacity: 0.5; } } @@ -49,7 +49,7 @@ $mat-tab-animation-duration: 500ms !default; white-space: nowrap; } - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { opacity: 1; } } @@ -58,18 +58,18 @@ $mat-tab-animation-duration: 500ms !default; @mixin ink-bar { $height: 2px; - @include mat-private-animation-noop(); + @include private.private-animation-noop(); position: absolute; bottom: 0; height: $height; - transition: $mat-tab-animation-duration $ease-in-out-curve-function; + transition: $tab-animation-duration variables.$ease-in-out-curve-function; .mat-tab-group-inverted-header & { bottom: auto; top: 0; } - @include cdk-high-contrast(active, off) { + @include a11y.high-contrast(active, off) { outline: solid $height; height: 0; } @@ -85,7 +85,7 @@ $mat-tab-animation-duration: 500ms !default; } .mat-tab-header-pagination { - @include user-select(none); + @include vendor-prefixes.user-select(none); position: relative; display: none; justify-content: center; @@ -120,7 +120,6 @@ $mat-tab-animation-duration: 500ms !default; .mat-tab-header-pagination-chevron { border-style: solid; border-width: 2px 2px 0 0; - content: ''; height: 8px; width: 8px; } diff --git a/src/material/tabs/_tabs-legacy-index.scss b/src/material/tabs/_tabs-legacy-index.scss new file mode 100644 index 000000000000..fab3462be5c4 --- /dev/null +++ b/src/material/tabs/_tabs-legacy-index.scss @@ -0,0 +1,6 @@ +@forward 'tabs-theme' hide color, theme, typography; +@forward 'tabs-theme' as mat-tabs-* hide mat-tabs-background, mat-tabs-density, mat-tabs-ink-bar, +mat-tabs-tab-label-focus; +@forward 'tabs-common' hide $tab-animation-duration, $tab-bar-height; +@forward 'tabs-common' as mat-* hide mat-ink-bar, mat-paginated-tab-header, +mat-paginated-tab-header-container, mat-paginated-tab-header-item-wrapper, mat-tab-label; diff --git a/src/material/tabs/_tabs-theme.import.scss b/src/material/tabs/_tabs-theme.import.scss new file mode 100644 index 000000000000..56058307fa2c --- /dev/null +++ b/src/material/tabs/_tabs-theme.import.scss @@ -0,0 +1,9 @@ +@forward '../core/theming/theming.import'; +@forward '../core/typography/typography-utils.import'; +@forward 'tabs-theme' hide color, theme, typography; +@forward 'tabs-theme' as mat-tabs-* hide mat-tabs-background, mat-tabs-density, mat-tabs-ink-bar, +mat-tabs-tab-label-focus; + +@import '../core/theming/palette'; +@import '../core/theming/theming'; +@import '../core/typography/typography-utils'; diff --git a/src/material/tabs/_tabs-theme.scss b/src/material/tabs/_tabs-theme.scss index 9bac48ab50c9..0e2c3bf192ed 100644 --- a/src/material/tabs/_tabs-theme.scss +++ b/src/material/tabs/_tabs-theme.scss @@ -1,15 +1,16 @@ -@import '../core/theming/palette'; -@import '../core/theming/theming'; -@import '../core/typography/typography-utils'; - -@mixin mat-tabs-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $primary: map-get($config, primary); - $accent: map-get($config, accent); - $warn: map-get($config, warn); - $background: map-get($config, background); - $foreground: map-get($config, foreground); - $header-border: 1px solid mat-color($foreground, divider); +@use 'sass:map'; +@use '../core/theming/theming'; +@use '../core/typography/typography'; +@use '../core/typography/typography-utils'; + +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $primary: map.get($config, primary); + $accent: map.get($config, accent); + $warn: map.get($config, warn); + $background: map.get($config, background); + $foreground: map.get($config, foreground); + $header-border: 1px solid theming.get-color-from-palette($foreground, divider); .mat-tab-nav-bar, .mat-tab-header { @@ -25,23 +26,23 @@ } .mat-tab-label, .mat-tab-link { - color: mat-color($foreground, text); + color: theming.get-color-from-palette($foreground, text); &.mat-tab-disabled { - color: mat-color($foreground, disabled-text); + color: theming.get-color-from-palette($foreground, disabled-text); } } .mat-tab-header-pagination-chevron { - border-color: mat-color($foreground, text); + border-color: theming.get-color-from-palette($foreground, text); } .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron { - border-color: mat-color($foreground, disabled-text); + border-color: theming.get-color-from-palette($foreground, disabled-text); } // Remove header border when there is a background color - .mat-tab-group[class*='mat-background-'] .mat-tab-header, + .mat-tab-group[class*='mat-background-'] > .mat-tab-header, .mat-tab-nav-bar[class*='mat-background-'] { border-bottom: none; border-top: none; @@ -57,12 +58,14 @@ @each $name, $color in $theme-colors { // Set the foreground color of the tabs &.mat-#{$name} { - @include _mat-tab-label-focus($color); - @include _mat-ink-bar($color); + @include _label-focus-color($color); + @include _ink-bar-color($color); // Override ink bar when background color is the same &.mat-background-#{$name} { - @include _mat-ink-bar($color, default-contrast); + > .mat-tab-header, > .mat-tab-link-container { + @include _ink-bar-color($color, default-contrast); + } } } } @@ -70,94 +73,108 @@ @each $name, $color in $theme-colors { // Set background color of the tabs and override focus color &.mat-background-#{$name} { - @include _mat-tab-label-focus($color); - @include _mat-tabs-background($color); + @include _label-focus-color($color); + @include _tabs-background($color); } } } } -@mixin _mat-ink-bar($color, $hue: default) { +@mixin _ink-bar-color($color, $hue: default) { .mat-ink-bar { - background-color: mat-color($color, $hue); + background-color: theming.get-color-from-palette($color, $hue); } } -@mixin _mat-tab-label-focus($tab-focus-color) { +@mixin _label-focus-color($tab-focus-color) { .mat-tab-label, .mat-tab-link { &.cdk-keyboard-focused, &.cdk-program-focused { &:not(.mat-tab-disabled) { - background-color: mat-color($tab-focus-color, lighter, 0.3); + background-color: theming.get-color-from-palette($tab-focus-color, lighter, 0.3); } } } } -@mixin _mat-tabs-background($background-color) { +@mixin _tabs-background($background-color) { + // Note that these selectors target direct descendants so + // that the styles don't apply to any nested tab groups. + // Set background color for the tab group - .mat-tab-header, .mat-tab-links, .mat-tab-header-pagination { - background-color: mat-color($background-color); + > .mat-tab-header, > .mat-tab-link-container, > .mat-tab-header-pagination { + background-color: theming.get-color-from-palette($background-color); } // Set labels to contrast against background - .mat-tab-label, .mat-tab-link { - color: mat-color($background-color, default-contrast); + > .mat-tab-header .mat-tab-label, > .mat-tab-link-container .mat-tab-link { + color: theming.get-color-from-palette($background-color, default-contrast); &.mat-tab-disabled { - color: mat-color($background-color, default-contrast, 0.4); + color: theming.get-color-from-palette($background-color, default-contrast, 0.4); } } // Set pagination chevrons to contrast background - .mat-tab-header-pagination-chevron { - border-color: mat-color($background-color, default-contrast); + > .mat-tab-header .mat-tab-header-pagination-chevron, + > .mat-tab-header-pagination .mat-tab-header-pagination-chevron, + > .mat-tab-link-container .mat-focus-indicator::before, + > .mat-tab-header .mat-focus-indicator::before { + border-color: theming.get-color-from-palette($background-color, default-contrast); } - .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron { - border-color: mat-color($background-color, default-contrast, 0.4); + > .mat-tab-header .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron, + > .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron { + // Set the color opacity via `opacity`, rather than `rgba`, because it may be a CSS variable. + border-color: theming.get-color-from-palette($background-color, default-contrast, 1); + opacity: 0.4; } // Set ripples color to be the contrast color of the new background. Otherwise the ripple // color will be based on the app background color. - .mat-ripple-element { - background-color: mat-color($background-color, default-contrast, 0.12); + > .mat-tab-header .mat-ripple-element, + > .mat-tab-link-container .mat-ripple-element, + > .mat-tab-header-pagination .mat-ripple-element { + // Set the color opacity via `opacity`, rather than `rgba`, because it may be a CSS variable. + background-color: theming.get-color-from-palette($background-color, default-contrast, 1); + opacity: 0.12; } } -@mixin mat-tabs-typography($config-or-theme) { - $config: mat-get-typography-config($config-or-theme); +@mixin typography($config-or-theme) { + $config: typography.private-typography-to-2014-config( + theming.get-typography-config($config-or-theme)); .mat-tab-group { - font-family: mat-font-family($config); + font-family: typography-utils.font-family($config); } .mat-tab-label, .mat-tab-link { font: { - family: mat-font-family($config, button); - size: mat-font-size($config, button); - weight: mat-font-weight($config, button); + family: typography-utils.font-family($config, button); + size: typography-utils.font-size($config, button); + weight: typography-utils.font-weight($config, button); } } } -@mixin _mat-tabs-density($config-or-theme) {} +@mixin _density($config-or-theme) {} -@mixin mat-tabs-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-tabs') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-tabs') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); @if $color != null { - @include mat-tabs-color($color); + @include color($color); } @if $density != null { - @include _mat-tabs-density($density); + @include _density($density); } @if $typography != null { - @include mat-tabs-typography($typography); + @include typography($typography); } } } diff --git a/src/material/tabs/ink-bar.ts b/src/material/tabs/ink-bar.ts index c357034a59ec..5291553b1b96 100644 --- a/src/material/tabs/ink-bar.ts +++ b/src/material/tabs/ink-bar.ts @@ -9,21 +9,22 @@ import {Directive, ElementRef, Inject, InjectionToken, NgZone, Optional} from '@angular/core'; import {ANIMATION_MODULE_TYPE} from '@angular/platform-browser/animations'; - /** * Interface for a a MatInkBar positioner method, defining the positioning and width of the ink * bar in a set of tabs. */ export interface _MatInkBarPositioner { - (element: HTMLElement): { left: string, width: string }; + (element: HTMLElement): {left: string; width: string}; } /** Injection token for the MatInkBar's Positioner. */ -export const _MAT_INK_BAR_POSITIONER = - new InjectionToken<_MatInkBarPositioner>('MatInkBarPositioner', { +export const _MAT_INK_BAR_POSITIONER = new InjectionToken<_MatInkBarPositioner>( + 'MatInkBarPositioner', + { providedIn: 'root', - factory: _MAT_INK_BAR_POSITIONER_FACTORY - }); + factory: _MAT_INK_BAR_POSITIONER_FACTORY, + }, +); /** * The default positioner function for the MatInkBar. @@ -54,7 +55,8 @@ export class MatInkBar { private _elementRef: ElementRef, private _ngZone: NgZone, @Inject(_MAT_INK_BAR_POSITIONER) private _inkBarPositioner: _MatInkBarPositioner, - @Optional() @Inject(ANIMATION_MODULE_TYPE) public _animationMode?: string) { } + @Optional() @Inject(ANIMATION_MODULE_TYPE) public _animationMode?: string, + ) {} /** * Calculates the styles from the provided element in order to align the ink-bar to that element. diff --git a/src/material/tabs/paginated-tab-header.ts b/src/material/tabs/paginated-tab-header.ts index 7282d5fef9c8..184e4162e7aa 100644 --- a/src/material/tabs/paginated-tab-header.ts +++ b/src/material/tabs/paginated-tab-header.ts @@ -31,10 +31,10 @@ import {takeUntil} from 'rxjs/operators'; import {Platform, normalizePassiveListenerOptions} from '@angular/cdk/platform'; import {ANIMATION_MODULE_TYPE} from '@angular/platform-browser/animations'; - /** Config used to bind passive event listeners */ -const passiveEventListenerOptions = - normalizePassiveListenerOptions({passive: true}) as EventListenerOptions; +const passiveEventListenerOptions = normalizePassiveListenerOptions({ + passive: true, +}) as EventListenerOptions; /** * The directions that scrolling can go in when the header's tabs exceed the header width. 'After' @@ -69,12 +69,14 @@ export type MatPaginatedTabHeaderItem = FocusableOption & {elementRef: ElementRe * @docs-private */ @Directive() -export abstract class MatPaginatedTabHeader implements AfterContentChecked, AfterContentInit, - AfterViewInit, OnDestroy { +export abstract class MatPaginatedTabHeader + implements AfterContentChecked, AfterContentInit, AfterViewInit, OnDestroy +{ abstract _items: QueryList; - abstract _inkBar: {hide: () => void, alignToElement: (element: HTMLElement) => void}; + abstract _inkBar: {hide: () => void; alignToElement: (element: HTMLElement) => void}; abstract _tabListContainer: ElementRef; abstract _tabList: ElementRef; + abstract _tabListInner: ElementRef; abstract _nextPaginator: ElementRef; abstract _previousPaginator: ElementRef; @@ -122,8 +124,10 @@ export abstract class MatPaginatedTabHeader implements AfterContentChecked, Afte disablePagination: boolean = false; /** The index of the active tab. */ - get selectedIndex(): number { return this._selectedIndex; } - set selectedIndex(value: number) { + get selectedIndex(): number { + return this._selectedIndex; + } + set selectedIndex(value: NumberInput) { value = coerceNumberProperty(value); if (this._selectedIndex != value) { @@ -143,14 +147,15 @@ export abstract class MatPaginatedTabHeader implements AfterContentChecked, Afte /** Event emitted when a label is focused. */ readonly indexFocused: EventEmitter = new EventEmitter(); - constructor(protected _elementRef: ElementRef, - protected _changeDetectorRef: ChangeDetectorRef, - private _viewportRuler: ViewportRuler, - @Optional() private _dir: Directionality, - private _ngZone: NgZone, - private _platform: Platform, - @Optional() @Inject(ANIMATION_MODULE_TYPE) public _animationMode?: string) { - + constructor( + protected _elementRef: ElementRef, + protected _changeDetectorRef: ChangeDetectorRef, + private _viewportRuler: ViewportRuler, + @Optional() private _dir: Directionality, + private _ngZone: NgZone, + private _platform: Platform, + @Optional() @Inject(ANIMATION_MODULE_TYPE) public _animationMode?: string, + ) { // Bind the `mouseleave` event on the outside since it doesn't change anything in the view. _ngZone.runOutsideAngular(() => { fromEvent(_elementRef.nativeElement, 'mouseleave') @@ -180,7 +185,7 @@ export abstract class MatPaginatedTabHeader implements AfterContentChecked, Afte } ngAfterContentInit() { - const dirChange = this._dir ? this._dir.change : observableOf(null); + const dirChange = this._dir ? this._dir.change : observableOf('ltr'); const resize = this._viewportRuler.change(150); const realign = () => { this.updatePagination(); @@ -200,11 +205,15 @@ export abstract class MatPaginatedTabHeader implements AfterContentChecked, Afte // On dir change or window resize, realign the ink bar and update the orientation of // the key manager if the direction has changed. - merge(dirChange, resize, this._items.changes).pipe(takeUntil(this._destroyed)).subscribe(() => { - // We need to defer this to give the browser some time to recalculate the element dimensions. - Promise.resolve().then(realign); - this._keyManager.withHorizontalOrientation(this._getLayoutDirection()); - }); + merge(dirChange, resize, this._items.changes) + .pipe(takeUntil(this._destroyed)) + .subscribe(() => { + // We need to defer this to give the browser some time to recalculate + // the element dimensions. The call has to be wrapped in `NgZone.run`, + // because the viewport change handler runs outside of Angular. + this._ngZone.run(() => Promise.resolve().then(realign)); + this._keyManager.withHorizontalOrientation(this._getLayoutDirection()); + }); // If there is a change in the focus key manager we need to emit the `indexFocused` // event in order to provide a public event that notifies about focus changes. Also we realign @@ -322,7 +331,9 @@ export abstract class MatPaginatedTabHeader implements AfterContentChecked, Afte * providing a valid index and return true. */ _isValidIndex(index: number): boolean { - if (!this._items) { return true; } + if (!this._items) { + return true; + } const tab = this._items ? this._items.toArray()[index] : null; return !!tab && !tab.disabled; @@ -386,7 +397,9 @@ export abstract class MatPaginatedTabHeader implements AfterContentChecked, Afte } /** Sets the distance in pixels that the tab header should be transformed in the X-axis. */ - get scrollDistance(): number { return this._scrollDistance; } + get scrollDistance(): number { + return this._scrollDistance; + } set scrollDistance(value: number) { this._scrollTo(value); } @@ -403,7 +416,7 @@ export abstract class MatPaginatedTabHeader implements AfterContentChecked, Afte const viewLength = this._tabListContainer.nativeElement.offsetWidth; // Move the scroll distance one-third the length of the tab list's viewport. - const scrollAmount = (direction == 'before' ? -1 : 1) * viewLength / 3; + const scrollAmount = ((direction == 'before' ? -1 : 1) * viewLength) / 3; return this._scrollTo(this._scrollDistance + scrollAmount); } @@ -440,7 +453,7 @@ export abstract class MatPaginatedTabHeader implements AfterContentChecked, Afte labelBeforePos = offsetLeft; labelAfterPos = labelBeforePos + offsetWidth; } else { - labelAfterPos = this._tabList.nativeElement.offsetWidth - offsetLeft; + labelAfterPos = this._tabListInner.nativeElement.offsetWidth - offsetLeft; labelBeforePos = labelAfterPos - offsetWidth; } @@ -469,7 +482,7 @@ export abstract class MatPaginatedTabHeader implements AfterContentChecked, Afte this._showPaginationControls = false; } else { const isEnabled = - this._tabList.nativeElement.scrollWidth > this._elementRef.nativeElement.offsetWidth; + this._tabListInner.nativeElement.scrollWidth > this._elementRef.nativeElement.offsetWidth; if (!isEnabled) { this.scrollDistance = 0; @@ -511,15 +524,15 @@ export abstract class MatPaginatedTabHeader implements AfterContentChecked, Afte * should be called sparingly. */ _getMaxScrollDistance(): number { - const lengthOfTabList = this._tabList.nativeElement.scrollWidth; + const lengthOfTabList = this._tabListInner.nativeElement.scrollWidth; const viewLength = this._tabListContainer.nativeElement.offsetWidth; - return (lengthOfTabList - viewLength) || 0; + return lengthOfTabList - viewLength || 0; } /** Tells the ink-bar to align itself to the current label wrapper */ _alignInkBarToSelectedTab(): void { - const selectedItem = this._items && this._items.length ? - this._items.toArray()[this.selectedIndex] : null; + const selectedItem = + this._items && this._items.length ? this._items.toArray()[this.selectedIndex] : null; const selectedLabelWrapper = selectedItem ? selectedItem.elementRef.nativeElement : null; if (selectedLabelWrapper) { @@ -583,6 +596,4 @@ export abstract class MatPaginatedTabHeader implements AfterContentChecked, Afte return {maxScrollDistance, distance: this._scrollDistance}; } - - static ngAcceptInputType_selectedIndex: NumberInput; } diff --git a/src/material/tabs/public-api.ts b/src/material/tabs/public-api.ts index cfce3a1ec09f..7c14d0697dd8 100644 --- a/src/material/tabs/public-api.ts +++ b/src/material/tabs/public-api.ts @@ -14,12 +14,12 @@ export { _MatTabBodyBase, MatTabBodyOriginState, MatTabBodyPositionState, - MatTabBodyPortal + MatTabBodyPortal, } from './tab-body'; export {MatTabHeader, _MatTabHeaderBase} from './tab-header'; export {MatTabLabelWrapper} from './tab-label-wrapper'; export {MatTab, MAT_TAB_GROUP} from './tab'; -export {MatTabLabel} from './tab-label'; +export {MatTabLabel, MAT_TAB} from './tab-label'; export {MatTabNav, MatTabLink, _MatTabNavBase, _MatTabLinkBase} from './tab-nav-bar/index'; export {MatTabContent} from './tab-content'; export {ScrollDirection} from './paginated-tab-header'; diff --git a/src/material/tabs/tab-body.html b/src/material/tabs/tab-body.html index f7fda5137c16..adb57188be8a 100644 --- a/src/material/tabs/tab-body.html +++ b/src/material/tabs/tab-body.html @@ -4,6 +4,7 @@ params: {animationDuration: animationDuration} }" (@translateTab.start)="_onTranslateTabStarted($event)" - (@translateTab.done)="_translateTabComplete.next($event)"> + (@translateTab.done)="_translateTabComplete.next($event)" + cdkScrollable> diff --git a/src/material/tabs/tab-body.scss b/src/material/tabs/tab-body.scss index 63daba18ea1a..a92aaf492e20 100644 --- a/src/material/tabs/tab-body.scss +++ b/src/material/tabs/tab-body.scss @@ -1,5 +1,3 @@ -@import '../core/style/vendor-prefixes'; - .mat-tab-body-content { height: 100%; overflow: auto; diff --git a/src/material/tabs/tab-body.spec.ts b/src/material/tabs/tab-body.spec.ts index b0ca02b647cc..2c83452496b6 100644 --- a/src/material/tabs/tab-body.spec.ts +++ b/src/material/tabs/tab-body.spec.ts @@ -5,30 +5,27 @@ import {AfterContentInit, Component, TemplateRef, ViewChild, ViewContainerRef} f import {waitForAsync, ComponentFixture, TestBed} from '@angular/core/testing'; import {MatRippleModule} from '@angular/material/core'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; +import {By} from '@angular/platform-browser'; +import {ScrollingModule, CdkScrollable} from '@angular/cdk/scrolling'; import {MatTabBody, MatTabBodyPortal} from './tab-body'; import {Subject} from 'rxjs'; - describe('MatTabBody', () => { let dir: Direction = 'ltr'; let dirChange: Subject = new Subject(); - beforeEach(waitForAsync(() => { - dir = 'ltr'; - TestBed.configureTestingModule({ - imports: [CommonModule, PortalModule, MatRippleModule, NoopAnimationsModule], - declarations: [ - MatTabBody, - MatTabBodyPortal, - SimpleTabBodyApp, - ], - providers: [ - {provide: Directionality, useFactory: () => ({value: dir, change: dirChange})} - ] - }); + beforeEach( + waitForAsync(() => { + dir = 'ltr'; + TestBed.configureTestingModule({ + imports: [CommonModule, PortalModule, MatRippleModule, NoopAnimationsModule], + declarations: [MatTabBody, MatTabBodyPortal, SimpleTabBodyApp], + providers: [{provide: Directionality, useFactory: () => ({value: dir, change: dirChange})}], + }); - TestBed.compileComponents(); - })); + TestBed.compileComponents(); + }), + ); describe('when initialized as center', () => { let fixture: ComponentFixture; @@ -55,7 +52,6 @@ describe('MatTabBody', () => { }); describe('in LTR direction', () => { - beforeEach(() => { dir = 'ltr'; fixture = TestBed.createComponent(SimpleTabBodyApp); @@ -178,14 +174,35 @@ describe('MatTabBody', () => { expect(fixture.componentInstance.tabBody._position).toBe('left'); }); -}); + it('should mark the tab body content as a scrollable container', () => { + TestBed.resetTestingModule() + .configureTestingModule({ + imports: [ + CommonModule, + PortalModule, + MatRippleModule, + NoopAnimationsModule, + ScrollingModule, + ], + declarations: [MatTabBody, MatTabBodyPortal, SimpleTabBodyApp], + }) + .compileComponents(); + + const fixture = TestBed.createComponent(SimpleTabBodyApp); + const tabBodyContent = fixture.nativeElement.querySelector('.mat-tab-body-content'); + const scrollable = fixture.debugElement.query(By.directive(CdkScrollable)); + + expect(scrollable).toBeTruthy(); + expect(scrollable.nativeElement).toBe(tabBodyContent); + }); +}); @Component({ template: ` Tab Body Content - ` + `, }) class SimpleTabBodyApp implements AfterContentInit { content: TemplatePortal; @@ -195,7 +212,7 @@ class SimpleTabBodyApp implements AfterContentInit { @ViewChild(MatTabBody) tabBody: MatTabBody; @ViewChild(TemplateRef) template: TemplateRef; - constructor(private _viewContainerRef: ViewContainerRef) { } + constructor(private _viewContainerRef: ViewContainerRef) {} ngAfterContentInit() { this.content = new TemplatePortal(this.template, this._viewContainerRef); diff --git a/src/material/tabs/tab-body.ts b/src/material/tabs/tab-body.ts index cfc86f47c82f..731f7380b22e 100644 --- a/src/material/tabs/tab-body.ts +++ b/src/material/tabs/tab-body.ts @@ -26,7 +26,7 @@ import { ViewChild, } from '@angular/core'; import {AnimationEvent} from '@angular/animations'; -import {TemplatePortal, CdkPortalOutlet, PortalHostDirective} from '@angular/cdk/portal'; +import {TemplatePortal, CdkPortalOutlet} from '@angular/cdk/portal'; import {Directionality, Direction} from '@angular/cdk/bidi'; import {DOCUMENT} from '@angular/common'; import {Subscription, Subject} from 'rxjs'; @@ -44,7 +44,11 @@ import {startWith, distinctUntilChanged} from 'rxjs/operators'; * psuedo-prior state. */ export type MatTabBodyPositionState = - 'left' | 'center' | 'right' | 'left-origin-center' | 'right-origin-center'; + | 'left' + | 'center' + | 'right' + | 'left-origin-center' + | 'right-origin-center'; /** * The origin state is an internally used state that is set on a new tab body indicating if it @@ -59,7 +63,7 @@ export type MatTabBodyOriginState = 'left' | 'right'; * @docs-private */ @Directive({ - selector: '[matTabBodyHost]' + selector: '[matTabBodyHost]', }) export class MatTabBodyPortal extends CdkPortalOutlet implements OnInit, OnDestroy { /** Subscription to events for when the tab body begins centering. */ @@ -71,12 +75,13 @@ export class MatTabBodyPortal extends CdkPortalOutlet implements OnInit, OnDestr componentFactoryResolver: ComponentFactoryResolver, viewContainerRef: ViewContainerRef, @Inject(forwardRef(() => MatTabBody)) private _host: MatTabBody, - @Inject(DOCUMENT) _document: any) { + @Inject(DOCUMENT) _document: any, + ) { super(componentFactoryResolver, viewContainerRef, _document); } /** Set initial visibility or set up subscription for changing visibility. */ - ngOnInit(): void { + override ngOnInit(): void { super.ngOnInit(); this._centeringSub = this._host._beforeCentering @@ -93,7 +98,7 @@ export class MatTabBodyPortal extends CdkPortalOutlet implements OnInit, OnDestr } /** Clean up centering subscription. */ - ngOnDestroy(): void { + override ngOnDestroy(): void { super.ngOnDestroy(); this._centeringSub.unsubscribe(); this._leavingSub.unsubscribe(); @@ -116,7 +121,7 @@ export abstract class _MatTabBodyBase implements OnInit, OnDestroy { _position: MatTabBodyPositionState; /** Emits when an animation on the tab is complete. */ - _translateTabComplete = new Subject(); + readonly _translateTabComplete = new Subject(); /** Event emitted when the tab begins to animate towards the center as the active tab. */ @Output() readonly _onCentering: EventEmitter = new EventEmitter(); @@ -130,8 +135,8 @@ export abstract class _MatTabBodyBase implements OnInit, OnDestroy { /** Event emitted when the tab completes its animation towards the center. */ @Output() readonly _onCentered: EventEmitter = new EventEmitter(true); - /** The portal host inside of this container into which the tab body content will be loaded. */ - abstract _portalHost: PortalHostDirective; + /** The portal host inside of this container into which the tab body content will be loaded. */ + abstract _portalHost: CdkPortalOutlet; /** The tab body content to display. */ @Input('content') _content: TemplatePortal; @@ -151,10 +156,11 @@ export abstract class _MatTabBodyBase implements OnInit, OnDestroy { this._computePositionAnimationState(); } - constructor(private _elementRef: ElementRef, - @Optional() private _dir: Directionality, - changeDetectorRef: ChangeDetectorRef) { - + constructor( + private _elementRef: ElementRef, + @Optional() private _dir: Directionality, + changeDetectorRef: ChangeDetectorRef, + ) { if (_dir) { this._dirChangeSubscription = _dir.change.subscribe((dir: Direction) => { this._computePositionAnimationState(dir); @@ -164,18 +170,22 @@ export abstract class _MatTabBodyBase implements OnInit, OnDestroy { // Ensure that we get unique animation events, because the `.done` callback can get // invoked twice in some browsers. See https://github.com/angular/angular/issues/24084. - this._translateTabComplete.pipe(distinctUntilChanged((x, y) => { - return x.fromState === y.fromState && x.toState === y.toState; - })).subscribe(event => { - // If the transition to the center is complete, emit an event. - if (this._isCenterPosition(event.toState) && this._isCenterPosition(this._position)) { - this._onCentered.emit(); - } - - if (this._isCenterPosition(event.fromState) && !this._isCenterPosition(this._position)) { - this._afterLeavingCenter.emit(); - } - }); + this._translateTabComplete + .pipe( + distinctUntilChanged((x, y) => { + return x.fromState === y.fromState && x.toState === y.toState; + }), + ) + .subscribe(event => { + // If the transition to the center is complete, emit an event. + if (this._isCenterPosition(event.toState) && this._isCenterPosition(this._position)) { + this._onCentered.emit(); + } + + if (this._isCenterPosition(event.fromState) && !this._isCenterPosition(this._position)) { + this._afterLeavingCenter.emit(); + } + }); } /** @@ -207,10 +217,10 @@ export abstract class _MatTabBodyBase implements OnInit, OnDestroy { } /** Whether the provided position state is considered center, regardless of origin. */ - _isCenterPosition(position: MatTabBodyPositionState|string): boolean { - return position == 'center' || - position == 'left-origin-center' || - position == 'right-origin-center'; + _isCenterPosition(position: MatTabBodyPositionState | string): boolean { + return ( + position == 'center' || position == 'left-origin-center' || position == 'right-origin-center' + ); } /** Computes the position state that will be used for the tab-body animation trigger. */ @@ -253,14 +263,16 @@ export abstract class _MatTabBodyBase implements OnInit, OnDestroy { animations: [matTabsAnimations.translateTab], host: { 'class': 'mat-tab-body', - } + }, }) export class MatTabBody extends _MatTabBodyBase { - @ViewChild(PortalHostDirective) _portalHost: PortalHostDirective; + @ViewChild(CdkPortalOutlet) _portalHost: CdkPortalOutlet; - constructor(elementRef: ElementRef, - @Optional() dir: Directionality, - changeDetectorRef: ChangeDetectorRef) { + constructor( + elementRef: ElementRef, + @Optional() dir: Directionality, + changeDetectorRef: ChangeDetectorRef, + ) { super(elementRef, dir, changeDetectorRef); } } diff --git a/src/material/tabs/tab-config.ts b/src/material/tabs/tab-config.ts index 5d8d30e1ab73..5c6711aa2c40 100644 --- a/src/material/tabs/tab-config.ts +++ b/src/material/tabs/tab-config.ts @@ -26,6 +26,9 @@ export interface MatTabsConfig { /** Whether the tab group should grow to the size of the active tab. */ dynamicHeight?: boolean; + + /** `tabindex` to be set on the inner element that wraps the tab content. */ + contentTabIndex?: number; } /** Injection token that can be used to provide the default options the tabs module. */ diff --git a/src/material/tabs/tab-content.ts b/src/material/tabs/tab-content.ts index 0c2ce242bfaa..03f097d324f0 100644 --- a/src/material/tabs/tab-content.ts +++ b/src/material/tabs/tab-content.ts @@ -21,6 +21,5 @@ export const MAT_TAB_CONTENT = new InjectionToken('MatTabContent' providers: [{provide: MAT_TAB_CONTENT, useExisting: MatTabContent}], }) export class MatTabContent { - constructor( - /** Content for the tab. */ public template: TemplateRef) {} + constructor(/** Content for the tab. */ public template: TemplateRef) {} } diff --git a/src/material/tabs/tab-group.html b/src/material/tabs/tab-group.html index 6bfb950472a4..268ed3076d1e 100644 --- a/src/material/tabs/tab-group.html +++ b/src/material/tabs/tab-group.html @@ -17,7 +17,8 @@ [class.mat-tab-label-active]="selectedIndex == i" [disabled]="tab.disabled" [matRippleDisabled]="tab.disabled || disableRipple" - (click)="_handleClick(tab, tabHeader, i)"> + (click)="_handleClick(tab, tabHeader, i)" + (cdkFocusChange)="_tabFocusChanged($event, i)">
@@ -39,8 +40,9 @@ { beforeEach(fakeAsync(() => { @@ -25,6 +38,8 @@ describe('MatTabGroup', () => { TabGroupWithIsActiveBinding, NestedTabs, TabGroupWithIndirectDescendantTabs, + TabGroupWithSpaceAbove, + NestedTabGroupWithLabel, ], }); @@ -50,7 +65,7 @@ describe('MatTabGroup', () => { }); it('should change selected index on click', () => { - let component = fixture.debugElement.componentInstance; + const component = fixture.debugElement.componentInstance; component.selectedIndex = 0; checkSelectedIndex(0, fixture); @@ -66,12 +81,12 @@ describe('MatTabGroup', () => { }); it('should support two-way binding for selectedIndex', fakeAsync(() => { - let component = fixture.componentInstance; + const component = fixture.componentInstance; component.selectedIndex = 0; fixture.detectChanges(); - let tabLabel = fixture.debugElement.queryAll(By.css('.mat-tab-label'))[1]; + const tabLabel = fixture.debugElement.queryAll(By.css('.mat-tab-label'))[1]; tabLabel.nativeElement.click(); fixture.detectChanges(); tick(); @@ -80,28 +95,31 @@ describe('MatTabGroup', () => { })); // Note: needs to be `async` in order to fail when we expect it to. - it('should set to correct tab on fast change', waitForAsync(() => { - let component = fixture.componentInstance; - component.selectedIndex = 0; - fixture.detectChanges(); - - setTimeout(() => { - component.selectedIndex = 1; + it( + 'should set to correct tab on fast change', + waitForAsync(() => { + const component = fixture.componentInstance; + component.selectedIndex = 0; fixture.detectChanges(); setTimeout(() => { - component.selectedIndex = 0; + component.selectedIndex = 1; fixture.detectChanges(); - fixture.whenStable().then(() => { - expect(component.selectedIndex).toBe(0); - }); + + setTimeout(() => { + component.selectedIndex = 0; + fixture.detectChanges(); + fixture.whenStable().then(() => { + expect(component.selectedIndex).toBe(0); + }); + }, 1); }, 1); - }, 1); - })); + }), + ); it('should change tabs based on selectedIndex', fakeAsync(() => { - let component = fixture.componentInstance; - let tabComponent = fixture.debugElement.query(By.css('mat-tab-group'))!.componentInstance; + const component = fixture.componentInstance; + const tabComponent = fixture.debugElement.query(By.css('mat-tab-group'))!.componentInstance; spyOn(component, 'handleSelection').and.callThrough(); @@ -118,8 +136,9 @@ describe('MatTabGroup', () => { it('should update tab positions when selected index is changed', () => { fixture.detectChanges(); - const component: MatTabGroup = - fixture.debugElement.query(By.css('mat-tab-group'))!.componentInstance; + const component: MatTabGroup = fixture.debugElement.query( + By.css('mat-tab-group'), + )!.componentInstance; const tabs: MatTab[] = component._tabs.toArray(); expect(tabs[0].position).toBeLessThan(0); @@ -143,8 +162,9 @@ describe('MatTabGroup', () => { it('should clamp the selected index to the size of the number of tabs', () => { fixture.detectChanges(); - const component: MatTabGroup = - fixture.debugElement.query(By.css('mat-tab-group'))!.componentInstance; + const component: MatTabGroup = fixture.debugElement.query( + By.css('mat-tab-group'), + )!.componentInstance; // Set the index to be negative, expect first tab selected fixture.componentInstance.selectedIndex = -1; @@ -158,7 +178,7 @@ describe('MatTabGroup', () => { }); it('should not crash when setting the selected index to NaN', () => { - let component = fixture.debugElement.componentInstance; + const component = fixture.debugElement.componentInstance; expect(() => { component.selectedIndex = NaN; @@ -173,13 +193,15 @@ describe('MatTabGroup', () => { const tabLabel = fixture.debugElement.queryAll(By.css('.mat-tab-label'))[1]; expect(testElement.querySelectorAll('.mat-ripple-element').length) - .toBe(0, 'Expected no ripples to show up initially.'); + .withContext('Expected no ripples to show up initially.') + .toBe(0); dispatchFakeEvent(tabLabel.nativeElement, 'mousedown'); dispatchFakeEvent(tabLabel.nativeElement, 'mouseup'); expect(testElement.querySelectorAll('.mat-ripple-element').length) - .toBe(1, 'Expected one ripple to show up on label mousedown.'); + .withContext('Expected one ripple to show up on label mousedown.') + .toBe(1); }); it('should allow disabling ripples for tab-group labels', () => { @@ -190,13 +212,15 @@ describe('MatTabGroup', () => { const tabLabel = fixture.debugElement.queryAll(By.css('.mat-tab-label'))[1]; expect(testElement.querySelectorAll('.mat-ripple-element').length) - .toBe(0, 'Expected no ripples to show up initially.'); + .withContext('Expected no ripples to show up initially.') + .toBe(0); dispatchFakeEvent(tabLabel.nativeElement, 'mousedown'); dispatchFakeEvent(tabLabel.nativeElement, 'mouseup'); expect(testElement.querySelectorAll('.mat-ripple-element').length) - .toBe(0, 'Expected no ripple to show up on label mousedown.'); + .withContext('Expected no ripple to show up on label mousedown.') + .toBe(0); }); it('should set the isActive flag on each of the tabs', fakeAsync(() => { @@ -222,7 +246,7 @@ describe('MatTabGroup', () => { fixture.detectChanges(); spyOn(fixture.componentInstance, 'animationDone'); - let tabLabel = fixture.debugElement.queryAll(By.css('.mat-tab-label'))[1]; + const tabLabel = fixture.debugElement.queryAll(By.css('.mat-tab-label'))[1]; tabLabel.nativeElement.click(); fixture.detectChanges(); tick(); @@ -251,8 +275,9 @@ describe('MatTabGroup', () => { fixture.detectChanges(); expect(fixture.componentInstance.handleFocus).toHaveBeenCalledTimes(1); - expect(fixture.componentInstance.handleFocus) - .toHaveBeenCalledWith(jasmine.objectContaining({index: 2})); + expect(fixture.componentInstance.handleFocus).toHaveBeenCalledWith( + jasmine.objectContaining({index: 2}), + ); }); it('should emit focusChange on arrow key navigation', () => { @@ -260,8 +285,8 @@ describe('MatTabGroup', () => { fixture.detectChanges(); const tabLabels = fixture.debugElement.queryAll(By.css('.mat-tab-label')); - const tabLabelContainer = fixture.debugElement - .query(By.css('.mat-tab-label-container'))!.nativeElement as HTMLElement; + const tabLabelContainer = fixture.debugElement.query(By.css('.mat-tab-label-container'))! + .nativeElement as HTMLElement; expect(fixture.componentInstance.handleFocus).toHaveBeenCalledTimes(0); @@ -275,13 +300,15 @@ describe('MatTabGroup', () => { dispatchKeyboardEvent(tabLabelContainer, 'keydown', LEFT_ARROW); expect(fixture.componentInstance.handleFocus).toHaveBeenCalledTimes(2); - expect(fixture.componentInstance.handleFocus) - .toHaveBeenCalledWith(jasmine.objectContaining({index: 1})); + expect(fixture.componentInstance.handleFocus).toHaveBeenCalledWith( + jasmine.objectContaining({index: 1}), + ); }); it('should clean up the tabs QueryList on destroy', () => { - const component: MatTabGroup = - fixture.debugElement.query(By.css('mat-tab-group'))!.componentInstance; + const component: MatTabGroup = fixture.debugElement.query( + By.css('mat-tab-group'), + )!.componentInstance; const spy = jasmine.createSpy('complete spy'); const subscription = component._tabs.changes.subscribe({complete: spy}); @@ -292,11 +319,66 @@ describe('MatTabGroup', () => { }); it('should have a focus indicator', () => { - const tabLabelNativeElements = - [...fixture.debugElement.nativeElement.querySelectorAll('.mat-tab-label')]; + const tabLabelNativeElements = [ + ...fixture.debugElement.nativeElement.querySelectorAll('.mat-tab-label'), + ]; + + expect(tabLabelNativeElements.every(el => el.classList.contains('mat-focus-indicator'))).toBe( + true, + ); + }); + + it('should emit focusChange when a tab receives focus', fakeAsync(() => { + spyOn(fixture.componentInstance, 'handleFocus'); + fixture.detectChanges(); + + const tabLabels = fixture.debugElement.queryAll(By.css('.mat-tab-label')); + + expect(fixture.componentInstance.handleFocus).toHaveBeenCalledTimes(0); + + // In order to verify that the `focusChange` event also fires with the correct + // index, we focus the second tab before testing the keyboard navigation. + dispatchFakeEvent(tabLabels[2].nativeElement, 'focus'); + fixture.detectChanges(); + flush(); + fixture.detectChanges(); + + expect(fixture.componentInstance.handleFocus).toHaveBeenCalledTimes(1); + expect(fixture.componentInstance.handleFocus).toHaveBeenCalledWith( + jasmine.objectContaining({index: 2}), + ); + })); + + it('should be able to programmatically focus a particular tab', () => { + fixture.detectChanges(); + const tabGroup: MatTabGroup = fixture.debugElement.query( + By.css('mat-tab-group'), + ).componentInstance; + const tabHeader: MatTabHeader = fixture.debugElement.query( + By.css('mat-tab-header'), + ).componentInstance; + + expect(tabHeader.focusIndex).not.toBe(3); + + tabGroup.focusTab(3); + fixture.detectChanges(); - expect(tabLabelNativeElements.every(el => el.classList.contains('mat-focus-indicator'))) - .toBe(true); + expect(tabHeader.focusIndex).not.toBe(3); + }); + + it('should be able to set a tabindex on the inner content element', () => { + fixture.componentInstance.contentTabIndex = 1; + fixture.detectChanges(); + const contentElements = Array.from( + fixture.nativeElement.querySelectorAll('mat-tab-body'), + ); + + expect(contentElements.map(e => e.getAttribute('tabindex'))).toEqual([null, '1', null]); + + fixture.componentInstance.selectedIndex = 0; + fixture.detectChanges(); + + expect(contentElements.map(e => e.getAttribute('tabindex'))).toEqual(['1', null, null]); }); }); @@ -368,8 +450,9 @@ describe('MatTabGroup', () => { expect(tabs[2].disabled).toBe(true); labels = fixture.debugElement.queryAll(By.css('.mat-tab-disabled')); expect(labels.length).toBe(2); - expect(labels.every(label => label.nativeElement.getAttribute('aria-disabled') === 'true')) - .toBe(true); + expect( + labels.every(label => label.nativeElement.getAttribute('aria-disabled') === 'true'), + ).toBe(true); }); }); @@ -383,42 +466,42 @@ describe('MatTabGroup', () => { fixture.detectChanges(); })); - it('should be able to add a new tab, select it, and have correct origin position', - fakeAsync(() => { - const component: MatTabGroup = - fixture.debugElement.query(By.css('mat-tab-group'))!.componentInstance; + it('should be able to add a new tab, select it, and have correct origin position', fakeAsync(() => { + const component: MatTabGroup = fixture.debugElement.query( + By.css('mat-tab-group'), + )!.componentInstance; - let tabs: MatTab[] = component._tabs.toArray(); - expect(tabs[0].origin).toBe(null); - expect(tabs[1].origin).toBe(0); - expect(tabs[2].origin).toBe(null); + let tabs: MatTab[] = component._tabs.toArray(); + expect(tabs[0].origin).toBe(null); + expect(tabs[1].origin).toBe(0); + expect(tabs[2].origin).toBe(null); - // Add a new tab on the right and select it, expect an origin >= than 0 (animate right) - fixture.componentInstance.tabs.push({label: 'New tab', content: 'to right of index'}); - fixture.componentInstance.selectedIndex = 4; - fixture.detectChanges(); - tick(); + // Add a new tab on the right and select it, expect an origin >= than 0 (animate right) + fixture.componentInstance.tabs.push({label: 'New tab', content: 'to right of index'}); + fixture.componentInstance.selectedIndex = 4; + fixture.detectChanges(); + tick(); - tabs = component._tabs.toArray(); - expect(tabs[3].origin).toBeGreaterThanOrEqual(0); + tabs = component._tabs.toArray(); + expect(tabs[3].origin).toBeGreaterThanOrEqual(0); - // Add a new tab in the beginning and select it, expect an origin < than 0 (animate left) - fixture.componentInstance.selectedIndex = 0; - fixture.detectChanges(); - tick(); + // Add a new tab in the beginning and select it, expect an origin < than 0 (animate left) + fixture.componentInstance.selectedIndex = 0; + fixture.detectChanges(); + tick(); - fixture.componentInstance.tabs.push({label: 'New tab', content: 'to left of index'}); - fixture.detectChanges(); - tick(); + fixture.componentInstance.tabs.push({label: 'New tab', content: 'to left of index'}); + fixture.detectChanges(); + tick(); - tabs = component._tabs.toArray(); - expect(tabs[0].origin).toBeLessThan(0); + tabs = component._tabs.toArray(); + expect(tabs[0].origin).toBeLessThan(0); })); - it('should update selected index if the last tab removed while selected', fakeAsync(() => { - const component: MatTabGroup = - fixture.debugElement.query(By.css('mat-tab-group'))!.componentInstance; + const component: MatTabGroup = fixture.debugElement.query( + By.css('mat-tab-group'), + )!.componentInstance; const numberOfTabs = component._tabs.length; fixture.componentInstance.selectedIndex = numberOfTabs - 1; @@ -433,11 +516,11 @@ describe('MatTabGroup', () => { expect(component.selectedIndex).toBe(numberOfTabs - 2); })); - it('should maintain the selected tab if a new tab is added', () => { fixture.detectChanges(); - const component: MatTabGroup = - fixture.debugElement.query(By.css('mat-tab-group'))!.componentInstance; + const component: MatTabGroup = fixture.debugElement.query( + By.css('mat-tab-group'), + )!.componentInstance; fixture.componentInstance.selectedIndex = 1; fixture.detectChanges(); @@ -450,14 +533,14 @@ describe('MatTabGroup', () => { expect(component._tabs.toArray()[2].isActive).toBe(true); }); - it('should maintain the selected tab if a tab is removed', () => { // Select the second tab. fixture.componentInstance.selectedIndex = 1; fixture.detectChanges(); - const component: MatTabGroup = - fixture.debugElement.query(By.css('mat-tab-group'))!.componentInstance; + const component: MatTabGroup = fixture.debugElement.query( + By.css('mat-tab-group'), + )!.componentInstance; // Remove the first tab that is right before the selected one. fixture.componentInstance.tabs.splice(0, 1); @@ -471,8 +554,9 @@ describe('MatTabGroup', () => { it('should be able to select a new tab after creation', fakeAsync(() => { fixture.detectChanges(); - const component: MatTabGroup = - fixture.debugElement.query(By.css('mat-tab-group'))!.componentInstance; + const component: MatTabGroup = fixture.debugElement.query( + By.css('mat-tab-group'), + )!.componentInstance; fixture.componentInstance.tabs.push({label: 'Last tab', content: 'at the end'}); fixture.componentInstance.selectedIndex = 3; @@ -498,7 +582,6 @@ describe('MatTabGroup', () => { expect(fixture.componentInstance.handleSelection).not.toHaveBeenCalled(); })); - }); describe('async tabs', () => { @@ -527,8 +610,8 @@ describe('MatTabGroup', () => { fixture.detectChanges(); tick(); - tabGroup = - fixture.debugElement.query(By.directive(MatTabGroup))!.componentInstance as MatTabGroup; + tabGroup = fixture.debugElement.query(By.directive(MatTabGroup))! + .componentInstance as MatTabGroup; })); it('should support a tab-group with the simple api', fakeAsync(() => { @@ -567,7 +650,7 @@ describe('MatTabGroup', () => { })); it('should support setting the header position', () => { - let tabGroupNode = fixture.debugElement.query(By.css('mat-tab-group'))!.nativeElement; + const tabGroupNode = fixture.debugElement.query(By.css('mat-tab-group'))!.nativeElement; expect(tabGroupNode.classList).not.toContain('mat-tab-group-inverted-header'); @@ -607,6 +690,25 @@ describe('MatTabGroup', () => { expect(fixture.nativeElement.textContent).toContain('pizza is active'); })); + + it('should not pick up mat-tab-label from a child tab', fakeAsync(() => { + const fixture = TestBed.createComponent(NestedTabGroupWithLabel); + fixture.detectChanges(); + tick(); + fixture.detectChanges(); + + const labels = fixture.nativeElement.querySelectorAll('.mat-tab-label-content'); + const contents = Array.from(labels).map(label => label.textContent?.trim()); + + expect(contents).toEqual([ + 'Parent 1', + 'Parent 2', + 'Parent 3', + 'Child 1', + 'Child 2', + 'Child 3', + ]); + })); }); describe('nested tabs', () => { @@ -619,10 +721,11 @@ describe('MatTabGroup', () => { const groups = fixture.componentInstance.groups.toArray(); expect(groups.length).toBe(2); - expect(groups[0]._tabs.map((tab: MatTab) => tab.textLabel)) - .toEqual(['One', 'Two']); - expect(groups[1]._tabs.map((tab: MatTab) => tab.textLabel)) - .toEqual(['Inner tab one', 'Inner tab two']); + expect(groups[0]._tabs.map((tab: MatTab) => tab.textLabel)).toEqual(['One', 'Two']); + expect(groups[1]._tabs.map((tab: MatTab) => tab.textLabel)).toEqual([ + 'Inner tab one', + 'Inner tab two', + ]); })); it('should pick up indirect descendant tabs', fakeAsync(() => { @@ -636,6 +739,46 @@ describe('MatTabGroup', () => { })); }); + describe('tall tabs', () => { + beforeEach(() => { + window.scrollTo({top: 0}); + }); + + it('should not scroll when changing tabs by clicking', fakeAsync(() => { + const fixture = TestBed.createComponent(TabGroupWithSpaceAbove); + fixture.detectChanges(); + tick(); + fixture.detectChanges(); + + window.scrollBy(0, 250); + expect(window.scrollY).toBe(250); + + // select the second tab + const tabLabel = fixture.debugElement.queryAll(By.css('.mat-tab-label'))[1]; + tabLabel.nativeElement.click(); + checkSelectedIndex(1, fixture); + + expect(window.scrollY).toBe(250); + tick(); + })); + + it('should not scroll when changing tabs programatically', fakeAsync(() => { + const fixture = TestBed.createComponent(TabGroupWithSpaceAbove); + fixture.detectChanges(); + tick(); + fixture.detectChanges(); + + window.scrollBy(0, 250); + expect(window.scrollY).toBe(250); + + fixture.componentInstance.tabGroup.selectedIndex = 1; + fixture.detectChanges(); + + expect(window.scrollY).toBe(250); + tick(); + })); + }); + /** * Checks that the `selectedIndex` has been updated; checks that the label and body have their * respective `active` classes @@ -643,16 +786,19 @@ describe('MatTabGroup', () => { function checkSelectedIndex(expectedIndex: number, fixture: ComponentFixture) { fixture.detectChanges(); - let tabComponent: MatTabGroup = fixture.debugElement - .query(By.css('mat-tab-group'))!.componentInstance; + const tabComponent: MatTabGroup = fixture.debugElement.query( + By.css('mat-tab-group'), + )!.componentInstance; expect(tabComponent.selectedIndex).toBe(expectedIndex); - let tabLabelElement = fixture.debugElement - .query(By.css(`.mat-tab-label:nth-of-type(${expectedIndex + 1})`))!.nativeElement; + const tabLabelElement = fixture.debugElement.query( + By.css(`.mat-tab-label:nth-of-type(${expectedIndex + 1})`), + )!.nativeElement; expect(tabLabelElement.classList.contains('mat-tab-label-active')).toBe(true); - let tabContentElement = fixture.debugElement - .query(By.css(`mat-tab-body:nth-of-type(${expectedIndex + 1})`))!.nativeElement; + const tabContentElement = fixture.debugElement.query( + By.css(`mat-tab-body:nth-of-type(${expectedIndex + 1})`), + )!.nativeElement; expect(tabContentElement.classList.contains('mat-tab-body-active')).toBe(true); } @@ -672,9 +818,7 @@ describe('MatTabNavBar with a default config', () => { TestBed.configureTestingModule({ imports: [MatTabsModule, BrowserAnimationsModule], declarations: [SimpleTabsTestApp], - providers: [ - {provide: MAT_TABS_CONFIG, useValue: {dynamicHeight: true}} - ] + providers: [{provide: MAT_TABS_CONFIG, useValue: {dynamicHeight: true}}], }); TestBed.compileComponents(); @@ -694,7 +838,7 @@ describe('nested MatTabGroup with enabled animations', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [MatTabsModule, BrowserAnimationsModule], - declarations: [NestedTabs, TabsWithCustomAnimationDuration] + declarations: [NestedTabs, TabsWithCustomAnimationDuration], }); TestBed.compileComponents(); @@ -702,7 +846,7 @@ describe('nested MatTabGroup with enabled animations', () => { it('should not throw when creating a component with nested tab groups', fakeAsync(() => { expect(() => { - let fixture = TestBed.createComponent(NestedTabs); + const fixture = TestBed.createComponent(NestedTabs); fixture.detectChanges(); tick(); }).not.toThrow(); @@ -710,20 +854,20 @@ describe('nested MatTabGroup with enabled animations', () => { it('should not throw when setting an animationDuration without units', fakeAsync(() => { expect(() => { - let fixture = TestBed.createComponent(TabsWithCustomAnimationDuration); + const fixture = TestBed.createComponent(TabsWithCustomAnimationDuration); fixture.detectChanges(); tick(); }).not.toThrow(); })); }); - @Component({ template: ` @@ -740,7 +884,7 @@ describe('nested MatTabGroup with enabled animations', () => { Tab three content - ` + `, }) class SimpleTabsTestApp { @ViewChild(MatTabGroup) tabGroup: MatTabGroup; @@ -749,6 +893,7 @@ class SimpleTabsTestApp { focusEvent: any; selectEvent: any; disableRipple: boolean = false; + contentTabIndex: number | null = null; headerPosition: MatTabHeaderPosition = 'above'; handleFocus(event: any) { this.focusEvent = event; @@ -756,7 +901,7 @@ class SimpleTabsTestApp { handleSelection(event: any) { this.selectEvent = event; } - animationDone() { } + animationDone() {} } @Component({ @@ -770,7 +915,7 @@ class SimpleTabsTestApp { {{tab.content}} - ` + `, }) class SimpleDynamicTabsTestApp { tabs = [ @@ -796,19 +941,19 @@ class SimpleDynamicTabsTestApp { {{tab.content}} - ` + `, }) class BindedTabsTestApp { tabs = [ - { label: 'one', content: 'one' }, - { label: 'two', content: 'two' } + {label: 'one', content: 'one'}, + {label: 'two', content: 'two'}, ]; selectedIndex = 0; addNewActiveTab(): void { this.tabs.push({ label: 'new tab', - content: 'new content' + content: 'new content', }); this.selectedIndex = this.tabs.length - 1; } @@ -846,12 +991,12 @@ class DisabledTabsTestApp { {{ tab.content }} - ` + `, }) class AsyncTabsTestApp implements OnInit { private _tabs = [ - { label: 'one', content: 'one' }, - { label: 'two', content: 'two' } + {label: 'one', content: 'one'}, + {label: 'two', content: 'two'}, ]; tabs: Observable; @@ -864,7 +1009,6 @@ class AsyncTabsTestApp implements OnInit { } } - @Component({ template: ` @@ -873,7 +1017,7 @@ class AsyncTabsTestApp implements OnInit { {{otherContent}}

Peanuts

- ` + `, }) class TabGroupWithSimpleApi { otherLabel = 'Fruit'; @@ -881,7 +1025,6 @@ class TabGroupWithSimpleApi { @ViewChild('legumes') legumes: any; } - @Component({ selector: 'nested-tabs', template: ` @@ -915,23 +1058,21 @@ class NestedTabs { `, - }) - class TemplateTabs {} - +}) +class TemplateTabs {} - @Component({ +@Component({ template: ` - ` + `, }) class TabGroupWithAriaInputs { ariaLabel: string; ariaLabelledby: string; } - @Component({ template: ` @@ -940,11 +1081,9 @@ class TabGroupWithAriaInputs {
pizza is active
- ` + `, }) -class TabGroupWithIsActiveBinding { -} - +class TabGroupWithIsActiveBinding {} @Component({ template: ` @@ -956,7 +1095,6 @@ class TabGroupWithIsActiveBinding { }) class TabsWithCustomAnimationDuration {} - @Component({ template: ` @@ -970,3 +1108,44 @@ class TabsWithCustomAnimationDuration {} class TabGroupWithIndirectDescendantTabs { @ViewChild(MatTabGroup) tabGroup: MatTabGroup; } + +@Component({ + template: ` +
+ Top Content here +
+ + + +
+
+ +
+
+
+
+ `, +}) +class TabGroupWithSpaceAbove { + @ViewChild(MatTabGroup) tabGroup: MatTabGroup; +} + +@Component({ + template: ` + + + + Content 1 + + Child 2 + Content 2 + + Child 3 + + + Parent 2 + Parent 3 + + `, +}) +class NestedTabGroupWithLabel {} diff --git a/src/material/tabs/tab-group.ts b/src/material/tabs/tab-group.ts index 500bd997d73a..318ae407779f 100644 --- a/src/material/tabs/tab-group.ts +++ b/src/material/tabs/tab-group.ts @@ -10,7 +10,7 @@ import { BooleanInput, coerceBooleanProperty, coerceNumberProperty, - NumberInput + NumberInput, } from '@angular/cdk/coercion'; import { AfterContentChecked, @@ -31,11 +31,10 @@ import { ViewChild, ViewEncapsulation, } from '@angular/core'; +import {FocusOrigin} from '@angular/cdk/a11y'; import { CanColor, - CanColorCtor, CanDisableRipple, - CanDisableRippleCtor, mixinColor, mixinDisableRipple, ThemePalette, @@ -46,7 +45,6 @@ import {startWith} from 'rxjs/operators'; import {MAT_TAB_GROUP, MatTab} from './tab'; import {MAT_TABS_CONFIG, MatTabsConfig} from './tab-config'; - /** Used to generate unique ID's for each tab component */ let nextId = 0; @@ -63,11 +61,14 @@ export type MatTabHeaderPosition = 'above' | 'below'; // Boilerplate for applying mixins to MatTabGroup. /** @docs-private */ -class MatTabGroupMixinBase { - constructor(public _elementRef: ElementRef) {} -} -const _MatTabGroupMixinBase: CanColorCtor & CanDisableRippleCtor & typeof MatTabGroupMixinBase = - mixinColor(mixinDisableRipple(MatTabGroupMixinBase), 'primary'); +const _MatTabGroupMixinBase = mixinColor( + mixinDisableRipple( + class { + constructor(public _elementRef: ElementRef) {} + }, + ), + 'primary', +); interface MatTabGroupBaseHeader { _alignInkBarToSelectedTab: () => void; @@ -79,9 +80,10 @@ interface MatTabGroupBaseHeader { * @docs-private */ @Directive() -export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements AfterContentInit, - AfterContentChecked, OnDestroy, CanColor, CanDisableRipple { - +export abstract class _MatTabGroupBase + extends _MatTabGroupMixinBase + implements AfterContentInit, AfterContentChecked, OnDestroy, CanColor, CanDisableRipple +{ /** * All tabs inside the tab group. This includes tabs that belong to groups that are nested * inside the current one. We filter out only the tabs that belong to this group in `_tabs`. @@ -107,14 +109,20 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements /** Whether the tab group should grow to the size of the active tab. */ @Input() - get dynamicHeight(): boolean { return this._dynamicHeight; } - set dynamicHeight(value: boolean) { this._dynamicHeight = coerceBooleanProperty(value); } + get dynamicHeight(): boolean { + return this._dynamicHeight; + } + set dynamicHeight(value: BooleanInput) { + this._dynamicHeight = coerceBooleanProperty(value); + } private _dynamicHeight: boolean; /** The index of the active tab. */ @Input() - get selectedIndex(): number | null { return this._selectedIndex; } - set selectedIndex(value: number | null) { + get selectedIndex(): number | null { + return this._selectedIndex; + } + set selectedIndex(value: NumberInput) { this._indexToSelect = coerceNumberProperty(value, null); } private _selectedIndex: number | null = null; @@ -124,12 +132,29 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements /** Duration for the tab animation. Will be normalized to milliseconds if no units are set. */ @Input() - get animationDuration(): string { return this._animationDuration; } - set animationDuration(value: string) { - this._animationDuration = /^\d+$/.test(value) ? value + 'ms' : value; + get animationDuration(): string { + return this._animationDuration; + } + set animationDuration(value: NumberInput) { + this._animationDuration = /^\d+$/.test(value + '') ? value + 'ms' : (value as string); } private _animationDuration: string; + /** + * `tabindex` to be set on the inner element that wraps the tab content. Can be used for improved + * accessibility when the tab does not have focusable elements or if it has scrollable content. + * The `tabindex` will be removed automatically for inactive tabs. + * Read more at https://www.w3.org/TR/wai-aria-practices/examples/tabs/tabs-2/tabs.html + */ + @Input() + get contentTabIndex(): number | null { + return this._contentTabIndex; + } + set contentTabIndex(value: NumberInput) { + this._contentTabIndex = coerceNumberProperty(value, null); + } + private _contentTabIndex: number | null; + /** * Whether pagination should be disabled. This can be used to avoid unnecessary * layout recalculations if it's known that pagination won't be required. @@ -139,7 +164,9 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements /** Background color of the tab group. */ @Input() - get backgroundColor(): ThemePalette { return this._backgroundColor; } + get backgroundColor(): ThemePalette { + return this._backgroundColor; + } set backgroundColor(value: ThemePalette) { const nativeElement: HTMLElement = this._elementRef.nativeElement; @@ -158,29 +185,34 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements /** Event emitted when focus has changed within a tab group. */ @Output() readonly focusChange: EventEmitter = - new EventEmitter(); + new EventEmitter(); /** Event emitted when the body animation has completed */ @Output() readonly animationDone: EventEmitter = new EventEmitter(); /** Event emitted when the tab selection has changed. */ @Output() readonly selectedTabChange: EventEmitter = - new EventEmitter(true); + new EventEmitter(true); private _groupId: number; - constructor(elementRef: ElementRef, - protected _changeDetectorRef: ChangeDetectorRef, - @Inject(MAT_TABS_CONFIG) @Optional() defaultConfig?: MatTabsConfig, - @Optional() @Inject(ANIMATION_MODULE_TYPE) public _animationMode?: string) { + constructor( + elementRef: ElementRef, + protected _changeDetectorRef: ChangeDetectorRef, + @Inject(MAT_TABS_CONFIG) @Optional() defaultConfig?: MatTabsConfig, + @Optional() @Inject(ANIMATION_MODULE_TYPE) public _animationMode?: string, + ) { super(elementRef); this._groupId = nextId++; - this.animationDuration = defaultConfig && defaultConfig.animationDuration ? - defaultConfig.animationDuration : '500ms'; - this.disablePagination = defaultConfig && defaultConfig.disablePagination != null ? - defaultConfig.disablePagination : false; - this.dynamicHeight = defaultConfig && defaultConfig.dynamicHeight != null ? - defaultConfig.dynamicHeight : false; + this.animationDuration = + defaultConfig && defaultConfig.animationDuration ? defaultConfig.animationDuration : '500ms'; + this.disablePagination = + defaultConfig && defaultConfig.disablePagination != null + ? defaultConfig.disablePagination + : false; + this.dynamicHeight = + defaultConfig && defaultConfig.dynamicHeight != null ? defaultConfig.dynamicHeight : false; + this.contentTabIndex = defaultConfig?.contentTabIndex ?? null; } /** @@ -192,7 +224,7 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements ngAfterContentChecked() { // Don't clamp the `indexToSelect` immediately in the setter because it can happen that // the amount of tabs changes before the actual change detection runs. - const indexToSelect = this._indexToSelect = this._clampTabIndex(this._indexToSelect); + const indexToSelect = (this._indexToSelect = this._clampTabIndex(this._indexToSelect)); // If there is a change in selected index, emit a change event. Should not trigger if // the selected index has not yet been initialized. @@ -201,15 +233,22 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements if (!isFirstRun) { this.selectedTabChange.emit(this._createChangeEvent(indexToSelect)); + // Preserve the height so page doesn't scroll up during tab change. + // Fixes https://stackblitz.com/edit/mat-tabs-scroll-page-top-on-tab-change + const wrapper = this._tabBodyWrapper.nativeElement; + wrapper.style.minHeight = wrapper.clientHeight + 'px'; } // Changing these values after change detection has run // since the checked content may contain references to them. Promise.resolve().then(() => { - this._tabs.forEach((tab, index) => tab.isActive = index === indexToSelect); + this._tabs.forEach((tab, index) => (tab.isActive = index === indexToSelect)); if (!isFirstRun) { this.selectedIndexChange.emit(indexToSelect); + // Clear the min-height, this was needed during tab change to avoid + // unnecessary scrolling. + this._tabBodyWrapper.nativeElement.style.minHeight = ''; } }); } @@ -265,12 +304,14 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements // Since we use a query with `descendants: true` to pick up the tabs, we may end up catching // some that are inside of nested tab groups. We filter them out manually by checking that // the closest group to the tab is the current one. - this._allTabs.changes - .pipe(startWith(this._allTabs)) - .subscribe((tabs: QueryList) => { - this._tabs.reset(tabs.filter(tab => tab._closestTabGroup === this)); - this._tabs.notifyOnChanges(); - }); + this._allTabs.changes.pipe(startWith(this._allTabs)).subscribe((tabs: QueryList) => { + this._tabs.reset( + tabs.filter(tab => { + return tab._closestTabGroup === this || !tab._closestTabGroup; + }), + ); + this._tabs.notifyOnChanges(); + }); } ngOnDestroy() { @@ -286,12 +327,24 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements } } + /** + * Sets focus to a particular tab. + * @param index Index of the tab to be focused. + */ + focusTab(index: number) { + const header = this._tabHeader; + + if (header) { + header.focusIndex = index; + } + } + _focusChanged(index: number) { this.focusChange.emit(this._createChangeEvent(index)); } private _createChangeEvent(index: number): MatTabChangeEvent { - const event = new MatTabChangeEvent; + const event = new MatTabChangeEvent(); event.index = index; if (this._tabs && this._tabs.length) { event.tab = this._tabs.toArray()[index]; @@ -310,8 +363,9 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements this._tabLabelSubscription.unsubscribe(); } - this._tabLabelSubscription = merge(...this._tabs.map(tab => tab._stateChanges)) - .subscribe(() => this._changeDetectorRef.markForCheck()); + this._tabLabelSubscription = merge(...this._tabs.map(tab => tab._stateChanges)).subscribe(() => + this._changeDetectorRef.markForCheck(), + ); } /** Clamps the given index to the bounds of 0 and the tabs length. */ @@ -337,7 +391,9 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements * height property is true. */ _setTabBodyWrapperHeight(tabHeight: number): void { - if (!this._dynamicHeight || !this._tabBodyWrapperHeight) { return; } + if (!this._dynamicHeight || !this._tabBodyWrapperHeight) { + return; + } const wrapper: HTMLElement = this._tabBodyWrapper.nativeElement; @@ -373,10 +429,16 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements return this.selectedIndex === idx ? 0 : -1; } - static ngAcceptInputType_dynamicHeight: BooleanInput; - static ngAcceptInputType_animationDuration: NumberInput; - static ngAcceptInputType_selectedIndex: NumberInput; - static ngAcceptInputType_disableRipple: BooleanInput; + /** Callback for when the focused state of a tab has changed. */ + _tabFocusChanged(focusOrigin: FocusOrigin, index: number) { + // Mouse/touch focus happens during the `mousedown`/`touchstart` phase which + // can cause the tab to be moved out from under the pointer, interrupting the + // click sequence (see #21898). We don't need to scroll the tab into view for + // such cases anyway, because it will be done when the tab becomes selected. + if (focusOrigin && focusOrigin !== 'mouse' && focusOrigin !== 'touch') { + this._tabHeader.focusIndex = index; + } + } } /** @@ -393,10 +455,12 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements // tslint:disable-next-line:validate-decorators changeDetection: ChangeDetectionStrategy.Default, inputs: ['color', 'disableRipple'], - providers: [{ - provide: MAT_TAB_GROUP, - useExisting: MatTabGroup - }], + providers: [ + { + provide: MAT_TAB_GROUP, + useExisting: MatTabGroup, + }, + ], host: { 'class': 'mat-tab-group', '[class.mat-tab-group-dynamic-height]': 'dynamicHeight', @@ -408,10 +472,12 @@ export class MatTabGroup extends _MatTabGroupBase { @ViewChild('tabBodyWrapper') _tabBodyWrapper: ElementRef; @ViewChild('tabHeader') _tabHeader: MatTabGroupBaseHeader; - constructor(elementRef: ElementRef, - changeDetectorRef: ChangeDetectorRef, - @Inject(MAT_TABS_CONFIG) @Optional() defaultConfig?: MatTabsConfig, - @Optional() @Inject(ANIMATION_MODULE_TYPE) animationMode?: string) { + constructor( + elementRef: ElementRef, + changeDetectorRef: ChangeDetectorRef, + @Inject(MAT_TABS_CONFIG) @Optional() defaultConfig?: MatTabsConfig, + @Optional() @Inject(ANIMATION_MODULE_TYPE) animationMode?: string, + ) { super(elementRef, changeDetectorRef, defaultConfig, animationMode); } } diff --git a/src/material/tabs/tab-header.html b/src/material/tabs/tab-header.html index e3febcb6f045..f963f9f3d003 100644 --- a/src/material/tabs/tab-header.html +++ b/src/material/tabs/tab-header.html @@ -16,7 +16,7 @@ [class._mat-animation-noopable]="_animationMode === 'NoopAnimations'" role="tablist" (cdkObserveContent)="_onContentChanges()"> -
+
diff --git a/src/material/tabs/tab-header.scss b/src/material/tabs/tab-header.scss index 4d9f737580a0..1cb81c98363d 100644 --- a/src/material/tabs/tab-header.scss +++ b/src/material/tabs/tab-header.scss @@ -1,31 +1,32 @@ -@import '../core/style/private'; -@import './tabs-common'; +@use '../core/style/private'; +@use './tabs-common'; +@use '../core/style/variables'; -@include paginated-tab-header; +@include tabs-common.paginated-tab-header; .mat-ink-bar { - @include ink-bar; + @include tabs-common.ink-bar; } .mat-tab-labels { - @include paginated-tab-header-item-wrapper('.mat-tab-header'); + @include tabs-common.paginated-tab-header-item-wrapper('.mat-tab-header'); } .mat-tab-label-container { - @include paginated-tab-header-container; + @include tabs-common.paginated-tab-header-container; } .mat-tab-list { - @include mat-private-animation-noop(); + @include private.private-animation-noop(); } // Wraps each tab label .mat-tab-label { - @include tab-label; + @include tabs-common.tab-label; position: relative; } -@media ($mat-xsmall) { +@media (variables.$xsmall) { .mat-tab-label { min-width: 72px; } diff --git a/src/material/tabs/tab-header.spec.ts b/src/material/tabs/tab-header.spec.ts index 53557f362f32..41749fd0adee 100644 --- a/src/material/tabs/tab-header.spec.ts +++ b/src/material/tabs/tab-header.spec.ts @@ -8,7 +8,7 @@ import { createKeyboardEvent, dispatchEvent, createMouseEvent, -} from '@angular/cdk/testing/private'; +} from '../../cdk/testing/private'; import {CommonModule} from '@angular/common'; import {Component, ViewChild} from '@angular/core'; import { @@ -27,31 +27,27 @@ import {MatTabLabelWrapper} from './tab-label-wrapper'; import {Subject} from 'rxjs'; import {ObserversModule, MutationObserverFactory} from '@angular/cdk/observers'; - describe('MatTabHeader', () => { let dir: Direction = 'ltr'; let change = new Subject(); let fixture: ComponentFixture; let appComponent: SimpleTabHeaderApp; - beforeEach(waitForAsync(() => { - dir = 'ltr'; - TestBed.configureTestingModule({ - imports: [CommonModule, PortalModule, MatRippleModule, ScrollingModule, ObserversModule], - declarations: [ - MatTabHeader, - MatInkBar, - MatTabLabelWrapper, - SimpleTabHeaderApp, - ], - providers: [ - ViewportRuler, - {provide: Directionality, useFactory: () => ({value: dir, change: change})}, - ] - }); + beforeEach( + waitForAsync(() => { + dir = 'ltr'; + TestBed.configureTestingModule({ + imports: [CommonModule, PortalModule, MatRippleModule, ScrollingModule, ObserversModule], + declarations: [MatTabHeader, MatInkBar, MatTabLabelWrapper, SimpleTabHeaderApp], + providers: [ + ViewportRuler, + {provide: Directionality, useFactory: () => ({value: dir, change: change})}, + ], + }); - TestBed.compileComponents(); - })); + TestBed.compileComponents(); + }), + ); describe('focusing', () => { let tabListContainer: HTMLElement; @@ -220,8 +216,7 @@ describe('MatTabHeader', () => { }); it('should not do anything if a modifier key is pressed', () => { - const rightArrowEvent = createKeyboardEvent( - 'keydown', RIGHT_ARROW, undefined, {shift: true}); + const rightArrowEvent = createKeyboardEvent('keydown', RIGHT_ARROW, undefined, {shift: true}); const enterEvent = createKeyboardEvent('keydown', ENTER, undefined, {shift: true}); appComponent.tabHeader.focusIndex = 0; @@ -239,7 +234,6 @@ describe('MatTabHeader', () => { expect(appComponent.selectedIndex).toBe(0); expect(enterEvent.defaultPrevented).toBe(false); }); - }); describe('pagination', () => { @@ -271,8 +265,9 @@ describe('MatTabHeader', () => { // Focus on the last tab, expect this to be the maximum scroll distance. appComponent.tabHeader.focusIndex = appComponent.tabs.length - 1; fixture.detectChanges(); - expect(appComponent.tabHeader.scrollDistance) - .toBe(appComponent.tabHeader._getMaxScrollDistance()); + expect(appComponent.tabHeader.scrollDistance).toBe( + appComponent.tabHeader._getMaxScrollDistance(), + ); // Focus on the first tab, expect this to be the maximum scroll distance. appComponent.tabHeader.focusIndex = 0; @@ -289,13 +284,15 @@ describe('MatTabHeader', () => { const buttonAfter = fixture.debugElement.query(By.css('.mat-tab-header-pagination-after'))!; expect(fixture.nativeElement.querySelectorAll('.mat-ripple-element').length) - .toBe(0, 'Expected no ripple to show up initially.'); + .withContext('Expected no ripple to show up initially.') + .toBe(0); dispatchFakeEvent(buttonAfter.nativeElement, 'mousedown'); dispatchFakeEvent(buttonAfter.nativeElement, 'mouseup'); expect(fixture.nativeElement.querySelectorAll('.mat-ripple-element').length) - .toBe(1, 'Expected one ripple to show up after mousedown'); + .withContext('Expected one ripple to show up after mousedown') + .toBe(1); }); it('should allow disabling ripples for pagination buttons', () => { @@ -308,15 +305,16 @@ describe('MatTabHeader', () => { const buttonAfter = fixture.debugElement.query(By.css('.mat-tab-header-pagination-after'))!; expect(fixture.nativeElement.querySelectorAll('.mat-ripple-element').length) - .toBe(0, 'Expected no ripple to show up initially.'); + .withContext('Expected no ripple to show up initially.') + .toBe(0); dispatchFakeEvent(buttonAfter.nativeElement, 'mousedown'); dispatchFakeEvent(buttonAfter.nativeElement, 'mouseup'); expect(fixture.nativeElement.querySelectorAll('.mat-ripple-element').length) - .toBe(0, 'Expected no ripple to show up after mousedown'); + .withContext('Expected no ripple to show up after mousedown') + .toBe(0); }); - }); describe('rtl', () => { @@ -337,8 +335,9 @@ describe('MatTabHeader', () => { // Focus on the last tab, expect this to be the maximum scroll distance. appComponent.tabHeader.focusIndex = appComponent.tabs.length - 1; fixture.detectChanges(); - expect(appComponent.tabHeader.scrollDistance) - .toBe(appComponent.tabHeader._getMaxScrollDistance()); + expect(appComponent.tabHeader.scrollDistance).toBe( + appComponent.tabHeader._getMaxScrollDistance(), + ); // Focus on the first tab, expect this to be the maximum scroll distance. appComponent.tabHeader.focusIndex = 0; @@ -367,28 +366,24 @@ describe('MatTabHeader', () => { headerElement = fixture.nativeElement.querySelector('.mat-tab-header'); }); - it('should scroll towards the end while holding down the next button using a mouse', - fakeAsync(() => { - assertNextButtonScrolling('mousedown', 'click'); - })); + it('should scroll towards the end while holding down the next button using a mouse', fakeAsync(() => { + assertNextButtonScrolling('mousedown', 'click'); + })); - it('should scroll towards the start while holding down the prev button using a mouse', - fakeAsync(() => { - assertPrevButtonScrolling('mousedown', 'click'); - })); + it('should scroll towards the start while holding down the prev button using a mouse', fakeAsync(() => { + assertPrevButtonScrolling('mousedown', 'click'); + })); - it('should scroll towards the end while holding down the next button using touch', - fakeAsync(() => { - assertNextButtonScrolling('touchstart', 'touchend'); - })); + it('should scroll towards the end while holding down the next button using touch', fakeAsync(() => { + assertNextButtonScrolling('touchstart', 'touchend'); + })); - it('should scroll towards the start while holding down the prev button using touch', - fakeAsync(() => { - assertPrevButtonScrolling('touchstart', 'touchend'); - })); + it('should scroll towards the start while holding down the prev button using touch', fakeAsync(() => { + assertPrevButtonScrolling('touchstart', 'touchend'); + })); it('should not scroll if the sequence is interrupted quickly', fakeAsync(() => { - expect(header.scrollDistance).toBe(0, 'Expected to start off not scrolled.'); + expect(header.scrollDistance).withContext('Expected to start off not scrolled.').toBe(0); dispatchFakeEvent(nextButton, 'mousedown'); fixture.detectChanges(); @@ -400,7 +395,9 @@ describe('MatTabHeader', () => { tick(3000); - expect(header.scrollDistance).toBe(0, 'Expected not to have scrolled after a while.'); + expect(header.scrollDistance) + .withContext('Expected not to have scrolled after a while.') + .toBe(0); })); it('should clear the timeouts on destroy', fakeAsync(() => { @@ -455,19 +452,23 @@ describe('MatTabHeader', () => { })); it('should stop scrolling if the pointer leaves the header', fakeAsync(() => { - expect(header.scrollDistance).toBe(0, 'Expected to start off not scrolled.'); + expect(header.scrollDistance).withContext('Expected to start off not scrolled.').toBe(0); dispatchFakeEvent(nextButton, 'mousedown'); fixture.detectChanges(); tick(300); - expect(header.scrollDistance).toBe(0, 'Expected not to scroll after short amount of time.'); + expect(header.scrollDistance) + .withContext('Expected not to scroll after short amount of time.') + .toBe(0); tick(1000); - expect(header.scrollDistance).toBeGreaterThan(0, 'Expected to scroll after some time.'); + expect(header.scrollDistance) + .withContext('Expected to scroll after some time.') + .toBeGreaterThan(0); - let previousDistance = header.scrollDistance; + const previousDistance = header.scrollDistance; dispatchFakeEvent(headerElement, 'mouseleave'); fixture.detectChanges(); @@ -477,13 +478,15 @@ describe('MatTabHeader', () => { })); it('should not scroll when pressing the right mouse button', fakeAsync(() => { - expect(header.scrollDistance).toBe(0, 'Expected to start off not scrolled.'); + expect(header.scrollDistance).withContext('Expected to start off not scrolled.').toBe(0); dispatchEvent(nextButton, createMouseEvent('mousedown', undefined, undefined, 2)); fixture.detectChanges(); tick(3000); - expect(header.scrollDistance).toBe(0, 'Expected not to have scrolled after a while.'); + expect(header.scrollDistance) + .withContext('Expected not to have scrolled after a while.') + .toBe(0); })); /** @@ -492,24 +495,29 @@ describe('MatTabHeader', () => { * @param endEventName Name of the event that is supposed to end the scrolling. */ function assertNextButtonScrolling(startEventName: string, endEventName: string) { - expect(header.scrollDistance).toBe(0, 'Expected to start off not scrolled.'); + expect(header.scrollDistance).withContext('Expected to start off not scrolled.').toBe(0); dispatchFakeEvent(nextButton, startEventName); fixture.detectChanges(); tick(300); - expect(header.scrollDistance).toBe(0, 'Expected not to scroll after short amount of time.'); + expect(header.scrollDistance) + .withContext('Expected not to scroll after short amount of time.') + .toBe(0); tick(1000); - expect(header.scrollDistance).toBeGreaterThan(0, 'Expected to scroll after some time.'); + expect(header.scrollDistance) + .withContext('Expected to scroll after some time.') + .toBeGreaterThan(0); - let previousDistance = header.scrollDistance; + const previousDistance = header.scrollDistance; tick(100); expect(header.scrollDistance) - .toBeGreaterThan(previousDistance, 'Expected to scroll again after some more time.'); + .withContext('Expected to scroll again after some more time.') + .toBeGreaterThan(previousDistance); dispatchFakeEvent(nextButton, endEventName); } @@ -525,30 +533,32 @@ describe('MatTabHeader', () => { let currentScroll = header.scrollDistance; - expect(currentScroll).toBeGreaterThan(0, 'Expected to start off scrolled.'); + expect(currentScroll).withContext('Expected to start off scrolled.').toBeGreaterThan(0); dispatchFakeEvent(prevButton, startEventName); fixture.detectChanges(); tick(300); expect(header.scrollDistance) - .toBe(currentScroll, 'Expected not to scroll after short amount of time.'); + .withContext('Expected not to scroll after short amount of time.') + .toBe(currentScroll); tick(1000); expect(header.scrollDistance) - .toBeLessThan(currentScroll, 'Expected to scroll after some time.'); + .withContext('Expected to scroll after some time.') + .toBeLessThan(currentScroll); currentScroll = header.scrollDistance; tick(100); expect(header.scrollDistance) - .toBeLessThan(currentScroll, 'Expected to scroll again after some more time.'); + .withContext('Expected to scroll again after some more time.') + .toBeLessThan(currentScroll); dispatchFakeEvent(nextButton, endEventName); } - }); describe('disabling pagination', () => { @@ -636,20 +646,20 @@ describe('MatTabHeader', () => { TestBed.overrideProvider(MutationObserverFactory, { useValue: { // Stub out the MutationObserver since the native one is async. - create: function(callback: Function) { + create: function (callback: Function) { mutationCallbacks.push(callback); return {observe: () => {}, disconnect: () => {}}; - } - } + }, + }, }); fixture = TestBed.createComponent(SimpleTabHeaderApp); fixture.detectChanges(); - const tabHeaderElement: HTMLElement = - fixture.nativeElement.querySelector('.mat-tab-header'); - const labels = - Array.from(fixture.nativeElement.querySelectorAll('.label-content')); + const tabHeaderElement: HTMLElement = fixture.nativeElement.querySelector('.mat-tab-header'); + const labels = Array.from( + fixture.nativeElement.querySelectorAll('.label-content'), + ); const extraText = new Array(100).fill('w').join(); const enabledClass = 'mat-tab-header-pagination-controls-enabled'; @@ -665,7 +675,6 @@ describe('MatTabHeader', () => { expect(tabHeaderElement.classList).toContain(enabledClass); }); - }); }); @@ -690,11 +699,13 @@ interface Tab {
`, - styles: [` + styles: [ + ` :host { width: 130px; } - `] + `, + ], }) class SimpleTabHeaderApp { disableRipple: boolean = false; diff --git a/src/material/tabs/tab-header.ts b/src/material/tabs/tab-header.ts index ac4664015f6f..7a7062b77d49 100644 --- a/src/material/tabs/tab-header.ts +++ b/src/material/tabs/tab-header.ts @@ -39,22 +39,29 @@ import {MatPaginatedTabHeader} from './paginated-tab-header'; * @docs-private */ @Directive() -export abstract class _MatTabHeaderBase extends MatPaginatedTabHeader implements - AfterContentChecked, AfterContentInit, AfterViewInit, OnDestroy { - +export abstract class _MatTabHeaderBase + extends MatPaginatedTabHeader + implements AfterContentChecked, AfterContentInit, AfterViewInit, OnDestroy +{ /** Whether the ripple effect is disabled or not. */ @Input() - get disableRipple() { return this._disableRipple; } - set disableRipple(value: any) { this._disableRipple = coerceBooleanProperty(value); } + get disableRipple(): boolean { + return this._disableRipple; + } + set disableRipple(value: BooleanInput) { + this._disableRipple = coerceBooleanProperty(value); + } private _disableRipple: boolean = false; - constructor(elementRef: ElementRef, - changeDetectorRef: ChangeDetectorRef, - viewportRuler: ViewportRuler, - @Optional() dir: Directionality, - ngZone: NgZone, - platform: Platform, - @Optional() @Inject(ANIMATION_MODULE_TYPE) animationMode?: string) { + constructor( + elementRef: ElementRef, + changeDetectorRef: ChangeDetectorRef, + viewportRuler: ViewportRuler, + @Optional() dir: Directionality, + ngZone: NgZone, + platform: Platform, + @Optional() @Inject(ANIMATION_MODULE_TYPE) animationMode?: string, + ) { super(elementRef, changeDetectorRef, viewportRuler, dir, ngZone, platform, animationMode); } @@ -90,18 +97,19 @@ export class MatTabHeader extends _MatTabHeaderBase { @ViewChild(MatInkBar, {static: true}) _inkBar: MatInkBar; @ViewChild('tabListContainer', {static: true}) _tabListContainer: ElementRef; @ViewChild('tabList', {static: true}) _tabList: ElementRef; + @ViewChild('tabListInner', {static: true}) _tabListInner: ElementRef; @ViewChild('nextPaginator') _nextPaginator: ElementRef; @ViewChild('previousPaginator') _previousPaginator: ElementRef; - constructor(elementRef: ElementRef, - changeDetectorRef: ChangeDetectorRef, - viewportRuler: ViewportRuler, - @Optional() dir: Directionality, - ngZone: NgZone, - platform: Platform, - @Optional() @Inject(ANIMATION_MODULE_TYPE) animationMode?: string) { + constructor( + elementRef: ElementRef, + changeDetectorRef: ChangeDetectorRef, + viewportRuler: ViewportRuler, + @Optional() dir: Directionality, + ngZone: NgZone, + platform: Platform, + @Optional() @Inject(ANIMATION_MODULE_TYPE) animationMode?: string, + ) { super(elementRef, changeDetectorRef, viewportRuler, dir, ngZone, platform, animationMode); } - - static ngAcceptInputType_disableRipple: BooleanInput; } diff --git a/src/material/tabs/tab-label-wrapper.ts b/src/material/tabs/tab-label-wrapper.ts index a77f03b2b982..0ae024e09126 100644 --- a/src/material/tabs/tab-label-wrapper.ts +++ b/src/material/tabs/tab-label-wrapper.ts @@ -6,16 +6,12 @@ * found in the LICENSE file at https://angular.io/license */ -import {BooleanInput} from '@angular/cdk/coercion'; import {Directive, ElementRef} from '@angular/core'; -import {CanDisable, CanDisableCtor, mixinDisabled} from '@angular/material/core'; - +import {CanDisable, mixinDisabled} from '@angular/material/core'; // Boilerplate for applying mixins to MatTabLabelWrapper. /** @docs-private */ -class MatTabLabelWrapperBase {} -const _MatTabLabelWrapperMixinBase: CanDisableCtor & typeof MatTabLabelWrapperBase = - mixinDisabled(MatTabLabelWrapperBase); +const _MatTabLabelWrapperBase = mixinDisabled(class {}); /** * Used in the `mat-tab-group` view to display tab labels. @@ -27,9 +23,9 @@ const _MatTabLabelWrapperMixinBase: CanDisableCtor & typeof MatTabLabelWrapperBa host: { '[class.mat-tab-disabled]': 'disabled', '[attr.aria-disabled]': '!!disabled', - } + }, }) -export class MatTabLabelWrapper extends _MatTabLabelWrapperMixinBase implements CanDisable { +export class MatTabLabelWrapper extends _MatTabLabelWrapperBase implements CanDisable { constructor(public elementRef: ElementRef) { super(); } @@ -46,6 +42,4 @@ export class MatTabLabelWrapper extends _MatTabLabelWrapperMixinBase implements getOffsetWidth(): number { return this.elementRef.nativeElement.offsetWidth; } - - static ngAcceptInputType_disabled: BooleanInput; } diff --git a/src/material/tabs/tab-label.ts b/src/material/tabs/tab-label.ts index 06f59b9c208f..9f2bc58d7aeb 100644 --- a/src/material/tabs/tab-label.ts +++ b/src/material/tabs/tab-label.ts @@ -6,7 +6,14 @@ * found in the LICENSE file at https://angular.io/license */ -import {Directive, InjectionToken} from '@angular/core'; +import { + Directive, + Inject, + InjectionToken, + Optional, + TemplateRef, + ViewContainerRef, +} from '@angular/core'; import {CdkPortal} from '@angular/cdk/portal'; /** @@ -16,9 +23,23 @@ import {CdkPortal} from '@angular/cdk/portal'; */ export const MAT_TAB_LABEL = new InjectionToken('MatTabLabel'); +/** + * Used to provide a tab label to a tab without causing a circular dependency. + * @docs-private + */ +export const MAT_TAB = new InjectionToken('MAT_TAB'); + /** Used to flag tab labels for use with the portal directive */ @Directive({ selector: '[mat-tab-label], [matTabLabel]', providers: [{provide: MAT_TAB_LABEL, useExisting: MatTabLabel}], }) -export class MatTabLabel extends CdkPortal {} +export class MatTabLabel extends CdkPortal { + constructor( + templateRef: TemplateRef, + viewContainerRef: ViewContainerRef, + @Inject(MAT_TAB) @Optional() public _closestTab: any, + ) { + super(templateRef, viewContainerRef); + } +} diff --git a/src/material/tabs/tab-nav-bar/tab-nav-bar.html b/src/material/tabs/tab-nav-bar/tab-nav-bar.html index 315f57a4e978..8cf81484051a 100644 --- a/src/material/tabs/tab-nav-bar/tab-nav-bar.html +++ b/src/material/tabs/tab-nav-bar/tab-nav-bar.html @@ -15,7 +15,7 @@ [class._mat-animation-noopable]="_animationMode === 'NoopAnimations'" #tabList (cdkObserveContent)="_onContentChanges()"> - `, }) class ScrollableTooltipDemo { - position: string = 'below'; - message: string = initialTooltipMessage; - showButton: boolean = true; + position: string = 'below'; + message: string = initialTooltipMessage; + showButton: boolean = true; - @ViewChild(CdkScrollable) scrollingContainer: CdkScrollable; + @ViewChild(CdkScrollable) scrollingContainer: CdkScrollable; - scrollDown() { - const scrollingContainerEl = this.scrollingContainer.getElementRef().nativeElement; - scrollingContainerEl.scrollTop = 250; + scrollDown() { + const scrollingContainerEl = this.scrollingContainer.getElementRef().nativeElement; + scrollingContainerEl.scrollTop = 250; - // Emit a scroll event from the scrolling element in our component. - // This event should be picked up by the scrollable directive and notify. - // The notification should be picked up by the service. - dispatchFakeEvent(scrollingContainerEl, 'scroll'); - } + // Emit a scroll event from the scrolling element in our component. + // This event should be picked up by the scrollable directive and notify. + // The notification should be picked up by the service. + dispatchFakeEvent(scrollingContainerEl, 'scroll'); + } } @Component({ @@ -1223,14 +1384,13 @@ class ScrollableTooltipDemo { [matTooltipPosition]="position"> Button `, - changeDetection: ChangeDetectionStrategy.OnPush + changeDetection: ChangeDetectionStrategy.OnPush, }) class OnPushTooltipDemo { position: string = 'below'; message: string = initialTooltipMessage; } - @Component({ selector: 'app', template: ` @@ -1250,7 +1410,6 @@ class DataBoundAriaLabelTooltip { message = 'Hello there'; } - @Component({ template: ` Button` + template: ``, }) class TooltipDemoWithoutPositionBinding { message: any = initialTooltipMessage; diff --git a/src/material/tooltip/tooltip.ts b/src/material/tooltip/tooltip.ts index 28f374f62393..e14392633e8d 100644 --- a/src/material/tooltip/tooltip.ts +++ b/src/material/tooltip/tooltip.ts @@ -8,10 +8,16 @@ import {AnimationEvent} from '@angular/animations'; import {AriaDescriber, FocusMonitor} from '@angular/cdk/a11y'; import {Directionality} from '@angular/cdk/bidi'; -import {BooleanInput, coerceBooleanProperty, NumberInput} from '@angular/cdk/coercion'; +import { + BooleanInput, + coerceBooleanProperty, + coerceNumberProperty, + NumberInput, +} from '@angular/cdk/coercion'; import {ESCAPE, hasModifierKey} from '@angular/cdk/keycodes'; import {BreakpointObserver, Breakpoints, BreakpointState} from '@angular/cdk/layout'; import { + ConnectedPosition, FlexibleConnectedPositionStrategy, HorizontalConnectionPos, OriginConnectionPosition, @@ -20,9 +26,10 @@ import { OverlayRef, ScrollStrategy, VerticalConnectionPos, + ConnectionPositionPair, } from '@angular/cdk/overlay'; import {Platform, normalizePassiveListenerOptions} from '@angular/cdk/platform'; -import {ComponentPortal} from '@angular/cdk/portal'; +import {ComponentPortal, ComponentType} from '@angular/cdk/portal'; import {ScrollDispatcher} from '@angular/cdk/scrolling'; import { ChangeDetectionStrategy, @@ -46,7 +53,6 @@ import {take, takeUntil} from 'rxjs/operators'; import {matTooltipAnimations} from './tooltip-animations'; - /** Possible positions for a tooltip. */ export type TooltipPosition = 'left' | 'right' | 'above' | 'below' | 'before' | 'after'; @@ -62,9 +68,15 @@ export type TooltipVisibility = 'initial' | 'visible' | 'hidden'; /** Time in ms to throttle repositioning after scroll events. */ export const SCROLL_THROTTLE_MS = 20; -/** CSS class that will be attached to the overlay panel. */ +/** + * CSS class that will be attached to the overlay panel. + * @deprecated + * @breaking-change 13.0.0 remove this variable + */ export const TOOLTIP_PANEL_CLASS = 'mat-tooltip-panel'; +const PANEL_CLASS = 'tooltip-panel'; + /** Options used to bind passive event listeners. */ const passiveListenerOptions = normalizePassiveListenerOptions({passive: true}); @@ -83,8 +95,9 @@ export function getMatTooltipInvalidPositionError(position: string) { } /** Injection token that determines the scroll handling while a tooltip is visible. */ -export const MAT_TOOLTIP_SCROLL_STRATEGY = - new InjectionToken<() => ScrollStrategy>('mat-tooltip-scroll-strategy'); +export const MAT_TOOLTIP_SCROLL_STRATEGY = new InjectionToken<() => ScrollStrategy>( + 'mat-tooltip-scroll-strategy', +); /** @docs-private */ export function MAT_TOOLTIP_SCROLL_STRATEGY_FACTORY(overlay: Overlay): () => ScrollStrategy { @@ -108,11 +121,13 @@ export interface MatTooltipDefaultOptions { } /** Injection token to be used to override the default options for `matTooltip`. */ -export const MAT_TOOLTIP_DEFAULT_OPTIONS = - new InjectionToken('mat-tooltip-default-options', { - providedIn: 'root', - factory: MAT_TOOLTIP_DEFAULT_OPTIONS_FACTORY - }); +export const MAT_TOOLTIP_DEFAULT_OPTIONS = new InjectionToken( + 'mat-tooltip-default-options', + { + providedIn: 'root', + factory: MAT_TOOLTIP_DEFAULT_OPTIONS_FACTORY, + }, +); /** @docs-private */ export function MAT_TOOLTIP_DEFAULT_OPTIONS_FACTORY(): MatTooltipDefaultOptions { @@ -123,45 +138,37 @@ export function MAT_TOOLTIP_DEFAULT_OPTIONS_FACTORY(): MatTooltipDefaultOptions }; } -/** - * Directive that attaches a material design tooltip to the host element. Animates the showing and - * hiding of a tooltip provided position (defaults to below the element). - * - * https://material.io/design/components/tooltips.html - */ -@Directive({ - selector: '[matTooltip]', - exportAs: 'matTooltip', - host: { - 'class': 'mat-tooltip-trigger' - } -}) -export class MatTooltip implements OnDestroy, AfterViewInit { +@Directive() +export abstract class _MatTooltipBase + implements OnDestroy, AfterViewInit +{ _overlayRef: OverlayRef | null; - _tooltipInstance: TooltipComponent | null; + _tooltipInstance: T | null; - private _portal: ComponentPortal; + private _portal: ComponentPortal; private _position: TooltipPosition = 'below'; private _disabled: boolean = false; - private _tooltipClass: string|string[]|Set|{[key: string]: any}; + private _tooltipClass: string | string[] | Set | {[key: string]: any}; private _scrollStrategy: () => ScrollStrategy; private _viewInitialized = false; private _pointerExitEventsInitialized = false; + protected abstract readonly _tooltipComponent: ComponentType; + protected _viewportMargin = 8; + private _currentPosition: TooltipPosition; + protected readonly _cssClassPrefix: string = 'mat'; /** Allows the user to define the position of the tooltip relative to the parent element */ @Input('matTooltipPosition') - get position(): TooltipPosition { return this._position; } + get position(): TooltipPosition { + return this._position; + } set position(value: TooltipPosition) { if (value !== this._position) { this._position = value; if (this._overlayRef) { - this._updatePosition(); - - if (this._tooltipInstance) { - this._tooltipInstance!.show(0); - } - + this._updatePosition(this._overlayRef); + this._tooltipInstance?.show(0); this._overlayRef.updatePosition(); } } @@ -169,8 +176,10 @@ export class MatTooltip implements OnDestroy, AfterViewInit { /** Disables the display of the tooltip. */ @Input('matTooltipDisabled') - get disabled(): boolean { return this._disabled; } - set disabled(value) { + get disabled(): boolean { + return this._disabled; + } + set disabled(value: BooleanInput) { this._disabled = coerceBooleanProperty(value); // If tooltip is disabled, hide immediately. @@ -182,10 +191,24 @@ export class MatTooltip implements OnDestroy, AfterViewInit { } /** The default delay in ms before showing the tooltip after show is called */ - @Input('matTooltipShowDelay') showDelay: number = this._defaultOptions.showDelay; + @Input('matTooltipShowDelay') + get showDelay(): number { + return this._showDelay; + } + set showDelay(value: NumberInput) { + this._showDelay = coerceNumberProperty(value); + } + private _showDelay = this._defaultOptions.showDelay; /** The default delay in ms before hiding the tooltip after hide is called */ - @Input('matTooltipHideDelay') hideDelay: number = this._defaultOptions.hideDelay; + @Input('matTooltipHideDelay') + get hideDelay(): number { + return this._hideDelay; + } + set hideDelay(value: NumberInput) { + this._hideDelay = coerceNumberProperty(value); + } + private _hideDelay = this._defaultOptions.hideDelay; /** * How touch gestures should be handled by the tooltip. On touch devices the tooltip directive @@ -205,7 +228,9 @@ export class MatTooltip implements OnDestroy, AfterViewInit { /** The message to be displayed in the tooltip */ @Input('matTooltip') - get message() { return this._message; } + get message() { + return this._message; + } set message(value: string) { this._ariaDescriber.removeDescription(this._elementRef.nativeElement, this._message, 'tooltip'); @@ -234,8 +259,10 @@ export class MatTooltip implements OnDestroy, AfterViewInit { /** Classes to be passed to the tooltip. Supports the same syntax as `ngClass`. */ @Input('matTooltipClass') - get tooltipClass() { return this._tooltipClass; } - set tooltipClass(value: string|string[]|Set|{[key: string]: any}) { + get tooltipClass() { + return this._tooltipClass; + } + set tooltipClass(value: string | string[] | Set | {[key: string]: any}) { this._tooltipClass = value; if (this._tooltipInstance) { this._setTooltipClass(this._tooltipClass); @@ -243,14 +270,11 @@ export class MatTooltip implements OnDestroy, AfterViewInit { } /** Manually-bound passive event listeners. */ - private readonly _passiveListeners: - (readonly [string, EventListenerOrEventListenerObject])[] = []; + private readonly _passiveListeners: (readonly [string, EventListenerOrEventListenerObject])[] = + []; - /** - * Reference to the current document. - * @breaking-change 11.0.0 Remove `| null` typing for `document`. - */ - private _document: Document | null; + /** Reference to the current document. */ + private _document: Document; /** Timer started at the last `touchstart` event. */ private _touchstartTimeout: number; @@ -267,15 +291,13 @@ export class MatTooltip implements OnDestroy, AfterViewInit { private _platform: Platform, private _ariaDescriber: AriaDescriber, private _focusMonitor: FocusMonitor, - @Inject(MAT_TOOLTIP_SCROLL_STRATEGY) scrollStrategy: any, - @Optional() private _dir: Directionality, - @Optional() @Inject(MAT_TOOLTIP_DEFAULT_OPTIONS) - private _defaultOptions: MatTooltipDefaultOptions, - - /** @breaking-change 11.0.0 _document argument to become required. */ - @Inject(DOCUMENT) _document: any) { - + scrollStrategy: any, + protected _dir: Directionality, + private _defaultOptions: MatTooltipDefaultOptions, + @Inject(DOCUMENT) _document: any, + ) { this._scrollStrategy = scrollStrategy; + this._document = _document; if (_defaultOptions) { if (_defaultOptions.position) { @@ -287,6 +309,12 @@ export class MatTooltip implements OnDestroy, AfterViewInit { } } + _dir.change.pipe(takeUntil(this._destroyed)).subscribe(() => { + if (this._overlayRef) { + this._updatePosition(this._overlayRef); + } + }); + _ngZone.runOutsideAngular(() => { _elementRef.nativeElement.addEventListener('keydown', this._handleKeydown); }); @@ -297,7 +325,8 @@ export class MatTooltip implements OnDestroy, AfterViewInit { this._viewInitialized = true; this._setupPointerEnterEventsIfNeeded(); - this._focusMonitor.monitor(this._elementRef) + this._focusMonitor + .monitor(this._elementRef) .pipe(takeUntil(this._destroyed)) .subscribe(origin => { // Note that the focus monitor runs outside the Angular zone. @@ -306,7 +335,7 @@ export class MatTooltip implements OnDestroy, AfterViewInit { } else if (origin === 'keyboard') { this._ngZone.run(() => this.show()); } - }); + }); } /** @@ -338,16 +367,23 @@ export class MatTooltip implements OnDestroy, AfterViewInit { /** Shows the tooltip after the delay in ms, defaults to tooltip-delay-show or 0ms if no input */ show(delay: number = this.showDelay): void { - if (this.disabled || !this.message || (this._isTooltipVisible() && - !this._tooltipInstance!._showTimeoutId && !this._tooltipInstance!._hideTimeoutId)) { - return; + if ( + this.disabled || + !this.message || + (this._isTooltipVisible() && + !this._tooltipInstance!._showTimeoutId && + !this._tooltipInstance!._hideTimeoutId) + ) { + return; } const overlayRef = this._createOverlay(); this._detach(); - this._portal = this._portal || new ComponentPortal(TooltipComponent, this._viewContainerRef); + this._portal = + this._portal || new ComponentPortal(this._tooltipComponent, this._viewContainerRef); this._tooltipInstance = overlayRef.attach(this._portal).instance; - this._tooltipInstance.afterHidden() + this._tooltipInstance + .afterHidden() .pipe(takeUntil(this._destroyed)) .subscribe(() => this._detach()); this._setTooltipClass(this._tooltipClass); @@ -382,7 +418,7 @@ export class MatTooltip implements OnDestroy, AfterViewInit { event.stopPropagation(); this._ngZone.run(() => this.hide(0)); } - } + }; /** Create the overlay config and position strategy */ private _createOverlay(): OverlayRef { @@ -390,18 +426,22 @@ export class MatTooltip implements OnDestroy, AfterViewInit { return this._overlayRef; } - const scrollableAncestors = - this._scrollDispatcher.getAncestorScrollContainers(this._elementRef); + const scrollableAncestors = this._scrollDispatcher.getAncestorScrollContainers( + this._elementRef, + ); // Create connected position strategy that listens for scroll events to reposition. - const strategy = this._overlay.position() - .flexibleConnectedTo(this._elementRef) - .withTransformOriginOn('.mat-tooltip') - .withFlexibleDimensions(false) - .withViewportMargin(8) - .withScrollableContainers(scrollableAncestors); + const strategy = this._overlay + .position() + .flexibleConnectedTo(this._elementRef) + .withTransformOriginOn(`.${this._cssClassPrefix}-tooltip`) + .withFlexibleDimensions(false) + .withViewportMargin(this._viewportMargin) + .withScrollableContainers(scrollableAncestors); strategy.positionChanges.pipe(takeUntil(this._destroyed)).subscribe(change => { + this._updateCurrentPositionClass(change.connectionPair); + if (this._tooltipInstance) { if (change.scrollableViewProperties.isOverlayClipped && this._tooltipInstance.isVisible()) { // After position changes occur and the overlay is clipped by @@ -414,16 +454,22 @@ export class MatTooltip implements OnDestroy, AfterViewInit { this._overlayRef = this._overlay.create({ direction: this._dir, positionStrategy: strategy, - panelClass: TOOLTIP_PANEL_CLASS, - scrollStrategy: this._scrollStrategy() + panelClass: `${this._cssClassPrefix}-${PANEL_CLASS}`, + scrollStrategy: this._scrollStrategy(), }); - this._updatePosition(); + this._updatePosition(this._overlayRef); - this._overlayRef.detachments() + this._overlayRef + .detachments() .pipe(takeUntil(this._destroyed)) .subscribe(() => this._detach()); + this._overlayRef + .outsidePointerEvents() + .pipe(takeUntil(this._destroyed)) + .subscribe(() => this._tooltipInstance?._handleBodyInteraction()); + return this._overlayRef; } @@ -437,23 +483,27 @@ export class MatTooltip implements OnDestroy, AfterViewInit { } /** Updates the position of the current tooltip. */ - private _updatePosition() { - const position = - this._overlayRef!.getConfig().positionStrategy as FlexibleConnectedPositionStrategy; + private _updatePosition(overlayRef: OverlayRef) { + const position = overlayRef.getConfig().positionStrategy as FlexibleConnectedPositionStrategy; const origin = this._getOrigin(); const overlay = this._getOverlayPosition(); position.withPositions([ - {...origin.main, ...overlay.main}, - {...origin.fallback, ...overlay.fallback} + this._addOffset({...origin.main, ...overlay.main}), + this._addOffset({...origin.fallback, ...overlay.fallback}), ]); } + /** Adds the configured offset to a position. Used as a hook for child classes. */ + protected _addOffset(position: ConnectedPosition): ConnectedPosition { + return position; + } + /** * Returns the origin position and a fallback position based on the user's position preference. * The fallback position is the inverse of the origin (e.g. `'below' -> 'above'`). */ - _getOrigin(): {main: OriginConnectionPosition, fallback: OriginConnectionPosition} { + _getOrigin(): {main: OriginConnectionPosition; fallback: OriginConnectionPosition} { const isLtr = !this._dir || this._dir.value == 'ltr'; const position = this.position; let originPosition: OriginConnectionPosition; @@ -463,12 +513,14 @@ export class MatTooltip implements OnDestroy, AfterViewInit { } else if ( position == 'before' || (position == 'left' && isLtr) || - (position == 'right' && !isLtr)) { + (position == 'right' && !isLtr) + ) { originPosition = {originX: 'start', originY: 'center'}; } else if ( position == 'after' || (position == 'right' && isLtr) || - (position == 'left' && !isLtr)) { + (position == 'left' && !isLtr) + ) { originPosition = {originX: 'end', originY: 'center'}; } else if (typeof ngDevMode === 'undefined' || ngDevMode) { throw getMatTooltipInvalidPositionError(position); @@ -478,12 +530,12 @@ export class MatTooltip implements OnDestroy, AfterViewInit { return { main: originPosition!, - fallback: {originX: x, originY: y} + fallback: {originX: x, originY: y}, }; } /** Returns the overlay position and a fallback position based on the user's preference */ - _getOverlayPosition(): {main: OverlayConnectionPosition, fallback: OverlayConnectionPosition} { + _getOverlayPosition(): {main: OverlayConnectionPosition; fallback: OverlayConnectionPosition} { const isLtr = !this._dir || this._dir.value == 'ltr'; const position = this.position; let overlayPosition: OverlayConnectionPosition; @@ -495,12 +547,14 @@ export class MatTooltip implements OnDestroy, AfterViewInit { } else if ( position == 'before' || (position == 'left' && isLtr) || - (position == 'right' && !isLtr)) { + (position == 'right' && !isLtr) + ) { overlayPosition = {overlayX: 'end', overlayY: 'center'}; } else if ( position == 'after' || (position == 'right' && isLtr) || - (position == 'left' && !isLtr)) { + (position == 'left' && !isLtr) + ) { overlayPosition = {overlayX: 'start', overlayY: 'center'}; } else if (typeof ngDevMode === 'undefined' || ngDevMode) { throw getMatTooltipInvalidPositionError(position); @@ -510,7 +564,7 @@ export class MatTooltip implements OnDestroy, AfterViewInit { return { main: overlayPosition!, - fallback: {overlayX: x, overlayY: y} + fallback: {overlayX: x, overlayY: y}, }; } @@ -522,10 +576,7 @@ export class MatTooltip implements OnDestroy, AfterViewInit { this._tooltipInstance.message = this.message; this._tooltipInstance._markForCheck(); - this._ngZone.onMicrotaskEmpty.pipe( - take(1), - takeUntil(this._destroyed) - ).subscribe(() => { + this._ngZone.onMicrotaskEmpty.pipe(take(1), takeUntil(this._destroyed)).subscribe(() => { if (this._tooltipInstance) { this._overlayRef!.updatePosition(); } @@ -534,7 +585,7 @@ export class MatTooltip implements OnDestroy, AfterViewInit { } /** Updates the tooltip class */ - private _setTooltipClass(tooltipClass: string|string[]|Set|{[key: string]: any}) { + private _setTooltipClass(tooltipClass: string | string[] | Set | {[key: string]: any}) { if (this._tooltipInstance) { this._tooltipInstance.tooltipClass = tooltipClass; this._tooltipInstance._markForCheck(); @@ -560,33 +611,74 @@ export class MatTooltip implements OnDestroy, AfterViewInit { return {x, y}; } + /** Updates the class on the overlay panel based on the current position of the tooltip. */ + private _updateCurrentPositionClass(connectionPair: ConnectionPositionPair): void { + const {overlayY, originX, originY} = connectionPair; + let newPosition: TooltipPosition; + + // If the overlay is in the middle along the Y axis, + // it means that it's either before or after. + if (overlayY === 'center') { + // Note that since this information is used for styling, we want to + // resolve `start` and `end` to their real values, otherwise consumers + // would have to remember to do it themselves on each consumption. + if (this._dir && this._dir.value === 'rtl') { + newPosition = originX === 'end' ? 'left' : 'right'; + } else { + newPosition = originX === 'start' ? 'left' : 'right'; + } + } else { + newPosition = overlayY === 'bottom' && originY === 'top' ? 'above' : 'below'; + } + + if (newPosition !== this._currentPosition) { + const overlayRef = this._overlayRef; + + if (overlayRef) { + const classPrefix = `${this._cssClassPrefix}-${PANEL_CLASS}-`; + overlayRef.removePanelClass(classPrefix + this._currentPosition); + overlayRef.addPanelClass(classPrefix + newPosition); + } + + this._currentPosition = newPosition; + } + } + /** Binds the pointer events to the tooltip trigger. */ private _setupPointerEnterEventsIfNeeded() { // Optimization: Defer hooking up events if there's no message or the tooltip is disabled. - if (this._disabled || !this.message || !this._viewInitialized || - this._passiveListeners.length) { + if ( + this._disabled || + !this.message || + !this._viewInitialized || + this._passiveListeners.length + ) { return; } // The mouse events shouldn't be bound on mobile devices, because they can prevent the // first tap from firing its click event or can cause the tooltip to open for clicks. if (this._platformSupportsMouseEvents()) { - this._passiveListeners - .push(['mouseenter', () => { - this._setupPointerExitEventsIfNeeded(); - this.show(); - }]); + this._passiveListeners.push([ + 'mouseenter', + () => { + this._setupPointerExitEventsIfNeeded(); + this.show(); + }, + ]); } else if (this.touchGestures !== 'off') { this._disableNativeGesturesIfNecessary(); - this._passiveListeners - .push(['touchstart', () => { - // Note that it's important that we don't `preventDefault` here, - // because it can prevent click events from firing on the element. - this._setupPointerExitEventsIfNeeded(); - clearTimeout(this._touchstartTimeout); - this._touchstartTimeout = setTimeout(() => this.show(), LONGPRESS_DELAY); - }]); + this._passiveListeners.push([ + 'touchstart', + () => { + // Note that it's important that we don't `preventDefault` here, + // because it can prevent click events from firing on the element. + this._setupPointerExitEventsIfNeeded(); + clearTimeout(this._touchstartTimeout); + this._touchstartTimeout = setTimeout(() => this.show(), LONGPRESS_DELAY); + }, + ]); } this._addListeners(this._passiveListeners); @@ -602,7 +694,7 @@ export class MatTooltip implements OnDestroy, AfterViewInit { if (this._platformSupportsMouseEvents()) { exitListeners.push( ['mouseleave', () => this.hide()], - ['wheel', event => this._wheelListener(event as WheelEvent)] + ['wheel', event => this._wheelListener(event as WheelEvent)], ); } else if (this.touchGestures !== 'off') { this._disableNativeGesturesIfNecessary(); @@ -611,18 +703,14 @@ export class MatTooltip implements OnDestroy, AfterViewInit { this.hide(this._defaultOptions.touchendHideDelay); }; - exitListeners.push( - ['touchend', touchendListener], - ['touchcancel', touchendListener], - ); + exitListeners.push(['touchend', touchendListener], ['touchcancel', touchendListener]); } this._addListeners(exitListeners); this._passiveListeners.push(...exitListeners); } - private _addListeners( - listeners: ReadonlyArray) { + private _addListeners(listeners: (readonly [string, EventListenerOrEventListenerObject])[]) { listeners.forEach(([event, listener]) => { this._elementRef.nativeElement.addEventListener(event, listener, passiveListenerOptions); }); @@ -635,9 +723,7 @@ export class MatTooltip implements OnDestroy, AfterViewInit { /** Listener for the `wheel` event on the element. */ private _wheelListener(event: WheelEvent) { if (this._isTooltipVisible()) { - // @breaking-change 11.0.0 Remove `|| document` once the document is a required param. - const doc = this._document || document; - const elementUnderPointer = doc.elementFromPoint(event.clientX, event.clientY); + const elementUnderPointer = this._document.elementFromPoint(event.clientX, event.clientY); const element = this._elementRef.nativeElement; // On non-touch devices we depend on the `mouseleave` event to close the tooltip, but it @@ -661,8 +747,11 @@ export class MatTooltip implements OnDestroy, AfterViewInit { // If gestures are set to `auto`, we don't disable text selection on inputs and // textareas, because it prevents the user from typing into them on iOS Safari. if (gestures === 'on' || (element.nodeName !== 'INPUT' && element.nodeName !== 'TEXTAREA')) { - style.userSelect = (style as any).msUserSelect = style.webkitUserSelect = - (style as any).MozUserSelect = 'none'; + style.userSelect = + (style as any).msUserSelect = + style.webkitUserSelect = + (style as any).MozUserSelect = + 'none'; } // If we have `auto` gestures and the element uses native HTML dragging, @@ -672,46 +761,71 @@ export class MatTooltip implements OnDestroy, AfterViewInit { } style.touchAction = 'none'; - style.webkitTapHighlightColor = 'transparent'; + (style as any).webkitTapHighlightColor = 'transparent'; } } - - static ngAcceptInputType_disabled: BooleanInput; - static ngAcceptInputType_hideDelay: NumberInput; - static ngAcceptInputType_showDelay: NumberInput; } /** - * Internal component that wraps the tooltip's content. - * @docs-private + * Directive that attaches a material design tooltip to the host element. Animates the showing and + * hiding of a tooltip provided position (defaults to below the element). + * + * https://material.io/design/components/tooltips.html */ -@Component({ - selector: 'mat-tooltip-component', - templateUrl: 'tooltip.html', - styleUrls: ['tooltip.css'], - encapsulation: ViewEncapsulation.None, - changeDetection: ChangeDetectionStrategy.OnPush, - animations: [matTooltipAnimations.tooltipState], +@Directive({ + selector: '[matTooltip]', + exportAs: 'matTooltip', host: { - // Forces the element to have a layout in IE and Edge. This fixes issues where the element - // won't be rendered if the animations are disabled or there is no web animations polyfill. - '[style.zoom]': '_visibility === "visible" ? 1 : null', - '(body:click)': 'this._handleBodyInteraction()', - 'aria-hidden': 'true', - } + 'class': 'mat-tooltip-trigger', + }, }) -export class TooltipComponent implements OnDestroy { +export class MatTooltip extends _MatTooltipBase { + protected readonly _tooltipComponent = TooltipComponent; + + constructor( + overlay: Overlay, + elementRef: ElementRef, + scrollDispatcher: ScrollDispatcher, + viewContainerRef: ViewContainerRef, + ngZone: NgZone, + platform: Platform, + ariaDescriber: AriaDescriber, + focusMonitor: FocusMonitor, + @Inject(MAT_TOOLTIP_SCROLL_STRATEGY) scrollStrategy: any, + @Optional() dir: Directionality, + @Optional() @Inject(MAT_TOOLTIP_DEFAULT_OPTIONS) defaultOptions: MatTooltipDefaultOptions, + @Inject(DOCUMENT) _document: any, + ) { + super( + overlay, + elementRef, + scrollDispatcher, + viewContainerRef, + ngZone, + platform, + ariaDescriber, + focusMonitor, + scrollStrategy, + dir, + defaultOptions, + _document, + ); + } +} + +@Directive() +export abstract class _TooltipComponentBase implements OnDestroy { /** Message to display in the tooltip */ message: string; /** Classes to be added to the tooltip. Supports the same syntax as `ngClass`. */ - tooltipClass: string|string[]|Set|{[key: string]: any}; + tooltipClass: string | string[] | Set | {[key: string]: any}; /** The timeout ID of any current timer set to show the tooltip */ - _showTimeoutId: number | null; + _showTimeoutId: number | undefined; /** The timeout ID of any current timer set to hide the tooltip */ - _hideTimeoutId: number | null; + _hideTimeoutId: number | undefined; /** Property watched by the animation framework to show or hide the tooltip */ _visibility: TooltipVisibility = 'initial'; @@ -722,12 +836,7 @@ export class TooltipComponent implements OnDestroy { /** Subject for notifying that the tooltip has been hidden from the view */ private readonly _onHide: Subject = new Subject(); - /** Stream that emits whether the user has a handset-sized display. */ - _isHandset: Observable = this._breakpointObserver.observe(Breakpoints.Handset); - - constructor( - private _changeDetectorRef: ChangeDetectorRef, - private _breakpointObserver: BreakpointObserver) {} + constructor(private _changeDetectorRef: ChangeDetectorRef) {} /** * Shows the tooltip with an animation originating from the provided origin @@ -735,16 +844,14 @@ export class TooltipComponent implements OnDestroy { */ show(delay: number): void { // Cancel the delayed hide if it is scheduled - if (this._hideTimeoutId) { - clearTimeout(this._hideTimeoutId); - this._hideTimeoutId = null; - } + clearTimeout(this._hideTimeoutId); // Body interactions should cancel the tooltip if there is a delay in showing. this._closeOnInteraction = true; this._showTimeoutId = setTimeout(() => { this._visibility = 'visible'; - this._showTimeoutId = null; + this._showTimeoutId = undefined; + this._onShow(); // Mark for check so if any parent component has set the // ChangeDetectionStrategy to OnPush it will be checked anyways @@ -758,14 +865,11 @@ export class TooltipComponent implements OnDestroy { */ hide(delay: number): void { // Cancel the delayed show if it is scheduled - if (this._showTimeoutId) { - clearTimeout(this._showTimeoutId); - this._showTimeoutId = null; - } + clearTimeout(this._showTimeoutId); this._hideTimeoutId = setTimeout(() => { this._visibility = 'hidden'; - this._hideTimeoutId = null; + this._hideTimeoutId = undefined; // Mark for check so if any parent component has set the // ChangeDetectionStrategy to OnPush it will be checked anyways @@ -784,6 +888,8 @@ export class TooltipComponent implements OnDestroy { } ngOnDestroy() { + clearTimeout(this._showTimeoutId); + clearTimeout(this._hideTimeoutId); this._onHide.complete(); } @@ -822,4 +928,41 @@ export class TooltipComponent implements OnDestroy { _markForCheck(): void { this._changeDetectorRef.markForCheck(); } + + /** + * Callback for when the timeout in this.show() gets completed. + * This method is only needed by the mdc-tooltip, and so it is only implemented + * in the mdc-tooltip, not here. + */ + protected _onShow(): void {} +} + +/** + * Internal component that wraps the tooltip's content. + * @docs-private + */ +@Component({ + selector: 'mat-tooltip-component', + templateUrl: 'tooltip.html', + styleUrls: ['tooltip.css'], + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + animations: [matTooltipAnimations.tooltipState], + host: { + // Forces the element to have a layout in IE and Edge. This fixes issues where the element + // won't be rendered if the animations are disabled or there is no web animations polyfill. + '[style.zoom]': '_visibility === "visible" ? 1 : null', + 'aria-hidden': 'true', + }, +}) +export class TooltipComponent extends _TooltipComponentBase { + /** Stream that emits whether the user has a handset-sized display. */ + _isHandset: Observable = this._breakpointObserver.observe(Breakpoints.Handset); + + constructor( + changeDetectorRef: ChangeDetectorRef, + private _breakpointObserver: BreakpointObserver, + ) { + super(changeDetectorRef); + } } diff --git a/src/material/tree/BUILD.bazel b/src/material/tree/BUILD.bazel index c5312d127e82..bb12bb15360b 100644 --- a/src/material/tree/BUILD.bazel +++ b/src/material/tree/BUILD.bazel @@ -17,7 +17,6 @@ ng_module( exclude = ["**/*.spec.ts"], ), assets = [":tree.css"] + glob(["**/*.html"]), - module_name = "@angular/material/tree", deps = [ "//src/cdk/collections", "//src/cdk/tree", diff --git a/src/material/tree/_tree-legacy-index.scss b/src/material/tree/_tree-legacy-index.scss new file mode 100644 index 000000000000..5faf229eccb6 --- /dev/null +++ b/src/material/tree/_tree-legacy-index.scss @@ -0,0 +1,2 @@ +@forward 'tree-variables' as mat-tree-*; +@forward 'tree-theme' as mat-tree-*; diff --git a/src/material/tree/_tree-theme.import.scss b/src/material/tree/_tree-theme.import.scss new file mode 100644 index 000000000000..c7ed1fdf06dd --- /dev/null +++ b/src/material/tree/_tree-theme.import.scss @@ -0,0 +1,9 @@ +@forward '../core/theming/theming.import'; +@forward 'tree-variables' as mat-tree-*; +@forward '../core/typography/typography-utils.import'; +@forward 'tree-theme' as mat-tree-*; + +@import '../core/density/private/compatibility'; +@import '../core/theming/palette'; +@import '../core/theming/theming'; +@import '../core/typography/typography-utils'; diff --git a/src/material/tree/_tree-theme.scss b/src/material/tree/_tree-theme.scss index 9f9a059d9934..871c27b85386 100644 --- a/src/material/tree/_tree-theme.scss +++ b/src/material/tree/_tree-theme.scss @@ -1,63 +1,66 @@ -@import '../core/density/private/compatibility'; -@import '../core/theming/palette'; -@import '../core/theming/theming'; -@import '../core/typography/typography-utils'; -@import './tree-variables'; +@use 'sass:map'; +@use '../core/density/private/compatibility'; +@use '../core/theming/theming'; +@use '../core/typography/typography'; +@use '../core/typography/typography-utils'; +@use './tree-variables'; -@mixin mat-tree-color($config-or-theme) { - $config: mat-get-color-config($config-or-theme); - $background: map-get($config, background); - $foreground: map-get($config, foreground); +@mixin color($config-or-theme) { + $config: theming.get-color-config($config-or-theme); + $background: map.get($config, background); + $foreground: map.get($config, foreground); .mat-tree { - background: mat-color($background, 'card'); + background: theming.get-color-from-palette($background, 'card'); } .mat-tree-node, .mat-nested-tree-node { - color: mat-color($foreground, text); + color: theming.get-color-from-palette($foreground, text); } } -@mixin mat-tree-typography($config-or-theme) { - $config: mat-get-typography-config($config-or-theme); +@mixin typography($config-or-theme) { + $config: typography.private-typography-to-2014-config( + theming.get-typography-config($config-or-theme)); .mat-tree { - font-family: mat-font-family($config); + font-family: typography-utils.font-family($config); } .mat-tree-node, .mat-nested-tree-node { - font-weight: mat-font-weight($config, body-1); - font-size: mat-font-size($config, body-1); + font-weight: typography-utils.font-weight($config, body-1); + font-size: typography-utils.font-size($config, body-1); } } -@mixin mat-tree-density($config-or-theme) { - $density-scale: mat-get-density-config($config-or-theme); - $height: mat-private-density-prop-value($mat-tree-density-config, $density-scale, height); +@mixin density($config-or-theme) { + $density-scale: theming.get-density-config($config-or-theme); + $height: compatibility.private-density-prop-value(tree-variables.$density-config, + $density-scale, height); - @include mat-private-density-legacy-compatibility() { + @include compatibility.private-density-legacy-compatibility() { .mat-tree-node { min-height: $height; } } } -@mixin mat-tree-theme($theme-or-color-config) { - $theme: mat-private-legacy-get-theme($theme-or-color-config); - @include mat-private-check-duplicate-theme-styles($theme, 'mat-tree') { - $color: mat-get-color-config($theme); - $density: mat-get-density-config($theme); - $typography: mat-get-typography-config($theme); +@mixin theme($theme-or-color-config) { + $theme: theming.private-legacy-get-theme($theme-or-color-config); + @include theming.private-check-duplicate-theme-styles($theme, 'mat-tree') { + $color: theming.get-color-config($theme); + $density: theming.get-density-config($theme); + $typography: theming.get-typography-config($theme); @if $color != null { - @include mat-tree-color($color); + @include color($color); } @if $density != null { - @include mat-tree-density($density); + @include density($density); } @if $typography != null { - @include mat-tree-typography($typography); + @include typography($typography); } } } diff --git a/src/material/tree/_tree-variables.import.scss b/src/material/tree/_tree-variables.import.scss new file mode 100644 index 000000000000..8cd583945dce --- /dev/null +++ b/src/material/tree/_tree-variables.import.scss @@ -0,0 +1 @@ +@forward 'tree-variables' as mat-tree-*; diff --git a/src/material/tree/_tree-variables.scss b/src/material/tree/_tree-variables.scss index e7e4730c64c7..dce20f39cacc 100644 --- a/src/material/tree/_tree-variables.scss +++ b/src/material/tree/_tree-variables.scss @@ -1,14 +1,14 @@ -$mat-tree-node-height: 48px !default; +$node-height: 48px !default; // Minimum height for tree nodes in highest density is difficult to determine as // developers can display arbitrary content. We use a minimum height which ensures // that common content placed in tree nodes does not exceed (e.g. icons, checkboxes). -$mat-tree-node-minimum-height: 24px !default; -$mat-tree-node-maximum-height: $mat-tree-node-height !default; +$node-minimum-height: 24px !default; +$node-maximum-height: $node-height !default; -$mat-tree-density-config: ( +$density-config: ( height: ( - default: $mat-tree-node-height, - maximum: $mat-tree-node-maximum-height, - minimum: $mat-tree-node-minimum-height, + default: $node-height, + maximum: $node-maximum-height, + minimum: $node-minimum-height, ) ) !default; diff --git a/src/material/tree/data-source/flat-data-source.ts b/src/material/tree/data-source/flat-data-source.ts index 6a5c56a42440..1763019ef080 100644 --- a/src/material/tree/data-source/flat-data-source.ts +++ b/src/material/tree/data-source/flat-data-source.ts @@ -46,15 +46,14 @@ import {map, take} from 'rxjs/operators'; * and the output flattened type is `F` with additional information. */ export class MatTreeFlattener { - - constructor(public transformFunction: (node: T, level: number) => F, - public getLevel: (node: F) => number, - public isExpandable: (node: F) => boolean, - public getChildren: (node: T) => - Observable | T[] | undefined | null) {} - - _flattenNode(node: T, level: number, - resultNodes: F[], parentMap: boolean[]): F[] { + constructor( + public transformFunction: (node: T, level: number) => F, + public getLevel: (node: F) => number, + public isExpandable: (node: F) => boolean, + public getChildren: (node: T) => Observable | T[] | undefined | null, + ) {} + + _flattenNode(node: T, level: number, resultNodes: F[], parentMap: boolean[]): F[] { const flatNode = this.transformFunction(node, level); resultNodes.push(flatNode); @@ -73,8 +72,7 @@ export class MatTreeFlattener { return resultNodes; } - _flattenChildren(children: T[], level: number, - resultNodes: F[], parentMap: boolean[]): void { + _flattenChildren(children: T[], level: number, resultNodes: F[], parentMap: boolean[]): void { children.forEach((child, index) => { let childParentMap: boolean[] = parentMap.slice(); childParentMap.push(index != children.length - 1); @@ -118,7 +116,6 @@ export class MatTreeFlattener { } } - /** * Data source for flat tree. * The data source need to handle expansion/collapsion of the tree node and change the data feed @@ -127,36 +124,45 @@ export class MatTreeFlattener { * to type `F` for `MatTree` to consume. */ export class MatTreeFlatDataSource extends DataSource { - _flattenedData = new BehaviorSubject([]); - - _expandedData = new BehaviorSubject([]); + private readonly _flattenedData = new BehaviorSubject([]); + private readonly _expandedData = new BehaviorSubject([]); - _data: BehaviorSubject; - get data() { return this._data.value; } + get data() { + return this._data.value; + } set data(value: T[]) { this._data.next(value); this._flattenedData.next(this._treeFlattener.flattenNodes(this.data)); this._treeControl.dataNodes = this._flattenedData.value; } + private readonly _data = new BehaviorSubject([]); - constructor(private _treeControl: FlatTreeControl, - private _treeFlattener: MatTreeFlattener, - initialData: T[] = []) { + constructor( + private _treeControl: FlatTreeControl, + private _treeFlattener: MatTreeFlattener, + initialData?: T[], + ) { super(); - this._data = new BehaviorSubject(initialData); + + if (initialData) { + // Assign the data through the constructor to ensure that all of the logic is executed. + this.data = initialData; + } } connect(collectionViewer: CollectionViewer): Observable { - const changes = [ + return merge( collectionViewer.viewChange, this._treeControl.expansionModel.changed, - this._flattenedData - ]; - return merge(...changes).pipe(map(() => { - this._expandedData.next( - this._treeFlattener.expandFlattenedNodes(this._flattenedData.value, this._treeControl)); - return this._expandedData.value; - })); + this._flattenedData, + ).pipe( + map(() => { + this._expandedData.next( + this._treeFlattener.expandFlattenedNodes(this._flattenedData.value, this._treeControl), + ); + return this._expandedData.value; + }), + ); } disconnect() { diff --git a/src/material/tree/data-source/nested-data-source.ts b/src/material/tree/data-source/nested-data-source.ts index c6e578c69d91..ffd992d9cba8 100644 --- a/src/material/tree/data-source/nested-data-source.ts +++ b/src/material/tree/data-source/nested-data-source.ts @@ -10,7 +10,6 @@ import {CollectionViewer, DataSource} from '@angular/cdk/collections'; import {BehaviorSubject, merge, Observable} from 'rxjs'; import {map} from 'rxjs/operators'; - /** * Data source for nested tree. * @@ -18,23 +17,24 @@ import {map} from 'rxjs/operators'; * or collapse. The expansion/collapsion will be handled by TreeControl and each non-leaf node. */ export class MatTreeNestedDataSource extends DataSource { - _data = new BehaviorSubject([]); - /** * Data for the nested tree */ - get data() { return this._data.value; } - set data(value: T[]) { this._data.next(value); } + get data() { + return this._data.value; + } + set data(value: T[]) { + this._data.next(value); + } + private readonly _data = new BehaviorSubject([]); connect(collectionViewer: CollectionViewer): Observable { - return merge(...[collectionViewer.viewChange, this._data]) - .pipe(map(() => { - return this.data; - })); + return merge(...([collectionViewer.viewChange, this._data] as Observable[])).pipe( + map(() => this.data), + ); } disconnect() { // no op } } - diff --git a/src/material/tree/node.ts b/src/material/tree/node.ts index 41537b03b141..437596f6add5 100644 --- a/src/material/tree/node.ts +++ b/src/material/tree/node.ts @@ -17,24 +17,16 @@ import { AfterContentInit, Attribute, Directive, - DoCheck, ElementRef, Input, IterableDiffers, - OnDestroy, OnInit, + OnDestroy, + OnInit, } from '@angular/core'; -import { - CanDisable, - CanDisableCtor, - HasTabIndex, - HasTabIndexCtor, - mixinDisabled, - mixinTabIndex, -} from '@angular/material/core'; -import {BooleanInput, coerceBooleanProperty, NumberInput} from '@angular/cdk/coercion'; +import {CanDisable, HasTabIndex, mixinDisabled, mixinTabIndex} from '@angular/material/core'; +import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion'; -const _MatTreeNodeMixinBase: HasTabIndexCtor & CanDisableCtor & typeof CdkTreeNode = - mixinTabIndex(mixinDisabled(CdkTreeNode)); +const _MatTreeNodeBase = mixinTabIndex(mixinDisabled(CdkTreeNode)); /** * Wrapper for the CdkTree node with Material design styles. @@ -43,52 +35,43 @@ const _MatTreeNodeMixinBase: HasTabIndexCtor & CanDisableCtor & typeof CdkTreeNo selector: 'mat-tree-node', exportAs: 'matTreeNode', inputs: ['role', 'disabled', 'tabIndex'], - providers: [{provide: CdkTreeNode, useExisting: MatTreeNode}] + providers: [{provide: CdkTreeNode, useExisting: MatTreeNode}], + host: { + 'class': 'mat-tree-node', + }, }) -export class MatTreeNode extends _MatTreeNodeMixinBase - implements CanDisable, DoCheck, HasTabIndex, OnInit, OnDestroy { - - - constructor(protected _elementRef: ElementRef, - protected _tree: CdkTree, - @Attribute('tabindex') tabIndex: string) { - super(_elementRef, _tree); - +export class MatTreeNode + extends _MatTreeNodeBase + implements CanDisable, HasTabIndex, OnInit, OnDestroy +{ + constructor( + elementRef: ElementRef, + tree: CdkTree, + @Attribute('tabindex') tabIndex: string, + ) { + super(elementRef, tree); this.tabIndex = Number(tabIndex) || 0; - // The classes are directly added here instead of in the host property because classes on - // the host property are not inherited with View Engine. It is not set as a @HostBinding because - // it is not set by the time it's children nodes try to read the class from it. - // TODO: move to host after View Engine deprecation - this._elementRef.nativeElement.classList.add('mat-tree-node'); } // This is a workaround for https://github.com/angular/angular/issues/23091 // In aot mode, the lifecycle hooks from parent class are not called. - ngOnInit() { + override ngOnInit() { super.ngOnInit(); } - ngDoCheck() { - super.ngDoCheck(); - } - - ngOnDestroy() { + override ngOnDestroy() { super.ngOnDestroy(); } - - static ngAcceptInputType_disabled: BooleanInput; - static ngAcceptInputType_tabIndex: NumberInput; } /** * Wrapper for the CdkTree node definition with Material design styles. + * Captures the node's template and a when predicate that describes when this node should be used. */ @Directive({ selector: '[matTreeNodeDef]', - inputs: [ - 'when: matTreeNodeDefWhen' - ], - providers: [{provide: CdkTreeNodeDef, useExisting: MatTreeNodeDef}] + inputs: ['when: matTreeNodeDefWhen'], + providers: [{provide: CdkTreeNodeDef, useExisting: MatTreeNodeDef}], }) export class MatTreeNodeDef extends CdkTreeNodeDef { @Input('matTreeNode') data: T; @@ -104,59 +87,61 @@ export class MatTreeNodeDef extends CdkTreeNodeDef { providers: [ {provide: CdkNestedTreeNode, useExisting: MatNestedTreeNode}, {provide: CdkTreeNode, useExisting: MatNestedTreeNode}, - {provide: CDK_TREE_NODE_OUTLET_NODE, useExisting: MatNestedTreeNode} - ] + {provide: CDK_TREE_NODE_OUTLET_NODE, useExisting: MatNestedTreeNode}, + ], + host: { + 'class': 'mat-nested-tree-node', + }, }) -export class MatNestedTreeNode extends CdkNestedTreeNode implements AfterContentInit, DoCheck, - OnDestroy, OnInit { +export class MatNestedTreeNode + extends CdkNestedTreeNode + implements AfterContentInit, OnDestroy, OnInit +{ @Input('matNestedTreeNode') node: T; /** Whether the node is disabled. */ @Input() - get disabled() { return this._disabled; } - set disabled(value: any) { this._disabled = coerceBooleanProperty(value); } + get disabled(): boolean { + return this._disabled; + } + set disabled(value: BooleanInput) { + this._disabled = coerceBooleanProperty(value); + } private _disabled = false; /** Tabindex for the node. */ @Input() - get tabIndex(): number { return this.disabled ? -1 : this._tabIndex; } + get tabIndex(): number { + return this.disabled ? -1 : this._tabIndex; + } set tabIndex(value: number) { // If the specified tabIndex value is null or undefined, fall back to the default value. this._tabIndex = value != null ? value : 0; } private _tabIndex: number; - constructor(protected _elementRef: ElementRef, - protected _tree: CdkTree, - protected _differs: IterableDiffers, - @Attribute('tabindex') tabIndex: string) { - super(_elementRef, _tree, _differs); + constructor( + elementRef: ElementRef, + tree: CdkTree, + differs: IterableDiffers, + @Attribute('tabindex') tabIndex: string, + ) { + super(elementRef, tree, differs); this.tabIndex = Number(tabIndex) || 0; - // The classes are directly added here instead of in the host property because classes on - // the host property are not inherited with View Engine. It is not set as a @HostBinding because - // it is not set by the time it's children nodes try to read the class from it. - // TODO: move to host after View Engine deprecation - this._elementRef.nativeElement.classList.add('mat-nested-tree-node'); } - // This is a workaround for https://github.com/angular/angular/issues/23091 + // This is a workaround for https://github.com/angular/angular/issues/19145 // In aot mode, the lifecycle hooks from parent class are not called. - // TODO(tinayuangao): Remove when the angular issue #23091 is fixed - ngOnInit() { + // TODO(tinayuangao): Remove when the angular issue #19145 is fixed + override ngOnInit() { super.ngOnInit(); } - ngDoCheck() { - super.ngDoCheck(); - } - - ngAfterContentInit() { + override ngAfterContentInit() { super.ngAfterContentInit(); } - ngOnDestroy() { + override ngOnDestroy() { super.ngOnDestroy(); } - - static ngAcceptInputType_disabled: BooleanInput; } diff --git a/src/material/tree/outlet.ts b/src/material/tree/outlet.ts index 5c759d67d742..537e7b2cfb91 100644 --- a/src/material/tree/outlet.ts +++ b/src/material/tree/outlet.ts @@ -6,12 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ import {CDK_TREE_NODE_OUTLET_NODE, CdkTreeNodeOutlet} from '@angular/cdk/tree'; -import { - Directive, - Inject, - Optional, - ViewContainerRef, -} from '@angular/core'; +import {Directive, Inject, Optional, ViewContainerRef} from '@angular/core'; /** * Outlet for nested CdkNode. Put `[matTreeNodeOutlet]` on a tag to place children dataNodes @@ -19,13 +14,16 @@ import { */ @Directive({ selector: '[matTreeNodeOutlet]', - providers: [{ - provide: CdkTreeNodeOutlet, - useExisting: MatTreeNodeOutlet - }] + providers: [ + { + provide: CdkTreeNodeOutlet, + useExisting: MatTreeNodeOutlet, + }, + ], }) export class MatTreeNodeOutlet implements CdkTreeNodeOutlet { constructor( - public viewContainer: ViewContainerRef, - @Inject(CDK_TREE_NODE_OUTLET_NODE) @Optional() public _node?: any) {} + public viewContainer: ViewContainerRef, + @Inject(CDK_TREE_NODE_OUTLET_NODE) @Optional() public _node?: any, + ) {} } diff --git a/src/material/tree/padding.ts b/src/material/tree/padding.ts index ed53c932f7f6..65a98cf6e37c 100644 --- a/src/material/tree/padding.ts +++ b/src/material/tree/padding.ts @@ -5,6 +5,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ +import {NumberInput} from '@angular/cdk/coercion'; import {CdkTreeNodePadding} from '@angular/cdk/tree'; import {Directive, Input} from '@angular/core'; @@ -13,17 +14,24 @@ import {Directive, Input} from '@angular/core'; */ @Directive({ selector: '[matTreeNodePadding]', - providers: [{provide: CdkTreeNodePadding, useExisting: MatTreeNodePadding}] + providers: [{provide: CdkTreeNodePadding, useExisting: MatTreeNodePadding}], }) -export class MatTreeNodePadding extends CdkTreeNodePadding { - +export class MatTreeNodePadding extends CdkTreeNodePadding { /** The level of depth of the tree node. The padding will be `level * indent` pixels. */ @Input('matTreeNodePadding') - get level(): number { return this._level; } - set level(value: number) { this._setLevelInput(value); } + override get level(): number { + return this._level; + } + override set level(value: NumberInput) { + this._setLevelInput(value); + } /** The indent for each level. Default number 40px from material design menu sub-menu spec. */ @Input('matTreeNodePaddingIndent') - get indent(): number | string { return this._indent; } - set indent(indent: number | string) { this._setIndentInput(indent); } + override get indent(): number | string { + return this._indent; + } + override set indent(indent: number | string) { + this._setIndentInput(indent); + } } diff --git a/src/material/tree/public-api.ts b/src/material/tree/public-api.ts index abc3e880201a..0b70042aa3b1 100644 --- a/src/material/tree/public-api.ts +++ b/src/material/tree/public-api.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ - export * from './node'; export * from './padding'; export * from './tree'; diff --git a/src/material/tree/testing/BUILD.bazel b/src/material/tree/testing/BUILD.bazel index f88c68d49b5d..97363fea2027 100644 --- a/src/material/tree/testing/BUILD.bazel +++ b/src/material/tree/testing/BUILD.bazel @@ -8,7 +8,6 @@ ts_library( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), - module_name = "@angular/material/tree/testing", deps = [ "//src/cdk/coercion", "//src/cdk/testing", diff --git a/src/material/tree/testing/node-harness.ts b/src/material/tree/testing/node-harness.ts index ea8dc1d9975f..b97fcf94906b 100644 --- a/src/material/tree/testing/node-harness.ts +++ b/src/material/tree/testing/node-harness.ts @@ -75,17 +75,25 @@ export class MatTreeNodeHarness extends ContentContainerComponentHarness function getNodePredicate( type: ComponentHarnessConstructor, - options: TreeNodeHarnessFilters): HarnessPredicate { + options: TreeNodeHarnessFilters, +): HarnessPredicate { return new HarnessPredicate(type, options) - .addOption('text', options.text, - (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text)) + .addOption('text', options.text, (harness, text) => + HarnessPredicate.stringMatches(harness.getText(), text), + ) .addOption( - 'disabled', options.disabled, - async (harness, disabled) => (await harness.isDisabled()) === disabled) + 'disabled', + options.disabled, + async (harness, disabled) => (await harness.isDisabled()) === disabled, + ) .addOption( - 'expanded', options.expanded, - async (harness, expanded) => (await harness.isExpanded()) === expanded) + 'expanded', + options.expanded, + async (harness, expanded) => (await harness.isExpanded()) === expanded, + ) .addOption( - 'level', options.level, - async (harness, level) => (await harness.getLevel()) === level); + 'level', + options.level, + async (harness, level) => (await harness.getLevel()) === level, + ); } diff --git a/src/material/tree/testing/shared.spec.ts b/src/material/tree/testing/shared.spec.ts index 8abdab9d02ec..d51872f3fe0f 100644 --- a/src/material/tree/testing/shared.spec.ts +++ b/src/material/tree/testing/shared.spec.ts @@ -4,7 +4,7 @@ import { MatTreeFlatDataSource, MatTreeFlattener, MatTreeModule, - MatTreeNestedDataSource + MatTreeNestedDataSource, } from '@angular/material/tree'; import {MatTreeHarness} from '@angular/material/tree/testing'; import {ComponentFixture, TestBed} from '@angular/core/testing'; @@ -14,7 +14,8 @@ import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; /** Shared tests to run on both the original and MDC-based trees. */ export function runHarnessTests( treeModule: typeof MatTreeModule, - treeHarness: typeof MatTreeHarness) { + treeHarness: typeof MatTreeHarness, +) { let fixture: ComponentFixture; let loader: HarnessLoader; @@ -97,15 +98,12 @@ export function runHarnessTests( expect(await firstGroup.isExpanded()).toBe(false); }); - it ('should correctly get tree structure', async () => { + it('should correctly get tree structure', async () => { const trees = await loader.getAllHarnesses(treeHarness); const flatTree = trees[0]; expect(await flatTree.getTreeStructure()).toEqual({ - children: [ - {text: 'Flat Group 1'}, - {text: 'Flat Group 2'} - ] + children: [{text: 'Flat Group 1'}, {text: 'Flat Group 2'}], }); const firstGroup = (await flatTree.getNodes({text: /Flat Group 1/}))[0]; @@ -115,14 +113,10 @@ export function runHarnessTests( children: [ { text: 'Flat Group 1', - children: [ - {text: 'Flat Leaf 1.1'}, - {text: 'Flat Leaf 1.2'}, - {text: 'Flat Leaf 1.3'} - ] + children: [{text: 'Flat Leaf 1.1'}, {text: 'Flat Leaf 1.2'}, {text: 'Flat Leaf 1.3'}], }, - {text: 'Flat Group 2'} - ] + {text: 'Flat Group 2'}, + ], }); const secondGroup = (await flatTree.getNodes({text: /Flat Group 2/}))[0]; @@ -132,19 +126,13 @@ export function runHarnessTests( children: [ { text: 'Flat Group 1', - children: [ - {text: 'Flat Leaf 1.1'}, - {text: 'Flat Leaf 1.2'}, - {text: 'Flat Leaf 1.3'} - ] + children: [{text: 'Flat Leaf 1.1'}, {text: 'Flat Leaf 1.2'}, {text: 'Flat Leaf 1.3'}], }, { text: 'Flat Group 2', - children: [ - {text: 'Flat Group 2.1'}, - ] - } - ] + children: [{text: 'Flat Group 2.1'}], + }, + ], }); }); @@ -152,50 +140,43 @@ export function runHarnessTests( const trees = await loader.getAllHarnesses(treeHarness); const nestedTree = trees[1]; expect(await nestedTree.getTreeStructure()).toEqual({ - children: [ - {text: 'Nested Group 1'}, - {text: 'Nested Group 2'} - ] + children: [{text: 'Nested Group 1'}, {text: 'Nested Group 2'}], }); const firstGroup = (await nestedTree.getNodes({text: /Nested Group 1/}))[0]; await firstGroup.expand(); - expect(await nestedTree.getTreeStructure()).toEqual( - { - children: [ - { - text: 'Nested Group 1', - children: [ - {text: 'Nested Leaf 1.1'}, - {text: 'Nested Leaf 1.2'}, - {text: 'Nested Leaf 1.3'} - ] - }, - {text: 'Nested Group 2'} - ] - }); + expect(await nestedTree.getTreeStructure()).toEqual({ + children: [ + { + text: 'Nested Group 1', + children: [ + {text: 'Nested Leaf 1.1'}, + {text: 'Nested Leaf 1.2'}, + {text: 'Nested Leaf 1.3'}, + ], + }, + {text: 'Nested Group 2'}, + ], + }); const secondGroup = (await nestedTree.getNodes({text: /Nested Group 2/}))[0]; await secondGroup.expand(); - expect(await nestedTree.getTreeStructure()).toEqual( - { - children: [ - { - text: 'Nested Group 1', - children: [ - {text: 'Nested Leaf 1.1'}, - {text: 'Nested Leaf 1.2'}, - {text: 'Nested Leaf 1.3'} - ] - }, - { - text: 'Nested Group 2', - children: [ - {text: 'Nested Group 2.1'}, - ] - } - ] - }); + expect(await nestedTree.getTreeStructure()).toEqual({ + children: [ + { + text: 'Nested Group 1', + children: [ + {text: 'Nested Leaf 1.1'}, + {text: 'Nested Leaf 1.2'}, + {text: 'Nested Leaf 1.3'}, + ], + }, + { + text: 'Nested Group 2', + children: [{text: 'Nested Group 2.1'}], + }, + ], + }); }); } @@ -207,45 +188,32 @@ interface Node { const FLAT_TREE_DATA: Node[] = [ { name: 'Flat Group 1', - children: [ - {name: 'Flat Leaf 1.1'}, - {name: 'Flat Leaf 1.2'}, - {name: 'Flat Leaf 1.3'}, - ] - }, { + children: [{name: 'Flat Leaf 1.1'}, {name: 'Flat Leaf 1.2'}, {name: 'Flat Leaf 1.3'}], + }, + { name: 'Flat Group 2', children: [ { name: 'Flat Group 2.1', - children: [ - {name: 'Flat Leaf 2.1.1'}, - {name: 'Flat Leaf 2.1.2'}, - {name: 'Flat Leaf 2.1.3'}, - ] - } - ] + children: [{name: 'Flat Leaf 2.1.1'}, {name: 'Flat Leaf 2.1.2'}, {name: 'Flat Leaf 2.1.3'}], + }, + ], }, ]; const NESTED_TREE_DATA: Node[] = [ { name: 'Nested Group 1', - children: [ - {name: 'Nested Leaf 1.1'}, - {name: 'Nested Leaf 1.2'}, - {name: 'Nested Leaf 1.3'}, - ] - }, { + children: [{name: 'Nested Leaf 1.1'}, {name: 'Nested Leaf 1.2'}, {name: 'Nested Leaf 1.3'}], + }, + { name: 'Nested Group 2', children: [ { name: 'Nested Group 2.1', - children: [ - {name: 'Nested Leaf 2.1.1'}, - {name: 'Nested Leaf 2.1.2'}, - ] + children: [{name: 'Nested Leaf 2.1.1'}, {name: 'Nested Leaf 2.1.2'}], }, - ] + ], }, ]; @@ -286,7 +254,7 @@ interface ExampleFlatNode { - ` + `, }) class TreeHarnessTest { private _transformer = (node: Node, level: number) => { @@ -295,12 +263,18 @@ class TreeHarnessTest { name: node.name, level: level, }; - } + }; treeFlattener = new MatTreeFlattener( - this._transformer, node => node.level, node => node.expandable, node => node.children); + this._transformer, + node => node.level, + node => node.expandable, + node => node.children, + ); flatTreeControl = new FlatTreeControl( - node => node.level, node => node.expandable); + node => node.level, + node => node.expandable, + ); flatTreeDataSource = new MatTreeFlatDataSource(this.flatTreeControl, this.treeFlattener); nestedTreeControl = new NestedTreeControl(node => node.children); nestedTreeDataSource = new MatTreeNestedDataSource(); diff --git a/src/material/tree/testing/tree-harness-filters.ts b/src/material/tree/testing/tree-harness-filters.ts index e2893059894a..1a8216f08690 100644 --- a/src/material/tree/testing/tree-harness-filters.ts +++ b/src/material/tree/testing/tree-harness-filters.ts @@ -9,8 +9,7 @@ import {BaseHarnessFilters} from '@angular/cdk/testing'; /** A set of criteria that can be used to filter a list of tree harness instances */ -export interface TreeHarnessFilters extends BaseHarnessFilters { -} +export interface TreeHarnessFilters extends BaseHarnessFilters {} /** A set of criteria that can be used to filter a list of node harness instances. */ export interface TreeNodeHarnessFilters extends BaseHarnessFilters { diff --git a/src/material/tree/testing/tree-harness.ts b/src/material/tree/testing/tree-harness.ts index 40da2fc8a889..472edab9c88e 100644 --- a/src/material/tree/testing/tree-harness.ts +++ b/src/material/tree/testing/tree-harness.ts @@ -79,9 +79,11 @@ export class MatTreeHarness extends ComponentHarness { */ async getTreeStructure(): Promise { const nodes = await this.getNodes(); - const nodeInformation = await parallel(() => nodes.map(node => { - return parallel(() => [node.getLevel(), node.getText(), node.isExpanded()]); - })); + const nodeInformation = await parallel(() => + nodes.map(node => { + return parallel(() => [node.getLevel(), node.getText(), node.isExpanded()]); + }), + ); return this._getTreeStructure(nodeInformation, 1, true); } @@ -91,8 +93,11 @@ export class MatTreeHarness extends ComponentHarness { * @param level The level of nodes that are being accounted for during this iteration * @param parentExpanded Whether the parent of the first node in param nodes is expanded */ - private _getTreeStructure(nodes: [number, string, boolean][], level: number, - parentExpanded: boolean): TextTree { + private _getTreeStructure( + nodes: [number, string, boolean][], + level: number, + parentExpanded: boolean, + ): TextTree { const result: TextTree = {}; for (let i = 0; i < nodes.length; i++) { const [nodeLevel, text, expanded] = nodes[i]; @@ -117,9 +122,11 @@ export class MatTreeHarness extends ComponentHarness { if (nextNodeLevel === level) { this._addChildToNode(result, {text}); } else if (nextNodeLevel > level) { - let children = this._getTreeStructure(nodes.slice(i + 1), + let children = this._getTreeStructure( + nodes.slice(i + 1), nextNodeLevel, - expanded)?.children; + expanded, + )?.children; let child = children ? {text, children} : {text}; this._addChildToNode(result, child); } else { @@ -132,6 +139,6 @@ export class MatTreeHarness extends ComponentHarness { } private _addChildToNode(result: TextTree, child: TextTree) { - result.children ? result.children.push(child) : result.children = [child]; + result.children ? result.children.push(child) : (result.children = [child]); } } diff --git a/src/material/tree/toggle.ts b/src/material/tree/toggle.ts index 16cf9afdf85f..370abd8423d1 100644 --- a/src/material/tree/toggle.ts +++ b/src/material/tree/toggle.ts @@ -6,24 +6,15 @@ * found in the LICENSE file at https://angular.io/license */ -import {coerceBooleanProperty} from '@angular/cdk/coercion'; import {CdkTreeNodeToggle} from '@angular/cdk/tree'; -import {Directive, Input} from '@angular/core'; +import {Directive} from '@angular/core'; /** * Wrapper for the CdkTree's toggle with Material design styles. */ @Directive({ selector: '[matTreeNodeToggle]', - providers: [{provide: CdkTreeNodeToggle, useExisting: MatTreeNodeToggle}] + providers: [{provide: CdkTreeNodeToggle, useExisting: MatTreeNodeToggle}], + inputs: ['recursive: matTreeNodeToggleRecursive'], }) -// tslint:disable-next-line: coercion-types -export class MatTreeNodeToggle extends CdkTreeNodeToggle { - @Input('matTreeNodeToggleRecursive') - get recursive(): boolean { return this._recursive; } - set recursive(value: boolean) { - // TODO: when we remove support for ViewEngine, change this setter to an input - // alias in the decorator metadata. - this._recursive = coerceBooleanProperty(value); - } -} +export class MatTreeNodeToggle extends CdkTreeNodeToggle {} diff --git a/src/material/tree/tree-module.ts b/src/material/tree/tree-module.ts index 66458c1cb959..db17a671f5fe 100644 --- a/src/material/tree/tree-module.ts +++ b/src/material/tree/tree-module.ts @@ -23,7 +23,7 @@ const MAT_TREE_DIRECTIVES = [ MatTreeNodeToggle, MatTree, MatTreeNode, - MatTreeNodeOutlet + MatTreeNodeOutlet, ]; @NgModule({ diff --git a/src/material/tree/tree.spec.ts b/src/material/tree/tree.spec.ts index 17d56a1d7129..76774f7584de 100644 --- a/src/material/tree/tree.spec.ts +++ b/src/material/tree/tree.spec.ts @@ -14,10 +14,9 @@ import { MatTreeFlatDataSource, MatTreeFlattener, MatTreeModule, - MatTreeNestedDataSource + MatTreeNestedDataSource, } from './index'; - describe('MatTree', () => { /** Represents an indent for expectNestedTreeToMatch */ const _ = {}; @@ -37,7 +36,6 @@ describe('MatTree', () => { let fixture: ComponentFixture; let component: SimpleMatTreeApp; - beforeEach(() => { configureMatTreeTestingModule([SimpleMatTreeApp]); fixture = TestBed.createComponent(SimpleMatTreeApp); @@ -52,7 +50,7 @@ describe('MatTree', () => { it('with rendered dataNodes', () => { const nodes = getNodes(treeElement); - expect(nodes).toBeDefined('Expect nodes to be defined'); + expect(nodes).withContext('Expect nodes to be defined').toBeDefined(); expect(nodes[0].classList).toContain('customNodeClass'); }); @@ -66,7 +64,7 @@ describe('MatTree', () => { it('with the right aria-level attrs', () => { // add a child to the first node - let data = underlyingDataSource.data; + const data = underlyingDataSource.data; underlyingDataSource.addChild(data[2]); component.treeControl.expandAll(); fixture.detectChanges(); @@ -77,38 +75,48 @@ describe('MatTree', () => { it('with the right aria-expanded attrs', () => { // add a child to the first node - let data = underlyingDataSource.data; + const data = underlyingDataSource.data; underlyingDataSource.addChild(data[2]); fixture.detectChanges(); - expect(getNodes(treeElement).every(node => { - return node.getAttribute('aria-expanded') === 'false'; - })).toBe(true); + expect( + getNodes(treeElement).every(node => { + return node.getAttribute('aria-expanded') === 'false'; + }), + ).toBe(true); component.treeControl.expandAll(); fixture.detectChanges(); - expect(getNodes(treeElement).every(node => { - return node.getAttribute('aria-expanded') === 'true'; - })).toBe(true); + expect( + getNodes(treeElement).every(node => { + return node.getAttribute('aria-expanded') === 'true'; + }), + ).toBe(true); }); it('with the right data', () => { expect(underlyingDataSource.data.length).toBe(3); - let data = underlyingDataSource.data; - expectFlatTreeToMatch(treeElement, 28, - [`topping_1 - cheese_1 + base_1`], - [`topping_2 - cheese_2 + base_2`], - [`topping_3 - cheese_3 + base_3`]); + const data = underlyingDataSource.data; + expectFlatTreeToMatch( + treeElement, + 28, + [`topping_1 - cheese_1 + base_1`], + [`topping_2 - cheese_2 + base_2`], + [`topping_3 - cheese_3 + base_3`], + ); underlyingDataSource.addChild(data[2]); fixture.detectChanges(); - expectFlatTreeToMatch(treeElement, 28, - [`topping_1 - cheese_1 + base_1`], - [`topping_2 - cheese_2 + base_2`], - [`topping_3 - cheese_3 + base_3`], - [`_, topping_4 - cheese_4 + base_4`]); + expectFlatTreeToMatch( + treeElement, + 28, + [`topping_1 - cheese_1 + base_1`], + [`topping_2 - cheese_2 + base_2`], + [`topping_3 - cheese_3 + base_3`], + [`_, topping_4 - cheese_4 + base_4`], + ); }); }); @@ -131,7 +139,8 @@ describe('MatTree', () => { expect(underlyingDataSource.data.length).toBe(3); expect(component.treeControl.expansionModel.selected.length) - .toBe(0, `Expect no expanded node`); + .withContext(`Expect no expanded node`) + .toBe(0); component.toggleRecursively = false; const data = underlyingDataSource.data; @@ -139,83 +148,107 @@ describe('MatTree', () => { underlyingDataSource.addChild(child); fixture.detectChanges(); - expectFlatTreeToMatch(treeElement, 40, - [`topping_1 - cheese_1 + base_1`], - [`topping_2 - cheese_2 + base_2`], - [`topping_3 - cheese_3 + base_3`]); - + expectFlatTreeToMatch( + treeElement, + 40, + [`topping_1 - cheese_1 + base_1`], + [`topping_2 - cheese_2 + base_2`], + [`topping_3 - cheese_3 + base_3`], + ); (getNodes(treeElement)[2] as HTMLElement).click(); fixture.detectChanges(); expect(component.treeControl.expansionModel.selected.length) - .toBe(1, `Expect node expanded one level`); - expectFlatTreeToMatch(treeElement, 40, - [`topping_1 - cheese_1 + base_1`], - [`topping_2 - cheese_2 + base_2`], - [`topping_3 - cheese_3 + base_3`], - [_, `topping_4 - cheese_4 + base_4`]); + .withContext(`Expect node expanded one level`) + .toBe(1); + expectFlatTreeToMatch( + treeElement, + 40, + [`topping_1 - cheese_1 + base_1`], + [`topping_2 - cheese_2 + base_2`], + [`topping_3 - cheese_3 + base_3`], + [_, `topping_4 - cheese_4 + base_4`], + ); (getNodes(treeElement)[3] as HTMLElement).click(); fixture.detectChanges(); expect(component.treeControl.expansionModel.selected.length) - .toBe(2, `Expect node expanded`); - expectFlatTreeToMatch(treeElement, 40, - [`topping_1 - cheese_1 + base_1`], - [`topping_2 - cheese_2 + base_2`], - [`topping_3 - cheese_3 + base_3`], - [_, `topping_4 - cheese_4 + base_4`], - [_, _, `topping_5 - cheese_5 + base_5`]); + .withContext(`Expect node expanded`) + .toBe(2); + expectFlatTreeToMatch( + treeElement, + 40, + [`topping_1 - cheese_1 + base_1`], + [`topping_2 - cheese_2 + base_2`], + [`topping_3 - cheese_3 + base_3`], + [_, `topping_4 - cheese_4 + base_4`], + [_, _, `topping_5 - cheese_5 + base_5`], + ); (getNodes(treeElement)[2] as HTMLElement).click(); fixture.detectChanges(); - expectFlatTreeToMatch(treeElement, 40, - [`topping_1 - cheese_1 + base_1`], - [`topping_2 - cheese_2 + base_2`], - [`topping_3 - cheese_3 + base_3`]); + expectFlatTreeToMatch( + treeElement, + 40, + [`topping_1 - cheese_1 + base_1`], + [`topping_2 - cheese_2 + base_2`], + [`topping_3 - cheese_3 + base_3`], + ); }); it('should expand/collapse the node recursively', () => { expect(underlyingDataSource.data.length).toBe(3); expect(component.treeControl.expansionModel.selected.length) - .toBe(0, `Expect no expanded node`); + .withContext(`Expect no expanded node`) + .toBe(0); const data = underlyingDataSource.data; const child = underlyingDataSource.addChild(data[2]); underlyingDataSource.addChild(child); fixture.detectChanges(); - expectFlatTreeToMatch(treeElement, 40, - [`topping_1 - cheese_1 + base_1`], - [`topping_2 - cheese_2 + base_2`], - [`topping_3 - cheese_3 + base_3`]); + expectFlatTreeToMatch( + treeElement, + 40, + [`topping_1 - cheese_1 + base_1`], + [`topping_2 - cheese_2 + base_2`], + [`topping_3 - cheese_3 + base_3`], + ); (getNodes(treeElement)[2] as HTMLElement).click(); fixture.detectChanges(); expect(component.treeControl.expansionModel.selected.length) - .toBe(3, `Expect nodes expanded`); - expectFlatTreeToMatch(treeElement, 40, - [`topping_1 - cheese_1 + base_1`], - [`topping_2 - cheese_2 + base_2`], - [`topping_3 - cheese_3 + base_3`], - [_, `topping_4 - cheese_4 + base_4`], - [_, _, `topping_5 - cheese_5 + base_5`]); - + .withContext(`Expect nodes expanded`) + .toBe(3); + expectFlatTreeToMatch( + treeElement, + 40, + [`topping_1 - cheese_1 + base_1`], + [`topping_2 - cheese_2 + base_2`], + [`topping_3 - cheese_3 + base_3`], + [_, `topping_4 - cheese_4 + base_4`], + [_, _, `topping_5 - cheese_5 + base_5`], + ); (getNodes(treeElement)[2] as HTMLElement).click(); fixture.detectChanges(); expect(component.treeControl.expansionModel.selected.length) - .toBe(0, `Expect node collapsed`); + .withContext(`Expect node collapsed`) + .toBe(0); - expectFlatTreeToMatch(treeElement, 40, + expectFlatTreeToMatch( + treeElement, + 40, [`topping_1 - cheese_1 + base_1`], [`topping_2 - cheese_2 + base_2`], - [`topping_3 - cheese_3 + base_3`]); + [`topping_3 - cheese_3 + base_3`], + ); }); }); @@ -235,22 +268,25 @@ describe('MatTree', () => { }); it('with the right data', () => { - expectFlatTreeToMatch(treeElement, 28, + expectFlatTreeToMatch( + treeElement, + 28, [`topping_1 - cheese_1 + base_1`], [`topping_2 - cheese_2 + base_2`], [`topping_3 - cheese_3 + base_3`], - [`>>> topping_4 - cheese_4 + base_4`]); + [`>>> topping_4 - cheese_4 + base_4`], + ); }); }); }); describe('flat tree with undefined or null children', () => { describe('should initialize', () => { - let fixture: ComponentFixture; + let fixture: ComponentFixture; beforeEach(() => { - configureMatTreeTestingModule([MatTreeWithNullOrUndefinedChild ]); - fixture = TestBed.createComponent(MatTreeWithNullOrUndefinedChild ); + configureMatTreeTestingModule([MatTreeWithNullOrUndefinedChild]); + fixture = TestBed.createComponent(MatTreeWithNullOrUndefinedChild); treeElement = fixture.nativeElement.querySelector('mat-tree'); fixture.detectChanges(); @@ -259,7 +295,7 @@ describe('MatTree', () => { it('with rendered dataNodes', () => { const nodes = getNodes(treeElement); - expect(nodes).toBeDefined('Expect nodes to be defined'); + expect(nodes).withContext('Expect nodes to be defined').toBeDefined(); expect(nodes[0].classList).toContain('customNodeClass'); }); }); @@ -267,7 +303,7 @@ describe('MatTree', () => { describe('nested tree with undefined or null children', () => { describe('should initialize', () => { - let fixture: ComponentFixture; + let fixture: ComponentFixture; beforeEach(() => { configureMatTreeTestingModule([MatNestedTreeWithNullOrUndefinedChild]); @@ -280,7 +316,7 @@ describe('MatTree', () => { it('with rendered dataNodes', () => { const nodes = getNodes(treeElement); - expect(nodes).toBeDefined('Expect nodes to be defined'); + expect(nodes).withContext('Expect nodes to be defined').toBeDefined(); expect(nodes[0].classList).toContain('customNodeClass'); }); }); @@ -304,7 +340,7 @@ describe('MatTree', () => { it('with rendered dataNodes', () => { const nodes = getNodes(treeElement); - expect(nodes).toBeDefined('Expect nodes to be defined'); + expect(nodes).withContext('Expect nodes to be defined').toBeDefined(); expect(nodes[0].classList).toContain('customNodeClass'); }); @@ -320,10 +356,12 @@ describe('MatTree', () => { expect(underlyingDataSource.data.length).toBe(3); let data = underlyingDataSource.data; - expectNestedTreeToMatch(treeElement, + expectNestedTreeToMatch( + treeElement, [`${data[0].pizzaTopping} - ${data[0].pizzaCheese} + ${data[0].pizzaBase}`], [`${data[1].pizzaTopping} - ${data[1].pizzaCheese} + ${data[1].pizzaBase}`], - [`${data[2].pizzaTopping} - ${data[2].pizzaCheese} + ${data[2].pizzaBase}`]); + [`${data[2].pizzaTopping} - ${data[2].pizzaCheese} + ${data[2].pizzaBase}`], + ); underlyingDataSource.addChild(data[1]); fixture.detectChanges(); @@ -331,48 +369,56 @@ describe('MatTree', () => { treeElement = fixture.nativeElement.querySelector('mat-tree'); data = underlyingDataSource.data; expect(data.length).toBe(3); - expectNestedTreeToMatch(treeElement, + expectNestedTreeToMatch( + treeElement, [`topping_1 - cheese_1 + base_1`], [`topping_2 - cheese_2 + base_2`], [_, `topping_4 - cheese_4 + base_4`], - [`topping_3 - cheese_3 + base_3`]); + [`topping_3 - cheese_3 + base_3`], + ); }); it('with nested child data', () => { expect(underlyingDataSource.data.length).toBe(3); - let data = underlyingDataSource.data; + const data = underlyingDataSource.data; const child = underlyingDataSource.addChild(data[1]); underlyingDataSource.addChild(child); fixture.detectChanges(); expect(data.length).toBe(3); - expectNestedTreeToMatch(treeElement, + expectNestedTreeToMatch( + treeElement, [`topping_1 - cheese_1 + base_1`], [`topping_2 - cheese_2 + base_2`], [_, `topping_4 - cheese_4 + base_4`], [_, _, `topping_5 - cheese_5 + base_5`], - [`topping_3 - cheese_3 + base_3`]); + [`topping_3 - cheese_3 + base_3`], + ); underlyingDataSource.addChild(child); fixture.detectChanges(); expect(data.length).toBe(3); - expectNestedTreeToMatch(treeElement, + expectNestedTreeToMatch( + treeElement, [`topping_1 - cheese_1 + base_1`], [`topping_2 - cheese_2 + base_2`], [_, `topping_4 - cheese_4 + base_4`], [_, _, `topping_5 - cheese_5 + base_5`], [_, _, `topping_6 - cheese_6 + base_6`], - [`topping_3 - cheese_3 + base_3`]); + [`topping_3 - cheese_3 + base_3`], + ); }); it('with correct aria-level on nodes', () => { - expect(getNodes(treeElement).every(node => { - return node.getAttribute('aria-level') === '1'; - })).toBe(true); + expect( + getNodes(treeElement).every(node => { + return node.getAttribute('aria-level') === '1'; + }), + ).toBe(true); - let data = underlyingDataSource.data; + const data = underlyingDataSource.data; const child = underlyingDataSource.addChild(data[1]); underlyingDataSource.addChild(child); fixture.detectChanges(); @@ -398,11 +444,13 @@ describe('MatTree', () => { }); it('with the right data', () => { - expectNestedTreeToMatch(treeElement, + expectNestedTreeToMatch( + treeElement, [`topping_1 - cheese_1 + base_1`], [`topping_2 - cheese_2 + base_2`], [`topping_3 - cheese_3 + base_3`], - [`>>> topping_4 - cheese_4 + base_4`]); + [`>>> topping_4 - cheese_4 + base_4`], + ); }); }); @@ -422,12 +470,14 @@ describe('MatTree', () => { }); it('with the right aria-expanded attrs', () => { - expect(getNodes(treeElement).every(node => { - return node.getAttribute('aria-expanded') === 'false'; - })).toBe(true); + expect( + getNodes(treeElement).every(node => { + return node.getAttribute('aria-expanded') === 'false'; + }), + ).toBe(true); component.toggleRecursively = false; - let data = underlyingDataSource.data; + const data = underlyingDataSource.data; const child = underlyingDataSource.addChild(data[1]); underlyingDataSource.addChild(child); fixture.detectChanges(); @@ -441,16 +491,18 @@ describe('MatTree', () => { it('should expand/collapse the node', () => { component.toggleRecursively = false; - let data = underlyingDataSource.data; + const data = underlyingDataSource.data; const child = underlyingDataSource.addChild(data[1]); underlyingDataSource.addChild(child); fixture.detectChanges(); - expectNestedTreeToMatch(treeElement, + expectNestedTreeToMatch( + treeElement, [`topping_1 - cheese_1 + base_1`], [`topping_2 - cheese_2 + base_2`], - [`topping_3 - cheese_3 + base_3`]); + [`topping_3 - cheese_3 + base_3`], + ); fixture.detectChanges(); @@ -458,56 +510,70 @@ describe('MatTree', () => { fixture.detectChanges(); expect(component.treeControl.expansionModel.selected.length) - .toBe(1, `Expect node expanded`); - expectNestedTreeToMatch(treeElement, + .withContext(`Expect node expanded`) + .toBe(1); + expectNestedTreeToMatch( + treeElement, [`topping_1 - cheese_1 + base_1`], [`topping_2 - cheese_2 + base_2`], [_, `topping_4 - cheese_4 + base_4`], - [`topping_3 - cheese_3 + base_3`]); + [`topping_3 - cheese_3 + base_3`], + ); (getNodes(treeElement)[1] as HTMLElement).click(); fixture.detectChanges(); - expectNestedTreeToMatch(treeElement, + expectNestedTreeToMatch( + treeElement, [`topping_1 - cheese_1 + base_1`], [`topping_2 - cheese_2 + base_2`], - [`topping_3 - cheese_3 + base_3`]); + [`topping_3 - cheese_3 + base_3`], + ); expect(component.treeControl.expansionModel.selected.length) - .toBe(0, `Expect node collapsed`); + .withContext(`Expect node collapsed`) + .toBe(0); }); it('should expand/collapse the node recursively', () => { - let data = underlyingDataSource.data; + const data = underlyingDataSource.data; const child = underlyingDataSource.addChild(data[1]); underlyingDataSource.addChild(child); fixture.detectChanges(); - expectNestedTreeToMatch(treeElement, + expectNestedTreeToMatch( + treeElement, [`topping_1 - cheese_1 + base_1`], [`topping_2 - cheese_2 + base_2`], - [`topping_3 - cheese_3 + base_3`]); + [`topping_3 - cheese_3 + base_3`], + ); (getNodes(treeElement)[1] as HTMLElement).click(); fixture.detectChanges(); expect(component.treeControl.expansionModel.selected.length) - .toBe(3, `Expect node expanded`); - expectNestedTreeToMatch(treeElement, + .withContext(`Expect node expanded`) + .toBe(3); + expectNestedTreeToMatch( + treeElement, [`topping_1 - cheese_1 + base_1`], [`topping_2 - cheese_2 + base_2`], [_, `topping_4 - cheese_4 + base_4`], [_, _, `topping_5 - cheese_5 + base_5`], - [`topping_3 - cheese_3 + base_3`]); + [`topping_3 - cheese_3 + base_3`], + ); (getNodes(treeElement)[1] as HTMLElement).click(); fixture.detectChanges(); expect(component.treeControl.expansionModel.selected.length) - .toBe(0, `Expect node collapsed`); - expectNestedTreeToMatch(treeElement, + .withContext(`Expect node collapsed`) + .toBe(0); + expectNestedTreeToMatch( + treeElement, [`topping_1 - cheese_1 + base_1`], [`topping_2 - cheese_2 + base_2`], - [`topping_3 - cheese_3 + base_3`]); + [`topping_3 - cheese_3 + base_3`], + ); }); }); }); @@ -522,8 +588,13 @@ export class TestData { observableChildren: BehaviorSubject; isSpecial: boolean; - constructor(pizzaTopping: string, pizzaCheese: string, pizzaBase: string, - children: TestData[] = [], isSpecial: boolean = false) { + constructor( + pizzaTopping: string, + pizzaCheese: string, + pizzaBase: string, + children: TestData[] = [], + isSpecial: boolean = false, + ) { this.pizzaTopping = pizzaTopping; this.pizzaCheese = pizzaCheese; this.pizzaBase = pizzaBase; @@ -536,8 +607,12 @@ export class TestData { class FakeDataSource { dataIndex = 0; _dataChange = new BehaviorSubject([]); - get data() { return this._dataChange.getValue(); } - set data(data: TestData[]) { this._dataChange.next(data); } + get data() { + return this._dataChange.getValue(); + } + set data(data: TestData[]) { + this._dataChange.next(data); + } connect(): Observable { return this._dataChange; @@ -558,7 +633,12 @@ class FakeDataSource { const index = this.data.indexOf(parent); if (index > -1) { parent = new TestData( - parent.pizzaTopping, parent.pizzaCheese, parent.pizzaBase, parent.children, isSpecial); + parent.pizzaTopping, + parent.pizzaCheese, + parent.pizzaBase, + parent.children, + isSpecial, + ); } parent.children.push(child); parent.observableChildren.next(parent.children); @@ -574,8 +654,15 @@ class FakeDataSource { addData(isSpecial: boolean = false) { const nextIndex = ++this.dataIndex; let copiedData = this.data.slice(); - copiedData.push(new TestData( - `topping_${nextIndex}`, `cheese_${nextIndex}`, `base_${nextIndex}`, [], isSpecial)); + copiedData.push( + new TestData( + `topping_${nextIndex}`, + `cheese_${nextIndex}`, + `base_${nextIndex}`, + [], + isSpecial, + ), + ); this.data = copiedData; } @@ -585,8 +672,11 @@ function getNodes(treeElement: Element): Element[] { return [].slice.call(treeElement.querySelectorAll('.mat-tree-node, .mat-nested-tree-node'))!; } -function expectFlatTreeToMatch(treeElement: Element, expectedPaddingIndent: number = 28, - ...expectedTree: any[]) { +function expectFlatTreeToMatch( + treeElement: Element, + expectedPaddingIndent: number = 28, + ...expectedTree: any[] +) { const missedExpectations: string[] = []; function checkNode(node: Element, expectedNode: any[]) { @@ -594,7 +684,8 @@ function expectFlatTreeToMatch(treeElement: Element, expectedPaddingIndent: numb const expectedTextContent = expectedNode[expectedNode.length - 1]; if (actualTextContent !== expectedTextContent) { missedExpectations.push( - `Expected node contents to be ${expectedTextContent} but was ${actualTextContent}`); + `Expected node contents to be ${expectedTextContent} but was ${actualTextContent}`, + ); } } @@ -605,22 +696,20 @@ function expectFlatTreeToMatch(treeElement: Element, expectedPaddingIndent: numb const actualLevel = rawLevel === '0' ? '0px' : rawLevel; if (expectedNode.length === 1) { if (actualLevel !== `` && actualLevel !== '0px') { - missedExpectations.push( - `Expected node level to be 0px but was ${actualLevel}`); + missedExpectations.push(`Expected node level to be 0px but was ${actualLevel}`); } } else { const expectedLevel = `${(expectedNode.length - 1) * expectedPaddingIndent}px`; if (actualLevel != expectedLevel) { missedExpectations.push( - `Expected node level to be ${expectedLevel} but was ${actualLevel}`); + `Expected node level to be ${expectedLevel} but was ${actualLevel}`, + ); } } } getNodes(treeElement).forEach((node, index) => { - const expected = expectedTree ? - expectedTree[index] : - null; + const expected = expectedTree ? expectedTree[index] : null; checkLevel(node, expected); checkNode(node, expected); @@ -638,7 +727,8 @@ function expectNestedTreeToMatch(treeElement: Element, ...expectedTree: any[]) { const actualTextContent = node.childNodes.item(0).textContent!.trim(); if (actualTextContent !== expectedTextContent) { missedExpectations.push( - `Expected node contents to be ${expectedTextContent} but was ${actualTextContent}`); + `Expected node contents to be ${expectedTextContent} but was ${actualTextContent}`, + ); } } @@ -656,15 +746,13 @@ function expectNestedTreeToMatch(treeElement: Element, ...expectedTree: any[]) { const actualDescendant = getNodes(node).length; if (actualDescendant !== expectedDescendant) { missedExpectations.push( - `Expected node descendant num to be ${expectedDescendant} but was ${actualDescendant}`); + `Expected node descendant num to be ${expectedDescendant} but was ${actualDescendant}`, + ); } } getNodes(treeElement).forEach((node, index) => { - - const expected = expectedTree ? - expectedTree[index] : - null; + const expected = expectedTree ? expectedTree[index] : null; checkNodeDescendants(node, expected, index); checkNodeContent(node, expected); @@ -684,7 +772,7 @@ function expectNestedTreeToMatch(treeElement: Element, ...expectedTree: any[]) { {{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}} - ` + `, }) class SimpleMatTreeApp { getLevel = (node: TestData) => node.level; @@ -693,10 +781,14 @@ class SimpleMatTreeApp { transformer = (node: TestData, level: number) => { node.level = level; return node; - } + }; treeFlattener = new MatTreeFlattener( - this.transformer, this.getLevel, this.isExpandable, this.getChildren); + this.transformer, + this.getLevel, + this.isExpandable, + this.getChildren, + ); treeControl = new FlatTreeControl(this.getLevel, this.isExpandable); @@ -732,29 +824,20 @@ interface ExampleFlatNode { const TREE_DATA: FoodNode[] = [ { name: 'Fruit', - children: [ - {name: 'Apple'}, - {name: 'Banana'}, - {name: 'Fruit loops', - children: null}, - ] - }, { + children: [{name: 'Apple'}, {name: 'Banana'}, {name: 'Fruit loops', children: null}], + }, + { name: 'Vegetables', children: [ { name: 'Green', - children: [ - {name: 'Broccoli'}, - {name: 'Brussels sprouts'}, - ] - }, { + children: [{name: 'Broccoli'}, {name: 'Brussels sprouts'}], + }, + { name: 'Orange', - children: [ - {name: 'Pumpkins'}, - {name: 'Carrots'}, - ] + children: [{name: 'Pumpkins'}, {name: 'Carrots'}], }, - ] + ], }, ]; @@ -766,7 +849,7 @@ const TREE_DATA: FoodNode[] = [ {{node.name}} - ` + `, }) class MatTreeWithNullOrUndefinedChild { private _transformer = (node: FoodNode, level: number) => { @@ -775,20 +858,22 @@ class MatTreeWithNullOrUndefinedChild { name: node.name, level: level, }; - } + }; treeControl = new FlatTreeControl( - node => node.level, node => node.expandable); + node => node.level, + node => node.expandable, + ); treeFlattener = new MatTreeFlattener( - this._transformer, node => node.level, node => node.expandable, node => node.children); + this._transformer, + node => node.level, + node => node.expandable, + node => node.children, + ); dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener, TREE_DATA); - constructor() { - this.dataSource.data = TREE_DATA; - } - hasChild = (_: number, node: ExampleFlatNode) => node.expandable; } @@ -800,7 +885,7 @@ class MatTreeWithNullOrUndefinedChild { - ` + `, }) class MatNestedTreeWithNullOrUndefinedChild { treeControl: NestedTreeControl; @@ -823,7 +908,7 @@ class MatNestedTreeWithNullOrUndefinedChild { - ` + `, }) class NestedMatTreeApp { getChildren = (node: TestData) => node.observableChildren; @@ -857,10 +942,10 @@ class NestedMatTreeApp {
- ` + `, }) class WhenNodeNestedMatTreeApp { - isSpecial = (_: number, node: TestData) => node.isSpecial; + isSpecial = (_: number, node: TestData) => node.isSpecial; getChildren = (node: TestData) => node.observableChildren; @@ -878,7 +963,6 @@ class WhenNodeNestedMatTreeApp { } } - @Component({ template: ` @@ -888,7 +972,7 @@ class WhenNodeNestedMatTreeApp { {{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}} - ` + `, }) class MatTreeAppWithToggle { toggleRecursively: boolean = true; @@ -899,10 +983,14 @@ class MatTreeAppWithToggle { transformer = (node: TestData, level: number) => { node.level = level; return node; - } + }; treeFlattener = new MatTreeFlattener( - this.transformer, this.getLevel, this.isExpandable, this.getChildren); + this.transformer, + this.getLevel, + this.isExpandable, + this.getChildren, + ); treeControl = new FlatTreeControl(this.getLevel, this.isExpandable); @@ -929,7 +1017,7 @@ class MatTreeAppWithToggle { - ` + `, }) class NestedMatTreeAppWithToggle { toggleRecursively: boolean = true; @@ -963,7 +1051,7 @@ class NestedMatTreeAppWithToggle { >>> {{node.pizzaTopping}} - {{node.pizzaCheese}} + {{node.pizzaBase}} - ` + `, }) class WhenNodeMatTreeApp { isSpecial = (_: number, node: TestData) => node.isSpecial; @@ -974,10 +1062,14 @@ class WhenNodeMatTreeApp { transformer = (node: TestData, level: number) => { node.level = level; return node; - } + }; treeFlattener = new MatTreeFlattener( - this.transformer, this.getLevel, this.isExpandable, this.getChildren); + this.transformer, + this.getLevel, + this.isExpandable, + this.getChildren, + ); treeControl = new FlatTreeControl(this.getLevel, this.isExpandable); diff --git a/src/material/tree/tree.ts b/src/material/tree/tree.ts index f64c6f4db725..e546cac0b234 100644 --- a/src/material/tree/tree.ts +++ b/src/material/tree/tree.ts @@ -7,12 +7,7 @@ */ import {CdkTree} from '@angular/cdk/tree'; -import { - ChangeDetectionStrategy, - Component, - ViewChild, - ViewEncapsulation -} from '@angular/core'; +import {ChangeDetectionStrategy, Component, ViewChild, ViewEncapsulation} from '@angular/core'; import {MatTreeNodeOutlet} from './outlet'; /** @@ -23,14 +18,7 @@ import {MatTreeNodeOutlet} from './outlet'; exportAs: 'matTree', template: ``, host: { - // The 'cdk-tree' class needs to be included here because classes set in the host in the - // parent class are not inherited with View Engine. The 'cdk-tree' class in CdkTreeNode has - // to be set in the host because: - // if it is set as a @HostBinding it is not set by the time the tree nodes try to read the - // class from it. - // the ElementRef is not available in the constructor so the class can't be applied directly - // without a breaking constructor change. - 'class': 'mat-tree cdk-tree', + 'class': 'mat-tree', 'role': 'tree', }, styleUrls: ['tree.css'], @@ -38,9 +26,9 @@ import {MatTreeNodeOutlet} from './outlet'; // See note on CdkTree for explanation on why this uses the default change detection strategy. // tslint:disable-next-line:validate-decorators changeDetection: ChangeDetectionStrategy.Default, - providers: [{provide: CdkTree, useExisting: MatTree}] + providers: [{provide: CdkTree, useExisting: MatTree}], }) -export class MatTree extends CdkTree { +export class MatTree extends CdkTree { // Outlets within the tree's template where the dataNodes will be inserted. - @ViewChild(MatTreeNodeOutlet, {static: true}) _nodeOutlet: MatTreeNodeOutlet; + @ViewChild(MatTreeNodeOutlet, {static: true}) override _nodeOutlet: MatTreeNodeOutlet; } diff --git a/src/material/tsconfig-tests.json b/src/material/tsconfig-tests.json deleted file mode 100644 index 7c67f4b16d38..000000000000 --- a/src/material/tsconfig-tests.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "extends": "../bazel-tsconfig-build.json", - "compilerOptions": { - "baseUrl": ".", - "outDir": "../../dist/packages/material", - "rootDir": ".", - "rootDirs": [ - ".", - "../../dist/packages/material" - ], - "importHelpers": false, - "module": "umd", - "target": "es5", - "types": ["jasmine"], - "experimentalDecorators": true, - "emitDecoratorMetadata": true, - "paths": { - "@angular/cdk": ["../../dist/packages/cdk"], - "@angular/cdk/*": ["../../dist/packages/cdk/*"], - "@angular/material/*": ["./*"] - } - }, - "include": [ - "**/index.ts", - "**/*.spec.ts", - "../dev-mode-types.d.ts" - ], - "exclude": [ - "core/theming/tests/**/*.ts", - "**/schematics/**/*.ts", - "**/*.e2e.spec.ts" - ] -} diff --git a/src/tsconfig-legacy.json b/src/tsconfig-legacy.json new file mode 100644 index 000000000000..813c81f0fea5 --- /dev/null +++ b/src/tsconfig-legacy.json @@ -0,0 +1,32 @@ +{ + "extends": "./bazel-tsconfig-test.json", + "compilerOptions": { + "outDir": "../dist/legacy-test-out", + "declaration": false, + // For the legacy tests, we use ES2016 so that ZoneJS can work with async/await. + "target": "es2016", + "paths": { + "@angular/*": ["./*"] + }, + "types": ["jasmine"], + "emitDecoratorMetadata": true, + "experimentalDecorators": true + }, + "include": [ + "**/*.spec.ts", + "dev-mode-types.d.ts", + "../node_modules/zone.js/zone.d.ts" + ], + "exclude": [ + "**/*.e2e.spec.ts", + "./cdk/schematics/**/*", + "./material/schematics/**/*", + "./components-examples/**/*", + "./material/core/theming/tests/**/*" + ], + "angularCompilerOptions": { + // This is needed so that test components are not AOT compiled. Ngtsc will + // not find an associated module for test components and error out. + "compileNonExportedClasses": false + } +} diff --git a/src/universal-app/BUILD.bazel b/src/universal-app/BUILD.bazel index 603ba3fedcf7..2be71a5bd5f4 100644 --- a/src/universal-app/BUILD.bazel +++ b/src/universal-app/BUILD.bazel @@ -3,7 +3,8 @@ load("//src/cdk:config.bzl", "CDK_TARGETS") load("//src/cdk-experimental:config.bzl", "CDK_EXPERIMENTAL_TARGETS") load("//src/material:config.bzl", "MATERIAL_TARGETS") load("//src/material-experimental:config.bzl", "MATERIAL_EXPERIMENTAL_TARGETS") -load("//tools:defaults.bzl", "ng_module", "sass_binary", "ts_library") +load("//tools:defaults.bzl", "devmode_esbuild", "ng_module", "sass_binary", "ts_library") +load("//tools/angular:index.bzl", "LINKER_PROCESSED_FW_PACKAGES") package(default_visibility = ["//visibility:public"]) @@ -33,6 +34,7 @@ ts_library( deps = [ ":kitchen-sink", "@npm//@angular/platform-server", + "@npm//@bazel/runfiles", "@npm//@types/node", "@npm//reflect-metadata", "@npm//zone.js", @@ -46,18 +48,38 @@ sass_binary( "external/npm/node_modules", ], deps = [ + "//src/material:theming_bundle", "//src/material-experimental/mdc-theming:all_themes", "//src/material-experimental/mdc-typography:all_typography", "//src/material/core:theming_scss_lib", ], ) +devmode_esbuild( + name = "server_bundle", + entry_point = ":prerender.ts", + platform = "node", + # We cannot use `ES2017` or higher as that would result in `async/await` not being downleveled. + # ZoneJS needs to be able to intercept these as otherwise change detection would not work properly. + target = "es2016", + # Note: We add all linker-processed FW packages as dependencies here so that ESBuild will + # map all framework packages to their linker-processed bundles from `tools/angular`. + deps = LINKER_PROCESSED_FW_PACKAGES + [ + ":server", + ], +) + nodejs_test( name = "server_test", data = [ "index.html", - ":server", + ":server_bundle", ":theme_scss", ], - entry_point = ":prerender.ts", + entry_point = ":server_bundle.js", + templated_args = [ + # TODO(josephperrott): update dependency usages to no longer need bazel patch module resolver + # See: https://github.com/bazelbuild/rules_nodejs/wiki#--bazel_patch_module_resolver-now-defaults-to-false-2324 + "--bazel_patch_module_resolver", + ], ) diff --git a/src/universal-app/DEBUG.md b/src/universal-app/DEBUG.md index 24fff3e3a8c1..cf1190863bd3 100644 --- a/src/universal-app/DEBUG.md +++ b/src/universal-app/DEBUG.md @@ -6,5 +6,5 @@ the file will be stored in the `bazel-out` folder. You can retrieve the path to the file by either running: -* `bazel test //src/universal-app:server_test --test_output=all` -* `echo $(bazel info bazel-bin)/src/universal-app/index-prerendered.html` +* `bazel run //src/universal-app:server_test --test_output=all` +* `echo $(bazel info bazel-testlogs)/src/universal-app/server_test/test.outputs/index-prerendered.html` diff --git a/src/universal-app/index.html b/src/universal-app/index.html index 2457d24e2f98..83773c967cc8 100644 --- a/src/universal-app/index.html +++ b/src/universal-app/index.html @@ -5,8 +5,9 @@ Angular Material Universal Kitchen Sink Test + - +
+ {{headerText}} + + {{dataAccessor(data, name)}} +