Merge pull request #431 from xmujay/0609_monitor
[phpmyadmin/aamir.git] / js / tbl_structure.js
blob3f45583d2feb9bcd306dfba68906a8ebfb9a8ff7
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  * Reload fields table
23  */
24 function reloadFieldForm(message) {
25     $.post($("#fieldsForm").attr('action'), $("#fieldsForm").serialize() + "&ajax_request=true", function (form_data) {
26         var $temp_div = $("<div id='temp_div'><div>").append(form_data.message);
27         $("#fieldsForm").replaceWith($temp_div.find("#fieldsForm"));
28         $("#addColumns").replaceWith($temp_div.find("#addColumns"));
29         $('#move_columns_dialog ul').replaceWith($temp_div.find("#move_columns_dialog ul"));
30         $("#moveColumns").removeClass("move-active");
31         /* reinitialise the more options in table */
32         $('#fieldsForm ul.table-structure-actions').menuResizer(PMA_tbl_structure_menu_resizer_callback);
33         setTimeout(function () {
34             PMA_ajaxShowMessage(message);
35         }, 500);
36     });
37     $('#page_content').show();
40 /**
41  * Unbind all event handlers before tearing down a page
42  */
43 AJAX.registerTeardown('tbl_structure.js', function () {
44     $("a.change_column_anchor.ajax").die('click');
45     $("button.change_columns_anchor.ajax, input.change_columns_anchor.ajax").die('click');
46     $("a.drop_column_anchor.ajax").die('click');
47     $("a.add_primary_key_anchor.ajax").die('click');
48     $("#move_columns_anchor").die('click');
49     $(".append_fields_form.ajax").unbind('submit');
50 });
52 AJAX.registerOnload('tbl_structure.js', function () {
54     /**
55      *Ajax action for submitting the "Column Change" and "Add Column" form
56      */
57     $(".append_fields_form.ajax").die().live('submit', function (event) {
58         event.preventDefault();
59         /**
60          * @var    the_form    object referring to the export form
61          */
62         var $form = $(this);
64         /*
65          * First validate the form; if there is a problem, avoid submitting it
66          *
67          * checkTableEditForm() needs a pure element and not a jQuery object,
68          * this is why we pass $form[0] as a parameter (the jQuery object
69          * is actually an array of DOM elements)
70          */
71         if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
72             // OK, form passed validation step
73             PMA_prepareForAjaxRequest($form);
74             //User wants to submit the form
75             $msg = PMA_ajaxShowMessage();
76             $.post($form.attr('action'), $form.serialize() + '&do_save_data=1', function (data) {
77                 if ($("#sqlqueryresults").length != 0) {
78                     $("#sqlqueryresults").remove();
79                 } else if ($(".error:not(.tab)").length != 0) {
80                     $(".error:not(.tab)").remove();
81                 }
82                 if (data.success == true) {
83                     $("#page_content")
84                         .empty()
85                         .append(data.message)
86                         .append(data.sql_query)
87                         .show();
88                     PMA_highlightSQL($('#page_content'));
89                     $("#result_query .notice").remove();
90                     $form.remove();
91                     PMA_ajaxRemoveMessage($msg);
92                     PMA_reloadNavigation();
93                 } else {
94                     PMA_ajaxShowMessage(data.error, false);
95                 }
96             }); // end $.post()
97         }
98     }); // end change table button "do_save_data"
100     /**
101      * Attach Event Handler for 'Change Column'
102      */
103     $("a.change_column_anchor.ajax").live('click', function (event) {
104         event.preventDefault();
105         var $msg = PMA_ajaxShowMessage();
106         $('#page_content').hide();
107         $.get($(this).attr('href'), {'ajax_request': true}, function (data) {
108             PMA_ajaxRemoveMessage($msg);
109             if (data.success) {
110                 $('<div id="change_column_dialog" class="margin"></div>')
111                     .html(data.message)
112                     .insertBefore('#page_content');
113                 PMA_highlightSQL($('#page_content'));
114                 PMA_verifyColumnsProperties();
115             } else {
116                 PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
117             }
118         });
119     });
121     /**
122      * Attach Event Handler for 'Change multiple columns'
123      */
124     $("button.change_columns_anchor.ajax, input.change_columns_anchor.ajax").live('click', function (event) {
125         event.preventDefault();
126         var $msg = PMA_ajaxShowMessage();
127         $('#page_content').hide();
128         var $form = $(this).closest('form');
129         var params = $form.serialize() + "&ajax_request=true&submit_mult=change";
130         $.post($form.prop("action"), params, function (data) {
131             PMA_ajaxRemoveMessage($msg);
132             if (data.success) {
133                 $('#page_content')
134                     .empty()
135                     .append(
136                         $('<div id="change_column_dialog"></div>')
137                             .html(data.message)
138                     )
139                     .show();
140                 PMA_highlightSQL($('#page_content'));
141                 PMA_verifyColumnsProperties();
142             } else {
143                 $('#page_content').show();
144                 PMA_ajaxShowMessage(data.error);
145             }
146         });
147     });
149     /**
150      * Attach Event Handler for 'Drop Column'
151      */
152     $("a.drop_column_anchor.ajax").live('click', function (event) {
153         event.preventDefault();
154         /**
155          * @var curr_table_name String containing the name of the current table
156          */
157         var curr_table_name = $(this).closest('form').find('input[name=table]').val();
158         /**
159          * @var curr_row    Object reference to the currently selected row (i.e. field in the table)
160          */
161         var $curr_row = $(this).parents('tr');
162         /**
163          * @var curr_column_name    String containing name of the field referred to by {@link curr_row}
164          */
165         var curr_column_name = $curr_row.children('th').children('label').text();
166         /**
167          * @var $after_field_item    Corresponding entry in the 'After' field.
168          */
169         var $after_field_item = $("select[name='after_field'] option[value='" + curr_column_name + "']");
170         /**
171          * @var question    String containing the question to be asked for confirmation
172          */
173         var question = $.sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` DROP `' + escapeHtml(curr_column_name) + '`;');
174         $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
175             var $msg = PMA_ajaxShowMessage(PMA_messages.strDroppingColumn, false);
176             $.get(url, {'is_js_confirmed' : 1, 'ajax_request' : true, 'ajax_page_request' : true}, function (data) {
177                 if (data.success == true) {
178                     PMA_ajaxRemoveMessage($msg);
179                     if ($('#result_query').length) {
180                         $('#result_query').remove();
181                     }
182                     if (data.sql_query) {
183                         $('<div id="result_query"></div>')
184                             .html(data.sql_query)
185                             .prependTo('#page_content');
186                         PMA_highlightSQL($('#page_content'));
187                     }
188                     toggleRowColors($curr_row.next());
189                     // Adjust the row numbers
190                     for (var $row = $curr_row.next(); $row.length > 0; $row = $row.next()) {
191                         var new_val = parseInt($row.find('td:nth-child(2)').text(), 10) - 1;
192                         $row.find('td:nth-child(2)').text(new_val);
193                     }
194                     $after_field_item.remove();
195                     $curr_row.hide("medium").remove();
196                     //refresh table stats
197                     if (data.tableStat) {
198                         $('#tablestatistics').html(data.tableStat);
199                     }
200                     // refresh the list of indexes (comes from sql.php)
201                     $('.index_info').replaceWith(data.indexes_list);
202                     PMA_reloadNavigation();
203                 } else {
204                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
205                 }
206             }); // end $.get()
207         }); // end $.PMA_confirm()
208     }); //end of Drop Column Anchor action
210     /**
211      * Ajax Event handler for 'Add Primary Key'
212      */
213     $("a.add_primary_key_anchor.ajax").live('click', function (event) {
214         event.preventDefault();
215         /**
216          * @var curr_table_name String containing the name of the current table
217          */
218         var curr_table_name = $(this).closest('form').find('input[name=table]').val();
219         /**
220          * @var curr_column_name    String containing name of the field referred to by {@link curr_row}
221          */
222         var curr_column_name = $(this).parents('tr').children('th').children('label').text();
223         /**
224          * @var question    String containing the question to be asked for confirmation
225          */
226         var question = $.sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` ADD PRIMARY KEY(`' + escapeHtml(curr_column_name) + '`);');
227         $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
228             var $msg = PMA_ajaxShowMessage(PMA_messages.strAddingPrimaryKey, false);
229             $.get(url, {'is_js_confirmed' : 1, 'ajax_request' : true}, function (data) {
230                 if (data.success === true) {
231                     PMA_ajaxRemoveMessage($msg);
232                     $(this).remove();
233                     if (typeof data.reload != 'undefined') {
234                         PMA_commonActions.refreshMain(false, function () {
235                             if ($('#result_query').length) {
236                                 $('#result_query').remove();
237                             }
238                             if (data.sql_query) {
239                                 $('<div id="result_query"></div>')
240                                     .html(data.sql_query)
241                                     .prependTo('#page_content');
242                                 PMA_highlightSQL($('#page_content'));
243                             }
244                         });
245                         PMA_reloadNavigation();
246                     }
247                 } else {
248                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
249                 }
250             }); // end $.get()
251         }); // end $.PMA_confirm()
252     }); //end Add Primary Key
254     /**
255      * Inline move columns
256     **/
257     $("#move_columns_anchor").live('click', function (e) {
258         e.preventDefault();
260         if ($(this).hasClass("move-active")) {
261             return;
262         }
264         /**
265          * @var    button_options  Object that stores the options passed to jQueryUI
266          *                          dialog
267          */
268         var button_options = {};
270         button_options[PMA_messages.strGo] = function (event) {
271             event.preventDefault();
272             var $msgbox = PMA_ajaxShowMessage();
273             var $this = $(this);
274             var $form = $this.find("form");
275             var serialized = $form.serialize();
277             // check if any columns were moved at all
278             if (serialized == $form.data("serialized-unmoved")) {
279                 PMA_ajaxRemoveMessage($msgbox);
280                 $this.dialog('close');
281                 return;
282             }
284             $.post($form.prop("action"), serialized + "&ajax_request=true", function (data) {
285                 if (data.success === false) {
286                     PMA_ajaxRemoveMessage($msgbox);
287                     $this
288                     .clone()
289                     .html(data.error)
290                     .dialog({
291                         title: $(this).prop("title"),
292                         height: 230,
293                         width: 900,
294                         modal: true,
295                         buttons: button_options_error
296                     }); // end dialog options
297                 } else {
298                     $('#fieldsForm ul.table-structure-actions').menuResizer('destroy');
299                     // sort the fields table
300                     var $fields_table = $("table#tablestructure tbody");
301                     // remove all existing rows and remember them
302                     var $rows = $fields_table.find("tr").remove();
303                     // loop through the correct order
304                     for (var i in data.columns) {
305                         var the_column = data.columns[i];
306                         var $the_row = $rows
307                             .find("input:checkbox[value=" + the_column + "]")
308                             .closest("tr");
309                         // append the row for this column to the table
310                         $fields_table.append($the_row);
311                     }
312                     var $firstrow = $fields_table.find("tr").eq(0);
313                     // Adjust the row numbers and colors
314                     for (var $row = $firstrow; $row.length > 0; $row = $row.next()) {
315                         $row
316                         .find('td:nth-child(2)')
317                         .text($row.index() + 1)
318                         .end()
319                         .removeClass("odd even")
320                         .addClass($row.index() % 2 === 0 ? "odd" : "even");
321                     }
322                     PMA_ajaxShowMessage(data.message);
323                     $this.dialog('close');
324                     $('#fieldsForm ul.table-structure-actions').menuResizer(PMA_tbl_structure_menu_resizer_callback);
325                 }
326             });
327         };
328         button_options[PMA_messages.strCancel] = function () {
329             $(this).dialog('close');
330         };
332         var button_options_error = {};
333         button_options_error[PMA_messages.strOK] = function () {
334             $(this).dialog('close').remove();
335         };
337         var columns = [];
339         $("#tablestructure tbody tr").each(function () {
340             var col_name = $(this).find("input:checkbox").eq(0).val();
341             var hidden_input = $("<input/>")
342                 .prop({
343                     name: "move_columns[]",
344                     type: "hidden"
345                 })
346                 .val(col_name);
347             columns[columns.length] = $("<li/>")
348                 .addClass("placeholderDrag")
349                 .text(col_name)
350                 .append(hidden_input);
351         });
353         var col_list = $("#move_columns_dialog ul")
354             .find("li").remove().end();
355         for (var i in columns) {
356             col_list.append(columns[i]);
357         }
358         col_list.sortable({
359             axis: 'y',
360             containment: $("#move_columns_dialog div")
361         }).disableSelection();
362         var $form = $("#move_columns_dialog form");
363         $form.data("serialized-unmoved", $form.serialize());
365         $("#move_columns_dialog").dialog({
366             modal: true,
367             buttons: button_options,
368             beforeClose: function () {
369                 $("#move_columns_anchor").removeClass("move-active");
370             }
371         });
372     });
376  * This function returns the horizontal space available for the menu in pixels.
377  * To calculate this value we start we the width of the main panel, then we
378  * substract the margin of the page content, then we substract any cellspacing
379  * that the table may have (original theme only) and finally we substract the
380  * width of all columns of the table except for the last one (which is where
381  * the menu will go). What we should end up with is the distance between the
382  * start of the last column on the table and the edge of the page, again this
383  * is the space available for the menu.
385  * In the case where the table cell where the menu will be displayed is already
386  * off-screen (the table is wider than the page), a negative value will be returned,
387  * but this will be treated as a zero by the menuResizer plugin.
389  * @return int
390  */
391 function PMA_tbl_structure_menu_resizer_callback() {
392     var pagewidth = $('body').width();
393     var $page = $('#page_content');
394     pagewidth -= $page.outerWidth(true) - $page.outerWidth();
395     var columnsWidth = 0;
396     var $columns = $('#tablestructure').find('tr:eq(1)').find('td,th');
397     $columns.not(':last').each(function () {
398         columnsWidth += $(this).outerWidth(true);
399     });
400     var totalCellSpacing = $('#tablestructure').width();
401     $columns.each(function () {
402         totalCellSpacing -= $(this).outerWidth(true);
403     });
404     return pagewidth - columnsWidth - totalCellSpacing - 15; // 15px extra margin
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     }));