makegrid.js 76 KB

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