`,
host: {
class: 'datatable-row-wrapper'
}
}]
}], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }, { type: i0.KeyValueDiffers }]; }, propDecorators: { innerWidth: [{
type: Input
}], rowDetail: [{
type: Input
}], groupHeader: [{
type: Input
}], offsetX: [{
type: Input
}], detailRowHeight: [{
type: Input
}], row: [{
type: Input
}], groupedRows: [{
type: Input
}], rowContextmenu: [{
type: Output
}], rowIndex: [{
type: Input
}], expanded: [{
type: Input
}], onContextmenu: [{
type: HostListener,
args: ['contextmenu', ['$event']]
}] } });
class DataTableBodyComponent {
/**
* Creates an instance of DataTableBodyComponent.
*/
constructor(cd) {
this.cd = cd;
this.selected = [];
this.scroll = new EventEmitter();
this.page = new EventEmitter();
this.activate = new EventEmitter();
this.select = new EventEmitter();
this.detailToggle = new EventEmitter();
this.rowContextmenu = new EventEmitter(false);
this.treeAction = new EventEmitter();
this.rowHeightsCache = new RowHeightCache();
this.temp = [];
this.offsetY = 0;
this.indexes = {};
this.rowIndexes = new WeakMap();
this.rowExpansions = [];
/**
* Get the height of the detail row.
*/
this.getDetailRowHeight = (row, index) => {
if (!this.rowDetail) {
return 0;
}
const rowHeight = this.rowDetail.rowHeight;
return typeof rowHeight === 'function' ? rowHeight(row, index) : rowHeight;
};
// declare fn here so we can get access to the `this` property
this.rowTrackingFn = (index, row) => {
const idx = this.getRowIndex(row);
if (this.trackByProp) {
return row[this.trackByProp];
}
else {
return idx;
}
};
}
set pageSize(val) {
this._pageSize = val;
this.recalcLayout();
}
get pageSize() {
return this._pageSize;
}
set rows(val) {
this._rows = val;
this.recalcLayout();
}
get rows() {
return this._rows;
}
set columns(val) {
this._columns = val;
const colsByPin = columnsByPin(val);
this.columnGroupWidths = columnGroupWidths(colsByPin, val);
}
get columns() {
return this._columns;
}
set offset(val) {
this._offset = val;
if (!this.scrollbarV || (this.scrollbarV && !this.virtualization))
this.recalcLayout();
}
get offset() {
return this._offset;
}
set rowCount(val) {
this._rowCount = val;
this.recalcLayout();
}
get rowCount() {
return this._rowCount;
}
get bodyWidth() {
if (this.scrollbarH) {
return this.innerWidth + 'px';
}
else {
return '100%';
}
}
set bodyHeight(val) {
if (this.scrollbarV) {
this._bodyHeight = val + 'px';
}
else {
this._bodyHeight = 'auto';
}
this.recalcLayout();
}
get bodyHeight() {
return this._bodyHeight;
}
/**
* Returns if selection is enabled.
*/
get selectEnabled() {
return !!this.selectionType;
}
/**
* Property that would calculate the height of scroll bar
* based on the row heights cache for virtual scroll and virtualization. Other scenarios
* calculate scroll height automatically (as height will be undefined).
*/
get scrollHeight() {
if (this.scrollbarV && this.virtualization && this.rowCount) {
return this.rowHeightsCache.query(this.rowCount - 1);
}
// avoid TS7030: Not all code paths return a value.
return undefined;
}
/**
* Called after the constructor, initializing input properties
*/
ngOnInit() {
if (this.rowDetail) {
this.listener = this.rowDetail.toggle.subscribe(({ type, value }) => {
if (type === 'row') {
this.toggleRowExpansion(value);
}
if (type === 'all') {
this.toggleAllRows(value);
}
// Refresh rows after toggle
// Fixes #883
this.updateIndexes();
this.updateRows();
this.cd.markForCheck();
});
}
if (this.groupHeader) {
this.listener = this.groupHeader.toggle.subscribe(({ type, value }) => {
if (type === 'group') {
this.toggleRowExpansion(value);
}
if (type === 'all') {
this.toggleAllRows(value);
}
// Refresh rows after toggle
// Fixes #883
this.updateIndexes();
this.updateRows();
this.cd.markForCheck();
});
}
}
/**
* Called once, before the instance is destroyed.
*/
ngOnDestroy() {
if (this.rowDetail || this.groupHeader) {
this.listener.unsubscribe();
}
}
/**
* Updates the Y offset given a new offset.
*/
updateOffsetY(offset) {
// scroller is missing on empty table
if (!this.scroller) {
return;
}
if (this.scrollbarV && this.virtualization && offset) {
// First get the row Index that we need to move to.
const rowIndex = this.pageSize * offset;
offset = this.rowHeightsCache.query(rowIndex - 1);
}
else if (this.scrollbarV && !this.virtualization) {
offset = 0;
}
this.scroller.setOffset(offset || 0);
}
/**
* Body was scrolled, this is mainly useful for
* when a user is server-side pagination via virtual scroll.
*/
onBodyScroll(event) {
const scrollYPos = event.scrollYPos;
const scrollXPos = event.scrollXPos;
// if scroll change, trigger update
// this is mainly used for header cell positions
if (this.offsetY !== scrollYPos || this.offsetX !== scrollXPos) {
this.scroll.emit({
offsetY: scrollYPos,
offsetX: scrollXPos
});
}
this.offsetY = scrollYPos;
this.offsetX = scrollXPos;
this.updateIndexes();
this.updatePage(event.direction);
this.updateRows();
}
/**
* Updates the page given a direction.
*/
updatePage(direction) {
let offset = this.indexes.first / this.pageSize;
if (direction === 'up') {
offset = Math.ceil(offset);
}
else if (direction === 'down') {
offset = Math.floor(offset);
}
if (direction !== undefined && !isNaN(offset)) {
this.page.emit({ offset });
}
}
/**
* Updates the rows in the view port
*/
updateRows() {
const { first, last } = this.indexes;
let rowIndex = first;
let idx = 0;
const temp = [];
// if grouprowsby has been specified treat row paging
// parameters as group paging parameters ie if limit 10 has been
// specified treat it as 10 groups rather than 10 rows
if (this.groupedRows) {
let maxRowsPerGroup = 3;
// if there is only one group set the maximum number of
// rows per group the same as the total number of rows
if (this.groupedRows.length === 1) {
maxRowsPerGroup = this.groupedRows[0].value.length;
}
while (rowIndex < last && rowIndex < this.groupedRows.length) {
// Add the groups into this page
const group = this.groupedRows[rowIndex];
this.rowIndexes.set(group, rowIndex);
if (group.value) {
// add indexes for each group item
group.value.forEach((g, i) => {
const _idx = `${rowIndex}-${i}`;
this.rowIndexes.set(g, _idx);
});
}
temp[idx] = group;
idx++;
// Group index in this context
rowIndex++;
}
}
else {
while (rowIndex < last && rowIndex < this.rowCount) {
const row = this.rows[rowIndex];
if (row) {
// add indexes for each row
this.rowIndexes.set(row, rowIndex);
temp[idx] = row;
}
idx++;
rowIndex++;
}
}
this.temp = temp;
}
/**
* Get the row height
*/
getRowHeight(row) {
// if its a function return it
if (typeof this.rowHeight === 'function') {
return this.rowHeight(row);
}
return this.rowHeight;
}
/**
* @param group the group with all rows
*/
getGroupHeight(group) {
let rowHeight = 0;
if (group.value) {
for (let index = 0; index < group.value.length; index++) {
rowHeight += this.getRowAndDetailHeight(group.value[index]);
}
}
return rowHeight;
}
/**
* Calculate row height based on the expanded state of the row.
*/
getRowAndDetailHeight(row) {
let rowHeight = this.getRowHeight(row);
const expanded = this.getRowExpanded(row);
// Adding detail row height if its expanded.
if (expanded) {
rowHeight += this.getDetailRowHeight(row);
}
return rowHeight;
}
/**
* Calculates the styles for the row so that the rows can be moved in 2D space
* during virtual scroll inside the DOM. In the below case the Y position is
* manipulated. As an example, if the height of row 0 is 30 px and row 1 is
* 100 px then following styles are generated:
*
* transform: translate3d(0px, 0px, 0px); -> row0
* transform: translate3d(0px, 30px, 0px); -> row1
* transform: translate3d(0px, 130px, 0px); -> row2
*
* Row heights have to be calculated based on the row heights cache as we wont
* be able to determine which row is of what height before hand. In the above
* case the positionY of the translate3d for row2 would be the sum of all the
* heights of the rows before it (i.e. row0 and row1).
*
* @param rows the row that needs to be placed in the 2D space.
* @returns the CSS3 style to be applied
*
* @memberOf DataTableBodyComponent
*/
getRowsStyles(rows) {
const styles = {};
// only add styles for the group if there is a group
if (this.groupedRows) {
styles.width = this.columnGroupWidths.total;
}
if (this.scrollbarV && this.virtualization) {
let idx = 0;
if (this.groupedRows) {
// Get the latest row rowindex in a group
const row = rows[rows.length - 1];
idx = row ? this.getRowIndex(row) : 0;
}
else {
idx = this.getRowIndex(rows);
}
// const pos = idx * rowHeight;
// The position of this row would be the sum of all row heights
// until the previous row position.
const pos = this.rowHeightsCache.query(idx - 1);
translateXY(styles, 0, pos);
}
return styles;
}
/**
* Calculate bottom summary row offset for scrollbar mode.
* For more information about cache and offset calculation
* see description for `getRowsStyles` method
*
* @returns the CSS3 style to be applied
*
* @memberOf DataTableBodyComponent
*/
getBottomSummaryRowStyles() {
if (!this.scrollbarV || !this.rows || !this.rows.length) {
return null;
}
const styles = { position: 'absolute' };
const pos = this.rowHeightsCache.query(this.rows.length - 1);
translateXY(styles, 0, pos);
return styles;
}
/**
* Hides the loading indicator
*/
hideIndicator() {
setTimeout(() => (this.loadingIndicator = false), 500);
}
/**
* Updates the index of the rows in the viewport
*/
updateIndexes() {
let first = 0;
let last = 0;
if (this.scrollbarV) {
if (this.virtualization) {
// Calculation of the first and last indexes will be based on where the
// scrollY position would be at. The last index would be the one
// that shows up inside the view port the last.
const height = parseInt(this.bodyHeight, 0);
first = this.rowHeightsCache.getRowIndex(this.offsetY);
last = this.rowHeightsCache.getRowIndex(height + this.offsetY) + 1;
}
else {
// If virtual rows are not needed
// We render all in one go
first = 0;
last = this.rowCount;
}
}
else {
// The server is handling paging and will pass an array that begins with the
// element at a specified offset. first should always be 0 with external paging.
if (!this.externalPaging) {
first = Math.max(this.offset * this.pageSize, 0);
}
last = Math.min(first + this.pageSize, this.rowCount);
}
this.indexes = { first, last };
}
/**
* Refreshes the full Row Height cache. Should be used
* when the entire row array state has changed.
*/
refreshRowHeightCache() {
if (!this.scrollbarV || (this.scrollbarV && !this.virtualization)) {
return;
}
// clear the previous row height cache if already present.
// this is useful during sorts, filters where the state of the
// rows array is changed.
this.rowHeightsCache.clearCache();
// Initialize the tree only if there are rows inside the tree.
if (this.rows && this.rows.length) {
const rowExpansions = new Set();
for (const row of this.rows) {
if (this.getRowExpanded(row)) {
rowExpansions.add(row);
}
}
this.rowHeightsCache.initCache({
rows: this.rows,
rowHeight: this.rowHeight,
detailRowHeight: this.getDetailRowHeight,
externalVirtual: this.scrollbarV && this.externalPaging,
rowCount: this.rowCount,
rowIndexes: this.rowIndexes,
rowExpansions
});
}
}
/**
* Gets the index for the view port
*/
getAdjustedViewPortIndex() {
// Capture the row index of the first row that is visible on the viewport.
// If the scroll bar is just below the row which is highlighted then make that as the
// first index.
const viewPortFirstRowIndex = this.indexes.first;
if (this.scrollbarV && this.virtualization) {
const offsetScroll = this.rowHeightsCache.query(viewPortFirstRowIndex - 1);
return offsetScroll <= this.offsetY ? viewPortFirstRowIndex - 1 : viewPortFirstRowIndex;
}
return viewPortFirstRowIndex;
}
/**
* Toggle the Expansion of the row i.e. if the row is expanded then it will
* collapse and vice versa. Note that the expanded status is stored as
* a part of the row object itself as we have to preserve the expanded row
* status in case of sorting and filtering of the row set.
*/
toggleRowExpansion(row) {
// Capture the row index of the first row that is visible on the viewport.
const viewPortFirstRowIndex = this.getAdjustedViewPortIndex();
const rowExpandedIdx = this.getRowExpandedIdx(row, this.rowExpansions);
const expanded = rowExpandedIdx > -1;
// If the detailRowHeight is auto --> only in case of non-virtualized scroll
if (this.scrollbarV && this.virtualization) {
const detailRowHeight = this.getDetailRowHeight(row) * (expanded ? -1 : 1);
// const idx = this.rowIndexes.get(row) || 0;
const idx = this.getRowIndex(row);
this.rowHeightsCache.update(idx, detailRowHeight);
}
// Update the toggled row and update thive nevere heights in the cache.
if (expanded) {
this.rowExpansions.splice(rowExpandedIdx, 1);
}
else {
this.rowExpansions.push(row);
}
this.detailToggle.emit({
rows: [row],
currentIndex: viewPortFirstRowIndex
});
}
/**
* Expand/Collapse all the rows no matter what their state is.
*/
toggleAllRows(expanded) {
// clear prev expansions
this.rowExpansions = [];
// Capture the row index of the first row that is visible on the viewport.
const viewPortFirstRowIndex = this.getAdjustedViewPortIndex();
if (expanded) {
for (const row of this.rows) {
this.rowExpansions.push(row);
}
}
if (this.scrollbarV) {
// Refresh the full row heights cache since every row was affected.
this.recalcLayout();
}
// Emit all rows that have been expanded.
this.detailToggle.emit({
rows: this.rows,
currentIndex: viewPortFirstRowIndex
});
}
/**
* Recalculates the table
*/
recalcLayout() {
this.refreshRowHeightCache();
this.updateIndexes();
this.updateRows();
}
/**
* Tracks the column
*/
columnTrackingFn(index, column) {
return column.$$id;
}
/**
* Gets the row pinning group styles
*/
stylesByGroup(group) {
const widths = this.columnGroupWidths;
const offsetX = this.offsetX;
const styles = {
width: `${widths[group]}px`
};
if (group === 'left') {
translateXY(styles, offsetX, 0);
}
else if (group === 'right') {
const bodyWidth = parseInt(this.innerWidth + '', 0);
const totalDiff = widths.total - bodyWidth;
const offsetDiff = totalDiff - offsetX;
const offset = offsetDiff * -1;
translateXY(styles, offset, 0);
}
return styles;
}
/**
* Returns if the row was expanded and set default row expansion when row expansion is empty
*/
getRowExpanded(row) {
if (this.rowExpansions.length === 0 && this.groupExpansionDefault) {
for (const group of this.groupedRows) {
this.rowExpansions.push(group);
}
}
return this.getRowExpandedIdx(row, this.rowExpansions) > -1;
}
getRowExpandedIdx(row, expanded) {
if (!expanded || !expanded.length)
return -1;
const rowId = this.rowIdentity(row);
return expanded.findIndex(r => {
const id = this.rowIdentity(r);
return id === rowId;
});
}
/**
* Gets the row index given a row
*/
getRowIndex(row) {
return this.rowIndexes.get(row) || 0;
}
onTreeAction(row) {
this.treeAction.emit({ row });
}
}
DataTableBodyComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.1.1", ngImport: i0, type: DataTableBodyComponent, deps: [{ token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Component });
DataTableBodyComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.1.1", type: DataTableBodyComponent, selector: "datatable-body", inputs: { scrollbarV: "scrollbarV", scrollbarH: "scrollbarH", loadingIndicator: "loadingIndicator", externalPaging: "externalPaging", rowHeight: "rowHeight", offsetX: "offsetX", emptyMessage: "emptyMessage", selectionType: "selectionType", selected: "selected", rowIdentity: "rowIdentity", rowDetail: "rowDetail", groupHeader: "groupHeader", selectCheck: "selectCheck", displayCheck: "displayCheck", trackByProp: "trackByProp", rowClass: "rowClass", groupedRows: "groupedRows", groupExpansionDefault: "groupExpansionDefault", innerWidth: "innerWidth", groupRowsBy: "groupRowsBy", virtualization: "virtualization", summaryRow: "summaryRow", summaryPosition: "summaryPosition", summaryHeight: "summaryHeight", pageSize: "pageSize", rows: "rows", columns: "columns", offset: "offset", rowCount: "rowCount", bodyHeight: "bodyHeight" }, outputs: { scroll: "scroll", page: "page", activate: "activate", select: "select", detailToggle: "detailToggle", rowContextmenu: "rowContextmenu", treeAction: "treeAction" }, host: { properties: { "style.width": "this.bodyWidth", "style.height": "this.bodyHeight" }, classAttribute: "datatable-body" }, viewQueries: [{ propertyName: "scroller", first: true, predicate: ScrollerComponent, descendants: true }], ngImport: i0, template: `
`, isInline: true, components: [{ type: ProgressBarComponent, selector: "datatable-progress" }, { type: DataTableSelectionComponent, selector: "datatable-selection", inputs: ["rows", "selected", "selectEnabled", "selectionType", "rowIdentity", "selectCheck"], outputs: ["activate", "select"] }, { type: ScrollerComponent, selector: "datatable-scroller", inputs: ["scrollbarV", "scrollbarH", "scrollHeight", "scrollWidth"], outputs: ["scroll"] }, { type: DataTableSummaryRowComponent, selector: "datatable-summary-row", inputs: ["rows", "columns", "rowHeight", "offsetX", "innerWidth"] }, { type: DataTableRowWrapperComponent, selector: "datatable-row-wrapper", inputs: ["innerWidth", "rowDetail", "groupHeader", "offsetX", "detailRowHeight", "row", "groupedRows", "rowIndex", "expanded"], outputs: ["rowContextmenu"] }, { type: DataTableBodyRowComponent, selector: "datatable-body-row", inputs: ["columns", "innerWidth", "expanded", "rowClass", "row", "group", "isSelected", "rowIndex", "displayCheck", "treeStatus", "offsetX", "rowHeight"], outputs: ["activate", "treeAction"] }], directives: [{ type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { type: i1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { type: i1.NgStyle, selector: "[ngStyle]", inputs: ["ngStyle"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.1.1", ngImport: i0, type: DataTableBodyComponent, decorators: [{
type: Component,
args: [{
selector: 'datatable-body',
template: `
`,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
class: 'datatable-body'
}
}]
}], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }]; }, propDecorators: { scrollbarV: [{
type: Input
}], scrollbarH: [{
type: Input
}], loadingIndicator: [{
type: Input
}], externalPaging: [{
type: Input
}], rowHeight: [{
type: Input
}], offsetX: [{
type: Input
}], emptyMessage: [{
type: Input
}], selectionType: [{
type: Input
}], selected: [{
type: Input
}], rowIdentity: [{
type: Input
}], rowDetail: [{
type: Input
}], groupHeader: [{
type: Input
}], selectCheck: [{
type: Input
}], displayCheck: [{
type: Input
}], trackByProp: [{
type: Input
}], rowClass: [{
type: Input
}], groupedRows: [{
type: Input
}], groupExpansionDefault: [{
type: Input
}], innerWidth: [{
type: Input
}], groupRowsBy: [{
type: Input
}], virtualization: [{
type: Input
}], summaryRow: [{
type: Input
}], summaryPosition: [{
type: Input
}], summaryHeight: [{
type: Input
}], pageSize: [{
type: Input
}], rows: [{
type: Input
}], columns: [{
type: Input
}], offset: [{
type: Input
}], rowCount: [{
type: Input
}], bodyWidth: [{
type: HostBinding,
args: ['style.width']
}], bodyHeight: [{
type: Input
}, {
type: HostBinding,
args: ['style.height']
}], scroll: [{
type: Output
}], page: [{
type: Output
}], activate: [{
type: Output
}], select: [{
type: Output
}], detailToggle: [{
type: Output
}], rowContextmenu: [{
type: Output
}], treeAction: [{
type: Output
}], scroller: [{
type: ViewChild,
args: [ScrollerComponent]
}] } });
/**
* Gets the next sort direction
*/
function nextSortDir(sortType, current) {
if (sortType === SortType.single) {
if (current === SortDirection.asc) {
return SortDirection.desc;
}
else {
return SortDirection.asc;
}
}
else {
if (!current) {
return SortDirection.asc;
}
else if (current === SortDirection.asc) {
return SortDirection.desc;
}
else if (current === SortDirection.desc) {
return undefined;
}
// avoid TS7030: Not all code paths return a value.
return undefined;
}
}
/**
* Adapted from fueld-ui on 6/216
* https://github.com/FuelInteractive/fuel-ui/tree/master/src/pipes/OrderBy
*/
function orderByComparator(a, b) {
if (a === null || typeof a === 'undefined')
a = 0;
if (b === null || typeof b === 'undefined')
b = 0;
if (a instanceof Date && b instanceof Date) {
if (a < b)
return -1;
if (a > b)
return 1;
}
else if (isNaN(parseFloat(a)) || !isFinite(a) || isNaN(parseFloat(b)) || !isFinite(b)) {
// Convert to string in case of a=0 or b=0
a = String(a);
b = String(b);
// Isn't a number so lowercase the string to properly compare
if (a.toLowerCase() < b.toLowerCase())
return -1;
if (a.toLowerCase() > b.toLowerCase())
return 1;
}
else {
// Parse strings as numbers to compare properly
if (parseFloat(a) < parseFloat(b))
return -1;
if (parseFloat(a) > parseFloat(b))
return 1;
}
// equal each other
return 0;
}
/**
* creates a shallow copy of the `rows` input and returns the sorted copy. this function
* does not sort the `rows` argument in place
*/
function sortRows(rows, columns, dirs) {
if (!rows)
return [];
if (!dirs || !dirs.length || !columns)
return [...rows];
/**
* record the row ordering of results from prior sort operations (if applicable)
* this is necessary to guarantee stable sorting behavior
*/
const rowToIndexMap = new Map();
rows.forEach((row, index) => rowToIndexMap.set(row, index));
const temp = [...rows];
const cols = columns.reduce((obj, col) => {
if (col.comparator && typeof col.comparator === 'function') {
obj[col.prop] = col.comparator;
}
return obj;
}, {});
// cache valueGetter and compareFn so that they
// do not need to be looked-up in the sort function body
const cachedDirs = dirs.map(dir => {
const prop = dir.prop;
return {
prop,
dir: dir.dir,
valueGetter: getterForProp(prop),
compareFn: cols[prop] || orderByComparator
};
});
return temp.sort(function (rowA, rowB) {
for (const cachedDir of cachedDirs) {
// Get property and valuegetters for column to be sorted
const { prop, valueGetter } = cachedDir;
// Get A and B cell values from rows based on properties of the columns
const propA = valueGetter(rowA, prop);
const propB = valueGetter(rowB, prop);
// Compare function gets five parameters:
// Two cell values to be compared as propA and propB
// Two rows corresponding to the cells as rowA and rowB
// Direction of the sort for this column as SortDirection
// Compare can be a standard JS comparison function (a,b) => -1|0|1
// as additional parameters are silently ignored. The whole row and sort
// direction enable more complex sort logic.
const comparison = cachedDir.dir !== SortDirection.desc
? cachedDir.compareFn(propA, propB, rowA, rowB, cachedDir.dir)
: -cachedDir.compareFn(propA, propB, rowA, rowB, cachedDir.dir);
// Don't return 0 yet in case of needing to sort by next property
if (comparison !== 0)
return comparison;
}
if (!(rowToIndexMap.has(rowA) && rowToIndexMap.has(rowB)))
return 0;
/**
* all else being equal, preserve original order of the rows (stable sort)
*/
return rowToIndexMap.get(rowA) < rowToIndexMap.get(rowB) ? -1 : 1;
});
}
class DataTableHeaderCellComponent {
constructor(cd) {
this.cd = cd;
this.sort = new EventEmitter();
this.select = new EventEmitter();
this.columnContextmenu = new EventEmitter(false);
this.sortFn = this.onSort.bind(this);
this.selectFn = this.select.emit.bind(this.select);
this.cellContext = {
column: this.column,
sortDir: this.sortDir,
sortFn: this.sortFn,
allRowsSelected: this.allRowsSelected,
selectFn: this.selectFn
};
}
set allRowsSelected(value) {
this._allRowsSelected = value;
this.cellContext.allRowsSelected = value;
}
get allRowsSelected() {
return this._allRowsSelected;
}
set column(column) {
this._column = column;
this.cellContext.column = column;
this.cd.markForCheck();
}
get column() {
return this._column;
}
set sorts(val) {
this._sorts = val;
this.sortDir = this.calcSortDir(val);
this.cellContext.sortDir = this.sortDir;
this.sortClass = this.calcSortClass(this.sortDir);
this.cd.markForCheck();
}
get sorts() {
return this._sorts;
}
get columnCssClasses() {
let cls = 'datatable-header-cell';
if (this.column.sortable)
cls += ' sortable';
if (this.column.resizeable)
cls += ' resizeable';
if (this.column.headerClass) {
if (typeof this.column.headerClass === 'string') {
cls += ' ' + this.column.headerClass;
}
else if (typeof this.column.headerClass === 'function') {
const res = this.column.headerClass({
column: this.column
});
if (typeof res === 'string') {
cls += res;
}
else if (typeof res === 'object') {
const keys = Object.keys(res);
for (const k of keys) {
if (res[k] === true)
cls += ` ${k}`;
}
}
}
}
const sortDir = this.sortDir;
if (sortDir) {
cls += ` sort-active sort-${sortDir}`;
}
return cls;
}
get name() {
// guaranteed to have a value by setColumnDefaults() in column-helper.ts
return this.column.headerTemplate === undefined ? this.column.name : undefined;
}
get minWidth() {
return this.column.minWidth;
}
get maxWidth() {
return this.column.maxWidth;
}
get width() {
return this.column.width;
}
get isCheckboxable() {
return this.column.checkboxable && this.column.headerCheckboxable && this.selectionType === SelectionType.checkbox;
}
onContextmenu($event) {
this.columnContextmenu.emit({ event: $event, column: this.column });
}
ngOnInit() {
this.sortClass = this.calcSortClass(this.sortDir);
}
calcSortDir(sorts) {
if (sorts && this.column) {
const sort = sorts.find((s) => {
return s.prop === this.column.prop;
});
if (sort)
return sort.dir;
}
}
onSort() {
if (!this.column.sortable)
return;
const newValue = nextSortDir(this.sortType, this.sortDir);
this.sort.emit({
column: this.column,
prevValue: this.sortDir,
newValue
});
}
calcSortClass(sortDir) {
if (!this.cellContext.column.sortable)
return;
if (sortDir === SortDirection.asc) {
return `sort-btn sort-asc ${this.sortAscendingIcon}`;
}
else if (sortDir === SortDirection.desc) {
return `sort-btn sort-desc ${this.sortDescendingIcon}`;
}
else {
return `sort-btn ${this.sortUnsetIcon}`;
}
}
}
DataTableHeaderCellComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.1.1", ngImport: i0, type: DataTableHeaderCellComponent, deps: [{ token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Component });
DataTableHeaderCellComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.1.1", type: DataTableHeaderCellComponent, selector: "datatable-header-cell", inputs: { sortType: "sortType", sortAscendingIcon: "sortAscendingIcon", sortDescendingIcon: "sortDescendingIcon", sortUnsetIcon: "sortUnsetIcon", isTarget: "isTarget", targetMarkerTemplate: "targetMarkerTemplate", targetMarkerContext: "targetMarkerContext", allRowsSelected: "allRowsSelected", selectionType: "selectionType", column: "column", headerHeight: "headerHeight", sorts: "sorts" }, outputs: { sort: "sort", select: "select", columnContextmenu: "columnContextmenu" }, host: { listeners: { "contextmenu": "onContextmenu($event)" }, properties: { "style.height.px": "this.headerHeight", "class": "this.columnCssClasses", "attr.title": "this.name", "style.minWidth.px": "this.minWidth", "style.maxWidth.px": "this.maxWidth", "style.width.px": "this.width" }, classAttribute: "datatable-header-cell" }, ngImport: i0, template: `
`,
host: {
class: 'datatable-pager'
},
changeDetection: ChangeDetectionStrategy.OnPush
}]
}], propDecorators: { pagerLeftArrowIcon: [{
type: Input
}], pagerRightArrowIcon: [{
type: Input
}], pagerPreviousIcon: [{
type: Input
}], pagerNextIcon: [{
type: Input
}], size: [{
type: Input
}], count: [{
type: Input
}], page: [{
type: Input
}], change: [{
type: Output
}] } });
class DataTableFooterComponent {
constructor() {
this.selectedCount = 0;
this.page = new EventEmitter();
}
get isVisible() {
return this.rowCount / this.pageSize > 1;
}
get curPage() {
return this.offset + 1;
}
}
DataTableFooterComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.1.1", ngImport: i0, type: DataTableFooterComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
DataTableFooterComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.1.1", type: DataTableFooterComponent, selector: "datatable-footer", inputs: { footerHeight: "footerHeight", rowCount: "rowCount", pageSize: "pageSize", offset: "offset", pagerLeftArrowIcon: "pagerLeftArrowIcon", pagerRightArrowIcon: "pagerRightArrowIcon", pagerPreviousIcon: "pagerPreviousIcon", pagerNextIcon: "pagerNextIcon", totalMessage: "totalMessage", footerTemplate: "footerTemplate", selectedCount: "selectedCount", selectedMessage: "selectedMessage" }, outputs: { page: "page" }, host: { classAttribute: "datatable-footer" }, ngImport: i0, template: `
`, isInline: true, components: [{ type: DataTablePagerComponent, selector: "datatable-pager", inputs: ["pagerLeftArrowIcon", "pagerRightArrowIcon", "pagerPreviousIcon", "pagerNextIcon", "size", "count", "page"], outputs: ["change"] }], directives: [{ type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { type: i1.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.1.1", ngImport: i0, type: DataTableFooterComponent, decorators: [{
type: Component,
args: [{
selector: 'datatable-footer',
template: `
`,
host: {
class: 'datatable-footer'
},
changeDetection: ChangeDetectionStrategy.OnPush
}]
}], propDecorators: { footerHeight: [{
type: Input
}], rowCount: [{
type: Input
}], pageSize: [{
type: Input
}], offset: [{
type: Input
}], pagerLeftArrowIcon: [{
type: Input
}], pagerRightArrowIcon: [{
type: Input
}], pagerPreviousIcon: [{
type: Input
}], pagerNextIcon: [{
type: Input
}], totalMessage: [{
type: Input
}], footerTemplate: [{
type: Input
}], selectedCount: [{
type: Input
}], selectedMessage: [{
type: Input
}], page: [{
type: Output
}] } });
class DatatableComponent {
constructor(scrollbarHelper, dimensionsHelper, cd, element, differs, columnChangesService, configuration) {
this.scrollbarHelper = scrollbarHelper;
this.dimensionsHelper = dimensionsHelper;
this.cd = cd;
this.columnChangesService = columnChangesService;
this.configuration = configuration;
/**
* List of row objects that should be
* represented as selected in the grid.
* Default value: `[]`
*/
this.selected = [];
/**
* Enable vertical scrollbars
*/
this.scrollbarV = false;
/**
* Enable horz scrollbars
*/
this.scrollbarH = false;
/**
* The row height; which is necessary
* to calculate the height for the lazy rendering.
*/
this.rowHeight = 30;
/**
* Type of column width distribution formula.
* Example: flex, force, standard
*/
this.columnMode = ColumnMode.standard;
/**
* The minimum header height in pixels.
* Pass a falsey for no header
*/
this.headerHeight = 30;
/**
* The minimum footer height in pixels.
* Pass falsey for no footer
*/
this.footerHeight = 0;
/**
* If the table should use external paging
* otherwise its assumed that all data is preloaded.
*/
this.externalPaging = false;
/**
* If the table should use external sorting or
* the built-in basic sorting.
*/
this.externalSorting = false;
/**
* Show the linear loading bar.
* Default value: `false`
*/
this.loadingIndicator = false;
/**
* Enable/Disable ability to re-order columns
* by dragging them.
*/
this.reorderable = true;
/**
* Swap columns on re-order columns or
* move them.
*/
this.swapColumns = true;
/**
* The type of sorting
*/
this.sortType = SortType.single;
/**
* Array of sorted columns by property and type.
* Default value: `[]`
*/
this.sorts = [];
/**
* Css class overrides
*/
this.cssClasses = {
sortAscending: 'datatable-icon-up',
sortDescending: 'datatable-icon-down',
sortUnset: 'datatable-icon-sort-unset',
pagerLeftArrow: 'datatable-icon-left',
pagerRightArrow: 'datatable-icon-right',
pagerPrevious: 'datatable-icon-prev',
pagerNext: 'datatable-icon-skip'
};
/**
* Message overrides for localization
*
* emptyMessage [default] = 'No data to display'
* totalMessage [default] = 'total'
* selectedMessage [default] = 'selected'
*/
this.messages = {
// Message to show when array is presented
// but contains no values
emptyMessage: 'No data to display',
// Footer total message
totalMessage: 'total',
// Footer selected message
selectedMessage: 'selected'
};
/**
* A boolean you can use to set the detault behaviour of rows and groups
* whether they will start expanded or not. If ommited the default is NOT expanded.
*
*/
this.groupExpansionDefault = false;
/**
* Property to which you can use for determining select all
* rows on current page or not.
*
* @memberOf DatatableComponent
*/
this.selectAllRowsOnPage = false;
/**
* A flag for row virtualization on / off
*/
this.virtualization = true;
/**
* A flag for switching summary row on / off
*/
this.summaryRow = false;
/**
* A height of summary row
*/
this.summaryHeight = 30;
/**
* A property holds a summary row position: top/bottom
*/
this.summaryPosition = 'top';
/**
* Body was scrolled typically in a `scrollbarV:true` scenario.
*/
this.scroll = new EventEmitter();
/**
* A cell or row was focused via keyboard or mouse click.
*/
this.activate = new EventEmitter();
/**
* A cell or row was selected.
*/
this.select = new EventEmitter();
/**
* Column sort was invoked.
*/
this.sort = new EventEmitter();
/**
* The table was paged either triggered by the pager or the body scroll.
*/
this.page = new EventEmitter();
/**
* Columns were re-ordered.
*/
this.reorder = new EventEmitter();
/**
* Column was resized.
*/
this.resize = new EventEmitter();
/**
* The context menu was invoked on the table.
* type indicates whether the header or the body was clicked.
* content contains either the column or the row that was clicked.
*/
this.tableContextmenu = new EventEmitter(false);
/**
* A row was expanded ot collapsed for tree
*/
this.treeAction = new EventEmitter();
this.rowCount = 0;
this._offsetX = new BehaviorSubject(0);
this._count = 0;
this._offset = 0;
this._subscriptions = [];
/**
* This will be used when displaying or selecting rows.
* when tracking/comparing them, we'll use the value of this fn,
*
* (`fn(x) === fn(y)` instead of `x === y`)
*/
this.rowIdentity = (x) => {
if (this._groupRowsBy) {
// each group in groupedRows are stored as {key, value: [rows]},
// where key is the groupRowsBy index
return x.key;
}
else {
return x;
}
};
// get ref to elm for measuring
this.element = element.nativeElement;
this.rowDiffer = differs.find({}).create();
// apply global settings from Module.forRoot
if (this.configuration && this.configuration.messages) {
this.messages = Object.assign({}, this.configuration.messages);
}
}
/**
* Rows that are displayed in the table.
*/
set rows(val) {
this._rows = val;
if (val) {
this._internalRows = [...val];
}
// auto sort on new updates
if (!this.externalSorting) {
this.sortInternalRows();
}
// auto group by parent on new update
this._internalRows = groupRowsByParents(this._internalRows, optionalGetterForProp(this.treeFromRelation), optionalGetterForProp(this.treeToRelation));
// recalculate sizes/etc
this.recalculate();
if (this._rows && this._groupRowsBy) {
// If a column has been specified in _groupRowsBy created a new array with the data grouped by that row
this.groupedRows = this.groupArrayBy(this._rows, this._groupRowsBy);
}
this.cd.markForCheck();
}
/**
* Gets the rows.
*/
get rows() {
return this._rows;
}
/**
* This attribute allows the user to set the name of the column to group the data with
*/
set groupRowsBy(val) {
if (val) {
this._groupRowsBy = val;
if (this._rows && this._groupRowsBy) {
// cretes a new array with the data grouped
this.groupedRows = this.groupArrayBy(this._rows, this._groupRowsBy);
}
}
}
get groupRowsBy() {
return this._groupRowsBy;
}
/**
* Columns to be displayed.
*/
set columns(val) {
if (val) {
this._internalColumns = [...val];
setColumnDefaults(this._internalColumns);
this.recalculateColumns();
}
this._columns = val;
}
/**
* Get the columns.
*/
get columns() {
return this._columns;
}
/**
* The page size to be shown.
* Default value: `undefined`
*/
set limit(val) {
this._limit = val;
// recalculate sizes/etc
this.recalculate();
}
/**
* Gets the limit.
*/
get limit() {
return this._limit;
}
/**
* The total count of all rows.
* Default value: `0`
*/
set count(val) {
this._count = val;
// recalculate sizes/etc
this.recalculate();
}
/**
* Gets the count.
*/
get count() {
return this._count;
}
/**
* The current offset ( page - 1 ) shown.
* Default value: `0`
*/
set offset(val) {
this._offset = val;
}
get offset() {
return Math.max(Math.min(this._offset, Math.ceil(this.rowCount / this.pageSize) - 1), 0);
}
/**
* CSS class applied if the header height if fixed height.
*/
get isFixedHeader() {
const headerHeight = this.headerHeight;
return typeof headerHeight === 'string' ? headerHeight !== 'auto' : true;
}
/**
* CSS class applied to the root element if
* the row heights are fixed heights.
*/
get isFixedRow() {
return this.rowHeight !== 'auto';
}
/**
* CSS class applied to root element if
* vertical scrolling is enabled.
*/
get isVertScroll() {
return this.scrollbarV;
}
/**
* CSS class applied to root element if
* virtualization is enabled.
*/
get isVirtualized() {
return this.virtualization;
}
/**
* CSS class applied to the root element
* if the horziontal scrolling is enabled.
*/
get isHorScroll() {
return this.scrollbarH;
}
/**
* CSS class applied to root element is selectable.
*/
get isSelectable() {
return this.selectionType !== undefined;
}
/**
* CSS class applied to root is checkbox selection.
*/
get isCheckboxSelection() {
return this.selectionType === SelectionType.checkbox;
}
/**
* CSS class applied to root if cell selection.
*/
get isCellSelection() {
return this.selectionType === SelectionType.cell;
}
/**
* CSS class applied to root if single select.
*/
get isSingleSelection() {
return this.selectionType === SelectionType.single;
}
/**
* CSS class added to root element if mulit select
*/
get isMultiSelection() {
return this.selectionType === SelectionType.multi;
}
/**
* CSS class added to root element if mulit click select
*/
get isMultiClickSelection() {
return this.selectionType === SelectionType.multiClick;
}
/**
* Column templates gathered from `ContentChildren`
* if described in your markup.
*/
set columnTemplates(val) {
this._columnTemplates = val;
this.translateColumns(val);
}
/**
* Returns the column templates.
*/
get columnTemplates() {
return this._columnTemplates;
}
/**
* Returns if all rows are selected.
*/
get allRowsSelected() {
let allRowsSelected = this.rows && this.selected && this.selected.length === this.rows.length;
if (this.bodyComponent && this.selectAllRowsOnPage) {
const indexes = this.bodyComponent.indexes;
const rowsOnPage = indexes.last - indexes.first;
allRowsSelected = this.selected.length === rowsOnPage;
}
return this.selected && this.rows && this.rows.length !== 0 && allRowsSelected;
}
/**
* Lifecycle hook that is called after data-bound
* properties of a directive are initialized.
*/
ngOnInit() {
// need to call this immediatly to size
// if the table is hidden the visibility
// listener will invoke this itself upon show
this.recalculate();
}
/**
* Lifecycle hook that is called after a component's
* view has been fully initialized.
*/
ngAfterViewInit() {
if (!this.externalSorting) {
this.sortInternalRows();
}
// this has to be done to prevent the change detection
// tree from freaking out because we are readjusting
if (typeof requestAnimationFrame === 'undefined') {
return;
}
requestAnimationFrame(() => {
this.recalculate();
// emit page for virtual server-side kickoff
if (this.externalPaging && this.scrollbarV) {
this.page.emit({
count: this.count,
pageSize: this.pageSize,
limit: this.limit,
offset: 0
});
}
});
}
/**
* Lifecycle hook that is called after a component's
* content has been fully initialized.
*/
ngAfterContentInit() {
this.columnTemplates.changes.subscribe(v => this.translateColumns(v));
this.listenForColumnInputChanges();
}
/**
* Translates the templates to the column objects
*/
translateColumns(val) {
if (val) {
const arr = val.toArray();
if (arr.length) {
this._internalColumns = translateTemplates(arr);
setColumnDefaults(this._internalColumns);
this.recalculateColumns();
this.sortInternalRows();
this.cd.markForCheck();
}
}
}
/**
* Creates a map with the data grouped by the user choice of grouping index
*
* @param originalArray the original array passed via parameter
* @param groupByIndex the index of the column to group the data by
*/
groupArrayBy(originalArray, groupBy) {
// create a map to hold groups with their corresponding results
const map = new Map();
let i = 0;
originalArray.forEach((item) => {
const key = item[groupBy];
if (!map.has(key)) {
map.set(key, [item]);
}
else {
map.get(key).push(item);
}
i++;
});
const addGroup = (key, value) => {
return { key, value };
};
// convert map back to a simple array of objects
return Array.from(map, x => addGroup(x[0], x[1]));
}
/*
* Lifecycle hook that is called when Angular dirty checks a directive.
*/
ngDoCheck() {
if (this.rowDiffer.diff(this.rows)) {
if (!this.externalSorting) {
this.sortInternalRows();
}
else {
this._internalRows = [...this.rows];
}
// auto group by parent on new update
this._internalRows = groupRowsByParents(this._internalRows, optionalGetterForProp(this.treeFromRelation), optionalGetterForProp(this.treeToRelation));
this.recalculatePages();
this.cd.markForCheck();
}
}
/**
* Recalc's the sizes of the grid.
*
* Updated automatically on changes to:
*
* - Columns
* - Rows
* - Paging related
*
* Also can be manually invoked or upon window resize.
*/
recalculate() {
this.recalculateDims();
this.recalculateColumns();
this.cd.markForCheck();
}
/**
* Window resize handler to update sizes.
*/
onWindowResize() {
this.recalculate();
}
/**
* Recalulcates the column widths based on column width
* distribution mode and scrollbar offsets.
*/
recalculateColumns(columns = this._internalColumns, forceIdx = -1, allowBleed = this.scrollbarH) {
if (!columns)
return undefined;
let width = this._innerWidth;
if (this.scrollbarV) {
width = width - this.scrollbarHelper.width;
}
if (this.columnMode === ColumnMode.force) {
forceFillColumnWidths(columns, width, forceIdx, allowBleed);
}
else if (this.columnMode === ColumnMode.flex) {
adjustColumnWidths(columns, width);
}
return columns;
}
/**
* Recalculates the dimensions of the table size.
* Internally calls the page size and row count calcs too.
*
*/
recalculateDims() {
const dims = this.dimensionsHelper.getDimensions(this.element);
this._innerWidth = Math.floor(dims.width);
if (this.scrollbarV) {
let height = dims.height;
if (this.headerHeight)
height = height - this.headerHeight;
if (this.footerHeight)
height = height - this.footerHeight;
this.bodyHeight = height;
}
this.recalculatePages();
}
/**
* Recalculates the pages after a update.
*/
recalculatePages() {
this.pageSize = this.calcPageSize();
this.rowCount = this.calcRowCount();
}
/**
* Body triggered a page event.
*/
onBodyPage({ offset }) {
// Avoid pagination caming from body events like scroll when the table
// has no virtualization and the external paging is enable.
// This means, let's the developer handle pagination by my him(her) self
if (this.externalPaging && !this.virtualization) {
return;
}
this.offset = offset;
this.page.emit({
count: this.count,
pageSize: this.pageSize,
limit: this.limit,
offset: this.offset
});
}
/**
* The body triggered a scroll event.
*/
onBodyScroll(event) {
this._offsetX.next(event.offsetX);
this.scroll.emit(event);
this.cd.detectChanges();
}
/**
* The footer triggered a page event.
*/
onFooterPage(event) {
this.offset = event.page - 1;
this.bodyComponent.updateOffsetY(this.offset);
this.page.emit({
count: this.count,
pageSize: this.pageSize,
limit: this.limit,
offset: this.offset
});
if (this.selectAllRowsOnPage) {
this.selected = [];
this.select.emit({
selected: this.selected
});
}
}
/**
* Recalculates the sizes of the page
*/
calcPageSize(val = this.rows) {
// Keep the page size constant even if the row has been expanded.
// This is because an expanded row is still considered to be a child of
// the original row. Hence calculation would use rowHeight only.
if (this.scrollbarV && this.virtualization) {
const size = Math.ceil(this.bodyHeight / this.rowHeight);
return Math.max(size, 0);
}
// if limit is passed, we are paging
if (this.limit !== undefined) {
return this.limit;
}
// otherwise use row length
if (val) {
return val.length;
}
// other empty :(
return 0;
}
/**
* Calculates the row count.
*/
calcRowCount(val = this.rows) {
if (!this.externalPaging) {
if (!val)
return 0;
if (this.groupedRows) {
return this.groupedRows.length;
}
else if (this.treeFromRelation != null && this.treeToRelation != null) {
return this._internalRows.length;
}
else {
return val.length;
}
}
return this.count;
}
/**
* The header triggered a contextmenu event.
*/
onColumnContextmenu({ event, column }) {
this.tableContextmenu.emit({ event, type: ContextmenuType.header, content: column });
}
/**
* The body triggered a contextmenu event.
*/
onRowContextmenu({ event, row }) {
this.tableContextmenu.emit({ event, type: ContextmenuType.body, content: row });
}
/**
* The header triggered a column resize event.
*/
onColumnResize({ column, newValue }) {
/* Safari/iOS 10.2 workaround */
if (column === undefined) {
return;
}
let idx;
const cols = this._internalColumns.map((c, i) => {
c = Object.assign({}, c);
if (c.$$id === column.$$id) {
idx = i;
c.width = newValue;
// set this so we can force the column
// width distribution to be to this value
c.$$oldWidth = newValue;
}
return c;
});
this.recalculateColumns(cols, idx);
this._internalColumns = cols;
this.resize.emit({
column,
newValue
});
}
/**
* The header triggered a column re-order event.
*/
onColumnReorder({ column, newValue, prevValue }) {
const cols = this._internalColumns.map(c => {
return Object.assign({}, c);
});
if (this.swapColumns) {
const prevCol = cols[newValue];
cols[newValue] = column;
cols[prevValue] = prevCol;
}
else {
if (newValue > prevValue) {
const movedCol = cols[prevValue];
for (let i = prevValue; i < newValue; i++) {
cols[i] = cols[i + 1];
}
cols[newValue] = movedCol;
}
else {
const movedCol = cols[prevValue];
for (let i = prevValue; i > newValue; i--) {
cols[i] = cols[i - 1];
}
cols[newValue] = movedCol;
}
}
this._internalColumns = cols;
this.reorder.emit({
column,
newValue,
prevValue
});
}
/**
* The header triggered a column sort event.
*/
onColumnSort(event) {
// clean selected rows
if (this.selectAllRowsOnPage) {
this.selected = [];
this.select.emit({
selected: this.selected
});
}
this.sorts = event.sorts;
// this could be optimized better since it will resort
// the rows again on the 'push' detection...
if (this.externalSorting === false) {
// don't use normal setter so we don't resort
this.sortInternalRows();
}
// auto group by parent on new update
this._internalRows = groupRowsByParents(this._internalRows, optionalGetterForProp(this.treeFromRelation), optionalGetterForProp(this.treeToRelation));
// Always go to first page when sorting to see the newly sorted data
this.offset = 0;
this.bodyComponent.updateOffsetY(this.offset);
this.sort.emit(event);
}
/**
* Toggle all row selection
*/
onHeaderSelect(event) {
if (this.bodyComponent && this.selectAllRowsOnPage) {
// before we splice, chk if we currently have all selected
const first = this.bodyComponent.indexes.first;
const last = this.bodyComponent.indexes.last;
const allSelected = this.selected.length === last - first;
// remove all existing either way
this.selected = [];
// do the opposite here
if (!allSelected) {
this.selected.push(...this._internalRows.slice(first, last));
}
}
else {
// before we splice, chk if we currently have all selected
const allSelected = this.selected.length === this.rows.length;
// remove all existing either way
this.selected = [];
// do the opposite here
if (!allSelected) {
this.selected.push(...this.rows);
}
}
this.select.emit({
selected: this.selected
});
}
/**
* A row was selected from body
*/
onBodySelect(event) {
this.select.emit(event);
}
/**
* A row was expanded or collapsed for tree
*/
onTreeAction(event) {
const row = event.row;
// TODO: For duplicated items this will not work
const rowIndex = this._rows.findIndex(r => r[this.treeToRelation] === event.row[this.treeToRelation]);
this.treeAction.emit({ row, rowIndex });
}
ngOnDestroy() {
this._subscriptions.forEach(subscription => subscription.unsubscribe());
}
/**
* listen for changes to input bindings of all DataTableColumnDirective and
* trigger the columnTemplates.changes observable to emit
*/
listenForColumnInputChanges() {
this._subscriptions.push(this.columnChangesService.columnInputChanges$.subscribe(() => {
if (this.columnTemplates) {
this.columnTemplates.notifyOnChanges();
}
}));
}
sortInternalRows() {
this._internalRows = sortRows(this._internalRows, this._internalColumns, this.sorts);
}
}
DatatableComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.1.1", ngImport: i0, type: DatatableComponent, deps: [{ token: ScrollbarHelper, skipSelf: true }, { token: DimensionsHelper, skipSelf: true }, { token: i0.ChangeDetectorRef }, { token: i0.ElementRef }, { token: i0.KeyValueDiffers }, { token: ColumnChangesService }, { token: 'configuration', optional: true }], target: i0.ɵɵFactoryTarget.Component });
DatatableComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.1.1", type: DatatableComponent, selector: "ngx-datatable", inputs: { targetMarkerTemplate: "targetMarkerTemplate", rows: "rows", groupRowsBy: "groupRowsBy", groupedRows: "groupedRows", columns: "columns", selected: "selected", scrollbarV: "scrollbarV", scrollbarH: "scrollbarH", rowHeight: "rowHeight", columnMode: "columnMode", headerHeight: "headerHeight", footerHeight: "footerHeight", externalPaging: "externalPaging", externalSorting: "externalSorting", limit: "limit", count: "count", offset: "offset", loadingIndicator: "loadingIndicator", selectionType: "selectionType", reorderable: "reorderable", swapColumns: "swapColumns", sortType: "sortType", sorts: "sorts", cssClasses: "cssClasses", messages: "messages", rowClass: "rowClass", selectCheck: "selectCheck", displayCheck: "displayCheck", groupExpansionDefault: "groupExpansionDefault", trackByProp: "trackByProp", selectAllRowsOnPage: "selectAllRowsOnPage", virtualization: "virtualization", treeFromRelation: "treeFromRelation", treeToRelation: "treeToRelation", summaryRow: "summaryRow", summaryHeight: "summaryHeight", summaryPosition: "summaryPosition", rowIdentity: "rowIdentity" }, outputs: { scroll: "scroll", activate: "activate", select: "select", sort: "sort", page: "page", reorder: "reorder", resize: "resize", tableContextmenu: "tableContextmenu", treeAction: "treeAction" }, host: { listeners: { "window:resize": "onWindowResize()" }, properties: { "class.fixed-header": "this.isFixedHeader", "class.fixed-row": "this.isFixedRow", "class.scroll-vertical": "this.isVertScroll", "class.virtualized": "this.isVirtualized", "class.scroll-horz": "this.isHorScroll", "class.selectable": "this.isSelectable", "class.checkbox-selection": "this.isCheckboxSelection", "class.cell-selection": "this.isCellSelection", "class.single-selection": "this.isSingleSelection", "class.multi-selection": "this.isMultiSelection", "class.multi-click-selection": "this.isMultiClickSelection" }, classAttribute: "ngx-datatable" }, queries: [{ propertyName: "rowDetail", first: true, predicate: DatatableRowDetailDirective, descendants: true }, { propertyName: "groupHeader", first: true, predicate: DatatableGroupHeaderDirective, descendants: true }, { propertyName: "footer", first: true, predicate: DatatableFooterDirective, descendants: true }, { propertyName: "columnTemplates", predicate: DataTableColumnDirective }], viewQueries: [{ propertyName: "bodyComponent", first: true, predicate: DataTableBodyComponent, descendants: true }, { propertyName: "headerComponent", first: true, predicate: DataTableHeaderComponent, descendants: true }], ngImport: i0, template: "