Skip to content

feat(data-table): add row context #5219

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 22, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions src/demo-app/data-table/data-table-demo.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
<div class="demo-data-source-actions">
<button md-raised-button (click)="connect()">Connect New Data Source</button>
<button md-raised-button (click)="disconnect()" [disabled]="!dataSource">Disconnect Data Source</button>
<div>
<button md-raised-button (click)="connect()">Connect New Data Source</button>
<button md-raised-button (click)="disconnect()" [disabled]="!dataSource">Disconnect Data Source</button>
</div>

<div class="demo-highlighter">
Highlight:
<md-checkbox (change)="toggleHighlight('first', $event.checked)">First Row</md-checkbox>
<md-checkbox (change)="toggleHighlight('last', $event.checked)">Last Row</md-checkbox>
<md-checkbox (change)="toggleHighlight('even', $event.checked)">Even Rows</md-checkbox>
<md-checkbox (change)="toggleHighlight('odd', $event.checked)">Odd Rows</md-checkbox>
</div>
</div>

<div class="demo-table-container mat-elevation-z4">
Expand Down Expand Up @@ -44,6 +54,14 @@
</ng-container>

<cdk-header-row *cdkHeaderRowDef="propertiesToDisplay"></cdk-header-row>
<cdk-row *cdkRowDef="let row; columns: propertiesToDisplay"></cdk-row>
<cdk-row *cdkRowDef="let row; columns: propertiesToDisplay;
let first = first; let last = last; let even = even; let odd = odd"
[ngClass]="{
'demo-row-highlight-first': highlights.has('first') && first,
'demo-row-highlight-last': highlights.has('last') && last,
'demo-row-highlight-even': highlights.has('even') && even,
'demo-row-highlight-odd': highlights.has('odd') && odd
}">
</cdk-row>
</cdk-table>
</div>
13 changes: 12 additions & 1 deletion src/demo-app/data-table/data-table-demo.scss
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,20 @@
}

.demo-data-source-actions {
margin: 16px 0;
& > div {
margin: 16px 0;
}

.demo-highlighter .mat-checkbox {
margin: 0 8px;
}
}

