@sparser/au2-data-grid
Version:
A data grid for Aurelia 2
293 lines • 12.8 kB
JavaScript
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0) continue;
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
if (_ = accept(result.get)) descriptor.get = _;
if (_ = accept(result.set)) descriptor.set = _;
if (_ = accept(result.init)) initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field") initializers.unshift(_);
else descriptor[key] = _;
}
}
if (target) Object.defineProperty(target, contextIn.name, descriptor);
done = true;
};
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
};
import { noop, } from '@aurelia/kernel';
import { observable, } from '@aurelia/runtime';
const defaultPageSize = 50;
/**
* Handles the data part of the grid.
* This has very little to do with the presentation of the data.
*/
let ContentModel = (() => {
let _allItems_decorators;
let _allItems_initializers = [];
let _allItems_extraInitializers = [];
return class ContentModel {
static {
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
_allItems_decorators = [observable];
__esDecorate(null, null, _allItems_decorators, { kind: "field", name: "allItems", static: false, private: false, access: { has: obj => "allItems" in obj, get: obj => obj.allItems, set: (obj, value) => { obj.allItems = value; } }, metadata: _metadata }, _allItems_initializers, _allItems_extraInitializers);
if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
}
onSorting;
isAnySelected = false;
isOneSelected = false;
selectionCount = 0;
allItems = __runInitializers(this, _allItems_initializers, void 0);
selectedItems = (__runInitializers(this, _allItems_extraInitializers), []);
selectionMode;
onSelectionChange;
pageSize;
fetchPage;
fetchCount;
logger;
_currentPage;
_currentPageNumber = 0;
pagePromise = null;
countPromise = null;
_totalCount = undefined;
_sortOptions = [];
_pageCount = undefined;
initialized = false;
constructor(allItems, pagingOptions, selectionOptions, onSorting, logger) {
this.onSorting = onSorting;
this.logger = logger.scopeTo('GridModel');
this.allItems = allItems;
const fetchPage = this.fetchPage = pagingOptions?.fetchPage ?? null;
this.fetchCount = pagingOptions?.fetchCount ?? null;
const hasAllItems = allItems !== null;
if (!hasAllItems && fetchPage === null)
throw new Error('Either allItems or pagingOptions is required.');
const pageSize = pagingOptions?.pageSize;
const isPagingDisabled = pagingOptions === null || pageSize === null;
this.pageSize = isPagingDisabled ? null : (pageSize ?? defaultPageSize);
if (isPagingDisabled && hasAllItems) {
this._currentPage = allItems;
this._totalCount = allItems.length;
}
this.selectionMode = selectionOptions?.mode ?? ItemSelectionMode.None;
this.onSelectionChange = selectionOptions?.onSelectionChange ?? noop;
this.initialized = true;
}
get currentPage() { return this._currentPage; }
get totalCount() { return this._totalCount; }
get pageCount() { return this._pageCount; }
get currentPageNumber() { return this._currentPageNumber; }
selectItem(item) {
const selectedItems = this.selectedItems;
switch (this.selectionMode) {
case ItemSelectionMode.None:
return;
case ItemSelectionMode.Single:
if (selectedItems[0] != item && this._currentPage.includes(item)) {
selectedItems[0] = item;
this.handleSelectionChange();
}
break;
case ItemSelectionMode.Multiple: {
if (!selectedItems.includes(item) && this._currentPage.includes(item)) {
selectedItems.push(item);
this.handleSelectionChange();
}
break;
}
}
}
selectRange(startIndex, endIndex) {
if (this.selectionMode !== ItemSelectionMode.Multiple)
return;
const start = Math.min(startIndex, endIndex);
const end = Math.max(startIndex, endIndex);
const items = this._currentPage;
const selectedItems = this.selectedItems;
let hasChange = false;
for (let i = start; i <= end; i++) {
const item = items[i];
if (!selectedItems.includes(item)) {
selectedItems.push(item);
hasChange = true;
}
}
if (hasChange) {
this.handleSelectionChange();
}
}
toggleSelection(item) {
if (this.selectionMode !== ItemSelectionMode.Multiple)
return;
const selectedItems = this.selectedItems;
const idx = selectedItems.findIndex(x => item === x);
if (idx === -1) {
selectedItems.push(item);
}
else {
selectedItems.splice(idx, 1);
}
this.handleSelectionChange();
}
handleSelectionChange() {
// cloned to avoid unintentional mutation
const selectedItems = this.selectedItems.slice();
const len = this.selectionCount = selectedItems.length;
const isAnySelected = this.isAnySelected = len > 0;
const isOneSelected = this.isOneSelected = len === 1;
this.onSelectionChange(selectedItems, isOneSelected, isAnySelected);
}
clearSelections() {
this.isAnySelected = this.isOneSelected = false;
this.selectionCount = 0;
this.selectedItems.length = 0;
}
isSelected(item) {
return this.selectedItems.includes(item);
}
applySorting(...sortOptions) {
const oldValue = this._sortOptions;
const newValue = this._sortOptions = sortOptions;
this.onSorting?.(newValue, oldValue, this.allItems, this);
this.goToPage(1, true);
}
goToPage(pageNumber, force = false) {
if (!this.initialized)
return;
const oldNumber = this._currentPageNumber;
if (oldNumber === pageNumber
&& this.pagePromise !== null
&& this.countPromise !== null) {
return;
}
this._currentPageNumber = pageNumber;
if (oldNumber !== pageNumber || force) {
this.setPage();
this.setTotalCount();
}
}
goToPreviousPage() {
const pageNumber = this._currentPageNumber;
if (pageNumber === 1) {
this.logger.warn('Cannot go to previous page; already on the first page.');
return;
}
this.goToPage(pageNumber - 1);
}
goToNextPage() {
const pageNumber = this._currentPageNumber;
if (pageNumber === this._pageCount) {
this.logger.warn('Cannot go to next page; already on the last page.');
return;
}
this.goToPage(pageNumber + 1);
}
/** @internal */
setTotalCount() {
const pageSize = this.pageSize;
const allItems = this.allItems;
if (allItems !== null) {
const totalCount = this._totalCount = allItems.length;
if (pageSize !== null) {
this._pageCount = Math.ceil(totalCount / pageSize);
}
this.countPromise = null;
return;
}
const fetchCount = this.fetchCount;
if (fetchCount === null) {
this.logger.warn('fetchCount is not set.');
return;
}
const countPromise = fetchCount(this);
if (countPromise instanceof Promise) {
const promise = this.countPromise = countPromise.then((count) => {
this._totalCount = count;
if (pageSize !== null) {
this._pageCount = Math.ceil(count / pageSize);
}
if (this.countPromise === promise) {
this.countPromise = null;
}
});
return;
}
this._totalCount = countPromise;
if (pageSize !== null) {
this._pageCount = Math.ceil(countPromise / pageSize);
}
this.countPromise = null;
}
/** @internal */
setPage() {
const allItems = this.allItems;
const pageSize = this.pageSize;
const pageNumber = this._currentPageNumber;
this.clearSelections();
if (allItems !== null) {
this._currentPage = pageSize !== null
? allItems.slice(pageSize * (pageNumber - 1), pageSize * pageNumber)
: allItems;
this.pagePromise = null;
return;
}
// one of fetchPage or allItems should always be there.
const fetchPage = this.fetchPage;
const pagePromise = fetchPage(pageNumber, pageSize, this);
if (pagePromise instanceof Promise) {
const promise = this.pagePromise = pagePromise
.then((data) => {
this._currentPage = data;
if (this.pagePromise === promise) {
this.pagePromise = null;
}
});
return;
}
this._currentPage = pagePromise;
this.pagePromise = null;
}
async wait(rethrowError = false) {
try {
await Promise.all([this.pagePromise, this.countPromise]);
}
catch (e) {
if (rethrowError) {
throw e;
}
}
}
async refresh(rethrowError = false) {
this.goToPage(1, true);
return this.wait(rethrowError);
}
allItemsChanged() {
this.goToPage(1, true);
}
};
})();
export { ContentModel };
export var ItemSelectionMode;
(function (ItemSelectionMode) {
ItemSelectionMode[ItemSelectionMode["None"] = 0] = "None";
ItemSelectionMode[ItemSelectionMode["Single"] = 1] = "Single";
ItemSelectionMode[ItemSelectionMode["Multiple"] = 2] = "Multiple";
})(ItemSelectionMode || (ItemSelectionMode = {}));
//# sourceMappingURL=content-model.js.map