Skip to content
This repository was archived by the owner on Jun 1, 2025. It is now read-only.

Commit cadfb9b

Browse files
authored
feat: allow providing custom date format via base Date Formatter (#1345)
1 parent c5e4837 commit cadfb9b

6 files changed

Lines changed: 148 additions & 59 deletions

File tree

docs/column-functionalities/formatters.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ A good example of a `Formatter` could be a timestamp or a `Date` object that we
5555
* `Formatters.dateTimeShortUs`: Takes a Date object and displays it as an US Date+Time (without seconds) format (MM/DD/YYYY HH:mm:ss)
5656
* `Formatters.dateTimeUsAmPm` : Takes a Date object and displays it as an US Date+Time+(am/pm) format (MM/DD/YYYY hh:mm:ss a)
5757
* `Formatters.dateUtc` : Takes a Date object and displays it as a TZ format (YYYY-MM-DDThh:mm:ssZ)
58+
* `Formatters.date`: Base Date Formatter, this formatter is a bit different compare to other date formatter since this one requires the user to provide a custom format in `params.dateFormat`
59+
- for example: `{ type: 'date', formatter: Formatters.date, params: { dateFormat: 'MMM DD, YYYY' }}`
5860
* `Formatters.decimal`: Display the value as x decimals formatted, defaults to 2 decimals. You can pass "minDecimal" and/or "maxDecimal" to the "params" property.
5961
* `Formatters.dollar`: Display the value as 2 decimals formatted with dollar sign '$' at the end of of the value.
6062
* `Formatters.dollarColored`: Display the value as 2 decimals formatted with dollar sign '$' at the end of of the value, change color of text to red/green on negative/positive value

docs/column-functionalities/sorting.md

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
- [Custom Sort Comparer](#custom-sort-comparer)
55
- [Update Sorting Dynamically](#update-sorting-dynamically)
66
- [Dynamic Query Field](#dynamic-query-field)
7+
- [Sorting Dates](#sorting-dates)
78
- [Pre-Parse Date Columns for better perf](#pre-parse-date-columns-for-better-perf)
89

910
### Demo
@@ -139,6 +140,14 @@ queryFieldNameGetterFn: (dataContext) => {
139140
},
140141
```
141142

143+
### Sorting Dates
144+
145+
Date sorting should work out of the box as long as you provide the correct column field type. Note that there are various field types that can be provided and they all do different things. For the Sorting to work properly, you need to make sure to use the correct type for Date parsing to work accordingly. Below is a list of column definition types that you can provide:
146+
147+
- `type`: input/output of date fields, or in other words, parsing/formatting dates with the field `type` provided
148+
- `outputType`: when a `type` is provided for parsing (i.e. from your dataset), you could use a different `outputType` to format your date differently
149+
- `saveOutputType`: if you already have a `type` and an `outputType` but you wish to save your date (i.e. save to DB) in yet another format
150+
142151
### Pre-Parse Date Columns for better perf
143152
##### requires v8.8.0 and higher
144153

@@ -154,11 +163,11 @@ The summary, is that we get a 10x boost **but** not only that, we also get an ex
154163

155164
#### Usage
156165

157-
You can use the `preParseDateColumns` grid option, it can be either set as either `boolean` or a `string` but there's big distinction between the 2 approaches (both approaches will mutate the dataset).
166+
You can use the `preParseDateColumns` grid option, it can be set as either a `boolean` or a `string` but there's a big distinction between the 2 approaches as shown below (note that both approaches will mutate the dataset).
158167
1. `string` (i.e. set to `"__"`, it will parse a `"start"` date string and assign it as a `Date` object to a new `"__start"` prop)
159168
2. `boolean` (i.e. parse `"start"` date string and reassign it as a `Date` object on the same `"start"` prop)
160169

161-
> **Note** this option **does not work** with Backend Services because it simply has no effect.
170+
> **Note** this option **does not work** with the Backend Service API because it simply has no effect.
162171
163172
For example if our dataset has 2 columns named "start" and "finish", then pre-parse the dataset,
164173

@@ -184,7 +193,7 @@ data = [
184193
]
185194
```
186195

187-
Which approach to choose? Both have pros and cons, overwriting the same props might cause problems with the column `type` that you use, you will have to give it a try yoursel. On the other hand, with the other approach, it will duplicate all date properties and take a bit more memory usage and when changing cells we'll need to make sure to keep these props in sync, however you will likely have less `type` issues.
196+
Which approach to choose? Both have pros and cons, overwriting the same props might cause problems with the column `type` that you use, you will have to give it a try yourself. On the other hand, with the other approach, it will duplicate all date properties and take a bit more memory usage and when changing cells we'll need to make sure to keep these props in sync, however you will likely have less `type` issues.
188197

189198
What happens when we do any cell changes (for our use case, it would be Create/Update), for any Editors we simply subscribe to the `onCellChange` change event and we re-parse the date strings when detected. We also subscribe to certain CRUD functions as long as they come from the `GridService` then all is fine... However, if you use the DataView functions directly then we have no way of knowing when to parse because these functions from the DataView don't have any events. Lastly, if we overwrite the entire dataset, we will also detect this (via an internal flag) and the next time you sort a date then the pre-parse kicks in again.
190199

packages/demo/src/examples/slickgrid/example40.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ <h2>
7272
dataset.bind="dataset"
7373
instances.bind="aureliaGrid"
7474
on-aurelia-grid-created.trigger="aureliaGridReady($event.detail)"
75-
on-row-count-changed.trigger="refreshMetrics($event.detail.args)"
75+
on-row-count-changed.trigger="handleOnRowCountChanged($event.detail.args)"
7676
on-sort.trigger="handleOnSort()"
7777
on-scroll.trigger="handleOnScroll($event.detail.args)">
7878
</aurelia-slickgrid>

packages/demo/src/examples/slickgrid/example40.ts

Lines changed: 72 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { ExcelExportService } from '@slickgrid-universal/excel-export';
12
import {
23
type AureliaGridInstance,
34
Aggregators,
@@ -13,6 +14,8 @@ import {
1314
SortDirectionNumber,
1415
} from 'aurelia-slickgrid';
1516

17+
import { randomNumber } from './utilities';
18+
1619
const FETCH_SIZE = 50;
1720

1821
export class Example40 {
@@ -40,11 +43,63 @@ export class Example40 {
4043
defineGrid() {
4144
this.columnDefinitions = [
4245
{ id: 'title', name: 'Title', field: 'title', sortable: true, minWidth: 100, filterable: true },
43-
{ id: 'duration', name: 'Duration (days)', field: 'duration', sortable: true, minWidth: 100, filterable: true, type: FieldType.number },
44-
{ id: 'percentComplete', name: '% Complete', field: 'percentComplete', sortable: true, minWidth: 100, filterable: true, type: FieldType.number },
45-
{ id: 'start', name: 'Start', field: 'start', formatter: Formatters.dateIso, exportWithFormatter: true, filterable: true, filter: { model: Filters.compoundDate } },
46-
{ id: 'finish', name: 'Finish', field: 'finish', formatter: Formatters.dateIso, exportWithFormatter: true, filterable: true, filter: { model: Filters.compoundDate } },
47-
{ id: 'effort-driven', name: 'Effort Driven', field: 'effortDriven', sortable: true, minWidth: 100, filterable: true, formatter: Formatters.checkmarkMaterial }
46+
{
47+
id: 'duration',
48+
name: 'Duration (days)',
49+
field: 'duration',
50+
sortable: true,
51+
minWidth: 100,
52+
filterable: true,
53+
type: FieldType.number,
54+
},
55+
{
56+
id: 'percentComplete',
57+
name: '% Complete',
58+
field: 'percentComplete',
59+
sortable: true,
60+
minWidth: 100,
61+
filterable: true,
62+
type: FieldType.number,
63+
},
64+
{
65+
id: 'start',
66+
name: 'Start',
67+
field: 'start',
68+
type: FieldType.date,
69+
outputType: FieldType.dateIso, // for date picker format
70+
formatter: Formatters.date,
71+
exportWithFormatter: true,
72+
params: { dateFormat: 'MMM DD, YYYY' },
73+
sortable: true,
74+
filterable: true,
75+
filter: {
76+
model: Filters.compoundDate,
77+
},
78+
},
79+
{
80+
id: 'finish',
81+
name: 'Finish',
82+
field: 'finish',
83+
type: FieldType.date,
84+
outputType: FieldType.dateIso, // for date picker format
85+
formatter: Formatters.date,
86+
exportWithFormatter: true,
87+
params: { dateFormat: 'MMM DD, YYYY' },
88+
sortable: true,
89+
filterable: true,
90+
filter: {
91+
model: Filters.compoundDate,
92+
},
93+
},
94+
{
95+
id: 'effort-driven',
96+
name: 'Effort Driven',
97+
field: 'effortDriven',
98+
sortable: true,
99+
minWidth: 100,
100+
filterable: true,
101+
formatter: Formatters.checkmarkMaterial,
102+
},
48103
];
49104

50105
this.gridOptions = {
@@ -57,6 +112,8 @@ export class Example40 {
57112
enableGrouping: true,
58113
editable: false,
59114
rowHeight: 33,
115+
enableExcelExport: true,
116+
externalResources: [new ExcelExportService()],
60117
};
61118
}
62119

@@ -115,19 +172,14 @@ export class Example40 {
115172
}
116173

117174
newItem(idx: number) {
118-
const randomYear = 2000 + Math.floor(Math.random() * 10);
119-
const randomMonth = Math.floor(Math.random() * 11);
120-
const randomDay = Math.floor((Math.random() * 29));
121-
const randomPercent = Math.round(Math.random() * 100);
122-
123175
return {
124176
id: idx,
125177
title: 'Task ' + idx,
126178
duration: Math.round(Math.random() * 100) + '',
127-
percentComplete: randomPercent,
128-
start: new Date(randomYear, randomMonth + 1, randomDay),
129-
finish: new Date(randomYear + 1, randomMonth + 1, randomDay),
130-
effortDriven: (idx % 5 === 0)
179+
percentComplete: randomNumber(1, 12),
180+
start: new Date(2020, randomNumber(1, 11), randomNumber(1, 28)),
181+
finish: new Date(2022, randomNumber(1, 11), randomNumber(1, 28)),
182+
effortDriven: idx % 5 === 0,
131183
};
132184
}
133185

@@ -143,13 +195,15 @@ export class Example40 {
143195

144196
setFiltersDynamically() {
145197
// we can Set Filters Dynamically (or different filters) afterward through the FilterService
146-
this.aureliaGrid?.filterService.updateFilters([
147-
{ columnId: 'percentComplete', searchTerms: ['50'], operator: '>=' },
148-
]);
198+
this.aureliaGrid?.filterService.updateFilters([{ columnId: 'start', searchTerms: ['2020-08-25'], operator: '<=' }]);
149199
}
150200

151-
refreshMetrics(args: OnRowCountChangedEventArgs) {
201+
handleOnRowCountChanged(args: OnRowCountChangedEventArgs) {
152202
if (this.aureliaGrid && args?.current >= 0) {
203+
// we probably want to re-sort the data when we get new items
204+
this.aureliaGrid.dataView?.reSort();
205+
206+
// update metrics
153207
this.metrics.itemCount = this.aureliaGrid.dataView?.getFilteredItemCount() || 0;
154208
this.metrics.totalItemCount = args.itemCount || 0;
155209
}

packages/demo/src/examples/slickgrid/utilities.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
export function randomNumber(min: number, max: number, floor = true) {
2+
const number = Math.random() * (max - min + 1) + min;
3+
return floor ? Math.floor(number) : number;
4+
}
5+
16
export function zeroPadding(input: string | number) {
27
const number = parseInt(input as string, 10);
38
return number < 10 ? `0${number}` : number;

test/cypress/e2e/example40.cy.ts

Lines changed: 56 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -18,44 +18,37 @@ describe('Example 40 - Infinite Scroll from JSON data', () => {
1818
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(0)`).should('contain', 'Task 0');
1919
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(1)`).contains(/[0-9]/);
2020
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(2)`).contains(/[0-9]/);
21-
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(3)`).contains(/20[0-9]{2}-[0-9]{2}-[0-9]{2}/);
22-
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(4)`).contains(/20[0-9]{2}-[0-9]{2}-[0-9]{2}/);
23-
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(5)`).find('.mdi.mdi-check').should('have.length', 1);
21+
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(3)`).contains('2020');
22+
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(4)`).contains('2022');
23+
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(5)`)
24+
.find('.mdi.mdi-check')
25+
.should('have.length', 1);
2426
});
2527

2628
it('should scroll to bottom of the grid and expect next batch of 50 items appended to current dataset for a total of 100 items', () => {
27-
cy.get('[data-test="totalItemCount"]')
28-
.should('have.text', '50');
29+
cy.get('[data-test="totalItemCount"]').should('have.text', '50');
2930

30-
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left')
31-
.scrollTo('bottom');
31+
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left').scrollTo('bottom');
3232

33-
cy.get('[data-test="totalItemCount"]')
34-
.should('have.text', '100');
33+
cy.get('[data-test="totalItemCount"]').should('have.text', '100');
3534
});
3635

3736
it('should scroll to bottom of the grid again and expect 50 more items for a total of now 150 items', () => {
38-
cy.get('[data-test="totalItemCount"]')
39-
.should('have.text', '100');
37+
cy.get('[data-test="totalItemCount"]').should('have.text', '100');
4038

41-
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left')
42-
.scrollTo('bottom');
39+
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left').scrollTo('bottom');
4340

44-
cy.get('[data-test="totalItemCount"]')
45-
.should('have.text', '150');
41+
cy.get('[data-test="totalItemCount"]').should('have.text', '150');
4642
});
4743

4844
it('should disable onSort for data reset and expect same dataset length of 150 items after sorting by Title', () => {
4945
cy.get('[data-test="onsort-off"]').click();
5046

51-
cy.get('[data-id="title"]')
52-
.click();
47+
cy.get('[data-id="title"]').click();
5348

54-
cy.get('[data-test="totalItemCount"]')
55-
.should('have.text', '150');
49+
cy.get('[data-test="totalItemCount"]').should('have.text', '150');
5650

57-
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left')
58-
.scrollTo('top');
51+
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left').scrollTo('top');
5952

6053
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(0)`).should('contain', 'Task 0');
6154
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 1}px;"] > .slick-cell:nth(0)`).should('contain', 'Task 1');
@@ -66,14 +59,11 @@ describe('Example 40 - Infinite Scroll from JSON data', () => {
6659
it('should enable onSort for data reset and expect dataset to be reset to 50 items after sorting by Title', () => {
6760
cy.get('[data-test="onsort-on"]').click();
6861

69-
cy.get('[data-id="title"]')
70-
.click();
62+
cy.get('[data-id="title"]').click();
7163

72-
cy.get('[data-test="totalItemCount"]')
73-
.should('have.text', '50');
64+
cy.get('[data-test="totalItemCount"]').should('have.text', '50');
7465

75-
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left')
76-
.scrollTo('top');
66+
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left').scrollTo('top');
7767

7868
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(0)`).should('contain', 'Task 9');
7969
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 1}px;"] > .slick-cell:nth(0)`).should('contain', 'Task 8');
@@ -84,27 +74,56 @@ describe('Example 40 - Infinite Scroll from JSON data', () => {
8474
it('should "Group by Duration" and expect 50 items grouped', () => {
8575
cy.get('[data-test="group-by-duration"]').click();
8676

87-
cy.get('[data-test="totalItemCount"]')
88-
.should('have.text', '50');
77+
cy.get('[data-test="totalItemCount"]').should('have.text', '50');
8978

90-
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left')
91-
.scrollTo('top');
79+
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left').scrollTo('top');
9280

9381
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(0) .slick-group-toggle.expanded`).should('have.length', 1);
9482
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(0) .slick-group-title`).contains(/Duration: [0-9]/);
9583
});
9684

9785
it('should scroll to the bottom "Group by Duration" and expect 50 more items for a total of 100 items grouped', () => {
98-
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left')
99-
.scrollTo('bottom');
86+
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left').scrollTo('bottom');
10087

101-
cy.get('[data-test="totalItemCount"]')
102-
.should('have.text', '100');
88+
cy.get('[data-test="totalItemCount"]').should('have.text', '100');
10389

104-
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left')
105-
.scrollTo('top');
90+
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left').scrollTo('top');
10691

10792
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(0) .slick-group-toggle.expanded`).should('have.length', 1);
10893
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(0) .slick-group-title`).contains(/Duration: [0-9]/);
10994
});
95+
96+
it('should clear all grouping', () => {
97+
cy.get('#grid40').find('.slick-row .slick-cell:nth(1)').rightclick({ force: true });
98+
99+
cy.get('.slick-context-menu.dropright .slick-menu-command-list')
100+
.find('.slick-menu-item')
101+
.find('.slick-menu-content')
102+
.contains('Clear all Grouping')
103+
.click();
104+
});
105+
106+
it('should hover over the "Start" column header menu of 1st grid and click on "Sort Descending" command', () => {
107+
cy.get('[data-test="clear-filters-sorting"]').click();
108+
cy.get('#grid40').find('.slick-header-column:nth(3)').trigger('mouseover').children('.slick-header-menu-button').invoke('show').click();
109+
110+
cy.get('.slick-header-menu .slick-menu-command-list').should('be.visible').should('contain', 'Sort Descending').click();
111+
112+
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(3)`).contains('2020');
113+
});
114+
115+
it('should load 200 items and filter "Start" column with <=2020-08-25', () => {
116+
cy.get('[data-test="set-dynamic-filter"]').click();
117+
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left').scrollTo('bottom');
118+
cy.wait(10);
119+
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left').scrollTo('bottom');
120+
cy.get('[data-test="totalItemCount"]').should('have.text', '200');
121+
122+
cy.get('.slick-viewport.slick-viewport-top.slick-viewport-left').scrollTo('top');
123+
124+
cy.get(`[data-row=0] > .slick-cell:nth(3)`).contains(/^Aug [0-9]{2}, 2020$/);
125+
cy.get(`[data-row=1] > .slick-cell:nth(3)`).contains(/^Aug [0-9]{2}, 2020$/);
126+
cy.get(`[data-row=2] > .slick-cell:nth(3)`).contains(/^Aug [0-9]{2}, 2020$/);
127+
cy.get(`[data-row=3] > .slick-cell:nth(3)`).contains(/^Aug [0-9]{2}, 2020$/);
128+
});
110129
});

0 commit comments

Comments
 (0)