build: add linting for class member naming (#15812)

Currently we have a convention for prefixing private members with an underscore, however there's nothing verifying it. This comes up occasionally in PRs and there some cases that have deviated from the pattern. These changes add a tslint rule that allows us to customize the naming pattern for the various modifiers.
This commit is contained in:
Kristiyan Kostadinov
2019-05-13 06:31:00 +02:00
committed by Jeremy Elbourn
parent 70bc4d56e1
commit 50b9fe2246
61 changed files with 446 additions and 342 deletions
+2 -2
View File
@@ -19,9 +19,9 @@ import {MatSnackBar} from '@angular/material';
export class CardAccessibilityDemo {
showProgress: boolean = false;
constructor(private snackBar: MatSnackBar) {}
constructor(private _snackBar: MatSnackBar) {}
openSnackbar(message: string) {
this.snackBar.open(message, '', {duration: 2000});
this._snackBar.open(message, '', {duration: 2000});
}
}
+2 -2
View File
@@ -16,9 +16,9 @@ import {MatSnackBar} from '@angular/material';
templateUrl: 'icon-a11y.html',
})
export class IconAccessibilityDemo {
constructor(private snackBar: MatSnackBar) {}
constructor(private _snackBar: MatSnackBar) {}
deleteIcon() {
this.snackBar.open('Item deleted', '', {duration: 2000});
this._snackBar.open('Item deleted', '', {duration: 2000});
}
}
@@ -20,9 +20,9 @@ export class SlideToggleAccessibilityDemo {
termsToggle = false;
musicToggle = false;
constructor(private snackBar: MatSnackBar) {}
constructor(private _snackBar: MatSnackBar) {}
onFormSubmit() {
this.snackBar.open('Terms and condistions accepted!', '', {duration: 2000});
this._snackBar.open('Terms and condistions accepted!', '', {duration: 2000});
}
}
+3 -3
View File
@@ -16,13 +16,13 @@ import {MatSnackBar} from '@angular/material';
templateUrl: 'snack-bar-a11y.html',
})
export class SnackBarAccessibilityDemo {
constructor(private snackBar: MatSnackBar) {}
constructor(private _snackBar: MatSnackBar) {}
openDiscoPartySnackBar() {
this.snackBar.open('Disco party!', 'Dismiss', {duration: 5000});
this._snackBar.open('Disco party!', 'Dismiss', {duration: 5000});
}
openNotificationSnackBar() {
this.snackBar.open('Thank you for your support!', '', {duration: 2000});
this._snackBar.open('Thank you for your support!', '', {duration: 2000});
}
}
+16 -16
View File
@@ -72,9 +72,9 @@ export class Dialog implements OnDestroy {
_openDialogs: DialogRef<any>[] = [];
constructor(
private overlay: Overlay,
private injector: Injector,
@Inject(DIALOG_REF) private dialogRefConstructor: Type<DialogRef<any>>,
private _overlay: Overlay,
private _injector: Injector,
@Inject(DIALOG_REF) private _dialogRefConstructor: Type<DialogRef<any>>,
// TODO(crisbeto): the `any` here can be replaced
// with the proper type once we start using Ivy.
@Inject(DIALOG_SCROLL_STRATEGY) scrollStrategy: any,
@@ -114,7 +114,7 @@ export class Dialog implements OnDestroy {
const dialogRef = this._attachDialogContentForComponent(component, dialogContainer,
overlayRef, config);
this.registerDialogRef(dialogRef);
this._registerDialogRef(dialogRef);
return dialogRef;
}
@@ -131,7 +131,7 @@ export class Dialog implements OnDestroy {
const dialogRef = this._attachDialogContentForTemplate(template, dialogContainer,
overlayRef, config);
this.registerDialogRef(dialogRef);
this._registerDialogRef(dialogRef);
return dialogRef;
}
@@ -143,7 +143,7 @@ export class Dialog implements OnDestroy {
/**
* Forwards emitting events for when dialogs are opened and all dialogs are closed.
*/
private registerDialogRef(dialogRef: DialogRef<any>): void {
private _registerDialogRef(dialogRef: DialogRef<any>): void {
this.openDialogs.push(dialogRef);
const dialogOpenSub = dialogRef.afterOpened().subscribe(() => {
@@ -172,7 +172,7 @@ export class Dialog implements OnDestroy {
*/
protected _createOverlay(config: DialogConfig): OverlayRef {
const overlayConfig = new OverlayConfig({
positionStrategy: this.overlay.position().global(),
positionStrategy: this._overlay.position().global(),
scrollStrategy: this._scrollStrategy(),
panelClass: config.panelClass,
hasBackdrop: config.hasBackdrop,
@@ -186,7 +186,7 @@ export class Dialog implements OnDestroy {
if (config.backdropClass) {
overlayConfig.backdropClass = config.backdropClass;
}
return this.overlay.create(overlayConfig);
return this._overlay.create(overlayConfig);
}
/**
@@ -196,9 +196,9 @@ export class Dialog implements OnDestroy {
* @returns A promise resolving to a ComponentRef for the attached container.
*/
protected _attachDialogContainer(overlay: OverlayRef, config: DialogConfig): CdkDialogContainer {
const container = config.containerComponent || this.injector.get(DIALOG_CONTAINER);
const container = config.containerComponent || this._injector.get(DIALOG_CONTAINER);
const userInjector = config && config.viewContainerRef && config.viewContainerRef.injector;
const injector = new PortalInjector(userInjector || this.injector, new WeakMap([
const injector = new PortalInjector(userInjector || this._injector, new WeakMap([
[DialogConfig, config]
]));
const containerPortal = new ComponentPortal(container, config.viewContainerRef, injector);
@@ -226,7 +226,7 @@ export class Dialog implements OnDestroy {
// Create a reference to the dialog we're creating in order to give the user a handle
// to modify and close it.
const dialogRef = new this.dialogRefConstructor(overlayRef, dialogContainer, config.id);
const dialogRef = new this._dialogRefConstructor(overlayRef, dialogContainer, config.id);
const injector = this._createInjector<T>(config, dialogRef, dialogContainer);
const contentRef = dialogContainer.attachComponentPortal(
new ComponentPortal(componentOrTemplateRef, undefined, injector));
@@ -257,7 +257,7 @@ export class Dialog implements OnDestroy {
// Create a reference to the dialog we're creating in order to give the user a handle
// to modify and close it.
const dialogRef = new this.dialogRefConstructor(overlayRef, dialogContainer, config.id);
const dialogRef = new this._dialogRefConstructor(overlayRef, dialogContainer, config.id);
dialogContainer.attachTemplatePortal(
new TemplatePortal<T>(componentOrTemplateRef, null!,
@@ -284,8 +284,8 @@ export class Dialog implements OnDestroy {
const userInjector = config && config.viewContainerRef && config.viewContainerRef.injector;
const injectionTokens = new WeakMap<any, any>([
[this.injector.get(DIALOG_REF), dialogRef],
[this.injector.get(DIALOG_CONTAINER), dialogContainer],
[this._injector.get(DIALOG_REF), dialogRef],
[this._injector.get(DIALOG_CONTAINER), dialogContainer],
[DIALOG_DATA, config.data]
]);
@@ -297,7 +297,7 @@ export class Dialog implements OnDestroy {
});
}
return new PortalInjector(userInjector || this.injector, injectionTokens);
return new PortalInjector(userInjector || this._injector, injectionTokens);
}
/**
@@ -305,7 +305,7 @@ export class Dialog implements OnDestroy {
* are undefined.
*/
private _applyConfigDefaults(config?: DialogConfig): DialogConfig {
const dialogConfig = this.injector.get(DIALOG_CONFIG) as typeof DialogConfig;
const dialogConfig = this._injector.get(DIALOG_CONFIG) as typeof DialogConfig;
return {...new dialogConfig(), ...config};
}
}
+6 -6
View File
@@ -193,29 +193,29 @@ export class FakeMediaQueryList {
@Injectable()
export class FakeMediaMatcher {
/** A map of match media queries. */
private queries = new Map<string, FakeMediaQueryList>();
private _queries = new Map<string, FakeMediaQueryList>();
/** The number of distinct queries created in the media matcher during a test. */
get queryCount(): number {
return this.queries.size;
return this._queries.size;
}
/** Fakes the match media response to be controlled in tests. */
matchMedia(query: string): FakeMediaQueryList {
const mql = new FakeMediaQueryList(true, query);
this.queries.set(query, mql);
this._queries.set(query, mql);
return mql;
}
/** Clears all queries from the map of queries. */
clear() {
this.queries.clear();
this._queries.clear();
}
/** Toggles the matching state of the provided query. */
setMatchesQuery(query: string, matches: boolean) {
if (this.queries.has(query)) {
this.queries.get(query)!.setMatches(matches);
if (this._queries.has(query)) {
this._queries.get(query)!.setMatches(matches);
} else {
throw Error('This query is not being observed.');
}
+3 -3
View File
@@ -47,7 +47,7 @@ export class BreakpointObserver implements OnDestroy {
/** A subject for all other observables to takeUntil based on. */
private _destroySubject = new Subject<void>();
constructor(private mediaMatcher: MediaMatcher, private zone: NgZone) {}
constructor(private _mediaMatcher: MediaMatcher, private _zone: NgZone) {}
/** Completes the active subject, signalling to all other observables to complete. */
ngOnDestroy() {
@@ -97,7 +97,7 @@ export class BreakpointObserver implements OnDestroy {
return this._queries.get(query)!;
}
const mql: MediaQueryList = this.mediaMatcher.matchMedia(query);
const mql: MediaQueryList = this._mediaMatcher.matchMedia(query);
// Create callback for match changes and add it is as a listener.
const queryObservable = new Observable<MediaQueryList>((observer: Observer<MediaQueryList>) => {
@@ -106,7 +106,7 @@ export class BreakpointObserver implements OnDestroy {
// webapis-media-query.js file alongside the zone.js file. Additionally, some browsers do not
// have MediaQueryList inherit from EventTarget, which causes inconsistencies in how Zone.js
// patches it.
const handler = (e: any) => this.zone.run(() => observer.next(e));
const handler = (e: any) => this._zone.run(() => observer.next(e));
mql.addListener(handler);
return () => {
+3 -3
View File
@@ -20,8 +20,8 @@ export class MediaMatcher {
/** The internal matchMedia method to return back a MediaQueryList like object. */
private _matchMedia: (query: string) => MediaQueryList;
constructor(private platform: Platform) {
this._matchMedia = this.platform.isBrowser && window.matchMedia ?
constructor(private _platform: Platform) {
this._matchMedia = this._platform.isBrowser && window.matchMedia ?
// matchMedia is bound to the window scope intentionally as it is an illegal invocation to
// call it from a different scope.
window.matchMedia.bind(window) :
@@ -35,7 +35,7 @@ export class MediaMatcher {
* MediaQueryList for the query provided.
*/
matchMedia(query: string): MediaQueryList {
if (this.platform.WEBKIT) {
if (this._platform.WEBKIT) {
createEmptyStyleRule(query);
}
return this._matchMedia(query);
@@ -77,7 +77,7 @@ export class FlexibleConnectedPositionStrategy implements PositionStrategy {
private _viewportMargin = 0;
/** The Scrollable containers used to check scrollable view properties on position change. */
private scrollables: CdkScrollable[] = [];
private _scrollables: CdkScrollable[] = [];
/** Ordered list of preferred positions, from most to least desirable. */
_preferredPositions: ConnectionPositionPair[] = [];
@@ -366,7 +366,7 @@ export class FlexibleConnectedPositionStrategy implements PositionStrategy {
* Scrollable must be an ancestor element of the strategy's origin element.
*/
withScrollableContainers(scrollables: CdkScrollable[]): this {
this.scrollables = scrollables;
this._scrollables = scrollables;
return this;
}
@@ -994,7 +994,7 @@ export class FlexibleConnectedPositionStrategy implements PositionStrategy {
// TODO(jelbourn): instead of needing all of the client rects for these scrolling containers
// every time, we should be able to use the scrollTop of the containers if the size of those
// containers hasn't changed.
const scrollContainerBounds = this.scrollables.map(scrollable => {
const scrollContainerBounds = this._scrollables.map(scrollable => {
return scrollable.getElementRef().nativeElement.getBoundingClientRect();
});
+8 -8
View File
@@ -26,16 +26,16 @@ export const STICKY_DIRECTIONS: StickyDirection[] = ['top', 'bottom', 'left', 'r
*/
export class StickyStyler {
/**
* @param isNativeHtmlTable Whether the sticky logic should be based on a table
* @param _isNativeHtmlTable Whether the sticky logic should be based on a table
* that uses the native `<table>` element.
* @param stickCellCss The CSS class that will be applied to every row/cell that has
* @param _stickCellCss The CSS class that will be applied to every row/cell that has
* sticky positioning applied.
* @param direction The directionality context of the table (ltr/rtl); affects column positioning
* by reversing left/right positions.
* @param _isBrowser Whether the table is currently being rendered on the server or the client.
*/
constructor(private isNativeHtmlTable: boolean,
private stickCellCss: string,
constructor(private _isNativeHtmlTable: boolean,
private _stickCellCss: string,
public direction: Direction,
private _isBrowser = true) { }
@@ -129,7 +129,7 @@ export class StickyStyler {
}
const row = rows[rowIndex];
if (this.isNativeHtmlTable) {
if (this._isNativeHtmlTable) {
for (let j = 0; j < row.children.length; j++) {
const cell = row.children[j] as HTMLElement;
this._addStickyStyle(cell, position, stickyHeight);
@@ -155,7 +155,7 @@ export class StickyStyler {
* the tfoot element.
*/
updateStickyFooterContainer(tableElement: Element, stickyStates: boolean[]) {
if (!this.isNativeHtmlTable) {
if (!this._isNativeHtmlTable) {
return;
}
@@ -183,7 +183,7 @@ export class StickyStyler {
const hasDirection = STICKY_DIRECTIONS.some(dir => !!element.style[dir]);
if (!hasDirection) {
element.style.position = '';
element.classList.remove(this.stickCellCss);
element.classList.remove(this._stickCellCss);
}
}
@@ -193,7 +193,7 @@ export class StickyStyler {
* direction and value.
*/
_addStickyStyle(element: HTMLElement, dir: StickyDirection, dirValue: number) {
element.classList.add(this.stickCellCss);
element.classList.add(this._stickCellCss);
element.style[dir] = `${dirValue}px`;
element.style.cssText += 'position: -webkit-sticky; position: sticky; ';
element.style.zIndex = this._getCalculatedZIndex(element);
+10 -10
View File
@@ -121,9 +121,9 @@ export class CdkTextColumn<T> implements OnDestroy, OnInit {
@ViewChild(CdkHeaderCellDef, {static: true}) headerCell: CdkHeaderCellDef;
constructor(
@Optional() private table: CdkTable<T>,
@Optional() @Inject(TEXT_COLUMN_OPTIONS) private options: TextColumnOptions<T>) {
this.options = options || {};
@Optional() private _table: CdkTable<T>,
@Optional() @Inject(TEXT_COLUMN_OPTIONS) private _options: TextColumnOptions<T>) {
this._options = _options || {};
}
ngOnInit() {
@@ -133,24 +133,24 @@ export class CdkTextColumn<T> implements OnDestroy, OnInit {
if (!this.dataAccessor) {
this.dataAccessor =
this.options.defaultDataAccessor || ((data: T, name: string) => (data as any)[name]);
this._options.defaultDataAccessor || ((data: T, name: string) => (data as any)[name]);
}
if (this.table) {
if (this._table) {
// Provide the cell and headerCell directly to the table with the static `ViewChild` query,
// since the columnDef will not pick up its content by the time the table finishes checking
// its content and initializing the rows.
this.columnDef.cell = this.cell;
this.columnDef.headerCell = this.headerCell;
this.table.addColumnDef(this.columnDef);
this._table.addColumnDef(this.columnDef);
} else {
throw getTableTextColumnMissingParentTableError();
}
}
ngOnDestroy() {
if (this.table) {
this.table.removeColumnDef(this.columnDef);
if (this._table) {
this._table.removeColumnDef(this.columnDef);
}
}
@@ -159,8 +159,8 @@ export class CdkTextColumn<T> implements OnDestroy, OnInit {
* has been provided. Otherwise simply capitalize the column name.
*/
_createDefaultHeaderText() {
if (this.options && this.options.defaultHeaderTextTransform) {
return this.options.defaultHeaderTextTransform(this.name);
if (this._options && this._options.defaultHeaderTextTransform) {
return this._options.defaultHeaderTextTransform(this.name);
}
return this.name[0].toUpperCase() + this.name.slice(1);
@@ -55,10 +55,10 @@ export class BottomSheetDemo {
`
})
export class ExampleBottomSheet {
constructor(private sheet: MatBottomSheetRef) {}
constructor(private _bottomSheet: MatBottomSheetRef) {}
handleClick(event: MouseEvent) {
event.preventDefault();
this.sheet.dismiss();
this._bottomSheet.dismiss();
}
}
@@ -16,9 +16,9 @@ import {LiveAnnouncer} from '@angular/cdk/a11y';
templateUrl: 'live-announcer-demo.html',
})
export class LiveAnnouncerDemo {
constructor(private live: LiveAnnouncer) {}
constructor(private _liveAnnouncer: LiveAnnouncer) {}
announceText(message: string) {
this.live.announce(message);
this._liveAnnouncer.announce(message);
}
}
@@ -26,18 +26,18 @@ export class ProgressBarDemo {
bufferBufferValue: number = 40;
stepDeterminateProgressVal(val: number) {
this.determinateProgressValue = this.clampValue(val + this.determinateProgressValue);
this.determinateProgressValue = this._clampValue(val + this.determinateProgressValue);
}
stepBufferProgressVal(val: number) {
this.bufferProgressValue = this.clampValue(val + this.bufferProgressValue);
this.bufferProgressValue = this._clampValue(val + this.bufferProgressValue);
}
stepBufferBufferVal(val: number) {
this.bufferBufferValue = this.clampValue(val + this.bufferBufferValue);
this.bufferBufferValue = this._clampValue(val + this.bufferBufferValue);
}
private clampValue(value: number) {
private _clampValue(value: number) {
return Math.max(0, Math.min(100, value));
}
}
+6 -6
View File
@@ -24,13 +24,13 @@ export class ScreenTypeDemo {
isPortrait: Observable<BreakpointState>;
isLandscape: Observable<BreakpointState>;
constructor(private breakpointObserver: BreakpointObserver) {
this.isHandset = this.breakpointObserver.observe([Breakpoints.HandsetLandscape,
constructor(breakpointObserver: BreakpointObserver) {
this.isHandset = breakpointObserver.observe([Breakpoints.HandsetLandscape,
Breakpoints.HandsetPortrait]);
this.isTablet = this.breakpointObserver.observe(Breakpoints.Tablet);
this.isWeb = this.breakpointObserver.observe([Breakpoints.WebLandscape,
this.isTablet = breakpointObserver.observe(Breakpoints.Tablet);
this.isWeb = breakpointObserver.observe([Breakpoints.WebLandscape,
Breakpoints.WebPortrait]);
this.isPortrait = this.breakpointObserver.observe('(orientation: portrait)');
this.isLandscape = this.breakpointObserver.observe('(orientation: landscape)');
this.isPortrait = breakpointObserver.observe('(orientation: portrait)');
this.isLandscape = breakpointObserver.observe('(orientation: landscape)');
}
}
+2 -2
View File
@@ -33,7 +33,7 @@ export class SnackBarDemo {
horizontalPosition: MatSnackBarHorizontalPosition = 'center';
verticalPosition: MatSnackBarVerticalPosition = 'bottom';
constructor(public snackBar: MatSnackBar, private dir: Directionality) {}
constructor(public snackBar: MatSnackBar, private _dir: Directionality) {}
open() {
const config = this._createConfig();
@@ -51,7 +51,7 @@ export class SnackBarDemo {
config.horizontalPosition = this.horizontalPosition;
config.duration = this.setAutoHide ? this.autoHide : 0;
config.panelClass = this.addExtraClass ? ['demo-party'] : undefined;
config.direction = this.dir.value;
config.direction = this._dir.value;
return config;
}
}
@@ -31,9 +31,9 @@ export class ChecklistNestedTreeDemo {
/** The selection for checklist */
checklistSelection = new SelectionModel<TodoItemNode>(true /* multiple */);
constructor(private database: ChecklistDatabase, private changeDetectorRef: ChangeDetectorRef) {
constructor(private _database: ChecklistDatabase, private _changeDetectorRef: ChangeDetectorRef) {
this.treeControl = new NestedTreeControl<TodoItemNode>(this.getChildren);
this.dataSource = database.data;
this.dataSource = _database.data;
}
getChildren = (node: TodoItemNode): Observable<TodoItemNode[]> => node.children;
@@ -50,7 +50,7 @@ export class ChecklistNestedTreeDemo {
const allSelected = descendants.every(child => this.checklistSelection.isSelected(child));
if (!selected && allSelected) {
this.checklistSelection.select(node);
this.changeDetectorRef.markForCheck();
this._changeDetectorRef.markForCheck();
}
return allSelected;
}
@@ -72,17 +72,17 @@ export class ChecklistNestedTreeDemo {
this.checklistSelection.isSelected(node)
? this.checklistSelection.select(...descendants, node)
: this.checklistSelection.deselect(...descendants, node);
this.changeDetectorRef.markForCheck();
this._changeDetectorRef.markForCheck();
}
/** Select the category so we can insert the new item. */
addNewItem(node: TodoItemNode) {
this.database.insertItem(node, '');
this._database.insertItem(node, '');
this.treeControl.expand(node);
}
/** Save the node to database */
saveNode(node: TodoItemNode, itemValue: string) {
this.database.updateItem(node, itemValue);
this._database.updateItem(node, itemValue);
}
}
@@ -35,14 +35,14 @@ export class ChecklistTreeDemo {
/** The selection for checklist */
checklistSelection = new SelectionModel<TodoItemNode>(true /* multiple */);
constructor(private database: ChecklistDatabase, private changeDetectorRef: ChangeDetectorRef) {
constructor(private _database: ChecklistDatabase, private _changeDetectorRef: ChangeDetectorRef) {
this.treeFlattener = new MatTreeFlattener(this.transformer, this.getLevel,
this.isExpandable, this.getChildren);
this.treeControl = new FlatTreeControl<TodoItemNode>(
this.getLevel, this.isExpandable);
this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
database.dataChange.subscribe(data => this.dataSource.data = data);
_database.dataChange.subscribe(data => this.dataSource.data = data);
}
getLevel = (node: TodoItemNode): number => {
@@ -74,7 +74,7 @@ export class ChecklistTreeDemo {
const allSelected = descendants.every(child => this.checklistSelection.isSelected(child));
if (!selected && allSelected) {
this.checklistSelection.select(node);
this.changeDetectorRef.markForCheck();
this._changeDetectorRef.markForCheck();
}
return allSelected;
}
@@ -96,17 +96,17 @@ export class ChecklistTreeDemo {
this.checklistSelection.isSelected(node)
? this.checklistSelection.select(...descendants, node)
: this.checklistSelection.deselect(...descendants, node);
this.changeDetectorRef.markForCheck();
this._changeDetectorRef.markForCheck();
}
/** Select the category so we can insert the new item. */
addNewItem(node: TodoItemNode) {
this.database.insertItem(node, '');
this._database.insertItem(node, '');
this.treeControl.expand(node);
}
/** Save the node to database */
saveNode(node: TodoItemNode, itemValue: string) {
this.database.updateItem(node, itemValue);
this._database.updateItem(node, itemValue);
}
}
@@ -60,15 +60,15 @@ export class DynamicDataSource {
get data(): DynamicFlatNode[] { return this.dataChange.value; }
set data(value: DynamicFlatNode[]) {
this.treeControl.dataNodes = value;
this._treeControl.dataNodes = value;
this.dataChange.next(value);
}
constructor(private treeControl: FlatTreeControl<DynamicFlatNode>,
private database: DynamicDatabase) {}
constructor(private _treeControl: FlatTreeControl<DynamicFlatNode>,
private _database: DynamicDatabase) {}
connect(collectionViewer: CollectionViewer): Observable<DynamicFlatNode[]> {
this.treeControl.expansionModel.onChange.subscribe(change => {
this._treeControl.expansionModel.onChange.subscribe(change => {
if (change.added || change.removed) {
this.handleTreeControl(change);
}
@@ -92,7 +92,7 @@ export class DynamicDataSource {
* Toggle the node, remove from display list
*/
toggleNode(node: DynamicFlatNode, expand: boolean) {
const children = this.database.getChildren(node.item);
const children = this._database.getChildren(node.item);
const index = this.data.indexOf(node);
if (!children || index < 0) { // If no children, or cannot find the node, no op
return;
@@ -102,7 +102,7 @@ export class DynamicDataSource {
setTimeout(() => {
if (expand) {
const nodes = children.map(name =>
new DynamicFlatNode(name, node.level + 1, this.database.isExpandable(name)));
new DynamicFlatNode(name, node.level + 1, this._database.isExpandable(name)));
this.data.splice(index + 1, 0, ...nodes);
} else {
let count = 0;
@@ -37,7 +37,7 @@ export class LoadmoreTreeDemo {
// Flat tree data source
dataSource: MatTreeFlatDataSource<LoadmoreNode, LoadmoreFlatNode>;
constructor(private database: LoadmoreDatabase) {
constructor(private _database: LoadmoreDatabase) {
this.treeFlattener = new MatTreeFlattener(this.transformer, this.getLevel,
this.isExpandable, this.getChildren);
@@ -45,11 +45,11 @@ export class LoadmoreTreeDemo {
this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
database.dataChange.subscribe(data => {
_database.dataChange.subscribe(data => {
this.dataSource.data = data;
});
database.initialize();
_database.initialize();
}
getChildren = (node: LoadmoreNode): Observable<LoadmoreNode[]> => { return node.childrenChange; };
@@ -74,10 +74,10 @@ export class LoadmoreTreeDemo {
/** Load more nodes from data source */
loadMore(item: string) {
this.database.loadMore(item);
this._database.loadMore(item);
}
loadChildren(node: LoadmoreFlatNode) {
this.database.loadMore(node.item, true);
this._database.loadMore(node.item, true);
}
}
@@ -24,7 +24,7 @@ export const _filter = (opt: string[], value: string): string[] => {
})
export class AutocompleteOptgroupExample implements OnInit {
stateForm: FormGroup = this.fb.group({
stateForm: FormGroup = this._formBuilder.group({
stateGroup: '',
});
@@ -91,7 +91,7 @@ export class AutocompleteOptgroupExample implements OnInit {
stateGroupOptions: Observable<StateGroup[]>;
constructor(private fb: FormBuilder) {}
constructor(private _formBuilder: FormBuilder) {}
ngOnInit() {
this.stateGroupOptions = this.stateForm.get('stateGroup')!.valueChanges
@@ -10,10 +10,10 @@ import {MatBottomSheet, MatBottomSheetRef} from '@angular/material/bottom-sheet'
styleUrls: ['bottom-sheet-overview-example.css'],
})
export class BottomSheetOverviewExample {
constructor(private bottomSheet: MatBottomSheet) {}
constructor(private _bottomSheet: MatBottomSheet) {}
openBottomSheet(): void {
this.bottomSheet.open(BottomSheetOverviewExampleSheet);
this._bottomSheet.open(BottomSheetOverviewExampleSheet);
}
}
@@ -22,10 +22,10 @@ export class BottomSheetOverviewExample {
templateUrl: 'bottom-sheet-overview-example-sheet.html',
})
export class BottomSheetOverviewExampleSheet {
constructor(private bottomSheetRef: MatBottomSheetRef<BottomSheetOverviewExampleSheet>) {}
constructor(private _bottomSheetRef: MatBottomSheetRef<BottomSheetOverviewExampleSheet>) {}
openLink(event: MouseEvent): void {
this.bottomSheetRef.dismiss();
this._bottomSheetRef.dismiss();
event.preventDefault();
}
}
@@ -14,44 +14,44 @@ export class CdkVirtualScrollDataSourceExample {
}
export class MyDataSource extends DataSource<string | undefined> {
private length = 100000;
private pageSize = 100;
private cachedData = Array.from<string>({length: this.length});
private fetchedPages = new Set<number>();
private dataStream = new BehaviorSubject<(string | undefined)[]>(this.cachedData);
private subscription = new Subscription();
private _length = 100000;
private _pageSize = 100;
private _cachedData = Array.from<string>({length: this._length});
private _fetchedPages = new Set<number>();
private _dataStream = new BehaviorSubject<(string | undefined)[]>(this._cachedData);
private _subscription = new Subscription();
connect(collectionViewer: CollectionViewer): Observable<(string | undefined)[]> {
this.subscription.add(collectionViewer.viewChange.subscribe(range => {
const startPage = this.getPageForIndex(range.start);
const endPage = this.getPageForIndex(range.end - 1);
this._subscription.add(collectionViewer.viewChange.subscribe(range => {
const startPage = this._getPageForIndex(range.start);
const endPage = this._getPageForIndex(range.end - 1);
for (let i = startPage; i <= endPage; i++) {
this.fetchPage(i);
this._fetchPage(i);
}
}));
return this.dataStream;
return this._dataStream;
}
disconnect(): void {
this.subscription.unsubscribe();
this._subscription.unsubscribe();
}
private getPageForIndex(index: number): number {
return Math.floor(index / this.pageSize);
private _getPageForIndex(index: number): number {
return Math.floor(index / this._pageSize);
}
private fetchPage(page: number) {
if (this.fetchedPages.has(page)) {
private _fetchPage(page: number) {
if (this._fetchedPages.has(page)) {
return;
}
this.fetchedPages.add(page);
this._fetchedPages.add(page);
// Use `setTimeout` to simulate fetching data from server.
setTimeout(() => {
this.cachedData.splice(page * this.pageSize, this.pageSize,
...Array.from({length: this.pageSize})
.map((_, i) => `Item #${page * this.pageSize + i}`));
this.dataStream.next(this.cachedData);
this._cachedData.splice(page * this._pageSize, this._pageSize,
...Array.from({length: this._pageSize})
.map((_, i) => `Item #${page * this._pageSize + i}`));
this._dataStream.next(this._cachedData);
}, Math.random() * 1000 + 200);
}
}
@@ -63,36 +63,36 @@ export class DatepickerCustomHeaderExample {
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ExampleHeader<D> implements OnDestroy {
private destroyed = new Subject<void>();
private _destroyed = new Subject<void>();
constructor(
private calendar: MatCalendar<D>, private dateAdapter: DateAdapter<D>,
@Inject(MAT_DATE_FORMATS) private dateFormats: MatDateFormats, cdr: ChangeDetectorRef) {
calendar.stateChanges
.pipe(takeUntil(this.destroyed))
private _calendar: MatCalendar<D>, private _dateAdapter: DateAdapter<D>,
@Inject(MAT_DATE_FORMATS) private _dateFormats: MatDateFormats, cdr: ChangeDetectorRef) {
_calendar.stateChanges
.pipe(takeUntil(this._destroyed))
.subscribe(() => cdr.markForCheck());
}
ngOnDestroy() {
this.destroyed.next();
this.destroyed.complete();
this._destroyed.next();
this._destroyed.complete();
}
get periodLabel() {
return this.dateAdapter
.format(this.calendar.activeDate, this.dateFormats.display.monthYearLabel)
return this._dateAdapter
.format(this._calendar.activeDate, this._dateFormats.display.monthYearLabel)
.toLocaleUpperCase();
}
previousClicked(mode: 'month' | 'year') {
this.calendar.activeDate = mode === 'month' ?
this.dateAdapter.addCalendarMonths(this.calendar.activeDate, -1) :
this.dateAdapter.addCalendarYears(this.calendar.activeDate, -1);
this._calendar.activeDate = mode === 'month' ?
this._dateAdapter.addCalendarMonths(this._calendar.activeDate, -1) :
this._dateAdapter.addCalendarYears(this._calendar.activeDate, -1);
}
nextClicked(mode: 'month' | 'year') {
this.calendar.activeDate = mode === 'month' ?
this.dateAdapter.addCalendarMonths(this.calendar.activeDate, 1) :
this.dateAdapter.addCalendarYears(this.calendar.activeDate, 1);
this._calendar.activeDate = mode === 'month' ?
this._dateAdapter.addCalendarMonths(this._calendar.activeDate, 1) :
this._dateAdapter.addCalendarYears(this._calendar.activeDate, 1);
}
}
@@ -20,9 +20,9 @@ import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/
],
})
export class DatepickerLocaleExample {
constructor(private adapter: DateAdapter<any>) {}
constructor(private _adapter: DateAdapter<any>) {}
french() {
this.adapter.setLocale('fr');
this._adapter.setLocale('fr');
}
}
@@ -11,7 +11,7 @@ export class FocusMonitorDirectivesExample {
elementOrigin = this.formatOrigin(null);
subtreeOrigin = this.formatOrigin(null);
constructor(private ngZone: NgZone, private cdr: ChangeDetectorRef) {}
constructor(private _ngZone: NgZone, private _cdr: ChangeDetectorRef) {}
formatOrigin(origin: FocusOrigin): string {
@@ -20,6 +20,6 @@ export class FocusMonitorDirectivesExample {
// Workaround for the fact that (cdkFocusChange) emits outside NgZone.
markForCheck() {
this.ngZone.run(() => this.cdr.markForCheck());
this._ngZone.run(() => this._cdr.markForCheck());
}
}
@@ -21,14 +21,14 @@ export class FocusMonitorFocusViaExample implements OnDestroy, AfterViewInit {
origin = this.formatOrigin(null);
constructor(public focusMonitor: FocusMonitor,
private cdr: ChangeDetectorRef,
private ngZone: NgZone) {}
private _cdr: ChangeDetectorRef,
private _ngZone: NgZone) {}
ngAfterViewInit() {
this.focusMonitor.monitor(this.monitoredEl)
.subscribe(origin => this.ngZone.run(() => {
.subscribe(origin => this._ngZone.run(() => {
this.origin = this.formatOrigin(origin);
this.cdr.markForCheck();
this._cdr.markForCheck();
}));
}
@@ -22,26 +22,26 @@ export class FocusMonitorOverviewExample implements OnDestroy, AfterViewInit {
elementOrigin = this.formatOrigin(null);
subtreeOrigin = this.formatOrigin(null);
constructor(private focusMonitor: FocusMonitor,
private cdr: ChangeDetectorRef,
private ngZone: NgZone) {}
constructor(private _focusMonitor: FocusMonitor,
private _cdr: ChangeDetectorRef,
private _ngZone: NgZone) {}
ngAfterViewInit() {
this.focusMonitor.monitor(this.element)
.subscribe(origin => this.ngZone.run(() => {
this._focusMonitor.monitor(this.element)
.subscribe(origin => this._ngZone.run(() => {
this.elementOrigin = this.formatOrigin(origin);
this.cdr.markForCheck();
this._cdr.markForCheck();
}));
this.focusMonitor.monitor(this.subtree, true)
.subscribe(origin => this.ngZone.run(() => {
this._focusMonitor.monitor(this.subtree, true)
.subscribe(origin => this._ngZone.run(() => {
this.subtreeOrigin = this.formatOrigin(origin);
this.cdr.markForCheck();
this._cdr.markForCheck();
}));
}
ngOnDestroy() {
this.focusMonitor.stopMonitoring(this.element);
this.focusMonitor.stopMonitoring(this.subtree);
this._focusMonitor.stopMonitoring(this.element);
this._focusMonitor.stopMonitoring(this.subtree);
}
formatOrigin(origin: FocusOrigin): string {
@@ -91,18 +91,18 @@ export class MyTelInput implements ControlValueAccessor, MatFormFieldControl<MyT
}
constructor(
fb: FormBuilder,
private fm: FocusMonitor,
private elRef: ElementRef<HTMLElement>,
formBuilder: FormBuilder,
private _focusMonitor: FocusMonitor,
private _elementRef: ElementRef<HTMLElement>,
@Optional() @Self() public ngControl: NgControl) {
this.parts = fb.group({
this.parts = formBuilder.group({
area: '',
exchange: '',
subscriber: '',
});
fm.monitor(elRef, true).subscribe(origin => {
_focusMonitor.monitor(_elementRef, true).subscribe(origin => {
if (this.focused && !origin) {
this.onTouched();
}
@@ -117,7 +117,7 @@ export class MyTelInput implements ControlValueAccessor, MatFormFieldControl<MyT
ngOnDestroy() {
this.stateChanges.complete();
this.fm.stopMonitoring(this.elRef);
this._focusMonitor.stopMonitoring(this._elementRef);
}
setDescribedByIds(ids: string[]) {
@@ -126,7 +126,7 @@ export class MyTelInput implements ControlValueAccessor, MatFormFieldControl<MyT
onContainerClick(event: MouseEvent) {
if ((event.target as Element).tagName.toLowerCase() != 'input') {
this.elRef.nativeElement.querySelector('input')!.focus();
this._elementRef.nativeElement.querySelector('input')!.focus();
}
}
@@ -12,10 +12,10 @@ import {MatSnackBar} from '@angular/material/snack-bar';
export class SnackBarComponentExample {
durationInSeconds = 5;
constructor(private snackBar: MatSnackBar) {}
constructor(private _snackBar: MatSnackBar) {}
openSnackBar() {
this.snackBar.openFromComponent(PizzaPartyComponent, {
this._snackBar.openFromComponent(PizzaPartyComponent, {
duration: this.durationInSeconds * 1000,
});
}
@@ -10,10 +10,10 @@ import {MatSnackBar} from '@angular/material/snack-bar';
styleUrls: ['snack-bar-overview-example.css'],
})
export class SnackBarOverviewExample {
constructor(private snackBar: MatSnackBar) {}
constructor(private _snackBar: MatSnackBar) {}
openSnackBar(message: string, action: string) {
this.snackBar.open(message, action, {
this._snackBar.open(message, action, {
duration: 2000,
});
}
@@ -18,10 +18,10 @@ export class SnackBarPositionExample {
horizontalPosition: MatSnackBarHorizontalPosition = 'start';
verticalPosition: MatSnackBarVerticalPosition = 'bottom';
constructor(private snackBar: MatSnackBar) {}
constructor(private _snackBar: MatSnackBar) {}
openSnackBar() {
this.snackBar.open('Canonball!!', 'End now', {
this._snackBar.open('Canonball!!', 'End now', {
duration: 500,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
@@ -25,10 +25,10 @@ export class TableHttpExample implements AfterViewInit {
@ViewChild(MatPaginator, {static: false}) paginator: MatPaginator;
@ViewChild(MatSort, {static: false}) sort: MatSort;
constructor(private http: HttpClient) {}
constructor(private _httpClient: HttpClient) {}
ngAfterViewInit() {
this.exampleDatabase = new ExampleHttpDatabase(this.http);
this.exampleDatabase = new ExampleHttpDatabase(this._httpClient);
// If the user changes the sort order, reset back to the first page.
this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0);
@@ -73,13 +73,13 @@ export interface GithubIssue {
/** An example database that the data source uses to retrieve data for the table. */
export class ExampleHttpDatabase {
constructor(private http: HttpClient) {}
constructor(private _httpClient: HttpClient) {}
getRepoIssues(sort: string, order: string, page: number): Observable<GithubApi> {
const href = 'https://api.github.com/search/issues';
const requestUrl =
`${href}?q=repo:angular/components&sort=${sort}&order=${order}&page=${page + 1}`;
return this.http.get<GithubApi>(requestUrl);
return this._httpClient.get<GithubApi>(requestUrl);
}
}
@@ -13,17 +13,17 @@ export class TextFieldAutofillMonitorExample implements AfterViewInit, OnDestroy
firstNameAutofilled: boolean;
lastNameAutofilled: boolean;
constructor(private autofill: AutofillMonitor) {}
constructor(private _autofill: AutofillMonitor) {}
ngAfterViewInit() {
this.autofill.monitor(this.firstName)
this._autofill.monitor(this.firstName)
.subscribe(e => this.firstNameAutofilled = e.isAutofilled);
this.autofill.monitor(this.lastName)
this._autofill.monitor(this.lastName)
.subscribe(e => this.lastNameAutofilled = e.isAutofilled);
}
ngOnDestroy() {
this.autofill.stopMonitoring(this.firstName);
this.autofill.stopMonitoring(this.lastName);
this._autofill.stopMonitoring(this.firstName);
this._autofill.stopMonitoring(this.lastName);
}
}
@@ -9,13 +9,13 @@ import {take} from 'rxjs/operators';
styleUrls: ['./text-field-autosize-textarea-example.css'],
})
export class TextFieldAutosizeTextareaExample {
constructor(private ngZone: NgZone) {}
constructor(private _ngZone: NgZone) {}
@ViewChild('autosize', {static: false}) autosize: CdkTextareaAutosize;
triggerResize() {
// Wait for changes to be applied, then trigger textarea resize.
this.ngZone.onStable.pipe(take(1))
this._ngZone.onStable.pipe(take(1))
.subscribe(() => this.autosize.resizeToFitContent(true));
}
}
@@ -131,13 +131,13 @@ export class TreeChecklistExample {
/** The selection for checklist */
checklistSelection = new SelectionModel<TodoItemFlatNode>(true /* multiple */);
constructor(private database: ChecklistDatabase) {
constructor(private _database: ChecklistDatabase) {
this.treeFlattener = new MatTreeFlattener(this.transformer, this.getLevel,
this.isExpandable, this.getChildren);
this.treeControl = new FlatTreeControl<TodoItemFlatNode>(this.getLevel, this.isExpandable);
this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
database.dataChange.subscribe(data => {
_database.dataChange.subscribe(data => {
this.dataSource.data = data;
});
}
@@ -251,13 +251,13 @@ export class TreeChecklistExample {
/** Select the category so we can insert the new item. */
addNewItem(node: TodoItemFlatNode) {
const parentNode = this.flatNodeMap.get(node);
this.database.insertItem(parentNode!, '');
this._database.insertItem(parentNode!, '');
this.treeControl.expand(node);
}
/** Save the node to database */
saveNode(node: TodoItemFlatNode, itemValue: string) {
const nestedNode = this.flatNodeMap.get(node);
this.database.updateItem(nestedNode!, itemValue);
this._database.updateItem(nestedNode!, itemValue);
}
}
@@ -51,15 +51,15 @@ export class DynamicDataSource {
get data(): DynamicFlatNode[] { return this.dataChange.value; }
set data(value: DynamicFlatNode[]) {
this.treeControl.dataNodes = value;
this._treeControl.dataNodes = value;
this.dataChange.next(value);
}
constructor(private treeControl: FlatTreeControl<DynamicFlatNode>,
private database: DynamicDatabase) {}
constructor(private _treeControl: FlatTreeControl<DynamicFlatNode>,
private _database: DynamicDatabase) {}
connect(collectionViewer: CollectionViewer): Observable<DynamicFlatNode[]> {
this.treeControl.expansionModel.onChange.subscribe(change => {
this._treeControl.expansionModel.onChange.subscribe(change => {
if ((change as SelectionChange<DynamicFlatNode>).added ||
(change as SelectionChange<DynamicFlatNode>).removed) {
this.handleTreeControl(change as SelectionChange<DynamicFlatNode>);
@@ -83,7 +83,7 @@ export class DynamicDataSource {
* Toggle the node, remove from display list
*/
toggleNode(node: DynamicFlatNode, expand: boolean) {
const children = this.database.getChildren(node.item);
const children = this._database.getChildren(node.item);
const index = this.data.indexOf(node);
if (!children || index < 0) { // If no children, or cannot find the node, no op
return;
@@ -94,7 +94,7 @@ export class DynamicDataSource {
setTimeout(() => {
if (expand) {
const nodes = children.map(name =>
new DynamicFlatNode(name, node.level + 1, this.database.isExpandable(name)));
new DynamicFlatNode(name, node.level + 1, this._database.isExpandable(name)));
this.data.splice(index + 1, 0, ...nodes);
} else {
let count = 0;
@@ -55,7 +55,7 @@ interface ExampleFlatNode {
styleUrls: ['tree-flat-overview-example.css'],
})
export class TreeFlatOverviewExample {
private transformer = (node: FoodNode, level: number) => {
private _transformer = (node: FoodNode, level: number) => {
return {
expandable: !!node.children && node.children.length > 0,
name: node.name,
@@ -67,7 +67,7 @@ export class TreeFlatOverviewExample {
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);
@@ -105,7 +105,7 @@ export class TreeLoadmoreExample {
// Flat tree data source
dataSource: MatTreeFlatDataSource<LoadmoreNode, LoadmoreFlatNode>;
constructor(private database: LoadmoreDatabase) {
constructor(private _database: LoadmoreDatabase) {
this.treeFlattener = new MatTreeFlattener(this.transformer, this.getLevel,
this.isExpandable, this.getChildren);
@@ -113,11 +113,11 @@ export class TreeLoadmoreExample {
this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
database.dataChange.subscribe(data => {
_database.dataChange.subscribe(data => {
this.dataSource.data = data;
});
database.initialize();
_database.initialize();
}
getChildren = (node: LoadmoreNode): Observable<LoadmoreNode[]> => node.childrenChange;
@@ -145,10 +145,10 @@ export class TreeLoadmoreExample {
/** Load more nodes from data source */
loadMore(item: string) {
this.database.loadMore(item);
this._database.loadMore(item);
}
loadChildren(node: LoadmoreFlatNode) {
this.database.loadMore(node.item, true);
this._database.loadMore(node.item, true);
}
}
@@ -1091,7 +1091,7 @@ describe('MatMenu', () => {
}
get overlayRect() {
return this.getOverlayPane().getBoundingClientRect();
return this._getOverlayPane().getBoundingClientRect();
}
get triggerRect() {
@@ -1102,7 +1102,7 @@ describe('MatMenu', () => {
return overlayContainerElement.querySelector('.mat-mdc-menu-panel');
}
private getOverlayPane() {
private _getOverlayPane() {
return overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement;
}
}
@@ -76,8 +76,8 @@ export class MatSlideToggleChange {
})
export class MatSlideToggle implements ControlValueAccessor, AfterViewInit, OnDestroy {
private onChange = (_: any) => {};
private onTouched = () => {};
private _onChange = (_: any) => {};
private _onTouched = () => {};
private _uniqueId: string = `mat-slide-toggle-${++nextUniqueId}`;
private _required: boolean = false;
@@ -249,7 +249,7 @@ export class MatSlideToggle implements ControlValueAccessor, AfterViewInit, OnDe
// Emit our custom change event only if the underlying input emitted one. This ensures that
// there is no change event, when the checked state changes programmatically.
this.onChange(this.checked);
this._onChange(this.checked);
this.change.emit(new MatSlideToggleChange(this, this.checked));
}
@@ -272,12 +272,12 @@ export class MatSlideToggle implements ControlValueAccessor, AfterViewInit, OnDe
/** Implemented as part of ControlValueAccessor. */
registerOnChange(fn: any): void {
this.onChange = fn;
this._onChange = fn;
}
/** Implemented as part of ControlValueAccessor. */
registerOnTouched(fn: any): void {
this.onTouched = fn;
this._onTouched = fn;
}
/** Implemented as a part of ControlValueAccessor. */
@@ -294,7 +294,7 @@ export class MatSlideToggle implements ControlValueAccessor, AfterViewInit, OnDe
/** Toggles the checked state of the slide-toggle. */
toggle(): void {
this.checked = !this.checked;
this.onChange(this.checked);
this._onChange(this.checked);
}
/** Handles blur events on the native input. */
@@ -306,7 +306,7 @@ export class MatSlideToggle implements ControlValueAccessor, AfterViewInit, OnDe
// telling the form control it has been touched until the next tick.
Promise.resolve().then(() => {
this._focused = false;
this.onTouched();
this._onTouched();
this._changeDetectorRef.markForCheck();
});
}
@@ -75,7 +75,7 @@ export class MomentDateAdapter extends DateAdapter<Moment> {
constructor(@Optional() @Inject(MAT_DATE_LOCALE) dateLocale: string,
@Optional() @Inject(MAT_MOMENT_DATE_ADAPTER_OPTIONS)
private options?: MatMomentDateAdapterOptions) {
private _options?: MatMomentDateAdapterOptions) {
super();
this.setLocale(dateLocale || moment.locale());
@@ -242,6 +242,6 @@ export class MomentDateAdapter extends DateAdapter<Moment> {
/** Creates a Moment instance while respecting the current UTC settings. */
private _createMoment(...args: any[]): Moment {
return (this.options && this.options.useUtc) ? moment.utc(...args) : moment(...args);
return (this._options && this._options.useUtc) ? moment.utc(...args) : moment(...args);
}
}
+12 -12
View File
@@ -106,13 +106,13 @@ export class RippleRenderer {
// Specify events which need to be registered on the trigger.
this._triggerEvents
.set('mousedown', this.onMousedown)
.set('mouseup', this.onPointerUp)
.set('mouseleave', this.onPointerUp)
.set('mousedown', this._onMousedown)
.set('mouseup', this._onPointerUp)
.set('mouseleave', this._onPointerUp)
.set('touchstart', this.onTouchStart)
.set('touchend', this.onPointerUp)
.set('touchcancel', this.onPointerUp);
.set('touchstart', this._onTouchStart)
.set('touchend', this._onPointerUp)
.set('touchcancel', this._onPointerUp);
}
}
@@ -171,7 +171,7 @@ export class RippleRenderer {
// Wait for the ripple element to be completely faded in.
// Once it's faded in, the ripple can be hidden immediately if the mouse is released.
this.runTimeoutOutsideZone(() => {
this._runTimeoutOutsideZone(() => {
const isMostRecentTransientRipple = rippleRef === this._mostRecentTransientRipple;
rippleRef.state = RippleState.VISIBLE;
@@ -214,7 +214,7 @@ export class RippleRenderer {
rippleRef.state = RippleState.FADING_OUT;
// Once the ripple faded out, the ripple can be safely removed from the DOM.
this.runTimeoutOutsideZone(() => {
this._runTimeoutOutsideZone(() => {
rippleRef.state = RippleState.HIDDEN;
rippleEl.parentNode!.removeChild(rippleEl);
}, animationConfig.exitDuration);
@@ -244,7 +244,7 @@ export class RippleRenderer {
}
/** Function being called whenever the trigger is being pressed using mouse. */
private onMousedown = (event: MouseEvent) => {
private _onMousedown = (event: MouseEvent) => {
// Screen readers will fire fake mouse events for space/enter. Skip launching a
// ripple in this case for consistency with the non-screen-reader experience.
const isFakeMousedown = isFakeMousedownFromScreenReader(event);
@@ -258,7 +258,7 @@ export class RippleRenderer {
}
/** Function being called whenever the trigger is being pressed using touch. */
private onTouchStart = (event: TouchEvent) => {
private _onTouchStart = (event: TouchEvent) => {
if (!this._target.rippleDisabled) {
// Some browsers fire mouse events after a `touchstart` event. Those synthetic mouse
// events will launch a second ripple if we don't ignore mouse events for a specific
@@ -277,7 +277,7 @@ export class RippleRenderer {
}
/** Function being called whenever the trigger is being released. */
private onPointerUp = () => {
private _onPointerUp = () => {
if (!this._isPointerDown) {
return;
}
@@ -298,7 +298,7 @@ export class RippleRenderer {
}
/** Runs a timeout outside of the Angular zone to avoid triggering the change detection. */
private runTimeoutOutsideZone(fn: Function, delay = 0) {
private _runTimeoutOutsideZone(fn: Function, delay = 0) {
this._ngZone.runOutsideAngular(() => setTimeout(fn, delay));
}
+2 -2
View File
@@ -1090,7 +1090,7 @@ describe('MatMenu', () => {
}
get overlayRect() {
return this.getOverlayPane().getBoundingClientRect();
return this._getOverlayPane().getBoundingClientRect();
}
get triggerRect() {
@@ -1101,7 +1101,7 @@ describe('MatMenu', () => {
return overlayContainerElement.querySelector('.mat-menu-panel');
}
private getOverlayPane() {
private _getOverlayPane() {
return overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement;
}
}
+3 -3
View File
@@ -135,7 +135,7 @@ export class MatProgressBar extends _MatProgressBarMixinBase implements CanColor
// When noop animation is set to true, trigger animationEnd directly.
if (this._isNoopAnimation) {
this.emitAnimationEnd();
this._emitAnimationEnd();
}
}
private _value: number = 0;
@@ -200,7 +200,7 @@ export class MatProgressBar extends _MatProgressBarMixinBase implements CanColor
this._animationEndSubscription =
(fromEvent(element, 'transitionend') as Observable<TransitionEvent>)
.pipe(filter(((e: TransitionEvent) => e.target === element)))
.subscribe(() => this._ngZone.run(() => this.emitAnimationEnd()));
.subscribe(() => this._ngZone.run(() => this._emitAnimationEnd()));
}));
}
}
@@ -210,7 +210,7 @@ export class MatProgressBar extends _MatProgressBarMixinBase implements CanColor
}
/** Emit an animationEnd event if in determinate or buffer mode. */
private emitAnimationEnd(): void {
private _emitAnimationEnd(): void {
if (this.mode === 'determinate' || this.mode === 'buffer') {
this.animationEnd.next({value: this.value});
}
@@ -130,13 +130,13 @@ export class MatProgressSpinner extends _MatProgressSpinnerMixinBase implements
private _fallbackAnimation = false;
/** Tracks diameters of existing instances to de-dupe generated styles (default d = 100) */
private static diameters = new Set<number>([BASE_SIZE]);
private static _diameters = new Set<number>([BASE_SIZE]);
/**
* Used for storing all of the generated keyframe animations.
* @dynamic
*/
private static styleTag: HTMLStyleElement|null = null;
private static _styleTag: HTMLStyleElement|null = null;
/** Whether the _mat-animation-noopable class should be applied, disabling animations. */
_noopAnimations: boolean;
@@ -147,7 +147,7 @@ export class MatProgressSpinner extends _MatProgressSpinnerMixinBase implements
set diameter(size: number) {
this._diameter = coerceNumberProperty(size);
if (!this._fallbackAnimation && !MatProgressSpinner.diameters.has(this._diameter)) {
if (!this._fallbackAnimation && !MatProgressSpinner._diameters.has(this._diameter)) {
this._attachStyleNode();
}
}
@@ -241,19 +241,19 @@ export class MatProgressSpinner extends _MatProgressSpinnerMixinBase implements
/** Dynamically generates a style tag containing the correct animation for this diameter. */
private _attachStyleNode(): void {
let styleTag = MatProgressSpinner.styleTag;
let styleTag = MatProgressSpinner._styleTag;
if (!styleTag) {
styleTag = this._document.createElement('style');
this._document.head.appendChild(styleTag);
MatProgressSpinner.styleTag = styleTag;
MatProgressSpinner._styleTag = styleTag;
}
if (styleTag && styleTag.sheet) {
(styleTag.sheet as CSSStyleSheet).insertRule(this._getAnimationText(), 0);
}
MatProgressSpinner.diameters.add(this.diameter);
MatProgressSpinner._diameters.add(this.diameter);
}
/** Generates animation styles adjusted for the spinner's diameter. */
+7 -7
View File
@@ -105,8 +105,8 @@ export class MatSlideToggle extends _MatSlideToggleMixinBase implements OnDestro
CanDisable, CanColor,
HasTabIndex,
CanDisableRipple {
private onChange = (_: any) => {};
private onTouched = () => {};
private _onChange = (_: any) => {};
private _onTouched = () => {};
private _uniqueId: string = `mat-slide-toggle-${++nextUniqueId}`;
private _required: boolean = false;
@@ -206,7 +206,7 @@ export class MatSlideToggle extends _MatSlideToggleMixinBase implements OnDestro
// 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());
Promise.resolve().then(() => this._onTouched());
}
});
}
@@ -262,12 +262,12 @@ export class MatSlideToggle extends _MatSlideToggleMixinBase implements OnDestro
/** Implemented as part of ControlValueAccessor. */
registerOnChange(fn: any): void {
this.onChange = fn;
this._onChange = fn;
}
/** Implemented as part of ControlValueAccessor. */
registerOnTouched(fn: any): void {
this.onTouched = fn;
this._onTouched = fn;
}
/** Implemented as a part of ControlValueAccessor. */
@@ -284,14 +284,14 @@ export class MatSlideToggle extends _MatSlideToggleMixinBase implements OnDestro
/** Toggles the checked state of the slide-toggle. */
toggle(): void {
this.checked = !this.checked;
this.onChange(this.checked);
this._onChange(this.checked);
}
/**
* Emits a change event on the `change` output. Also notifies the FormControl about the change.
*/
private _emitChangeEvent() {
this.onChange(this.checked);
this._onChange(this.checked);
this.change.emit(new MatSlideToggleChange(this, this.checked));
}
@@ -135,12 +135,12 @@ export class MatTreeFlatDataSource<T, F> extends DataSource<F> {
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;
this._flattenedData.next(this._treeFlattener.flattenNodes(this.data));
this._treeControl.dataNodes = this._flattenedData.value;
}
constructor(private treeControl: FlatTreeControl<F>,
private treeFlattener: MatTreeFlattener<T, F>,
constructor(private _treeControl: FlatTreeControl<F>,
private _treeFlattener: MatTreeFlattener<T, F>,
initialData: T[] = []) {
super();
this._data = new BehaviorSubject<T[]>(initialData);
@@ -149,12 +149,12 @@ export class MatTreeFlatDataSource<T, F> extends DataSource<F> {
connect(collectionViewer: CollectionViewer): Observable<F[]> {
const changes = [
collectionViewer.viewChange,
this.treeControl.expansionModel.onChange,
this._treeControl.expansionModel.onChange,
this._flattenedData
];
return merge(...changes).pipe(map(() => {
this._expandedData.next(
this.treeFlattener.expandFlattenedNodes(this._flattenedData.value, this.treeControl));
this._treeFlattener.expandFlattenedNodes(this._flattenedData.value, this._treeControl));
return this._expandedData.value;
}));
}
+4 -4
View File
@@ -707,7 +707,7 @@ const TREE_DATA: FoodNode[] = [
`
})
class MatTreeWithNullOrUndefinedChild {
private transformer = (node: FoodNode, level: number) => {
private _transformer = (node: FoodNode, level: number) => {
return {
expandable: !!node.children,
name: node.name,
@@ -719,7 +719,7 @@ class MatTreeWithNullOrUndefinedChild {
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);
@@ -745,12 +745,12 @@ class MatNestedTreeWithNullOrUndefinedChild {
dataSource: MatTreeNestedDataSource<FoodNode>;
constructor() {
this.treeControl = new NestedTreeControl<FoodNode>(this.getChildren);
this.treeControl = new NestedTreeControl<FoodNode>(this._getChildren);
this.dataSource = new MatTreeNestedDataSource();
this.dataSource.data = TREE_DATA;
}
private getChildren = (node: FoodNode) => node.children;
private _getChildren = (node: FoodNode) => node.children;
}
@Component({
+16 -16
View File
@@ -39,26 +39,26 @@ export class Categorizer implements Processor {
$process(docs: DocCollection) {
docs
.filter(doc => doc.docType === 'class' || doc.docType === 'interface')
.forEach(doc => this.decorateClassLikeDoc(doc));
.forEach(doc => this._decorateClassLikeDoc(doc));
docs
.filter(doc => doc.docType === 'function')
.forEach(doc => this.decorateFunctionExportDoc(doc));
.forEach(doc => this._decorateFunctionExportDoc(doc));
docs
.filter(doc => doc.docType === 'const')
.forEach(doc => this.decorateConstExportDoc(doc));
.forEach(doc => this._decorateConstExportDoc(doc));
docs
.filter(doc => doc.docType === 'type-alias')
.forEach(doc => this.decorateTypeAliasExportDoc(doc));
.forEach(doc => this._decorateTypeAliasExportDoc(doc));
}
/**
* Decorates all class and interface docs inside of the dgeni pipeline.
* - Members of a class and interface document will be extracted into separate variables.
*/
private decorateClassLikeDoc(classLikeDoc: CategorizedClassLikeDoc) {
private _decorateClassLikeDoc(classLikeDoc: CategorizedClassLikeDoc) {
// Resolve all methods and properties from the classDoc.
classLikeDoc.methods = classLikeDoc.members
.filter(isMethod)
@@ -70,13 +70,13 @@ export class Categorizer implements Processor {
// Special decorations for real class documents that don't apply for interfaces.
if (classLikeDoc.docType === 'class') {
this.decorateClassDoc(classLikeDoc as CategorizedClassDoc);
this.replaceMethodsWithOverload(classLikeDoc as CategorizedClassDoc);
this._decorateClassDoc(classLikeDoc as CategorizedClassDoc);
this._replaceMethodsWithOverload(classLikeDoc as CategorizedClassDoc);
}
// Call decorate hooks that can modify the method and property docs.
classLikeDoc.methods.forEach(doc => this.decorateMethodDoc(doc));
classLikeDoc.properties.forEach(doc => this.decoratePropertyDoc(doc));
classLikeDoc.methods.forEach(doc => this._decorateMethodDoc(doc));
classLikeDoc.properties.forEach(doc => this._decoratePropertyDoc(doc));
decorateDeprecatedDoc(classLikeDoc);
@@ -90,7 +90,7 @@ export class Categorizer implements Processor {
* - Identifies directives, services or NgModules and marks them them inside of the doc.
* - Links the Dgeni document to the Dgeni document that the current class extends from.
*/
private decorateClassDoc(classDoc: CategorizedClassDoc) {
private _decorateClassDoc(classDoc: CategorizedClassDoc) {
// Classes can only extend a single class. This means that there can't be multiple extend
// clauses for the Dgeni document. To make the template syntax simpler and more readable,
// store the extended class in a variable.
@@ -113,7 +113,7 @@ export class Categorizer implements Processor {
* Method that will be called for each method doc. The parameters for the method-docs
* will be normalized, so that they can be easily used inside of dgeni templates.
*/
private decorateMethodDoc(methodDoc: CategorizedMethodMemberDoc) {
private _decorateMethodDoc(methodDoc: CategorizedMethodMemberDoc) {
normalizeFunctionParameters(methodDoc);
decorateDeprecatedDoc(methodDoc);
}
@@ -122,7 +122,7 @@ export class Categorizer implements Processor {
* Method that will be called for each function export doc. The parameters for the functions
* will be normalized, so that they can be easily used inside of Dgeni templates.
*/
private decorateFunctionExportDoc(functionDoc: CategorizedFunctionExportDoc) {
private _decorateFunctionExportDoc(functionDoc: CategorizedFunctionExportDoc) {
normalizeFunctionParameters(functionDoc);
decorateDeprecatedDoc(functionDoc);
}
@@ -131,7 +131,7 @@ export class Categorizer implements Processor {
* Method that will be called for each const export document. We decorate the const
* documents with a property that states whether the constant is deprecated or not.
*/
private decorateConstExportDoc(doc: CategorizedConstExportDoc) {
private _decorateConstExportDoc(doc: CategorizedConstExportDoc) {
decorateDeprecatedDoc(doc);
}
@@ -139,7 +139,7 @@ export class Categorizer implements Processor {
* Method that will be called for each type-alias export document. We decorate the type-alias
* documents with a property that states whether the type-alias is deprecated or not.
*/
private decorateTypeAliasExportDoc(doc: CategorizedTypeAliasExportDoc) {
private _decorateTypeAliasExportDoc(doc: CategorizedTypeAliasExportDoc) {
decorateDeprecatedDoc(doc);
}
@@ -147,7 +147,7 @@ export class Categorizer implements Processor {
* Method that will be called for each property doc. Properties that are Angular inputs or
* outputs will be marked. Aliases for the inputs or outputs will be stored as well.
*/
private decoratePropertyDoc(propertyDoc: CategorizedPropertyMemberDoc) {
private _decoratePropertyDoc(propertyDoc: CategorizedPropertyMemberDoc) {
decorateDeprecatedDoc(propertyDoc);
const metadata = propertyDoc.containerDoc.docType === 'class' ?
@@ -167,7 +167,7 @@ export class Categorizer implements Processor {
* Walks through every method of the specified class doc and replaces the method
* with its referenced overload method definitions, if the method is having overload definitions.
*/
private replaceMethodsWithOverload(classDoc: CategorizedClassDoc) {
private _replaceMethodsWithOverload(classDoc: CategorizedClassDoc) {
const methodsToAdd: CategorizedMethodMemberDoc[] = [];
classDoc.methods.forEach((methodDoc, index) => {
@@ -35,28 +35,28 @@ export class DocsPrivateFilter implements Processor {
$runBefore = ['categorizer'];
$process(docs: DocCollection) {
return docs.filter(doc => this.isPublicDoc(doc));
return docs.filter(doc => this._isPublicDoc(doc));
}
/** Marks the given API doc with a property that describes its public state. */
private isPublicDoc(doc: ApiDoc) {
if (this.hasDocsPrivateTag(doc) || doc.name.startsWith('_')) {
private _isPublicDoc(doc: ApiDoc) {
if (this._hasDocsPrivateTag(doc) || doc.name.startsWith('_')) {
return false;
} else if (doc instanceof MemberDoc) {
return !this.isInternalMember(doc);
return !this._isInternalMember(doc);
} else if (doc instanceof ClassExportDoc) {
doc.members = doc.members.filter(memberDoc => this.isPublicDoc(memberDoc));
doc.members = doc.members.filter(memberDoc => this._isPublicDoc(memberDoc));
}
return true;
}
/** Whether the given method member is listed as an internal member. */
private isInternalMember(memberDoc: MemberDoc) {
private _isInternalMember(memberDoc: MemberDoc) {
return INTERNAL_METHODS.includes(memberDoc.name);
}
/** Whether the given doc has a @docs-private tag set. */
private hasDocsPrivateTag(doc: any) {
private _hasDocsPrivateTag(doc: any) {
const tags = doc.tags && doc.tags.tags;
return tags ? tags.find((d: any) => d.tagName == 'docs-private') : false;
}
@@ -13,20 +13,20 @@ export class MergeInheritedProperties implements Processor {
$process(docs: DocCollection) {
return docs
.filter(doc => doc.docType === 'class')
.forEach(doc => this.addInheritedProperties(doc));
.forEach(doc => this._addInheritedProperties(doc));
}
private addInheritedProperties(doc: ClassExportDoc) {
private _addInheritedProperties(doc: ClassExportDoc) {
doc.implementsClauses.filter(clause => clause.doc).forEach(clause => {
clause.doc!.members.forEach(member => this.addMemberDocIfNotPresent(doc, member));
clause.doc!.members.forEach(member => this._addMemberDocIfNotPresent(doc, member));
});
doc.extendsClauses.filter(clause => clause.doc).forEach(clause => {
clause.doc!.members.forEach(member => this.addMemberDocIfNotPresent(doc, member));
clause.doc!.members.forEach(member => this._addMemberDocIfNotPresent(doc, member));
});
}
private addMemberDocIfNotPresent(destination: ClassExportDoc, memberDoc: MemberDoc) {
private _addMemberDocIfNotPresent(destination: ClassExportDoc, memberDoc: MemberDoc) {
if (!destination.members.find(member => member.name === memberDoc.name)) {
// To be able to differentiate between member docs from the heritage clause and the
// member doc for the destination class, we clone the member doc. It's important to keep
+32 -32
View File
@@ -19,30 +19,30 @@ const bundlesDir = join(buildConfig.outputDir, 'bundles');
export class PackageBundler {
/** Name of the AMD module for the primary entry point of the build package. */
private readonly primaryAmdModuleName: string;
private readonly _primaryAmdModuleName: string;
constructor(private buildPackage: BuildPackage) {
this.primaryAmdModuleName = this.getAmdModuleName(buildPackage.name);
constructor(private _buildPackage: BuildPackage) {
this._primaryAmdModuleName = this._getAmdModuleName(_buildPackage.name);
}
/** Creates all bundles for the package and all associated entry points (UMD, ES5, ES2015). */
async createBundles() {
for (const entryPoint of this.buildPackage.secondaryEntryPoints) {
await this.bundleSecondaryEntryPoint(entryPoint);
for (const entryPoint of this._buildPackage.secondaryEntryPoints) {
await this._bundleSecondaryEntryPoint(entryPoint);
}
await this.bundlePrimaryEntryPoint();
await this._bundlePrimaryEntryPoint();
}
/** Bundles the primary entry-point w/ given entry file, e.g. @angular/cdk */
private async bundlePrimaryEntryPoint() {
const packageName = this.buildPackage.name;
private async _bundlePrimaryEntryPoint() {
const packageName = this._buildPackage.name;
return this.bundleEntryPoint({
entryFile: this.buildPackage.entryFilePath,
esm5EntryFile: join(this.buildPackage.esm5OutputDir, 'index.js'),
return this._bundleEntryPoint({
entryFile: this._buildPackage.entryFilePath,
esm5EntryFile: join(this._buildPackage.esm5OutputDir, 'index.js'),
importName: `@angular/${packageName}`,
moduleName: this.primaryAmdModuleName,
moduleName: this._primaryAmdModuleName,
esm2015Dest: join(bundlesDir, `${packageName}.js`),
esm5Dest: join(bundlesDir, `${packageName}.es5.js`),
umdDest: join(bundlesDir, `${packageName}.umd.js`),
@@ -51,16 +51,16 @@ export class PackageBundler {
}
/** Bundles a single secondary entry-point w/ given entry file, e.g. @angular/cdk/a11y */
private async bundleSecondaryEntryPoint(entryPointName: string) {
const packageName = this.buildPackage.name;
const entryFile = join(this.buildPackage.outputDir, entryPointName, 'index.js');
const esm5EntryFile = join(this.buildPackage.esm5OutputDir, entryPointName, 'index.js');
private async _bundleSecondaryEntryPoint(entryPointName: string) {
const packageName = this._buildPackage.name;
const entryFile = join(this._buildPackage.outputDir, entryPointName, 'index.js');
const esm5EntryFile = join(this._buildPackage.esm5OutputDir, entryPointName, 'index.js');
return this.bundleEntryPoint({
return this._bundleEntryPoint({
entryFile,
esm5EntryFile,
importName: `@angular/${packageName}/${entryPointName}`,
moduleName: this.getAmdModuleName(packageName, entryPointName),
moduleName: this._getAmdModuleName(packageName, entryPointName),
esm2015Dest: join(bundlesDir, `${packageName}`, `${entryPointName}.js`),
esm5Dest: join(bundlesDir, `${packageName}`, `${entryPointName}.es5.js`),
umdDest: join(bundlesDir, `${packageName}-${entryPointName}.umd.js`),
@@ -73,9 +73,9 @@ export class PackageBundler {
* @param config Configuration that specifies the entry-point, module name, and output
* bundle paths.
*/
private async bundleEntryPoint(config: BundlesConfig) {
private async _bundleEntryPoint(config: BundlesConfig) {
// Build FESM-2015 bundle file.
await this.createRollupBundle({
await this._createRollupBundle({
importName: config.importName,
moduleName: config.moduleName,
entry: config.entryFile,
@@ -84,7 +84,7 @@ export class PackageBundler {
});
// Build FESM-5 bundle file.
await this.createRollupBundle({
await this._createRollupBundle({
importName: config.importName,
moduleName: config.moduleName,
entry: config.esm5EntryFile,
@@ -93,7 +93,7 @@ export class PackageBundler {
});
// Create UMD bundle of ES5 output.
await this.createRollupBundle({
await this._createRollupBundle({
importName: config.importName,
moduleName: config.moduleName,
entry: config.esm5Dest,
@@ -112,7 +112,7 @@ export class PackageBundler {
}
/** Creates a rollup bundle of a specified JavaScript file. */
private async createRollupBundle(config: RollupBundleConfig) {
private async _createRollupBundle(config: RollupBundleConfig) {
const bundleOptions = {
context: 'this',
external: Object.keys(rollupGlobals),
@@ -158,17 +158,17 @@ export class PackageBundler {
// If each secondary entry-point is re-exported at the root, we want to exclude those
// secondary entry-points from the rollup globals because we want the UMD for the
// primary entry-point to include *all* of the sources for those entry-points.
if (this.buildPackage.exportsSecondaryEntryPointsAtRoot &&
config.moduleName === this.primaryAmdModuleName) {
if (this._buildPackage.exportsSecondaryEntryPointsAtRoot &&
config.moduleName === this._primaryAmdModuleName) {
const importRegex = new RegExp(`@angular/${this.buildPackage.name}/.+`);
const importRegex = new RegExp(`@angular/${this._buildPackage.name}/.+`);
external = external.filter(e => !importRegex.test(e));
// Use the rollup-alias plugin to map imports of the form `@angular/material/button`
// to the actual file location so that rollup can resolve the imports (otherwise they
// will be treated as external dependencies and not included in the bundle).
bundleOptions.plugins.push(
rollupAlias(this.getResolvedSecondaryEntryPointImportPaths(config.dest)));
rollupAlias(this._getResolvedSecondaryEntryPointImportPaths(config.dest)));
}
bundleOptions.external = external;
@@ -183,10 +183,10 @@ export class PackageBundler {
* @param bundleOutputDir Path to the bundle output directory.
* @returns Map of alias to resolved path.
*/
private getResolvedSecondaryEntryPointImportPaths(bundleOutputDir: string) {
return this.buildPackage.secondaryEntryPoints.reduce((map, p) => {
map[`@angular/${this.buildPackage.name}/${p}`] =
join(dirname(bundleOutputDir), this.buildPackage.name, `${p}.es5.js`);
private _getResolvedSecondaryEntryPointImportPaths(bundleOutputDir: string) {
return this._buildPackage.secondaryEntryPoints.reduce((map, p) => {
map[`@angular/${this._buildPackage.name}/${p}`] =
join(dirname(bundleOutputDir), this._buildPackage.name, `${p}.es5.js`);
return map;
}, {} as {[key: string]: string});
}
@@ -195,7 +195,7 @@ export class PackageBundler {
* Gets the AMD module name for a package and an optional entry point. This is consistent
* to the module name format being used in "angular/angular".
*/
private getAmdModuleName(packageName: string, entryPointName?: string) {
private _getAmdModuleName(packageName: string, entryPointName?: string) {
// For example, the AMD module name for the "@angular/material-examples" package should be
// "ng.materialExamples". We camel-case the package name in case it contains dashes.
let amdModuleName = `ng.${dashCaseToCamelCase(packageName)}`;
+5 -5
View File
@@ -39,18 +39,18 @@ export class BuildPackage {
readonly entryFilePath: string;
/** Package bundler instance. */
private bundler = new PackageBundler(this);
private _bundler = new PackageBundler(this);
/** Secondary entry-points partitioned by their build depth. */
get secondaryEntryPointsByDepth(): string[][] {
this.cacheSecondaryEntryPoints();
this._cacheSecondaryEntryPoints();
return this._secondaryEntryPointsByDepth;
}
private _secondaryEntryPointsByDepth: string[][];
/** Secondary entry points for the package. */
get secondaryEntryPoints(): string[] {
this.cacheSecondaryEntryPoints();
this._cacheSecondaryEntryPoints();
return this._secondaryEntryPoints;
}
private _secondaryEntryPoints: string[];
@@ -85,7 +85,7 @@ export class BuildPackage {
/** Creates all bundles for the package and all associated entry points. */
async createBundles() {
await this.bundler.createBundles();
await this._bundler.createBundles();
}
/** Compiles TS into both ES2015 and ES5, then updates exports. */
@@ -96,7 +96,7 @@ export class BuildPackage {
}
/** Stores the secondary entry-points for this package if they haven't been computed already. */
private cacheSecondaryEntryPoints() {
private _cacheSecondaryEntryPoints() {
if (!this._secondaryEntryPoints) {
this._secondaryEntryPointsByDepth = getSecondaryEntryPointsForPackage(this);
this._secondaryEntryPoints =
+2 -2
View File
@@ -1,5 +1,5 @@
export declare class BreakpointObserver implements OnDestroy {
constructor(mediaMatcher: MediaMatcher, zone: NgZone);
constructor(_mediaMatcher: MediaMatcher, _zone: NgZone);
isMatched(value: string | string[]): boolean;
ngOnDestroy(): void;
observe(value: string | string[]): Observable<BreakpointState>;
@@ -33,6 +33,6 @@ export declare class LayoutModule {
}
export declare class MediaMatcher {
constructor(platform: Platform);
constructor(_platform: Platform);
matchMedia(query: string): MediaQueryList;
}
+2 -2
View File
@@ -173,7 +173,7 @@ export declare class CdkTextColumn<T> implements OnDestroy, OnInit {
headerText: string;
justify: 'start' | 'end';
name: string;
constructor(table: CdkTable<T>, options: TextColumnOptions<T>);
constructor(_table: CdkTable<T>, _options: TextColumnOptions<T>);
_createDefaultHeaderText(): string;
ngOnDestroy(): void;
ngOnInit(): void;
@@ -224,7 +224,7 @@ export declare type StickyDirection = 'top' | 'bottom' | 'left' | 'right';
export declare class StickyStyler {
direction: Direction;
constructor(isNativeHtmlTable: boolean, stickCellCss: string, direction: Direction, _isBrowser?: boolean);
constructor(_isNativeHtmlTable: boolean, _stickCellCss: string, direction: Direction, _isBrowser?: boolean);
_addStickyStyle(element: HTMLElement, dir: StickyDirection, dirValue: number): void;
_getCalculatedZIndex(element: HTMLElement): string;
_getCellWidths(row: HTMLElement): number[];
+1 -1
View File
@@ -18,7 +18,7 @@ export declare class MatTreeFlatDataSource<T, F> extends DataSource<F> {
_expandedData: BehaviorSubject<F[]>;
_flattenedData: BehaviorSubject<F[]>;
data: T[];
constructor(treeControl: FlatTreeControl<F>, treeFlattener: MatTreeFlattener<T, F>, initialData?: T[]);
constructor(_treeControl: FlatTreeControl<F>, _treeFlattener: MatTreeFlattener<T, F>, initialData?: T[]);
connect(collectionViewer: CollectionViewer): Observable<F[]>;
disconnect(): void;
}
+18 -18
View File
@@ -79,19 +79,19 @@ class PublishReleaseTask extends BaseReleaseTask {
// Branch that will be used to build the output for the release of the current version.
const publishBranch = this.switchToPublishBranch(newVersion);
this.verifyLastCommitVersionBump();
this._verifyLastCommitVersionBump();
this.verifyLocalCommitsMatchUpstream(publishBranch);
const upstreamRemote = await this.getProjectUpstreamRemote();
const upstreamRemote = await this._getProjectUpstreamRemote();
const npmDistTag = await promptForNpmDistTag(newVersion);
// In case the user wants to publish a stable version to the "next" npm tag, we want
// to double-check because usually only pre-release's are pushed to that tag.
if (npmDistTag === 'next' && !newVersion.prereleaseLabel) {
await this.promptStableVersionForNextTag();
await this._promptStableVersionForNextTag();
}
this.buildReleasePackages();
this._buildReleasePackages();
console.info(green(` ✓ Built the release output.`));
// Checks all release packages against release output validations before releasing.
@@ -107,18 +107,18 @@ class PublishReleaseTask extends BaseReleaseTask {
}
// Create and push the release tag before publishing to NPM.
this.createReleaseTag(newVersionName, releaseNotes);
this.pushReleaseTag(newVersionName, upstreamRemote);
this._createReleaseTag(newVersionName, releaseNotes);
this._pushReleaseTag(newVersionName, upstreamRemote);
// Ensure that we are authenticated before running "npm publish" for each package.
this.checkNpmAuthentication();
this._checkNpmAuthentication();
// Just in order to double-check that the user is sure to publish to NPM, we want
// the user to interactively confirm that the script should continue.
await this.promptConfirmReleasePublish();
await this._promptConfirmReleasePublish();
for (let packageName of releasePackages) {
this.publishPackageToNpm(packageName, npmDistTag);
this._publishPackageToNpm(packageName, npmDistTag);
}
const newReleaseUrl = getGithubNewReleaseUrl({
@@ -150,7 +150,7 @@ class PublishReleaseTask extends BaseReleaseTask {
* Verifies that the latest commit on the current branch is a version bump from the
* staging script.
*/
private verifyLastCommitVersionBump() {
private _verifyLastCommitVersionBump() {
if (!/chore: bump version/.test(this.git.getCommitTitle('HEAD'))) {
console.error(red(` ✘ The latest commit of the current branch does not seem to be a ` +
`version bump.`));
@@ -160,7 +160,7 @@ class PublishReleaseTask extends BaseReleaseTask {
}
/** Builds all release packages that should be published. */
private buildReleasePackages() {
private _buildReleasePackages() {
const binDir = join(this.projectDir, 'node_modules/.bin');
const spawnOptions = {cwd: binDir, stdio: 'inherit'};
@@ -175,7 +175,7 @@ class PublishReleaseTask extends BaseReleaseTask {
* Prompts the user whether they are sure that the current stable version should be
* released to the "next" NPM dist-tag.
*/
private async promptStableVersionForNextTag() {
private async _promptStableVersionForNextTag() {
if (!await this.promptConfirm(
'Are you sure that you want to release a stable version to the "next" tag?')) {
console.log();
@@ -188,7 +188,7 @@ class PublishReleaseTask extends BaseReleaseTask {
* Prompts the user whether he is sure that the script should continue publishing
* the release to NPM.
*/
private async promptConfirmReleasePublish() {
private async _promptConfirmReleasePublish() {
if (!await this.promptConfirm('Are you sure that you want to release now?')) {
console.log();
console.log(yellow('Aborting publish...'));
@@ -201,7 +201,7 @@ class PublishReleaseTask extends BaseReleaseTask {
* the NPM credentials that are necessary to publish the release. We achieve this by basically
* running "npm login" as a child process and piping stdin/stdout/stderr to the current tty.
*/
private checkNpmAuthentication() {
private _checkNpmAuthentication() {
if (isNpmAuthenticated()) {
console.info(green(` ✓ NPM is authenticated.`));
return;
@@ -231,7 +231,7 @@ class PublishReleaseTask extends BaseReleaseTask {
}
/** Publishes the specified package within the given NPM dist tag. */
private publishPackageToNpm(packageName: string, npmDistTag: string) {
private _publishPackageToNpm(packageName: string, npmDistTag: string) {
console.info(green(` ⭮ Publishing "${packageName}"..`));
const errorOutput = npmPublish(join(this.releaseOutputPath, packageName), npmDistTag);
@@ -247,7 +247,7 @@ class PublishReleaseTask extends BaseReleaseTask {
}
/** Creates the specified release tag locally. */
private createReleaseTag(tagName: string, releaseNotes: string) {
private _createReleaseTag(tagName: string, releaseNotes: string) {
if (this.git.hasLocalTag(tagName)) {
const expectedSha = this.git.getLocalCommitSha('HEAD');
@@ -269,7 +269,7 @@ class PublishReleaseTask extends BaseReleaseTask {
}
/** Pushes the release tag to the remote repository. */
private pushReleaseTag(tagName: string, upstreamRemote: string) {
private _pushReleaseTag(tagName: string, upstreamRemote: string) {
const remoteTagSha = this.git.getShaOfRemoteTag(tagName);
const expectedSha = this.git.getLocalCommitSha('HEAD');
@@ -300,7 +300,7 @@ class PublishReleaseTask extends BaseReleaseTask {
* Determines the name of the Git remote that is used for pushing changes
* upstream to github.
*/
private async getProjectUpstreamRemote() {
private async _getProjectUpstreamRemote() {
const remoteName = this.git.hasRemote('upstream') ?
'upstream' : await promptForUpstreamRemote(this.git.getAvailableRemotes());
+4 -4
View File
@@ -90,14 +90,14 @@ class StageReleaseTask extends BaseReleaseTask {
const publishBranch = this.switchToPublishBranch(newVersion);
this.verifyLocalCommitsMatchUpstream(publishBranch);
await this.verifyPassingGithubStatus(publishBranch);
await this._verifyPassingGithubStatus(publishBranch);
if (!this.git.checkoutNewBranch(stagingBranch)) {
console.error(red(`Could not create release staging branch: ${stagingBranch}. Aborting...`));
process.exit(1);
}
this.updatePackageJsonVersion(newVersionName);
this._updatePackageJsonVersion(newVersionName);
console.log(green(` ✓ Updated the version to "${bold(newVersionName)}" inside of the ` +
`${italic('package.json')}`));
@@ -130,13 +130,13 @@ class StageReleaseTask extends BaseReleaseTask {
}
/** Updates the version of the project package.json and writes the changes to disk. */
private updatePackageJsonVersion(newVersionName: string) {
private _updatePackageJsonVersion(newVersionName: string) {
const newPackageJson = {...this.packageJson, version: newVersionName};
writeFileSync(this.packageJsonPath, JSON.stringify(newPackageJson, null, 2) + '\n');
}
/** Verifies that the latest commit of the current branch is passing all Github statuses. */
private async verifyPassingGithubStatus(expectedPublishBranch: string) {
private async _verifyPassingGithubStatus(expectedPublishBranch: string) {
const commitRef = this.git.getLocalCommitSha('HEAD');
const githubCommitsUrl = getGithubBranchCommitsUrl(this.repositoryOwner, this.repositoryName,
expectedPublishBranch);
+101
View File
@@ -0,0 +1,101 @@
import * as ts from 'typescript';
import * as tsutils from 'tsutils';
import * as Lint from 'tslint';
/**
* Lint rule that checks the names of class members against a pattern. Configured per modifier, e.g.
* {
* "member-naming": [true, {
* "private": "^_" // All private properties should start with `_`.
* }]
* }
*/
export class Rule extends Lint.Rules.AbstractRule {
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new Walker(sourceFile, this.getOptions()));
}
}
class Walker extends Lint.RuleWalker {
/** Configured patterns for each of the modifiers. */
private _config: {
private?: RegExp;
protected?: RegExp;
public?: RegExp;
};
constructor(sourceFile: ts.SourceFile, options: Lint.IOptions) {
super(sourceFile, options);
const args = options.ruleArguments[0] || {};
this._config = Object.keys(args).reduce((config, key) => {
config[key] = new RegExp(args[key]);
return config;
}, {} as {[key: string]: RegExp});
}
visitClassDeclaration(node: ts.ClassDeclaration) {
node.members.forEach(member => {
// Members without a modifier are considered public.
if (!member.modifiers || tsutils.hasModifier(member.modifiers, ts.SyntaxKind.PublicKeyword)) {
this._validateMember(member, 'public');
} else if (tsutils.hasModifier(member.modifiers, ts.SyntaxKind.PrivateKeyword)) {
this._validateMember(member, 'private');
} else if (tsutils.hasModifier(member.modifiers, ts.SyntaxKind.ProtectedKeyword)) {
this._validateMember(member, 'protected');
}
});
super.visitClassDeclaration(node);
}
visitConstructorDeclaration(node: ts.ConstructorDeclaration) {
node.parameters.forEach(param => {
const modifiers = param.modifiers;
// Check class members that were declared via the constructor
// (e.g. `constructor(private _something: number)`. These nodes don't
// show up under `ClassDeclaration.members`.
if (tsutils.hasModifier(modifiers, ts.SyntaxKind.ReadonlyKeyword) ||
tsutils.hasModifier(modifiers, ts.SyntaxKind.PublicKeyword)) {
this._validateNode(param, 'public');
} else if (tsutils.hasModifier(modifiers, ts.SyntaxKind.PrivateKeyword)) {
this._validateNode(param, 'private');
} else if (tsutils.hasModifier(modifiers, ts.SyntaxKind.ProtectedKeyword)) {
this._validateNode(param, 'protected');
}
});
super.visitConstructorDeclaration(node);
}
/**
* Validates that a class member matches the pattern configured for the particular modifier.
* @param node Class member to be validated.
* @param modifier Modifiers against which to validate.
*/
private _validateMember(node: ts.ClassElement, modifier: 'public' | 'private' | 'protected') {
if (ts.isMethodDeclaration(node) || ts.isPropertyDeclaration(node)) {
this._validateNode(node, modifier);
}
}
/**
* Validates that a node matches the pattern for the corresponding modifier.
* @param node Node to be validated.
* @param modifier Modifier to validate against.
*/
private _validateNode(node: ts.Node & {name: ts.PropertyName | ts.BindingName},
modifier: 'public' | 'private' | 'protected') {
const pattern = this._config[modifier];
if (pattern) {
const failureMessage = `${modifier} modifier name has to match the pattern ${pattern}`;
if (!pattern.test(node.name.getText())) {
this.addFailureAtNode(node.name, failureMessage);
}
}
}
}
+3
View File
@@ -109,6 +109,9 @@
"HostBinding",
"HostListener"
],
"member-naming": [true, {
"private": "^_"
}],
"validate-decorators": [true, {
"Component": {
"!host": "\\[class\\]",