-
Notifications
You must be signed in to change notification settings - Fork 727
/
w2grid.js
8799 lines (8515 loc) · 395 KB
/
w2grid.js
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Part of w2ui 2.0 library
* - Dependencies: jQuery, w2utils, w2base, w2toolbar, w2field
*
* == TODO ==
* - problem with .set() and arrays, array get extended too, but should be replaced
* - allow functions in routeData (also add routeData to list/enum)
* - send parsed URL to the event if there is routeData
* - add selectType: 'none' so that no selection can be make but with mouse
* - focus/blur for selectType = cell not display grayed out selection
* - allow enum in inline edit (see https://github.com/vitmalina/w2ui/issues/911#issuecomment-107341193)
* - remote source, but localSort/localSearch
* - promise for request, load, save, etc.
* - onloadmore event (so it will be easy to implement remote data source with local sort)
* - status() - clears on next select, etc. Should not if it is off
*
* == DEMOS To create ==
* - batch for disabled buttons
* - natural sort
*
* == 2.0 changes
* - toolbarInput - deprecated, toolbarSearch stays
* - searchSuggest
* - searchSave, searchSelected, savedSearches, defaultSearches, useLocalStorage, searchFieldTooltip
* - cache, cacheSave
* - onSearchSave, onSearchRemove, onSearchSelect
* - show.searchLogic
* - show.searchSave
* - refreshSearch
* - initAllFields -> searchInitInput
* - textSearch - deprecated in favor of defaultOperator
* - grid.confirm - refactored
* - grid.message - refactored
* - search.type == 'text' can have 'in' and 'not in' operators, then it will switch to enum
* - grid.find(..., displayedOnly)
* - column.render(..., this) - added
* - observeResize for the box
* - remove edit.type == 'select'
* - editDone(...)
* - liveSearch
* - deprecated onUnselect event
* - requestComplete(data, action, callBack, resolve, reject) - new argument list
* - msgAJAXError -> msgHTTPError
* - aded msgServerError
* - deleted grid.method
* - added mouseEnter/mouseLeave
* - grid.show.columnReorder -> grid.reorderRows
* - updagte docs search.label (not search.text)
* - added columnAutoSize - which resizes column based on text in it
* - added grid.replace()
* - grid.compareSelection
* - this.showContextMenu(event, { recid, column, index }) - arguments changed
*/
import { w2base } from './w2base.js'
import { w2ui, w2utils } from './w2utils.js'
import { query } from './query.js'
import { w2toolbar } from './w2toolbar.js'
import { w2menu, w2tooltip } from './w2tooltip.js'
import { w2field } from './w2field.js'
class w2grid extends w2base {
constructor(options) {
super(options.name)
this.name = null
this.box = null // HTML element that hold this element
this.columns = [] // { field, text, size, attr, render, hidden, gridMinWidth, editable }
this.columnGroups = [] // { span: int, text: 'string', main: true/false, style: 'string' }
this.records = [] // { recid: int(required), field1: 'value1', ... fieldN: 'valueN', style: 'string', changes: object }
this.summary = [] // array of summary records, same structure as records array
this.searches = [] // { type, label, field, attr, text, hidden }
this.toolbar = {} // if not empty object; then it is toolbar object
this.ranges = []
this.contextMenu = []
this.searchMap = {} // re-map search fields
this.searchData = []
this.sortMap = {} // re-map sort fields
this.sortData = []
this.savedSearches = []
this.defaultSearches = []
this.total = 0 // server total
this.recid = null // field from records to be used as recid
// internal
this.last = {
field : '', // last search field, e.g. 'all'
label : '', // last search field label, e.g. 'All Fields'
logic : 'AND', // last search logic, e.g. 'AND' or 'OR'
search : '', // last search text
searchIds : [], // last search IDs
selection : { // last selection details
indexes : [],
columns : {}
},
saved_sel : null, // last result of selectionSave()
multi : false, // last multi flag, true when searching for multiple fields
fetch: {
action : '', // last fetch command, e.g. 'load'
offset : null, // last fetch offset, integer
start : 0, // timestamp of start of last fetch request
response : 0, // time it took to complete the last fetch request in seconds
options : null,
controller: null,
loaded : false, // data is loaded from the server
hasMore : false // flag to indicate if there are more items to pull from the server
},
vscroll: {
scrollTop : 0, // last scrollTop position
scrollLeft : 0, // last scrollLeft position
recIndStart : null, // record index for first record in DOM
recIndEnd : null, // record index for last record in DOM
colIndStart : 0, // for column virtual scrolling
colIndEnd : 0, // for column virtual scrolling
pull_more : false,
pull_refresh : true,
show_extra : 0, // last show extra for virtual scrolling
},
sel_ind : null, // last selected cell index
sel_col : null, // last selected column
sel_type : null, // last selection type, e.g. 'click' or 'key'
sel_recid : null, // last selected record id
idCache : {}, // object, id cache for get()
move : null, // object, move details
cancelClick : null, // boolean flag to indicate if the click event should be ignored, set during mouseMove()
inEditMode : false, // flag to indicate if we're currently in edit mode during inline editing
_edit : null, // object with details on the last edited cell, { value, index, column, recid }
kbd_timer : null, // last id of blur() timer
marker_timer : null, // last id of markSearch() timer
click_time : null, // timestamp of last click
click_recid : null, // last clicked record id
bubbleEl : null, // last bubble element
colResizing : false, // flag to indicate that a column is currently being resized
tmp : null, // object with last column resizing details
copy_event : null, // last copy event
userSelect : '', // last user select type, e.g. 'text'
columnDrag : false, // false or an object with a remove() method
state : null, // last grid state
toolbar_height: 0, // height of grid's toolbar
}
this.header = ''
this.url = ''
this.limit = 100
this.offset = 0 // how many records to skip (for infinite scroll) when pulling from server
this.postData = {}
this.routeData = {}
this.httpHeaders = {}
this.show = {
header : false,
toolbar : false,
footer : false,
columnMenu : true,
columnHeaders : true,
lineNumbers : false,
expandColumn : false,
selectColumn : false,
emptyRecords : true,
toolbarReload : true,
toolbarColumns : false,
toolbarSearch : true,
toolbarAdd : false,
toolbarEdit : false,
toolbarDelete : false,
toolbarSave : false,
searchAll : true,
searchLogic : true,
searchHiddenMsg : false,
searchSave : true,
statusRange : true,
statusBuffered : false,
statusRecordID : true,
statusSelection : true,
statusResponse : true,
statusSort : false,
statusSearch : false,
recordTitles : false,
selectionBorder : true,
selectionResizer: true,
skipRecords : true,
saveRestoreState: true
}
this.stateId = null // Custom state name for stateSave, stateRestore and stateReset
this.hasFocus = false
this.autoLoad = true // for infinite scroll
this.fixedBody = true // if false; then grid grows with data
this.recordHeight = 32
this.lineNumberWidth = 34
this.keyboard = true
this.selectType = 'row' // can be row|cell
this.liveSearch = false // if true, it will auto search if typed in search_all
this.multiSearch = true
this.multiSelect = true
this.multiSort = true
this.reorderColumns = false
this.reorderRows = false
this.showExtraOnSearch = 0 // show extra records before and after on search
this.markSearch = true
this.columnTooltip = 'top|bottom' // can be top, bottom, left, right
this.disableCVS = false // disable Column Virtual Scroll
this.nestedFields = true // use field name containing dots as separator to look into object
this.vs_start = 150
this.vs_extra = 5
this.style = ''
this.tabIndex = null
this.dataType = null // if defined, then overwrites w2utils.settings.dataType
this.parser = null
this.advanceOnEdit = true // automatically begin editing the next cell after submitting an inline edit?
this.useLocalStorage = true
// default values for the column
this.colTemplate = {
text : '', // column text (can be a function)
field : '', // field name to map the column to a record
size : null, // size of column in px or %
min : 20, // minimum width of column in px
max : null, // maximum width of column in px
gridMinWidth : null, // minimum width of the grid when column is visible
sizeCorrected : null, // read only, corrected size (see explanation below)
sizeCalculated : null, // read only, size in px (see explanation below)
sizeOriginal : null, // size as defined
sizeType : null, // px or %
hidden : false, // indicates if column is hidden
sortable : false, // indicates if column is sortable
sortMode : null, // sort mode ('default'|'natural'|'i18n') or custom compare function
searchable : false, // bool/string: int,float,date,... or an object to create search field
resizable : true, // indicates if column is resizable
hideable : true, // indicates if column can be hidden
autoResize : null, // indicates if column can be auto-resized by double clicking on the resizer
attr : '', // string that will be inside the <td ... attr> tag
style : '', // additional style for the td tag
render : null, // string or render function
title : null, // string or function for the title property for the column cells
tooltip : null, // string for the title property for the column header
editable : {}, // editable object (see explanation below)
frozen : false, // indicates if the column is fixed to the left
info : null, // info bubble, can be bool/object
clipboardCopy : false, // if true (or string or function), it will display clipboard copy icon
}
// these column properties will be saved in stateSave()
this.stateColProps = {
text : false,
field : true,
size : true,
min : false,
max : false,
gridMinWidth : false,
sizeCorrected : false,
sizeCalculated : true,
sizeOriginal : true,
sizeType : true,
hidden : true,
sortable : false,
sortMode : true,
searchable : false,
resizable : false,
hideable : false,
autoResize : false,
attr : false,
style : false,
render : false,
title : false,
tooltip : false,
editable : false,
frozen : true,
info : false,
clipboardCopy : false
}
this.msgDelete = 'Are you sure you want to delete ${count} ${records}?'
this.msgNotJSON = 'Returned data is not in valid JSON format.'
this.msgHTTPError = 'HTTP error. See console for more details.'
this.msgServerError= 'Server error'
this.msgRefresh = 'Refreshing...'
this.msgNeedReload = 'Your remote data source record count has changed, reloading from the first record.'
this.msgEmpty = '' // if not blank, then it is message when server returns no records
this.buttons = {
'reload' : { type: 'button', id: 'w2ui-reload', icon: 'w2ui-icon-reload', tooltip: w2utils.lang('Reload data in the list') },
'columns' : { type: 'menu-check', id: 'w2ui-column-on-off', icon: 'w2ui-icon-columns', tooltip: w2utils.lang('Show/hide columns'),
overlay: { align: 'none' }
},
'search' : { type: 'html', id: 'w2ui-search',
html: '<div class="w2ui-icon w2ui-icon-search w2ui-search-down w2ui-action" data-click="searchShowFields"></div>'
},
'add' : { type: 'button', id: 'w2ui-add', text: 'Add New', tooltip: w2utils.lang('Add new record'), icon: 'w2ui-icon-plus' },
'edit' : { type: 'button', id: 'w2ui-edit', text: 'Edit', tooltip: w2utils.lang('Edit selected record'), icon: 'w2ui-icon-pencil', batch: 1, disabled: true },
'delete' : { type: 'button', id: 'w2ui-delete', text: 'Delete', tooltip: w2utils.lang('Delete selected records'), icon: 'w2ui-icon-cross', batch: true, disabled: true },
'save' : { type: 'button', id: 'w2ui-save', text: 'Save', tooltip: w2utils.lang('Save changed records'), icon: 'w2ui-icon-check' }
}
this.operators = { // for search fields
'text' : ['is', 'begins', 'contains', 'ends'], // could have "in" and "not in"
'number' : ['=', 'between', '>', '<', '>=', '<='],
'date' : ['is', { oper: 'less', text: 'before'}, { oper: 'more', text: 'since' }, 'between'],
'list' : ['is'],
'hex' : ['is', 'between'],
'color' : ['is', 'begins', 'contains', 'ends'],
'enum' : ['in', 'not in']
// -- all possible
// "text" : ['is', 'begins', 'contains', 'ends'],
// "number" : ['is', 'between', 'less:less than', 'more:more than', 'null:is null', 'not null:is not null'],
// "list" : ['is', 'null:is null', 'not null:is not null'],
// "enum" : ['in', 'not in', 'null:is null', 'not null:is not null']
}
this.defaultOperator = {
'text' : 'begins',
'number' : '=',
'date' : 'is',
'list' : 'is',
'enum' : 'in',
'hex' : 'begins',
'color' : 'begins'
}
// map search field type to operator
this.operatorsMap = {
'text' : 'text',
'int' : 'number',
'float' : 'number',
'money' : 'number',
'currency' : 'number',
'percent' : 'number',
'hex' : 'hex',
'alphanumeric' : 'text',
'color' : 'color',
'date' : 'date',
'time' : 'date',
'datetime' : 'date',
'list' : 'list',
'combo' : 'text',
'enum' : 'enum',
'file' : 'enum',
'select' : 'list',
'radio' : 'list',
'checkbox' : 'list',
'toggle' : 'list'
}
// events
this.onAdd = null
this.onEdit = null
this.onRequest = null // called on any server event
this.onLoad = null
this.onDelete = null
this.onSave = null
this.onSelect = null
this.onClick = null
this.onDblClick = null
this.onContextMenu = null
this.onContextMenuClick = null // when context menu item selected
this.onColumnClick = null
this.onColumnDblClick = null
this.onColumnContextMenu = null
this.onColumnResize = null
this.onColumnAutoResize = null
this.onSort = null
this.onSearch = null
this.onSearchOpen = null
this.onChange = null // called when editable record is changed
this.onRestore = null // called when editable record is restored
this.onExpand = null
this.onCollapse = null
this.onError = null
this.onKeydown = null
this.onToolbar = null // all events from toolbar
this.onColumnOnOff = null
this.onCopy = null
this.onPaste = null
this.onSelectionExtend = null
this.onEditField = null
this.onRender = null
this.onRefresh = null
this.onReload = null
this.onResize = null
this.onDestroy = null
this.onStateSave = null
this.onStateRestore = null
this.onFocus = null
this.onBlur = null
this.onReorderRow = null
this.onSearchSave = null
this.onSearchRemove = null
this.onSearchSelect = null
this.onColumnSelect = null
this.onColumnDragStart = null
this.onColumnDragEnd = null
this.onResizerDblClick = null
this.onMouseEnter = null // mouse enter over record event
this.onMouseLeave = null
// need deep merge, should be extend, not objectAssign
w2utils.extend(this, options)
// check if there are records without recid
if (Array.isArray(this.records)) {
let remove = [] // remove from records as they are summary
this.records.forEach((rec, ind) => {
if (rec[this.recid] != null) {
rec.recid = rec[this.recid]
}
if (rec.recid == null) {
console.log('ERROR: Cannot add records without recid. (obj: '+ this.name +')')
}
if (rec.w2ui?.summary === true) {
this.summary.push(rec)
remove.push(ind) // cannot remove here as it will mess up array walk thru
}
})
remove.sort()
for (let t = remove.length-1; t >= 0; t--) {
this.records.splice(remove[t], 1)
}
}
// add searches
if (Array.isArray(this.columns)) {
this.columns.forEach((col, ind) => {
col = w2utils.extend({}, this.colTemplate, col)
this.columns[ind] = col
let search = col.searchable
if (search == null || search === false || this.getSearch(col.field) != null) return
if (w2utils.isPlainObject(search)) {
this.addSearch(w2utils.extend({ field: col.field, label: col.text, type: 'text' }, search))
} else {
let stype = col.searchable
let attr = ''
if (col.searchable === true) {
stype = 'text'
attr = 'size="20"'
}
this.addSearch({ field: col.field, label: col.text, type: stype, attr: attr })
}
})
}
// add icon to default searches if not defined
if (Array.isArray(this.defaultSearches)) {
this.defaultSearches.forEach((search, ind) => {
search.id = 'default-'+ ind
search.icon ??= 'w2ui-icon-search'
})
}
// check if there are saved searches in localStorage
let data = this.cache('searches')
if (Array.isArray(data)) {
data.forEach(search => {
this.savedSearches.push({
id: search.id ?? 'none',
text: search.text ?? 'none',
icon: 'w2ui-icon-search',
remove: true,
logic: search.logic ?? 'AND',
data: search.data ?? []
})
})
}
// init toolbar
this.initToolbar()
// render if box specified
if (typeof this.box == 'string') this.box = query(this.box).get(0)
if (this.box) this.render(this.box)
}
add(record, first) {
if (!Array.isArray(record)) record = [record]
let added = 0
for (let i = 0; i < record.length; i++) {
let rec = record[i]
if (rec[this.recid] != null) {
rec.recid = rec[this.recid]
}
if (rec.recid == null) {
console.log('ERROR: Cannot add record without recid. (obj: '+ this.name +')')
continue
}
if (rec.w2ui?.summary === true) {
if (first) this.summary.unshift(rec); else this.summary.push(rec)
} else {
if (first) this.records.unshift(rec); else this.records.push(rec)
}
added++
}
let url = this.url?.get ?? this.url
if (!url) {
this.total = this.records.length
this.localSort(false, true)
this.localSearch()
// only refresh if it is in virtual view
let indStart = this.records.length - record.length
let indEnd = indStart + record.length
if (this.last.vscroll.recIndStart <= indEnd && this.last.vscroll.recIndEnd >= indStart) {
this.refresh()
} else {
// just update total if it it there
query(this.box)
.find('#grid_'+ this.name + '_footer .w2ui-footer-right .w2ui-total')
.html(w2utils.formatNumber(this.total))
}
} else {
this.refresh()
}
return added
}
find(obj, returnIndex, displayedOnly) {
if (obj == null) obj = {}
let recs = []
let hasDots = false
// check if property is nested - needed for speed
for (let o in obj) if (String(o).indexOf('.') != -1) hasDots = true
// look for an item
let start = displayedOnly ? this.last.vscroll.recIndStart : 0
let end = displayedOnly ? this.last.vscroll.recIndEnd + 1: this.records.length
if (end > this.records.length) end = this.records.length
for (let i = start; i < end; i++) {
let match = true
for (let o in obj) {
let val = this.records[i][o]
if (hasDots && String(o).indexOf('.') != -1) val = this.parseField(this.records[i], o)
if (obj[o] == 'not-null') {
if (val == null || val === '') match = false
} else {
if (obj[o] != val) match = false
}
}
if (match && returnIndex !== true) recs.push(this.records[i].recid)
if (match && returnIndex === true) recs.push(i)
}
return recs
}
// does not delete existing, but overrides on top of it
set(recid, record, noRefresh) {
if ((typeof recid == 'object') && (recid !== null)) {
noRefresh = record
record = recid
recid = null
}
// update all records
if (recid == null) {
for (let i = 0; i < this.records.length; i++) {
w2utils.extend(this.records[i], record) // recid is the whole record
}
if (noRefresh !== true) this.refresh()
} else { // find record to update
let ind = this.get(recid, true)
if (ind == null) return false
let isSummary = (this.records[ind]?.recid == recid ? false : true)
if (isSummary) {
w2utils.extend(this.summary[ind], record)
} else {
w2utils.extend(this.records[ind], record)
}
if (noRefresh !== true) this.refreshRow(recid, ind) // refresh only that record
}
return true
}
// replaces existing record
replace(recid, record, noRefresh) {
let ind = this.get(recid, true)
if (ind == null) return false
let isSummary = (this.records[ind]?.recid == recid ? false : true)
if (isSummary) {
this.summary[ind] = record
} else {
this.records[ind] = record
}
if (noRefresh !== true) this.refreshRow(recid, ind) // refresh only that record
return true
}
get(recid, returnIndex) {
// search records
if (Array.isArray(recid)) {
let recs = []
for (let i = 0; i < recid.length; i++) {
let v = this.get(recid[i], returnIndex)
if (v !== null)
recs.push(v)
}
return recs
} else {
// get() must be fast, implements a cache to bypass loop over all records
// most of the time.
let idCache = this.last.idCache
if (!idCache) {
this.last.idCache = idCache = {}
}
let i = idCache[recid]
if (typeof(i) === 'number') {
if (i >= 0 && i < this.records.length && this.records[i].recid == recid) {
if (returnIndex === true) return i; else return this.records[i]
}
// summary indexes are stored as negative numbers, try them now.
i = ~i
if (i >= 0 && i < this.summary.length && this.summary[i].recid == recid) {
if (returnIndex === true) return i; else return this.summary[i]
}
// wrong index returned, clear cache
this.last.idCache = idCache = {}
}
for (let i = 0; i < this.records.length; i++) {
if (this.records[i].recid == recid) {
idCache[recid] = i
if (returnIndex === true) return i; else return this.records[i]
}
}
// search summary
for (let i = 0; i < this.summary.length; i++) {
if (this.summary[i].recid == recid) {
idCache[recid] = ~i
if (returnIndex === true) return i; else return this.summary[i]
}
}
return null
}
}
getFirst(offset) {
if (this.records.length == 0) return null
let rec = this.records[0]
let tmp = this.last.searchIds
if (this.searchData.length > 0) {
if (Array.isArray(tmp) && tmp.length > 0) {
rec = this.records[tmp[offset || 0]]
} else {
rec = null
}
}
return rec
}
remove() {
let removed = 0
for (let a = 0; a < arguments.length; a++) {
for (let r = this.records.length-1; r >= 0; r--) {
if (this.records[r].recid == arguments[a]) { this.records.splice(r, 1); removed++ }
}
for (let r = this.summary.length-1; r >= 0; r--) {
if (this.summary[r].recid == arguments[a]) { this.summary.splice(r, 1); removed++ }
}
}
let url = this.url?.get ?? this.url
if (!url) {
this.localSort(false, true)
this.localSearch()
this.total = this.records.length
}
this.refresh()
return removed
}
addColumn(before, columns) {
let added = 0
if (arguments.length == 1) {
columns = before
before = this.columns.length
} else {
if (typeof before == 'string') before = this.getColumn(before, true)
if (before == null) before = this.columns.length
}
if (!Array.isArray(columns)) columns = [columns]
for (let i = 0; i < columns.length; i++) {
let col = w2utils.extend({}, this.colTemplate, columns[i])
this.columns.splice(before, 0, col)
// if column is searchable, add search field
if (columns[i].searchable) {
let stype = columns[i].searchable
let attr = ''
if (columns[i].searchable === true) { stype = 'text'; attr = 'size="20"' }
this.addSearch({ field: columns[i].field, label: columns[i].text, type: stype, attr: attr })
}
before++
added++
}
this.refresh()
return added
}
removeColumn() {
let removed = 0
for (let a = 0; a < arguments.length; a++) {
for (let r = this.columns.length-1; r >= 0; r--) {
if (this.columns[r].field == arguments[a]) {
if (this.columns[r].searchable) this.removeSearch(arguments[a])
this.columns.splice(r, 1)
removed++
}
}
}
this.refresh()
return removed
}
getColumn(field, returnIndex) {
// no arguments - return fields of all columns
if (arguments.length === 0) {
let ret = []
for (let i = 0; i < this.columns.length; i++) ret.push(this.columns[i].field)
return ret
}
// find column
for (let i = 0; i < this.columns.length; i++) {
if (this.columns[i].field == field) {
if (returnIndex === true) return i; else return this.columns[i]
}
}
return null
}
updateColumn(fields, updates) {
let effected = 0
fields = (Array.isArray(fields) ? fields : [fields])
fields.forEach((colName) => {
this.columns.forEach((col) => {
if (col.field == colName) {
let _updates = w2utils.clone(updates)
Object.keys(_updates).forEach((key) => {
// if it is a function
if (typeof _updates[key] == 'function') {
_updates[key] = _updates[key](col)
}
if (col[key] != _updates[key]) effected++
})
w2utils.extend(col, _updates)
}
})
})
if (effected > 0) {
this.refresh() // need full refresh due to colgroups not reassigning properly
}
return effected
}
toggleColumn() {
return this.updateColumn(Array.from(arguments), { hidden(col) { return !col.hidden } })
}
showColumn() {
return this.updateColumn(Array.from(arguments), { hidden: false })
}
hideColumn() {
return this.updateColumn(Array.from(arguments), { hidden: true })
}
addSearch(before, search) {
let added = 0
if (arguments.length == 1) {
search = before
before = this.searches.length
} else {
if (typeof before == 'string') before = this.getSearch(before, true)
if (before == null) before = this.searches.length
}
if (!Array.isArray(search)) search = [search]
for (let i = 0; i < search.length; i++) {
this.searches.splice(before, 0, search[i])
before++
added++
}
this.searchClose()
return added
}
removeSearch() {
let removed = 0
for (let a = 0; a < arguments.length; a++) {
for (let r = this.searches.length-1; r >= 0; r--) {
if (this.searches[r].field == arguments[a]) { this.searches.splice(r, 1); removed++ }
}
}
this.searchClose()
return removed
}
getSearch(field, returnIndex) {
// no arguments - return fields of all searches
if (arguments.length === 0) {
let ret = []
for (let i = 0; i < this.searches.length; i++) ret.push(this.searches[i].field)
return ret
}
// find search
for (let i = 0; i < this.searches.length; i++) {
if (this.searches[i].field == field) {
if (returnIndex === true) return i; else return this.searches[i]
}
}
return null
}
toggleSearch() {
let effected = 0
for (let a = 0; a < arguments.length; a++) {
for (let r = this.searches.length-1; r >= 0; r--) {
if (this.searches[r].field == arguments[a]) {
this.searches[r].hidden = !this.searches[r].hidden
effected++
}
}
}
this.searchClose()
return effected
}
showSearch() {
let shown = 0
for (let a = 0; a < arguments.length; a++) {
for (let r = this.searches.length-1; r >= 0; r--) {
if (this.searches[r].field == arguments[a] && this.searches[r].hidden !== false) {
this.searches[r].hidden = false
shown++
}
}
}
this.searchClose()
return shown
}
hideSearch() {
let hidden = 0
for (let a = 0; a < arguments.length; a++) {
for (let r = this.searches.length-1; r >= 0; r--) {
if (this.searches[r].field == arguments[a] && this.searches[r].hidden !== true) {
this.searches[r].hidden = true
hidden++
}
}
}
this.searchClose()
return hidden
}
getSearchData(field) {
for (let i = 0; i < this.searchData.length; i++) {
if (this.searchData[i].field == field) return this.searchData[i]
}
return null
}
localSort(silent, noResetRefresh) {
let obj = this
let url = this.url?.get ?? this.url
if (url) {
console.log('ERROR: grid.localSort can only be used on local data source, grid.url should be empty.')
return 0 // time it took
}
if (Object.keys(this.sortData).length === 0) {
// restore original sorting
let os = this.last.originalSort
if (os) {
this.records.sort((a, b) => {
let aInd = os.indexOf(a.recid)
let bInd = os.indexOf(b.recid)
// order cann be equal, so, no need to return 0
return aInd > bInd ? 1 : -1
})
}
return 0 // time it took
}
let time = Date.now()
// process date fields
this.selectionSave()
this.prepareData()
if (!noResetRefresh) {
this.reset()
}
// process sortData
for (let i = 0; i < this.sortData.length; i++) {
let column = this.getColumn(this.sortData[i].field)
if (!column) return // TODO: ability to sort columns when they are not part of colums array
if (typeof column.render == 'string') {
if (['date', 'age'].indexOf(column.render.split(':')[0]) != -1) {
this.sortData[i].field_ = column.field + '_'
}
if (['time'].indexOf(column.render.split(':')[0]) != -1) {
this.sortData[i].field_ = column.field + '_'
}
}
}
// prepare paths and process sort
preparePaths()
this.records.sort((a, b) => {
return compareRecordPaths(a, b)
})
cleanupPaths()
this.selectionRestore(noResetRefresh)
time = Date.now() - time
if (silent !== true && this.show.statusSort) {
setTimeout(() => {
this.status(w2utils.lang('Sorting took ${count} seconds', { count: time/1000 }))
}, 10)
}
return time
// grab paths before sorting for efficiency and because calling obj.get()
// while sorting 'obj.records' is unsafe, at least on webkit
function preparePaths() {
for (let i = 0; i < obj.records.length; i++) {
let rec = obj.records[i]
if (rec.w2ui?.parent_recid != null) {
rec.w2ui._path = getRecordPath(rec)
}
}
}
// cleanup and release memory allocated by preparePaths()
function cleanupPaths() {
for (let i = 0; i < obj.records.length; i++) {
let rec = obj.records[i]
if (rec.w2ui?.parent_recid != null) {
rec.w2ui._path = null
}
}
}
// compare two paths, from root of tree to given records
function compareRecordPaths(a, b) {
if ((!a.w2ui || a.w2ui.parent_recid == null) && (!b.w2ui || b.w2ui.parent_recid == null)) {
return compareRecords(a, b) // no tree, fast path
}
let pa = getRecordPath(a)
let pb = getRecordPath(b)
for (let i = 0; i < Math.min(pa.length, pb.length); i++) {
let diff = compareRecords(pa[i], pb[i])
if (diff !== 0) return diff // different subpath
}
if (pa.length > pb.length) return 1
if (pa.length < pb.length) return -1
console.log('ERROR: two paths should not be equal.')
return 0
}
// return an array of all records from root to and including 'rec'
function getRecordPath(rec) {
if (!rec.w2ui || rec.w2ui.parent_recid == null) return [rec]
if (rec.w2ui._path)
return rec.w2ui._path
// during actual sort, we should never reach this point
let subrec = obj.get(rec.w2ui.parent_recid)
if (!subrec) {
console.log('ERROR: no parent record: ' + rec.w2ui.parent_recid)
return [rec]
}
return (getRecordPath(subrec).concat(rec))
}
// compare two records according to sortData and finally recid
function compareRecords(a, b) {
if (a === b) return 0 // optimize, same object
for (let i = 0; i < obj.sortData.length; i++) {
let fld = obj.sortData[i].field
let sortFld = (obj.sortData[i].field_) ? obj.sortData[i].field_ : fld
let aa = a[sortFld]
let bb = b[sortFld]
if (String(fld).indexOf('.') != -1) {
aa = obj.parseField(a, sortFld)
bb = obj.parseField(b, sortFld)
}
let col = obj.getColumn(fld)
if (col && Object.keys(col.editable).length > 0) { // for drop editable fields and drop downs
if (w2utils.isPlainObject(aa) && aa.text) aa = aa.text
if (w2utils.isPlainObject(bb) && bb.text) bb = bb.text
}
let ret = compareCells(aa, bb, i, obj.sortData[i].direction, col.sortMode || 'default')
if (ret !== 0) return ret
}
// break tie for similar records,
// required to have consistent ordering for tree paths
let ret = compareCells(a.recid, b.recid, -1, 'asc')
return ret
}
// compare two values, aa and bb, producing consistent ordering
function compareCells(aa, bb, i, direction, sortMode) {
// if both objects are strictly equal, we're done
if (aa === bb)
return 0
// all nulls, empty and undefined on bottom
if ((aa == null || aa === '') && (bb != null && bb !== ''))
return 1
if ((aa != null && aa !== '') && (bb == null || bb === ''))
return -1
let dir = (direction.toLowerCase() === 'asc') ? 1 : -1
// for different kind of objects, sort by object type
if (typeof aa != typeof bb)
return (typeof aa > typeof bb) ? dir : -dir
// for different kind of classes, sort by classes
if (aa.constructor.name != bb.constructor.name)
return (aa.constructor.name > bb.constructor.name) ? dir : -dir
// if we're dealing with non-null objects, call valueOf().
// this mean that Date() or custom objects will compare properly.
if (aa && typeof aa == 'object')
aa = aa.valueOf()
if (bb && typeof bb == 'object')
bb = bb.valueOf()
// if we're still dealing with non-null objects that have
// a useful Object => String conversion, convert to string.