This repository was archived by the owner on Jun 1, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathExample23.tsx
More file actions
387 lines (348 loc) · 15.6 KB
/
Example23.tsx
File metadata and controls
387 lines (348 loc) · 15.6 KB
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
import { addDay, format } from '@formkit/tempo';
import { SlickCustomTooltip } from '@slickgrid-universal/custom-tooltip-plugin';
import { ExcelExportService } from '@slickgrid-universal/excel-export';
import i18next from 'i18next';
import { CustomInputFilter } from './custom-inputFilter';
import {
type Column,
type CurrentFilter,
FieldType,
Filters,
type Formatter,
Formatters,
type GridOption,
type GridStateChange,
type Metrics,
type MultipleSelectOption,
OperatorType,
type SlickGrid,
type SliderRangeOption,
SlickgridReact,
type SlickgridReactInstance,
} from '../../slickgrid-react';
import React, { useEffect, useRef, useState } from 'react';
import { withTranslation } from 'react-i18next';
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 }) ?? '';
};
const Example23: React.FC = () => {
const defaultLang = 'en';
const [columnDefinitions, setColumnDefinitions] = useState<Column[]>([]);
const [dataset] = useState<any[]>(getData(NB_ITEMS));
const [gridOptions, setGridOptions] = useState<GridOption | undefined>(undefined);
const [selectedLanguage, setSelectedLanguage] = useState<string>(defaultLang);
const reactGridRef = useRef<SlickgridReactInstance | null>(null);
const [filterList] = useState<{ value: string; label: string; }[]>([
{ value: '', label: '...' },
{ value: 'currentYearTasks', label: 'Current Year Completed Tasks' },
{ value: 'nextYearTasks', label: 'Next Year Active Tasks' }
]);
const [metrics, setMetrics] = useState<Metrics>();
const [hideSubTitle, setHideSubTitle] = useState(false);
useEffect(() => {
i18next.changeLanguage(defaultLang);
defineGrid();
// save grid state before unmounting
return () => {
saveCurrentGridState();
}
}, []);
function reactGridReady(reactGrid: SlickgridReactInstance) {
reactGridRef.current = reactGrid;
}
/* Define grid Options and Columns */
function 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: i18next,
// 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()],
};
setColumnDefinitions(columnDefinitions);
setGridOptions(gridOptions);
}
function getData(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;
}
// function clearFilters() {
// setSelectedPredefinedFilter('')
// // () => reactGrid.filterService.clearFilters());
// }
/** Dispatched event of a Grid State Changed event */
function gridStateChanged(gridState: GridStateChange) {
console.log('Client sample, Grid State changed:: ', gridState);
}
/** Save current Filters, Sorters in LocaleStorage or DB */
function saveCurrentGridState() {
console.log('Client sample, current Grid State:: ', reactGridRef.current?.gridStateService.getCurrentGridState());
}
function refreshMetrics(_e: Event, args: any) {
if (args?.current >= 0) {
window.setTimeout(() => {
setMetrics({
startTime: new Date(),
itemCount: args?.current ?? 0,
totalItemCount: dataset?.length || 0
});
});
}
}
// function selectedColumnChanged(e: React.ChangeEvent<HTMLSelectElement>) {
// const selectedVal = (e.target as HTMLSelectElement)?.value ?? '';
// const selectedColumn = columnDefinitions.find(c => c.id === selectedVal);
// setSelectedColumn(selectedColumn);
// }
function 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
reactGridRef.current?.filterService.updateFilters([
{ columnId: 'duration', searchTerms: ['14..78'], operator: 'RangeInclusive' },
{ columnId: 'percentComplete', operator: 'RangeExclusive', searchTerms: [15, 85] },
{ columnId: 'finish', operator: 'RangeInclusive', searchTerms: [presetLowestDay, presetHighestDay] },
]);
}
function setSortingDynamically() {
reactGridRef.current?.sortService.updateSorting([
// orders matter, whichever is first in array will be the first sorted column
{ columnId: 'finish', direction: 'DESC' },
{ columnId: 'percentComplete', direction: 'ASC' },
]);
}
async function switchLanguage() {
const nextLanguage = (selectedLanguage === 'en') ? 'fr' : 'en';
await i18next.changeLanguage(nextLanguage);
setSelectedLanguage(nextLanguage);
}
function 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;
}
reactGridRef.current?.filterService.updateFilters(filters);
}
function toggleSubTitle() {
const newHideSubTitle = !hideSubTitle;
setHideSubTitle(newHideSubTitle);
const action = newHideSubTitle ? 'add' : 'remove';
document.querySelector('.subtitle')?.classList[action]('hidden');
reactGridRef.current?.resizerService.resizeGrid(0);
}
return !gridOptions ? '' : (
<div id="demo-container" className="container-fluid">
<h2>
Example 23: Filtering from Range of Search Values
<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>
<button className="ms-2 btn btn-outline-secondary btn-sm btn-icon" type="button" data-test="toggle-subtitle" onClick={() => toggleSubTitle()}>
<span className="mdi mdi-information-outline" title="Toggle example sub-title details"></span>
</button>
</h2>
<div className="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 className="small">
<li>All input filters support the following operators: (>, >=, <, <=, <>, !=, =, ==, *) and now also the (..) for an input range</li>
<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>
</div>
<br />
{metrics && <span><><b>Metrics:</b>
{metrics.endTime ? format(metrics.endTime, 'YYYY-MM-DD HH:mm:ss') : ''}
| {metrics.itemCount} of {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={() => reactGridRef.current?.filterService.clearFilters()}>
Clear Filters
</button>
</div>
<div className="col">
<button className="btn btn-outline-secondary btn-sm btn-icon" data-test="clear-sorting"
onClick={() => reactGridRef.current?.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={() => 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={() => 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) => predefinedFilterChanged($event)}>
{
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={() => switchLanguage()}>
<i className="mdi mdi-translate me-1"></i>
Switch Language
</button>
<b>Locale: </b> <span style={{ fontStyle: 'italic' }} data-test="selected-locale">{selectedLanguage + '.json'}</span>
</div>
</div>
<SlickgridReact gridId="grid23"
columnDefinitions={columnDefinitions}
gridOptions={gridOptions}
dataset={dataset}
onReactGridCreated={$event => reactGridReady($event.detail)}
onGridStateChanged={$event => gridStateChanged($event.detail)}
onRowCountChanged={$event => refreshMetrics($event.detail.eventData, $event.detail.args)}
/>
</div>
);
}
export default withTranslation()(Example23);