Skip to content

refactor(list): use light-weight tokens for injecting parent lists #19568

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -514,8 +514,8 @@ jobs:
- *setup_bazel_remote_execution
- *yarn_install
- *setup_bazel_binary
# Integration tests run with --config=view-engine because we release with View Engine.
- run: bazel test integration/... --build_tests_only --config=view-engine
- run: yarn integration-tests
- run: yarn integration-tests:view-engine

# ----------------------------------------------------------------------------
# Job that runs all Bazel tests against material-components-web@canary
Expand Down
2 changes: 2 additions & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -319,3 +319,5 @@
/.vscode/** @angular/dev-infra-components @mmalerba
/src/* @jelbourn
/goldens/ts-circular-deps.json @angular/dev-infra-components
/goldens/size-test.json @jelbourn @mmalerba @crisbeto
/goldens/* @angular/dev-infra-components
4 changes: 2 additions & 2 deletions WORKSPACE
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# Add NodeJS rules
http_archive(
name = "build_bazel_rules_nodejs",
sha256 = "d14076339deb08e5460c221fae5c5e9605d2ef4848eee1f0c81c9ffdc1ab31c1",
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/1.6.1/rules_nodejs-1.6.1.tar.gz"],
sha256 = "84abf7ac4234a70924628baa9a73a5a5cbad944c4358cf9abdb4aab29c9a5b77",
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/1.7.0/rules_nodejs-1.7.0.tar.gz"],
)

# Add sass rules
Expand Down
3 changes: 3 additions & 0 deletions goldens/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
exports_files([
"size-test.json",
])
3 changes: 3 additions & 0 deletions goldens/size-test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"material/list": 215881
}
17 changes: 17 additions & 0 deletions integration/size-test/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
load("//tools:defaults.bzl", "ts_library")

package(default_visibility = ["//visibility:public"])

exports_files([
"rollup.config.js",
"terser-config.json",
])

ts_library(
name = "check-size",
srcs = ["check-size.ts"],
deps = [
"@npm//@types/node",
"@npm//chalk",
],
)
75 changes: 75 additions & 0 deletions integration/size-test/check-size.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* Script that measures the size of a given test file and compares it
* with an entry in a file size golden. If the size deviates by certain
* amount, the script will fail with a non-zero exit code.
*/

import chalk from 'chalk';
import {readFileSync, statSync, writeFileSync} from 'fs';

/**
* Absolute byte deviation from the expected value that is allowed. If the
* size deviates by 500 bytes of the expected value, the script will fail.
*/
const ABSOLUTE_BYTE_THRESHOLD = 500;
/**
* Percentage deviation from the expected value that is allowed. If the
* size deviates by 1% of the expected value, the script will fail.
*/
const PERCENTAGE_DEVIATION_THRESHOLD = 1;

/**
* Extracted command line arguments specified by the Bazel NodeJS binaries:
* - `testId`: Unique id for the given test file that is used as key in the golden.
* - `testFileRootpath`: Bazel rootpath that resolves to the test file that should be measured.
* - `isApprove`: Whether the script runs in approve mode, and the golden should be updated
* with the actual measured size.
*/
const [testId, testFileRootpath, isApprove] = process.argv.slice(2);
const testFilePath = require.resolve(`angular_material/${testFileRootpath}`);
const goldenFilePath = require.resolve('../../goldens/size-test.json');

const golden = JSON.parse(readFileSync(goldenFilePath, 'utf8'));
const fileStat = statSync(testFilePath);
const actualSize = fileStat.size;

// If in approve mode, update the golden to reflect the new size.
if (isApprove) {
golden[testId] = actualSize;
writeFileSync(goldenFilePath, JSON.stringify(golden, null, 2));
console.info(chalk.green(`Approved golden size for "${testId}"`));
process.exit(0);
}

// If no size has been collected for the test id, report an error.
if (golden[testId] === undefined) {
console.error(`No golden size for "${testId}". Please create a new entry.`);
printApproveCommand();
process.exit(1);
}

const expectedSize = Number(golden[testId]);
const absoluteSizeDiff = Math.abs(actualSize - expectedSize);
const deviatedByPercentage =
absoluteSizeDiff > (expectedSize * PERCENTAGE_DEVIATION_THRESHOLD / 100);
const deviatedByAbsoluteDiff = absoluteSizeDiff > ABSOLUTE_BYTE_THRESHOLD;

// Always print the expected and actual size so that it's easier to find culprit
// commits when the size slowly moves toward the threshold boundaries.
console.info(chalk.yellow(`Expected: ${expectedSize}, but got: ${actualSize}`));

