forked from plotly/dash-ag-grid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashAgGridFunctions.js
More file actions
541 lines (469 loc) · 15.7 KB
/
dashAgGridFunctions.js
File metadata and controls
541 lines (469 loc) · 15.7 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
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
var dagfuncs = window.dashAgGridFunctions = window.dashAgGridFunctions || {};
dagfuncs.Round = function (v, a = 2) {
return Math.round(v * (10 ** a)) / (10 ** a)
}
dagfuncs.toFixed = function (v, a = 2) {
return Number(v).toFixed(a)
}
dagfuncs.addEdits = function (params) {
if (params.data.changes) {
var newList = JSON.parse(params.data.changes)
newList.push(params.colDef.field)
params.data.changes = JSON.stringify(newList)
} else {
params.data.changes = JSON.stringify([params.colDef.field])
}
params.data[params.colDef.field] = params.newValue
return true;
}
dagfuncs.highlightEdits = function (params) {
if (params.data.changes) {
if (JSON.parse(params.data.changes).includes(params.colDef.field)) {
return true
}
}
return false;
}
dagfuncs.rowTest = function (params) {
if (params.data.make == 'Toyota') {
return 'testing'
}
}
dagfuncs.ratioValueGetter = function (params) {
if (!(params.node && params.node.group)) {
// no need to handle group levels - calculated in the 'ratioAggFunc'
return createValueObject(params.data.gold, params.data.silver);
}
}
dagfuncs.ratioAggFunc = function (params) {
let goldSum = 0;
let silverSum = 0;
params.values.forEach((value) => {
if (value && value.gold) {
goldSum += value.gold;
}
if (value && value.silver) {
silverSum += value.silver;
}
});
return createValueObject(goldSum, silverSum);
}
function createValueObject(gold, silver) {
return {
gold: gold,
silver: silver,
toString: () => `${gold && silver ? gold / silver : 0}`,
};
}
dagfuncs.ratioFormatter = function (params) {
if (!params.value || params.value === 0) return '';
return '' + Math.round(params.value * 100) / 100;
}
dagfuncs.filterParams = () => {
return {
filterOptions: [
'lessThan',
{
displayKey: 'lessThanWithNulls',
displayName: 'Less Than with Nulls',
predicate: ([filterValue], cellValue) => cellValue == null || cellValue < filterValue,
},
'greaterThan',
{
displayKey: 'greaterThanWithNulls',
displayName: 'Greater Than with Nulls',
predicate: ([filterValue], cellValue) => cellValue == null || cellValue > filterValue,
},
{
displayKey: 'betweenExclusive',
displayName: 'Between (Exclusive)',
predicate: ([fv1, fv2], cellValue) => cellValue == null || fv1 < cellValue && fv2 > cellValue,
numberOfInputs: 2,
}
],
defaultOption: 'lessThanWithNulls',
}
};
dagfuncs.getDataPath = function (data) {
return data.orgHierarchy;
}
dagfuncs.DatePicker = class {
// gets called once before the renderer is used
init(params) {
// create the cell
this.eInput = document.createElement('input');
this.eInput.value = params.value;
this.eInput.classList.add('ag-input');
this.eInput.style.height = 'var(--ag-row-height)';
this.eInput.style.fontSize = 'calc(var(--ag-font-size) + 1px)';
// https://jqueryui.com/datepicker/
$(this.eInput).datepicker({
dateFormat: 'yy-mm-dd',
onSelect: () => {
this.eInput.focus();
},
});
}
// gets called once when grid ready to insert the element
getGui() {
return this.eInput;
}
// focus and select can be done after the gui is attached
afterGuiAttached() {
this.eInput.focus();
this.eInput.select();
}
// returns the new value after editing
getValue() {
return this.eInput.value;
}
// any cleanup we need to be done here
destroy() {
// but this example is simple, no cleanup, we could
// even leave this method out as it's optional
}
// if true, then this editor will appear in a popup
isPopup() {
// and we could leave this method out also, false is the default
return false;
}
}
dagfuncs.dateComparator = function (date1, date2) {
const date1Number = monthToComparableNumber(date1);
const date2Number = monthToComparableNumber(date2);
if (date1Number === null && date2Number === null) {
return 0;
}
if (date1Number === null) {
return -1;
}
if (date2Number === null) {
return 1;
}
return date1Number - date2Number;
}
// eg 29/08/2004 gets converted to 20040829
function monthToComparableNumber(date) {
if (date === undefined || date === null) {
return null;
}
const yearNumber = parseInt(date.split('/')[2]);
const monthNumber = parseInt(date.split('/')[1]);
const dayNumber = parseInt(date.split('/')[0]);
return yearNumber * 10000 + monthNumber * 100 + dayNumber;
}
const {useImperativeHandle, useState, useEffect, forwardRef} = React;
// This example was adapted from https://www.ag-grid.com/react-data-grid/component-filter/
// The only differences are:
// - React.createElement instead of JSX
// - setProps, which all Dash components use to report user interactions,
// instead of a plain js event handler
dagfuncs.YearFilter = forwardRef((props, ref) => {
const [year, setYear] = useState('All');
dash_ag_grid.useGridFilter({
doesFilterPass(params) {
return params.data.year >= 2010;
},
// this example isn't using getModel() and setModel(),
// so safe to just leave these empty. don't do this in your code!!!
getModel() {
},
setModel() {
}
});
useEffect(() => {
props.onModelChange(year === "All" ? null : year)
}, [year]);
setProps = ({value}) => {
if (value) {
setYear(value)
}
}
return React.createElement(
window.dash_core_components.RadioItems,
{
options: [
{'label': 'All', 'value': 'All'},
{'label': 'Since 2010', 'value': '2010'},
],
value: year,
setProps
}
)
});
dagfuncs.setBody = () => {
return document.querySelector('body')
}
// cell editor custom component - dmc.Select
dagfuncs.DMC_Select = class {
// gets called once before the renderer is used
init(params) {
// create the cell
this.params = params;
// function for when Dash is trying to send props back to the component / server
var setProps = (props) => {
if (typeof props.value != typeof undefined) {
// updates the value of the editor
this.value = props.value;
// re-enables keyboard event
delete params.colDef.suppressKeyboardEvent;
// tells the grid to stop editing the cell
params.api.stopEditing();
// sets focus back to the grid's previously active cell
this.prevFocus.focus();
}
};
this.eInput = document.createElement('div');
// renders component into the editor element
ReactDOM.render(
React.createElement(window.dash_mantine_components.Select, {
data: params.options,
value: params.value,
setProps,
style: {width: params.column.actualWidth - 2, ...params.style},
className: params.className,
clearable: params.clearable,
searchable: params.searchable || true,
creatable: params.creatable,
debounce: params.debounce,
disabled: params.disabled,
filterDataOnExactSearchMatch:
params.filterDataOnExactSearchMatch,
limit: params.limit,
maxDropdownHeight: params.maxDropdownHeight,
nothingFound: params.nothingFound,
placeholder: params.placeholder,
required: params.required,
searchValue: params.searchValue,
shadow: params.shadow,
size: params.size,
styles: params.styles,
switchDirectionOnFlip: params.switchDirectionOnFlip,
variant: params.variant,
}),
this.eInput
);
// allows focus event
this.eInput.tabIndex = '0';
// sets editor value to the value from the cell
this.value = params.value;
}
// gets called once when grid ready to insert the element
getGui() {
return this.eInput;
}
focusChild() {
// needed to delay and allow the component to render
setTimeout(() => {
var inp = this.eInput.getElementsByClassName(
'mantine-Select-input'
)[0];
inp.tabIndex = '1';
// disables keyboard event
this.params.colDef.suppressKeyboardEvent = (params) => {
const gridShouldDoNothing = params.editing;
return gridShouldDoNothing;
};
// shows dropdown options
inp.focus();
}, 100);
}
// focus and select can be done after the gui is attached
afterGuiAttached() {
// stores the active cell
this.prevFocus = document.activeElement;
// adds event listener to trigger event to go into dash component
this.eInput.addEventListener('focus', this.focusChild());
// triggers focus event
this.eInput.focus();
}
// returns the new value after editing
getValue() {
return this.value;
}
// any cleanup we need to be done here
destroy() {
// sets focus back to the grid's previously active cell
this.prevFocus.focus();
}
};
dagfuncs.contextTest = (params) => {
var result = [
{
// custom item
name: 'Alert ' + params.value,
action: () => {
window.alert('Alerting about ' + params.value);
},
cssClasses: ['redFont', 'bold'],
},
'copy',
'separator',
'chartRange',
];
return result;
};
// FOR test_custom_filter.py
dagfuncs.myTextFormatter = (text) => {
if (text == null) return null;
return text
.toLowerCase()
.replace(/[àáâãäå]/g, 'a')
.replace(/æ/g, 'ae')
.replace(/ç/g, 'c')
.replace(/[èéêë]/g, 'e')
.replace(/[ìíîï]/g, 'i')
.replace(/ñ/g, 'n')
.replace(/[òóôõö]/g, 'o')
.replace(/œ/g, 'oe')
.replace(/[ùúûü]/g, 'u')
.replace(/[ýÿ]/g, 'y');
}
function contains(target, lookingFor) {
return target && target.indexOf(lookingFor) >= 0;
}
dagfuncs.myTextMatcher = ({value, filterText}) => {
const aliases = {
usa: "united states",
holland: "netherlands",
niall: "ireland",
sean: "south africa",
alberto: "mexico",
john: "australia",
xi: "china",
};
const literalMatch = contains(value, filterText || "");
return literalMatch || contains(value, aliases[filterText || ""]);
}
dagfuncs.myNumberParser = (text) => {
return text === null ? null : parseFloat(text.replace(",", ".").replace("$", ""));
}
dagfuncs.myNumberFormatter = (value) => {
return value === null ? null : value.toString().replace(".", ",");
}
dagfuncs.startWith = ([filterValues], cellValue) => {
const name = cellValue ? cellValue.split(" ")[1] : ""
return name && name.toLowerCase().indexOf(filterValues.toLowerCase()) === 0
}
dagfuncs.dateFilterComparator = (filterLocalDateAtMidnight, cellValue) => {
const dateAsString = cellValue;
if (dateAsString == null) {
// Return -1 to show nulls "before" any date
return -1;
}
// The data from this CSV is in dd/mm/yyyy format
const dateParts = dateAsString.split("/");
if (dateParts.length !== 3) {
// Handle invalid format
return 0;
}
const day = Number(dateParts[0]);
const month = Number(dateParts[1]) - 1; // JS months are 0-indexed
const year = Number(dateParts[2]);
const cellDate = new Date(year, month, day);
// Check for invalid date (e.g., from "NaN")
if (isNaN(cellDate.getTime())) {
return 0;
}
// Now that both parameters are Date objects, we can compare
if (cellDate < filterLocalDateAtMidnight) {
return -1;
} else if (cellDate > filterLocalDateAtMidnight) {
return 1;
}
return 0;
};
// END test_custom_filter.py
// FOR test_quick_filter.py
dagfuncs.quickFilterMatcher = (quickFilterParts, rowQuickFilterAggregateText) => {
return quickFilterParts.every(part => rowQuickFilterAggregateText.match(part));
}
// END test_quick_filter.py
// FOR test_cell_data_type_override.py
dagfuncs.dataTypeDefinitions = {
percentage: {
baseDataType: "number",
extendsDataType: "number",
valueFormatter: (params) => params.value == null ? '' : (Math.round(params.value * 1000) / 10).toFixed(1) + '%'
},
dateString: {
baseDataType: 'dateString',
extendsDataType: 'dateString',
valueParser: (params) => {
return params.newValue != null &&
!!params.newValue.match(/\d{2}\/\d{2}\/\d{4}/)
? params.newValue
: null
},
valueFormatter: (params) => {
return params.value == null ? '' : params.value
},
dataTypeMatcher: (value) => {
return typeof value === 'string' && !!value.match(/\d{2}\/\d{2}\/\d{4}/)
},
dateParser: (value) => {
if (value == null || value === '') {
return undefined;
}
const dateParts = value.split('/');
return dateParts.length === 3
? new Date(
parseInt(dateParts[2]),
parseInt(dateParts[1]) - 1,
parseInt(dateParts[0])
)
: undefined;
},
dateFormatter: (value) => {
if (value == null) {
return undefined;
}
const date = String(value.getDate());
const month = String(value.getMonth() + 1);
return `${date.length === 1 ? '0' + date : date}/${
month.length === 1 ? '0' + month : month
}/${value.getFullYear()}`;
},
},
};
dagfuncs.dateParser = (value) => {
if (value == null || value === '') {
return undefined;
}
const dateParts = value.split('/');
return dateParts.length === 3
? new Date(
parseInt(dateParts[2]),
parseInt(dateParts[1]) - 1,
parseInt(dateParts[0])
)
: undefined;
}
dagfuncs.dateFormatter = (value) => {
if (value == null) {
return undefined;
}
const date = String(value.getDate());
const month = String(value.getMonth() + 1);
return `${date.length === 1 ? '0' + date : date}/${
month.length === 1 ? '0' + month : month
}/${value.getFullYear()}`;
}
// END test_cell_data_type_override.py
// BEGIN test_event_listeners.py
dagfuncs.showOutput = (params, setGridProps) => {
const {colId, rowId, rowIndex, value} = params
cellClicked = {colId, rowId, rowIndex, timestamp: Date.now(), value, contextMenu: true}
setGridProps({'cellClicked': cellClicked})
}
// END test_event_listeners.py
// BEGIN test_pivot_column_order.py
dagfuncs.sortColumns = (a, b) => b.localeCompare(a)
// BEGIN test_pivot_column_order.py
dagfuncs.TestEvent = (params, setEventData) => {
console.log(params)
setEventData('here I am')
}
dagfuncs.testToyota = (params) => {
return params.data.make == 'Toyota' ? {'color': 'blue'} : {}
}