forked from SitePen/dgrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Editor.js
969 lines (848 loc) · 30.4 KB
/
Editor.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
define([
'dojo/_base/array',
'dojo/_base/declare',
'dojo/_base/lang',
'dojo/Deferred',
'dojo/dom-construct',
'dojo/dom-class',
'dojo/on',
'dojo/query',
'dojo/sniff',
'./Grid'
], function (arrayUtil, declare, lang, Deferred, domConstruct, domClass, on, query, has, Grid) {
return declare(null, {
editorFocusWrapperClassName: 'dgrid-editor-focus-wrapper',
constructor: function () {
this._editorInstances = {};
// Tracks shared editor dismissal listeners, and editor click/change listeners for old IE
this._editorColumnListeners = [];
// Tracks always-on editor listeners for old IE, or listeners for triggering shared editors
this._editorCellListeners = {};
this._editorsPendingStartup = [];
},
postCreate: function () {
var self = this;
this.inherited(arguments);
this.on('.dgrid-input:focusin', function () {
self._focusedEditorCell = self.cell(this);
});
this._editorFocusoutHandle = on.pausable(this.domNode, '.dgrid-input:focusout', function (event) {
// Widgets can trigger a 'focusout' event when clicking within the widget, since the widget
// is still focused the 'focusout' event should be ignored
if (self._focusedEditorCell && self._focusedEditorCell.element.contains(event.target)) {
return;
}
self._focusedEditorCell = null;
});
this._listeners.push(this._editorFocusoutHandle);
},
insertRow: function () {
this._editorRowListeners = {};
var rowElement = this.inherited(arguments);
var row = this.row(rowElement);
var rowListeners = this._editorCellListeners[rowElement.id] =
this._editorCellListeners[rowElement.id] || {};
for (var key in this._editorRowListeners) {
rowListeners[key] = this._editorRowListeners[key];
}
// Null this out so that _createEditor can tell whether the editor being created is
// an individual cell editor at insertion time, vs. a cell being refreshed
this._editorRowListeners = null;
var previouslyFocusedCell = this._previouslyFocusedEditorCell;
if (previouslyFocusedCell && previouslyFocusedCell.row.id === row.id) {
this.edit(this.cell(row, previouslyFocusedCell.column.id));
this._previouslyFocusedEditorCell = null;
}
return rowElement;
},
refresh: function () {
for (var id in this._editorInstances) {
var editorInstanceDomNode = this._getEditorRootNode(this._editorInstances[id].domNode);
if (editorInstanceDomNode && editorInstanceDomNode.parentNode) {
this._removeEditorBlurHandles();
// Remove any editor widgets from the DOM before List destroys it, to avoid issues in IE (#1100)
editorInstanceDomNode.parentNode.removeChild(editorInstanceDomNode);
}
}
return this.inherited(arguments);
},
removeRow: function (rowElement) {
var self = this;
var focusedCell = this._focusedEditorCell;
var row = this.row(rowElement);
if (focusedCell && row && focusedCell.row.id === row.id) {
this._previouslyFocusedEditorCell = focusedCell;
// Pause the focusout handler until after this row has had
// time to re-render, if this removal is part of an update.
// A setTimeout is used here instead of resuming in insertRow,
// since if a row were actually removed (not updated) while
// editing, the handler would not be properly hooked up again
// for future occurrences.
this._editorFocusoutHandle.pause();
setTimeout(function () {
self._editorFocusoutHandle.resume();
self._previouslyFocusedEditorCell = null;
}, 0);
}
if (this._editorCellListeners[rowElement.id]) {
for (var columnId in this._editorCellListeners[rowElement.id]) {
this._editorCellListeners[rowElement.id][columnId].remove();
}
delete this._editorCellListeners[rowElement.id];
}
for (var i = this._alwaysOnWidgetColumns.length; i--;) {
// Destroy always-on editor widgets during the row removal operation,
// but don't trip over loading nodes from incomplete requests
var cellElement = this.cell(rowElement, this._alwaysOnWidgetColumns[i].id).element,
widget = cellElement && (cellElement.contents || cellElement).widget;
if (widget) {
this._editorFocusoutHandle.pause();
widget.destroyRecursive();
this._editorFocusoutHandle.resume();
}
}
return this.inherited(arguments);
},
renderArray: function () {
var rows = this.inherited(arguments);
if (rows.length) {
// Finish processing any pending editors that are now displayed
this._startupPendingEditors();
}
else {
this._editorsPendingStartup = [];
}
return rows;
},
_onNotification: function () {
this.inherited(arguments);
this._startupPendingEditors();
},
_destroyColumns: function () {
this._editorStructureCleanup();
this.inherited(arguments);
},
_editorStructureCleanup: function () {
var editorInstances = this._editorInstances;
var listeners = this._editorColumnListeners;
if (this._editTimer) {
clearTimeout(this._editTimer);
}
// Do any clean up of previous column structure.
for (var columnId in editorInstances) {
var editor = editorInstances[columnId];
if (editor.domNode) {
// The editor is a widget
editor.destroyRecursive();
}
}
this._editorInstances = {};
for (var i = listeners.length; i--;) {
listeners[i].remove();
}
for (var rowId in this._editorCellListeners) {
for (columnId in this._editorCellListeners[rowId]) {
this._editorCellListeners[rowId][columnId].remove();
}
}
for (i = 0; i < this._editorColumnListeners.length; i++) {
this._editorColumnListeners[i].remove();
}
this._editorCellListeners = {};
this._editorColumnListeners = [];
this._editorsPendingStartup = [];
},
configStructure: function () {
this._alwaysOnWidgetColumns = [];
this.inherited(arguments);
},
_configColumns: function () {
var columnArray = this.inherited(arguments);
for (var i = 0, l = columnArray.length; i < l; i++) {
if (columnArray[i].editor) {
this._configureEditorColumn(columnArray[i]);
}
}
return columnArray;
},
_configureEditorColumn: function (column) {
// summary:
// Adds editing capability to a column's cells.
var editor = column.editor;
var self = this;
var originalRenderCell = column.renderCell || this._defaultRenderCell;
var editOn = column.editOn;
var isWidget = typeof editor !== 'string';
if (editOn) {
// Create one shared widget/input to be swapped into the active cell.
this._editorInstances[column.id] = this._createSharedEditor(column, originalRenderCell);
}
else if (isWidget) {
// Append to array iterated in removeRow
this._alwaysOnWidgetColumns.push(column);
}
column.renderCell = editOn ? function (object, value, cell, options) {
// TODO: Consider using event delegation
// (Would require using dgrid's focus events for activating on focus,
// which we already advocate in docs for optimal use)
if (!options || !options.alreadyHooked) {
var listener = on(cell, editOn, function () {
self._activeOptions = options;
self.edit(this);
});
if (self._editorRowListeners) {
self._editorRowListeners[column.id] = listener;
}
else {
// We're in refreshCell since _editorRowListeners doesn't exist,
// so the row should exist
var row = self.row(object);
self._editorCellListeners[row.element.id][column.id] = listener;
}
}
// initially render content in non-edit mode
return originalRenderCell.call(column, object, value, cell, options);
} : function (object, value, cell, options) {
// always-on: create editor immediately upon rendering each cell
if (!column.canEdit || column.canEdit(object, value)) {
// _createEditor also needs the object for when this is invoked via refreshCell, to get the row
var cmp = self._createEditor(column, object);
self._showEditor(cmp, column, cell, value);
// Maintain reference for later use.
cell[isWidget ? 'widget' : 'input'] = cmp;
}
else {
return originalRenderCell.call(column, object, value, cell, options);
}
};
},
edit: function (cell) {
// summary:
// Shows/focuses the editor for a given grid cell.
// cell: Object
// Cell (or something resolvable by grid.cell) to activate editor on.
// returns:
// If the cell is editable, returns a promise resolving to the editor
// input/widget when the cell editor is focused.
// If the cell is not editable, returns null.
var self = this;
var column;
var cellElement;
var dirty;
var field;
var value;
var cmp;
var dfd;
function showEditor(dfd) {
self._activeCell = cellElement;
self._showEditor(cmp, column, cellElement, value);
// focus / blur-handler-resume logic is surrounded in a setTimeout
// to play nice with Keyboard's dgrid-cellfocusin as an editOn event
self._editTimer = setTimeout(function () {
var focusNode = self._getEditorFocusNode(cmp);
// focus the newly-placed control (supported by form widgets and HTML inputs)
if (focusNode.focus) {
focusNode.focus();
}
// resume blur handler once editor is focused
if (column._editorBlurHandle) {
column._editorBlurHandle.resume();
}
self._editTimer = null;
dfd.resolve(cmp);
}, 0);
}
if (!cell.column) {
cell = this.cell(cell);
}
if (!cell || !cell.element) {
return null;
}
this._previouslyFocusedEditorCell = cell;
column = cell.column;
field = column.field;
cellElement = cell.element.contents || cell.element;
if ((cmp = this._editorInstances[column.id])) {
// Shared editor (editOn used)
if (this._activeCell !== cellElement) {
// Get the cell value
var row = cell.row;
dirty = this.dirty && this.dirty[row.id];
value = (dirty && field in dirty) ? dirty[field] :
column.get ? column.get(row.data) : row.data[field];
// Check to see if the cell can be edited
if (!column.canEdit || column.canEdit(cell.row.data, value)) {
dfd = new Deferred();
// In some browsers, moving a DOM node causes a blur event to fire which in this case,
// is a bad time for the blur handler to run. Blur the input node first.
var focusNode = this._getEditorFocusNode(cmp);
if (focusNode.offsetWidth) {
// The editor is visible. Blur it.
focusNode.blur();
// In IE, the blur does not complete immediately.
// Push showing of the editor to the next turn.
// (dfd will be resolved within showEditor)
setTimeout(function () {
showEditor(dfd);
}, 0);
} else {
showEditor(dfd);
}
return dfd.promise;
}
}
}
else if (column.editor) {
// editor but not shared; always-on
cmp = cellElement.widget || cellElement.input;
if (cmp) {
dfd = new Deferred();
if (cmp.focus) {
cmp.focus();
}
dfd.resolve(cmp);
return dfd.promise;
}
}
return null;
},
refreshCell: function (cell) {
var column = cell.column;
var value = column.get ? column.get(cell.row.data) : cell.row.data[column.field];
var editor;
if (column.editor) {
if (cell.column.editOn && this._activeCell === cell.element) {
editor = this._editorInstances[cell.column.id];
}
else if (!cell.column.editOn) {
editor = cell.element.widget || cell.element.input;
}
}
if (editor) {
if (editor.domNode) {
editor.set('value', value);
}
else {
this._updateInputValue(editor, value);
}
return (new Deferred()).resolve();
}
if (column._editorBlurHandle) {
// _StoreMixin#refreshCell will empty the cell, causing the blur handler to be triggered
// Remove the blur handler to avoid having it called unnecessarily (and throwing an error)
column._editorBlurHandle.remove();
}
return this.inherited(arguments);
},
_showEditor: function (cmp, column, cellElement, value) {
// Places a shared editor into the newly-active cell in the column.
// Also called when rendering an editor in an "always-on" editor column.
var isWidget = cmp.domNode;
// for regular inputs, we can update the value before even showing it
if (!isWidget) {
this._updateInputValue(cmp, value);
}
cellElement.innerHTML = '';
domClass.add(cellElement, 'dgrid-cell-editing');
// If a shared editor is a validation widget, reset it to clear validation state
// (The value will be preserved since it is explicitly set in _startupEditor)
if (isWidget && column.editOn && cmp.validate && cmp.reset) {
cmp.reset();
}
cellElement.appendChild(this._getEditorRootNode(cmp));
if (isWidget && !column.editOn) {
// Queue arguments to be run once editor is in DOM
this._editorsPendingStartup.push([cmp, column, cellElement, value]);
}
else {
this._startupEditor(cmp, column, cellElement, value);
}
},
_startupEditor: function (cmp, column, cellElement, value) {
// summary:
// Handles editor widget startup logic and updates the editor's value.
if (cmp.domNode) {
// For widgets, ensure startup is called before setting value, to maximize compatibility
// with flaky widgets like dijit/form/Select.
if (!cmp._started) {
cmp.startup();
}
// Set value, but ensure it isn't processed as a user-generated change.
// (Clear flag on a timeout to wait for delayed onChange to fire first)
cmp._dgridIgnoreChange = true;
cmp.set('value', value);
setTimeout(function () {
cmp._dgridIgnoreChange = false;
}, 0);
}
// track previous value for short-circuiting or in case we need to revert
cmp._dgridLastValue = value;
// if this is an editor with editOn, also update _activeValue
// (_activeOptions will have been updated previously)
if (this._activeCell) {
this._activeValue = value;
// emit an event immediately prior to placing a shared editor
on.emit(cellElement, 'dgrid-editor-show', {
grid: this,
cell: this.cell(cellElement),
column: column,
editor: cmp,
bubbles: true,
cancelable: false
});
}
},
_startupPendingEditors: function () {
var args = this._editorsPendingStartup;
for (var i = args.length; i--;) {
this._startupEditor.apply(this, args[i]);
}
this._editorsPendingStartup = [];
},
_handleEditorChange: function (evt, column) {
var target = evt.target;
if ('_dgridLastValue' in target && target.className.indexOf('dgrid-input') > -1) {
this._updatePropertyFromEditor(column || this.cell(target).column, target, evt);
}
},
// summary:
// Get the focus node of an editor component. For a wrapped node, the focus node will be the wrapper.
// For a non-wrapped widget, the focus node will be widget.focusNode OR widget.domNode.
// For a non-wrapped input element, the focus node will be the input element
// cmp:
// editor component which can be:
// 1. an HTMLInputElement
// 2. a Dijit widget instance
// returns:
// HTMLElement
_getEditorFocusNode: function (cmp) {
var focusNode = cmp.parentNode || (cmp.domNode && cmp.domNode.parentNode);
if (!focusNode || !domClass.contains(focusNode, this.editorFocusWrapperClassName)) {
focusNode = cmp.focusNode || cmp.domNode || cmp;
}
return focusNode;
},
// summary:
// Get the editor component's root node, which may be the wrapper node
// cmp:
// editor component which can be:
// 1. an HTMLInputElement
// 2. a Dijit widget instance
// returns:
// Wrapper node OR widget.domNode OR HTMLInputElement
_getEditorRootNode: function (cmp) {
if (!cmp) {
return;
}
var rootNode = cmp.parentNode || (cmp.domNode && cmp.domNode.parentNode);
if (!rootNode || !domClass.contains(rootNode, this.editorFocusWrapperClassName)) {
rootNode = cmp.domNode || cmp;
}
return rootNode;
},
// In OS X form controls are not considered focusable elements. Some browsers (Safari, Firefox)
// adopt this decision:
// https://github.com/whatwg/html/issues/4356
// https://bugzilla.mozilla.org/show_bug.cgi?id=1524863
// https://bugs.webkit.org/show_bug.cgi?id=22261
// The resulting implementation is broken - you can call `focus()` on a checkbox and it
// will be focused, but clicking on a checkbox does not focus it. Further, clicking on a focused
// checkbox blurs it. To overcome these challenges checkboxes and radios are wrapped in a div
// that can receive focus (and blur) in a consistent manner.
//
// summary:
// Create a focus wrapper for an editor component
// node:
// the node to wrap, either a plain HTMLInputElement or the root node of a widget (widget.domNode)
// tabIndex:
// [optional] tabIndex value to set on the wrapper node, defaults to the node's tabIndex or -1
// returns:
// HTMLDivElement that has `node` as its only child
_createEditorFocusWrapper: function (node, tabIndex) {
if (isNaN(tabIndex)) {
if (isNaN(node.tabIndex)) {
tabIndex = -1;
}
else {
tabIndex = node.tabIndex;
}
}
var wrapper = domConstruct.create('div', {
className: this.editorFocusWrapperClassName,
tabIndex: tabIndex
});
wrapper.appendChild(node);
return wrapper;
},
_createEditor: function (column, object) {
// Creates an editor instance based on column definition properties,
// and hooks up events.
var editor = column.editor,
editOn = column.editOn,
self = this,
Widget = typeof editor !== 'string' && editor,
args,
cmp,
node,
tagName,
tagArgs = {},
wrapperNode;
args = column.editorArgs || {};
if (typeof args === 'function') {
// `object` is undefined for shared editors, but for always-on
// editors it will be the row data.
args = args.call(this, column, object);
}
if (Widget) {
cmp = new Widget(args);
node = cmp.focusNode || cmp.domNode;
// Add dgrid-input to className to make consistent with HTML inputs.
node.className += ' dgrid-input';
if (has('mac') && column.editOn && /checkbox|radio/i.test(node.type)) {
wrapperNode = this._createEditorFocusWrapper(cmp.domNode, column.tabIndex);
this._listeners.push(
on(wrapperNode, 'blur', function () {
if (!cmp._dgridIgnoreChange) {
self._updatePropertyFromEditor(column, cmp, {type: 'widget'});
}
})
);
}
else if (!editOn) {
// For editOn editors the update is handled in the shared editor's blur handler since
// the 'change' event is delayed by setTimeouts in Dijit and will fire too late.
cmp.on('change', function () {
if (!cmp._dgridIgnoreChange) {
self._updatePropertyFromEditor(column, cmp, {type: 'widget'});
}
});
}
}
else {
// considerations for standard HTML form elements
if (!this._hasInputListener) {
// register one listener at the top level that receives events delegated
this._hasInputListener = true;
this.on('change', function (evt) {
self._handleEditorChange(evt);
});
// also register a focus listener
}
if (editor === 'textarea') {
tagName = 'textarea';
}
else {
tagName = 'input';
tagArgs.type = editor;
}
cmp = node = domConstruct.create(tagName, lang.mixin(tagArgs, {
className: 'dgrid-input',
name: column.field,
tabIndex: isNaN(column.tabIndex) ? -1 : column.tabIndex
}, args));
if (has('mac') && column.editOn && /checkbox|radio/i.test(editor)) {
wrapperNode = this._createEditorFocusWrapper(cmp);
cmp.tabIndex = 0;
cmp.removeAttribute('tabindex');
}
if (has('ie') < 9) {
// IE<9 doesn't fire change events for all the right things,
// and it doesn't bubble.
var listener;
if (editor === 'radio' || editor === 'checkbox') {
// listen for clicks since IE doesn't fire change events properly for checks/radios
listener = on(cmp, 'click', function (evt) {
self._handleEditorChange(evt, column);
});
}
else {
listener = on(cmp, 'change', function (evt) {
self._handleEditorChange(evt, column);
});
}
if (editOn) {
// Shared editor handlers are maintained in _editorColumnListeners, since they're not per-row
this._editorColumnListeners.push(listener);
}
else if (this._editorRowListeners) {
this._editorRowListeners[column.id] = listener;
}
// If editRowListeners doesn't exist and this is an always-on editor,
// then we're here from renderCell via refreshCell, and the row should exist
else {
this._editorCellListeners[this.row(object).element.id][column.id] = listener;
}
}
}
if (column.autoSelect) {
var selectNode = cmp.focusNode || cmp;
if (selectNode.select) {
on(selectNode, 'focus', function () {
// setTimeout is needed for always-on editors on WebKit,
// otherwise selection is reset immediately afterwards
setTimeout(function () {
selectNode.select();
}, 0);
});
}
}
return cmp;
},
_createSharedEditor: function (column) {
// Creates an editor instance with additional considerations for
// shared usage across an entire column (for columns with editOn specified).
var cmp = this._createEditor(column),
self = this,
isWidget = cmp.domNode,
rootNode = this._getEditorRootNode(cmp),
focusNode = this._getEditorFocusNode(cmp),
reset = isWidget ?
function () {
cmp.set('value', cmp._dgridLastValue);
} :
function () {
self._updateInputValue(cmp, cmp._dgridLastValue);
// Update property again in case we need to revert a previous change
self._updatePropertyFromEditor(column, cmp);
};
function blur() {
var element = self._activeCell;
focusNode.blur();
if (typeof self.focus === 'function') {
// Dijit form widgets don't end up dismissed until the next turn,
// so wait before calling focus (otherwise Keyboard will focus the
// input again). IE<9 needs to wait longer, otherwise the cell loses
// focus after we've set it.
setTimeout(function () {
self.focus(element);
}, isWidget && has('ie') < 9 ? 15 : 0);
}
}
function onblur(event) {
var wrapperNode;
// a blur caused by clicking within an editor widget's dropDown (e.g. dijit/form/Select) should be
// ignored, otherwise the cell reverts to the read state when the user opens the dropdown
if (cmp.dropDown && cmp.dropDown.domNode.contains(event.relatedTarget || document.activeElement)) {
return;
}
if (event && event.target) {
wrapperNode = event.target;
wrapperNode = domClass.contains(wrapperNode, self.editorFocusWrapperClassName) && wrapperNode;
// Some browsers on OS X emit a blur event when a focused checkbox is clicked
// Revert the erroneous blur by refocusing the wrapper and exit
// (see notes above on the _createEditorFocusWrapper method)
if (wrapperNode && event.relatedTarget === (cmp.focusNode || cmp)) {
wrapperNode.focus();
return;
}
}
self._updatePropertyFromEditor(column, cmp, {type: 'widget'});
var parentNode = rootNode.parentNode,
options = { alreadyHooked: true },
cell = self.cell(rootNode);
// emit an event immediately prior to removing an editOn editor
on.emit(cell.element, 'dgrid-editor-hide', {
grid: self,
cell: cell,
column: column,
editor: cmp,
bubbles: true,
cancelable: false
});
column._editorBlurHandle.pause();
// Remove the editor from the cell, to be reused later.
parentNode.removeChild(rootNode);
if (cell.row) {
// If the row is still present (i.e. we didn't blur due to removal),
// clear out the rest of the cell's contents, then re-render with new value.
domClass.remove(cell.element, 'dgrid-cell-editing');
domConstruct.empty(parentNode);
Grid.appendIfNode(parentNode, column.renderCell(cell.row.data, self._activeValue, parentNode,
self._activeOptions ? lang.delegate(options, self._activeOptions) : options));
}
// Reset state now that editor is deactivated;
// reset _focusedEditorCell as well since some browsers will not
// trigger the focusout event handler in this case
self._focusedEditorCell = self._activeCell = self._activeValue = self._activeOptions = null;
}
function dismissOnKey(evt) {
// Contains logic for reacting to enter/escape keypresses to save/cancel edits.
// Calls `focusNode.blur()` in cases where field should be dismissed.
var key = evt.keyCode || evt.which;
if (key === 27) {
// Escape: revert + dismiss
reset();
self._activeValue = cmp._dgridLastValue;
blur();
}
else if (key === 13 && column.dismissOnEnter !== false) {
// Enter: dismiss
blur();
}
}
// hook up enter/esc key handling
this._editorColumnListeners.push(on(focusNode, 'keydown', dismissOnKey));
// hook up blur handler, but don't activate until widget is activated
(column._editorBlurHandle = on.pausable(this._getEditorFocusNode(cmp), 'blur', onblur)).pause();
this._editorColumnListeners.push(column._editorBlurHandle);
return cmp;
},
_updatePropertyFromEditor: function (column, cmp, triggerEvent) {
var value,
id,
editedRow;
if (!cmp.isValid || cmp.isValid()) {
value = this._updateProperty((cmp.domNode || cmp).parentNode,
this._activeCell ? this._activeValue : cmp._dgridLastValue,
this._retrieveEditorValue(column, cmp), triggerEvent);
if (this._activeCell) { // for editors with editOn defined
this._activeValue = value;
}
else { // for always-on editors, update _dgridLastValue immediately
cmp._dgridLastValue = value;
}
if (cmp.type === 'radio' && cmp.name && !column.editOn && column.field) {
editedRow = this.row(cmp);
// Update all other rendered radio buttons in the group
query('input[type=radio][name=' + cmp.name + ']', this.contentNode).forEach(function (radioBtn) {
var row = this.row(radioBtn);
// Only update _dgridLastValue and the dirty data if it exists
// and is not already false
if (radioBtn !== cmp && radioBtn._dgridLastValue) {
radioBtn._dgridLastValue = false;
if (this.updateDirty) {
this.updateDirty(row.id, column.field, false);
}
else {
// update store-less grid
row.data[column.field] = false;
}
}
}, this);
// Also update dirty data for rows that are not currently rendered
for (id in this.dirty) {
if (editedRow.id.toString() !== id && this.dirty[id][column.field]) {
this.updateDirty(id, column.field, false);
}
}
}
}
},
_updateProperty: function (cellElement, oldValue, value, triggerEvent) {
// Updates dirty hash and fires dgrid-datachange event for a changed value.
var self = this;
// test whether old and new values are inequal, with coercion (e.g. for Dates)
if ((oldValue && oldValue.valueOf()) !== (value && value.valueOf())) {
var cell = this.cell(cellElement);
var row = cell.row;
var column = cell.column;
// Re-resolve cellElement in case the passed element was nested
cellElement = cell.element;
if (column.field && row) {
var eventObject = {
grid: this,
cell: cell,
oldValue: oldValue,
value: value,
bubbles: true,
cancelable: true
};
if (triggerEvent && triggerEvent.type) {
eventObject.parentType = triggerEvent.type;
}
if (on.emit(cellElement, 'dgrid-datachange', eventObject)) {
if (this.updateDirty) {
// for OnDemandGrid: update dirty data, and save if autoSave is true
this.updateDirty(row.id, column.field, value);
// perform auto-save (if applicable) in next tick to avoid
// unintentional mishaps due to order of handler execution
if (column.autoSave) {
setTimeout(function () {
self._trackError('save');
}, 0);
}
}
else {
// update store-less grid
row.data[column.field] = value;
}
}
else {
// Otherwise keep the value the same
// For the sake of always-on editors, need to manually reset the value
var cmp;
if ((cmp = cellElement.widget)) {
// set _dgridIgnoreChange to prevent an infinite loop in the
// onChange handler and prevent dgrid-datachange from firing
// a second time
cmp._dgridIgnoreChange = true;
cmp.set('value', oldValue);
setTimeout(function () {
cmp._dgridIgnoreChange = false;
}, 0);
}
else if ((cmp = cellElement.input)) {
this._updateInputValue(cmp, oldValue);
}
return oldValue;
}
}
}
return value;
},
_updateInputValue: function (input, value) {
// summary:
// Updates the value of a standard input, updating the
// checked state if applicable.
input.value = value;
if (input.type === 'radio' || input.type === 'checkbox') {
input.checked = input.defaultChecked = !!value;
}
},
_retrieveEditorValue: function (column, cmp) {
// summary:
// Intermediary between _convertEditorValue and
// _updatePropertyFromEditor.
if (typeof cmp.get === 'function') { // widget
return this._convertEditorValue(cmp.get('value'));
}
else { // HTML input
return this._convertEditorValue(
cmp[cmp.type === 'checkbox' || cmp.type === 'radio' ? 'checked' : 'value']);
}
},
_convertEditorValue: function (value, oldValue) {
// summary:
// Contains default logic for translating values from editors;
// tries to preserve type if possible.
if (typeof oldValue === 'number') {
value = isNaN(value) ? value : parseFloat(value);
}
else if (typeof oldValue === 'boolean') {
value = value === 'true' ? true : value === 'false' ? false : value;
}
else if (oldValue instanceof Date) {
var asDate = new Date(value);
value = isNaN(asDate.getTime()) ? value : asDate;
}
return value;
},
_removeEditorBlurHandles: function () {
// summary:
// The blur handler created in _createSharedEditor will remove the editor node from the DOM.
// If other code needs to remove an editor node from the DOM it must first remove the editor's
// blur handle to avoid making a duplicate call to remove the node from the DOM which will
// throw an error.
arrayUtil.forEach(this.subRows, function (subRow) {
if (subRow instanceof Array) {
arrayUtil.forEach(subRow, function (column) {
column._editorBlurHandle && column._editorBlurHandle.remove();
});
}
else {
subRow._editorBlurHandle && subRow._editorBlurHandle.remove();
}
});
}
});
});