if (deviatedByPercentage) {
console.error(`Actual size deviates by more than 1% of the expected size. `);
printApproveCommand();
process.exit(1);
} else if (deviatedByAbsoluteDiff) {
console.error(`Actual size deviates by more than 500 bytes from the expected.`);
printApproveCommand();
process.exit(1);
}

/** Prints the command for approving the current test. */
function printApproveCommand() {
console.info(chalk.yellow('You can approve the golden by running the following command:'));
console.info(chalk.yellow(` bazel run ${process.env.BAZEL_TARGET}.approve`));
}
74 changes: 74 additions & 0 deletions integration/size-test/index.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_binary", "nodejs_test")
load("@npm_bazel_rollup//:index.bzl", "rollup_bundle")
load("@npm_bazel_terser//:index.bzl", "terser_minified")
load("//tools:defaults.bzl", "ng_module")

"""
Performs size measurements for the specified file. The file will be built as part
of a `ng_module` and then will be optimized with build-optimizer, rollup and Terser.

The resulting size will be validated against a golden file to ensure that we don't
regress in payload size, or that we can improvements to payload size.
"""

def size_test(name, file, deps):
# Generates an unique id for the given size test. e.g. if the macro is called
# within the `integration/size-test/material` package with `name = list`, then
# the unique id will be set to `material/list`.
test_id = "%s/%s" % (native.package_name()[len("integration/size-test/"):], name)

ng_module(
name = "%s_lib" % name,
srcs = ["%s.ts" % name],
testonly = True,
deps = [
"@npm//@angular/core",
"@npm//@angular/platform-browser-dynamic",
] + deps,
)

rollup_bundle(
name = "%s_bundle" % name,
config_file = "//integration/size-test:rollup.config.js",
testonly = True,
entry_points = {
(file): "%s_bundled" % name,
},
deps = [
":%s_lib" % name,
"@npm//rollup-plugin-node-resolve",
"@npm//@angular-devkit/build-optimizer",
],
sourcemap = "false",
)

terser_minified(
testonly = True,
name = "%s_bundle_min" % name,
src = ":%s_bundle" % name,
config_file = "//integration/size-test:terser-config.json",
sourcemap = False,
)

nodejs_test(
name = name,
data = [
"//goldens:size-test.json",
"//integration/size-test:check-size",
":%s_bundle_min" % name,
],
entry_point = "//integration/size-test:check-size.ts",
args = [test_id, "$(rootpath :%s_bundle_min)" % name],
)

nodejs_binary(
name = "%s.approve" % name,
testonly = True,
data = [
"//goldens:size-test.json",
"//integration/size-test:check-size",
":%s_bundle_min" % name,
],
entry_point = "//integration/size-test:check-size.ts",
args = [test_id, "$(rootpath :%s_bundle_min)" % name, "true"],
)
7 changes: 7 additions & 0 deletions integration/size-test/material/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
load("//integration/size-test:index.bzl", "size_test")

size_test(
name = "list",
file = "list.ts",
deps = ["//src/material/list"],
)
28 changes: 28 additions & 0 deletions integration/size-test/material/list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import {Component, NgModule} from '@angular/core';
import {platformBrowser} from '@angular/platform-browser';
import {MatListModule} from '@angular/material/list';

/**
* Basic component using `MatNavList` and `MatListItem`. Other parts of the list
* module such as `MatList`, `MatSelectionList` or `MatListOption` are not used
* and should be tree-shaken away.
*/
@Component({
template: `
<mat-nav-list>
<mat-list-item>
hello
</mat-list-item>
</mat-nav-list>
`,
})
export class TestComponent {}

@NgModule({
imports: [MatListModule],
declarations: [TestComponent],
bootstrap: [TestComponent],
})
export class AppModule {}

platformBrowser().bootstrapModule(AppModule);
31 changes: 31 additions & 0 deletions integration/size-test/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const {buildOptimizer} = require('@angular-devkit/build-optimizer');
const node = require('rollup-plugin-node-resolve');

const buildOptimizerPlugin = {
name: 'build-optimizer',
transform: (content, id) => {
const {content: code, sourceMap: map} = buildOptimizer({
content,
inputFilePath: id,
emitSourceMap: true,
isSideEffectFree: true,
isAngularCoreFile: false,
});
if (!code) {
return null;
}
if (!map) {
throw new Error('No sourcemap produced by build optimizer');
}
return {code, map};
},
};

