@true-directive/base
Version:
The set of base classes for the TrueDirective Grid
348 lines (347 loc) • 14 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { SortInfo, SortType } from './sort-info.class';
import { SummaryType } from './summary.class';
import { FilterPipe } from '../data-transforms/filter.pipe';
import { SortPipe } from '../data-transforms/sort.pipe';
import { SummaryPipe } from '../data-transforms/summary.pipe';
import { ColumnCollection } from './column-collection.class';
import { GridSettings } from './grid-settings.class';
import { ValueFormatter } from './value-formatter.class';
import { Utils } from '../common/utils.class';
import { RowDragOverseer } from './row-drag-overseer.class';
import { LazyLoadingMode } from './enums';
import { DataQuery } from './data-query.class';
import { AxInject } from './ax-inject.class';
/**
* Источник данных
*/
var DataSource = /** @class */ (function () {
function DataSource() {
this._totalRowCount = null;
this.lazyLoaded = null;
/**
* Общий текстовый фильтр
*/
this.searchString = '';
/**
* Filters
*/
this.filters = [];
/**
* Sortings
*/
this.sortings = [];
/**
* Resulting rows list
*/
this._resultRows = null;
// Value Formatter
this.valueFormatter = new ValueFormatter();
}
Object.defineProperty(DataSource.prototype, "model", {
get: function () {
return this._model;
},
set: function (rows) {
this._model = rows;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DataSource.prototype, "totalRowCount", {
get: function () {
return this._totalRowCount;
},
set: function (n) {
this._totalRowCount = n;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DataSource.prototype, "loadedRowCount", {
get: function () {
if (!this._model) {
return 0;
}
return this._model.length;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DataSource.prototype, "resultRowCount", {
get: function () {
return this._resultRows === null ? 0 : this._resultRows.length;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DataSource.prototype, "resultRows", {
get: function () {
return this._resultRows;
},
enumerable: true,
configurable: true
});
DataSource.prototype.clearSorting = function () {
this.sortings.splice(0, this.sortings.length);
};
DataSource.prototype.clearFilters = function () {
this.filters.splice(0, this.filters.length);
};
DataSource.prototype.clear = function () {
this.searchString = '';
this.clearFilters();
this.clearSorting();
};
DataSource.prototype.getQuery = function (counter, subject) {
if (counter === void 0) { counter = 0; }
if (subject === void 0) { subject = null; }
return new DataQuery(counter, this.filters, this.searchString, this.sortings, [], subject);
};
/**
* Наложение фильтров
* @param rows Список строк
* @return Отфильтрованный набор строк
*/
DataSource.prototype.doFilter = function (rows) {
return new FilterPipe().transform(rows, this.columnCollection.columns, this.filters, this.searchString, this.valueFormatter);
};
/**
* Сортировка строк.
* @param rows Список строк, подлежащих группировке
* @return Отсортированный список строк
*/
DataSource.prototype.doSort = function (rows) {
return new SortPipe().transform(rows, this.sortings);
};
// Суммирование
DataSource.prototype.summaries = function (columns) {
var _this = this;
columns.forEach(function (c) {
return c.summaries.forEach(function (a) { return a.value = new SummaryPipe().transform(_this.resultRows, c, a.type); });
});
};
DataSource.prototype.sortedByField = function (fieldName) {
return this.sortings.find(function (s) { return s.fieldName === fieldName; });
};
// Не учитываем COUNT, т.к. после редактирования количество строк не изменится
DataSource.prototype.summariedByColumn = function (col) {
return col.summaries.find(function (s) { return s.type !== SummaryType.COUNT; }) !== undefined;
};
/**
* Проверка видимости строки после изменения значения одного из полей
* @param r Измененная строка
* @param fieldName Наименование поля
* @return Необходим ли перезапрос данных
*/
DataSource.prototype.checkDataUpdateNeed = function (r, fieldName) {
var fp = new FilterPipe();
var filterMatch = fp.match(r, this.columnCollection.columns, this.filters, this.searchString, this.valueFormatter);
if (!filterMatch) {
return true;
}
if (this.sortedByField(fieldName)) {
return true;
}
var col = this.columnCollection.columnByFieldName(fieldName);
if (this.summariedByColumn(col)) {
return true;
}
return false; // Ничего страшного
};
/**
* Окончательная обрабтка данных и сохранение в resultRows.
* @param rows [description]
* @return [description]
*/
DataSource.prototype.accomplishFetch = function (rows) {
this._resultRows = rows;
this.summaries(this.columnCollection.columns);
};
/**
* Пересчет данных для отображения
*/
DataSource.prototype.recalcData = function () {
// Фильтруем
var filtered;
if (this.settings.treeChildrenProperty !== '') {
// Для дерева не фильтруем - применится при обработке дерева
filtered = this.model;
}
else {
filtered = this.doFilter(this.model);
}
// Сортируем
var sorted = this.doSort(filtered);
// Фиксируем
this.accomplishFetch(sorted);
};
/**
* Получение данных для отображения, которые обработаны вне нашего компонента.
* Например, сервером.
* @param rows Отфильтрованные, отсортированные данные.
* @param settings Настройки
*/
DataSource.prototype.fetchData = function (rows, totalRowCount) {
if (totalRowCount === void 0) { totalRowCount = null; }
if (this.settings.lazyLoading !== LazyLoadingMode.NONE) {
return;
}
// Производим окончательную обработку и фиксируем данные
this.model = rows;
this.totalRowCount = totalRowCount;
this.accomplishFetch(rows);
};
/**
* Установка фильтра
* @param f Фильтр
*/
DataSource.prototype.setFilter = function (f) {
this.removeFilter(f.fieldName);
this.filters.push(f);
};
/**
* Удаляем фильтр по заданной колонке
* @param fieldName Наименование поля
* @return Если фильтр удален - возвращаем true. Если фильтра не было - false.
*/
DataSource.prototype.removeFilter = function (fieldName) {
for (var i = 0; i < this.filters.length; i++) {
if (this.filters[i].fieldName === fieldName) {
this.filters.splice(i, 1);
return true;
}
}
return false;
};
/**
* Получить фильтр заданной колонки.
* Используется в том числе заголовком для отображения подсвеченной иконки
* @param c Колонка, для которой нужно получить фильтр
* @return Фильтр, если есть
*/
DataSource.prototype.getFilter = function (c) {
return this.filters.find(function (f) { return f.fieldName === c.fieldName; });
};
/**
* Data sorting
* @param sortings List of sortings
*/
DataSource.prototype.sort = function (sortings) {
var _this = this;
this.clearSorting();
sortings.forEach(function (s) { return _this.sortings.push(s); });
};
/**
* Data filtering
* @param filters List of filters
*/
DataSource.prototype.filter = function (filters) {
var _this = this;
this.clearFilters();
filters.forEach(function (f) { return _this.filters.push(f); });
};
/**
* Сортировка по колонке
* @param col Колонка
*/
DataSource.prototype.sortByColumn = function (col, add) {
if (add === void 0) { add = false; }
var sortInfo = this.sortedByField(col.fieldName);
if (sortInfo && (add || this.sortings.length === 1)) {
// Меняем направление сортировки на противоположное
sortInfo.invert();
if (sortInfo.sortType === SortType.NONE) {
this.sortings.splice(this.sortings.indexOf(sortInfo), 1);
}
}
else {
if (!add) {
this.clearSorting();
}
this.sortings.push(new SortInfo(col.fieldName, SortType.ASC));
}
};
/**
* Убрать одну строку из результирующего набора строк. Например, по причине
* того, что она перестала удовлетворять условиям фильтра при изменении одного
* из полей.
* @param r Строка, подлежащая скрытию
* @return Было ли удаление
*/
DataSource.prototype.removeResultRow = function (r) {
var i = this._resultRows.indexOf(r);
if (i > 0) {
this._resultRows.splice(i, 1);
return true;
}
return false;
};
DataSource.prototype.rowData = function (row) {
return row ? row : null;
};
DataSource.prototype.displayedValue = function (col, value, row) {
return this.valueFormatter.displayedValue(col, value, row);
};
DataSource.prototype.value = function (row, fieldName) {
var rd = this.rowData(row);
return rd === null ? null : rd[fieldName];
};
DataSource.prototype.updateValue = function (row, fieldName, value) {
var rd = this.rowData(row);
if (rd !== null) {
rd[fieldName] = value;
}
return rd;
};
/**
* Check drag possibility
* @param draggedRows [description]
* @param dropRow [description]
* @param dropPos [description]
* @return [description]
*/
DataSource.prototype.canDrop = function (draggedRows, dropRow, dropPos) {
var overseer = new RowDragOverseer();
return overseer.canDrop(this.resultRows, draggedRows, dropRow, dropPos, false);
};
DataSource.prototype.canEditCell = function (cp) {
if (cp) {
var col = this.columnCollection.columnByFieldName(cp.fieldName);
return col.isCheckbox ? false : this.settings.canEditColumnCell(col);
}
return false;
};
DataSource.prototype.moveRows = function (draggedRows, dropTarget, dropPos) {
for (var i = 0; i < draggedRows.length; i++) {
var ri = this.model.indexOf(dropTarget);
if (dropPos === 'after') {
ri++;
}
var ri0 = this.model.indexOf(draggedRows[i]);
if (ri0 < ri) {
ri--;
}
Utils.moveArrayItem(this.model, ri0, ri);
}
return false;
};
__decorate([
AxInject('columns'),
__metadata("design:type", ColumnCollection)
], DataSource.prototype, "columnCollection", void 0);
__decorate([
AxInject('settings'),
__metadata("design:type", GridSettings)
], DataSource.prototype, "settings", void 0);
return DataSource;
}());
export { DataSource };