diff --git a/README.md b/README.md
index 3da1eb728..4fe57fcb9 100644
--- a/README.md
+++ b/README.md
@@ -52,7 +52,7 @@ For a full compatibility table of Aurelia-Slickgrid with Slickgrid-Universal, yo
There are also 2 new Themes, Material & Salesforce that are available as well and if you wish to use SVG then take a look at the [Docs - SVG Icons](https://ghiscoding.gitbook.io/aurelia-slickgrid/styling/svg-icons).
#### Working Demos
-For a complete set of working demos (over 30 examples), we strongly suggest you to clone the [Aurelia-Slickgrid Demos](https://github.com/ghiscoding/aurelia-slickgrid-demos) repository (instructions are provided in the demo repo). The repo provides multiple demos and they are updated every time a new version is out, so it is updated frequently and is also used as the GitHub live demo page for both the [Bootstrap 5 demo](https://ghiscoding.github.io/aurelia-slickgrid) and [Bootstrap 5 demo (single Locale)](https://ghiscoding.github.io/aurelia-slickgrid-demos).
+For a complete set of working demos (40+ examples), we strongly suggest you to clone the [Aurelia-Slickgrid Demos](https://github.com/ghiscoding/aurelia-slickgrid-demos) repository (instructions are provided in the demo repo). The repo provides multiple demos and they are updated every time a new version is out, so it is updated frequently and is also used as the GitHub live demo page for both the [Bootstrap 5 demo](https://ghiscoding.github.io/aurelia-slickgrid) and [Bootstrap 5 demo (single Locale)](https://ghiscoding.github.io/aurelia-slickgrid-demos).
For a complete working set of demos, you can clone the [Aurelia-Slickgrid Demos](https://github.com/ghiscoding/aurelia-slickgrid-demos) repository (instructions are provided in the demo repo). This repo provides multiple samples (RequireJS, WebPack, CLI, ...) and it is also worth to know that the 2 WebPacks demos are updated frequently since they are the actual live GitHub [Bootstrap 5 demo (single Locale)](https://ghiscoding.github.io/aurelia-slickgrid-demos/#/slickgrid) / [Bootstrap 5 demo](https://ghiscoding.github.io/aurelia-slickgrid).
diff --git a/docs/TOC.md b/docs/TOC.md
index 5b3018258..e9cb8c6a0 100644
--- a/docs/TOC.md
+++ b/docs/TOC.md
@@ -58,6 +58,7 @@
* [Grid State & Presets](grid-functionalities/grid-state-preset.md)
* [Grouping & Aggregators](grid-functionalities/grouping-aggregators.md)
* [Header Menu & Header Buttons](grid-functionalities/header-menu-header-buttons.md)
+* [Infinite Scroll](grid-functionalities/infinite-scroll.md)
* [Pinning (frozen) of Columns/Rows](grid-functionalities/frozen-columns-rows.md)
* [Providing data to the grid](grid-functionalities/providing-grid-data.md)
* [Row Detail](grid-functionalities/row-detail.md)
diff --git a/docs/grid-functionalities/infinite-scroll.md b/docs/grid-functionalities/infinite-scroll.md
new file mode 100644
index 000000000..88518bd92
--- /dev/null
+++ b/docs/grid-functionalities/infinite-scroll.md
@@ -0,0 +1,151 @@
+## Description
+
+Infinite scrolling allows the grid to lazy-load rows from the server (or locally) when reaching the scroll bottom (end) position.
+In its simplest form, the more the user scrolls down, the more rows will get loaded and appended to the in-memory dataset.
+
+### Demo
+
+[JSON Data - Demo Page](https://ghiscoding.github.io/aurelia-slickgrid/#/slickgrid/example38) / [Demo ViewModel](https://github.com/ghiscoding/aurelia-slickgrid/blob/master/packages/demo/src/examples/slickgrid/example38.ts)
+
+[OData Backend Service - Demo Page](https://ghiscoding.github.io/aurelia-slickgrid/#/slickgrid/example39) / [Demo ViewModel](https://github.com/ghiscoding/aurelia-slickgrid/blob/master/packages/demo/src/examples/slickgrid/example39.ts)
+
+[GraphQL Backend Service - Demo Page](https://ghiscoding.github.io/aurelia-slickgrid/#/slickgrid/example40) / [Demo ViewModel](https://github.com/ghiscoding/aurelia-slickgrid/blob/master/packages/demo/src/examples/slickgrid/example40.ts)
+
+> ![WARNING]
+> Pagination Grid Preset (`presets.pagination`) is **not** supported with Infinite Scroll
+
+## Infinite Scroll with JSON data
+
+As describe above, when used with a local JSON dataset, it will add data to the in-memory dataset whenever we scroll to the bottom until we reach the end of the dataset (if ever).
+
+#### Code Sample
+When used with a local JSON dataset, the Infinite Scroll is a feature that must be implemented by yourself. You implement by subscribing to 1 main event (`onScroll`) and if you want to reset the data when Sorting then you'll also need to subscribe to the (`onSort`) event. So the idea is to have simple code in the `onScroll` event to detect when we reach the scroll end and then use the DataView `addItems()` to append data to the existing dataset (in-memory) and that's about it.
+
+##### View
+```html
+
+
+```
+
+```ts
+export class Example {
+ scrollEndCalled = false;
+
+ // add onScroll listener which will detect when we reach the scroll end
+ // if so, then append items to the dataset
+ handleOnScroll(event) {
+ const args = event.detail?.args;
+ const viewportElm = args.grid.getViewportNode();
+ if (
+ ['mousewheel', 'scroll'].includes(args.triggeredBy || '')
+ && !this.scrollEndCalled
+ && viewportElm.scrollTop > 0
+ && Math.ceil(viewportElm.offsetHeight + args.scrollTop) >= args.scrollHeight
+ ) {
+ // onScroll end reached, add more items
+ // for demo purposes, we'll mock next subset of data at last id index + 1
+ const startIdx = this.aureliaGrid.dataView?.getItemCount() || 0;
+ const newItems = this.loadData(startIdx, FETCH_SIZE);
+ this.aureliaGrid.dataView?.addItems(newItems);
+ this.scrollEndCalled = false; //
+ }
+ }
+
+ // do we want to reset the dataset when Sorting?
+ // if answering Yes then use the code below
+ handleOnSort() {
+ if (this.shouldResetOnSort) {
+ const newData = this.loadData(0, FETCH_SIZE);
+ this.aureliaGrid.slickGrid?.scrollTo(0); // scroll back to top to avoid unwanted onScroll end triggered
+ this.aureliaGrid.dataView?.setItems(newData);
+ this.aureliaGrid.dataView?.reSort();
+ }
+ }
+}
+```
+
+---
+
+## Infinite Scroll with Backend Services
+
+As describe above, when used with the Backend Service API, it will add data to the in-memory dataset whenever we scroll to the bottom. However there is one thing to note that might surprise you which is that even if Pagination is hidden in the UI, but the fact is that behind the scene that is exactly what it uses (mainly the Pagination Service `.goToNextPage()` to fetch the next set of data).
+
+#### Code Sample
+We'll use the OData Backend Service to demo Infinite Scroll with a Backend Service, however the implementation is similar for any Backend Services. The main difference with the Infinite Scroll implementation is around the `onProcess` and the callback that we use within (which is the `getCustomerCallback` in our use case). This callback will receive a data object that include the `infiniteScrollBottomHit` boolean property, this prop will be `true` only on the 2nd and more passes which will help us make a distinction between the first page load and any other subset of data to append to our in-memory dataset. With this property in mind, we'll assign the entire dataset on 1st pass with `this.dataset = data.value` (when `infiniteScrollBottomHit: false`) but for any other passes, we'll want to use the DataView `addItems()` to append data to the existing dataset (in-memory) and that's about it.
+
+##### View
+```html
+
+
+```
+
+```ts
+export class Example {
+ initializeGrid() {
+ this.columnDefinitions = [ /* ... */ ];
+
+ this.gridOptions = {
+ presets: {
+ // NOTE: pagination preset is NOT supported with infinite scroll
+ // filters: [{ columnId: 'gender', searchTerms: ['female'] }]
+ },
+ backendServiceApi: {
+ service: new GridOdataService(), // or any Backend Service
+ options: {
+ // enable infinite scroll via Boolean OR via { fetchSize: number }
+ infiniteScroll: { fetchSize: 30 }, // or use true, in that case it would use default size of 25
+
+ preProcess: () => {
+ this.displaySpinner(true);
+ },
+ process: (query) => this.getCustomerApiCall(query),
+ postProcess: (response) => {
+ this.displaySpinner(false);
+ this.getCustomerCallback(response);
+ },
+ // we could use local in-memory Filtering (please note that it only filters against what is currently loaded)
+ // that is when we want to avoid reloading the entire dataset every time
+ // useLocalFiltering: true,
+ } as OdataServiceApi,
+ };
+ }
+
+ // Web API call
+ getCustomerApiCall(odataQuery) {
+ return this.http.get(`/api/getCustomers?${odataQuery}`);
+ }
+
+ getCustomerCallback(data: { '@odata.count': number; infiniteScrollBottomHit: boolean; metrics: Metrics; query: string; value: any[]; }) {
+ // totalItems property needs to be filled for pagination to work correctly
+ const totalItemCount: number = data['@odata.count'];
+ this.metrics.totalItemCount = totalItemCount;
+
+ // even if we're not showing pagination, it is still used behind the scene to fetch next set of data (next page basically)
+ // once pagination totalItems is filled, we can update the dataset
+
+ // infinite scroll has an extra data property to determine if we hit an infinite scroll and there's still more data (in that case we need append data)
+ // or if we're on first data fetching (no scroll bottom ever occured yet)
+ if (!data.infiniteScrollBottomHit) {
+ // initial load not scroll hit yet, full dataset assignment
+ this.aureliaGrid.slickGrid?.scrollTo(0); // scroll back to top to avoid unwanted onScroll end triggered
+ this.dataset = data.value;
+ this.metrics.itemCount = data.value.length;
+ } else {
+ // scroll hit, for better perf we can simply use the DataView directly for better perf (which is better compare to replacing the entire dataset)
+ this.aureliaGrid.dataView?.addItems(data.value);
+ }
+ }
+}
+```
diff --git a/package.json b/package.json
index f5932edc7..831d13578 100644
--- a/package.json
+++ b/package.json
@@ -48,9 +48,9 @@
"@jest/types": "^29.6.3",
"@lerna-lite/cli": "^3.8.0",
"@lerna-lite/publish": "^3.8.0",
- "@slickgrid-universal/common": "^5.4.0",
+ "@slickgrid-universal/common": "^5.5.0",
"@types/jest": "^29.5.12",
- "@types/node": "^20.14.14",
+ "@types/node": "^22.1.0",
"conventional-changelog-conventionalcommits": "^7.0.2",
"cross-env": "^7.0.3",
"cypress": "^13.13.2",
@@ -72,7 +72,7 @@
"rimraf": "^5.0.10",
"rxjs": "^7.8.1",
"ts-jest": "^29.2.4",
- "typescript": "^5.5.3",
+ "typescript": "^5.5.4",
"typescript-eslint": "^8.0.1"
},
"packageManager": "pnpm@8.15.9"
diff --git a/packages/aurelia-slickgrid/package.json b/packages/aurelia-slickgrid/package.json
index 38d1b2a38..bfd0591da 100644
--- a/packages/aurelia-slickgrid/package.json
+++ b/packages/aurelia-slickgrid/package.json
@@ -53,13 +53,13 @@
"@aurelia/runtime": "^2.0.0-beta.20",
"@aurelia/runtime-html": "^2.0.0-beta.20",
"@formkit/tempo": "^0.1.2",
- "@slickgrid-universal/common": "~5.4.0",
- "@slickgrid-universal/custom-footer-component": "~5.4.0",
- "@slickgrid-universal/empty-warning-component": "~5.4.0",
- "@slickgrid-universal/event-pub-sub": "~5.4.0",
- "@slickgrid-universal/pagination-component": "~5.4.0",
- "@slickgrid-universal/row-detail-view-plugin": "~5.4.0",
- "@slickgrid-universal/utils": "~5.4.0",
+ "@slickgrid-universal/common": "~5.5.0",
+ "@slickgrid-universal/custom-footer-component": "~5.5.0",
+ "@slickgrid-universal/empty-warning-component": "~5.5.0",
+ "@slickgrid-universal/event-pub-sub": "~5.5.0",
+ "@slickgrid-universal/pagination-component": "~5.5.0",
+ "@slickgrid-universal/row-detail-view-plugin": "~5.5.0",
+ "@slickgrid-universal/utils": "~5.5.0",
"dequal": "^2.0.3",
"sortablejs": "^1.15.2"
},
@@ -69,6 +69,6 @@
"dompurify": "^3.1.6",
"rimraf": "^5.0.10",
"tslib": "^2.6.3",
- "typescript": "^5.5.3"
+ "typescript": "^5.5.4"
}
}
diff --git a/packages/aurelia-slickgrid/src/custom-elements/aurelia-slickgrid.ts b/packages/aurelia-slickgrid/src/custom-elements/aurelia-slickgrid.ts
index 45e1e0f16..3684cdb7d 100644
--- a/packages/aurelia-slickgrid/src/custom-elements/aurelia-slickgrid.ts
+++ b/packages/aurelia-slickgrid/src/custom-elements/aurelia-slickgrid.ts
@@ -1,5 +1,6 @@
+// interfaces/types
import type {
- // interfaces/types
+ BackendService,
AutocompleterEditor,
BackendServiceApi,
BackendServiceOption,
@@ -100,6 +101,7 @@ export class AureliaSlickgridCustomElement {
protected _isLocalGrid = true;
protected _paginationOptions: Pagination | undefined;
protected _registeredResources: ExternalResource[] = [];
+ protected _scrollEndCalled = false;
protected _columnDefinitionObserver?: ICollectionObserver<'array'>;
protected _columnDefinitionsSubscriber: ICollectionSubscriber = {
handleCollectionChange: this.columnDefinitionsHandler.bind(this)
@@ -230,6 +232,10 @@ export class AureliaSlickgridCustomElement {
this.containerService.registerInstance('TreeDataService', this.treeDataService);
}
+ get backendService(): BackendService | undefined {
+ return this.gridOptions.backendServiceApi?.service;
+ }
+
get eventHandler(): SlickEventHandler {
return this._eventHandler;
}
@@ -298,7 +304,10 @@ export class AureliaSlickgridCustomElement {
this.backendServiceApi = this.gridOptions?.backendServiceApi;
this._isLocalGrid = !this.backendServiceApi; // considered a local grid if it doesn't have a backend service set
- this.createBackendApiInternalPostProcessCallback(this.gridOptions);
+ // unless specified, we'll create an internal postProcess callback (currently only available for GraphQL)
+ if (this.gridOptions.backendServiceApi && !this.gridOptions.backendServiceApi?.disableInternalPostProcess) {
+ this.createBackendApiInternalPostProcessCallback(this.gridOptions);
+ }
if (!this.customDataView) {
const dataviewInlineFilters = this.gridOptions.dataView && this.gridOptions.dataView.inlineFilters || false;
@@ -463,7 +472,7 @@ export class AureliaSlickgridCustomElement {
dispose: this.disposeInstance.bind(this),
// return all available Services (non-singleton)
- backendService: this.gridOptions?.backendServiceApi?.service,
+ backendService: this.backendService,
eventPubSubService: this._eventPubSubService,
filterService: this.filterService,
gridEventService: this.gridEventService,
@@ -505,6 +514,9 @@ export class AureliaSlickgridCustomElement {
});
this.serviceList = [];
+ // dispose backend service when defined and a dispose method exists
+ this.backendService?.dispose?.();
+
// dispose all registered external resources
this.disposeExternalResources();
@@ -637,8 +649,8 @@ export class AureliaSlickgridCustomElement {
/**
* Define our internal Post Process callback, it will execute internally after we get back result from the Process backend call
- * For now, this is GraphQL Service ONLY feature and it will basically
- * refresh the Dataset & Pagination without having the user to create his own PostProcess every time
+ * Currently ONLY available with the GraphQL Backend Service.
+ * The behavior is to refresh the Dataset & Pagination without requiring the user to create his own PostProcess every time
*/
createBackendApiInternalPostProcessCallback(gridOptions: GridOption) {
const backendApi = gridOptions?.backendServiceApi;
@@ -796,7 +808,7 @@ export class AureliaSlickgridCustomElement {
backendApiService.updateSorters(undefined, sortColumns);
}
// Pagination "presets"
- if (backendApiService.updatePagination && gridOptions.presets.pagination) {
+ if (backendApiService.updatePagination && gridOptions.presets.pagination && !this.hasBackendInfiniteScroll()) {
const { pageNumber, pageSize } = gridOptions.presets.pagination;
backendApiService.updatePagination(pageNumber, pageSize);
}
@@ -840,6 +852,56 @@ export class AureliaSlickgridCustomElement {
}
});
}
+
+ // when user enables Infinite Scroll
+ if (backendApi.service.options?.infiniteScroll) {
+ this.addBackendInfiniteScrollCallback();
+ }
+ }
+ }
+
+ protected addBackendInfiniteScrollCallback(): void {
+ if (this.grid && this.gridOptions.backendServiceApi && this.hasBackendInfiniteScroll() && !this.gridOptions.backendServiceApi?.onScrollEnd) {
+ const onScrollEnd = () => {
+ this.backendUtilityService.setInfiniteScrollBottomHit(true);
+
+ // even if we're not showing pagination, we still use pagination service behind the scene
+ // to keep track of the scroll position and fetch next set of data (aka next page)
+ // we also need a flag to know if we reached the of the dataset or not (no more pages)
+ this.paginationService.goToNextPage().then(hasNext => {
+ if (!hasNext) {
+ this.backendUtilityService.setInfiniteScrollBottomHit(false);
+ }
+ });
+ };
+ this.gridOptions.backendServiceApi.onScrollEnd = onScrollEnd;
+
+ // subscribe to SlickGrid onScroll to determine when reaching the end of the scroll bottom position
+ // run onScrollEnd() method when that happens
+ this._eventHandler.subscribe(this.grid.onScroll, (_e, args) => {
+ const viewportElm = args.grid.getViewportNode()!;
+ if (
+ ['mousewheel', 'scroll'].includes(args.triggeredBy || '')
+ && this.paginationService?.totalItems
+ && args.scrollTop > 0
+ && Math.ceil(viewportElm.offsetHeight + args.scrollTop) >= args.scrollHeight
+ ) {
+ if (!this._scrollEndCalled) {
+ onScrollEnd();
+ this._scrollEndCalled = true;
+ }
+ }
+ });
+
+ // use postProcess to identify when scrollEnd process is finished to avoid calling the scrollEnd multiple times
+ // we also need to keep a ref of the user's postProcess and call it after our own postProcess
+ const orgPostProcess = this.gridOptions.backendServiceApi.postProcess;
+ this.gridOptions.backendServiceApi.postProcess = (processResult: any) => {
+ this._scrollEndCalled = false;
+ if (orgPostProcess) {
+ orgPostProcess(processResult);
+ }
+ };
}
}
@@ -940,7 +1002,7 @@ export class AureliaSlickgridCustomElement {
}
// display the Pagination component only after calling this refresh data first, we call it here so that if we preset pagination page number it will be shown correctly
- this.showPagination = (this.gridOptions && (this.gridOptions.enablePagination || (this.gridOptions.backendServiceApi && this.gridOptions.enablePagination === undefined))) ? true : false;
+ this.showPagination = !!(this.gridOptions && (this.gridOptions.enablePagination || (this.gridOptions.backendServiceApi && this.gridOptions.enablePagination === undefined)));
if (this._paginationOptions && this.gridOptions?.pagination && this.gridOptions?.backendServiceApi) {
const paginationOptions = this.setPaginationOptionsWhenPresetDefined(this.gridOptions, this._paginationOptions);
@@ -992,10 +1054,14 @@ export class AureliaSlickgridCustomElement {
* Check if there's any Pagination Presets defined in the Grid Options,
* if there are then load them in the paginationOptions object
*/
- setPaginationOptionsWhenPresetDefined(gridOptions: GridOption, paginationOptions: Pagination): Pagination {
+ protected setPaginationOptionsWhenPresetDefined(gridOptions: GridOption, paginationOptions: Pagination): Pagination {
if (gridOptions.presets?.pagination && gridOptions.pagination) {
- paginationOptions.pageSize = gridOptions.presets.pagination.pageSize;
- paginationOptions.pageNumber = gridOptions.presets.pagination.pageNumber;
+ if (this.hasBackendInfiniteScroll()) {
+ console.warn('[Aurelia-Slickgrid] `presets.pagination` is not supported with Infinite Scroll, reverting to first page.');
+ } else {
+ paginationOptions.pageSize = gridOptions.presets.pagination.pageSize;
+ paginationOptions.pageNumber = gridOptions.presets.pagination.pageNumber;
+ }
}
return paginationOptions;
}
@@ -1261,16 +1327,22 @@ export class AureliaSlickgridCustomElement {
}
}
+ hasBackendInfiniteScroll(gridOptions?: GridOption): boolean {
+ return !!(gridOptions || this.gridOptions).backendServiceApi?.service.options?.infiniteScroll;
+ }
+
protected mergeGridOptions(gridOptions: GridOption): GridOption {
gridOptions.gridId = this.gridId;
gridOptions.gridContainerId = `slickGridContainer-${this.gridId}`;
- // if we have a backendServiceApi and the enablePagination is undefined, we'll assume that we do want to see it, else get that defined value
- gridOptions.enablePagination = ((gridOptions.backendServiceApi && gridOptions.enablePagination === undefined) ? true : gridOptions.enablePagination) || false;
-
// use extend to deep merge & copy to avoid immutable properties being changed in GlobalGridOptions after a route change
const options = extend(true, {}, GlobalGridOptions, gridOptions) as GridOption;
+ // if we have a backendServiceApi and the enablePagination is undefined, we'll assume that we do want to see it, else get that defined value
+ if (!this.hasBackendInfiniteScroll(gridOptions)) {
+ gridOptions.enablePagination = !!((gridOptions.backendServiceApi && gridOptions.enablePagination === undefined) ? true : gridOptions.enablePagination);
+ }
+
// using copy extend to do a deep clone has an unwanted side on objects and pageSizes but ES6 spread has other worst side effects
// so we will just overwrite the pageSizes when needed, this is the only one causing issues so far.
// On a deep extend, Object and Array are extended, but object wrappers on primitive types such as String, Boolean, and Number are not.
@@ -1409,9 +1481,7 @@ export class AureliaSlickgridCustomElement {
this.slickPagination.renderPagination(this.elm.querySelector('div') as HTMLDivElement);
this._isPaginationInitialized = true;
} else if (!showPagination) {
- if (this.slickPagination) {
- this.slickPagination.dispose();
- }
+ this.slickPagination?.dispose();
this._isPaginationInitialized = false;
}
}
diff --git a/packages/demo/package.json b/packages/demo/package.json
index 5dfd7dbc0..fc33de1b0 100644
--- a/packages/demo/package.json
+++ b/packages/demo/package.json
@@ -43,15 +43,15 @@
"@fnando/sparkline": "^0.3.10",
"@formkit/tempo": "^0.1.2",
"@popperjs/core": "^2.11.8",
- "@slickgrid-universal/common": "^5.4.0",
- "@slickgrid-universal/composite-editor-component": "^5.4.0",
- "@slickgrid-universal/custom-tooltip-plugin": "^5.4.0",
- "@slickgrid-universal/excel-export": "^5.4.0",
- "@slickgrid-universal/graphql": "^5.4.0",
- "@slickgrid-universal/odata": "^5.4.0",
- "@slickgrid-universal/row-detail-view-plugin": "^5.4.0",
- "@slickgrid-universal/rxjs-observable": "^5.4.0",
- "@slickgrid-universal/text-export": "^5.4.0",
+ "@slickgrid-universal/common": "^5.5.0",
+ "@slickgrid-universal/composite-editor-component": "^5.5.0",
+ "@slickgrid-universal/custom-tooltip-plugin": "^5.5.0",
+ "@slickgrid-universal/excel-export": "^5.5.0",
+ "@slickgrid-universal/graphql": "^5.5.0",
+ "@slickgrid-universal/odata": "^5.5.0",
+ "@slickgrid-universal/row-detail-view-plugin": "^5.5.0",
+ "@slickgrid-universal/rxjs-observable": "^5.5.0",
+ "@slickgrid-universal/text-export": "^5.5.0",
"aurelia": "^2.0.0-beta.20",
"aurelia-slickgrid": "workspace:*",
"bootstrap": "^5.3.3",
@@ -66,7 +66,7 @@
"@types/dompurify": "^3.0.5",
"@types/fnando__sparkline": "^0.3.7",
"@types/jest": "^29.5.12",
- "@types/node": "^20.14.14",
+ "@types/node": "^22.1.0",
"@types/sortablejs": "^1.15.8",
"aurelia-polyfills": "^1.3.4",
"autoprefixer": "^10.4.20",
@@ -90,7 +90,7 @@
"ts-loader": "^9.5.1",
"ts-node": "^10.9.2",
"tslib": "^2.6.3",
- "typescript": "^5.5.3",
+ "typescript": "^5.5.4",
"webpack": "^5.93.0",
"webpack-bundle-analyzer": "^4.10.2",
"webpack-cli": "^5.1.4",
diff --git a/packages/demo/src/examples/slickgrid/example38.html b/packages/demo/src/examples/slickgrid/example38.html
new file mode 100644
index 000000000..6fb9f79d1
--- /dev/null
+++ b/packages/demo/src/examples/slickgrid/example38.html
@@ -0,0 +1,103 @@
+
+
+ Example 38: OData (v4) Backend Service with Infinite Scroll
+
+
+ code
+
+
+
+
+
+
+
+ Infinite scrolling allows the grid to lazy-load rows from the server when reaching the scroll bottom (end) position.
+ In its simplest form, the more the user scrolls down, the more rows get loaded.
+ If we reached the end of the dataset and there is no more data to load, then we'll assume to have the entire dataset loaded in memory.
+ This contrast with the regular Pagination approach which will hold only hold data for 1 page at a time.
+
+
NOTES
+
+
+ presets.pagination is not supported with Infinite Scroll and will revert to the first page,
+ simply because since we keep appending data, we always have to start from index zero (no offset).
+
+
+ Pagination is not shown BUT in fact, that is what is being used behind the scene whenever reaching the scroll end (fetching next batch).
+
+
+ Also note that whenever the user changes the Sort(s)/Filter(s) it will always reset and go back to zero index (first page).
+
+
+
+
+
+
+
+
+ Backend Error:
+
+
+
+
+
+
+
+ Status: ${status.text}
+
+
+
+
+
+
+
+ OData Query:${odataQuery}
+
+
+
+
+
+
+
+
+
+
+
+
+ Metrics:
+
+ ${metrics.endTime | dateFormat: 'DD MMM, h:mm:ss a'} —
+ ${metrics.itemCount}
+ of
+ ${metrics.totalItemCount}
+ items
+
+ All Data Loaded!!!
+
+
+
+
+
+
+
diff --git a/packages/demo/src/examples/slickgrid/example38.scss b/packages/demo/src/examples/slickgrid/example38.scss
new file mode 100644
index 000000000..b1af851ed
--- /dev/null
+++ b/packages/demo/src/examples/slickgrid/example38.scss
@@ -0,0 +1,8 @@
+.demo38 {
+ .badge {
+ display: none;
+ &.fully-loaded {
+ display: inline-flex;
+ }
+ }
+}
\ No newline at end of file
diff --git a/packages/demo/src/examples/slickgrid/example38.ts b/packages/demo/src/examples/slickgrid/example38.ts
new file mode 100644
index 000000000..d891bf39a
--- /dev/null
+++ b/packages/demo/src/examples/slickgrid/example38.ts
@@ -0,0 +1,395 @@
+import { IHttpClient } from '@aurelia/fetch-client';
+import { newInstanceOf, resolve } from '@aurelia/kernel';
+import { GridOdataService, type OdataServiceApi } from '@slickgrid-universal/odata';
+import {
+ type AureliaGridInstance,
+ Aggregators,
+ type Column,
+ FieldType,
+ Filters,
+ type GridOption,
+ type Grouping,
+ type Metrics,
+ type OnRowCountChangedEventArgs,
+ SortComparers,
+} from 'aurelia-slickgrid';
+
+import './example38.scss';
+
+const sampleDataRoot = 'assets/data';
+const CARET_HTML_ESCAPED = '%5E';
+const PERCENT_HTML_ESCAPED = '%25';
+
+export class Example38 {
+ aureliaGrid: AureliaGridInstance;
+ backendService: GridOdataService;
+ columnDefinitions!: Column[];
+ gridOptions!: GridOption;
+ dataset: any[] = [];
+ isPageErrorTest = false;
+ metrics!: Partial;
+ tagDataClass = '';
+ odataQuery = '';
+ processing = false;
+ errorStatus = '';
+ errorStatusClass = 'hidden';
+ status = { text: 'processing...', class: 'alert alert-danger' };
+
+ constructor(readonly http: IHttpClient = resolve(newInstanceOf(IHttpClient))) {
+ this.backendService = new GridOdataService();
+ this.initializeGrid();
+ }
+
+ aureliaGridReady(aureliaGrid: AureliaGridInstance) {
+ this.aureliaGrid = aureliaGrid;
+ }
+
+ initializeGrid() {
+ this.columnDefinitions = [
+ {
+ id: 'name', name: 'Name', field: 'name', sortable: true,
+ type: FieldType.string,
+ filterable: true,
+ filter: { model: Filters.compoundInput }
+ },
+ {
+ id: 'gender', name: 'Gender', field: 'gender', filterable: true, sortable: true,
+ filter: {
+ model: Filters.singleSelect,
+ collection: [{ value: '', label: '' }, { value: 'male', label: 'male' }, { value: 'female', label: 'female' }]
+ }
+ },
+ { id: 'company', name: 'Company', field: 'company', filterable: true, sortable: true },
+ {
+ id: 'category_name', name: 'Category', field: 'category/name', filterable: true, sortable: true,
+ formatter: (_row, _cell, _val, _colDef, dataContext) => dataContext['category']?.['name'] || ''
+ }
+ ];
+
+ this.gridOptions = {
+ enableAutoResize: true,
+ autoResize: {
+ container: '#demo-container',
+ rightPadding: 10
+ },
+ checkboxSelector: {
+ // you can toggle these 2 properties to show the "select all" checkbox in different location
+ hideInFilterHeaderRow: false,
+ hideInColumnTitleRow: true
+ },
+ enableCellNavigation: true,
+ enableFiltering: true,
+ enableCheckboxSelector: true,
+ enableRowSelection: true,
+ enableGrouping: true,
+ headerMenu: {
+ hideFreezeColumnsCommand: false,
+ },
+ presets: {
+ // NOTE: pagination preset is NOT supported with infinite scroll
+ // filters: [{ columnId: 'gender', searchTerms: ['female'] }]
+ },
+ backendServiceApi: {
+ service: this.backendService,
+ options: {
+ // enable infinite via Boolean OR via { fetchSize: number }
+ infiniteScroll: { fetchSize: 30 }, // or use true, in that case it would use default size of 25
+ enableCount: true,
+ version: 4
+ },
+ onError: (error: Error) => {
+ this.errorStatus = error.message;
+ this.errorStatusClass = 'visible notification is-light is-danger is-small is-narrow';
+ this.displaySpinner(false, true);
+ },
+ preProcess: () => {
+ this.errorStatus = '';
+ this.errorStatusClass = 'hidden';
+ this.displaySpinner(true);
+ },
+ process: (query) => this.getCustomerApiCall(query),
+ postProcess: (response) => {
+ this.metrics = response.metrics;
+ this.displaySpinner(false);
+ this.getCustomerCallback(response);
+ },
+ // we could use local in-memory Filtering (please note that it only filters against what is currently loaded)
+ // that is when we want to avoid reloading the entire dataset every time
+ // useLocalFiltering: true,
+ } as OdataServiceApi,
+ };
+ }
+
+ displaySpinner(isProcessing: boolean, isError?: boolean) {
+ this.processing = isProcessing;
+ if (isError) {
+ this.status = { text: 'ERROR!!!', class: 'alert alert-danger' };
+ } else {
+ this.status = (isProcessing)
+ ? { text: 'loading', class: 'alert alert-warning' }
+ : { text: 'finished', class: 'alert alert-success' };
+ }
+ }
+
+ getCustomerCallback(data: { '@odata.count': number; infiniteScrollBottomHit: boolean; metrics: Metrics; query: string; value: any[]; }) {
+ // totalItems property needs to be filled for pagination to work correctly
+ // however we need to force a dirty check, doing a clone object will do just that
+ const totalItemCount: number = data['@odata.count'];
+ this.metrics.totalItemCount = totalItemCount;
+
+ // even if we're not showing pagination, it is still used behind the scene to fetch next set of data (next page basically)
+ // once pagination totalItems is filled, we can update the dataset
+
+ // infinite scroll has an extra data property to determine if we hit an infinite scroll and there's still more data (in that case we need append data)
+ // or if we're on first data fetching (no scroll bottom ever occured yet)
+ if (!data.infiniteScrollBottomHit) {
+ // initial load not scroll hit yet, full dataset assignment
+ this.aureliaGrid.slickGrid?.scrollTo(0); // scroll back to top to avoid unwanted onScroll end triggered
+ this.dataset = data.value;
+ this.metrics.itemCount = data.value.length;
+ } else {
+ // scroll hit, for better perf we can simply use the DataView directly for better perf (which is better compare to replacing the entire dataset)
+ this.aureliaGrid.dataView?.addItems(data.value);
+ }
+
+ this.odataQuery = data['query'];
+
+ // NOTE: you can get currently loaded item count via the `onRowCountChanged`slick event, see `refreshMetrics()` below
+ // OR you could also calculate it yourself or get it via: `this.sgb.dataView.getItemCount() === totalItemCount`
+ // console.log('is data fully loaded: ', this.sgb.dataView?.getItemCount() === totalItemCount);
+ }
+
+ getCustomerApiCall(query: string) {
+ // in your case, you will call your WebAPI function (wich needs to return a Promise)
+ // for the demo purpose, we will call a mock WebAPI function
+ return this.getCustomerDataApiMock(query);
+ }
+
+ /**
+ * This function is only here to mock a WebAPI call (since we are using a JSON file for the demo)
+ * in your case the getCustomer() should be a WebAPI function returning a Promise
+ */
+ getCustomerDataApiMock(query: string): Promise {
+ this.errorStatusClass = 'hidden';
+
+ // the mock is returning a Promise, just like a WebAPI typically does
+ return new Promise((resolve) => {
+ const queryParams = query.toLowerCase().split('&');
+ let top = 0;
+ let skip = 0;
+ let orderBy = '';
+ let countTotalItems = 100;
+ const columnFilters: any = {};
+
+ if (this.isPageErrorTest) {
+ this.isPageErrorTest = false;
+ throw new Error('Server timed out trying to retrieve data for the last page');
+ }
+
+ for (const param of queryParams) {
+ if (param.includes('$top=')) {
+ top = +(param.substring('$top='.length));
+ if (top === 50000) {
+ throw new Error('Server timed out retrieving 50,000 rows');
+ }
+ }
+ if (param.includes('$skip=')) {
+ skip = +(param.substring('$skip='.length));
+ }
+ if (param.includes('$orderby=')) {
+ orderBy = param.substring('$orderby='.length);
+ }
+ if (param.includes('$filter=')) {
+ const filterBy = param.substring('$filter='.length).replace('%20', ' ');
+ if (filterBy.includes('matchespattern')) {
+ const regex = new RegExp(`matchespattern\\(([a-zA-Z]+),\\s'${CARET_HTML_ESCAPED}(.*?)'\\)`, 'i');
+ const filterMatch = filterBy.match(regex) || [];
+ const fieldName = filterMatch[1].trim();
+ columnFilters[fieldName] = { type: 'matchespattern', term: '^' + filterMatch[2].trim() };
+ }
+ if (filterBy.includes('contains')) {
+ const filterMatch = filterBy.match(/contains\(([a-zA-Z/]+),\s?'(.*?)'/) || [];
+ const fieldName = filterMatch[1].trim();
+ columnFilters[fieldName] = { type: 'substring', term: filterMatch[2].trim() };
+ }
+ if (filterBy.includes('substringof')) {
+ const filterMatch = filterBy.match(/substringof\('(.*?)',\s([a-zA-Z/]+)/) || [];
+ const fieldName = filterMatch[2].trim();
+ columnFilters[fieldName] = { type: 'substring', term: filterMatch[1].trim() };
+ }
+ for (const operator of ['eq', 'ne', 'le', 'lt', 'gt', 'ge']) {
+ if (filterBy.includes(operator)) {
+ const re = new RegExp(`([a-zA-Z ]*) ${operator} '(.*?)'`);
+ const filterMatch = re.exec(filterBy);
+ if (Array.isArray(filterMatch)) {
+ const fieldName = filterMatch[1].trim();
+ columnFilters[fieldName] = { type: operator, term: filterMatch[2].trim() };
+ }
+ }
+ }
+ if (filterBy.includes('startswith') && filterBy.includes('endswith')) {
+ const filterStartMatch = filterBy.match(/startswith\(([a-zA-Z ]*),\s?'(.*?)'/) || [];
+ const filterEndMatch = filterBy.match(/endswith\(([a-zA-Z ]*),\s?'(.*?)'/) || [];
+ const fieldName = filterStartMatch[1].trim();
+ columnFilters[fieldName] = { type: 'starts+ends', term: [filterStartMatch[2].trim(), filterEndMatch[2].trim()] };
+ } else if (filterBy.includes('startswith')) {
+ const filterMatch = filterBy.match(/startswith\(([a-zA-Z ]*),\s?'(.*?)'/) || [];
+ const fieldName = filterMatch[1].trim();
+ columnFilters[fieldName] = { type: 'starts', term: filterMatch[2].trim() };
+ } else if (filterBy.includes('endswith')) {
+ const filterMatch = filterBy.match(/endswith\(([a-zA-Z ]*),\s?'(.*?)'/) || [];
+ const fieldName = filterMatch[1].trim();
+ columnFilters[fieldName] = { type: 'ends', term: filterMatch[2].trim() };
+ }
+
+ // simular a backend error when trying to sort on the "Company" field
+ if (filterBy.includes('company')) {
+ throw new Error('Server could not filter using the field "Company"');
+ }
+ }
+ }
+
+ // simulate a backend error when trying to sort on the "Company" field
+ if (orderBy.includes('company')) {
+ throw new Error('Server could not sort using the field "Company"');
+ }
+
+ this.http.fetch(`${sampleDataRoot}/customers_100.json`)
+ .then(e => e.json())
+ .then((data: any) => {
+ // Sort the data
+ if (orderBy?.length > 0) {
+ const orderByClauses = orderBy.split(',');
+ for (const orderByClause of orderByClauses) {
+ const orderByParts = orderByClause.split(' ');
+ const orderByField = orderByParts[0];
+
+ let selector = (obj: any): string => obj;
+ for (const orderByFieldPart of orderByField.split('/')) {
+ const prevSelector = selector;
+ selector = (obj: any) => {
+ return prevSelector(obj)[orderByFieldPart as any];
+ };
+ }
+
+ const sort = orderByParts[1] ?? 'asc';
+ switch (sort.toLocaleLowerCase()) {
+ case 'asc':
+ data = data.sort((a, b) => selector(a).localeCompare(selector(b)));
+ break;
+ case 'desc':
+ data = data.sort((a, b) => selector(b).localeCompare(selector(a)));
+ break;
+ }
+ }
+ }
+
+ // Read the result field from the JSON response.
+ let firstRow = skip;
+ let filteredData = data;
+ if (columnFilters) {
+ for (const columnId in columnFilters) {
+ if (columnFilters.hasOwnProperty(columnId)) {
+ filteredData = filteredData.filter(column => {
+ const filterType = columnFilters[columnId].type;
+ const searchTerm = columnFilters[columnId].term;
+ let colId = columnId;
+ if (columnId?.indexOf(' ') !== -1) {
+ const splitIds = columnId.split(' ');
+ colId = splitIds[splitIds.length - 1];
+ }
+
+ let filterTerm;
+ let col = column;
+ for (const part of colId.split('/')) {
+ filterTerm = col[part];
+ col = filterTerm;
+ }
+
+ if (filterTerm) {
+ const [term1, term2] = Array.isArray(searchTerm) ? searchTerm : [searchTerm];
+
+ switch (filterType) {
+ case 'eq': return filterTerm.toLowerCase() === term1;
+ case 'ne': return filterTerm.toLowerCase() !== term1;
+ case 'le': return filterTerm.toLowerCase() <= term1;
+ case 'lt': return filterTerm.toLowerCase() < term1;
+ case 'gt': return filterTerm.toLowerCase() > term1;
+ case 'ge': return filterTerm.toLowerCase() >= term1;
+ case 'ends': return filterTerm.toLowerCase().endsWith(term1);
+ case 'starts': return filterTerm.toLowerCase().startsWith(term1);
+ case 'starts+ends': return filterTerm.toLowerCase().startsWith(term1) && filterTerm.toLowerCase().endsWith(term2);
+ case 'substring': return filterTerm.toLowerCase().includes(term1);
+ case 'matchespattern': return new RegExp((term1 as string).replaceAll(PERCENT_HTML_ESCAPED, '.*'), 'i').test(filterTerm);
+ }
+ }
+ });
+ }
+ }
+ countTotalItems = filteredData.length;
+ }
+
+ // make sure page skip is not out of boundaries, if so reset to first page & remove skip from query
+ if (firstRow > filteredData.length) {
+ query = query.replace(`$skip=${firstRow}`, '');
+ firstRow = 0;
+ }
+ const updatedData = filteredData.slice(firstRow, firstRow + top);
+
+ setTimeout(() => {
+ const backendResult: any = { query };
+ backendResult['value'] = updatedData;
+ backendResult['@odata.count'] = countTotalItems;
+
+ // console.log('Backend Result', backendResult);
+ resolve(backendResult);
+ }, 100);
+ });
+ });
+ }
+
+ groupByGender() {
+ this.aureliaGrid?.dataView?.setGrouping({
+ getter: 'gender',
+ formatter: (g) => `Gender: ${g.value} (${g.count} items)`,
+ comparer: (a, b) => SortComparers.string(a.value, b.value),
+ aggregators: [
+ new Aggregators.Sum('gemder')
+ ],
+ aggregateCollapsed: false,
+ lazyTotalsCalculation: true
+ } as Grouping);
+
+ // you need to manually add the sort icon(s) in UI
+ this.aureliaGrid?.slickGrid.setSortColumns([{ columnId: 'duration', sortAsc: true }]);
+ this.aureliaGrid?.slickGrid.invalidate(); // invalidate all rows and re-render
+ }
+
+ clearAllFiltersAndSorts() {
+ if (this.aureliaGrid?.gridService) {
+ this.aureliaGrid.gridService.clearAllFiltersAndSorts();
+ }
+ }
+
+ setFiltersDynamically() {
+ // we can Set Filters Dynamically (or different filters) afterward through the FilterService
+ this.aureliaGrid?.filterService.updateFilters([
+ { columnId: 'gender', searchTerms: ['female'] },
+ ]);
+ }
+
+ refreshMetrics(args: OnRowCountChangedEventArgs) {
+ if (args?.current >= 0) {
+ this.metrics.itemCount = this.aureliaGrid.dataView?.getFilteredItemCount() || 0;
+ this.tagDataClass = this.metrics.itemCount === this.metrics.totalItemCount
+ ? 'fully-loaded'
+ : 'partial-load';
+ }
+ }
+
+ setSortingDynamically() {
+ this.aureliaGrid?.sortService.updateSorting([
+ { columnId: 'name', direction: 'DESC' },
+ ]);
+ }
+}
diff --git a/packages/demo/src/examples/slickgrid/example39.html b/packages/demo/src/examples/slickgrid/example39.html
new file mode 100644
index 000000000..53adde957
--- /dev/null
+++ b/packages/demo/src/examples/slickgrid/example39.html
@@ -0,0 +1,101 @@
+
+
+ Example 39: GraphQL Backend Service with Infinite Scroll
+
+
+ code
+
+
+
+
+
+
+
+ Infinite scrolling allows the grid to lazy-load rows from the server when reaching the scroll bottom (end) position.
+ In its simplest form, the more the user scrolls down, the more rows get loaded.
+ If we reached the end of the dataset and there is no more data to load, then we'll assume to have the entire dataset loaded in memory.
+ This contrast with the regular Pagination approach which will hold only hold data for 1 page at a time.
+
+
NOTES
+
+
+ presets.pagination is not supported with Infinite Scroll and will revert to the first page,
+ simply because since we keep appending data, we always have to start from index zero (no offset).
+
+
+ Pagination is not shown BUT in fact, that is what is being used behind the scene whenever reaching the scroll end (fetching next batch).
+
+
+ Also note that whenever the user changes the Sort(s)/Filter(s) it will always reset and go back to zero index (first page).
+
+
+
+
+
+
+
+
+ Status: ${status.text}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Locale:
+
+ ${selectedLanguage + '.json'}
+
+
+
+
+
+ Metrics:
+
+ ${metrics.endTime | dateFormat: 'DD MMM, h:mm:ss a'} —
+ ${metrics.itemCount}
+ of
+ ${metrics.totalItemCount}
+ items
+
+ All Data Loaded!!!
+