@angular/cdk
Version:
Angular Material Component Development Kit
1,240 lines (1,232 loc) • 91.7 kB
JavaScript
import { Directionality } from '@angular/cdk/bidi';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { isDataSource, _VIEW_REPEATER_STRATEGY, _DisposeViewRepeaterStrategy } from '@angular/cdk/collections';
export { DataSource } from '@angular/cdk/collections';
import { Platform } from '@angular/cdk/platform';
import { ViewportRuler, ScrollingModule } from '@angular/cdk/scrolling';
import { DOCUMENT } from '@angular/common';
import { InjectionToken, Directive, TemplateRef, Inject, Optional, Input, ContentChild, ElementRef, Injectable, NgZone, IterableDiffers, ViewContainerRef, Component, ChangeDetectionStrategy, ViewEncapsulation, EmbeddedViewRef, ChangeDetectorRef, Attribute, ViewChild, ContentChildren, NgModule } from '@angular/core';
import { Subject, from, BehaviorSubject, isObservable, of } from 'rxjs';
import { takeUntil, take } from 'rxjs/operators';
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Mixin to provide a directive with a function that checks if the sticky input has been
* changed since the last time the function was called. Essentially adds a dirty-check to the
* sticky value.
* @docs-private
*/
function mixinHasStickyInput(base) {
return class extends base {
constructor(...args) {
super(...args);
this._sticky = false;
/** Whether the sticky input has changed since it was last checked. */
this._hasStickyChanged = false;
}
/** Whether sticky positioning should be applied. */
get sticky() { return this._sticky; }
set sticky(v) {
const prevValue = this._sticky;
this._sticky = coerceBooleanProperty(v);
this._hasStickyChanged = prevValue !== this._sticky;
}
/** Whether the sticky value has changed since this was last called. */
hasStickyChanged() {
const hasStickyChanged = this._hasStickyChanged;
this._hasStickyChanged = false;
return hasStickyChanged;
}
/** Resets the dirty check for cases where the sticky state has been used without checking. */
resetStickyChanged() {
this._hasStickyChanged = false;
}
};
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Used to provide a table to some of the sub-components without causing a circular dependency.
* @docs-private
*/
const CDK_TABLE = new InjectionToken('CDK_TABLE');
/** Injection token that can be used to specify the text column options. */
const TEXT_COLUMN_OPTIONS = new InjectionToken('text-column-options');
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Cell definition for a CDK table.
* Captures the template of a column's data row cell as well as cell-specific properties.
*/
class CdkCellDef {
constructor(/** @docs-private */ template) {
this.template = template;
}
}
CdkCellDef.decorators = [
{ type: Directive, args: [{ selector: '[cdkCellDef]' },] }
];
CdkCellDef.ctorParameters = () => [
{ type: TemplateRef }
];
/**
* Header cell definition for a CDK table.
* Captures the template of a column's header cell and as well as cell-specific properties.
*/
class CdkHeaderCellDef {
constructor(/** @docs-private */ template) {
this.template = template;
}
}
CdkHeaderCellDef.decorators = [
{ type: Directive, args: [{ selector: '[cdkHeaderCellDef]' },] }
];
CdkHeaderCellDef.ctorParameters = () => [
{ type: TemplateRef }
];
/**
* Footer cell definition for a CDK table.
* Captures the template of a column's footer cell and as well as cell-specific properties.
*/
class CdkFooterCellDef {
constructor(/** @docs-private */ template) {
this.template = template;
}
}
CdkFooterCellDef.decorators = [
{ type: Directive, args: [{ selector: '[cdkFooterCellDef]' },] }
];
CdkFooterCellDef.ctorParameters = () => [
{ type: TemplateRef }
];
// Boilerplate for applying mixins to CdkColumnDef.
/** @docs-private */
class CdkColumnDefBase {
}
const _CdkColumnDefBase = mixinHasStickyInput(CdkColumnDefBase);
/**
* Column definition for the CDK table.
* Defines a set of cells available for a table column.
*/
class CdkColumnDef extends _CdkColumnDefBase {
constructor(_table) {
super();
this._table = _table;
this._stickyEnd = false;
}
/** Unique name for this column. */
get name() { return this._name; }
set name(name) { this._setNameInput(name); }
/**
* Whether this column should be sticky positioned on the end of the row. Should make sure
* that it mimics the `CanStick` mixin such that `_hasStickyChanged` is set to true if the value
* has been changed.
*/
get stickyEnd() {
return this._stickyEnd;
}
set stickyEnd(v) {
const prevValue = this._stickyEnd;
this._stickyEnd = coerceBooleanProperty(v);
this._hasStickyChanged = prevValue !== this._stickyEnd;
}
/**
* Overridable method that sets the css classes that will be added to every cell in this
* column.
* In the future, columnCssClassName will change from type string[] to string and this
* will set a single string value.
* @docs-private
*/
_updateColumnCssClassName() {
this._columnCssClassName = [`cdk-column-${this.cssClassFriendlyName}`];
}
/**
* This has been extracted to a util because of TS 4 and VE.
* View Engine doesn't support property rename inheritance.
* TS 4.0 doesn't allow properties to override accessors or vice-versa.
* @docs-private
*/
_setNameInput(value) {
// If the directive is set without a name (updated programatically), then this setter will
// trigger with an empty string and should not overwrite the programatically set value.
if (value) {
this._name = value;
this.cssClassFriendlyName = value.replace(/[^a-z0-9_-]/ig, '-');
this._updateColumnCssClassName();
}
}
}
CdkColumnDef.decorators = [
{ type: Directive, args: [{
selector: '[cdkColumnDef]',
inputs: ['sticky'],
providers: [{ provide: 'MAT_SORT_HEADER_COLUMN_DEF', useExisting: CdkColumnDef }],
},] }
];
CdkColumnDef.ctorParameters = () => [
{ type: undefined, decorators: [{ type: Inject, args: [CDK_TABLE,] }, { type: Optional }] }
];
CdkColumnDef.propDecorators = {
name: [{ type: Input, args: ['cdkColumnDef',] }],
stickyEnd: [{ type: Input, args: ['stickyEnd',] }],
cell: [{ type: ContentChild, args: [CdkCellDef,] }],
headerCell: [{ type: ContentChild, args: [CdkHeaderCellDef,] }],
footerCell: [{ type: ContentChild, args: [CdkFooterCellDef,] }]
};
/** Base class for the cells. Adds a CSS classname that identifies the column it renders in. */
class BaseCdkCell {
constructor(columnDef, elementRef) {
// If IE 11 is dropped before we switch to setting a single class name, change to multi param
// with destructuring.
const classList = elementRef.nativeElement.classList;
for (const className of columnDef._columnCssClassName) {
classList.add(className);
}
}
}
/** Header cell template container that adds the right classes and role. */
class CdkHeaderCell extends BaseCdkCell {
constructor(columnDef, elementRef) {
super(columnDef, elementRef);
}
}
CdkHeaderCell.decorators = [
{ type: Directive, args: [{
selector: 'cdk-header-cell, th[cdk-header-cell]',
host: {
'class': 'cdk-header-cell',
'role': 'columnheader',
},
},] }
];
CdkHeaderCell.ctorParameters = () => [
{ type: CdkColumnDef },
{ type: ElementRef }
];
/** Footer cell template container that adds the right classes and role. */
class CdkFooterCell extends BaseCdkCell {
constructor(columnDef, elementRef) {
super(columnDef, elementRef);
}
}
CdkFooterCell.decorators = [
{ type: Directive, args: [{
selector: 'cdk-footer-cell, td[cdk-footer-cell]',
host: {
'class': 'cdk-footer-cell',
'role': 'gridcell',
},
},] }
];
CdkFooterCell.ctorParameters = () => [
{ type: CdkColumnDef },
{ type: ElementRef }
];
/** Cell template container that adds the right classes and role. */
class CdkCell extends BaseCdkCell {
constructor(columnDef, elementRef) {
super(columnDef, elementRef);
}
}
CdkCell.decorators = [
{ type: Directive, args: [{
selector: 'cdk-cell, td[cdk-cell]',
host: {
'class': 'cdk-cell',
'role': 'gridcell',
},
},] }
];
CdkCell.ctorParameters = () => [
{ type: CdkColumnDef },
{ type: ElementRef }
];
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @docs-private
*/
class _Schedule {
constructor() {
this.tasks = [];
this.endTasks = [];
}
}
/** Injection token used to provide a coalesced style scheduler. */
const _COALESCED_STYLE_SCHEDULER = new InjectionToken('_COALESCED_STYLE_SCHEDULER');
/**
* Allows grouping up CSSDom mutations after the current execution context.
* This can significantly improve performance when separate consecutive functions are
* reading from the CSSDom and then mutating it.
*
* @docs-private
*/
class _CoalescedStyleScheduler {
constructor(_ngZone) {
this._ngZone = _ngZone;
this._currentSchedule = null;
this._destroyed = new Subject();
}
/**
* Schedules the specified task to run at the end of the current VM turn.
*/
schedule(task) {
this._createScheduleIfNeeded();
this._currentSchedule.tasks.push(task);
}
/**
* Schedules the specified task to run after other scheduled tasks at the end of the current
* VM turn.
*/
scheduleEnd(task) {
this._createScheduleIfNeeded();
this._currentSchedule.endTasks.push(task);
}
/** Prevent any further tasks from running. */
ngOnDestroy() {
this._destroyed.next();
this._destroyed.complete();
}
_createScheduleIfNeeded() {
if (this._currentSchedule) {
return;
}
this._currentSchedule = new _Schedule();
this._getScheduleObservable().pipe(takeUntil(this._destroyed)).subscribe(() => {
while (this._currentSchedule.tasks.length || this._currentSchedule.endTasks.length) {
const schedule = this._currentSchedule;
// Capture new tasks scheduled by the current set of tasks.
this._currentSchedule = new _Schedule();
for (const task of schedule.tasks) {
task();
}
for (const task of schedule.endTasks) {
task();
}
}
this._currentSchedule = null;
});
}
_getScheduleObservable() {
// Use onStable when in the context of an ongoing change detection cycle so that we
// do not accidentally trigger additional cycles.
return this._ngZone.isStable ?
from(Promise.resolve(undefined)) :
this._ngZone.onStable.pipe(take(1));
}
}
_CoalescedStyleScheduler.decorators = [
{ type: Injectable }
];
_CoalescedStyleScheduler.ctorParameters = () => [
{ type: NgZone }
];
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* The row template that can be used by the mat-table. Should not be used outside of the
* material library.
*/
const CDK_ROW_TEMPLATE = `<ng-container cdkCellOutlet></ng-container>`;
/**
* Base class for the CdkHeaderRowDef and CdkRowDef that handles checking their columns inputs
* for changes and notifying the table.
*/
class BaseRowDef {
constructor(
/** @docs-private */ template, _differs) {
this.template = template;
this._differs = _differs;
}
ngOnChanges(changes) {
// Create a new columns differ if one does not yet exist. Initialize it based on initial value
// of the columns property or an empty array if none is provided.
if (!this._columnsDiffer) {
const columns = (changes['columns'] && changes['columns'].currentValue) || [];
this._columnsDiffer = this._differs.find(columns).create();
this._columnsDiffer.diff(columns);
}
}
/**
* Returns the difference between the current columns and the columns from the last diff, or null
* if there is no difference.
*/
getColumnsDiff() {
return this._columnsDiffer.diff(this.columns);
}
/** Gets this row def's relevant cell template from the provided column def. */
extractCellTemplate(column) {
if (this instanceof CdkHeaderRowDef) {
return column.headerCell.template;
}
if (this instanceof CdkFooterRowDef) {
return column.footerCell.template;
}
else {
return column.cell.template;
}
}
}
BaseRowDef.decorators = [
{ type: Directive }
];
BaseRowDef.ctorParameters = () => [
{ type: TemplateRef },
{ type: IterableDiffers }
];
// Boilerplate for applying mixins to CdkHeaderRowDef.
/** @docs-private */
class CdkHeaderRowDefBase extends BaseRowDef {
}
const _CdkHeaderRowDefBase = mixinHasStickyInput(CdkHeaderRowDefBase);
/**
* Header row definition for the CDK table.
* Captures the header row's template and other header properties such as the columns to display.
*/
class CdkHeaderRowDef extends _CdkHeaderRowDefBase {
constructor(template, _differs, _table) {
super(template, _differs);
this._table = _table;
}
// Prerender fails to recognize that ngOnChanges in a part of this class through inheritance.
// Explicitly define it so that the method is called as part of the Angular lifecycle.
ngOnChanges(changes) {
super.ngOnChanges(changes);
}
}
CdkHeaderRowDef.decorators = [
{ type: Directive, args: [{
selector: '[cdkHeaderRowDef]',
inputs: ['columns: cdkHeaderRowDef', 'sticky: cdkHeaderRowDefSticky'],
},] }
];
CdkHeaderRowDef.ctorParameters = () => [
{ type: TemplateRef },
{ type: IterableDiffers },
{ type: undefined, decorators: [{ type: Inject, args: [CDK_TABLE,] }, { type: Optional }] }
];
// Boilerplate for applying mixins to CdkFooterRowDef.
/** @docs-private */
class CdkFooterRowDefBase extends BaseRowDef {
}
const _CdkFooterRowDefBase = mixinHasStickyInput(CdkFooterRowDefBase);
/**
* Footer row definition for the CDK table.
* Captures the footer row's template and other footer properties such as the columns to display.
*/
class CdkFooterRowDef extends _CdkFooterRowDefBase {
constructor(template, _differs, _table) {
super(template, _differs);
this._table = _table;
}
// Prerender fails to recognize that ngOnChanges in a part of this class through inheritance.
// Explicitly define it so that the method is called as part of the Angular lifecycle.
ngOnChanges(changes) {
super.ngOnChanges(changes);
}
}
CdkFooterRowDef.decorators = [
{ type: Directive, args: [{
selector: '[cdkFooterRowDef]',
inputs: ['columns: cdkFooterRowDef', 'sticky: cdkFooterRowDefSticky'],
},] }
];
CdkFooterRowDef.ctorParameters = () => [
{ type: TemplateRef },
{ type: IterableDiffers },
{ type: undefined, decorators: [{ type: Inject, args: [CDK_TABLE,] }, { type: Optional }] }
];
/**
* Data row definition for the CDK table.
* Captures the header row's template and other row properties such as the columns to display and
* a when predicate that describes when this row should be used.
*/
class CdkRowDef extends BaseRowDef {
// TODO(andrewseguin): Add an input for providing a switch function to determine
// if this template should be used.
constructor(template, _differs, _table) {
super(template, _differs);
this._table = _table;
}
}
CdkRowDef.decorators = [
{ type: Directive, args: [{
selector: '[cdkRowDef]',
inputs: ['columns: cdkRowDefColumns', 'when: cdkRowDefWhen'],
},] }
];
CdkRowDef.ctorParameters = () => [
{ type: TemplateRef },
{ type: IterableDiffers },
{ type: undefined, decorators: [{ type: Inject, args: [CDK_TABLE,] }, { type: Optional }] }
];
/**
* Outlet for rendering cells inside of a row or header row.
* @docs-private
*/
class CdkCellOutlet {
constructor(_viewContainer) {
this._viewContainer = _viewContainer;
CdkCellOutlet.mostRecentCellOutlet = this;
}
ngOnDestroy() {
// If this was the last outlet being rendered in the view, remove the reference
// from the static property after it has been destroyed to avoid leaking memory.
if (CdkCellOutlet.mostRecentCellOutlet === this) {
CdkCellOutlet.mostRecentCellOutlet = null;
}
}
}
/**
* Static property containing the latest constructed instance of this class.
* Used by the CDK table when each CdkHeaderRow and CdkRow component is created using
* createEmbeddedView. After one of these components are created, this property will provide
* a handle to provide that component's cells and context. After init, the CdkCellOutlet will
* construct the cells with the provided context.
*/
CdkCellOutlet.mostRecentCellOutlet = null;
CdkCellOutlet.decorators = [
{ type: Directive, args: [{ selector: '[cdkCellOutlet]' },] }
];
CdkCellOutlet.ctorParameters = () => [
{ type: ViewContainerRef }
];
/** Header template container that contains the cell outlet. Adds the right class and role. */
class CdkHeaderRow {
}
CdkHeaderRow.decorators = [
{ type: Component, args: [{
selector: 'cdk-header-row, tr[cdk-header-row]',
template: CDK_ROW_TEMPLATE,
host: {
'class': 'cdk-header-row',
'role': 'row',
},
// See note on CdkTable for explanation on why this uses the default change detection strategy.
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.None
},] }
];
/** Footer template container that contains the cell outlet. Adds the right class and role. */
class CdkFooterRow {
}
CdkFooterRow.decorators = [
{ type: Component, args: [{
selector: 'cdk-footer-row, tr[cdk-footer-row]',
template: CDK_ROW_TEMPLATE,
host: {
'class': 'cdk-footer-row',
'role': 'row',
},
// See note on CdkTable for explanation on why this uses the default change detection strategy.
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.None
},] }
];
/** Data row template container that contains the cell outlet. Adds the right class and role. */
class CdkRow {
}
CdkRow.decorators = [
{ type: Component, args: [{
selector: 'cdk-row, tr[cdk-row]',
template: CDK_ROW_TEMPLATE,
host: {
'class': 'cdk-row',
'role': 'row',
},
// See note on CdkTable for explanation on why this uses the default change detection strategy.
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.None
},] }
];
/** Row that can be used to display a message when no data is shown in the table. */
class CdkNoDataRow {
constructor(templateRef) {
this.templateRef = templateRef;
}
}
CdkNoDataRow.decorators = [
{ type: Directive, args: [{
selector: 'ng-template[cdkNoDataRow]'
},] }
];
CdkNoDataRow.ctorParameters = () => [
{ type: TemplateRef }
];
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* List of all possible directions that can be used for sticky positioning.
* @docs-private
*/
const STICKY_DIRECTIONS = ['top', 'bottom', 'left', 'right'];
/**
* Applies and removes sticky positioning styles to the `CdkTable` rows and columns cells.
* @docs-private
*/
class StickyStyler {
/**
* @param _isNativeHtmlTable Whether the sticky logic should be based on a table
* that uses the native `<table>` element.
* @param _stickCellCss The CSS class that will be applied to every row/cell that has
* 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.
* @param _needsPositionStickyOnElement Whether we need to specify position: sticky on cells
* using inline styles. If false, it is assumed that position: sticky is included in
* the component stylesheet for _stickCellCss.
*/
constructor(_isNativeHtmlTable, _stickCellCss, direction,
/**
* @deprecated `_coalescedStyleScheduler` parameter to become required.
* @breaking-change 11.0.0
*/
_coalescedStyleScheduler, _isBrowser = true, _needsPositionStickyOnElement = true) {
this._isNativeHtmlTable = _isNativeHtmlTable;
this._stickCellCss = _stickCellCss;
this.direction = direction;
this._coalescedStyleScheduler = _coalescedStyleScheduler;
this._isBrowser = _isBrowser;
this._needsPositionStickyOnElement = _needsPositionStickyOnElement;
this._cachedCellWidths = [];
}
/**
* Clears the sticky positioning styles from the row and its cells by resetting the `position`
* style, setting the zIndex to 0, and unsetting each provided sticky direction.
* @param rows The list of rows that should be cleared from sticking in the provided directions
* @param stickyDirections The directions that should no longer be set as sticky on the rows.
*/
clearStickyPositioning(rows, stickyDirections) {
const elementsToClear = [];
for (const row of rows) {
// If the row isn't an element (e.g. if it's an `ng-container`),
// it won't have inline styles or `children` so we skip it.
if (row.nodeType !== row.ELEMENT_NODE) {
continue;
}
elementsToClear.push(row);
for (let i = 0; i < row.children.length; i++) {
elementsToClear.push(row.children[i]);
}
}
// Coalesce with sticky row/column updates (and potentially other changes like column resize).
this._scheduleStyleChanges(() => {
for (const element of elementsToClear) {
this._removeStickyStyle(element, stickyDirections);
}
});
}
/**
* Applies sticky left and right positions to the cells of each row according to the sticky
* states of the rendered column definitions.
* @param rows The rows that should have its set of cells stuck according to the sticky states.
* @param stickyStartStates A list of boolean states where each state represents whether the cell
* in this index position should be stuck to the start of the row.
* @param stickyEndStates A list of boolean states where each state represents whether the cell
* in this index position should be stuck to the end of the row.
* @param recalculateCellWidths Whether the sticky styler should recalculate the width of each
* column cell. If `false` cached widths will be used instead.
*/
updateStickyColumns(rows, stickyStartStates, stickyEndStates, recalculateCellWidths = true) {
if (!rows.length || !this._isBrowser || !(stickyStartStates.some(state => state) ||
stickyEndStates.some(state => state))) {
return;
}
const firstRow = rows[0];
const numCells = firstRow.children.length;
const cellWidths = this._getCellWidths(firstRow, recalculateCellWidths);
const startPositions = this._getStickyStartColumnPositions(cellWidths, stickyStartStates);
const endPositions = this._getStickyEndColumnPositions(cellWidths, stickyEndStates);
// Coalesce with sticky row updates (and potentially other changes like column resize).
this._scheduleStyleChanges(() => {
const isRtl = this.direction === 'rtl';
const start = isRtl ? 'right' : 'left';
const end = isRtl ? 'left' : 'right';
for (const row of rows) {
for (let i = 0; i < numCells; i++) {
const cell = row.children[i];
if (stickyStartStates[i]) {
this._addStickyStyle(cell, start, startPositions[i]);
}
if (stickyEndStates[i]) {
this._addStickyStyle(cell, end, endPositions[i]);
}
}
}
});
}
/**
* Applies sticky positioning to the row's cells if using the native table layout, and to the
* row itself otherwise.
* @param rowsToStick The list of rows that should be stuck according to their corresponding
* sticky state and to the provided top or bottom position.
* @param stickyStates A list of boolean states where each state represents whether the row
* should be stuck in the particular top or bottom position.
* @param position The position direction in which the row should be stuck if that row should be
* sticky.
*
*/
stickRows(rowsToStick, stickyStates, position) {
// Since we can't measure the rows on the server, we can't stick the rows properly.
if (!this._isBrowser) {
return;
}
// If positioning the rows to the bottom, reverse their order when evaluating the sticky
// position such that the last row stuck will be "bottom: 0px" and so on. Note that the
// sticky states need to be reversed as well.
const rows = position === 'bottom' ? rowsToStick.slice().reverse() : rowsToStick;
const states = position === 'bottom' ? stickyStates.slice().reverse() : stickyStates;
// Measure row heights all at once before adding sticky styles to reduce layout thrashing.
const stickyHeights = [];
const elementsToStick = [];
for (let rowIndex = 0, stickyHeight = 0; rowIndex < rows.length; rowIndex++) {
stickyHeights[rowIndex] = stickyHeight;
if (!states[rowIndex]) {
continue;
}
const row = rows[rowIndex];
elementsToStick[rowIndex] = this._isNativeHtmlTable ?
Array.from(row.children) : [row];
if (rowIndex !== rows.length - 1) {
stickyHeight += row.getBoundingClientRect().height;
}
}
// Coalesce with other sticky row updates (top/bottom), sticky columns updates
// (and potentially other changes like column resize).
this._scheduleStyleChanges(() => {
for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
if (!states[rowIndex]) {
continue;
}
const height = stickyHeights[rowIndex];
for (const element of elementsToStick[rowIndex]) {
this._addStickyStyle(element, position, height);
}
}
});
}
/**
* When using the native table in Safari, sticky footer cells do not stick. The only way to stick
* footer rows is to apply sticky styling to the tfoot container. This should only be done if
* all footer rows are sticky. If not all footer rows are sticky, remove sticky positioning from
* the tfoot element.
*/
updateStickyFooterContainer(tableElement, stickyStates) {
if (!this._isNativeHtmlTable) {
return;
}
const tfoot = tableElement.querySelector('tfoot');
// Coalesce with other sticky updates (and potentially other changes like column resize).
this._scheduleStyleChanges(() => {
if (stickyStates.some(state => !state)) {
this._removeStickyStyle(tfoot, ['bottom']);
}
else {
this._addStickyStyle(tfoot, 'bottom', 0);
}
});
}
/**
* Removes the sticky style on the element by removing the sticky cell CSS class, re-evaluating
* the zIndex, removing each of the provided sticky directions, and removing the
* sticky position if there are no more directions.
*/
_removeStickyStyle(element, stickyDirections) {
for (const dir of stickyDirections) {
element.style[dir] = '';
}
// If the element no longer has any more sticky directions, remove sticky positioning and
// the sticky CSS class.
// Short-circuit checking element.style[dir] for stickyDirections as they
// were already removed above.
const hasDirection = STICKY_DIRECTIONS.some(dir => stickyDirections.indexOf(dir) === -1 && element.style[dir]);
if (hasDirection) {
element.style.zIndex = this._getCalculatedZIndex(element);
}
else {
// When not hasDirection, _getCalculatedZIndex will always return ''.
element.style.zIndex = '';
if (this._needsPositionStickyOnElement) {
element.style.position = '';
}
element.classList.remove(this._stickCellCss);
}
}
/**
* Adds the sticky styling to the element by adding the sticky style class, changing position
* to be sticky (and -webkit-sticky), setting the appropriate zIndex, and adding a sticky
* direction and value.
*/
_addStickyStyle(element, dir, dirValue) {
element.classList.add(this._stickCellCss);
element.style[dir] = `${dirValue}px`;
element.style.zIndex = this._getCalculatedZIndex(element);
if (this._needsPositionStickyOnElement) {
element.style.cssText += 'position: -webkit-sticky; position: sticky; ';
}
}
/**
* Calculate what the z-index should be for the element, depending on what directions (top,
* bottom, left, right) have been set. It should be true that elements with a top direction
* should have the highest index since these are elements like a table header. If any of those
* elements are also sticky in another direction, then they should appear above other elements
* that are only sticky top (e.g. a sticky column on a sticky header). Bottom-sticky elements
* (e.g. footer rows) should then be next in the ordering such that they are below the header
* but above any non-sticky elements. Finally, left/right sticky elements (e.g. sticky columns)
* should minimally increment so that they are above non-sticky elements but below top and bottom
* elements.
*/
_getCalculatedZIndex(element) {
const zIndexIncrements = {
top: 100,
bottom: 10,
left: 1,
right: 1,
};
let zIndex = 0;
// Use `Iterable` instead of `Array` because TypeScript, as of 3.6.3,
// loses the array generic type in the `for of`. But we *also* have to use `Array` because
// typescript won't iterate over an `Iterable` unless you compile with `--downlevelIteration`
for (const dir of STICKY_DIRECTIONS) {
if (element.style[dir]) {
zIndex += zIndexIncrements[dir];
}
}
return zIndex ? `${zIndex}` : '';
}
/** Gets the widths for each cell in the provided row. */
_getCellWidths(row, recalculateCellWidths = true) {
if (!recalculateCellWidths && this._cachedCellWidths.length) {
return this._cachedCellWidths;
}
const cellWidths = [];
const firstRowCells = row.children;
for (let i = 0; i < firstRowCells.length; i++) {
let cell = firstRowCells[i];
cellWidths.push(cell.getBoundingClientRect().width);
}
this._cachedCellWidths = cellWidths;
return cellWidths;
}
/**
* Determines the left and right positions of each sticky column cell, which will be the
* accumulation of all sticky column cell widths to the left and right, respectively.
* Non-sticky cells do not need to have a value set since their positions will not be applied.
*/
_getStickyStartColumnPositions(widths, stickyStates) {
const positions = [];
let nextPosition = 0;
for (let i = 0; i < widths.length; i++) {
if (stickyStates[i]) {
positions[i] = nextPosition;
nextPosition += widths[i];
}
}
return positions;
}
/**
* Determines the left and right positions of each sticky column cell, which will be the
* accumulation of all sticky column cell widths to the left and right, respectively.
* Non-sticky cells do not need to have a value set since their positions will not be applied.
*/
_getStickyEndColumnPositions(widths, stickyStates) {
const positions = [];
let nextPosition = 0;
for (let i = widths.length; i > 0; i--) {
if (stickyStates[i]) {
positions[i] = nextPosition;
nextPosition += widths[i];
}
}
return positions;
}
/**
* Schedules styles to be applied when the style scheduler deems appropriate.
* @breaking-change 11.0.0 This method can be removed in favor of calling
* `CoalescedStyleScheduler.schedule` directly once the scheduler is a required parameter.
*/
_scheduleStyleChanges(changes) {
if (this._coalescedStyleScheduler) {
this._coalescedStyleScheduler.schedule(changes);
}
else {
changes();
}
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Returns an error to be thrown when attempting to find an unexisting column.
* @param id Id whose lookup failed.
* @docs-private
*/
function getTableUnknownColumnError(id) {
return Error(`Could not find column with id "${id}".`);
}
/**
* Returns an error to be thrown when two column definitions have the same name.
* @docs-private
*/
function getTableDuplicateColumnNameError(name) {
return Error(`Duplicate column definition name provided: "${name}".`);
}
/**
* Returns an error to be thrown when there are multiple rows that are missing a when function.
* @docs-private
*/
function getTableMultipleDefaultRowDefsError() {
return Error(`There can only be one default row without a when predicate function.`);
}
/**
* Returns an error to be thrown when there are no matching row defs for a particular set of data.
* @docs-private
*/
function getTableMissingMatchingRowDefError(data) {
return Error(`Could not find a matching row definition for the` +
`provided row data: ${JSON.stringify(data)}`);
}
/**
* Returns an error to be thrown when there is no row definitions present in the content.
* @docs-private
*/
function getTableMissingRowDefsError() {
return Error('Missing definitions for header, footer, and row; ' +
'cannot determine which columns should be rendered.');
}
/**
* Returns an error to be thrown when the data source does not match the compatible types.
* @docs-private
*/
function getTableUnknownDataSourceError() {
return Error(`Provided data source did not match an array, Observable, or DataSource`);
}
/**
* Returns an error to be thrown when the text column cannot find a parent table to inject.
* @docs-private
*/
function getTableTextColumnMissingParentTableError() {
return Error(`Text column could not find a parent table for registration.`);
}
/**
* Returns an error to be thrown when a table text column doesn't have a name.
* @docs-private
*/
function getTableTextColumnMissingNameError() {
return Error(`Table text column must have a name.`);
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Provides a handle for the table to grab the view container's ng-container to insert data rows.
* @docs-private
*/
class DataRowOutlet {
constructor(viewContainer, elementRef) {
this.viewContainer = viewContainer;
this.elementRef = elementRef;
}
}
DataRowOutlet.decorators = [
{ type: Directive, args: [{ selector: '[rowOutlet]' },] }
];
DataRowOutlet.ctorParameters = () => [
{ type: ViewContainerRef },
{ type: ElementRef }
];
/**
* Provides a handle for the table to grab the view container's ng-container to insert the header.
* @docs-private
*/
class HeaderRowOutlet {
constructor(viewContainer, elementRef) {
this.viewContainer = viewContainer;
this.elementRef = elementRef;
}
}
HeaderRowOutlet.decorators = [
{ type: Directive, args: [{ selector: '[headerRowOutlet]' },] }
];
HeaderRowOutlet.ctorParameters = () => [
{ type: ViewContainerRef },
{ type: ElementRef }
];
/**
* Provides a handle for the table to grab the view container's ng-container to insert the footer.
* @docs-private
*/
class FooterRowOutlet {
constructor(viewContainer, elementRef) {
this.viewContainer = viewContainer;
this.elementRef = elementRef;
}
}
FooterRowOutlet.decorators = [
{ type: Directive, args: [{ selector: '[footerRowOutlet]' },] }
];
FooterRowOutlet.ctorParameters = () => [
{ type: ViewContainerRef },
{ type: ElementRef }
];
/**
* Provides a handle for the table to grab the view
* container's ng-container to insert the no data row.
* @docs-private
*/
class NoDataRowOutlet {
constructor(viewContainer, elementRef) {
this.viewContainer = viewContainer;
this.elementRef = elementRef;
}
}
NoDataRowOutlet.decorators = [
{ type: Directive, args: [{ selector: '[noDataRowOutlet]' },] }
];
NoDataRowOutlet.ctorParameters = () => [
{ type: ViewContainerRef },
{ type: ElementRef }
];
/**
* The table template that can be used by the mat-table. Should not be used outside of the
* material library.
* @docs-private
*/
const CDK_TABLE_TEMPLATE =
// Note that according to MDN, the `caption` element has to be projected as the **first**
// element in the table. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption
`
<ng-content select="caption"></ng-content>
<ng-content select="colgroup, col"></ng-content>
<ng-container headerRowOutlet></ng-container>
<ng-container rowOutlet></ng-container>
<ng-container noDataRowOutlet></ng-container>
<ng-container footerRowOutlet></ng-container>
`;
/**
* Class used to conveniently type the embedded view ref for rows with a context.
* @docs-private
*/
class RowViewRef extends EmbeddedViewRef {
}
/**
* A data table that can render a header row, data rows, and a footer row.
* Uses the dataSource input to determine the data to be rendered. The data can be provided either
* as a data array, an Observable stream that emits the data array to render, or a DataSource with a
* connect function that will return an Observable stream that emits the data array to render.
*/
class CdkTable {
constructor(_differs, _changeDetectorRef, _elementRef, role, _dir, _document, _platform,
/**
* @deprecated `_coalescedStyleScheduler`, `_viewRepeater` and `_viewportRuler`
* parameters to become required.
* @breaking-change 11.0.0
*/
_viewRepeater, _coalescedStyleScheduler,
// Optional for backwards compatibility. The viewport ruler is provided in root. Therefore,
// this property will never be null.
// tslint:disable-next-line: lightweight-tokens
_viewportRuler) {
this._differs = _differs;
this._changeDetectorRef = _changeDetectorRef;
this._elementRef = _elementRef;
this._dir = _dir;
this._platform = _platform;
this._viewRepeater = _viewRepeater;
this._coalescedStyleScheduler = _coalescedStyleScheduler;
this._viewportRuler = _viewportRuler;
/** Subject that emits when the component has been destroyed. */
this._onDestroy = new Subject();
/**
* Map of all the user's defined columns (header, data, and footer cell template) identified by
* name. Collection populated by the column definitions gathered by `ContentChildren` as well as
* any custom column definitions added to `_customColumnDefs`.
*/
this._columnDefsByName = new Map();
/**
* Column definitions that were defined outside of the direct content children of the table.
* These will be defined when, e.g., creating a wrapper around the cdkTable that has
* column definitions as *its* content child.
*/
this._customColumnDefs = new Set();
/**
* Data row definitions that were defined outside of the direct content children of the table.
* These will be defined when, e.g., creating a wrapper around the cdkTable that has
* built-in data rows as *its* content child.
*/
this._customRowDefs = new Set();
/**
* Header row definitions that were defined outside of the direct content children of the table.
* These will be defined when, e.g., creating a wrapper around the cdkTable that has
* built-in header rows as *its* content child.
*/
this._customHeaderRowDefs = new Set();
/**
* Footer row definitions that were defined outside of the direct content children of the table.
* These will be defined when, e.g., creating a wrapper around the cdkTable that has a
* built-in footer row as *its* content child.
*/
this._customFooterRowDefs = new Set();
/**
* Whether the header row definition has been changed. Triggers an update to the header row after
* content is checked. Initialized as true so that the table renders the initial set of rows.
*/
this._headerRowDefChanged = true;
/**
* Whether the footer row definition has been changed. Triggers an update to the footer row after
* content is checked. Initialized as true so that the table renders the initial set of rows.
*/
this._footerRowDefChanged = true;
/**
* Whether the sticky column styles need to be updated. Set to `true` when the visible columns
* change.
*/
this._stickyColumnStylesNeedReset = true;
/**
* Whether the sticky styler should recalculate cell widths when applying sticky styles. If
* `false`, cached values will be used instead. This is only applicable to tables with
* {@link fixedLayout} enabled. For other tables, cell widths will always be recalculated.
*/
this._forceRecalculateCellWidths = true;
/**
* Cache of the latest rendered `RenderRow` objects as a map for easy retrieval when constructing
* a new list of `RenderRow` objects for rendering rows. Since the new list is constructed with
* the cached `RenderRow` objects when possible, the row identity is preserved when the data
* and row template matches, which allows the `IterableDiffer` to check rows by reference
* and understand which rows are added/moved/removed.
*
* Implemented as a map of maps where the first key is the `data: T` object and the second is the
* `CdkRowDef<T>` object. With the two keys, the cache points to a `RenderRow<T>` object that
* contains an array of created pairs. The array is necessary to handle cases where the data
* array contains multiple duplicate data objects and each instantiated `RenderRow` must be
* stored.
*/
this._cachedRenderRowsMap = new Map();
/**
* CSS class added to any row or cell that has sticky positioning applied. May be overriden by
* table subclasses.
*/
this.stickyCssClass = 'cdk-table-sticky';
/**
* Whether to manually add positon: sticky to all sticky cell elements. Not needed if
* the position is set in a selector associated with the value of stickyCssClass. May be
* overridden by table subclasses
*/
this.needsPositionStickyOnElement = true;
/** Whether the no data row is currently showing anything. */
this._isShowingNoDataRow = false;
this._multiTemplateDataRows = false;
this._fixedLayout = false;
// TODO(andrewseguin): Remove max value as the end index
// and instead calculate the view on init and scroll.
/**
* Stream containing the latest information on what rows are being displayed on screen.
* Can be used by the data source to as a heuristic of what data should be provided.
*
* @docs-private
*/
this.viewChange = new BehaviorSubject({ start: 0, end: Number.MAX_VALUE });
if (!role) {
this._elementRef.nativeElement.setAttribute('role', 'grid');
}
this._document = _document;
this._isNativeHtmlTable = this._elementRef.nativeElement.nodeName === 'TABLE';
}
/**
* Tracking function that will be used to check the differences in data changes. Used similarly
* to `ngFor` `trackBy` function. Optimize row operations by identifying a row based on its data
* relative to the function to know if a row should be added/removed/moved.
* Accepts a function that takes two parameters, `index` and `item`.
*/
get trackBy() {
return this._trackByFn;
}
set trackBy(fn) {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && fn != null && typeof fn !== 'function') {
console.warn(`trackBy must be a function, but received ${JSON.stringify(fn)}.`);
}
this._trackByFn = fn;
}
/**
* The table's source of data, which can be provided in three ways (in order of complexity):
* - Simple data array (each object represents one table row)
* - Stream that emits a data array each time the array changes
* - `DataSource` object that implements the connect/disconnect interface.
*
* If a data array is provided, the table must be notified when the array's objects are
* added, removed, or moved. This can be done by calling the `renderRows()` function which will
* render the diff since the last table render. If the data array reference is changed, the table
* will automatically trigger an update to the rows.
*
* When providing an Observable stream, the table will trigger an update automatically when the
* stream emits a new array of data.
*
* Finally, when providing a `DataSource` object, the table will use the Observable stream
* provided by the connect function and trigger updates when that stream emits new data array
* values. During the table's ngOnDestroy or when the data source is removed from the table, the
* table will call the DataSource's `disconnect` function (may be useful for cleaning up any
* subscriptions registered during the connect process).
*/
get dataSource() {
return this._dataSource;
}
set dataSource(dataSource) {
if (this._dataSource !== dataSource) {
this._switchDataSource(dataSource);
}
}
/**
* Whether to allow multiple rows per data object by evaluating which rows evaluate their 'when'
* predicate to true. If `multiTemplateDataRows` is false, which is the default value, then each
* dataobject will render the first row that evaluates its when predicate to true, in the order
* defined in the table, or otherwise the default row which does not have a when predicate.
*/
get multiTemplateDataRows() {
return this._multiTemplateDataRows;
}
set multiTemplateDataRows(v) {
this._multiTemplateDataRows = coerceBooleanProperty(v);
// In Ivy if this va