var CustomGridEditor = /** @class */ (function () {
    /**
     * Initializes a new instance of a CustomGridEditor.
     *
     * @param col Column that will be edited with the custom editor.
     * @param edt HTMLElement that hosts the custom editor.
     */
    function CustomGridEditor(col, edt) {
        var _this = this;
        // save references
        this._grid = col.grid;
        this._col = col;
        this._edt = edt;
        this._ctl = wijmo.Control.getControl(edt);
        // sanity
        wijmo.assert(this._col != null, 'invalid column');
        wijmo.assert(this._edt != null, 'invalid editor element');
        wijmo.assert(this._ctl != null, 'editor element doesn\'t have a control');
        // initialize input event dispatcher
        this._evtInput = document.createEvent('HTMLEvents');
        this._evtInput.initEvent('input', true, false);
        // optional: increase row height a little to give editors more room
        //this._grid.rows.defaultSize = 32;
        // remove editor from DOM
        this._edt.parentElement.removeChild(this._edt);
        // connect grid events
        var flex = this._grid;
        flex.beginningEdit.addHandler(this._beginningEdit, this);
        flex.sortingColumn.addHandler(function () {
            var ecv = _this._grid.editableCollectionView;
            if (ecv) {
                ecv.commitEdit();
            }
        });
        flex.scrollPositionChanged.addHandler(this._closeEditor, this);
        // connect editor events
        this._edt.addEventListener('keydown', function (e) {
            switch (e.keyCode) {
                case wijmo.Key.Tab:
                case wijmo.Key.Enter:
                    e.preventDefault(); // TFS 255685
                    _this._closeEditor(true);
                    _this._grid.focus();
                    // forward event to the grid so it will move the selection
                    var evt = document.createEvent('HTMLEvents');
                    evt.initEvent('keydown', true, true);
                    evt['ctrlKey'] = e.ctrlKey;
                    evt['shiftKey'] = e.shiftKey;
                    evt['keyCode'] = e.keyCode;
                    _this._grid.hostElement.dispatchEvent(evt);
                    break;
                case wijmo.Key.Escape:
                    _this._closeEditor(false);
                    _this._grid.focus();
                    break;
            }
        });
        // close the editor when it loses focus
        this._ctl.lostFocus.addHandler(function () {
            setTimeout(function () {
                if (!_this._ctl.containsFocus()) {
                    _this._closeEditor(true); // apply edits and close editor
                    _this._grid.onLostFocus(); // commit item edits if the grid lost focus
                }
            });
        });
        // commit edits when grid loses focus (TFS 261311)
        this._grid.lostFocus.addHandler(function () {
            setTimeout(function () {
                if (!_this._grid.containsFocus() && !CustomGridEditor._isEditing) {
                    var ecv = _this._grid.editableCollectionView;
                    if (ecv) {
                        ecv.commitEdit();
                    }
                }
            });
        });
        // keep track of key that initiated the editing process, open drop-down on f4/alt-down
        this._grid.addEventListener(this._grid.hostElement, 'keydown', function (e) {
            // clear keypress buffer
            _this._key = null;
            // start editing and open drop-down on F4/alt+up/down
            _this._openDropDown = false;
            if (e.keyCode == wijmo.Key.F4 ||
                (e.altKey && (e.keyCode == wijmo.Key.Down || e.keyCode == wijmo.Key.Up))) {
                _this._openDropDown = true;
                _this._grid.startEditing(true);
                e.preventDefault();
            }
            // commit edits on Enter (in case we're at the last row, TFS 268944)
            if (e.keyCode == wijmo.Key.Enter) {
                var ecv = _this._grid.editableCollectionView;
                if (ecv && ecv.currentEditItem) {
                    ecv.commitEdit();
                }
            }
        }, true);
        this._grid.addEventListener(this._grid.hostElement, 'keypress', function (e) {
            _this._key = e.charCode > 32 ? String.fromCharCode(e.charCode) : null;
        }, true);
        this._grid.addEventListener(this._edt, 'keypress', function (e) {
            if (_this._key && e.charCode > 32) {
                _this._key += String.fromCharCode(e.charCode);
            }
        }, true);
        // close editor when user resizes the window
        // REVIEW: not needed, hides editor when soft keyboard pops up
        //window.addEventListener('resize', () => {
        //    if (this._containsFocus(this._edt)) {
        //        this._closeEditor(true);
        //        this._grid.focus();
        //    }
        //});
    }
    // handle the grid's beginningEdit event by canceling the built-in editor,
    // initializing the custom editor and giving it the focus.
    CustomGridEditor.prototype._beginningEdit = function (grid, args) {
        var _this = this;
        // check that this is not the Delete key 
        // (which is used to clear cells and should not be messed with)
        var evt = args.data;
        if (evt && evt.keyCode == wijmo.Key.Delete) {
            return;
        }
        // check that we really want to edit and that this is our column
        if (!args.cancel && grid.columns[args.col] == this._col) {
            // cancel built-in editor
            args.cancel = true;
            // save cell being edited
            this._rng = args.range;
            CustomGridEditor._isEditing = true;
            // initialize editor host
            var rcCell = grid.getCellBoundingRect(args.row, args.col), rcBody = document.body.getBoundingClientRect(), ptOffset = new wijmo.Point(-rcBody.left, -rcBody.top), zIndex = (args.row < grid.frozenRows || args.col < grid.frozenColumns) ? '3' : '';
            wijmo.setCss(this._edt, {
                position: 'absolute',
                left: rcCell.left - 1 + ptOffset.x,
                top: rcCell.top - 1 + ptOffset.y,
                width: rcCell.width + 1,
                height: grid.rows[args.row].renderHeight + 1,
                borderRadius: '0px',
                zIndex: zIndex // TFS 291852
            });
            // initialize editor content
            if (this._ctl != null) {
                if (!wijmo.isUndefined(this._ctl['checkedItems'])) {
                    var items = grid.getCellData(this._rng.row, this._rng.col, false);
                    this._ctl['checkedItems'] = items ? items : [];
                }
                else if (!wijmo.isUndefined(this._ctl['value'])) {
                    this._ctl['value'] = grid.getCellData(this._rng.row, this._rng.col, false);
                }
                else if (!wijmo.isUndefined(this._ctl['text'])) {
                    this._ctl['text'] = ''; // initialize AutoComplete (TFS 285936)
                    this._ctl['text'] = grid.getCellData(this._rng.row, this._rng.col, true);
                }
                else {
                    throw 'Can\'t set editor value/text...';
                }
            }
            // start editing item
            var ecv = this._grid.editableCollectionView, item = grid.rows[args.row].dataItem;
            if (ecv && item) {
                setTimeout(function () {
                    if (_this._edt.parentElement) {
                        ecv.editItem(item); // start editing item
                    }
                }, 50); // wait for the grid to commit edits after losing focus
            }
            // activate editor
            document.body.appendChild(this._edt);
            this._ctl.focus();
            setTimeout(function () {
                // apply the last key pressed to the editor
                var input = _this._edt.querySelector('input');
                if (_this._key) {
                    if (input) {
                        if (input.readOnly) {
                            _this._openDropDown = true;
                        }
                        else {
                            input.value = _this._key;
                            wijmo.setSelectionRange(input, _this._key.length, _this._key.length);
                            input.dispatchEvent(_this._evtInput);
                        }
                    }
                }
                else if (input) {
                    input.focus();
                    input.select();
                }
                _this._key = null;
                // open drop-down on F4/alt-down
                if (_this._openDropDown && _this._ctl instanceof wijmo.input.DropDown) {
                    _this._ctl.isDroppedDown = true;
                    _this._ctl.dropDown.focus();
                }
            }, 50);
        }
    };
    // close the custom editor, optionally saving the edits back to the grid
    CustomGridEditor.prototype._closeEditor = function (saveEdits) {
        // check that the editor is active
        var parent = this._edt.parentElement, grid = this._grid, edt = wijmo.Control.getControl(this._edt);
        if (parent) {
            // raise grid's cellEditEnding event
            var e = new wijmo.grid.CellEditEndingEventArgs(grid.cells, this._rng);
            grid.onCellEditEnding(e);
            // save editor value into grid
            if (saveEdits && !e.cancel) {
                if (edt != null) {
                    if (!wijmo.isUndefined(edt['checkedItems'])) {
                        var items = edt['checkedItems'];
                        grid.setCellData(this._rng.row, this._rng.col, items.length ? items.splice(0) : null);
                    }
                    else if (!wijmo.isUndefined(edt['value'])) {
                        grid.setCellData(this._rng.row, this._rng.col, edt['value']);
                    }
                    else if (!wijmo.isUndefined(edt['text'])) {
                        grid.setCellData(this._rng.row, this._rng.col, edt['text']);
                    }
                    else {
                        throw 'Can\'t get editor value/text...';
                    }
                    grid.invalidate();
                }
            }
            // close editor and remove it from the DOM
            if (edt instanceof wijmo.input.DropDown) {
                edt.isDroppedDown = false;
            }
            parent.removeChild(this._edt);
            this._rng = null;
            CustomGridEditor._isEditing = false;
            // raise grid's cellEditEnded event
            grid.onCellEditEnded(e);
        }
    };
    // checks whether an element contains the focus
    CustomGridEditor.prototype._containsFocus = function (element) {
        var control = wijmo.Control.getControl(element);
        return control
            ? control.containsFocus() // controls may have popups...
            : wijmo.contains(element, document.activeElement);
    };
    return CustomGridEditor;
}());
//# sourceMappingURL=CustomGridEditor.js.map