makegrid.js 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  1. /* vim: set expandtab sw=4 ts=4 sts=4: */
  2. /**
  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
  10. *
  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
  16. */
  17. function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdit) {
  18. var g = {
  19. /***********
  20. * Constant
  21. ***********/
  22. minColWidth: 15,
  23. /***********
  24. * Variables, assigned with default value, changed later
  25. ***********/
  26. actionSpan: 5, // number of colspan in Actions header in a table
  27. tableCreateTime: null, // table creation time, used for saving column order and visibility to server, only available in "Browse tab"
  28. // Column reordering variables
  29. colOrder: [], // array of column order
  30. // Column visibility variables
  31. colVisib: [], // array of column visibility
  32. showAllColText: '', // string, text for "show all" button under column visibility list
  33. visibleHeadersCount: 0, // number of visible data headers
  34. // Table hint variables
  35. reorderHint: '', // string, hint for column reordering
  36. sortHint: '', // string, hint for column sorting
  37. markHint: '', // string, hint for column marking
  38. copyHint: '', // string, hint for copy column name
  39. showReorderHint: false,
  40. showSortHint: false,
  41. showMarkHint: false,
  42. // Grid editing
  43. isCellEditActive: false, // true if current focus is in edit cell
  44. isEditCellTextEditable: false, // true if current edit cell is editable in the text input box (not textarea)
  45. currentEditCell: null, // reference to <td> that currently being edited
  46. cellEditHint: '', // hint shown when doing grid edit
  47. gotoLinkText: '', // "Go to link" text
  48. wasEditedCellNull: false, // true if last value of the edited cell was NULL
  49. maxTruncatedLen: 0, // number of characters that can be displayed in a cell
  50. saveCellsAtOnce: false, // $cfg[saveCellsAtOnce]
  51. isCellEdited: false, // true if at least one cell has been edited
  52. saveCellWarning: '', // string, warning text when user want to leave a page with unsaved edited data
  53. lastXHR : null, // last XHR object used in AJAX request
  54. 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
  55. alertNonUnique: '', // string, alert shown when saving edited nonunique table
  56. // Common hidden inputs
  57. token: null,
  58. server: null,
  59. db: null,
  60. table: null,
  61. /************
  62. * Functions
  63. ************/
  64. /**
  65. * Start to resize column. Called when clicking on column separator.
  66. *
  67. * @param e event
  68. * @param obj dragged div object
  69. */
  70. dragStartRsz: function (e, obj) {
  71. var n = $(g.cRsz).find('div').index(obj); // get the index of separator (i.e., column index)
  72. $(obj).addClass('colborder_active');
  73. g.colRsz = {
  74. x0: e.pageX,
  75. n: n,
  76. obj: obj,
  77. objLeft: $(obj).position().left,
  78. objWidth: $(g.t).find('th.draggable:visible:eq(' + n + ') span').outerWidth()
  79. };
  80. $(document.body).css('cursor', 'col-resize').noSelect();
  81. if (g.isCellEditActive) {
  82. g.hideEditCell();
  83. }
  84. },
  85. /**
  86. * Start to reorder column. Called when clicking on table header.
  87. *
  88. * @param e event
  89. * @param obj table header object
  90. */
  91. dragStartReorder: function (e, obj) {
  92. // prepare the cCpy (column copy) and cPointer (column pointer) from the dragged column
  93. $(g.cCpy).text($(obj).text());
  94. var objPos = $(obj).position();
  95. $(g.cCpy).css({
  96. top: objPos.top + 20,
  97. left: objPos.left,
  98. height: $(obj).height(),
  99. width: $(obj).width()
  100. });
  101. $(g.cPointer).css({
  102. top: objPos.top
  103. });
  104. // get the column index, zero-based
  105. var n = g.getHeaderIdx(obj);
  106. g.colReorder = {
  107. x0: e.pageX,
  108. y0: e.pageY,
  109. n: n,
  110. newn: n,
  111. obj: obj,
  112. objTop: objPos.top,
  113. objLeft: objPos.left
  114. };
  115. $(document.body).css('cursor', 'move').noSelect();
  116. if (g.isCellEditActive) {
  117. g.hideEditCell();
  118. }
  119. },
  120. /**
  121. * Handle mousemove event when dragging.
  122. *
  123. * @param e event
  124. */
  125. dragMove: function (e) {
  126. if (g.colRsz) {
  127. var dx = e.pageX - g.colRsz.x0;
  128. if (g.colRsz.objWidth + dx > g.minColWidth) {
  129. $(g.colRsz.obj).css('left', g.colRsz.objLeft + dx + 'px');
  130. }
  131. } else if (g.colReorder) {
  132. // dragged column animation
  133. var dx = e.pageX - g.colReorder.x0;
  134. $(g.cCpy)
  135. .css('left', g.colReorder.objLeft + dx)
  136. .show();
  137. // pointer animation
  138. var hoveredCol = g.getHoveredCol(e);
  139. if (hoveredCol) {
  140. var newn = g.getHeaderIdx(hoveredCol);
  141. g.colReorder.newn = newn;
  142. if (newn != g.colReorder.n) {
  143. // show the column pointer in the right place
  144. var colPos = $(hoveredCol).position();
  145. var newleft = newn < g.colReorder.n ?
  146. colPos.left :
  147. colPos.left + $(hoveredCol).outerWidth();
  148. $(g.cPointer)
  149. .css({
  150. left: newleft,
  151. visibility: 'visible'
  152. });
  153. } else {
  154. // no movement to other column, hide the column pointer
  155. $(g.cPointer).css('visibility', 'hidden');
  156. }
  157. }
  158. }
  159. },
  160. /**
  161. * Stop the dragging action.
  162. *
  163. * @param e event
  164. */
  165. dragEnd: function (e) {
  166. if (g.colRsz) {
  167. var dx = e.pageX - g.colRsz.x0;
  168. var nw = g.colRsz.objWidth + dx;
  169. if (nw < g.minColWidth) {
  170. nw = g.minColWidth;
  171. }
  172. var n = g.colRsz.n;
  173. // do the resizing
  174. g.resize(n, nw);
  175. g.reposRsz();
  176. g.reposDrop();
  177. g.colRsz = false;
  178. $(g.cRsz).find('div').removeClass('colborder_active');
  179. if($('#sticky_columns').length !== 0) {
  180. rearrangeStickyColumns();
  181. }
  182. } else if (g.colReorder) {
  183. // shift columns
  184. if (g.colReorder.newn != g.colReorder.n) {
  185. g.shiftCol(g.colReorder.n, g.colReorder.newn);
  186. // assign new position
  187. var objPos = $(g.colReorder.obj).position();
  188. g.colReorder.objTop = objPos.top;
  189. g.colReorder.objLeft = objPos.left;
  190. g.colReorder.n = g.colReorder.newn;
  191. // send request to server to remember the column order
  192. if (g.tableCreateTime) {
  193. g.sendColPrefs();
  194. }
  195. g.refreshRestoreButton();
  196. }
  197. // animate new column position
  198. $(g.cCpy).stop(true, true)
  199. .animate({
  200. top: g.colReorder.objTop,
  201. left: g.colReorder.objLeft
  202. }, 'fast')
  203. .fadeOut();
  204. $(g.cPointer).css('visibility', 'hidden');
  205. g.colReorder = false;
  206. if($('#sticky_columns').length !== 0) {
  207. rearrangeStickyColumns();
  208. }
  209. }
  210. $(document.body).css('cursor', 'inherit').noSelect(false);
  211. },
  212. /**
  213. * Resize column n to new width "nw"
  214. *
  215. * @param n zero-based column index
  216. * @param nw new width of the column in pixel
  217. */
  218. resize: function (n, nw) {
  219. $(g.t).find('tr').each(function () {
  220. $(this).find('th.draggable:visible:eq(' + n + ') span,' +
  221. 'td:visible:eq(' + (g.actionSpan + n) + ') span')
  222. .css('width', nw);
  223. });
  224. },
  225. /**
  226. * Reposition column resize bars.
  227. */
  228. reposRsz: function () {
  229. $(g.cRsz).find('div').hide();
  230. var $firstRowCols = $(g.t).find('tr:first th.draggable:visible');
  231. var $resizeHandles = $(g.cRsz).find('div').removeClass('condition');
  232. $('table.pma_table').find('thead th:first').removeClass('before-condition');
  233. for (var n = 0, l = $firstRowCols.length; n < l; n++) {
  234. var $col = $($firstRowCols[n]);
  235. $($resizeHandles[n]).css('left', $col.position().left + $col.outerWidth(true))
  236. .show();
  237. if ($col.hasClass('condition')) {
  238. $($resizeHandles[n]).addClass('condition');
  239. if (n > 0) {
  240. $($resizeHandles[n - 1]).addClass('condition');
  241. }
  242. }
  243. }
  244. if ($($resizeHandles[0]).hasClass('condition')) {
  245. $('table.pma_table').find('thead th:first').addClass('before-condition');
  246. }
  247. $(g.cRsz).css('height', $(g.t).height());
  248. },
  249. /**
  250. * Shift column from index oldn to newn.
  251. *
  252. * @param oldn old zero-based column index
  253. * @param newn new zero-based column index
  254. */
  255. shiftCol: function (oldn, newn) {
  256. $(g.t).find('tr').each(function () {
  257. if (newn < oldn) {
  258. $(this).find('th.draggable:eq(' + newn + '),' +
  259. 'td:eq(' + (g.actionSpan + newn) + ')')
  260. .before($(this).find('th.draggable:eq(' + oldn + '),' +
  261. 'td:eq(' + (g.actionSpan + oldn) + ')'));
  262. } else {
  263. $(this).find('th.draggable:eq(' + newn + '),' +
  264. 'td:eq(' + (g.actionSpan + newn) + ')')
  265. .after($(this).find('th.draggable:eq(' + oldn + '),' +
  266. 'td:eq(' + (g.actionSpan + oldn) + ')'));
  267. }
  268. });
  269. // reposition the column resize bars
  270. g.reposRsz();
  271. // adjust the column visibility list
  272. if (newn < oldn) {
  273. $(g.cList).find('.lDiv div:eq(' + newn + ')')
  274. .before($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
  275. } else {
  276. $(g.cList).find('.lDiv div:eq(' + newn + ')')
  277. .after($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
  278. }
  279. // adjust the colOrder
  280. var tmp = g.colOrder[oldn];
  281. g.colOrder.splice(oldn, 1);
  282. g.colOrder.splice(newn, 0, tmp);
  283. // adjust the colVisib
  284. if (g.colVisib.length > 0) {
  285. tmp = g.colVisib[oldn];
  286. g.colVisib.splice(oldn, 1);
  287. g.colVisib.splice(newn, 0, tmp);
  288. }
  289. },
  290. /**
  291. * Find currently hovered table column's header (excluding actions column).
  292. *
  293. * @param e event
  294. * @return the hovered column's th object or undefined if no hovered column found.
  295. */
  296. getHoveredCol: function (e) {
  297. var hoveredCol;
  298. $headers = $(g.t).find('th.draggable:visible');
  299. $headers.each(function () {
  300. var left = $(this).offset().left;
  301. var right = left + $(this).outerWidth();
  302. if (left <= e.pageX && e.pageX <= right) {
  303. hoveredCol = this;
  304. }
  305. });
  306. return hoveredCol;
  307. },
  308. /**
  309. * Get a zero-based index from a <th class="draggable"> tag in a table.
  310. *
  311. * @param obj table header <th> object
  312. * @return zero-based index of the specified table header in the set of table headers (visible or not)
  313. */
  314. getHeaderIdx: function (obj) {
  315. return $(obj).parents('tr').find('th.draggable').index(obj);
  316. },
  317. /**
  318. * Reposition the columns back to normal order.
  319. */
  320. restoreColOrder: function () {
  321. // use insertion sort, since we already have shiftCol function
  322. for (var i = 1; i < g.colOrder.length; i++) {
  323. var x = g.colOrder[i];
  324. var j = i - 1;
  325. while (j >= 0 && x < g.colOrder[j]) {
  326. j--;
  327. }
  328. if (j != i - 1) {
  329. g.shiftCol(i, j + 1);
  330. }
  331. }
  332. if (g.tableCreateTime) {
  333. // send request to server to remember the column order
  334. g.sendColPrefs();
  335. }
  336. g.refreshRestoreButton();
  337. },
  338. /**
  339. * Send column preferences (column order and visibility) to the server.
  340. */
  341. sendColPrefs: function () {
  342. if ($(g.t).is('.ajax')) { // only send preferences if ajax class
  343. var post_params = {
  344. ajax_request: true,
  345. db: g.db,
  346. table: g.table,
  347. token: g.token,
  348. server: g.server,
  349. set_col_prefs: true,
  350. table_create_time: g.tableCreateTime
  351. };
  352. if (g.colOrder.length > 0) {
  353. $.extend(post_params, {col_order: g.colOrder.toString()});
  354. }
  355. if (g.colVisib.length > 0) {
  356. $.extend(post_params, {col_visib: g.colVisib.toString()});
  357. }
  358. $.post('sql.php', post_params, function (data) {
  359. if (data.success !== true) {
  360. var $temp_div = $(document.createElement('div'));
  361. $temp_div.html(data.error);
  362. $temp_div.addClass("error");
  363. PMA_ajaxShowMessage($temp_div, false);
  364. }
  365. });
  366. }
  367. },
  368. /**
  369. * Refresh restore button state.
  370. * Make restore button disabled if the table is similar with initial state.
  371. */
  372. refreshRestoreButton: function () {
  373. // check if table state is as initial state
  374. var isInitial = true;
  375. for (var i = 0; i < g.colOrder.length; i++) {
  376. if (g.colOrder[i] != i) {
  377. isInitial = false;
  378. break;
  379. }
  380. }
  381. // check if only one visible column left
  382. var isOneColumn = g.visibleHeadersCount == 1;
  383. // enable or disable restore button
  384. if (isInitial || isOneColumn) {
  385. $('div.restore_column').hide();
  386. } else {
  387. $('div.restore_column').show();
  388. }
  389. },
  390. /**
  391. * Update current hint using the boolean values (showReorderHint, showSortHint, etc.).
  392. *
  393. */
  394. updateHint: function () {
  395. var text = '';
  396. if (!g.colRsz && !g.colReorder) { // if not resizing or dragging
  397. if (g.visibleHeadersCount > 1) {
  398. g.showReorderHint = true;
  399. }
  400. if ($(t).find('th.marker').length > 0) {
  401. g.showMarkHint = true;
  402. }
  403. if (g.showSortHint && g.sortHint) {
  404. text += text.length > 0 ? '<br />' : '';
  405. text += '- ' + g.sortHint;
  406. }
  407. if (g.showMultiSortHint && g.strMultiSortHint) {
  408. text += text.length > 0 ? '<br />' : '';
  409. text += '- ' + g.strMultiSortHint;
  410. }
  411. if (g.showMarkHint && g.markHint
  412. && !g.showSortHint // we do not show mark hint, when sort hint is shown
  413. && g.showReorderHint && g.reorderHint
  414. ) {
  415. text += text.length > 0 ? '<br />' : '';
  416. text += '- ' + g.reorderHint;
  417. text += text.length > 0 ? '<br />' : '';
  418. text += '- ' + g.markHint;
  419. text += text.length > 0 ? '<br />' : '';
  420. text += '- ' + g.copyHint;
  421. }
  422. }
  423. return text;
  424. },
  425. /**
  426. * Toggle column's visibility.
  427. * After calling this function and it returns true, afterToggleCol() must be called.
  428. *
  429. * @return boolean True if the column is toggled successfully.
  430. */
  431. toggleCol: function (n) {
  432. if (g.colVisib[n]) {
  433. // can hide if more than one column is visible
  434. if (g.visibleHeadersCount > 1) {
  435. $(g.t).find('tr').each(function () {
  436. $(this).find('th.draggable:eq(' + n + '),' +
  437. 'td:eq(' + (g.actionSpan + n) + ')')
  438. .hide();
  439. });
  440. g.colVisib[n] = 0;
  441. $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', false);
  442. } else {
  443. // cannot hide, force the checkbox to stay checked
  444. $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', true);
  445. return false;
  446. }
  447. } else { // column n is not visible
  448. $(g.t).find('tr').each(function () {
  449. $(this).find('th.draggable:eq(' + n + '),' +
  450. 'td:eq(' + (g.actionSpan + n) + ')')
  451. .show();
  452. });
  453. g.colVisib[n] = 1;
  454. $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', true);
  455. }
  456. return true;
  457. },
  458. /**
  459. * This must be called if toggleCol() returns is true.
  460. *
  461. * This function is separated from toggleCol because, sometimes, we want to toggle
  462. * some columns together at one time and do just one adjustment after it, e.g. in showAllColumns().
  463. */
  464. afterToggleCol: function () {
  465. // some adjustments after hiding column
  466. g.reposRsz();
  467. g.reposDrop();
  468. g.sendColPrefs();
  469. // check visible first row headers count
  470. g.visibleHeadersCount = $(g.t).find('tr:first th.draggable:visible').length;
  471. g.refreshRestoreButton();
  472. },
  473. /**
  474. * Show columns' visibility list.
  475. *
  476. * @param obj The drop down arrow of column visibility list
  477. */
  478. showColList: function (obj) {
  479. // only show when not resizing or reordering
  480. if (!g.colRsz && !g.colReorder) {
  481. var pos = $(obj).position();
  482. // check if the list position is too right
  483. if (pos.left + $(g.cList).outerWidth(true) > $(document).width()) {
  484. pos.left = $(document).width() - $(g.cList).outerWidth(true);
  485. }
  486. $(g.cList).css({
  487. left: pos.left,
  488. top: pos.top + $(obj).outerHeight(true)
  489. })
  490. .show();
  491. $(obj).addClass('coldrop-hover');
  492. }
  493. },
  494. /**
  495. * Hide columns' visibility list.
  496. */
  497. hideColList: function () {
  498. $(g.cList).hide();
  499. $(g.cDrop).find('.coldrop-hover').removeClass('coldrop-hover');
  500. },
  501. /**
  502. * Reposition the column visibility drop-down arrow.
  503. */
  504. reposDrop: function () {
  505. var $th = $(t).find('th:not(.draggable)');
  506. for (var i = 0; i < $th.length; i++) {
  507. var $cd = $(g.cDrop).find('div:eq(' + i + ')'); // column drop-down arrow
  508. var pos = $($th[i]).position();
  509. $cd.css({
  510. left: pos.left + $($th[i]).width() - $cd.width(),
  511. top: pos.top
  512. });
  513. }
  514. },
  515. /**
  516. * Show all hidden columns.
  517. */
  518. showAllColumns: function () {
  519. for (var i = 0; i < g.colVisib.length; i++) {
  520. if (!g.colVisib[i]) {
  521. g.toggleCol(i);
  522. }
  523. }
  524. g.afterToggleCol();
  525. },
  526. /**
  527. * Show edit cell, if it can be shown
  528. *
  529. * @param cell <td> element to be edited
  530. */
  531. showEditCell: function (cell) {
  532. if ($(cell).is('.grid_edit') &&
  533. !g.colRsz && !g.colReorder)
  534. {
  535. if (!g.isCellEditActive) {
  536. var $cell = $(cell);
  537. // remove all edit area and hide it
  538. $(g.cEdit).find('.edit_area').empty().hide();
  539. // reposition the cEdit element
  540. $(g.cEdit).css({
  541. top: $cell.position().top,
  542. left: $cell.position().left
  543. })
  544. .show()
  545. .find('.edit_box')
  546. .css({
  547. width: $cell.outerWidth(),
  548. height: $cell.outerHeight()
  549. });
  550. // fill the cell edit with text from <td>
  551. var value = PMA_getCellValue(cell);
  552. $(g.cEdit).find('.edit_box').val(value);
  553. g.currentEditCell = cell;
  554. $(g.cEdit).find('.edit_box').focus();
  555. $(g.cEdit).find('*').removeProp('disabled');
  556. }
  557. }
  558. },
  559. /**
  560. * Remove edit cell and the edit area, if it is shown.
  561. *
  562. * @param force Optional, force to hide edit cell without saving edited field.
  563. * @param data Optional, data from the POST AJAX request to save the edited field
  564. * or just specify "true", if we want to replace the edited field with the new value.
  565. * @param field Optional, the edited <td>. If not specified, the function will
  566. * use currently edited <td> from g.currentEditCell.
  567. */
  568. hideEditCell: function (force, data, field) {
  569. if (g.isCellEditActive && !force) {
  570. // cell is being edited, save or post the edited data
  571. g.saveOrPostEditedCell();
  572. return;
  573. }
  574. // cancel any previous request
  575. if (g.lastXHR !== null) {
  576. g.lastXHR.abort();
  577. g.lastXHR = null;
  578. }
  579. if (data) {
  580. if (g.currentEditCell) { // save value of currently edited cell
  581. // replace current edited field with the new value
  582. var $this_field = $(g.currentEditCell);
  583. var is_null = $this_field.data('value') === null;
  584. if (is_null) {
  585. $this_field.find('span').html('NULL');
  586. $this_field.addClass('null');
  587. } else {
  588. $this_field.removeClass('null');
  589. var new_html = data.isNeedToRecheck
  590. ? data.truncatableFieldValue
  591. : $this_field.data('value');
  592. //remove decimal places if column type not supported
  593. if (($this_field.attr('data-decimals') == 0) && ( $this_field.attr('data-type').indexOf('time') != -1)) {
  594. new_html = new_html.substring(0, new_html.indexOf('.'));
  595. }
  596. //remove addtional decimal places
  597. if (($this_field.attr('data-decimals') > 0) && ( $this_field.attr('data-type').indexOf('time') != -1)){
  598. new_html = new_html.substring(0, new_html.length - (6 - $this_field.attr('data-decimals')));
  599. }
  600. if ($this_field.is('.truncated')) {
  601. if (new_html.length > g.maxTruncatedLen) {
  602. new_html = new_html.substring(0, g.maxTruncatedLen) + '...';
  603. }
  604. }
  605. $this_field.find('span').text(new_html);
  606. }
  607. if ($this_field.is('.bit')) {
  608. $this_field.find('span').text($this_field.data('value'));
  609. }
  610. }
  611. if (data.transformations !== undefined) {
  612. $.each(data.transformations, function (cell_index, value) {
  613. var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
  614. $this_field.find('span').html(value);
  615. });
  616. }
  617. if (data.relations !== undefined) {
  618. $.each(data.relations, function (cell_index, value) {
  619. var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
  620. $this_field.find('span').html(value);
  621. });
  622. }
  623. // refresh the grid
  624. g.reposRsz();
  625. g.reposDrop();
  626. }
  627. // hide the cell editing area
  628. $(g.cEdit).hide();
  629. $(g.cEdit).find('.edit_box').blur();
  630. g.isCellEditActive = false;
  631. g.currentEditCell = null;
  632. // destroy datepicker in edit area, if exist
  633. var $dp = $(g.cEdit).find('.hasDatepicker');
  634. if ($dp.length > 0) {
  635. $dp.datepicker('destroy');
  636. // change the cursor in edit box back to normal
  637. // (the cursor become a hand pointer when we add datepicker)
  638. $(g.cEdit).find('.edit_box').css('cursor', 'inherit');
  639. }
  640. },
  641. /**
  642. * Show drop-down edit area when edit cell is focused.
  643. */
  644. showEditArea: function () {
  645. if (!g.isCellEditActive) { // make sure the edit area has not been shown
  646. g.isCellEditActive = true;
  647. g.isEditCellTextEditable = false;
  648. /**
  649. * @var $td current edited cell
  650. */
  651. var $td = $(g.currentEditCell);
  652. /**
  653. * @var $editArea the editing area
  654. */
  655. var $editArea = $(g.cEdit).find('.edit_area');
  656. /**
  657. * @var where_clause WHERE clause for the edited cell
  658. */
  659. var where_clause = $td.parent('tr').find('.where_clause').val();
  660. /**
  661. * @var field_name String containing the name of this field.
  662. * @see getFieldName()
  663. */
  664. var field_name = getFieldName($td);
  665. /**
  666. * @var relation_curr_value String current value of the field (for fields that are foreign keyed).
  667. */
  668. var relation_curr_value = $td.text();
  669. /**
  670. * @var relation_key_or_display_column String relational key if in 'Relational display column' mode,
  671. * relational display column if in 'Relational key' mode (for fields that are foreign keyed).
  672. */
  673. var relation_key_or_display_column = $td.find('a').attr('title');
  674. /**
  675. * @var curr_value String current value of the field (for fields that are of type enum or set).
  676. */
  677. var curr_value = $td.find('span').text();
  678. // empty all edit area, then rebuild it based on $td classes
  679. $editArea.empty();
  680. $editArea.removeClass('edit_area_right');
  681. // add show data row link if the data resulted by 'browse distinct values' in table structure
  682. if ($td.find('input').hasClass('data_browse_link')) {
  683. var showDataRowLink = document.createElement('div');
  684. showDataRowLink.className = 'goto_link';
  685. $(showDataRowLink).append("<a href='" + $td.find('.data_browse_link').val() + "'>" + g.showDataRowLinkText + "</a>");
  686. $editArea.append(showDataRowLink);
  687. }
  688. // add goto link, if this cell contains a link
  689. if ($td.find('a').length > 0) {
  690. var gotoLink = document.createElement('div');
  691. gotoLink.className = 'goto_link';
  692. $(gotoLink).append(g.gotoLinkText + ' ').append($td.find('a').clone());
  693. $editArea.append(gotoLink);
  694. }
  695. g.wasEditedCellNull = false;
  696. if ($td.is(':not(.not_null)')) {
  697. // append a null checkbox
  698. $editArea.append('<div class="null_div">Null:<input type="checkbox"></div>');
  699. var $checkbox = $editArea.find('.null_div input');
  700. // check if current <td> is NULL
  701. if ($td.is('.null')) {
  702. $checkbox.prop('checked', true);
  703. g.wasEditedCellNull = true;
  704. }
  705. // if the select/editor is changed un-check the 'checkbox_null_<field_name>_<row_index>'.
  706. if ($td.is('.enum, .set')) {
  707. $editArea.find('select').live('change', function (e) {
  708. $checkbox.prop('checked', false);
  709. });
  710. } else if ($td.is('.relation')) {
  711. $editArea.find('select').live('change', function (e) {
  712. $checkbox.prop('checked', false);
  713. });
  714. $editArea.find('.browse_foreign').live('click', function (e) {
  715. $checkbox.prop('checked', false);
  716. });
  717. } else {
  718. $(g.cEdit).find('.edit_box').live('keypress change', function (e) {
  719. $checkbox.prop('checked', false);
  720. });
  721. // Capture ctrl+v (on IE and Chrome)
  722. $(g.cEdit).find('.edit_box').live('keydown', function (e) {
  723. if (e.ctrlKey && e.which == 86) {
  724. $checkbox.prop('checked', false);
  725. }
  726. });
  727. $editArea.find('textarea').live('keydown', function (e) {
  728. $checkbox.prop('checked', false);
  729. });
  730. }
  731. // if null checkbox is clicked empty the corresponding select/editor.
  732. $checkbox.click(function (e) {
  733. if ($td.is('.enum')) {
  734. $editArea.find('select').val('');
  735. } else if ($td.is('.set')) {
  736. $editArea.find('select').find('option').each(function () {
  737. var $option = $(this);
  738. $option.prop('selected', false);
  739. });
  740. } else if ($td.is('.relation')) {
  741. // if the dropdown is there to select the foreign value
  742. if ($editArea.find('select').length > 0) {
  743. $editArea.find('select').val('');
  744. }
  745. } else {
  746. $editArea.find('textarea').val('');
  747. }
  748. $(g.cEdit).find('.edit_box').val('');
  749. });
  750. }
  751. //reset the position of the edit_area div after closing datetime picker
  752. $('.edit_area').css({'top' :'0','position':''});
  753. if ($td.is('.relation')) {
  754. //handle relations
  755. $editArea.addClass('edit_area_loading');
  756. // initialize the original data
  757. $td.data('original_data', null);
  758. /**
  759. * @var post_params Object containing parameters for the POST request
  760. */
  761. var post_params = {
  762. 'ajax_request' : true,
  763. 'get_relational_values' : true,
  764. 'server' : g.server,
  765. 'db' : g.db,
  766. 'table' : g.table,
  767. 'column' : field_name,
  768. 'token' : g.token,
  769. 'curr_value' : relation_curr_value,
  770. 'relation_key_or_display_column' : relation_key_or_display_column
  771. };
  772. g.lastXHR = $.post('sql.php', post_params, function (data) {
  773. g.lastXHR = null;
  774. $editArea.removeClass('edit_area_loading');
  775. if ($(data.dropdown).is('select')) {
  776. // save original_data
  777. var value = $(data.dropdown).val();
  778. $td.data('original_data', value);
  779. // update the text input field, in case where the "Relational display column" is checked
  780. $(g.cEdit).find('.edit_box').val(value);
  781. }
  782. $editArea.append(data.dropdown);
  783. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  784. // for 'Browse foreign values' options,
  785. // hide the value next to 'Browse foreign values' link
  786. $editArea.find('span.curr_value').hide();
  787. // handle update for new values selected from new window
  788. $editArea.find('span.curr_value').change(function () {
  789. $(g.cEdit).find('.edit_box').val($(this).text());
  790. });
  791. }); // end $.post()
  792. $editArea.show();
  793. $editArea.find('select').live('change', function (e) {
  794. $(g.cEdit).find('.edit_box').val($(this).val());
  795. });
  796. g.isEditCellTextEditable = true;
  797. }
  798. else if ($td.is('.enum')) {
  799. //handle enum fields
  800. $editArea.addClass('edit_area_loading');
  801. /**
  802. * @var post_params Object containing parameters for the POST request
  803. */
  804. var post_params = {
  805. 'ajax_request' : true,
  806. 'get_enum_values' : true,
  807. 'server' : g.server,
  808. 'db' : g.db,
  809. 'table' : g.table,
  810. 'column' : field_name,
  811. 'token' : g.token,
  812. 'curr_value' : curr_value
  813. };
  814. g.lastXHR = $.post('sql.php', post_params, function (data) {
  815. g.lastXHR = null;
  816. $editArea.removeClass('edit_area_loading');
  817. $editArea.append(data.dropdown);
  818. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  819. }); // end $.post()
  820. $editArea.show();
  821. $editArea.find('select').live('change', function (e) {
  822. $(g.cEdit).find('.edit_box').val($(this).val());
  823. });
  824. }
  825. else if ($td.is('.set')) {
  826. //handle set fields
  827. $editArea.addClass('edit_area_loading');
  828. /**
  829. * @var post_params Object containing parameters for the POST request
  830. */
  831. var post_params = {
  832. 'ajax_request' : true,
  833. 'get_set_values' : true,
  834. 'server' : g.server,
  835. 'db' : g.db,
  836. 'table' : g.table,
  837. 'column' : field_name,
  838. 'token' : g.token,
  839. 'curr_value' : curr_value
  840. };
  841. g.lastXHR = $.post('sql.php', post_params, function (data) {
  842. g.lastXHR = null;
  843. $editArea.removeClass('edit_area_loading');
  844. $editArea.append(data.select);
  845. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  846. }); // end $.post()
  847. $editArea.show();
  848. $editArea.find('select').live('change', function (e) {
  849. $(g.cEdit).find('.edit_box').val($(this).val());
  850. });
  851. }
  852. else if ($td.is('.truncated, .transformed')) {
  853. if ($td.is('.to_be_saved')) { // cell has been edited
  854. var value = $td.data('value');
  855. $(g.cEdit).find('.edit_box').val(value);
  856. $editArea.append('<textarea></textarea>');
  857. $editArea.find('textarea')
  858. .val(value)
  859. .live('keyup', function (e) {
  860. $(g.cEdit).find('.edit_box').val($(this).val());
  861. });
  862. $(g.cEdit).find('.edit_box').live('keyup', function (e) {
  863. $editArea.find('textarea').val($(this).val());
  864. });
  865. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  866. } else {
  867. //handle truncated/transformed values values
  868. $editArea.addClass('edit_area_loading');
  869. // initialize the original data
  870. $td.data('original_data', null);
  871. /**
  872. * @var sql_query String containing the SQL query used to retrieve value of truncated/transformed data
  873. */
  874. var sql_query = 'SELECT `' + field_name + '` FROM `' + g.table + '` WHERE ' + PMA_urldecode(where_clause);
  875. // Make the Ajax call and get the data, wrap it and insert it
  876. g.lastXHR = $.post('sql.php', {
  877. 'token' : g.token,
  878. 'server' : g.server,
  879. 'db' : g.db,
  880. 'ajax_request' : true,
  881. 'sql_query' : sql_query,
  882. 'grid_edit' : true
  883. }, function (data) {
  884. g.lastXHR = null;
  885. $editArea.removeClass('edit_area_loading');
  886. if (data.success === true) {
  887. if ($td.is('.truncated')) {
  888. // get the truncated data length
  889. g.maxTruncatedLen = $(g.currentEditCell).text().length - 3;
  890. }
  891. $td.data('original_data', data.value);
  892. $(g.cEdit).find('.edit_box').val(data.value);
  893. $editArea.append('<textarea></textarea>');
  894. $editArea.find('textarea')
  895. .val(data.value)
  896. .live('keyup', function (e) {
  897. $(g.cEdit).find('.edit_box').val($(this).val());
  898. });
  899. $(g.cEdit).find('.edit_box').live('keyup', function (e) {
  900. $editArea.find('textarea').val($(this).val());
  901. });
  902. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  903. } else {
  904. PMA_ajaxShowMessage(data.error, false);
  905. }
  906. }); // end $.post()
  907. $editArea.show();
  908. }
  909. g.isEditCellTextEditable = true;
  910. } else if ($td.is('.timefield, .datefield, .datetimefield, .timestampfield')) {
  911. var $input_field = $(g.cEdit).find('.edit_box');
  912. // remember current datetime value in $input_field, if it is not null
  913. var is_null = $td.is('.null');
  914. var current_datetime_value = !is_null ? $input_field.val() : '';
  915. var showMillisec = false;
  916. var showMicrosec = false;
  917. var timeFormat = 'HH:mm:ss';
  918. // check for decimal places of seconds
  919. if (($td.attr('data-decimals') > 0) && ($td.attr('data-type').indexOf('time') != -1)){
  920. showMillisec = true;
  921. timeFormat = 'HH:mm:ss.lc';
  922. if ($td.attr('data-decimals') > 3) {
  923. showMicrosec = true;
  924. }
  925. }
  926. // add datetime picker
  927. PMA_addDatepicker($input_field, $td.attr('data-type'), {
  928. showMillisec: showMillisec,
  929. showMicrosec: showMicrosec,
  930. timeFormat: timeFormat
  931. });
  932. $input_field.datepicker("show");
  933. //move ui-datepicker-div inside cEdit div
  934. var datepicker_div = $('#ui-datepicker-div');
  935. datepicker_div.css({'top': 0, 'left': 0, 'position': 'relative'});
  936. $('.cEdit').append(datepicker_div);
  937. var edit_area_top = $('#ui-datepicker-div').height()+32;
  938. $('.edit_area').css({'top' : edit_area_top+'px', 'position': 'absolute'});
  939. if(is_null){
  940. $('.edit_area').hide();
  941. }
  942. // cancel any click on the datepicker element
  943. $editArea.find('> *').click(function (e) {
  944. e.stopPropagation();
  945. });
  946. } else {
  947. g.isEditCellTextEditable = true;
  948. // only append edit area hint if there is a null checkbox
  949. if ($editArea.children().length > 0) {
  950. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  951. }
  952. }
  953. if ($(g.cEdit).offset().left + $editArea.outerWidth() > $(document.body).width()) {
  954. $editArea.addClass('edit_area_right');
  955. $editArea.css('top','');
  956. }
  957. if ($editArea.children().length > 0 && !is_null) {
  958. $editArea.show();
  959. }
  960. }
  961. },
  962. /**
  963. * Post the content of edited cell.
  964. */
  965. postEditedCell: function () {
  966. if (g.isSaving) {
  967. return;
  968. }
  969. g.isSaving = true;
  970. /**
  971. * @var relation_fields Array containing the name/value pairs of relational fields
  972. */
  973. var relation_fields = {};
  974. /**
  975. * @var relational_display string 'K' if relational key, 'D' if relational display column
  976. */
  977. var relational_display = $("#relational_display_K").prop('checked') ? 'K' : 'D';
  978. /**
  979. * @var transform_fields Array containing the name/value pairs for transformed fields
  980. */
  981. var transform_fields = {};
  982. /**
  983. * @var transformation_fields Boolean, if there are any transformed fields in the edited cells
  984. */
  985. var transformation_fields = false;
  986. /**
  987. * @var full_sql_query String containing the complete SQL query to update this table
  988. */
  989. var full_sql_query = '';
  990. /**
  991. * @var rel_fields_list String, url encoded representation of {@link relations_fields}
  992. */
  993. var rel_fields_list = '';
  994. /**
  995. * @var transform_fields_list String, url encoded representation of {@link transform_fields}
  996. */
  997. var transform_fields_list = '';
  998. /**
  999. * @var where_clause Array containing where clause for updated fields
  1000. */
  1001. var full_where_clause = [];
  1002. /**
  1003. * @var is_unique Boolean, whether the rows in this table is unique or not
  1004. */
  1005. var is_unique = $('td.edit_row_anchor').is('.nonunique') ? 0 : 1;
  1006. /**
  1007. * multi edit variables
  1008. */
  1009. var me_fields_name = [];
  1010. var me_fields_type = [];
  1011. var me_fields = [];
  1012. var me_fields_null = [];
  1013. // alert user if edited table is not unique
  1014. if (!is_unique) {
  1015. alert(g.alertNonUnique);
  1016. }
  1017. // loop each edited row
  1018. $('td.to_be_saved').parents('tr').each(function () {
  1019. var $tr = $(this);
  1020. var where_clause = $tr.find('.where_clause').val();
  1021. full_where_clause.push(PMA_urldecode(where_clause));
  1022. var condition_array = jQuery.parseJSON($tr.find('.condition_array').val());
  1023. /**
  1024. * multi edit variables, for current row
  1025. * @TODO array indices are still not correct, they should be md5 of field's name
  1026. */
  1027. var fields_name = [];
  1028. var fields_type = [];
  1029. var fields = [];
  1030. var fields_null = [];
  1031. // loop each edited cell in a row
  1032. $tr.find('.to_be_saved').each(function () {
  1033. /**
  1034. * @var $this_field Object referring to the td that is being edited
  1035. */
  1036. var $this_field = $(this);
  1037. /**
  1038. * @var field_name String containing the name of this field.
  1039. * @see getFieldName()
  1040. */
  1041. var field_name = getFieldName($this_field);
  1042. /**
  1043. * @var this_field_params Array temporary storage for the name/value of current field
  1044. */
  1045. var this_field_params = {};
  1046. if ($this_field.is('.transformed')) {
  1047. transformation_fields = true;
  1048. }
  1049. this_field_params[field_name] = $this_field.data('value');
  1050. /**
  1051. * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
  1052. */
  1053. var is_null = this_field_params[field_name] === null;
  1054. fields_name.push(field_name);
  1055. if (is_null) {
  1056. fields_null.push('on');
  1057. fields.push('');
  1058. } else {
  1059. if ($this_field.is('.bit')) {
  1060. fields_type.push('bit');
  1061. }
  1062. fields_null.push('');
  1063. fields.push($this_field.data('value'));
  1064. var cell_index = $this_field.index('.to_be_saved');
  1065. if ($this_field.is(":not(.relation, .enum, .set, .bit)")) {
  1066. if ($this_field.is('.transformed')) {
  1067. transform_fields[cell_index] = {};
  1068. $.extend(transform_fields[cell_index], this_field_params);
  1069. }
  1070. } else if ($this_field.is('.relation')) {
  1071. relation_fields[cell_index] = {};
  1072. $.extend(relation_fields[cell_index], this_field_params);
  1073. }
  1074. }
  1075. // check if edited field appears in WHERE clause
  1076. if (where_clause.indexOf(PMA_urlencode(field_name)) > -1) {
  1077. var field_str = '`' + g.table + '`.' + '`' + field_name + '`';
  1078. for (var field in condition_array) {
  1079. if (field.indexOf(field_str) > -1) {
  1080. condition_array[field] = is_null ? 'IS NULL' : "= '" + this_field_params[field_name].replace(/'/g, "''") + "'";
  1081. break;
  1082. }
  1083. }
  1084. }
  1085. }); // end of loop for every edited cells in a row
  1086. // save new_clause
  1087. var new_clause = '';
  1088. for (var field in condition_array) {
  1089. new_clause += field + ' ' + condition_array[field] + ' AND ';
  1090. }
  1091. new_clause = new_clause.substring(0, new_clause.length - 5); // remove the last AND
  1092. new_clause = PMA_urlencode(new_clause);
  1093. $tr.data('new_clause', new_clause);
  1094. // save condition_array
  1095. $tr.find('.condition_array').val(JSON.stringify(condition_array));
  1096. me_fields_name.push(fields_name);
  1097. me_fields_type.push(fields_type);
  1098. me_fields.push(fields);
  1099. me_fields_null.push(fields_null);
  1100. }); // end of loop for every edited rows
  1101. rel_fields_list = $.param(relation_fields);
  1102. transform_fields_list = $.param(transform_fields);
  1103. // Make the Ajax post after setting all parameters
  1104. /**
  1105. * @var post_params Object containing parameters for the POST request
  1106. */
  1107. var post_params = {'ajax_request' : true,
  1108. 'sql_query' : full_sql_query,
  1109. 'token' : g.token,
  1110. 'server' : g.server,
  1111. 'db' : g.db,
  1112. 'table' : g.table,
  1113. 'clause_is_unique' : is_unique,
  1114. 'where_clause' : full_where_clause,
  1115. 'fields[multi_edit]' : me_fields,
  1116. 'fields_name[multi_edit]' : me_fields_name,
  1117. 'fields_type[multi_edit]' : me_fields_type,
  1118. 'fields_null[multi_edit]' : me_fields_null,
  1119. 'rel_fields_list' : rel_fields_list,
  1120. 'do_transformations' : transformation_fields,
  1121. 'transform_fields_list' : transform_fields_list,
  1122. 'relational_display' : relational_display,
  1123. 'goto' : 'sql.php',
  1124. 'submit_type' : 'save'
  1125. };
  1126. if (!g.saveCellsAtOnce) {
  1127. $(g.cEdit).find('*').prop('disabled', true);
  1128. $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
  1129. } else {
  1130. $('div.save_edited').addClass('saving_edited_data')
  1131. .find('input').prop('disabled', true); // disable the save button
  1132. }
  1133. $.ajax({
  1134. type: 'POST',
  1135. url: 'tbl_replace.php',
  1136. data: post_params,
  1137. success:
  1138. function (data) {
  1139. g.isSaving = false;
  1140. if (!g.saveCellsAtOnce) {
  1141. $(g.cEdit).find('*').removeProp('disabled');
  1142. $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
  1143. } else {
  1144. $('div.save_edited').removeClass('saving_edited_data')
  1145. .find('input').removeProp('disabled'); // enable the save button back
  1146. }
  1147. if (data.success === true) {
  1148. PMA_ajaxShowMessage(data.message);
  1149. // update where_clause related data in each edited row
  1150. $('td.to_be_saved').parents('tr').each(function () {
  1151. var new_clause = $(this).data('new_clause');
  1152. var $where_clause = $(this).find('.where_clause');
  1153. var old_clause = $where_clause.val();
  1154. var decoded_old_clause = PMA_urldecode(old_clause);
  1155. var decoded_new_clause = PMA_urldecode(new_clause);
  1156. $where_clause.val(new_clause);
  1157. // update Edit, Copy, and Delete links also
  1158. $(this).find('a').each(function () {
  1159. $(this).attr('href', $(this).attr('href').replace(old_clause, new_clause));
  1160. // update delete confirmation in Delete link
  1161. if ($(this).attr('href').indexOf('DELETE') > -1) {
  1162. $(this).removeAttr('onclick')
  1163. .unbind('click')
  1164. .bind('click', function () {
  1165. return confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' +
  1166. decoded_new_clause + (is_unique ? '' : ' LIMIT 1'));
  1167. });
  1168. }
  1169. });
  1170. // update the multi edit checkboxes
  1171. $(this).find('input[type=checkbox]').each(function () {
  1172. var $checkbox = $(this);
  1173. var checkbox_name = $checkbox.attr('name');
  1174. var checkbox_value = $checkbox.val();
  1175. $checkbox.attr('name', checkbox_name.replace(old_clause, new_clause));
  1176. $checkbox.val(checkbox_value.replace(decoded_old_clause, decoded_new_clause));
  1177. });
  1178. });
  1179. // update the display of executed SQL query command
  1180. if (typeof data.sql_query != 'undefined') {
  1181. //extract query box
  1182. var $result_query = $($.parseHTML(data.sql_query));
  1183. var sqlOuter = $result_query.find('.sqlOuter').wrap('<p>').parent().html();
  1184. var tools = $result_query.find('.tools').wrap('<p>').parent().html();
  1185. // sqlOuter and tools will not be present if 'Show SQL queries' configuration is off
  1186. if (typeof sqlOuter != 'undefined' && typeof tools != 'undefined') {
  1187. // If two query box exists update query in second else add a second box
  1188. if ($('#result_query').find('div.sqlOuter').length > 1) {
  1189. $('#result_query').children(":nth-child(4)").remove();
  1190. $('#result_query').children(":nth-child(4)").remove();
  1191. $('#result_query').append(sqlOuter + tools);
  1192. } else {
  1193. $('#result_query').append(sqlOuter + tools);
  1194. }
  1195. PMA_highlightSQL($('#result_query'));
  1196. }
  1197. }
  1198. // hide and/or update the successfully saved cells
  1199. g.hideEditCell(true, data);
  1200. // remove the "Save edited cells" button
  1201. $('div.save_edited').hide();
  1202. // update saved fields
  1203. $(g.t).find('.to_be_saved')
  1204. .removeClass('to_be_saved')
  1205. .data('value', null)
  1206. .data('original_data', null);
  1207. g.isCellEdited = false;
  1208. } else {
  1209. PMA_ajaxShowMessage(data.error, false);
  1210. }
  1211. }
  1212. }); // end $.ajax()
  1213. },
  1214. /**
  1215. * Save edited cell, so it can be posted later.
  1216. */
  1217. saveEditedCell: function () {
  1218. /**
  1219. * @var $this_field Object referring to the td that is being edited
  1220. */
  1221. var $this_field = $(g.currentEditCell);
  1222. var $test_element = ''; // to test the presence of a element
  1223. var need_to_post = false;
  1224. /**
  1225. * @var field_name String containing the name of this field.
  1226. * @see getFieldName()
  1227. */
  1228. var field_name = getFieldName($this_field);
  1229. /**
  1230. * @var this_field_params Array temporary storage for the name/value of current field
  1231. */
  1232. var this_field_params = {};
  1233. /**
  1234. * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
  1235. */
  1236. var is_null = $(g.cEdit).find('input:checkbox').is(':checked');
  1237. var value;
  1238. if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
  1239. // the edit area is still loading (retrieving cell data), no need to post
  1240. need_to_post = false;
  1241. } else if (is_null) {
  1242. if (!g.wasEditedCellNull) {
  1243. this_field_params[field_name] = null;
  1244. need_to_post = true;
  1245. }
  1246. } else {
  1247. if ($this_field.is('.bit')) {
  1248. this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
  1249. } else if ($this_field.is('.set')) {
  1250. $test_element = $(g.cEdit).find('select');
  1251. this_field_params[field_name] = $test_element.map(function () {
  1252. return $(this).val();
  1253. }).get().join(",");
  1254. } else if ($this_field.is('.relation, .enum')) {
  1255. // for relation and enumeration, take the results from edit box value,
  1256. // because selected value from drop-down, new window or multiple
  1257. // selection list will always be updated to the edit box
  1258. this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
  1259. } else {
  1260. this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
  1261. }
  1262. if (g.wasEditedCellNull || this_field_params[field_name] != PMA_getCellValue(g.currentEditCell)) {
  1263. need_to_post = true;
  1264. }
  1265. }
  1266. if (need_to_post) {
  1267. $(g.currentEditCell).addClass('to_be_saved')
  1268. .data('value', this_field_params[field_name]);
  1269. if (g.saveCellsAtOnce) {
  1270. $('div.save_edited').show();
  1271. }
  1272. g.isCellEdited = true;
  1273. }
  1274. return need_to_post;
  1275. },
  1276. /**
  1277. * Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
  1278. */
  1279. saveOrPostEditedCell: function () {
  1280. var saved = g.saveEditedCell();
  1281. if (!g.saveCellsAtOnce) {
  1282. if (saved) {
  1283. g.postEditedCell();
  1284. } else {
  1285. g.hideEditCell(true);
  1286. }
  1287. } else {
  1288. if (saved) {
  1289. g.hideEditCell(true, true);
  1290. } else {
  1291. g.hideEditCell(true);
  1292. }
  1293. }
  1294. },
  1295. /**
  1296. * Initialize column resize feature.
  1297. */
  1298. initColResize: function () {
  1299. // create column resizer div
  1300. g.cRsz = document.createElement('div');
  1301. g.cRsz.className = 'cRsz';
  1302. // get data columns in the first row of the table
  1303. var $firstRowCols = $(g.t).find('tr:first th.draggable');
  1304. // create column borders
  1305. $firstRowCols.each(function () {
  1306. var cb = document.createElement('div'); // column border
  1307. $(cb).addClass('colborder')
  1308. .mousedown(function (e) {
  1309. g.dragStartRsz(e, this);
  1310. });
  1311. $(g.cRsz).append(cb);
  1312. });
  1313. g.reposRsz();
  1314. // attach to global div
  1315. $(g.gDiv).prepend(g.cRsz);
  1316. },
  1317. /**
  1318. * Initialize column reordering feature.
  1319. */
  1320. initColReorder: function () {
  1321. g.cCpy = document.createElement('div'); // column copy, to store copy of dragged column header
  1322. g.cPointer = document.createElement('div'); // column pointer, used when reordering column
  1323. // adjust g.cCpy
  1324. g.cCpy.className = 'cCpy';
  1325. $(g.cCpy).hide();
  1326. // adjust g.cPointer
  1327. g.cPointer.className = 'cPointer';
  1328. $(g.cPointer).css('visibility', 'hidden'); // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
  1329. // assign column reordering hint
  1330. g.reorderHint = PMA_messages.strColOrderHint;
  1331. // get data columns in the first row of the table
  1332. var $firstRowCols = $(g.t).find('tr:first th.draggable');
  1333. // initialize column order
  1334. $col_order = $('#col_order'); // check if column order is passed from PHP
  1335. if ($col_order.length > 0) {
  1336. g.colOrder = $col_order.val().split(',');
  1337. for (var i = 0; i < g.colOrder.length; i++) {
  1338. g.colOrder[i] = parseInt(g.colOrder[i], 10);
  1339. }
  1340. } else {
  1341. g.colOrder = [];
  1342. for (var i = 0; i < $firstRowCols.length; i++) {
  1343. g.colOrder.push(i);
  1344. }
  1345. }
  1346. // register events
  1347. $(t).find('th.draggable')
  1348. .mousedown(function (e) {
  1349. $('#sqlqueryresults').addClass("turnOffSelect");
  1350. if (g.visibleHeadersCount > 1) {
  1351. g.dragStartReorder(e, this);
  1352. }
  1353. })
  1354. .mouseenter(function (e) {
  1355. if (g.visibleHeadersCount > 1) {
  1356. $(this).css('cursor', 'move');
  1357. } else {
  1358. $(this).css('cursor', 'inherit');
  1359. }
  1360. })
  1361. .mouseleave(function (e) {
  1362. g.showReorderHint = false;
  1363. $(this).tooltip("option", {
  1364. content: g.updateHint()
  1365. });
  1366. })
  1367. .dblclick(function (e) {
  1368. e.preventDefault();
  1369. $("<div/>")
  1370. .prop("title", PMA_messages.strColNameCopyTitle)
  1371. .addClass("modal-copy")
  1372. .text(PMA_messages.strColNameCopyText)
  1373. .append(
  1374. $("<input/>")
  1375. .prop("readonly", true)
  1376. .val($(this).data("column"))
  1377. )
  1378. .dialog({
  1379. resizable: false,
  1380. modal: true
  1381. })
  1382. .find("input").focus().select();
  1383. });
  1384. $(t).find('th.draggable a')
  1385. .dblclick(function (e) {
  1386. e.stopPropagation();
  1387. });
  1388. // restore column order when the restore button is clicked
  1389. $('div.restore_column').click(function () {
  1390. g.restoreColOrder();
  1391. });
  1392. // attach to global div
  1393. $(g.gDiv).append(g.cPointer);
  1394. $(g.gDiv).append(g.cCpy);
  1395. // prevent default "dragstart" event when dragging a link
  1396. $(t).find('th a').bind('dragstart', function () {
  1397. return false;
  1398. });
  1399. // refresh the restore column button state
  1400. g.refreshRestoreButton();
  1401. },
  1402. /**
  1403. * Initialize column visibility feature.
  1404. */
  1405. initColVisib: function () {
  1406. g.cDrop = document.createElement('div'); // column drop-down arrows
  1407. g.cList = document.createElement('div'); // column visibility list
  1408. // adjust g.cDrop
  1409. g.cDrop.className = 'cDrop';
  1410. // adjust g.cList
  1411. g.cList.className = 'cList';
  1412. $(g.cList).hide();
  1413. // assign column visibility related hints
  1414. g.showAllColText = PMA_messages.strShowAllCol;
  1415. // get data columns in the first row of the table
  1416. var $firstRowCols = $(g.t).find('tr:first th.draggable');
  1417. // initialize column visibility
  1418. var $col_visib = $('#col_visib'); // check if column visibility is passed from PHP
  1419. if ($col_visib.length > 0) {
  1420. g.colVisib = $col_visib.val().split(',');
  1421. for (var i = 0; i < g.colVisib.length; i++) {
  1422. g.colVisib[i] = parseInt(g.colVisib[i], 10);
  1423. }
  1424. } else {
  1425. g.colVisib = [];
  1426. for (var i = 0; i < $firstRowCols.length; i++) {
  1427. g.colVisib.push(1);
  1428. }
  1429. }
  1430. // make sure we have more than one column
  1431. if ($firstRowCols.length > 1) {
  1432. var $colVisibTh = $(g.t).find('th:not(.draggable)');
  1433. PMA_tooltip(
  1434. $colVisibTh,
  1435. 'th',
  1436. PMA_messages.strColVisibHint
  1437. );
  1438. // create column visibility drop-down arrow(s)
  1439. $colVisibTh.each(function () {
  1440. var $th = $(this);
  1441. var cd = document.createElement('div'); // column drop-down arrow
  1442. var pos = $th.position();
  1443. $(cd).addClass('coldrop')
  1444. .click(function () {
  1445. if (g.cList.style.display == 'none') {
  1446. g.showColList(this);
  1447. } else {
  1448. g.hideColList();
  1449. }
  1450. });
  1451. $(g.cDrop).append(cd);
  1452. });
  1453. // add column visibility control
  1454. g.cList.innerHTML = '<div class="lDiv"></div>';
  1455. var $listDiv = $(g.cList).find('div');
  1456. for (var i = 0; i < $firstRowCols.length; i++) {
  1457. var currHeader = $firstRowCols[i];
  1458. var listElmt = document.createElement('div');
  1459. $(listElmt).text($(currHeader).text())
  1460. .prepend('<input type="checkbox" ' + (g.colVisib[i] ? 'checked="checked" ' : '') + '/>');
  1461. $listDiv.append(listElmt);
  1462. // add event on click
  1463. $(listElmt).click(function () {
  1464. if (g.toggleCol($(this).index())) {
  1465. g.afterToggleCol();
  1466. }
  1467. });
  1468. }
  1469. // add "show all column" button
  1470. var showAll = document.createElement('div');
  1471. $(showAll).addClass('showAllColBtn')
  1472. .text(g.showAllColText);
  1473. $(g.cList).append(showAll);
  1474. $(showAll).click(function () {
  1475. g.showAllColumns();
  1476. });
  1477. // prepend "show all column" button at top if the list is too long
  1478. if ($firstRowCols.length > 10) {
  1479. var clone = showAll.cloneNode(true);
  1480. $(g.cList).prepend(clone);
  1481. $(clone).click(function () {
  1482. g.showAllColumns();
  1483. });
  1484. }
  1485. }
  1486. // hide column visibility list if we move outside the list
  1487. $(t).find('td, th.draggable').mouseenter(function () {
  1488. g.hideColList();
  1489. });
  1490. // attach to global div
  1491. $(g.gDiv).append(g.cDrop);
  1492. $(g.gDiv).append(g.cList);
  1493. // some adjustment
  1494. g.reposDrop();
  1495. },
  1496. /**
  1497. * Initialize grid editing feature.
  1498. */
  1499. initGridEdit: function () {
  1500. function startGridEditing(e, cell) {
  1501. if (g.isCellEditActive) {
  1502. g.saveOrPostEditedCell();
  1503. } else {
  1504. g.showEditCell(cell);
  1505. }
  1506. e.stopPropagation();
  1507. }
  1508. // create cell edit wrapper element
  1509. g.cEdit = document.createElement('div');
  1510. // adjust g.cEdit
  1511. g.cEdit.className = 'cEdit';
  1512. $(g.cEdit).html('<input class="edit_box" rows="1" ></input><div class="edit_area" />');
  1513. $(g.cEdit).hide();
  1514. // assign cell editing hint
  1515. g.cellEditHint = PMA_messages.strCellEditHint;
  1516. g.saveCellWarning = PMA_messages.strSaveCellWarning;
  1517. g.alertNonUnique = PMA_messages.strAlertNonUnique;
  1518. g.gotoLinkText = PMA_messages.strGoToLink;
  1519. g.showDataRowLinkText = PMA_messages.strShowDataRowLink;
  1520. // initialize cell editing configuration
  1521. g.saveCellsAtOnce = $('#save_cells_at_once').val();
  1522. // register events
  1523. $(t).find('td.data.click1')
  1524. .click(function (e) {
  1525. startGridEditing(e, this);
  1526. // prevent default action when clicking on "link" in a table
  1527. if ($(e.target).is('.grid_edit a')) {
  1528. e.preventDefault();
  1529. }
  1530. });
  1531. $(t).find('td.data.click2')
  1532. .click(function (e) {
  1533. $cell = $(this);
  1534. // In the case of relational link, We want single click on the link
  1535. // to goto the link and double click to start grid-editing.
  1536. var $link = $(e.target);
  1537. if ($link.is('.grid_edit.relation a')) {
  1538. e.preventDefault();
  1539. // get the click count and increase
  1540. var clicks = $cell.data('clicks');
  1541. clicks = (typeof clicks === 'undefined') ? 1 : clicks + 1;
  1542. if (clicks == 1) {
  1543. // if there are no previous clicks,
  1544. // start the single click timer
  1545. timer = setTimeout(function () {
  1546. // temporarily remove ajax class so the page loader will not handle it,
  1547. // submit and then add it back
  1548. $link.removeClass('ajax');
  1549. AJAX.requestHandler.call($link[0]);
  1550. $link.addClass('ajax');
  1551. $cell.data('clicks', 0);
  1552. }, 700);
  1553. $cell.data('clicks', clicks);
  1554. $cell.data('timer', timer);
  1555. } else {
  1556. // this is a double click, cancel the single click timer
  1557. // and make the click count 0
  1558. clearTimeout($cell.data('timer'));
  1559. $cell.data('clicks', 0);
  1560. // start grid-editing
  1561. startGridEditing(e, this);
  1562. }
  1563. }
  1564. })
  1565. .dblclick(function (e) {
  1566. if ($(e.target).is('.grid_edit a')) {
  1567. e.preventDefault();
  1568. } else {
  1569. startGridEditing(e, this);
  1570. }
  1571. });
  1572. $(g.cEdit).find('.edit_box').focus(function (e) {
  1573. g.showEditArea();
  1574. });
  1575. $(g.cEdit).find('.edit_box, select').live('keydown', function (e) {
  1576. if (e.which == 13) {
  1577. // post on pressing "Enter"
  1578. e.preventDefault();
  1579. g.saveOrPostEditedCell();
  1580. }
  1581. });
  1582. $(g.cEdit).keydown(function (e) {
  1583. if (!g.isEditCellTextEditable) {
  1584. // prevent text editing
  1585. e.preventDefault();
  1586. }
  1587. });
  1588. $('html').click(function (e) {
  1589. // hide edit cell if the click is not fromDat edit area
  1590. if ($(e.target).parents().index($(g.cEdit)) == -1
  1591. && ! $(e.target).parents('.ui-datepicker-header').length
  1592. ) {
  1593. g.hideEditCell();
  1594. }
  1595. }).keydown(function (e) {
  1596. if (e.which == 27 && g.isCellEditActive) {
  1597. // cancel on pressing "Esc"
  1598. g.hideEditCell(true);
  1599. }
  1600. });
  1601. $('div.save_edited').click(function () {
  1602. g.hideEditCell();
  1603. g.postEditedCell();
  1604. });
  1605. $(window).bind('beforeunload', function (e) {
  1606. if (g.isCellEdited) {
  1607. return g.saveCellWarning;
  1608. }
  1609. });
  1610. // attach to global div
  1611. $(g.gDiv).append(g.cEdit);
  1612. // add hint for grid editing feature when hovering "Edit" link in each table row
  1613. if (PMA_messages.strGridEditFeatureHint !== undefined) {
  1614. PMA_tooltip(
  1615. $(g.t).find('.edit_row_anchor a'),
  1616. 'a',
  1617. PMA_messages.strGridEditFeatureHint
  1618. );
  1619. }
  1620. }
  1621. };
  1622. /******************
  1623. * Initialize grid
  1624. ******************/
  1625. // wrap all data cells, except actions cell, with span
  1626. $(t).find('th, td:not(:has(span))')
  1627. .wrapInner('<span />');
  1628. // create grid elements
  1629. g.gDiv = document.createElement('div'); // create global div
  1630. // initialize the table variable
  1631. g.t = t;
  1632. // get data columns in the first row of the table
  1633. var $firstRowCols = $(t).find('tr:first th.draggable');
  1634. // initialize visible headers count
  1635. g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
  1636. // assign first column (actions) span
  1637. if (! $(t).find('tr:first th:first').hasClass('draggable')) { // action header exist
  1638. g.actionSpan = $(t).find('tr:first th:first').prop('colspan');
  1639. } else {
  1640. g.actionSpan = 0;
  1641. }
  1642. // assign table create time
  1643. // #table_create_time will only available if we are in "Browse" tab
  1644. g.tableCreateTime = $('#table_create_time').val();
  1645. // assign the hints
  1646. g.sortHint = PMA_messages.strSortHint;
  1647. g.strMultiSortHint = PMA_messages.strMultiSortHint;
  1648. g.markHint = PMA_messages.strColMarkHint;
  1649. g.copyHint = PMA_messages.strColNameCopyHint;
  1650. // assign common hidden inputs
  1651. var $common_hidden_inputs = $('div.common_hidden_inputs');
  1652. g.token = $common_hidden_inputs.find('input[name=token]').val();
  1653. g.server = $common_hidden_inputs.find('input[name=server]').val();
  1654. g.db = $common_hidden_inputs.find('input[name=db]').val();
  1655. g.table = $common_hidden_inputs.find('input[name=table]').val();
  1656. // add table class
  1657. $(t).addClass('pma_table');
  1658. // add relative position to global div so that resize handlers are correctly positioned
  1659. $(g.gDiv).css('position', 'relative');
  1660. // link the global div
  1661. $(t).before(g.gDiv);
  1662. $(g.gDiv).append(t);
  1663. // FEATURES
  1664. enableResize = enableResize === undefined ? true : enableResize;
  1665. enableReorder = enableReorder === undefined ? true : enableReorder;
  1666. enableVisib = enableVisib === undefined ? true : enableVisib;
  1667. enableGridEdit = enableGridEdit === undefined ? true : enableGridEdit;
  1668. if (enableResize) {
  1669. g.initColResize();
  1670. }
  1671. if (enableReorder &&
  1672. $('table.navigation').length > 0) // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
  1673. {
  1674. g.initColReorder();
  1675. }
  1676. if (enableVisib) {
  1677. g.initColVisib();
  1678. }
  1679. if (enableGridEdit &&
  1680. $(t).is('.ajax')) // make sure we have the ajax class
  1681. {
  1682. g.initGridEdit();
  1683. }
  1684. // create tooltip for each <th> with draggable class
  1685. PMA_tooltip(
  1686. $(t).find("th.draggable"),
  1687. 'th',
  1688. g.updateHint()
  1689. );
  1690. // register events for hint tooltip (anchors inside draggable th)
  1691. $(t).find('th.draggable a')
  1692. .mouseenter(function (e) {
  1693. g.showSortHint = true;
  1694. g.showMultiSortHint = true;
  1695. $(t).find("th.draggable").tooltip("option", {
  1696. content: g.updateHint()
  1697. });
  1698. })
  1699. .mouseleave(function (e) {
  1700. g.showSortHint = false;
  1701. g.showMultiSortHint = false;
  1702. $(t).find("th.draggable").tooltip("option", {
  1703. content: g.updateHint()
  1704. });
  1705. });
  1706. // register events for dragging-related feature
  1707. if (enableResize || enableReorder) {
  1708. $(document).mousemove(function (e) {
  1709. g.dragMove(e);
  1710. });
  1711. $(document).mouseup(function (e) {
  1712. $('#sqlqueryresults').removeClass("turnOffSelect");
  1713. g.dragEnd(e);
  1714. });
  1715. }
  1716. // some adjustment
  1717. $(t).removeClass('data');
  1718. $(g.gDiv).addClass('data');
  1719. }