.demo-row-highlight-first { background: #f3f315; }
.demo-row-highlight-last { background: #0dd5fc; }
.demo-row-highlight-even { background: #ff0099; }
.demo-row-highlight-odd { background: #83f52c; }

/*
* Styles to make the demo's cdk-table match the material design spec
* https://material.io/guidelines/components/data-tables.html
Expand Down
5 changes: 5 additions & 0 deletions src/demo-app/data-table/data-table-demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export type UserProperties = 'userId' | 'userName' | 'progress' | 'color' | unde
export class DataTableDemo {
dataSource: PersonDataSource | null;
propertiesToDisplay: UserProperties[] = [];
highlights = new Set<string>();

constructor(private _peopleDatabase: PeopleDatabase) {
this.connect();
Expand Down Expand Up @@ -42,4 +43,8 @@ export class DataTableDemo {
this.propertiesToDisplay.splice(colorColumnIndex, 1);
}
}

toggleHighlight(property: string, enable: boolean) {
enable ? this.highlights.add(property) : this.highlights.delete(property);
}
}
130 changes: 128 additions & 2 deletions src/lib/core/data-table/data-table.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,16 @@ describe('CdkTable', () => {

TestBed.configureTestingModule({
imports: [CdkDataTableModule],
declarations: [SimpleCdkTableApp, DynamicDataSourceCdkTableApp, CustomRoleCdkTableApp],
declarations: [
SimpleCdkTableApp,
DynamicDataSourceCdkTableApp,
CustomRoleCdkTableApp,
RowContextCdkTableApp
],
}).compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(SimpleCdkTableApp);

component = fixture.componentInstance;
Expand All @@ -33,7 +40,7 @@ describe('CdkTable', () => {

fixture.detectChanges(); // Let the component and table create embedded views
fixture.detectChanges(); // Let the cells render
}));
});

describe('should initialize', () => {
it('with a connected data source', () => {
Expand Down Expand Up @@ -153,6 +160,7 @@ describe('CdkTable', () => {
// Add data to the table and recreate what the rendered output should be.
dataSource.addData();
expect(dataSource.data.length).toBe(initialDataLength + 1); // Make sure data was added
fixture.detectChanges();

data = dataSource.data;
expect(tableElement).toMatchTableContent([
Expand Down Expand Up @@ -198,6 +206,88 @@ describe('CdkTable', () => {
]);
});

it('should be able to apply classes to rows based on their context', () => {
const contextFixture = TestBed.createComponent(RowContextCdkTableApp);
const contextComponent = contextFixture.componentInstance;
tableElement = contextFixture.nativeElement.querySelector('cdk-table');

contextFixture.detectChanges(); // Let the table initialize its view
contextFixture.detectChanges(); // Let the table render the rows and cells

const rowElements = contextFixture.nativeElement.querySelectorAll('cdk-row');

// Rows should not have any context classes
for (let i = 0; i < rowElements.length; i++) {
expect(rowElements[i].classList.contains('custom-row-class-first')).toBe(false);
expect(rowElements[i].classList.contains('custom-row-class-last')).toBe(false);
expect(rowElements[i].classList.contains('custom-row-class-even')).toBe(false);
expect(rowElements[i].classList.contains('custom-row-class-odd')).toBe(false);
}

// Enable all the context classes
contextComponent.enableRowContextClasses = true;
contextFixture.detectChanges();

expect(rowElements[0].classList.contains('custom-row-class-first')).toBe(true);
expect(rowElements[0].classList.contains('custom-row-class-last')).toBe(false);
expect(rowElements[0].classList.contains('custom-row-class-even')).toBe(true);
expect(rowElements[0].classList.contains('custom-row-class-odd')).toBe(false);

expect(rowElements[1].classList.contains('custom-row-class-first')).toBe(false);
expect(rowElements[1].classList.contains('custom-row-class-last')).toBe(false);
expect(rowElements[1].classList.contains('custom-row-class-even')).toBe(false);
expect(rowElements[1].classList.contains('custom-row-class-odd')).toBe(true);

expect(rowElements[2].classList.contains('custom-row-class-first')).toBe(false);
expect(rowElements[2].classList.contains('custom-row-class-last')).toBe(true);
expect(rowElements[2].classList.contains('custom-row-class-even')).toBe(true);
expect(rowElements[2].classList.contains('custom-row-class-odd')).toBe(false);
});

it('should be able to apply classes to cells based on their row context', () => {
const contextFixture = TestBed.createComponent(RowContextCdkTableApp);
const contextComponent = contextFixture.componentInstance;
tableElement = contextFixture.nativeElement.querySelector('cdk-table');

contextFixture.detectChanges(); // Let the table initialize its view
contextFixture.detectChanges(); // Let the table render the rows and cells

const rowElements = contextFixture.nativeElement.querySelectorAll('cdk-row');

for (let i = 0; i < rowElements.length; i++) {
// Cells should not have any context classes
const cellElements = rowElements[i].querySelectorAll('cdk-cell');
for (let j = 0; j < cellElements.length; j++) {
expect(cellElements[j].classList.contains('custom-cell-class-first')).toBe(false);
expect(cellElements[j].classList.contains('custom-cell-class-last')).toBe(false);
expect(cellElements[j].classList.contains('custom-cell-class-even')).toBe(false);
expect(cellElements[j].classList.contains('custom-cell-class-odd')).toBe(false);
}
}

// Enable the context classes
contextComponent.enableCellContextClasses = true;
contextFixture.detectChanges();

let cellElement = rowElements[0].querySelectorAll('cdk-cell')[0];
expect(cellElement.classList.contains('custom-cell-class-first')).toBe(true);
expect(cellElement.classList.contains('custom-cell-class-last')).toBe(false);
expect(cellElement.classList.contains('custom-cell-class-even')).toBe(true);
expect(cellElement.classList.contains('custom-cell-class-odd')).toBe(false);

cellElement = rowElements[1].querySelectorAll('cdk-cell')[0];
expect(cellElement.classList.contains('custom-cell-class-first')).toBe(false);
expect(cellElement.classList.contains('custom-cell-class-last')).toBe(false);
expect(cellElement.classList.contains('custom-cell-class-even')).toBe(false);
expect(cellElement.classList.contains('custom-cell-class-odd')).toBe(true);

cellElement = rowElements[2].querySelectorAll('cdk-cell')[0];
expect(cellElement.classList.contains('custom-cell-class-first')).toBe(false);
expect(cellElement.classList.contains('custom-cell-class-last')).toBe(true);
expect(cellElement.classList.contains('custom-cell-class-even')).toBe(true);
expect(cellElement.classList.contains('custom-cell-class-odd')).toBe(false);
});

it('should be able to dynamically change the columns for header and rows', () => {
expect(dataSource.data.length).toBe(3);

Expand Down Expand Up @@ -336,6 +426,42 @@ class CustomRoleCdkTableApp {
@ViewChild(CdkTable) table: CdkTable<TestData>;
}

@Component({
template: `
<cdk-table [dataSource]="dataSource">
<ng-container cdkColumnDef="column_a">
<cdk-header-cell *cdkHeaderCellDef> Column A</cdk-header-cell>
<cdk-cell *cdkCellDef="let row; let first = first;
let last = last; let even = even; let odd = odd"
[ngClass]="{
'custom-cell-class-first': enableCellContextClasses && first,
'custom-cell-class-last': enableCellContextClasses && last,
'custom-cell-class-even': enableCellContextClasses && even,
'custom-cell-class-odd': enableCellContextClasses && odd
}">
{{row.a}}
</cdk-cell>
</ng-container>
<cdk-header-row *cdkHeaderRowDef="columnsToRender"></cdk-header-row>
<cdk-row *cdkRowDef="let row; columns: columnsToRender;
let first = first; let last = last; let even = even; let odd = odd"
[ngClass]="{
'custom-row-class-first': enableRowContextClasses && first,
'custom-row-class-last': enableRowContextClasses && last,
'custom-row-class-even': enableRowContextClasses && even,
'custom-row-class-odd': enableRowContextClasses && odd
}">
</cdk-row>
</cdk-table>
`
})
class RowContextCdkTableApp {
dataSource: FakeDataSource = new FakeDataSource();
columnsToRender = ['column_a'];
enableRowContextClasses = false;
enableCellContextClasses = false;
}

function getElements(element: Element, query: string): Element[] {
return [].slice.call(element.querySelectorAll(query));
}
Expand Down
56 changes: 42 additions & 14 deletions src/lib/core/data-table/data-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
ContentChildren,
Directive,
ElementRef,
EmbeddedViewRef,
Input,
IterableChangeRecord,
IterableDiffer,
Expand All @@ -27,15 +28,15 @@ import {
ViewEncapsulation
} from '@angular/core';
import {CollectionViewer, DataSource} from './data-source';
import {BaseRowDef, CdkCellOutlet, CdkHeaderRowDef, CdkRowDef} from './row';
import {CdkCellDef, CdkColumnDef, CdkHeaderCellDef} from './cell';
import {CdkCellOutlet, CdkCellOutletRowContext, CdkHeaderRowDef, CdkRowDef} from './row';
import {Observable} from 'rxjs/Observable';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/let';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/observable/combineLatest';
import {Subscription} from 'rxjs/Subscription';
import {Subject} from 'rxjs/Subject';
import {CdkCellDef, CdkColumnDef, CdkHeaderCellDef} from './cell';

/**
* Returns an error to be thrown when attempting to find an unexisting column.
Expand Down Expand Up @@ -198,13 +199,14 @@ export class CdkTable<T> implements CollectionViewer {
}

ngAfterViewInit() {
this._isViewInitialized = true;
this._renderHeaderRow();
}

if (this.dataSource) {
ngDoCheck() {
if (this._isViewInitialized && this.dataSource && !this._renderChangeSubscription) {
this._observeRenderChanges();
}

this._isViewInitialized = true;
}

/**
Expand Down Expand Up @@ -251,8 +253,10 @@ export class CdkTable<T> implements CollectionViewer {
// of `createEmbeddedView`.
this._headerRowPlaceholder.viewContainer
.createEmbeddedView(this._headerDefinition.template, {cells});
CdkCellOutlet.mostRecentCellOutlet.cells = cells;
CdkCellOutlet.mostRecentCellOutlet.context = {};

cells.forEach(cell => {
CdkCellOutlet.mostRecentCellOutlet._viewContainer.createEmbeddedView(cell.template, {});
});

this._changeDetectorRef.markForCheck();
}
Expand All @@ -262,17 +266,20 @@ export class CdkTable<T> implements CollectionViewer {
const changes = this._dataDiffer.diff(this._data);
if (!changes) { return; }

const viewContainer = this._rowPlaceholder.viewContainer;
changes.forEachOperation(
(item: IterableChangeRecord<any>, adjustedPreviousIndex: number, currentIndex: number) => {
if (item.previousIndex == null) {
this._insertRow(this._data[currentIndex], currentIndex);
} else if (currentIndex == null) {
this._rowPlaceholder.viewContainer.remove(adjustedPreviousIndex);
viewContainer.remove(adjustedPreviousIndex);
} else {
const view = this._rowPlaceholder.viewContainer.get(adjustedPreviousIndex);
this._rowPlaceholder.viewContainer.move(view!, currentIndex);
const view = viewContainer.get(adjustedPreviousIndex);
viewContainer.move(view!, currentIndex);
}
});

this._updateRowContext();
}

/**
Expand All @@ -285,20 +292,41 @@ export class CdkTable<T> implements CollectionViewer {
// the data rather than choosing the first row definition.
const row = this._rowDefinitions.first;

// TODO(andrewseguin): Add more context, such as first/last/isEven/etc
const context = {$implicit: rowData};
// Row context that will be provided to both the created embedded row view and its cells.
const context: CdkCellOutletRowContext<T> = {$implicit: rowData};

// TODO(andrewseguin): add some code to enforce that exactly one
// CdkCellOutlet was instantiated as a result of `createEmbeddedView`.
this._rowPlaceholder.viewContainer.createEmbeddedView(row.template, context, index);

// Insert empty cells if there is no data to improve rendering time.
CdkCellOutlet.mostRecentCellOutlet.cells = rowData ? this._getCellTemplatesForRow(row) : [];
CdkCellOutlet.mostRecentCellOutlet.context = context;
const cells = rowData ? this._getCellTemplatesForRow(row) : [];

cells.forEach(cell => {
CdkCellOutlet.mostRecentCellOutlet._viewContainer.createEmbeddedView(cell.template, context);
});

this._changeDetectorRef.markForCheck();
}

/**
* Updates the context for each row to reflect any data changes that may have caused
* rows to be added, removed, or moved. The view container contains the same context
* that was provided to each of its cells.
*/
private _updateRowContext() {
const viewContainer = this._rowPlaceholder.viewContainer;
for (let index = 0, count = viewContainer.length; index < count; index++) {
const viewRef = viewContainer.get(index) as EmbeddedViewRef<CdkCellOutletRowContext<T>>;
viewRef.context.index = index;
viewRef.context.count = count;
viewRef.context.first = index === 0;
viewRef.context.last = index === count - 1;
viewRef.context.even = index % 2 === 0;
viewRef.context.odd = index % 2 !== 0;
}
}

/**
* Returns the cell template definitions to insert into the header
* as defined by its list of columns to display.
Expand Down
Loading