-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathExample23.tsx
425 lines (380 loc) · 16 KB
/
Example23.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import { addDay, format } from '@formkit/tempo';
import { SlickCustomTooltip } from '@slickgrid-universal/custom-tooltip-plugin';
import { ExcelExportService } from '@slickgrid-universal/excel-export';
import i18next, { type TFunction } from 'i18next';
import { CustomInputFilter } from './custom-inputFilter';
import {
type Column,
type CurrentFilter,
FieldType,
Filters,
type Formatter,
Formatters,
type GridOption,
type GridStateChange,
type GroupingGetterFunction,
type Metrics,
type MultipleSelectOption,
OperatorType,
type SlickGrid,
type SliderRangeOption,
SlickgridReact,
type SlickgridReactInstance,
} from '../../slickgrid-react';
import React from 'react';
import { withTranslation } from 'react-i18next';
import type BaseSlickGridState from './state-slick-grid-base';
interface Props {
t: TFunction;
}
interface State extends BaseSlickGridState {
selectedLanguage: string;
metrics?: Metrics;
selectedGroupingFields: Array<string | GroupingGetterFunction>;
selectedPredefinedFilter: string;
filterList: Array<{ value: string; label: string; }>;
}
const NB_ITEMS = 1500;
function randomBetween(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// create a custom translate Formatter (typically you would move that a separate file, for separation of concerns)
const taskTranslateFormatter: Formatter = (_row, _cell, value, _columnDef, _dataContext, grid: SlickGrid) => {
const gridOptions = grid.getOptions() as GridOption;
return gridOptions.i18n?.t('TASK_X', { x: value }) ?? '';
};
class Example23 extends React.Component<Props, State> {
title = 'Example 23: Filtering from Range of Search Values';
subTitle = `
This demo shows how to use Filters with Range of Search Values (<a href="https://ghiscoding.gitbook.io/slickgrid-react/column-functionalities/filters/range-filters" target="_blank">Docs</a>)
<br/>
<ul class="small">
<li>All input filters support the following operators: (>, >=, <, <=, <>, !=, =, ==, *) and now also the (..) for an input range
<li>All filters (which support ranges) can be defined via the 2 dots (..) which represents a range, this also works for dates and slider in the "presets"</li>
<ul>
<li>For a numeric range defined in an input filter (must be of type text), you can use 2 dots (..) to represent a range</li>
<li>example: typing "10..90" will filter values between 10 and 90 (but excluding the number 10 and 90)</li>
</ul>
</ul>
`;
reactGrid!: SlickgridReactInstance;
// private i18n: i18n;
constructor(public readonly props: Props) {
super(props);
// always start with English for Cypress E2E tests to be consistent
const defaultLang = 'en';
i18next.changeLanguage(defaultLang);
this.state = {
gridOptions: undefined,
columnDefinitions: [],
selectedLanguage: 'en',
metrics: undefined,
selectedGroupingFields: ['', '', ''],
selectedPredefinedFilter: '',
filterList: [
{ value: '', label: '...' },
{ value: 'currentYearTasks', label: 'Current Year Completed Tasks' },
{ value: 'nextYearTasks', label: 'Next Year Active Tasks' }
]
};
}
componentDidMount() {
document.title = this.title;
// define the grid options & columns and then create the grid itself
this.defineGrid();
}
componentWillUnmount() {
this.saveCurrentGridState();
}
reactGridReady(reactGrid: SlickgridReactInstance) {
this.reactGrid = reactGrid;
}
/* Define grid Options and Columns */
defineGrid() {
const columnDefinitions: Column[] = [
{
id: 'title', name: 'Title', field: 'id', nameKey: 'TITLE', minWidth: 100,
formatter: taskTranslateFormatter,
sortable: true,
filterable: true,
params: { useFormatterOuputToFilter: true }
},
{
id: 'description', name: 'Description', field: 'description', filterable: true, sortable: true, minWidth: 80,
type: FieldType.string,
filter: {
model: CustomInputFilter, // create a new instance to make each Filter independent from each other
enableTrimWhiteSpace: true // or use global "enableFilterTrimWhiteSpace" to trim on all Filters
}
},
{
id: 'percentComplete', name: '% Complete', field: 'percentComplete', nameKey: 'PERCENT_COMPLETE', minWidth: 120,
sortable: true,
customTooltip: { position: 'center' },
formatter: Formatters.progressBar,
type: FieldType.number,
filterable: true,
filter: {
model: Filters.sliderRange,
maxValue: 100, // or you can use the filterOptions as well
operator: OperatorType.rangeInclusive, // defaults to inclusive
filterOptions: {
hideSliderNumbers: false, // you can hide/show the slider numbers on both side
min: 0, step: 5
} as SliderRangeOption
}
},
{
id: 'start', name: 'Start', field: 'start', nameKey: 'START', formatter: Formatters.dateIso, sortable: true, minWidth: 75, width: 100, exportWithFormatter: true,
type: FieldType.date, filterable: true, filter: { model: Filters.compoundDate }
},
{
id: 'finish', name: 'Finish', field: 'finish', nameKey: 'FINISH', formatter: Formatters.dateIso, sortable: true, minWidth: 75, width: 120, exportWithFormatter: true,
type: FieldType.date,
filterable: true,
filter: {
model: Filters.dateRange,
}
},
{
id: 'duration', field: 'duration', nameKey: 'DURATION', maxWidth: 90,
type: FieldType.number,
sortable: true,
filterable: true, filter: {
model: Filters.input,
operator: OperatorType.rangeExclusive // defaults to exclusive
}
},
{
id: 'completed', name: 'Completed', field: 'completed', nameKey: 'COMPLETED', minWidth: 85, maxWidth: 90,
formatter: Formatters.checkmarkMaterial,
exportWithFormatter: true, // you can set this property in the column definition OR in the grid options, column def has priority over grid options
filterable: true,
filter: {
collection: [{ value: '', label: '' }, { value: true, label: 'True' }, { value: false, label: 'False' }],
model: Filters.singleSelect,
filterOptions: { autoAdjustDropHeight: true } as MultipleSelectOption
}
}
];
const presetLowestDay = format(addDay(new Date(), -2), 'YYYY-MM-DD');
const presetHighestDay = format(addDay(new Date(), 25), 'YYYY-MM-DD');
const gridOptions: GridOption = {
autoResize: {
container: '#demo-container',
rightPadding: 10
},
enableExcelCopyBuffer: true,
enableFiltering: true,
// enableFilterTrimWhiteSpace: true,
enableTranslate: true,
// i18n: this.i18n,
// use columnDef searchTerms OR use presets as shown below
presets: {
filters: [
// you can use the 2 dots separator on all Filters which support ranges
{ columnId: 'duration', searchTerms: ['4..88'] },
// { columnId: 'percentComplete', searchTerms: ['5..80'] }, // without operator will default to 'RangeExclusive'
// { columnId: 'finish', operator: 'RangeInclusive', searchTerms: [`${presetLowestDay}..${presetHighestDay}`] },
// or you could also use 2 searchTerms values, instead of using the 2 dots (only works with SliderRange & DateRange Filters)
// BUT make sure to provide the operator, else the filter service won't know that this is really a range
{ columnId: 'percentComplete', operator: 'RangeInclusive', searchTerms: [5, 80] }, // same result with searchTerms: ['5..80']
{ columnId: 'finish', operator: 'RangeInclusive', searchTerms: [presetLowestDay, presetHighestDay] },
],
sorters: [
{ columnId: 'percentComplete', direction: 'DESC' },
{ columnId: 'duration', direction: 'ASC' },
],
},
externalResources: [new SlickCustomTooltip(), new ExcelExportService()],
};
this.setState((state: State) => ({
...state,
gridOptions,
columnDefinitions,
dataset: this.mockData(NB_ITEMS)
}));
}
mockData(itemCount: number, startingIndex = 0): any[] {
// mock a dataset
const tempDataset: any[] = [];
for (let i = startingIndex; i < (startingIndex + itemCount); i++) {
const randomDuration = randomBetween(0, 365);
const randomYear = randomBetween(new Date().getFullYear(), new Date().getFullYear() + 1);
const randomMonth = randomBetween(0, 12);
const randomDay = randomBetween(10, 28);
const randomPercent = randomBetween(0, 100);
tempDataset.push({
id: i,
title: 'Task ' + i,
description: (i % 5) ? 'desc ' + i : null, // also add some random to test NULL field
duration: randomDuration,
percentComplete: randomPercent,
percentCompleteNumber: randomPercent,
start: (i % 4) ? null : new Date(randomYear, randomMonth, randomDay), // provide a Date format
finish: new Date(randomYear, randomMonth, randomDay),
completed: (randomPercent === 100) ? true : false,
});
}
return tempDataset;
}
clearFilters() {
this.setState((state: State) => {
return {
...state,
selectedPredefinedFilter: ''
};
}, () => this.reactGrid.filterService.clearFilters());
}
/** Dispatched event of a Grid State Changed event */
gridStateChanged(gridState: GridStateChange) {
console.log('Client sample, Grid State changed:: ', gridState);
}
/** Save current Filters, Sorters in LocaleStorage or DB */
saveCurrentGridState() {
console.log('Client sample, current Grid State:: ', this.reactGrid.gridStateService.getCurrentGridState());
}
refreshMetrics(_e: Event, args: any) {
if (args?.current >= 0) {
window.setTimeout(() => {
this.setState((state: State) => {
return {
...state,
metrics: {
startTime: new Date(),
itemCount: args?.current ?? 0,
totalItemCount: state.dataset?.length || 0
}
};
});
});
}
}
selectedColumnChanged(e: React.ChangeEvent<HTMLSelectElement>) {
const selectedVal = (e.target as HTMLSelectElement)?.value ?? '';
const selectedColumn = this.state.columnDefinitions.find(c => c.id === selectedVal);
this.setState((state: State) => {
return {
...state,
selectedColumn,
};
});
}
setFiltersDynamically() {
const presetLowestDay = format(addDay(new Date(), -5), 'YYYY-MM-DD');
const presetHighestDay = format(addDay(new Date(), 25), 'YYYY-MM-DD');
// we can Set Filters Dynamically (or different filters) afterward through the FilterService
this.reactGrid.filterService.updateFilters([
{ columnId: 'duration', searchTerms: ['14..78'], operator: 'RangeInclusive' },
{ columnId: 'percentComplete', operator: 'RangeExclusive', searchTerms: [15, 85] },
{ columnId: 'finish', operator: 'RangeInclusive', searchTerms: [presetLowestDay, presetHighestDay] },
]);
}
setSortingDynamically() {
this.reactGrid.sortService.updateSorting([
// orders matter, whichever is first in array will be the first sorted column
{ columnId: 'finish', direction: 'DESC' },
{ columnId: 'percentComplete', direction: 'ASC' },
]);
}
async switchLanguage() {
const nextLanguage = (this.state.selectedLanguage === 'en') ? 'fr' : 'en';
await i18next.changeLanguage(nextLanguage);
this.setState((state: State) => ({ ...state, selectedLanguage: nextLanguage }));
}
predefinedFilterChanged(e: React.ChangeEvent<HTMLSelectElement>) {
const newPredefinedFilter = (e.target as HTMLSelectElement)?.value ?? '';
let filters: CurrentFilter[] = [];
const currentYear = new Date().getFullYear();
switch (newPredefinedFilter) {
case 'currentYearTasks':
filters = [
{ columnId: 'finish', operator: OperatorType.rangeInclusive, searchTerms: [`${currentYear}-01-01`, `${currentYear}-12-31`] },
{ columnId: 'completed', operator: OperatorType.equal, searchTerms: [true] },
];
break;
case 'nextYearTasks':
filters = [{ columnId: 'start', operator: '>=', searchTerms: [`${currentYear + 1}-01-01`] }];
break;
}
this.reactGrid.filterService.updateFilters(filters);
}
render() {
return !this.state.gridOptions ? '' : (
<div id="demo-container" className="container-fluid">
<h2>
{this.title}
<span className="float-end font18">
see
<a target="_blank"
href="https://github.com/ghiscoding/slickgrid-react/blob/master/src/examples/slickgrid/Example23.tsx">
<span className="mdi mdi-link-variant"></span> code
</a>
</span>
</h2>
<div className="subtitle" dangerouslySetInnerHTML={{ __html: this.subTitle }}></div>
<br />
{this.state.metrics && <span><><b>Metrics:</b>
{this.state.metrics.endTime ? format(this.state.metrics.endTime, 'YYYY-MM-DD HH:mm:ss') : ''}
| {this.state.metrics.itemCount} of {this.state.metrics.totalItemCount} items </>
</span>}
<form className="row row-cols-lg-auto g-1 align-items-center" onSubmit={(e) => e.preventDefault()}>
<div className="col">
<button className="btn btn-outline-secondary btn-sm btn-icon" data-test="clear-filters"
onClick={() => this.reactGrid.filterService.clearFilters()}>
Clear Filters
</button>
</div>
<div className="col">
<button className="btn btn-outline-secondary btn-sm btn-icon" data-test="clear-sorting"
onClick={() => this.reactGrid.sortService.clearSorting()}>
Clear Sorting
</button>
</div>
<div className="col">
<button className="btn btn-outline-secondary btn-sm btn-icon" data-test="set-dynamic-filter"
onClick={() => this.setFiltersDynamically()}>
Set Filters Dynamically
</button>
</div>
<div className="col">
<button className="btn btn-outline-secondary btn-sm btn-icon" data-test="set-dynamic-sorting"
onClick={() => this.setSortingDynamically()}>
Set Sorting Dynamically
</button>
</div>
<div className="col">
<label htmlFor="selectedFilter" style={{ marginLeft: '10px' }}>Predefined Filters</label>
</div>
<div className="col">
<select className="form-select" data-test="select-dynamic-filter" name="selectedFilter" onChange={($event) => this.predefinedFilterChanged($event)}>
{
this.state.filterList.map((filter) =>
<option value={filter.value} key={filter.value}>{filter.label}</option>
)
}
</select>
</div>
</form>
<div className="row mt-2">
<div className="col">
<button className="btn btn-outline-secondary btn-sm btn-icon me-1" data-test="language" onClick={() => this.switchLanguage()}>
<i className="mdi mdi-translate me-1"></i>
Switch Language
</button>
<b>Locale: </b> <span style={{ fontStyle: 'italic' }} data-test="selected-locale">{this.state.selectedLanguage + '.json'}</span>
</div>
</div>
<SlickgridReact gridId="grid23"
columnDefinitions={this.state.columnDefinitions}
gridOptions={this.state.gridOptions}
dataset={this.state.dataset}
onReactGridCreated={$event => this.reactGridReady($event.detail)}
onGridStateChanged={$event => this.gridStateChanged($event.detail)}
onRowCountChanged={$event => this.refreshMetrics($event.detail.eventData, $event.detail.args)}
/>
</div>
);
}
}
export default withTranslation()(Example23);