diff --git a/src/a11y-demo/card/card-a11y.ts b/src/a11y-demo/card/card-a11y.ts index bad993a05ba8..ae42e59867ba 100644 --- a/src/a11y-demo/card/card-a11y.ts +++ b/src/a11y-demo/card/card-a11y.ts @@ -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}); } } diff --git a/src/a11y-demo/icon/icon-a11y.ts b/src/a11y-demo/icon/icon-a11y.ts index ebc545c38606..6df8f7a12008 100644 --- a/src/a11y-demo/icon/icon-a11y.ts +++ b/src/a11y-demo/icon/icon-a11y.ts @@ -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}); } } diff --git a/src/a11y-demo/slide-toggle/slide-toggle-a11y.ts b/src/a11y-demo/slide-toggle/slide-toggle-a11y.ts index cf16073b281f..6a8b4fe12b20 100644 --- a/src/a11y-demo/slide-toggle/slide-toggle-a11y.ts +++ b/src/a11y-demo/slide-toggle/slide-toggle-a11y.ts @@ -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}); } } diff --git a/src/a11y-demo/snack-bar/snack-bar-a11y.ts b/src/a11y-demo/snack-bar/snack-bar-a11y.ts index 918a4cf41139..7c5aec08d4c0 100644 --- a/src/a11y-demo/snack-bar/snack-bar-a11y.ts +++ b/src/a11y-demo/snack-bar/snack-bar-a11y.ts @@ -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}); } } diff --git a/src/cdk-experimental/dialog/dialog.ts b/src/cdk-experimental/dialog/dialog.ts index f612af5ed821..aaad4a3efea3 100644 --- a/src/cdk-experimental/dialog/dialog.ts +++ b/src/cdk-experimental/dialog/dialog.ts @@ -72,9 +72,9 @@ export class Dialog implements OnDestroy { _openDialogs: DialogRef[] = []; constructor( - private overlay: Overlay, - private injector: Injector, - @Inject(DIALOG_REF) private dialogRefConstructor: Type>, + private _overlay: Overlay, + private _injector: Injector, + @Inject(DIALOG_REF) private _dialogRefConstructor: Type>, // 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): void { + private _registerDialogRef(dialogRef: DialogRef): 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(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(componentOrTemplateRef, null!, @@ -284,8 +284,8 @@ export class Dialog implements OnDestroy { const userInjector = config && config.viewContainerRef && config.viewContainerRef.injector; const injectionTokens = new WeakMap([ - [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}; } } diff --git a/src/cdk/layout/breakpoints-observer.spec.ts b/src/cdk/layout/breakpoints-observer.spec.ts index d215dfdcf3d4..22ac426eb9bc 100644 --- a/src/cdk/layout/breakpoints-observer.spec.ts +++ b/src/cdk/layout/breakpoints-observer.spec.ts @@ -193,29 +193,29 @@ export class FakeMediaQueryList { @Injectable() export class FakeMediaMatcher { /** A map of match media queries. */ - private queries = new Map(); + private _queries = new Map(); /** 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.'); } diff --git a/src/cdk/layout/breakpoints-observer.ts b/src/cdk/layout/breakpoints-observer.ts index ae6b7a9a56e3..4555d41692b3 100644 --- a/src/cdk/layout/breakpoints-observer.ts +++ b/src/cdk/layout/breakpoints-observer.ts @@ -47,7 +47,7 @@ export class BreakpointObserver implements OnDestroy { /** A subject for all other observables to takeUntil based on. */ private _destroySubject = new Subject(); - 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((observer: Observer) => { @@ -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 () => { diff --git a/src/cdk/layout/media-matcher.ts b/src/cdk/layout/media-matcher.ts index aaeb1bade75f..25983e73d917 100644 --- a/src/cdk/layout/media-matcher.ts +++ b/src/cdk/layout/media-matcher.ts @@ -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); diff --git a/src/cdk/overlay/position/flexible-connected-position-strategy.ts b/src/cdk/overlay/position/flexible-connected-position-strategy.ts index f908661a1fe6..6b99e2124833 100644 --- a/src/cdk/overlay/position/flexible-connected-position-strategy.ts +++ b/src/cdk/overlay/position/flexible-connected-position-strategy.ts @@ -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(); }); diff --git a/src/cdk/table/sticky-styler.ts b/src/cdk/table/sticky-styler.ts index f0fca155b406..b1d392c8b12a 100644 --- a/src/cdk/table/sticky-styler.ts +++ b/src/cdk/table/sticky-styler.ts @@ -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 `` 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); diff --git a/src/cdk/table/text-column.ts b/src/cdk/table/text-column.ts index 5418d4095554..a65abffe7996 100644 --- a/src/cdk/table/text-column.ts +++ b/src/cdk/table/text-column.ts @@ -121,9 +121,9 @@ export class CdkTextColumn implements OnDestroy, OnInit { @ViewChild(CdkHeaderCellDef, {static: true}) headerCell: CdkHeaderCellDef; constructor( - @Optional() private table: CdkTable, - @Optional() @Inject(TEXT_COLUMN_OPTIONS) private options: TextColumnOptions) { - this.options = options || {}; + @Optional() private _table: CdkTable, + @Optional() @Inject(TEXT_COLUMN_OPTIONS) private _options: TextColumnOptions) { + this._options = _options || {}; } ngOnInit() { @@ -133,24 +133,24 @@ export class CdkTextColumn 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 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); diff --git a/src/dev-app/bottom-sheet/bottom-sheet-demo.ts b/src/dev-app/bottom-sheet/bottom-sheet-demo.ts index dff9f74f9a5e..f5558aba33b1 100644 --- a/src/dev-app/bottom-sheet/bottom-sheet-demo.ts +++ b/src/dev-app/bottom-sheet/bottom-sheet-demo.ts @@ -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(); } } diff --git a/src/dev-app/live-announcer/live-announcer-demo.ts b/src/dev-app/live-announcer/live-announcer-demo.ts index 5ac00de1807f..771836a98aee 100644 --- a/src/dev-app/live-announcer/live-announcer-demo.ts +++ b/src/dev-app/live-announcer/live-announcer-demo.ts @@ -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); } } diff --git a/src/dev-app/progress-bar/progress-bar-demo.ts b/src/dev-app/progress-bar/progress-bar-demo.ts index 1d9db4663aa0..20038ee88934 100644 --- a/src/dev-app/progress-bar/progress-bar-demo.ts +++ b/src/dev-app/progress-bar/progress-bar-demo.ts @@ -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)); } } diff --git a/src/dev-app/screen-type/screen-type-demo.ts b/src/dev-app/screen-type/screen-type-demo.ts index f8c845d1c084..e4f3a914dd5c 100644 --- a/src/dev-app/screen-type/screen-type-demo.ts +++ b/src/dev-app/screen-type/screen-type-demo.ts @@ -24,13 +24,13 @@ export class ScreenTypeDemo { isPortrait: Observable; isLandscape: Observable; - 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)'); } } diff --git a/src/dev-app/snack-bar/snack-bar-demo.ts b/src/dev-app/snack-bar/snack-bar-demo.ts index 4e89b786035d..1c43135625df 100644 --- a/src/dev-app/snack-bar/snack-bar-demo.ts +++ b/src/dev-app/snack-bar/snack-bar-demo.ts @@ -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; } } diff --git a/src/dev-app/tree/checklist-tree-demo/checklist-nested-tree-demo.ts b/src/dev-app/tree/checklist-tree-demo/checklist-nested-tree-demo.ts index 5bb05ac243f5..10c880a505e9 100644 --- a/src/dev-app/tree/checklist-tree-demo/checklist-nested-tree-demo.ts +++ b/src/dev-app/tree/checklist-tree-demo/checklist-nested-tree-demo.ts @@ -31,9 +31,9 @@ export class ChecklistNestedTreeDemo { /** The selection for checklist */ checklistSelection = new SelectionModel(true /* multiple */); - constructor(private database: ChecklistDatabase, private changeDetectorRef: ChangeDetectorRef) { + constructor(private _database: ChecklistDatabase, private _changeDetectorRef: ChangeDetectorRef) { this.treeControl = new NestedTreeControl(this.getChildren); - this.dataSource = database.data; + this.dataSource = _database.data; } getChildren = (node: TodoItemNode): Observable => 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); } } diff --git a/src/dev-app/tree/checklist-tree-demo/checklist-tree-demo.ts b/src/dev-app/tree/checklist-tree-demo/checklist-tree-demo.ts index 758919bf6eb5..b7025fc63327 100644 --- a/src/dev-app/tree/checklist-tree-demo/checklist-tree-demo.ts +++ b/src/dev-app/tree/checklist-tree-demo/checklist-tree-demo.ts @@ -35,14 +35,14 @@ export class ChecklistTreeDemo { /** The selection for checklist */ checklistSelection = new SelectionModel(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( 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); } } diff --git a/src/dev-app/tree/dynamic-tree-demo/dynamic-database.ts b/src/dev-app/tree/dynamic-tree-demo/dynamic-database.ts index 29d7522578cf..c51d609e4243 100644 --- a/src/dev-app/tree/dynamic-tree-demo/dynamic-database.ts +++ b/src/dev-app/tree/dynamic-tree-demo/dynamic-database.ts @@ -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, - private database: DynamicDatabase) {} + constructor(private _treeControl: FlatTreeControl, + private _database: DynamicDatabase) {} connect(collectionViewer: CollectionViewer): Observable { - 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; diff --git a/src/dev-app/tree/loadmore-tree-demo/loadmore-tree-demo.ts b/src/dev-app/tree/loadmore-tree-demo/loadmore-tree-demo.ts index bc9605175ebd..592661714f06 100644 --- a/src/dev-app/tree/loadmore-tree-demo/loadmore-tree-demo.ts +++ b/src/dev-app/tree/loadmore-tree-demo/loadmore-tree-demo.ts @@ -37,7 +37,7 @@ export class LoadmoreTreeDemo { // Flat tree data source dataSource: MatTreeFlatDataSource; - 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 => { 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); } } diff --git a/src/material-examples/autocomplete-optgroup/autocomplete-optgroup-example.ts b/src/material-examples/autocomplete-optgroup/autocomplete-optgroup-example.ts index 862f40097355..a9cf8988fd24 100644 --- a/src/material-examples/autocomplete-optgroup/autocomplete-optgroup-example.ts +++ b/src/material-examples/autocomplete-optgroup/autocomplete-optgroup-example.ts @@ -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; - constructor(private fb: FormBuilder) {} + constructor(private _formBuilder: FormBuilder) {} ngOnInit() { this.stateGroupOptions = this.stateForm.get('stateGroup')!.valueChanges diff --git a/src/material-examples/bottom-sheet-overview/bottom-sheet-overview-example.ts b/src/material-examples/bottom-sheet-overview/bottom-sheet-overview-example.ts index 1ca0cd424174..5fa4ea4a4901 100644 --- a/src/material-examples/bottom-sheet-overview/bottom-sheet-overview-example.ts +++ b/src/material-examples/bottom-sheet-overview/bottom-sheet-overview-example.ts @@ -10,10 +10,10 @@ import {MatBottomSheet, MatBottomSheetRef} from '@angular/material'; 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) {} + constructor(private _bottomSheetRef: MatBottomSheetRef) {} openLink(event: MouseEvent): void { - this.bottomSheetRef.dismiss(); + this._bottomSheetRef.dismiss(); event.preventDefault(); } } diff --git a/src/material-examples/cdk-virtual-scroll-data-source/cdk-virtual-scroll-data-source-example.ts b/src/material-examples/cdk-virtual-scroll-data-source/cdk-virtual-scroll-data-source-example.ts index c610ad424e86..e53cac202053 100644 --- a/src/material-examples/cdk-virtual-scroll-data-source/cdk-virtual-scroll-data-source-example.ts +++ b/src/material-examples/cdk-virtual-scroll-data-source/cdk-virtual-scroll-data-source-example.ts @@ -14,44 +14,44 @@ export class CdkVirtualScrollDataSourceExample { } export class MyDataSource extends DataSource { - private length = 100000; - private pageSize = 100; - private cachedData = Array.from({length: this.length}); - private fetchedPages = new Set(); - private dataStream = new BehaviorSubject<(string | undefined)[]>(this.cachedData); - private subscription = new Subscription(); + private _length = 100000; + private _pageSize = 100; + private _cachedData = Array.from({length: this._length}); + private _fetchedPages = new Set(); + 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); } } diff --git a/src/material-examples/datepicker-custom-header/datepicker-custom-header-example.ts b/src/material-examples/datepicker-custom-header/datepicker-custom-header-example.ts index 2a3380179132..c1770cc550c6 100644 --- a/src/material-examples/datepicker-custom-header/datepicker-custom-header-example.ts +++ b/src/material-examples/datepicker-custom-header/datepicker-custom-header-example.ts @@ -63,36 +63,36 @@ export class DatepickerCustomHeaderExample { changeDetection: ChangeDetectionStrategy.OnPush, }) export class ExampleHeader implements OnDestroy { - private destroyed = new Subject(); + private _destroyed = new Subject(); constructor( - private calendar: MatCalendar, private dateAdapter: DateAdapter, - @Inject(MAT_DATE_FORMATS) private dateFormats: MatDateFormats, cdr: ChangeDetectorRef) { - calendar.stateChanges - .pipe(takeUntil(this.destroyed)) + private _calendar: MatCalendar, private _dateAdapter: DateAdapter, + @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); } } diff --git a/src/material-examples/datepicker-locale/datepicker-locale-example.ts b/src/material-examples/datepicker-locale/datepicker-locale-example.ts index c99ee56aba53..fc4af21698c9 100644 --- a/src/material-examples/datepicker-locale/datepicker-locale-example.ts +++ b/src/material-examples/datepicker-locale/datepicker-locale-example.ts @@ -20,9 +20,9 @@ import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/ ], }) export class DatepickerLocaleExample { - constructor(private adapter: DateAdapter) {} + constructor(private _adapter: DateAdapter) {} french() { - this.adapter.setLocale('fr'); + this._adapter.setLocale('fr'); } } diff --git a/src/material-examples/focus-monitor-directives/focus-monitor-directives-example.ts b/src/material-examples/focus-monitor-directives/focus-monitor-directives-example.ts index 35ce0309f18f..682c174a7b9d 100644 --- a/src/material-examples/focus-monitor-directives/focus-monitor-directives-example.ts +++ b/src/material-examples/focus-monitor-directives/focus-monitor-directives-example.ts @@ -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()); } } diff --git a/src/material-examples/focus-monitor-focus-via/focus-monitor-focus-via-example.ts b/src/material-examples/focus-monitor-focus-via/focus-monitor-focus-via-example.ts index 39b6707d46fc..65a01eb8e3e5 100644 --- a/src/material-examples/focus-monitor-focus-via/focus-monitor-focus-via-example.ts +++ b/src/material-examples/focus-monitor-focus-via/focus-monitor-focus-via-example.ts @@ -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(); })); } diff --git a/src/material-examples/focus-monitor-overview/focus-monitor-overview-example.ts b/src/material-examples/focus-monitor-overview/focus-monitor-overview-example.ts index fa9129bcdba1..3290c5076d0f 100644 --- a/src/material-examples/focus-monitor-overview/focus-monitor-overview-example.ts +++ b/src/material-examples/focus-monitor-overview/focus-monitor-overview-example.ts @@ -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 { diff --git a/src/material-examples/form-field-custom-control/form-field-custom-control-example.ts b/src/material-examples/form-field-custom-control/form-field-custom-control-example.ts index a1716eb7b033..a19d173bc33d 100644 --- a/src/material-examples/form-field-custom-control/form-field-custom-control-example.ts +++ b/src/material-examples/form-field-custom-control/form-field-custom-control-example.ts @@ -91,18 +91,18 @@ export class MyTelInput implements ControlValueAccessor, MatFormFieldControl, + formBuilder: FormBuilder, + private _focusMonitor: FocusMonitor, + private _elementRef: ElementRef, @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 this.paginator.pageIndex = 0); @@ -72,13 +72,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 { 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(requestUrl); + return this._httpClient.get(requestUrl); } } diff --git a/src/material-examples/text-field-autofill-monitor/text-field-autofill-monitor-example.ts b/src/material-examples/text-field-autofill-monitor/text-field-autofill-monitor-example.ts index 145e58290f60..6d8f5713822a 100644 --- a/src/material-examples/text-field-autofill-monitor/text-field-autofill-monitor-example.ts +++ b/src/material-examples/text-field-autofill-monitor/text-field-autofill-monitor-example.ts @@ -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); } } diff --git a/src/material-examples/text-field-autosize-textarea/text-field-autosize-textarea-example.ts b/src/material-examples/text-field-autosize-textarea/text-field-autosize-textarea-example.ts index af33c8b31966..bd03fd26c030 100644 --- a/src/material-examples/text-field-autosize-textarea/text-field-autosize-textarea-example.ts +++ b/src/material-examples/text-field-autosize-textarea/text-field-autosize-textarea-example.ts @@ -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)); } } diff --git a/src/material-examples/tree-checklist/tree-checklist-example.ts b/src/material-examples/tree-checklist/tree-checklist-example.ts index b3c1461cc4b6..6e5f1d1cb497 100644 --- a/src/material-examples/tree-checklist/tree-checklist-example.ts +++ b/src/material-examples/tree-checklist/tree-checklist-example.ts @@ -131,13 +131,13 @@ export class TreeChecklistExample { /** The selection for checklist */ checklistSelection = new SelectionModel(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(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); } } diff --git a/src/material-examples/tree-dynamic/tree-dynamic-example.ts b/src/material-examples/tree-dynamic/tree-dynamic-example.ts index 7933e19e6bdf..a00cdbbe1ad0 100644 --- a/src/material-examples/tree-dynamic/tree-dynamic-example.ts +++ b/src/material-examples/tree-dynamic/tree-dynamic-example.ts @@ -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, - private database: DynamicDatabase) {} + constructor(private _treeControl: FlatTreeControl, + private _database: DynamicDatabase) {} connect(collectionViewer: CollectionViewer): Observable { - this.treeControl.expansionModel.onChange.subscribe(change => { + this._treeControl.expansionModel.onChange.subscribe(change => { if ((change as SelectionChange).added || (change as SelectionChange).removed) { this.handleTreeControl(change as SelectionChange); @@ -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; diff --git a/src/material-examples/tree-flat-overview/tree-flat-overview-example.ts b/src/material-examples/tree-flat-overview/tree-flat-overview-example.ts index 0f99a7f14ae3..fd610f208f1a 100644 --- a/src/material-examples/tree-flat-overview/tree-flat-overview-example.ts +++ b/src/material-examples/tree-flat-overview/tree-flat-overview-example.ts @@ -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); diff --git a/src/material-examples/tree-loadmore/tree-loadmore-example.ts b/src/material-examples/tree-loadmore/tree-loadmore-example.ts index 0c958a8a97d4..de7bc6855e30 100644 --- a/src/material-examples/tree-loadmore/tree-loadmore-example.ts +++ b/src/material-examples/tree-loadmore/tree-loadmore-example.ts @@ -105,7 +105,7 @@ export class TreeLoadmoreExample { // Flat tree data source dataSource: MatTreeFlatDataSource; - 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 => 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); } } diff --git a/src/material-experimental/mdc-menu/menu.spec.ts b/src/material-experimental/mdc-menu/menu.spec.ts index d6985647b3d9..4e6ed3a5c12b 100644 --- a/src/material-experimental/mdc-menu/menu.spec.ts +++ b/src/material-experimental/mdc-menu/menu.spec.ts @@ -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; } } diff --git a/src/material-experimental/mdc-slide-toggle/slide-toggle.ts b/src/material-experimental/mdc-slide-toggle/slide-toggle.ts index 6947473eb7d1..df7a5ec2731f 100644 --- a/src/material-experimental/mdc-slide-toggle/slide-toggle.ts +++ b/src/material-experimental/mdc-slide-toggle/slide-toggle.ts @@ -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(); }); } diff --git a/src/material-moment-adapter/adapter/moment-date-adapter.ts b/src/material-moment-adapter/adapter/moment-date-adapter.ts index ea05ecb63f76..12a35fb1ac45 100644 --- a/src/material-moment-adapter/adapter/moment-date-adapter.ts +++ b/src/material-moment-adapter/adapter/moment-date-adapter.ts @@ -75,7 +75,7 @@ export class MomentDateAdapter extends DateAdapter { 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 { /** 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); } } diff --git a/src/material/core/ripple/ripple-renderer.ts b/src/material/core/ripple/ripple-renderer.ts index 8c5d3e700aa3..e6cc5e872773 100644 --- a/src/material/core/ripple/ripple-renderer.ts +++ b/src/material/core/ripple/ripple-renderer.ts @@ -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)); } diff --git a/src/material/menu/menu.spec.ts b/src/material/menu/menu.spec.ts index 6207d00a129d..dc6d7f78b8c3 100644 --- a/src/material/menu/menu.spec.ts +++ b/src/material/menu/menu.spec.ts @@ -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; } } diff --git a/src/material/progress-bar/progress-bar.ts b/src/material/progress-bar/progress-bar.ts index 1177d1920684..ae3ccf4c683e 100644 --- a/src/material/progress-bar/progress-bar.ts +++ b/src/material/progress-bar/progress-bar.ts @@ -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) .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}); } diff --git a/src/material/progress-spinner/progress-spinner.ts b/src/material/progress-spinner/progress-spinner.ts index 106dddaa95a3..b1b3375f6349 100644 --- a/src/material/progress-spinner/progress-spinner.ts +++ b/src/material/progress-spinner/progress-spinner.ts @@ -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([BASE_SIZE]); + private static _diameters = new Set([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. */ diff --git a/src/material/slide-toggle/slide-toggle.ts b/src/material/slide-toggle/slide-toggle.ts index 9d621fc5713b..978b7218fbd8 100644 --- a/src/material/slide-toggle/slide-toggle.ts +++ b/src/material/slide-toggle/slide-toggle.ts @@ -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)); } diff --git a/src/material/tree/data-source/flat-data-source.ts b/src/material/tree/data-source/flat-data-source.ts index fce72e2cb63a..76f9aca8af4f 100644 --- a/src/material/tree/data-source/flat-data-source.ts +++ b/src/material/tree/data-source/flat-data-source.ts @@ -135,12 +135,12 @@ export class MatTreeFlatDataSource extends DataSource { 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, - private treeFlattener: MatTreeFlattener, + constructor(private _treeControl: FlatTreeControl, + private _treeFlattener: MatTreeFlattener, initialData: T[] = []) { super(); this._data = new BehaviorSubject(initialData); @@ -149,12 +149,12 @@ export class MatTreeFlatDataSource extends DataSource { connect(collectionViewer: CollectionViewer): Observable { 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; })); } diff --git a/src/material/tree/tree.spec.ts b/src/material/tree/tree.spec.ts index 49c76ccd0668..0b9265936bc1 100644 --- a/src/material/tree/tree.spec.ts +++ b/src/material/tree/tree.spec.ts @@ -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; constructor() { - this.treeControl = new NestedTreeControl(this.getChildren); + this.treeControl = new NestedTreeControl(this._getChildren); this.dataSource = new MatTreeNestedDataSource(); this.dataSource.data = TREE_DATA; } - private getChildren = (node: FoodNode) => node.children; + private _getChildren = (node: FoodNode) => node.children; } @Component({ diff --git a/tools/dgeni/processors/categorizer.ts b/tools/dgeni/processors/categorizer.ts index 573f37582173..49cf3b3535c8 100644 --- a/tools/dgeni/processors/categorizer.ts +++ b/tools/dgeni/processors/categorizer.ts @@ -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) => { diff --git a/tools/dgeni/processors/docs-private-filter.ts b/tools/dgeni/processors/docs-private-filter.ts index 69159b587342..2dbc39f7bcd0 100644 --- a/tools/dgeni/processors/docs-private-filter.ts +++ b/tools/dgeni/processors/docs-private-filter.ts @@ -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; } diff --git a/tools/dgeni/processors/merge-inherited-properties.ts b/tools/dgeni/processors/merge-inherited-properties.ts index 346bf8fd5056..6925cf5356f3 100644 --- a/tools/dgeni/processors/merge-inherited-properties.ts +++ b/tools/dgeni/processors/merge-inherited-properties.ts @@ -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 diff --git a/tools/package-tools/build-bundles.ts b/tools/package-tools/build-bundles.ts index 7f76e250318a..64bff96231db 100644 --- a/tools/package-tools/build-bundles.ts +++ b/tools/package-tools/build-bundles.ts @@ -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)}`; diff --git a/tools/package-tools/build-package.ts b/tools/package-tools/build-package.ts index 4979829dd689..ecabb414e361 100644 --- a/tools/package-tools/build-package.ts +++ b/tools/package-tools/build-package.ts @@ -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 = diff --git a/tools/public_api_guard/cdk/layout.d.ts b/tools/public_api_guard/cdk/layout.d.ts index 16c0873b3e34..ccb5d8c6f248 100644 --- a/tools/public_api_guard/cdk/layout.d.ts +++ b/tools/public_api_guard/cdk/layout.d.ts @@ -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; @@ -33,6 +33,6 @@ export declare class LayoutModule { } export declare class MediaMatcher { - constructor(platform: Platform); + constructor(_platform: Platform); matchMedia(query: string): MediaQueryList; } diff --git a/tools/public_api_guard/cdk/table.d.ts b/tools/public_api_guard/cdk/table.d.ts index c4f06a3bd0eb..52203aa8c207 100644 --- a/tools/public_api_guard/cdk/table.d.ts +++ b/tools/public_api_guard/cdk/table.d.ts @@ -173,7 +173,7 @@ export declare class CdkTextColumn implements OnDestroy, OnInit { headerText: string; justify: 'start' | 'end'; name: string; - constructor(table: CdkTable, options: TextColumnOptions); + constructor(_table: CdkTable, _options: TextColumnOptions); _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[]; diff --git a/tools/public_api_guard/material/tree.d.ts b/tools/public_api_guard/material/tree.d.ts index 36fdda3d91f4..3a55f4234983 100644 --- a/tools/public_api_guard/material/tree.d.ts +++ b/tools/public_api_guard/material/tree.d.ts @@ -18,7 +18,7 @@ export declare class MatTreeFlatDataSource extends DataSource { _expandedData: BehaviorSubject; _flattenedData: BehaviorSubject; data: T[]; - constructor(treeControl: FlatTreeControl, treeFlattener: MatTreeFlattener, initialData?: T[]); + constructor(_treeControl: FlatTreeControl, _treeFlattener: MatTreeFlattener, initialData?: T[]); connect(collectionViewer: CollectionViewer): Observable; disconnect(): void; } diff --git a/tools/release/publish-release.ts b/tools/release/publish-release.ts index 10226b87ece2..1b5ab3df617f 100644 --- a/tools/release/publish-release.ts +++ b/tools/release/publish-release.ts @@ -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()); diff --git a/tools/release/stage-release.ts b/tools/release/stage-release.ts index bfd99b0bd85c..8f5d92879d2b 100644 --- a/tools/release/stage-release.ts +++ b/tools/release/stage-release.ts @@ -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); diff --git a/tools/tslint-rules/memberNamingRule.ts b/tools/tslint-rules/memberNamingRule.ts new file mode 100644 index 000000000000..0e1e266587fe --- /dev/null +++ b/tools/tslint-rules/memberNamingRule.ts @@ -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); + } + } + } +} diff --git a/tslint.json b/tslint.json index 28d425438ade..730f3896d165 100644 --- a/tslint.json +++ b/tslint.json @@ -107,6 +107,9 @@ "HostBinding", "HostListener" ], + "member-naming": [true, { + "private": "^_" + }], "validate-decorators": [true, { "Component": { "!host": "\\[class\\]",