1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 * Create advanced table (resize, reorder, and show/hide columns; and also grid editing).
4 * This function is designed mainly for table DOM generated from browsing a table in the database.
5 * For using this function in other table DOM, you may need to:
6 * - add "draggable" class in the table header <th>, in order to make it resizable, sortable or hidable
7 * - have at least one non-"draggable" header in the table DOM for placing column visibility drop-down arrow
8 * - pass the value "false" for the parameter "enableGridEdit"
9 * - adjust other parameter value, to select which features that will be enabled
11 * @param t the table DOM element
12 * @param enableResize Optional, if false, column resizing feature will be disabled
13 * @param enableReorder Optional, if false, column reordering feature will be disabled
14 * @param enableVisib Optional, if false, show/hide column feature will be disabled
15 * @param enableGridEdit Optional, if false, grid editing feature will be disabled
17 function PMA_makegrid (t, enableResize, enableReorder, enableVisib, enableGridEdit) {
26 * Variables, assigned with default value, changed later
28 actionSpan: 5, // number of colspan in Actions header in a table
29 tableCreateTime: null, // table creation time, used for saving column order and visibility to server, only available in "Browse tab"
31 // Column reordering variables
32 colOrder: [], // array of column order
34 // Column visibility variables
35 colVisib: [], // array of column visibility
36 showAllColText: '', // string, text for "show all" button under column visibility list
37 visibleHeadersCount: 0, // number of visible data headers
39 // Table hint variables
40 reorderHint: '', // string, hint for column reordering
41 sortHint: '', // string, hint for column sorting
42 markHint: '', // string, hint for column marking
43 copyHint: '', // string, hint for copy column name
44 showReorderHint: false,
49 isCellEditActive: false, // true if current focus is in edit cell
50 isEditCellTextEditable: false, // true if current edit cell is editable in the text input box (not textarea)
51 currentEditCell: null, // reference to <td> that currently being edited
52 cellEditHint: '', // hint shown when doing grid edit
53 gotoLinkText: '', // "Go to link" text
54 wasEditedCellNull: false, // true if last value of the edited cell was NULL
55 maxTruncatedLen: 0, // number of characters that can be displayed in a cell
56 saveCellsAtOnce: false, // $cfg[saveCellsAtOnce]
57 isCellEdited: false, // true if at least one cell has been edited
58 saveCellWarning: '', // string, warning text when user want to leave a page with unsaved edited data
59 lastXHR : null, // last XHR object used in AJAX request
60 isSaving: false, // true when currently saving edited data, used to handle double posting caused by pressing ENTER in grid edit text box in Chrome browser
61 alertNonUnique: '', // string, alert shown when saving edited nonunique table
63 // Common hidden inputs
75 * Start to resize column. Called when clicking on column separator.
78 * @param obj dragged div object
80 dragStartRsz: function (e, obj) {
81 var n = $(g.cRsz).find('div').index(obj); // get the index of separator (i.e., column index)
82 $(obj).addClass('colborder_active');
87 objLeft: $(obj).position().left,
88 objWidth: $(g.t).find('th.draggable:visible:eq(' + n + ') span').outerWidth()
90 $(document.body).css('cursor', 'col-resize').noSelect();
91 if (g.isCellEditActive) {
97 * Start to reorder column. Called when clicking on table header.
100 * @param obj table header object
102 dragStartReorder: function (e, obj) {
103 // prepare the cCpy (column copy) and cPointer (column pointer) from the dragged column
104 $(g.cCpy).text($(obj).text());
105 var objPos = $(obj).position();
107 top: objPos.top + 20,
109 height: $(obj).height(),
110 width: $(obj).width()
116 // get the column index, zero-based
117 var n = g.getHeaderIdx(obj);
129 $(document.body).css('cursor', 'move').noSelect();
130 if (g.isCellEditActive) {
136 * Handle mousemove event when dragging.
140 dragMove: function (e) {
142 var dx = e.pageX - g.colRsz.x0;
143 if (g.colRsz.objWidth + dx > g.minColWidth) {
144 $(g.colRsz.obj).css('left', g.colRsz.objLeft + dx + 'px');
146 } else if (g.colReorder) {
147 // dragged column animation
148 var dx = e.pageX - g.colReorder.x0;
150 .css('left', g.colReorder.objLeft + dx)
154 var hoveredCol = g.getHoveredCol(e);
156 var newn = g.getHeaderIdx(hoveredCol);
157 g.colReorder.newn = newn;
158 if (newn !== g.colReorder.n) {
159 // show the column pointer in the right place
160 var colPos = $(hoveredCol).position();
161 var newleft = newn < g.colReorder.n ?
163 colPos.left + $(hoveredCol).outerWidth();
167 visibility: 'visible'
170 // no movement to other column, hide the column pointer
171 $(g.cPointer).css('visibility', 'hidden');
178 * Stop the dragging action.
182 dragEnd: function (e) {
184 var dx = e.pageX - g.colRsz.x0;
185 var nw = g.colRsz.objWidth + dx;
186 if (nw < g.minColWidth) {
196 $(g.cRsz).find('div').removeClass('colborder_active');
197 rearrangeStickyColumns($(t).prev('.sticky_columns'), $(t));
198 } else if (g.colReorder) {
200 if (g.colReorder.newn !== g.colReorder.n) {
201 g.shiftCol(g.colReorder.n, g.colReorder.newn);
202 // assign new position
203 var objPos = $(g.colReorder.obj).position();
204 g.colReorder.objTop = objPos.top;
205 g.colReorder.objLeft = objPos.left;
206 g.colReorder.n = g.colReorder.newn;
207 // send request to server to remember the column order
208 if (g.tableCreateTime) {
211 g.refreshRestoreButton();
214 // animate new column position
215 $(g.cCpy).stop(true, true)
217 top: g.colReorder.objTop,
218 left: g.colReorder.objLeft
221 $(g.cPointer).css('visibility', 'hidden');
223 g.colReorder = false;
224 rearrangeStickyColumns($(t).prev('.sticky_columns'), $(t));
226 $(document.body).css('cursor', 'inherit').noSelect(false);
230 * Resize column n to new width "nw"
232 * @param n zero-based column index
233 * @param nw new width of the column in pixel
235 resize: function (n, nw) {
236 $(g.t).find('tr').each(function () {
237 $(this).find('th.draggable:visible:eq(' + n + ') span,' +
238 'td:visible:eq(' + (g.actionSpan + n) + ') span')
244 * Reposition column resize bars.
246 reposRsz: function () {
247 $(g.cRsz).find('div').hide();
248 var $firstRowCols = $(g.t).find('tr:first th.draggable:visible');
249 var $resizeHandles = $(g.cRsz).find('div').removeClass('condition');
250 $(g.t).find('table.pma_table').find('thead th:first').removeClass('before-condition');
251 for (var n = 0, l = $firstRowCols.length; n < l; n++) {
252 var $col = $($firstRowCols[n]);
254 if (navigator.userAgent.toLowerCase().indexOf('safari') !== -1) {
255 colWidth = $col.outerWidth();
257 colWidth = $col.outerWidth(true);
259 $($resizeHandles[n]).css('left', $col.position().left + colWidth)
261 if ($col.hasClass('condition')) {
262 $($resizeHandles[n]).addClass('condition');
264 $($resizeHandles[n - 1]).addClass('condition');
268 if ($($resizeHandles[0]).hasClass('condition')) {
269 $(g.t).find('thead th:first').addClass('before-condition');
271 $(g.cRsz).css('height', $(g.t).height());
275 * Shift column from index oldn to newn.
277 * @param oldn old zero-based column index
278 * @param newn new zero-based column index
280 shiftCol: function (oldn, newn) {
281 $(g.t).find('tr').each(function () {
283 $(this).find('th.draggable:eq(' + newn + '),' +
284 'td:eq(' + (g.actionSpan + newn) + ')')
285 .before($(this).find('th.draggable:eq(' + oldn + '),' +
286 'td:eq(' + (g.actionSpan + oldn) + ')'));
288 $(this).find('th.draggable:eq(' + newn + '),' +
289 'td:eq(' + (g.actionSpan + newn) + ')')
290 .after($(this).find('th.draggable:eq(' + oldn + '),' +
291 'td:eq(' + (g.actionSpan + oldn) + ')'));
294 // reposition the column resize bars
297 // adjust the column visibility list
299 $(g.cList).find('.lDiv div:eq(' + newn + ')')
300 .before($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
302 $(g.cList).find('.lDiv div:eq(' + newn + ')')
303 .after($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
305 // adjust the colOrder
306 var tmp = g.colOrder[oldn];
307 g.colOrder.splice(oldn, 1);
308 g.colOrder.splice(newn, 0, tmp);
309 // adjust the colVisib
310 if (g.colVisib.length > 0) {
311 tmp = g.colVisib[oldn];
312 g.colVisib.splice(oldn, 1);
313 g.colVisib.splice(newn, 0, tmp);
318 * Find currently hovered table column's header (excluding actions column).
321 * @return the hovered column's th object or undefined if no hovered column found.
323 getHoveredCol: function (e) {
325 $headers = $(g.t).find('th.draggable:visible');
326 $headers.each(function () {
327 var left = $(this).offset().left;
328 var right = left + $(this).outerWidth();
329 if (left <= e.pageX && e.pageX <= right) {
337 * Get a zero-based index from a <th class="draggable"> tag in a table.
339 * @param obj table header <th> object
340 * @return zero-based index of the specified table header in the set of table headers (visible or not)
342 getHeaderIdx: function (obj) {
343 return $(obj).parents('tr').find('th.draggable').index(obj);
347 * Reposition the columns back to normal order.
349 restoreColOrder: function () {
350 // use insertion sort, since we already have shiftCol function
351 for (var i = 1; i < g.colOrder.length; i++) {
352 var x = g.colOrder[i];
354 while (j >= 0 && x < g.colOrder[j]) {
358 g.shiftCol(i, j + 1);
361 if (g.tableCreateTime) {
362 // send request to server to remember the column order
365 g.refreshRestoreButton();
369 * Send column preferences (column order and visibility) to the server.
371 sendColPrefs: function () {
372 if ($(g.t).is('.ajax')) { // only send preferences if ajax class
380 table_create_time: g.tableCreateTime
382 if (g.colOrder.length > 0) {
383 $.extend(post_params, { col_order: g.colOrder.toString() });
385 if (g.colVisib.length > 0) {
386 $.extend(post_params, { col_visib: g.colVisib.toString() });
388 $.post('sql.php', post_params, function (data) {
389 if (data.success !== true) {
390 var $temp_div = $(document.createElement('div'));
391 $temp_div.html(data.error);
392 $temp_div.addClass('error');
393 PMA_ajaxShowMessage($temp_div, false);
400 * Refresh restore button state.
401 * Make restore button disabled if the table is similar with initial state.
403 refreshRestoreButton: function () {
404 // check if table state is as initial state
405 var isInitial = true;
406 for (var i = 0; i < g.colOrder.length; i++) {
407 if (g.colOrder[i] !== i) {
412 // check if only one visible column left
413 var isOneColumn = g.visibleHeadersCount === 1;
414 // enable or disable restore button
415 if (isInitial || isOneColumn) {
416 $(g.o).find('div.restore_column').hide();
418 $(g.o).find('div.restore_column').show();
423 * Update current hint using the boolean values (showReorderHint, showSortHint, etc.).
426 updateHint: function () {
428 if (!g.colRsz && !g.colReorder) { // if not resizing or dragging
429 if (g.visibleHeadersCount > 1) {
430 g.showReorderHint = true;
432 if ($(t).find('th.marker').length > 0) {
433 g.showMarkHint = true;
435 if (g.showSortHint && g.sortHint) {
436 text += text.length > 0 ? '<br>' : '';
437 text += '- ' + g.sortHint;
439 if (g.showMultiSortHint && g.strMultiSortHint) {
440 text += text.length > 0 ? '<br>' : '';
441 text += '- ' + g.strMultiSortHint;
443 if (g.showMarkHint &&
445 ! g.showSortHint && // we do not show mark hint, when sort hint is shown
449 text += text.length > 0 ? '<br>' : '';
450 text += '- ' + g.reorderHint;
451 text += text.length > 0 ? '<br>' : '';
452 text += '- ' + g.markHint;
453 text += text.length > 0 ? '<br>' : '';
454 text += '- ' + g.copyHint;
461 * Toggle column's visibility.
462 * After calling this function and it returns true, afterToggleCol() must be called.
464 * @return boolean True if the column is toggled successfully.
466 toggleCol: function (n) {
468 // can hide if more than one column is visible
469 if (g.visibleHeadersCount > 1) {
470 $(g.t).find('tr').each(function () {
471 $(this).find('th.draggable:eq(' + n + '),' +
472 'td:eq(' + (g.actionSpan + n) + ')')
476 $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', false);
478 // cannot hide, force the checkbox to stay checked
479 $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', true);
482 } else { // column n is not visible
483 $(g.t).find('tr').each(function () {
484 $(this).find('th.draggable:eq(' + n + '),' +
485 'td:eq(' + (g.actionSpan + n) + ')')
489 $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', true);
495 * This must be called if toggleCol() returns is true.
497 * This function is separated from toggleCol because, sometimes, we want to toggle
498 * some columns together at one time and do just one adjustment after it, e.g. in showAllColumns().
500 afterToggleCol: function () {
501 // some adjustments after hiding column
506 // check visible first row headers count
507 g.visibleHeadersCount = $(g.t).find('tr:first th.draggable:visible').length;
508 g.refreshRestoreButton();
512 * Show columns' visibility list.
514 * @param obj The drop down arrow of column visibility list
516 showColList: function (obj) {
517 // only show when not resizing or reordering
518 if (!g.colRsz && !g.colReorder) {
519 var pos = $(obj).position();
520 // check if the list position is too right
521 if (pos.left + $(g.cList).outerWidth(true) > $(document).width()) {
522 pos.left = $(document).width() - $(g.cList).outerWidth(true);
526 top: pos.top + $(obj).outerHeight(true)
529 $(obj).addClass('coldrop-hover');
534 * Hide columns' visibility list.
536 hideColList: function () {
538 $(g.cDrop).find('.coldrop-hover').removeClass('coldrop-hover');
542 * Reposition the column visibility drop-down arrow.
544 reposDrop: function () {
545 var $th = $(t).find('th:not(.draggable)');
546 for (var i = 0; i < $th.length; i++) {
547 var $cd = $(g.cDrop).find('div:eq(' + i + ')'); // column drop-down arrow
548 var pos = $($th[i]).position();
550 left: pos.left + $($th[i]).width() - $cd.width(),
557 * Show all hidden columns.
559 showAllColumns: function () {
560 for (var i = 0; i < g.colVisib.length; i++) {
561 if (!g.colVisib[i]) {
569 * Show edit cell, if it can be shown
571 * @param cell <td> element to be edited
573 showEditCell: function (cell) {
574 if ($(cell).is('.grid_edit') &&
575 !g.colRsz && !g.colReorder) {
576 if (!g.isCellEditActive) {
579 if ('string' === $cell.attr('data-type') ||
580 'blob' === $cell.attr('data-type') ||
581 'json' === $cell.attr('data-type')
583 g.cEdit = g.cEditTextarea;
585 g.cEdit = g.cEditStd;
588 // remove all edit area and hide it
589 $(g.cEdit).find('.edit_area').empty().hide();
590 // reposition the cEdit element
592 top: $cell.position().top,
593 left: $cell.position().left
598 width: $cell.outerWidth(),
599 height: $cell.outerHeight()
601 // fill the cell edit with text from <td>
602 var value = PMA_getCellValue(cell);
603 if ($cell.attr('data-type') === 'json') {
604 value = JSON.stringify(JSON.parse(value), null, 4);
606 $(g.cEdit).find('.edit_box').val(value);
608 g.currentEditCell = cell;
609 $(g.cEdit).find('.edit_box').focus();
610 moveCursorToEnd($(g.cEdit).find('.edit_box'));
611 $(g.cEdit).find('*').prop('disabled', false);
615 function moveCursorToEnd (input) {
616 var originalValue = input.val();
617 var originallength = originalValue.length;
619 input.blur().focus().val(originalValue);
620 input[0].setSelectionRange(originallength, originallength);
625 * Remove edit cell and the edit area, if it is shown.
627 * @param force Optional, force to hide edit cell without saving edited field.
628 * @param data Optional, data from the POST AJAX request to save the edited field
629 * or just specify "true", if we want to replace the edited field with the new value.
630 * @param field Optional, the edited <td>. If not specified, the function will
631 * use currently edited <td> from g.currentEditCell.
632 * @param field Optional, this object contains a boolean named move (true, if called from move* functions)
633 * and a <td> to which the grid_edit should move
635 hideEditCell: function (force, data, field, options) {
636 if (g.isCellEditActive && !force) {
637 // cell is being edited, save or post the edited data
638 if (options !== undefined) {
639 g.saveOrPostEditedCell(options);
641 g.saveOrPostEditedCell();
646 // cancel any previous request
647 if (g.lastXHR !== null) {
653 if (g.currentEditCell) { // save value of currently edited cell
654 // replace current edited field with the new value
655 var $this_field = $(g.currentEditCell);
656 var is_null = $this_field.data('value') === null;
658 $this_field.find('span').html('NULL');
659 $this_field.addClass('null');
661 $this_field.removeClass('null');
662 var value = data.isNeedToRecheck
663 ? data.truncatableFieldValue
664 : $this_field.data('value');
666 // Truncates the text.
667 $this_field.removeClass('truncated');
668 if (PMA_commonParams.get('pftext') === 'P' && value.length > g.maxTruncatedLen) {
669 $this_field.addClass('truncated');
670 value = value.substring(0, g.maxTruncatedLen) + '...';
673 // Add <br> before carriage return.
674 new_html = escapeHtml(value);
675 new_html = new_html.replace(/\n/g, '<br>\n');
677 // remove decimal places if column type not supported
678 if (($this_field.attr('data-decimals') === 0) && ($this_field.attr('data-type').indexOf('time') !== -1)) {
679 new_html = new_html.substring(0, new_html.indexOf('.'));
682 // remove addtional decimal places
683 if (($this_field.attr('data-decimals') > 0) && ($this_field.attr('data-type').indexOf('time') !== -1)) {
684 new_html = new_html.substring(0, new_html.length - (6 - $this_field.attr('data-decimals')));
687 var selector = 'span';
688 if ($this_field.hasClass('hex') && $this_field.find('a').length) {
692 // Updates the code keeping highlighting (if any).
693 var $target = $this_field.find(selector);
694 if (!PMA_updateCode($target, new_html, value)) {
695 $target.html(new_html);
698 if ($this_field.is('.bit')) {
699 $this_field.find('span').text($this_field.data('value'));
702 if (data.transformations !== undefined) {
703 $.each(data.transformations, function (cell_index, value) {
704 var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
705 $this_field.find('span').html(value);
708 if (data.relations !== undefined) {
709 $.each(data.relations, function (cell_index, value) {
710 var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
711 $this_field.find('span').html(value);
720 // hide the cell editing area
722 $(g.cEdit).find('.edit_box').blur();
723 g.isCellEditActive = false;
724 g.currentEditCell = null;
725 // destroy datepicker in edit area, if exist
726 var $dp = $(g.cEdit).find('.hasDatepicker');
727 if ($dp.length > 0) {
728 $(document).bind('mousedown', $.datepicker._checkExternalClick);
729 $dp.datepicker('destroy');
730 // change the cursor in edit box back to normal
731 // (the cursor become a hand pointer when we add datepicker)
732 $(g.cEdit).find('.edit_box').css('cursor', 'inherit');
737 * Show drop-down edit area when edit cell is focused.
739 showEditArea: function () {
740 if (!g.isCellEditActive) { // make sure the edit area has not been shown
741 g.isCellEditActive = true;
742 g.isEditCellTextEditable = false;
744 * @var $td current edited cell
746 var $td = $(g.currentEditCell);
748 * @var $editArea the editing area
750 var $editArea = $(g.cEdit).find('.edit_area');
752 * @var where_clause WHERE clause for the edited cell
754 var where_clause = $td.parent('tr').find('.where_clause').val();
756 * @var field_name String containing the name of this field.
757 * @see getFieldName()
759 var field_name = getFieldName($(t), $td);
761 * @var relation_curr_value String current value of the field (for fields that are foreign keyed).
763 var relation_curr_value = $td.text();
765 * @var relation_key_or_display_column String relational key if in 'Relational display column' mode,
766 * relational display column if in 'Relational key' mode (for fields that are foreign keyed).
768 var relation_key_or_display_column = $td.find('a').attr('title');
770 * @var curr_value String current value of the field (for fields that are of type enum or set).
772 var curr_value = $td.find('span').text();
774 // empty all edit area, then rebuild it based on $td classes
777 // remember this instead of testing more than once
778 var is_null = $td.is('.null');
780 // add goto link, if this cell contains a link
781 if ($td.find('a').length > 0) {
782 var gotoLink = document.createElement('div');
783 gotoLink.className = 'goto_link';
784 $(gotoLink).append(g.gotoLinkText + ' ').append($td.find('a').clone());
785 $editArea.append(gotoLink);
788 g.wasEditedCellNull = false;
789 if ($td.is(':not(.not_null)')) {
790 // append a null checkbox
791 $editArea.append('<div class="null_div"><label>Null:<input type="checkbox"></label></div>');
793 var $checkbox = $editArea.find('.null_div input');
794 // check if current <td> is NULL
796 $checkbox.prop('checked', true);
797 g.wasEditedCellNull = true;
800 // if the select/editor is changed un-check the 'checkbox_null_<field_name>_<row_index>'.
801 if ($td.is('.enum, .set')) {
802 $editArea.on('change', 'select', function () {
803 $checkbox.prop('checked', false);
805 } else if ($td.is('.relation')) {
806 $editArea.on('change', 'select', function () {
807 $checkbox.prop('checked', false);
809 $editArea.on('click', '.browse_foreign', function () {
810 $checkbox.prop('checked', false);
813 $(g.cEdit).on('keypress change paste', '.edit_box', function () {
814 $checkbox.prop('checked', false);
816 // Capture ctrl+v (on IE and Chrome)
817 $(g.cEdit).on('keydown', '.edit_box', function (e) {
818 if (e.ctrlKey && e.which === 86) {
819 $checkbox.prop('checked', false);
822 $editArea.on('keydown', 'textarea', function () {
823 $checkbox.prop('checked', false);
826 // if some text is written in textbox automatically unmark the null checkbox and if it is emptied again mark the checkbox.
827 $(g.cEdit).find('.edit_box').on('input', function () {
828 if ($(g.cEdit).find('.edit_box').val() !== '') {
829 $checkbox.prop('checked', false);
831 $checkbox.prop('checked', true);
834 // if null checkbox is clicked empty the corresponding select/editor.
835 $checkbox.on('click', function () {
836 if ($td.is('.enum')) {
837 $editArea.find('select').val('');
838 } else if ($td.is('.set')) {
839 $editArea.find('select').find('option').each(function () {
840 var $option = $(this);
841 $option.prop('selected', false);
843 } else if ($td.is('.relation')) {
844 // if the dropdown is there to select the foreign value
845 if ($editArea.find('select').length > 0) {
846 $editArea.find('select').val('');
849 $editArea.find('textarea').val('');
851 $(g.cEdit).find('.edit_box').val('');
855 // reset the position of the edit_area div after closing datetime picker
856 $(g.cEdit).find('.edit_area').css({ 'top' :'0','position':'' });
858 if ($td.is('.relation')) {
860 $editArea.addClass('edit_area_loading');
862 // initialize the original data
863 $td.data('original_data', null);
866 * @var post_params Object containing parameters for the POST request
869 'ajax_request' : true,
870 'get_relational_values' : true,
874 'column' : field_name,
875 'curr_value' : relation_curr_value,
876 'relation_key_or_display_column' : relation_key_or_display_column
879 g.lastXHR = $.post('sql.php', post_params, function (data) {
881 $editArea.removeClass('edit_area_loading');
882 if ($(data.dropdown).is('select')) {
883 // save original_data
884 var value = $(data.dropdown).val();
885 $td.data('original_data', value);
886 // update the text input field, in case where the "Relational display column" is checked
887 $(g.cEdit).find('.edit_box').val(value);
890 $editArea.append(data.dropdown);
891 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
893 // for 'Browse foreign values' options,
894 // hide the value next to 'Browse foreign values' link
895 $editArea.find('span.curr_value').hide();
896 // handle update for new values selected from new window
897 $editArea.find('span.curr_value').on('change', function () {
898 $(g.cEdit).find('.edit_box').val($(this).text());
903 $editArea.on('change', 'select', function () {
904 $(g.cEdit).find('.edit_box').val($(this).val());
906 g.isEditCellTextEditable = true;
907 } else if ($td.is('.enum')) {
908 // handle enum fields
909 $editArea.addClass('edit_area_loading');
912 * @var post_params Object containing parameters for the POST request
915 'ajax_request' : true,
916 'get_enum_values' : true,
920 'column' : field_name,
921 'curr_value' : curr_value
923 g.lastXHR = $.post('sql.php', post_params, function (data) {
925 $editArea.removeClass('edit_area_loading');
926 $editArea.append(data.dropdown);
927 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
931 $editArea.on('change', 'select', function () {
932 $(g.cEdit).find('.edit_box').val($(this).val());
934 } else if ($td.is('.set')) {
936 $editArea.addClass('edit_area_loading');
939 * @var post_params Object containing parameters for the POST request
942 'ajax_request' : true,
943 'get_set_values' : true,
947 'column' : field_name,
948 'curr_value' : curr_value
951 // if the data is truncated, get the full data
952 if ($td.is('.truncated')) {
953 post_params.get_full_values = true;
954 post_params.where_clause = where_clause;
957 g.lastXHR = $.post('sql.php', post_params, function (data) {
959 $editArea.removeClass('edit_area_loading');
960 $editArea.append(data.select);
961 $td.data('original_data', $(data.select).val().join());
962 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
966 $editArea.on('change', 'select', function () {
967 $(g.cEdit).find('.edit_box').val($(this).val());
969 } else if ($td.is('.truncated, .transformed')) {
970 if ($td.is('.to_be_saved')) { // cell has been edited
971 var value = $td.data('value');
972 $(g.cEdit).find('.edit_box').val(value);
973 $editArea.append('<textarea></textarea>');
974 $editArea.find('textarea').val(value);
976 .on('keyup', 'textarea', function () {
977 $(g.cEdit).find('.edit_box').val($(this).val());
979 $(g.cEdit).on('keyup', '.edit_box', function () {
980 $editArea.find('textarea').val($(this).val());
982 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
984 // handle truncated/transformed values values
985 $editArea.addClass('edit_area_loading');
987 // initialize the original data
988 $td.data('original_data', null);
991 * @var sql_query String containing the SQL query used to retrieve value of truncated/transformed data
993 var sql_query = 'SELECT `' + field_name + '` FROM `' + g.table + '` WHERE ' + where_clause;
995 // Make the Ajax call and get the data, wrap it and insert it
996 g.lastXHR = $.post('sql.php', {
999 'ajax_request' : true,
1000 'sql_query' : sql_query,
1002 }, function (data) {
1004 $editArea.removeClass('edit_area_loading');
1005 if (typeof data !== 'undefined' && data.success === true) {
1006 $td.data('original_data', data.value);
1007 $(g.cEdit).find('.edit_box').val(data.value);
1009 PMA_ajaxShowMessage(data.error, false);
1013 g.isEditCellTextEditable = true;
1014 } else if ($td.is('.timefield, .datefield, .datetimefield, .timestampfield')) {
1015 var $input_field = $(g.cEdit).find('.edit_box');
1017 // remember current datetime value in $input_field, if it is not null
1018 var datetime_value = !is_null ? $input_field.val() : '';
1020 var showMillisec = false;
1021 var showMicrosec = false;
1022 var timeFormat = 'HH:mm:ss';
1023 // check for decimal places of seconds
1024 if (($td.attr('data-decimals') > 0) && ($td.attr('data-type').indexOf('time') !== -1)) {
1025 if (datetime_value && datetime_value.indexOf('.') === false) {
1026 datetime_value += '.';
1028 if ($td.attr('data-decimals') > 3) {
1029 showMillisec = true;
1030 showMicrosec = true;
1031 timeFormat = 'HH:mm:ss.lc';
1033 if (datetime_value) {
1034 datetime_value += '000000';
1035 var datetime_value = datetime_value.substring(0, datetime_value.indexOf('.') + 7);
1036 $input_field.val(datetime_value);
1039 showMillisec = true;
1040 timeFormat = 'HH:mm:ss.l';
1042 if (datetime_value) {
1043 datetime_value += '000';
1044 var datetime_value = datetime_value.substring(0, datetime_value.indexOf('.') + 4);
1045 $input_field.val(datetime_value);
1050 // add datetime picker
1051 PMA_addDatepicker($input_field, $td.attr('data-type'), {
1052 showMillisec: showMillisec,
1053 showMicrosec: showMicrosec,
1054 timeFormat: timeFormat
1057 $input_field.on('keyup', function (e) {
1058 if (e.which === 13) {
1059 // post on pressing "Enter"
1061 e.stopPropagation();
1062 g.saveOrPostEditedCell();
1063 } else if (e.which === 27) {
1065 toggleDatepickerIfInvalid($td, $input_field);
1069 $input_field.datepicker('show');
1070 toggleDatepickerIfInvalid($td, $input_field);
1072 // unbind the mousedown event to prevent the problem of
1073 // datepicker getting closed, needs to be checked for any
1074 // change in names when updating
1075 $(document).off('mousedown', $.datepicker._checkExternalClick);
1077 // move ui-datepicker-div inside cEdit div
1078 var datepicker_div = $('#ui-datepicker-div');
1079 datepicker_div.css({ 'top': 0, 'left': 0, 'position': 'relative' });
1080 $(g.cEdit).append(datepicker_div);
1082 // cancel any click on the datepicker element
1083 $editArea.find('> *').on('click', function (e) {
1084 e.stopPropagation();
1087 g.isEditCellTextEditable = true;
1089 g.isEditCellTextEditable = true;
1090 // only append edit area hint if there is a null checkbox
1091 if ($editArea.children().length > 0) {
1092 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
1095 if ($editArea.children().length > 0) {
1102 * Post the content of edited cell.
1104 * @param field Optional, this object contains a boolean named move (true, if called from move* functions)
1105 * and a <td> to which the grid_edit should move
1107 postEditedCell: function (options) {
1113 * @var relation_fields Array containing the name/value pairs of relational fields
1115 var relation_fields = {};
1117 * @var relational_display string 'K' if relational key, 'D' if relational display column
1119 var relational_display = $(g.o).find('input[name=relational_display]:checked').val();
1121 * @var transform_fields Array containing the name/value pairs for transformed fields
1123 var transform_fields = {};
1125 * @var transformation_fields Boolean, if there are any transformed fields in the edited cells
1127 var transformation_fields = false;
1129 * @var full_sql_query String containing the complete SQL query to update this table
1131 var full_sql_query = '';
1133 * @var rel_fields_list String, url encoded representation of {@link relations_fields}
1135 var rel_fields_list = '';
1137 * @var transform_fields_list String, url encoded representation of {@link transform_fields}
1139 var transform_fields_list = '';
1141 * @var where_clause Array containing where clause for updated fields
1143 var full_where_clause = [];
1145 * @var is_unique Boolean, whether the rows in this table is unique or not
1147 var is_unique = $(g.t).find('td.edit_row_anchor').is('.nonunique') ? 0 : 1;
1149 * multi edit variables
1151 var me_fields_name = [];
1152 var me_fields_type = [];
1154 var me_fields_null = [];
1156 // alert user if edited table is not unique
1158 alert(g.alertNonUnique);
1161 // loop each edited row
1162 $(g.t).find('td.to_be_saved').parents('tr').each(function () {
1164 var where_clause = $tr.find('.where_clause').val();
1165 if (typeof where_clause === 'undefined') {
1168 full_where_clause.push(where_clause);
1169 var condition_array = JSON.parse($tr.find('.condition_array').val());
1172 * multi edit variables, for current row
1173 * @TODO array indices are still not correct, they should be md5 of field's name
1175 var fields_name = [];
1176 var fields_type = [];
1178 var fields_null = [];
1180 // loop each edited cell in a row
1181 $tr.find('.to_be_saved').each(function () {
1183 * @var $this_field Object referring to the td that is being edited
1185 var $this_field = $(this);
1188 * @var field_name String containing the name of this field.
1189 * @see getFieldName()
1191 var field_name = getFieldName($(g.t), $this_field);
1194 * @var this_field_params Array temporary storage for the name/value of current field
1196 var this_field_params = {};
1198 if ($this_field.is('.transformed')) {
1199 transformation_fields = true;
1201 this_field_params[field_name] = $this_field.data('value');
1204 * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1206 var is_null = this_field_params[field_name] === null;
1208 fields_name.push(field_name);
1211 fields_null.push('on');
1214 if ($this_field.is('.bit')) {
1215 fields_type.push('bit');
1216 } else if ($this_field.hasClass('hex')) {
1217 fields_type.push('hex');
1219 fields_null.push('');
1220 // Convert \n to \r\n to be consistent with form submitted value.
1221 // The internal browser representation has to be just \n
1222 // while form submitted value \r\n, see specification:
1223 // https://www.w3.org/TR/html5/forms.html#the-textarea-element
1224 fields.push($this_field.data('value').replace(/\n/g, '\r\n'));
1226 var cell_index = $this_field.index('.to_be_saved');
1227 if ($this_field.is(':not(.relation, .enum, .set, .bit)')) {
1228 if ($this_field.is('.transformed')) {
1229 transform_fields[cell_index] = {};
1230 $.extend(transform_fields[cell_index], this_field_params);
1232 } else if ($this_field.is('.relation')) {
1233 relation_fields[cell_index] = {};
1234 $.extend(relation_fields[cell_index], this_field_params);
1237 // check if edited field appears in WHERE clause
1238 if (where_clause.indexOf(PMA_urlencode(field_name)) > -1) {
1239 var field_str = '`' + g.table + '`.' + '`' + field_name + '`';
1240 for (var field in condition_array) {
1241 if (field.indexOf(field_str) > -1) {
1242 condition_array[field] = is_null ? 'IS NULL' : '= \'' + this_field_params[field_name].replace(/'/g, '\'\'') + '\'';
1247 }); // end of loop for every edited cells in a row
1250 var new_clause = '';
1251 for (var field in condition_array) {
1252 new_clause += field + ' ' + condition_array[field] + ' AND ';
1254 new_clause = new_clause.substring(0, new_clause.length - 5); // remove the last AND
1255 $tr.data('new_clause', new_clause);
1256 // save condition_array
1257 $tr.find('.condition_array').val(JSON.stringify(condition_array));
1259 me_fields_name.push(fields_name);
1260 me_fields_type.push(fields_type);
1261 me_fields.push(fields);
1262 me_fields_null.push(fields_null);
1263 }); // end of loop for every edited rows
1265 rel_fields_list = $.param(relation_fields);
1266 transform_fields_list = $.param(transform_fields);
1268 // Make the Ajax post after setting all parameters
1270 * @var post_params Object containing parameters for the POST request
1272 var post_params = { 'ajax_request' : true,
1273 'sql_query' : full_sql_query,
1274 'server' : g.server,
1277 'clause_is_unique' : is_unique,
1278 'where_clause' : full_where_clause,
1279 'fields[multi_edit]' : me_fields,
1280 'fields_name[multi_edit]' : me_fields_name,
1281 'fields_type[multi_edit]' : me_fields_type,
1282 'fields_null[multi_edit]' : me_fields_null,
1283 'rel_fields_list' : rel_fields_list,
1284 'do_transformations' : transformation_fields,
1285 'transform_fields_list' : transform_fields_list,
1286 'relational_display' : relational_display,
1288 'submit_type' : 'save'
1291 if (!g.saveCellsAtOnce) {
1292 $(g.cEdit).find('*').prop('disabled', true);
1293 $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
1295 $(g.o).find('div.save_edited').addClass('saving_edited_data')
1296 .find('input').prop('disabled', true); // disable the save button
1301 url: 'tbl_replace.php',
1306 if (!g.saveCellsAtOnce) {
1307 $(g.cEdit).find('*').prop('disabled', false);
1308 $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
1310 $(g.o).find('div.save_edited').removeClass('saving_edited_data')
1311 .find('input').prop('disabled', false); // enable the save button back
1313 if (typeof data !== 'undefined' && data.success === true) {
1314 if (typeof options === 'undefined' || ! options.move) {
1315 PMA_ajaxShowMessage(data.message);
1318 // update where_clause related data in each edited row
1319 $(g.t).find('td.to_be_saved').parents('tr').each(function () {
1320 var new_clause = $(this).data('new_clause');
1321 var $where_clause = $(this).find('.where_clause');
1322 var old_clause = $where_clause.val();
1323 var decoded_old_clause = old_clause;
1324 var decoded_new_clause = new_clause;
1326 $where_clause.val(new_clause);
1327 // update Edit, Copy, and Delete links also
1328 $(this).find('a').each(function () {
1329 $(this).attr('href', $(this).attr('href').replace(old_clause, new_clause));
1330 // update delete confirmation in Delete link
1331 if ($(this).attr('href').indexOf('DELETE') > -1) {
1332 $(this).removeAttr('onclick')
1334 .on('click', function () {
1335 return confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' +
1336 decoded_new_clause + (is_unique ? '' : ' LIMIT 1'));
1340 // update the multi edit checkboxes
1341 $(this).find('input[type=checkbox]').each(function () {
1342 var $checkbox = $(this);
1343 var checkbox_name = $checkbox.attr('name');
1344 var checkbox_value = $checkbox.val();
1346 $checkbox.attr('name', checkbox_name.replace(old_clause, new_clause));
1347 $checkbox.val(checkbox_value.replace(decoded_old_clause, decoded_new_clause));
1350 // update the display of executed SQL query command
1351 if (typeof data.sql_query !== 'undefined') {
1352 // extract query box
1353 var $result_query = $($.parseHTML(data.sql_query));
1354 var sqlOuter = $result_query.find('.sqlOuter').wrap('<p>').parent().html();
1355 var tools = $result_query.find('.tools').wrap('<p>').parent().html();
1356 // sqlOuter and tools will not be present if 'Show SQL queries' configuration is off
1357 if (typeof sqlOuter !== 'undefined' && typeof tools !== 'undefined') {
1358 $(g.o).find('.result_query:not(:last)').remove();
1359 var $existing_query = $(g.o).find('.result_query');
1360 // If two query box exists update query in second else add a second box
1361 if ($existing_query.find('div.sqlOuter').length > 1) {
1362 $existing_query.children(':nth-child(4)').remove();
1363 $existing_query.children(':nth-child(4)').remove();
1364 $existing_query.append(sqlOuter + tools);
1366 $existing_query.append(sqlOuter + tools);
1368 PMA_highlightSQL($existing_query);
1371 // hide and/or update the successfully saved cells
1372 g.hideEditCell(true, data);
1374 // remove the "Save edited cells" button
1375 $(g.o).find('div.save_edited').hide();
1376 // update saved fields
1377 $(g.t).find('.to_be_saved')
1378 .removeClass('to_be_saved')
1379 .data('value', null)
1380 .data('original_data', null);
1382 g.isCellEdited = false;
1384 PMA_ajaxShowMessage(data.error, false);
1385 if (!g.saveCellsAtOnce) {
1386 $(g.t).find('.to_be_saved')
1387 .removeClass('to_be_saved');
1391 }).done(function () {
1392 if (options !== undefined && options.move) {
1393 g.showEditCell(options.cell);
1399 * Save edited cell, so it can be posted later.
1401 saveEditedCell: function () {
1403 * @var $this_field Object referring to the td that is being edited
1405 var $this_field = $(g.currentEditCell);
1406 var $test_element = ''; // to test the presence of a element
1408 var need_to_post = false;
1411 * @var field_name String containing the name of this field.
1412 * @see getFieldName()
1414 var field_name = getFieldName($(g.t), $this_field);
1417 * @var this_field_params Array temporary storage for the name/value of current field
1419 var this_field_params = {};
1422 * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1424 var is_null = $(g.cEdit).find('input:checkbox').is(':checked');
1426 if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
1427 // the edit area is still loading (retrieving cell data), no need to post
1428 need_to_post = false;
1429 } else if (is_null) {
1430 if (!g.wasEditedCellNull) {
1431 this_field_params[field_name] = null;
1432 need_to_post = true;
1435 if ($this_field.is('.bit')) {
1436 this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1437 } else if ($this_field.is('.set')) {
1438 $test_element = $(g.cEdit).find('select');
1439 this_field_params[field_name] = $test_element.map(function () {
1440 return $(this).val();
1442 } else if ($this_field.is('.relation, .enum')) {
1443 // for relation and enumeration, take the results from edit box value,
1444 // because selected value from drop-down, new window or multiple
1445 // selection list will always be updated to the edit box
1446 this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1447 } else if ($this_field.hasClass('hex')) {
1448 if ($(g.cEdit).find('.edit_box').val().match(/^(0x)?[a-f0-9]*$/i) !== null) {
1449 this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1451 var hexError = '<div class="error">' + PMA_messages.strEnterValidHex + '</div>';
1452 PMA_ajaxShowMessage(hexError, false);
1453 this_field_params[field_name] = PMA_getCellValue(g.currentEditCell);
1456 this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1458 if (g.wasEditedCellNull || this_field_params[field_name] !== PMA_getCellValue(g.currentEditCell)) {
1459 need_to_post = true;
1464 $(g.currentEditCell).addClass('to_be_saved')
1465 .data('value', this_field_params[field_name]);
1466 if (g.saveCellsAtOnce) {
1467 $(g.o).find('div.save_edited').show();
1469 g.isCellEdited = true;
1472 return need_to_post;
1476 * Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
1478 * @param field Optional, this object contains a boolean named move (true, if called from move* functions)
1479 * and a <td> to which the grid_edit should move
1481 saveOrPostEditedCell: function (options) {
1482 var saved = g.saveEditedCell();
1483 // Check if $cfg['SaveCellsAtOnce'] is false
1484 if (!g.saveCellsAtOnce) {
1485 // Check if need_to_post is true
1487 // Check if this function called from 'move' functions
1488 if (options !== undefined && options.move) {
1489 g.postEditedCell(options);
1493 // need_to_post is false
1495 // Check if this function called from 'move' functions
1496 if (options !== undefined && options.move) {
1497 g.hideEditCell(true);
1498 g.showEditCell(options.cell);
1499 // NOT called from 'move' functions
1501 g.hideEditCell(true);
1504 // $cfg['SaveCellsAtOnce'] is true
1508 // If this function called from 'move' functions
1509 if (options !== undefined && options.move) {
1510 g.hideEditCell(true, true, false, options);
1511 g.showEditCell(options.cell);
1512 // NOT called from 'move' functions
1514 g.hideEditCell(true, true);
1517 // If this function called from 'move' functions
1518 if (options !== undefined && options.move) {
1519 g.hideEditCell(true, false, false, options);
1520 g.showEditCell(options.cell);
1521 // NOT called from 'move' functions
1523 g.hideEditCell(true);
1530 * Initialize column resize feature.
1532 initColResize: function () {
1533 // create column resizer div
1534 g.cRsz = document.createElement('div');
1535 g.cRsz.className = 'cRsz';
1537 // get data columns in the first row of the table
1538 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1540 // create column borders
1541 $firstRowCols.each(function () {
1542 var cb = document.createElement('div'); // column border
1543 $(cb).addClass('colborder')
1544 .on('mousedown', function (e) {
1545 g.dragStartRsz(e, this);
1547 $(g.cRsz).append(cb);
1551 // attach to global div
1552 $(g.gDiv).prepend(g.cRsz);
1556 * Initialize column reordering feature.
1558 initColReorder: function () {
1559 g.cCpy = document.createElement('div'); // column copy, to store copy of dragged column header
1560 g.cPointer = document.createElement('div'); // column pointer, used when reordering column
1563 g.cCpy.className = 'cCpy';
1566 // adjust g.cPointer
1567 g.cPointer.className = 'cPointer';
1568 $(g.cPointer).css('visibility', 'hidden'); // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
1570 // assign column reordering hint
1571 g.reorderHint = PMA_messages.strColOrderHint;
1573 // get data columns in the first row of the table
1574 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1576 // initialize column order
1577 $col_order = $(g.o).find('.col_order'); // check if column order is passed from PHP
1578 if ($col_order.length > 0) {
1579 g.colOrder = $col_order.val().split(',');
1580 for (var i = 0; i < g.colOrder.length; i++) {
1581 g.colOrder[i] = parseInt(g.colOrder[i], 10);
1585 for (var i = 0; i < $firstRowCols.length; i++) {
1591 $(g.t).find('th.draggable')
1592 .on('mousedown', function (e) {
1593 $(g.o).addClass('turnOffSelect');
1594 if (g.visibleHeadersCount > 1) {
1595 g.dragStartReorder(e, this);
1598 .on('mouseenter', function () {
1599 if (g.visibleHeadersCount > 1) {
1600 $(this).css('cursor', 'move');
1602 $(this).css('cursor', 'inherit');
1605 .mouseleave(function () {
1606 g.showReorderHint = false;
1607 $(this).tooltip('option', {
1608 content: g.updateHint()
1611 .dblclick(function (e) {
1614 .prop('title', PMA_messages.strColNameCopyTitle)
1615 .addClass('modal-copy')
1616 .text(PMA_messages.strColNameCopyText)
1619 .prop('readonly', true)
1620 .val($(this).data('column'))
1626 .find('input').focus().select();
1628 $(g.t).find('th.draggable a')
1629 .dblclick(function (e) {
1630 e.stopPropagation();
1632 // restore column order when the restore button is clicked
1633 $(g.o).find('div.restore_column').on('click', function () {
1634 g.restoreColOrder();
1637 // attach to global div
1638 $(g.gDiv).append(g.cPointer);
1639 $(g.gDiv).append(g.cCpy);
1641 // prevent default "dragstart" event when dragging a link
1642 $(g.t).find('th a').on('dragstart', function () {
1646 // refresh the restore column button state
1647 g.refreshRestoreButton();
1651 * Initialize column visibility feature.
1653 initColVisib: function () {
1654 g.cDrop = document.createElement('div'); // column drop-down arrows
1655 g.cList = document.createElement('div'); // column visibility list
1658 g.cDrop.className = 'cDrop';
1661 g.cList.className = 'cList';
1664 // assign column visibility related hints
1665 g.showAllColText = PMA_messages.strShowAllCol;
1667 // get data columns in the first row of the table
1668 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1671 // initialize column visibility
1672 var $col_visib = $(g.o).find('.col_visib'); // check if column visibility is passed from PHP
1673 if ($col_visib.length > 0) {
1674 g.colVisib = $col_visib.val().split(',');
1675 for (i = 0; i < g.colVisib.length; i++) {
1676 g.colVisib[i] = parseInt(g.colVisib[i], 10);
1680 for (i = 0; i < $firstRowCols.length; i++) {
1685 // make sure we have more than one column
1686 if ($firstRowCols.length > 1) {
1687 var $colVisibTh = $(g.t).find('th:not(.draggable)');
1691 PMA_messages.strColVisibHint
1694 // create column visibility drop-down arrow(s)
1695 $colVisibTh.each(function () {
1697 var cd = document.createElement('div'); // column drop-down arrow
1698 var pos = $th.position();
1699 $(cd).addClass('coldrop')
1700 .on('click', function () {
1701 if (g.cList.style.display === 'none') {
1702 g.showColList(this);
1707 $(g.cDrop).append(cd);
1710 // add column visibility control
1711 g.cList.innerHTML = '<div class="lDiv"></div>';
1712 var $listDiv = $(g.cList).find('div');
1714 var tempClick = function () {
1715 if (g.toggleCol($(this).index())) {
1720 for (i = 0; i < $firstRowCols.length; i++) {
1721 var currHeader = $firstRowCols[i];
1722 var listElmt = document.createElement('div');
1723 $(listElmt).text($(currHeader).text())
1724 .prepend('<input type="checkbox" ' + (g.colVisib[i] ? 'checked="checked" ' : '') + '>');
1725 $listDiv.append(listElmt);
1726 // add event on click
1727 $(listElmt).on('click', tempClick);
1729 // add "show all column" button
1730 var showAll = document.createElement('div');
1731 $(showAll).addClass('showAllColBtn')
1732 .text(g.showAllColText);
1733 $(g.cList).append(showAll);
1734 $(showAll).on('click', function () {
1737 // prepend "show all column" button at top if the list is too long
1738 if ($firstRowCols.length > 10) {
1739 var clone = showAll.cloneNode(true);
1740 $(g.cList).prepend(clone);
1741 $(clone).on('click', function () {
1747 // hide column visibility list if we move outside the list
1748 $(g.t).find('td, th.draggable').on('mouseenter', function () {
1752 // attach to global div
1753 $(g.gDiv).append(g.cDrop);
1754 $(g.gDiv).append(g.cList);
1761 * Move currently Editing Cell to Up
1763 moveUp: function (e) {
1765 var $this_field = $(g.currentEditCell);
1766 var field_name = getFieldName($(g.t), $this_field);
1768 var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
1769 if (typeof where_clause === 'undefined') {
1777 $this_field.parents('tr').first().parents('tbody').children().each(function () {
1778 if ($(this).find('.where_clause').val() === where_clause) {
1780 $found_row = $(this);
1783 $prev_row = $(this);
1789 if (found && $prev_row) {
1790 $prev_row.children('td').each(function () {
1791 if (getFieldName($(g.t), $(this)) === field_name) {
1798 g.hideEditCell(false, false, false, { move : true, cell : new_cell });
1803 * Move currently Editing Cell to Down
1805 moveDown: function (e) {
1808 var $this_field = $(g.currentEditCell);
1809 var field_name = getFieldName($(g.t), $this_field);
1811 var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
1812 if (typeof where_clause === 'undefined') {
1819 var next_row_found = false;
1820 $this_field.parents('tr').first().parents('tbody').children().each(function () {
1821 if ($(this).find('.where_clause').val() === where_clause) {
1823 $found_row = $(this);
1826 if (j >= 1 && ! next_row_found) {
1827 $next_row = $(this);
1828 next_row_found = true;
1836 if (found && $next_row) {
1837 $next_row.children('td').each(function () {
1838 if (getFieldName($(g.t), $(this)) === field_name) {
1845 g.hideEditCell(false, false, false, { move : true, cell : new_cell });
1850 * Move currently Editing Cell to Left
1852 moveLeft: function (e) {
1855 var $this_field = $(g.currentEditCell);
1856 var field_name = getFieldName($(g.t), $this_field);
1858 var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
1859 if (typeof where_clause === 'undefined') {
1865 $this_field.parents('tr').first().parents('tbody').children().each(function () {
1866 if ($(this).find('.where_clause').val() === where_clause) {
1868 $found_row = $(this);
1873 var cell_found = false;
1875 $found_row.children('td.grid_edit').each(function () {
1876 if (getFieldName($(g.t), $(this)) === field_name) {
1886 g.hideEditCell(false, false, false, { move : true, cell : left_cell });
1891 * Move currently Editing Cell to Right
1893 moveRight: function (e) {
1896 var $this_field = $(g.currentEditCell);
1897 var field_name = getFieldName($(g.t), $this_field);
1899 var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
1900 if (typeof where_clause === 'undefined') {
1906 $this_field.parents('tr').first().parents('tbody').children().each(function () {
1907 if ($(this).find('.where_clause').val() === where_clause) {
1909 $found_row = $(this);
1914 var cell_found = false;
1915 var next_cell_found = false;
1917 $found_row.children('td.grid_edit').each(function () {
1918 if (getFieldName($(g.t), $(this)) === field_name) {
1922 if (j >= 1 && ! next_cell_found) {
1924 next_cell_found = true;
1933 g.hideEditCell(false, false, false, { move : true, cell : right_cell });
1938 * Initialize grid editing feature.
1940 initGridEdit: function () {
1941 function startGridEditing (e, cell) {
1942 if (g.isCellEditActive) {
1943 g.saveOrPostEditedCell();
1945 g.showEditCell(cell);
1947 e.stopPropagation();
1950 function handleCtrlNavigation (e) {
1951 if ((e.ctrlKey && e.which === 38) || (e.altKey && e.which === 38)) {
1953 } else if ((e.ctrlKey && e.which === 40) || (e.altKey && e.which === 40)) {
1955 } else if ((e.ctrlKey && e.which === 37) || (e.altKey && e.which === 37)) {
1957 } else if ((e.ctrlKey && e.which === 39) || (e.altKey && e.which === 39)) {
1962 // create cell edit wrapper element
1963 g.cEditStd = document.createElement('div');
1964 g.cEdit = g.cEditStd;
1965 g.cEditTextarea = document.createElement('div');
1967 // adjust g.cEditStd
1968 g.cEditStd.className = 'cEdit';
1969 $(g.cEditStd).html('<input class="edit_box" rows="1"><div class="edit_area"></div>');
1970 $(g.cEditStd).hide();
1973 g.cEditTextarea.className = 'cEdit';
1974 $(g.cEditTextarea).html('<textarea class="edit_box" rows="1"></textarea><div class="edit_area"></div>');
1975 $(g.cEditTextarea).hide();
1977 // assign cell editing hint
1978 g.cellEditHint = PMA_messages.strCellEditHint;
1979 g.saveCellWarning = PMA_messages.strSaveCellWarning;
1980 g.alertNonUnique = PMA_messages.strAlertNonUnique;
1981 g.gotoLinkText = PMA_messages.strGoToLink;
1983 // initialize cell editing configuration
1984 g.saveCellsAtOnce = $(g.o).find('.save_cells_at_once').val();
1985 g.maxTruncatedLen = PMA_commonParams.get('LimitChars');
1988 $(g.t).find('td.data.click1')
1989 .on('click', function (e) {
1990 startGridEditing(e, this);
1991 // prevent default action when clicking on "link" in a table
1992 if ($(e.target).is('.grid_edit a')) {
1997 $(g.t).find('td.data.click2')
1998 .on('click', function (e) {
1999 var $cell = $(this);
2000 // In the case of relational link, We want single click on the link
2001 // to goto the link and double click to start grid-editing.
2002 var $link = $(e.target);
2003 if ($link.is('.grid_edit.relation a')) {
2005 // get the click count and increase
2006 var clicks = $cell.data('clicks');
2007 clicks = (typeof clicks === 'undefined') ? 1 : clicks + 1;
2010 // if there are no previous clicks,
2011 // start the single click timer
2012 var timer = setTimeout(function () {
2013 // temporarily remove ajax class so the page loader will not handle it,
2014 // submit and then add it back
2015 $link.removeClass('ajax');
2016 AJAX.requestHandler.call($link[0]);
2017 $link.addClass('ajax');
2018 $cell.data('clicks', 0);
2020 $cell.data('clicks', clicks);
2021 $cell.data('timer', timer);
2023 // this is a double click, cancel the single click timer
2024 // and make the click count 0
2025 clearTimeout($cell.data('timer'));
2026 $cell.data('clicks', 0);
2027 // start grid-editing
2028 startGridEditing(e, this);
2032 .dblclick(function (e) {
2033 if ($(e.target).is('.grid_edit a')) {
2036 startGridEditing(e, this);
2040 $(g.cEditStd).on('keydown', 'input.edit_box, select', handleCtrlNavigation);
2042 $(g.cEditStd).find('.edit_box').focus(function () {
2045 $(g.cEditStd).on('keydown', '.edit_box, select', function (e) {
2046 if (e.which === 13) {
2047 // post on pressing "Enter"
2049 g.saveOrPostEditedCell();
2052 $(g.cEditStd).on('keydown', function (e) {
2053 if (!g.isEditCellTextEditable) {
2054 // prevent text editing
2059 $(g.cEditTextarea).on('keydown', 'textarea.edit_box, select', handleCtrlNavigation);
2061 $(g.cEditTextarea).find('.edit_box').focus(function () {
2064 $(g.cEditTextarea).on('keydown', '.edit_box, select', function (e) {
2065 if (e.which === 13 && !e.shiftKey) {
2066 // post on pressing "Enter"
2068 g.saveOrPostEditedCell();
2071 $(g.cEditTextarea).on('keydown', function (e) {
2072 if (!g.isEditCellTextEditable) {
2073 // prevent text editing
2077 $('html').on('click', function (e) {
2078 // hide edit cell if the click is not fromDat edit area
2079 if ($(e.target).parents().index($(g.cEdit)) === -1 &&
2080 !$(e.target).parents('.ui-datepicker-header').length &&
2081 !$('.browse_foreign_modal.ui-dialog:visible').length &&
2082 !$(e.target).closest('.dismissable').length
2086 }).on('keydown', function (e) {
2087 if (e.which === 27 && g.isCellEditActive) {
2088 // cancel on pressing "Esc"
2089 g.hideEditCell(true);
2092 $(g.o).find('div.save_edited').on('click', function () {
2096 $(window).on('beforeunload', function () {
2097 if (g.isCellEdited) {
2098 return g.saveCellWarning;
2102 // attach to global div
2103 $(g.gDiv).append(g.cEditStd);
2104 $(g.gDiv).append(g.cEditTextarea);
2106 // add hint for grid editing feature when hovering "Edit" link in each table row
2107 if (PMA_messages.strGridEditFeatureHint !== undefined) {
2109 $(g.t).find('.edit_row_anchor a'),
2111 PMA_messages.strGridEditFeatureHint
2117 /** ****************
2121 // wrap all truncated data cells with span indicating the original length
2122 // todo update the original length after a grid edit
2123 $(t).find('td.data.truncated:not(:has(span))')
2124 .wrapInner(function () {
2125 return '<span title="' + PMA_messages.strOriginalLength + ' ' +
2126 $(this).data('originallength') + '"></span>';
2129 // wrap remaining cells, except actions cell, with span
2130 $(t).find('th, td:not(:has(span))')
2131 .wrapInner('<span></span>');
2133 // create grid elements
2134 g.gDiv = document.createElement('div'); // create global div
2136 // initialize the table variable
2139 // enclosing .sqlqueryresults div
2140 g.o = $(t).parents('.sqlqueryresults');
2142 // get data columns in the first row of the table
2143 var $firstRowCols = $(t).find('tr:first th.draggable');
2145 // initialize visible headers count
2146 g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
2148 // assign first column (actions) span
2149 if (! $(t).find('tr:first th:first').hasClass('draggable')) { // action header exist
2150 g.actionSpan = $(t).find('tr:first th:first').prop('colspan');
2155 // assign table create time
2156 // table_create_time will only available if we are in "Browse" tab
2157 g.tableCreateTime = $(g.o).find('.table_create_time').val();
2160 g.sortHint = PMA_messages.strSortHint;
2161 g.strMultiSortHint = PMA_messages.strMultiSortHint;
2162 g.markHint = PMA_messages.strColMarkHint;
2163 g.copyHint = PMA_messages.strColNameCopyHint;
2165 // assign common hidden inputs
2166 var $common_hidden_inputs = $(g.o).find('div.common_hidden_inputs');
2167 g.server = $common_hidden_inputs.find('input[name=server]').val();
2168 g.db = $common_hidden_inputs.find('input[name=db]').val();
2169 g.table = $common_hidden_inputs.find('input[name=table]').val();
2172 $(t).addClass('pma_table');
2174 // add relative position to global div so that resize handlers are correctly positioned
2175 $(g.gDiv).css('position', 'relative');
2177 // link the global div
2178 $(t).before(g.gDiv);
2179 $(g.gDiv).append(t);
2182 enableResize = enableResize === undefined ? true : enableResize;
2183 enableReorder = enableReorder === undefined ? true : enableReorder;
2184 enableVisib = enableVisib === undefined ? true : enableVisib;
2185 enableGridEdit = enableGridEdit === undefined ? true : enableGridEdit;
2189 // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
2190 if (enableReorder &&
2191 $(g.o).find('table.navigation').length > 0) {
2197 // make sure we have the ajax class
2198 if (enableGridEdit &&
2203 // create tooltip for each <th> with draggable class
2205 $(t).find('th.draggable'),
2210 // register events for hint tooltip (anchors inside draggable th)
2211 $(t).find('th.draggable a')
2212 .on('mouseenter', function () {
2213 g.showSortHint = true;
2214 g.showMultiSortHint = true;
2215 $(t).find('th.draggable').tooltip('option', {
2216 content: g.updateHint()
2219 .mouseleave(function () {
2220 g.showSortHint = false;
2221 g.showMultiSortHint = false;
2222 $(t).find('th.draggable').tooltip('option', {
2223 content: g.updateHint()
2227 // register events for dragging-related feature
2228 if (enableResize || enableReorder) {
2229 $(document).mousemove(function (e) {
2232 $(document).mouseup(function (e) {
2233 $(g.o).removeClass('turnOffSelect');
2239 $(t).removeClass('data');
2240 $(g.gDiv).addClass('data');
2244 * jQuery plugin to cancel selection in HTML code.
2247 $.fn.noSelect = function (p) { // no select plugin by Paulo P.Marinas
2248 var prevent = (p === null) ? true : p;
2249 var is_msie = navigator.userAgent.indexOf('MSIE') > -1 || !!window.navigator.userAgent.match(/Trident.*rv\:11\./);
2250 var is_firefox = navigator.userAgent.indexOf('Firefox') > -1;
2251 var is_safari = navigator.userAgent.indexOf('Safari') > -1;
2252 var is_opera = navigator.userAgent.indexOf('Presto') > -1;
2254 return this.each(function () {
2255 if (is_msie || is_safari) {
2256 $(this).on('selectstart', false);
2257 } else if (is_firefox) {
2258 $(this).css('MozUserSelect', 'none');
2259 $('body').trigger('focus');
2260 } else if (is_opera) {
2261 $(this).on('mousedown', false);
2263 $(this).attr('unselectable', 'on');
2267 return this.each(function () {
2268 if (is_msie || is_safari) {
2269 $(this).off('selectstart');
2270 } else if (is_firefox) {
2271 $(this).css('MozUserSelect', 'inherit');
2272 } else if (is_opera) {
2273 $(this).off('mousedown');
2275 $(this).removeAttr('unselectable');