module.exports = {
plugins: [
buildOptimizerPlugin,
node({
mainFields: ['es2015_ivy_ngcc', 'module_ivy_ngcc','es2015', 'module'],
}),
],
};
16 changes: 16 additions & 0 deletions integration/size-test/terser-config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"output": {
"ecma": "es2015",
"comments": false
},
"compress": {
"global_defs": {
"ngDevMode": false,
"ngI18nClosureMode": false,
"ngJitMode": false
},
"passes": 3,
"pure_getters": true
},
"mangle": true
}
7 changes: 7 additions & 0 deletions integration/size-test/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"lib": ["es2015"],
"types": ["node"]
}
}
4 changes: 3 additions & 1 deletion integration/ts-compat/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ typescript_version_packages = [
],
entry_point = "test.js",
tags = [
"integration",
# These tests run in view engine only as the release packages are
# built with View Engine and we want to reproduce this here.
"view-engine-only",
],
)
for ts_pkg_name in typescript_version_packages
Expand Down
15 changes: 9 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@
"ts-circular-deps:check": "yarn -s ts-circular-deps check --config ./src/circular-deps-test.conf.js",
"ts-circular-deps:approve": "yarn -s ts-circular-deps approve --config ./src/circular-deps-test.conf.js",
"merge": "ng-dev pr merge",
"approve-api": "node ./scripts/approve-api-golden.js"
"approve-api": "node ./scripts/approve-api-golden.js",
"integration-tests": "bazel test //integration/... --test_tag_filters=-view-engine-only --build_tests_only",
"integration-tests:view-engine": "bazel test //integration/... --test_tag_filters=view-engine-only --build_tests_only --config=view-engine"
},
"version": "10.0.0-rc.1",
"dependencies": {
Expand Down Expand Up @@ -79,11 +81,12 @@
"@bazel/bazelisk": "^1.4.0",
"@bazel/buildifier": "^2.2.1",
"@bazel/ibazel": "^0.13.0",
"@bazel/jasmine": "^1.6.0",
"@bazel/karma": "^1.6.0",
"@bazel/protractor": "^1.6.0",
"@bazel/terser": "^1.4.1",
"@bazel/typescript": "^1.6.0",
"@bazel/jasmine": "^1.7.0",
"@bazel/karma": "^1.7.0",
"@bazel/protractor": "^1.7.0",
"@bazel/rollup": "^1.7.0",
"@bazel/terser": "^1.7.0",
"@bazel/typescript": "^1.7.0",
"@firebase/app-types": "^0.3.2",
"@octokit/rest": "16.28.7",
"@schematics/angular": "^10.0.0-rc.2",
Expand Down
22 changes: 20 additions & 2 deletions src/material/list/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import {
OnDestroy,
ChangeDetectorRef,
Input,
InjectionToken,
Inject,
} from '@angular/core';
import {
CanDisable,
Expand All @@ -48,6 +50,20 @@ class MatListItemBase {}
const _MatListItemMixinBase: CanDisableRippleCtor & typeof MatListItemBase =
mixinDisableRipple(MatListItemBase);

/**
* Injection token that can be used to inject instances of `MatList`. It serves as
* alternative token to the actual `MatList` class which could cause unnecessary
* retention of the class and its component metadata.
*/
export const MAT_LIST = new InjectionToken<MatList>('MatList');

/**
* Injection token that can be used to inject instances of `MatNavList`. It serves as
* alternative token to the actual `MatNavList` class which could cause unnecessary
* retention of the class and its component metadata.
*/
export const MAT_NAV_LIST = new InjectionToken<MatNavList>('MatNavList');

@Component({
selector: 'mat-nav-list',
exportAs: 'matNavList',
Expand All @@ -60,6 +76,7 @@ const _MatListItemMixinBase: CanDisableRippleCtor & typeof MatListItemBase =
inputs: ['disableRipple', 'disabled'],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [{provide: MAT_NAV_LIST, useExisting: MatNavList}],
})
export class MatNavList extends _MatListMixinBase implements CanDisable, CanDisableRipple,
OnChanges, OnDestroy {
Expand Down Expand Up @@ -89,6 +106,7 @@ export class MatNavList extends _MatListMixinBase implements CanDisable, CanDisa
inputs: ['disableRipple', 'disabled'],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [{provide: MAT_LIST, useExisting: MatList}],
})
export class MatList extends _MatListMixinBase implements CanDisable, CanDisableRipple, OnChanges,
OnDestroy {
Expand Down Expand Up @@ -187,8 +205,8 @@ export class MatListItem extends _MatListItemMixinBase implements AfterContentIn

constructor(private _element: ElementRef<HTMLElement>,
_changeDetectorRef: ChangeDetectorRef,
@Optional() navList?: MatNavList,
@Optional() list?: MatList) {
@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;
Expand Down
Loading