Translated using Weblate (Slovenian)
[phpmyadmin.git] / js / tbl_structure.js
blob08481b72ae74232ddf99463cc0335faa84b9a9a3
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 ul').replaceWith($temp_div.find("#move_columns_dialog ul"));
62         $("#moveColumns").removeClass("move-active");
63         /* reinitialise the more options in table */
64         $('#fieldsForm ul.table-structure-actions').menuResizer(PMA_tbl_structure_menu_resizer_callback);
65     });
66     $('#page_content').show();
69 /**
70  * Unbind all event handlers before tearing down a page
71  */
72 AJAX.registerTeardown('tbl_structure.js', function () {
73     $("a.change_column_anchor.ajax").die('click');
74     $("button.change_columns_anchor.ajax, input.change_columns_anchor.ajax").die('click');
75     $("a.drop_column_anchor.ajax").die('click');
76     $("a.add_primary_key_anchor.ajax").die('click');
77     $("#move_columns_anchor").die('click');
78     $(".append_fields_form.ajax").unbind('submit');
79 });
81 AJAX.registerOnload('tbl_structure.js', function () {
83     /**
84      *Ajax action for submitting the "Column Change" and "Add Column" form
85      */
86     $(".append_fields_form.ajax").die().live('submit', function (event) {
87         event.preventDefault();
88         /**
89          * @var    the_form    object referring to the export form
90          */
91         var $form = $(this);
93         /*
94          * First validate the form; if there is a problem, avoid submitting it
95          *
96          * checkTableEditForm() needs a pure element and not a jQuery object,
97          * this is why we pass $form[0] as a parameter (the jQuery object
98          * is actually an array of DOM elements)
99          */
100         if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
101             // OK, form passed validation step
102             PMA_prepareForAjaxRequest($form);
103             //User wants to submit the form
104             $msg = PMA_ajaxShowMessage();
105             $.post($form.attr('action'), $form.serialize() + '&do_save_data=1', function (data) {
106                 if ($("#sqlqueryresults").length !== 0) {
107                     $("#sqlqueryresults").remove();
108                 } else if ($(".error:not(.tab)").length !== 0) {
109                     $(".error:not(.tab)").remove();
110                 }
111                 if (data.success === true) {
112                     $("#page_content")
113                         .empty()
114                         .append(data.message)
115                         .append(data.sql_query)
116                         .show();
117                     PMA_highlightSQL($('#page_content'));
118                     $("#result_query .notice").remove();
119                     reloadFieldForm();
120                     $form.remove();
121                     PMA_ajaxRemoveMessage($msg);
122                     PMA_reloadNavigation();
123                 } else {
124                     PMA_ajaxShowMessage(data.error, false);
125                 }
126             }); // end $.post()
127         }
128     }); // end change table button "do_save_data"
130     /**
131      * Attach Event Handler for 'Change Column'
132      */
133     $("a.change_column_anchor.ajax").live('click', function (event) {
134         event.preventDefault();
135         var $msg = PMA_ajaxShowMessage();
136         $('#page_content').hide();
137         $.get($(this).attr('href'), {'ajax_request': true}, function (data) {
138             PMA_ajaxRemoveMessage($msg);
139             if (data.success) {
140                 $('<div id="change_column_dialog" class="margin"></div>')
141                     .html(data.message)
142                     .insertBefore('#page_content');
143                 PMA_highlightSQL($('#page_content'));
144                 PMA_showHints();
145                 PMA_verifyColumnsProperties();
146             } else {
147                 PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
148             }
149         });
150     });
152     /**
153      * Attach Event Handler for 'Change multiple columns'
154      */
155     $("button.change_columns_anchor.ajax, input.change_columns_anchor.ajax").live('click', function (event) {
156         event.preventDefault();
157         var $msg = PMA_ajaxShowMessage();
158         $('#page_content').hide();
159         var $form = $(this).closest('form');
160         var params = $form.serialize() + "&ajax_request=true&submit_mult=change";
161         $.post($form.prop("action"), params, function (data) {
162             PMA_ajaxRemoveMessage($msg);
163             if (data.success) {
164                 $('#page_content')
165                     .empty()
166                     .append(
167                         $('<div id="change_column_dialog"></div>')
168                             .html(data.message)
169                     )
170                     .show();
171                 PMA_highlightSQL($('#page_content'));
172                 PMA_showHints();
173                 PMA_verifyColumnsProperties();
174             } else {
175                 $('#page_content').show();
176                 PMA_ajaxShowMessage(data.error);
177             }
178         });
179     });
181     /**
182      * Attach Event Handler for 'Drop Column'
183      */
184     $("a.drop_column_anchor.ajax").live('click', function (event) {
185         event.preventDefault();
186         /**
187          * @var curr_table_name String containing the name of the current table
188          */
189         var curr_table_name = $(this).closest('form').find('input[name=table]').val();
190         /**
191          * @var curr_row    Object reference to the currently selected row (i.e. field in the table)
192          */
193         var $curr_row = $(this).parents('tr');
194         /**
195          * @var curr_column_name    String containing name of the field referred to by {@link curr_row}
196          */
197         var curr_column_name = $curr_row.children('th').children('label').text();
198         /**
199          * @var $after_field_item    Corresponding entry in the 'After' field.
200          */
201         var $after_field_item = $("select[name='after_field'] option[value='" + curr_column_name + "']");
202         /**
203          * @var question    String containing the question to be asked for confirmation
204          */
205         var question = $.sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` DROP `' + escapeHtml(curr_column_name) + '`;');
206         $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
207             var $msg = PMA_ajaxShowMessage(PMA_messages.strDroppingColumn, false);
208             $.get(url, {'is_js_confirmed' : 1, 'ajax_request' : true, 'ajax_page_request' : true}, function (data) {
209                 if (data.success === true) {
210                     PMA_ajaxRemoveMessage($msg);
211                     if ($('#result_query').length) {
212                         $('#result_query').remove();
213                     }
214                     if (data.sql_query) {
215                         $('<div id="result_query"></div>')
216                             .html(data.sql_query)
217                             .prependTo('#page_content');
218                         PMA_highlightSQL($('#page_content'));
219                     }
220                     toggleRowColors($curr_row.next());
221                     // Adjust the row numbers
222                     for (var $row = $curr_row.next(); $row.length > 0; $row = $row.next()) {
223                         var new_val = parseInt($row.find('td:nth-child(2)').text(), 10) - 1;
224                         $row.find('td:nth-child(2)').text(new_val);
225                     }
226                     $after_field_item.remove();
227                     $curr_row.hide("medium").remove();
228                     //refresh table stats
229                     if (data.tableStat) {
230                         $('#tablestatistics').html(data.tableStat);
231                     }
232                     // refresh the list of indexes (comes from sql.php)
233                     $('.index_info').replaceWith(data.indexes_list);
234                     PMA_reloadNavigation();
235                 } else {
236                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
237                 }
238             }); // end $.get()
239         }); // end $.PMA_confirm()
240     }); //end of Drop Column Anchor action
242     /**
243      * Ajax Event handler for 'Add Primary Key'
244      */
245     $("a.add_primary_key_anchor.ajax").live('click', function (event) {
246         event.preventDefault();
247         /**
248          * @var curr_table_name String containing the name of the current table
249          */
250         var curr_table_name = $(this).closest('form').find('input[name=table]').val();
251         /**
252          * @var curr_column_name    String containing name of the field referred to by {@link curr_row}
253          */
254         var curr_column_name = $(this).parents('tr').children('th').children('label').text();
255         /**
256          * @var question    String containing the question to be asked for confirmation
257          */
258         var question = $.sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` ADD PRIMARY KEY(`' + escapeHtml(curr_column_name) + '`);');
259         $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
260             var $msg = PMA_ajaxShowMessage(PMA_messages.strAddingPrimaryKey, false);
261             $.get(url, {'is_js_confirmed' : 1, 'ajax_request' : true}, function (data) {
262                 if (data.success === true) {
263                     PMA_ajaxRemoveMessage($msg);
264                     $(this).remove();
265                     if (typeof data.reload != 'undefined') {
266                         PMA_commonActions.refreshMain(false, function () {
267                             if ($('#result_query').length) {
268                                 $('#result_query').remove();
269                             }
270                             if (data.sql_query) {
271                                 $('<div id="result_query"></div>')
272                                     .html(data.sql_query)
273                                     .prependTo('#page_content');
274                                 PMA_highlightSQL($('#page_content'));
275                             }
276                         });
277                         PMA_reloadNavigation();
278                     }
279                 } else {
280                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
281                 }
282             }); // end $.get()
283         }); // end $.PMA_confirm()
284     }); //end Add Primary Key
286     /**
287      * Inline move columns
288     **/
289     $("#move_columns_anchor").live('click', function (e) {
290         e.preventDefault();
292         if ($(this).hasClass("move-active")) {
293             return;
294         }
296         /**
297          * @var    button_options  Object that stores the options passed to jQueryUI
298          *                          dialog
299          */
300         var button_options = {};
302         button_options[PMA_messages.strGo] = function (event) {
303             event.preventDefault();
304             var $msgbox = PMA_ajaxShowMessage();
305             var $this = $(this);
306             var $form = $this.find("form");
307             var serialized = $form.serialize();
309             // check if any columns were moved at all
310             if (serialized == $form.data("serialized-unmoved")) {
311                 PMA_ajaxRemoveMessage($msgbox);
312                 $this.dialog('close');
313                 return;
314             }
316             $.post($form.prop("action"), serialized + "&ajax_request=true", function (data) {
317                 if (data.success === false) {
318                     PMA_ajaxRemoveMessage($msgbox);
319                     $this
320                     .clone()
321                     .html(data.error)
322                     .dialog({
323                         title: $(this).prop("title"),
324                         height: 230,
325                         width: 900,
326                         modal: true,
327                         buttons: button_options_error
328                     }); // end dialog options
329                 } else {
330                     $('#fieldsForm ul.table-structure-actions').menuResizer('destroy');
331                     // sort the fields table
332                     var $fields_table = $("table#tablestructure tbody");
333                     // remove all existing rows and remember them
334                     var $rows = $fields_table.find("tr").remove();
335                     // loop through the correct order
336                     for (var i in data.columns) {
337                         var the_column = data.columns[i];
338                         var $the_row = $rows
339                             .find("input:checkbox[value=" + the_column + "]")
340                             .closest("tr");
341                         // append the row for this column to the table
342                         $fields_table.append($the_row);
343                     }
344                     var $firstrow = $fields_table.find("tr").eq(0);
345                     // Adjust the row numbers and colors
346                     for (var $row = $firstrow; $row.length > 0; $row = $row.next()) {
347                         $row
348                         .find('td:nth-child(2)')
349                         .text($row.index() + 1)
350                         .end()
351                         .removeClass("odd even")
352                         .addClass($row.index() % 2 === 0 ? "odd" : "even");
353                     }
354                     PMA_ajaxShowMessage(data.message);
355                     $this.dialog('close');
356                     $('#fieldsForm ul.table-structure-actions').menuResizer(PMA_tbl_structure_menu_resizer_callback);
357                 }
358             });
359         };
360         button_options[PMA_messages.strCancel] = function () {
361             $(this).dialog('close');
362         };
364         var button_options_error = {};
365         button_options_error[PMA_messages.strOK] = function () {
366             $(this).dialog('close').remove();
367         };
369         var columns = [];
371         $("#tablestructure tbody tr").each(function () {
372             var col_name = $(this).find("input:checkbox").eq(0).val();
373             var hidden_input = $("<input/>")
374                 .prop({
375                     name: "move_columns[]",
376                     type: "hidden"
377                 })
378                 .val(col_name);
379             columns[columns.length] = $("<li/>")
380                 .addClass("placeholderDrag")
381                 .text(col_name)
382                 .append(hidden_input);
383         });
385         var col_list = $("#move_columns_dialog ul")
386             .find("li").remove().end();
387         for (var i in columns) {
388             col_list.append(columns[i]);
389         }
390         col_list.sortable({
391             axis: 'y',
392             containment: $("#move_columns_dialog div")
393         }).disableSelection();
394         var $form = $("#move_columns_dialog form");
395         $form.data("serialized-unmoved", $form.serialize());
397         $("#move_columns_dialog").dialog({
398             modal: true,
399             buttons: button_options,
400             beforeClose: function () {
401                 $("#move_columns_anchor").removeClass("move-active");
402             }
403         });
404     });
407 /** Handler for "More" dropdown in structure table rows */
408 AJAX.registerOnload('tbl_structure.js', function () {
409     if ($('#fieldsForm').hasClass('HideStructureActions')) {
410         $('#fieldsForm ul.table-structure-actions').menuResizer(PMA_tbl_structure_menu_resizer_callback);
411     }
413 AJAX.registerTeardown('tbl_structure.js', function () {
414     $('#fieldsForm ul.table-structure-actions').menuResizer('destroy');
416 $(function () {
417     $(window).resize($.throttle(function () {
418         var $list = $('#fieldsForm ul.table-structure-actions');
419         if ($list.length) {
420             $list.menuResizer('resize');
421         }
422     }));