Translated using Weblate (Slovenian)
[phpmyadmin.git] / js / tbl_structure.js
blob8999aea70029d537e1dc5c9f4ca94a954ef9ce25
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * @fileoverview    functions used on the table structure page
4  * @name            Table Structure
5  *
6  * @requires    jQuery
7  * @requires    jQueryUI
8  * @required    js/functions.js
9  */
11 /**
12  * AJAX scripts for tbl_structure.php
13  *
14  * Actions ajaxified here:
15  * Drop Column
16  * Add Primary Key
17  * Drop Primary Key/Index
18  *
19  */
21 /**
22  * This function returns the horizontal space available for the menu in pixels.
23  * To calculate this value we start we the width of the main panel, then we
24  * substract the margin of the page content, then we substract any cellspacing
25  * that the table may have (original theme only) and finally we substract the
26  * width of all columns of the table except for the last one (which is where
27  * the menu will go). What we should end up with is the distance between the
28  * start of the last column on the table and the edge of the page, again this
29  * is the space available for the menu.
30  *
31  * In the case where the table cell where the menu will be displayed is already
32  * off-screen (the table is wider than the page), a negative value will be returned,
33  * but this will be treated as a zero by the menuResizer plugin.
34  *
35  * @return int
36  */
37 function PMA_tbl_structure_menu_resizer_callback() {
38     var pagewidth = $('body').width();
39     var $page = $('#page_content');
40     pagewidth -= $page.outerWidth(true) - $page.outerWidth();
41     var columnsWidth = 0;
42     var $columns = $('#tablestructure').find('tr:eq(1)').find('td,th');
43     $columns.not(':last').each(function () {
44         columnsWidth += $(this).outerWidth(true);
45     });
46     var totalCellSpacing = $('#tablestructure').width();
47     $columns.each(function () {
48         totalCellSpacing -= $(this).outerWidth(true);
49     });
50     return pagewidth - columnsWidth - totalCellSpacing - 15; // 15px extra margin
53 /**
54  * Reload fields table
55  */
56 function reloadFieldForm() {
57     $.post($("#fieldsForm").attr('action'), $("#fieldsForm").serialize() + "&ajax_request=true", function (form_data) {
58         var $temp_div = $("<div id='temp_div'><div>").append(form_data.message);
59         $("#fieldsForm").replaceWith($temp_div.find("#fieldsForm"));
60         $("#addColumns").replaceWith($temp_div.find("#addColumns"));
61         $('#move_columns_dialog').find('ul').replaceWith($temp_div.find("#move_columns_dialog ul"));
62         $("#moveColumns").removeClass("move-active");
63         /* reinitialise the more options in table */
64         if ($('#fieldsForm').hasClass('HideStructureActions')) {
65             $('#fieldsForm').find('ul.table-structure-actions').menuResizer(PMA_tbl_structure_menu_resizer_callback);
66         }
67     });
68     $('#page_content').show();
71 function checkFirst() {
72     if ($("select[name=after_field] option:selected").data('pos') === 'first') {
73         $("input[name=field_where]").val('first');
74     } else {
75         $("input[name=field_where]").val('after');
76     }
78 /**
79  * Unbind all event handlers before tearing down a page
80  */
81 AJAX.registerTeardown('tbl_structure.js', function () {
82     $(document).off('click', "a.drop_column_anchor.ajax");
83     $(document).off('click', "a.add_key.ajax");
84     $(document).off('click', "#move_columns_anchor");
85     $(document).off('click', "#printView");
86     $(document).off('submit', ".append_fields_form.ajax");
87     $('body').off('click', '#fieldsForm.ajax button[name="submit_mult"], #fieldsForm.ajax input[name="submit_mult"]');
88     $(document).off('click', 'a[name^=partition_action].ajax');
89     $(document).off('click', '#remove_partitioning.ajax');
90 });
92 AJAX.registerOnload('tbl_structure.js', function () {
94     // Re-initialize variables.
95     primary_indexes = [];
96     indexes = [];
97     fulltext_indexes = [];
98     spatial_indexes = [];
100     /**
101      *Ajax action for submitting the "Column Change" and "Add Column" form
102      */
103     $(".append_fields_form.ajax").off();
104     $(document).on('submit', ".append_fields_form.ajax", function (event) {
105         event.preventDefault();
106         /**
107          * @var    the_form    object referring to the export form
108          */
109         var $form = $(this);
110         var field_cnt = $form.find('input[name=orig_num_fields]').val();
113         function submitForm(){
114             $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
115             $.post($form.attr('action'), $form.serialize() + '&do_save_data=1', function (data) {
116                 if ($(".sqlqueryresults").length !== 0) {
117                     $(".sqlqueryresults").remove();
118                 } else if ($(".error:not(.tab)").length !== 0) {
119                     $(".error:not(.tab)").remove();
120                 }
121                 if (typeof data.success != 'undefined' && data.success === true) {
122                     $("#page_content")
123                         .empty()
124                         .append(data.message)
125                         .show();
126                     PMA_highlightSQL($('#page_content'));
127                     $(".result_query .notice").remove();
128                     reloadFieldForm();
129                     $form.remove();
130                     PMA_ajaxRemoveMessage($msg);
131                     PMA_init_slider();
132                     PMA_reloadNavigation();
133                 } else {
134                     PMA_ajaxShowMessage(data.error, false);
135                 }
136             }); // end $.post()
137         }
139         function checkIfConfirmRequired($form, $field_cnt) {
140             var i = 0, id, elm, val, name_orig, elm_orig, val_orig;
141             var checkRequired = false;
142             for (i = 0; i < field_cnt; i++) {
143                 id = "#field_" + i + "_5";
144                 elm = $(id);
145                 val = elm.val();
147                 name_orig = "input[name=field_collation_orig\\[" + i + "\\]]";
148                 elm_orig = $form.find(name_orig);
149                 val_orig = elm_orig.val();
151                 if (val && val_orig && val !== val_orig){
152                     checkRequired = true;
153                     break;
154                 }
155             }
156             return checkRequired;
157         }
159         /*
160          * First validate the form; if there is a problem, avoid submitting it
161          *
162          * checkTableEditForm() needs a pure element and not a jQuery object,
163          * this is why we pass $form[0] as a parameter (the jQuery object
164          * is actually an array of DOM elements)
165          */
166         if (checkTableEditForm($form[0], field_cnt)) {
167             // OK, form passed validation step
169             PMA_prepareForAjaxRequest($form);
170             if (PMA_checkReservedWordColumns($form)) {
171                 //User wants to submit the form
173                 // If Collation is changed, Warn and Confirm
174                 if (checkIfConfirmRequired($form, field_cnt)){
175                     var question = sprintf(
176                         PMA_messages.strChangeColumnCollation, 'https://wiki.phpmyadmin.net/pma/Garbled_data'
177                     );
178                     $form.PMA_confirm(question, $form.attr('action'), function (url) {
179                         submitForm();
180                     });
181                 } else {
182                     submitForm();
183                 }
184             }
185         }
186     }); // end change table button "do_save_data"
188     /**
189      * Attach Event Handler for 'Drop Column'
190      */
191     $(document).on('click', "a.drop_column_anchor.ajax", function (event) {
192         event.preventDefault();
193         /**
194          * @var curr_table_name String containing the name of the current table
195          */
196         var curr_table_name = $(this).closest('form').find('input[name=table]').val();
197         /**
198          * @var curr_row    Object reference to the currently selected row (i.e. field in the table)
199          */
200         var $curr_row = $(this).parents('tr');
201         /**
202          * @var curr_column_name    String containing name of the field referred to by {@link curr_row}
203          */
204         var curr_column_name = $curr_row.children('th').children('label').text().trim();
205         curr_column_name = escapeHtml(curr_column_name);
206         /**
207          * @var $after_field_item    Corresponding entry in the 'After' field.
208          */
209         var $after_field_item = $("select[name='after_field'] option[value='" + curr_column_name + "']");
210         /**
211          * @var question    String containing the question to be asked for confirmation
212          */
213         var question = PMA_sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` DROP `' + escapeHtml(curr_column_name) + '`;');
214         $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
215             var $msg = PMA_ajaxShowMessage(PMA_messages.strDroppingColumn, false);
216             var params = {
217                 'is_js_confirmed' : 1,
218                 'ajax_request' : true,
219                 'ajax_page_request' : true,
220                 'token': PMA_commonParams.get('token')
221             };
222             $.post(url, params, function (data) {
223                 if (typeof data !== 'undefined' && data.success === true) {
224                     PMA_ajaxRemoveMessage($msg);
225                     if ($('.result_query').length) {
226                         $('.result_query').remove();
227                     }
228                     if (data.sql_query) {
229                         $('<div class="result_query"></div>')
230                             .html(data.sql_query)
231                             .prependTo('#structure_content');
232                         PMA_highlightSQL($('#page_content'));
233                     }
234                     // Adjust the row numbers
235                     for (var $row = $curr_row.next(); $row.length > 0; $row = $row.next()) {
236                         var new_val = parseInt($row.find('td:nth-child(2)').text(), 10) - 1;
237                         $row.find('td:nth-child(2)').text(new_val);
238                     }
239                     $after_field_item.remove();
240                     $curr_row.hide("medium").remove();
242                     // Remove the dropped column from select menu for 'after field'
243                     $("select[name=after_field]").find(
244                         '[value="' + curr_column_name + '"]'
245                     ).remove();
247                     // by default select the (new) last option to add new column
248                     // (in case last column is dropped)
249                     $("select[name=after_field] option:last").attr("selected","selected");
251                     //refresh table stats
252                     if (data.tableStat) {
253                         $('#tablestatistics').html(data.tableStat);
254                     }
255                     // refresh the list of indexes (comes from sql.php)
256                     $('.index_info').replaceWith(data.indexes_list);
257                     PMA_reloadNavigation();
258                 } else {
259                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
260                 }
261             }); // end $.post()
262         }); // end $.PMA_confirm()
263     }); //end of Drop Column Anchor action
265     /**
266      * Attach Event Handler for 'Print' link
267      */
268     $(document).on('click', "#printView", function (event) {
269         event.preventDefault();
271         // Take to preview mode
272         printPreview();
273     }); //end of Print View action
275     /**
276      * Ajax Event handler for adding keys
277      */
278     $(document).on('click', "a.add_key.ajax", function (event) {
279         event.preventDefault();
281         var $this = $(this);
282         var curr_table_name = $this.closest('form').find('input[name=table]').val();
283         var curr_column_name = $this.parents('tr').children('th').children('label').text().trim();
285         var add_clause = '';
286         if ($this.is('.add_primary_key_anchor')) {
287             add_clause = 'ADD PRIMARY KEY';
288         } else if ($this.is('.add_index_anchor')) {
289             add_clause = 'ADD INDEX';
290         } else if ($this.is('.add_unique_anchor')) {
291             add_clause = 'ADD UNIQUE';
292         } else if ($this.is('.add_spatial_anchor')) {
293             add_clause = 'ADD SPATIAL';
294         } else if ($this.is('.add_fulltext_anchor')) {
295             add_clause = 'ADD FULLTEXT';
296         }
297         var question = PMA_sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' +
298                 escapeHtml(curr_table_name) + '` ' + add_clause + '(`' + escapeHtml(curr_column_name) + '`);');
300         $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
301             PMA_ajaxShowMessage();
302             AJAX.source = $this;
303             var params = {
304                 'ajax_request' : true,
305                 'ajax_page_request' : true,
306                 'token': PMA_commonParams.get('token')
307             };
308             $.post(url, params, AJAX.responseHandler);
309         }); // end $.PMA_confirm()
310     }); //end Add key
312     /**
313      * Inline move columns
314     **/
315     $(document).on('click', "#move_columns_anchor", function (e) {
316         e.preventDefault();
318         if ($(this).hasClass("move-active")) {
319             return;
320         }
322         /**
323          * @var    button_options  Object that stores the options passed to jQueryUI
324          *                          dialog
325          */
326         var button_options = {};
328         button_options[PMA_messages.strGo] = function (event) {
329             event.preventDefault();
330             var $msgbox = PMA_ajaxShowMessage();
331             var $this = $(this);
332             var $form = $this.find("form");
333             var serialized = $form.serialize();
335             // check if any columns were moved at all
336             if (serialized == $form.data("serialized-unmoved")) {
337                 PMA_ajaxRemoveMessage($msgbox);
338                 $this.dialog('close');
339                 return;
340             }
342             $.post($form.prop("action"), serialized + "&ajax_request=true", function (data) {
343                 if (data.success === false) {
344                     PMA_ajaxRemoveMessage($msgbox);
345                     $this
346                     .clone()
347                     .html(data.error)
348                     .dialog({
349                         title: $(this).prop("title"),
350                         height: 230,
351                         width: 900,
352                         modal: true,
353                         buttons: button_options_error
354                     }); // end dialog options
355                 } else {
356                     if ($('#fieldsForm').hasClass('HideStructureActions')) {
357                         $('#fieldsForm').find('ul.table-structure-actions').menuResizer('destroy');
358                     }
359                     // sort the fields table
360                     var $fields_table = $("table#tablestructure tbody");
361                     // remove all existing rows and remember them
362                     var $rows = $fields_table.find("tr").remove();
363                     // loop through the correct order
364                     for (var i in data.columns) {
365                         var the_column = data.columns[i];
366                         var $the_row = $rows
367                             .find("input:checkbox[value='" + the_column + "']")
368                             .closest("tr");
369                         // append the row for this column to the table
370                         $fields_table.append($the_row);
371                     }
372                     var $firstrow = $fields_table.find("tr").eq(0);
373                     // Adjust the row numbers and colors
374                     for (var $row = $firstrow; $row.length > 0; $row = $row.next()) {
375                         $row
376                         .find('td:nth-child(2)')
377                         .text($row.index() + 1)
378                         .end()
379                         .removeClass("odd even")
380                         .addClass($row.index() % 2 === 0 ? "odd" : "even");
381                     }
382                     PMA_ajaxShowMessage(data.message);
383                     $this.dialog('close');
384                     if ($('#fieldsForm').hasClass('HideStructureActions')) {
385                         $('#fieldsForm').find('ul.table-structure-actions').menuResizer(PMA_tbl_structure_menu_resizer_callback);
386                     }
387                 }
388             });
389         };
390         button_options[PMA_messages.strCancel] = function () {
391             $(this).dialog('close');
392         };
394         var button_options_error = {};
395         button_options_error[PMA_messages.strOK] = function () {
396             $(this).dialog('close').remove();
397         };
399         var columns = [];
401         $("#tablestructure").find("tbody tr").each(function () {
402             var col_name = $(this).find("input:checkbox").eq(0).val();
403             var hidden_input = $("<input/>")
404                 .prop({
405                     name: "move_columns[]",
406                     type: "hidden"
407                 })
408                 .val(col_name);
409             columns[columns.length] = $("<li/>")
410                 .addClass("placeholderDrag")
411                 .text(col_name)
412                 .append(hidden_input);
413         });
415         var col_list = $("#move_columns_dialog").find("ul")
416             .find("li").remove().end();
417         for (var i in columns) {
418             col_list.append(columns[i]);
419         }
420         col_list.sortable({
421             axis: 'y',
422             containment: $("#move_columns_dialog").find("div"),
423             tolerance: 'pointer'
424         }).disableSelection();
425         var $form = $("#move_columns_dialog").find("form");
426         $form.data("serialized-unmoved", $form.serialize());
428         $("#move_columns_dialog").dialog({
429             modal: true,
430             buttons: button_options,
431             open: function () {
432                 if ($('#move_columns_dialog').parents('.ui-dialog').height() > $(window).height()) {
433                     $('#move_columns_dialog').dialog("option", "height", $(window).height());
434                 }
435             },
436             beforeClose: function () {
437                 $("#move_columns_anchor").removeClass("move-active");
438             }
439         });
440     });
442     /**
443      * Handles multi submits in table structure page such as change, browse, drop, primary etc.
444      */
445     $('body').on('click', '#fieldsForm.ajax button[name="submit_mult"], #fieldsForm.ajax input[name="submit_mult"]', function (e) {
446         e.preventDefault();
447         var $button = $(this);
448         var $form = $button.parents('form');
449         var submitData = $form.serialize() + '&ajax_request=true&ajax_page_request=true&submit_mult=' + $button.val();
450         PMA_ajaxShowMessage();
451         AJAX.source = $form;
452         $.post($form.attr('action'), submitData, AJAX.responseHandler);
453     });
455     /**
456      * Handles clicks on Action links in partition table
457      */
458     $(document).on('click', 'a[name^=partition_action].ajax', function (e) {
459         e.preventDefault();
460         var $link = $(this);
462         function submitPartitionAction(url) {
463             var params = {
464                 'ajax_request' : true,
465                 'ajax_page_request' : true,
466                 'token': PMA_commonParams.get('token')
467             };
468             PMA_ajaxShowMessage();
469             AJAX.source = $link;
470             $.post(url, params, AJAX.responseHandler);
471         }
473         if ($link.is('#partition_action_DROP')) {
474             var question = PMA_messages.strDropPartitionWarning;
475             $link.PMA_confirm(question, $link.attr('href'), function (url) {
476                 submitPartitionAction(url);
477             });
478         } else if ($link.is('#partition_action_TRUNCATE')) {
479             var question = PMA_messages.strTruncatePartitionWarning;
480             $link.PMA_confirm(question, $link.attr('href'), function (url) {
481                 submitPartitionAction(url);
482             });
483         } else {
484             submitPartitionAction($link.attr('href'));
485         }
486     });
488     /**
489      * Handles remove partitioning
490      */
491     $(document).on('click', '#remove_partitioning.ajax', function (e) {
492         e.preventDefault();
493         var $link = $(this);
494         var question = PMA_messages.strRemovePartitioningWarning;
495         $link.PMA_confirm(question, $link.attr('href'), function (url) {
496             var params = {
497                 'ajax_request' : true,
498                 'ajax_page_request' : true,
499                 'token': PMA_commonParams.get('token')
500             };
501             PMA_ajaxShowMessage();
502             AJAX.source = $link;
503             $.post(url, params, AJAX.responseHandler);
504         });
505     });
508 /** Handler for "More" dropdown in structure table rows */
509 AJAX.registerOnload('tbl_structure.js', function () {
510     if ($('#fieldsForm').hasClass('HideStructureActions')) {
511         $('#fieldsForm').find('ul.table-structure-actions').menuResizer(PMA_tbl_structure_menu_resizer_callback);
512     } else {
513         $('.table-structure-actions').width(function () {
514             var width = 5;
515             $(this).find('li').each(function () {
516                 width += $(this).outerWidth(true);
517             });
518             return width;
519         });
520     }
522 AJAX.registerTeardown('tbl_structure.js', function () {
523     if ($('#fieldsForm').hasClass('HideStructureActions')) {
524         $('#fieldsForm').find('ul.table-structure-actions').menuResizer('destroy');
525     }
527 $(function () {
528     $(window).resize($.throttle(function () {
529         if ($('#fieldsForm').length && $('#fieldsForm').hasClass('HideStructureActions')) {
530             $('#fieldsForm').find('ul.table-structure-actions').menuResizer('resize');
531         }
532     }));