makegrid.js 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301
  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. rearrangeStickyColumns($(t).prev('.sticky_columns'), $(t));
  180. } else if (g.colReorder) {
  181. // shift columns
  182. if (g.colReorder.newn !== g.colReorder.n) {
  183. g.shiftCol(g.colReorder.n, g.colReorder.newn);
  184. // assign new position
  185. var objPos = $(g.colReorder.obj).position();
  186. g.colReorder.objTop = objPos.top;
  187. g.colReorder.objLeft = objPos.left;
  188. g.colReorder.n = g.colReorder.newn;
  189. // send request to server to remember the column order
  190. if (g.tableCreateTime) {
  191. g.sendColPrefs();
  192. }
  193. g.refreshRestoreButton();
  194. }
  195. // animate new column position
  196. $(g.cCpy).stop(true, true)
  197. .animate({
  198. top: g.colReorder.objTop,
  199. left: g.colReorder.objLeft
  200. }, 'fast')
  201. .fadeOut();
  202. $(g.cPointer).css('visibility', 'hidden');
  203. g.colReorder = false;
  204. rearrangeStickyColumns($(t).prev('.sticky_columns'), $(t));
  205. }
  206. $(document.body).css('cursor', 'inherit').noSelect(false);
  207. },
  208. /**
  209. * Resize column n to new width "nw"
  210. *
  211. * @param n zero-based column index
  212. * @param nw new width of the column in pixel
  213. */
  214. resize: function (n, nw) {
  215. $(g.t).find('tr').each(function () {
  216. $(this).find('th.draggable:visible:eq(' + n + ') span,' +
  217. 'td:visible:eq(' + (g.actionSpan + n) + ') span')
  218. .css('width', nw);
  219. });
  220. },
  221. /**
  222. * Reposition column resize bars.
  223. */
  224. reposRsz: function () {
  225. $(g.cRsz).find('div').hide();
  226. var $firstRowCols = $(g.t).find('tr:first th.draggable:visible');
  227. var $resizeHandles = $(g.cRsz).find('div').removeClass('condition');
  228. $(g.t).find('table.pma_table').find('thead th:first').removeClass('before-condition');
  229. for (var n = 0, l = $firstRowCols.length; n < l; n++) {
  230. var $col = $($firstRowCols[n]);
  231. var colWidth;
  232. if (navigator.userAgent.toLowerCase().indexOf('safari') !== -1) {
  233. colWidth = $col.outerWidth();
  234. } else {
  235. colWidth = $col.outerWidth(true);
  236. }
  237. $($resizeHandles[n]).css('left', $col.position().left + colWidth)
  238. .show();
  239. if ($col.hasClass('condition')) {
  240. $($resizeHandles[n]).addClass('condition');
  241. if (n > 0) {
  242. $($resizeHandles[n - 1]).addClass('condition');
  243. }
  244. }
  245. }
  246. if ($($resizeHandles[0]).hasClass('condition')) {
  247. $(g.t).find('thead th:first').addClass('before-condition');
  248. }
  249. $(g.cRsz).css('height', $(g.t).height());
  250. },
  251. /**
  252. * Shift column from index oldn to newn.
  253. *
  254. * @param oldn old zero-based column index
  255. * @param newn new zero-based column index
  256. */
  257. shiftCol: function (oldn, newn) {
  258. $(g.t).find('tr').each(function () {
  259. if (newn < oldn) {
  260. $(this).find('th.draggable:eq(' + newn + '),' +
  261. 'td:eq(' + (g.actionSpan + newn) + ')')
  262. .before($(this).find('th.draggable:eq(' + oldn + '),' +
  263. 'td:eq(' + (g.actionSpan + oldn) + ')'));
  264. } else {
  265. $(this).find('th.draggable:eq(' + newn + '),' +
  266. 'td:eq(' + (g.actionSpan + newn) + ')')
  267. .after($(this).find('th.draggable:eq(' + oldn + '),' +
  268. 'td:eq(' + (g.actionSpan + oldn) + ')'));
  269. }
  270. });
  271. // reposition the column resize bars
  272. g.reposRsz();
  273. // adjust the column visibility list
  274. if (newn < oldn) {
  275. $(g.cList).find('.lDiv div:eq(' + newn + ')')
  276. .before($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
  277. } else {
  278. $(g.cList).find('.lDiv div:eq(' + newn + ')')
  279. .after($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
  280. }
  281. // adjust the colOrder
  282. var tmp = g.colOrder[oldn];
  283. g.colOrder.splice(oldn, 1);
  284. g.colOrder.splice(newn, 0, tmp);
  285. // adjust the colVisib
  286. if (g.colVisib.length > 0) {
  287. tmp = g.colVisib[oldn];
  288. g.colVisib.splice(oldn, 1);
  289. g.colVisib.splice(newn, 0, tmp);
  290. }
  291. },
  292. /**
  293. * Find currently hovered table column's header (excluding actions column).
  294. *
  295. * @param e event
  296. * @return the hovered column's th object or undefined if no hovered column found.
  297. */
  298. getHoveredCol: function (e) {
  299. var hoveredCol;
  300. $headers = $(g.t).find('th.draggable:visible');
  301. $headers.each(function () {
  302. var left = $(this).offset().left;
  303. var right = left + $(this).outerWidth();
  304. if (left <= e.pageX && e.pageX <= right) {
  305. hoveredCol = this;
  306. }
  307. });
  308. return hoveredCol;
  309. },
  310. /**
  311. * Get a zero-based index from a <th class="draggable"> tag in a table.
  312. *
  313. * @param obj table header <th> object
  314. * @return zero-based index of the specified table header in the set of table headers (visible or not)
  315. */
  316. getHeaderIdx: function (obj) {
  317. return $(obj).parents('tr').find('th.draggable').index(obj);
  318. },
  319. /**
  320. * Reposition the columns back to normal order.
  321. */
  322. restoreColOrder: function () {
  323. // use insertion sort, since we already have shiftCol function
  324. for (var i = 1; i < g.colOrder.length; i++) {
  325. var x = g.colOrder[i];
  326. var j = i - 1;
  327. while (j >= 0 && x < g.colOrder[j]) {
  328. j--;
  329. }
  330. if (j !== i - 1) {
  331. g.shiftCol(i, j + 1);
  332. }
  333. }
  334. if (g.tableCreateTime) {
  335. // send request to server to remember the column order
  336. g.sendColPrefs();
  337. }
  338. g.refreshRestoreButton();
  339. },
  340. /**
  341. * Send column preferences (column order and visibility) to the server.
  342. */
  343. sendColPrefs: function () {
  344. if ($(g.t).is('.ajax')) { // only send preferences if ajax class
  345. var post_params = {
  346. ajax_request: true,
  347. db: g.db,
  348. table: g.table,
  349. token: g.token,
  350. server: g.server,
  351. set_col_prefs: true,
  352. table_create_time: g.tableCreateTime
  353. };
  354. if (g.colOrder.length > 0) {
  355. $.extend(post_params, { col_order: g.colOrder.toString() });
  356. }
  357. if (g.colVisib.length > 0) {
  358. $.extend(post_params, { col_visib: g.colVisib.toString() });
  359. }
  360. $.post('sql.php', post_params, function (data) {
  361. if (data.success !== true) {
  362. var $temp_div = $(document.createElement('div'));
  363. $temp_div.html(data.error);
  364. $temp_div.addClass('error');
  365. PMA_ajaxShowMessage($temp_div, false);
  366. }
  367. });
  368. }
  369. },
  370. /**
  371. * Refresh restore button state.
  372. * Make restore button disabled if the table is similar with initial state.
  373. */
  374. refreshRestoreButton: function () {
  375. // check if table state is as initial state
  376. var isInitial = true;
  377. for (var i = 0; i < g.colOrder.length; i++) {
  378. if (g.colOrder[i] !== i) {
  379. isInitial = false;
  380. break;
  381. }
  382. }
  383. // check if only one visible column left
  384. var isOneColumn = g.visibleHeadersCount === 1;
  385. // enable or disable restore button
  386. if (isInitial || isOneColumn) {
  387. $(g.o).find('div.restore_column').hide();
  388. } else {
  389. $(g.o).find('div.restore_column').show();
  390. }
  391. },
  392. /**
  393. * Update current hint using the boolean values (showReorderHint, showSortHint, etc.).
  394. *
  395. */
  396. updateHint: function () {
  397. var text = '';
  398. if (!g.colRsz && !g.colReorder) { // if not resizing or dragging
  399. if (g.visibleHeadersCount > 1) {
  400. g.showReorderHint = true;
  401. }
  402. if ($(t).find('th.marker').length > 0) {
  403. g.showMarkHint = true;
  404. }
  405. if (g.showSortHint && g.sortHint) {
  406. text += text.length > 0 ? '<br />' : '';
  407. text += '- ' + g.sortHint;
  408. }
  409. if (g.showMultiSortHint && g.strMultiSortHint) {
  410. text += text.length > 0 ? '<br />' : '';
  411. text += '- ' + g.strMultiSortHint;
  412. }
  413. if (g.showMarkHint &&
  414. g.markHint &&
  415. ! g.showSortHint && // we do not show mark hint, when sort hint is shown
  416. g.showReorderHint &&
  417. g.reorderHint
  418. ) {
  419. text += text.length > 0 ? '<br />' : '';
  420. text += '- ' + g.reorderHint;
  421. text += text.length > 0 ? '<br />' : '';
  422. text += '- ' + g.markHint;
  423. text += text.length > 0 ? '<br />' : '';
  424. text += '- ' + g.copyHint;
  425. }
  426. }
  427. return text;
  428. },
  429. /**
  430. * Toggle column's visibility.
  431. * After calling this function and it returns true, afterToggleCol() must be called.
  432. *
  433. * @return boolean True if the column is toggled successfully.
  434. */
  435. toggleCol: function (n) {
  436. if (g.colVisib[n]) {
  437. // can hide if more than one column is visible
  438. if (g.visibleHeadersCount > 1) {
  439. $(g.t).find('tr').each(function () {
  440. $(this).find('th.draggable:eq(' + n + '),' +
  441. 'td:eq(' + (g.actionSpan + n) + ')')
  442. .hide();
  443. });
  444. g.colVisib[n] = 0;
  445. $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', false);
  446. } else {
  447. // cannot hide, force the checkbox to stay checked
  448. $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', true);
  449. return false;
  450. }
  451. } else { // column n is not visible
  452. $(g.t).find('tr').each(function () {
  453. $(this).find('th.draggable:eq(' + n + '),' +
  454. 'td:eq(' + (g.actionSpan + n) + ')')
  455. .show();
  456. });
  457. g.colVisib[n] = 1;
  458. $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', true);
  459. }
  460. return true;
  461. },
  462. /**
  463. * This must be called if toggleCol() returns is true.
  464. *
  465. * This function is separated from toggleCol because, sometimes, we want to toggle
  466. * some columns together at one time and do just one adjustment after it, e.g. in showAllColumns().
  467. */
  468. afterToggleCol: function () {
  469. // some adjustments after hiding column
  470. g.reposRsz();
  471. g.reposDrop();
  472. g.sendColPrefs();
  473. // check visible first row headers count
  474. g.visibleHeadersCount = $(g.t).find('tr:first th.draggable:visible').length;
  475. g.refreshRestoreButton();
  476. },
  477. /**
  478. * Show columns' visibility list.
  479. *
  480. * @param obj The drop down arrow of column visibility list
  481. */
  482. showColList: function (obj) {
  483. // only show when not resizing or reordering
  484. if (!g.colRsz && !g.colReorder) {
  485. var pos = $(obj).position();
  486. // check if the list position is too right
  487. if (pos.left + $(g.cList).outerWidth(true) > $(document).width()) {
  488. pos.left = $(document).width() - $(g.cList).outerWidth(true);
  489. }
  490. $(g.cList).css({
  491. left: pos.left,
  492. top: pos.top + $(obj).outerHeight(true)
  493. })
  494. .show();
  495. $(obj).addClass('coldrop-hover');
  496. }
  497. },
  498. /**
  499. * Hide columns' visibility list.
  500. */
  501. hideColList: function () {
  502. $(g.cList).hide();
  503. $(g.cDrop).find('.coldrop-hover').removeClass('coldrop-hover');
  504. },
  505. /**
  506. * Reposition the column visibility drop-down arrow.
  507. */
  508. reposDrop: function () {
  509. var $th = $(t).find('th:not(.draggable)');
  510. for (var i = 0; i < $th.length; i++) {
  511. var $cd = $(g.cDrop).find('div:eq(' + i + ')'); // column drop-down arrow
  512. var pos = $($th[i]).position();
  513. $cd.css({
  514. left: pos.left + $($th[i]).width() - $cd.width(),
  515. top: pos.top
  516. });
  517. }
  518. },
  519. /**
  520. * Show all hidden columns.
  521. */
  522. showAllColumns: function () {
  523. for (var i = 0; i < g.colVisib.length; i++) {
  524. if (!g.colVisib[i]) {
  525. g.toggleCol(i);
  526. }
  527. }
  528. g.afterToggleCol();
  529. },
  530. /**
  531. * Show edit cell, if it can be shown
  532. *
  533. * @param cell <td> element to be edited
  534. */
  535. showEditCell: function (cell) {
  536. if ($(cell).is('.grid_edit') &&
  537. !g.colRsz && !g.colReorder) {
  538. if (!g.isCellEditActive) {
  539. var $cell = $(cell);
  540. if ('string' === $cell.attr('data-type') ||
  541. 'blob' === $cell.attr('data-type') ||
  542. 'json' === $cell.attr('data-type')
  543. ) {
  544. g.cEdit = g.cEditTextarea;
  545. } else {
  546. g.cEdit = g.cEditStd;
  547. }
  548. // remove all edit area and hide it
  549. $(g.cEdit).find('.edit_area').empty().hide();
  550. // reposition the cEdit element
  551. $(g.cEdit).css({
  552. top: $cell.position().top,
  553. left: $cell.position().left
  554. })
  555. .show()
  556. .find('.edit_box')
  557. .css({
  558. width: $cell.outerWidth(),
  559. height: $cell.outerHeight()
  560. });
  561. // fill the cell edit with text from <td>
  562. var value = PMA_getCellValue(cell);
  563. if ($cell.attr('data-type') === 'json' && $cell.is('.truncated') === false) {
  564. try {
  565. value = JSON.stringify(JSON.parse(value), null, 4);
  566. } catch (e) {
  567. // Show as is
  568. }
  569. }
  570. $(g.cEdit).find('.edit_box').val(value);
  571. g.currentEditCell = cell;
  572. $(g.cEdit).find('.edit_box').focus();
  573. moveCursorToEnd($(g.cEdit).find('.edit_box'));
  574. $(g.cEdit).find('*').prop('disabled', false);
  575. }
  576. }
  577. function moveCursorToEnd (input) {
  578. var originalValue = input.val();
  579. var originallength = originalValue.length;
  580. input.val('');
  581. input.blur().focus().val(originalValue);
  582. input[0].setSelectionRange(originallength, originallength);
  583. }
  584. },
  585. /**
  586. * Remove edit cell and the edit area, if it is shown.
  587. *
  588. * @param force Optional, force to hide edit cell without saving edited field.
  589. * @param data Optional, data from the POST AJAX request to save the edited field
  590. * or just specify "true", if we want to replace the edited field with the new value.
  591. * @param field Optional, the edited <td>. If not specified, the function will
  592. * use currently edited <td> from g.currentEditCell.
  593. * @param field Optional, this object contains a boolean named move (true, if called from move* functions)
  594. * and a <td> to which the grid_edit should move
  595. */
  596. hideEditCell: function (force, data, field, options) {
  597. if (g.isCellEditActive && !force) {
  598. // cell is being edited, save or post the edited data
  599. if (options !== undefined) {
  600. g.saveOrPostEditedCell(options);
  601. } else {
  602. g.saveOrPostEditedCell();
  603. }
  604. return;
  605. }
  606. // cancel any previous request
  607. if (g.lastXHR !== null) {
  608. g.lastXHR.abort();
  609. g.lastXHR = null;
  610. }
  611. if (data) {
  612. if (g.currentEditCell) { // save value of currently edited cell
  613. // replace current edited field with the new value
  614. var $this_field = $(g.currentEditCell);
  615. var is_null = $this_field.data('value') === null;
  616. if (is_null) {
  617. $this_field.find('span').html('NULL');
  618. $this_field.addClass('null');
  619. } else {
  620. $this_field.removeClass('null');
  621. var value = data.isNeedToRecheck
  622. ? data.truncatableFieldValue
  623. : $this_field.data('value');
  624. // Truncates the text.
  625. $this_field.removeClass('truncated');
  626. if (PMA_commonParams.get('pftext') === 'P' && value.length > g.maxTruncatedLen) {
  627. $this_field.addClass('truncated');
  628. value = value.substring(0, g.maxTruncatedLen) + '...';
  629. }
  630. // Add <br> before carriage return.
  631. new_html = escapeHtml(value);
  632. new_html = new_html.replace(/\n/g, '<br>\n');
  633. // remove decimal places if column type not supported
  634. if (($this_field.attr('data-decimals') === 0) && ($this_field.attr('data-type').indexOf('time') !== -1)) {
  635. new_html = new_html.substring(0, new_html.indexOf('.'));
  636. }
  637. // remove addtional decimal places
  638. if (($this_field.attr('data-decimals') > 0) && ($this_field.attr('data-type').indexOf('time') !== -1)) {
  639. new_html = new_html.substring(0, new_html.length - (6 - $this_field.attr('data-decimals')));
  640. }
  641. var selector = 'span';
  642. if ($this_field.hasClass('hex') && $this_field.find('a').length) {
  643. selector = 'a';
  644. }
  645. // Updates the code keeping highlighting (if any).
  646. var $target = $this_field.find(selector);
  647. if (!PMA_updateCode($target, new_html, value)) {
  648. $target.html(new_html);
  649. }
  650. }
  651. if ($this_field.is('.bit')) {
  652. $this_field.find('span').text($this_field.data('value'));
  653. }
  654. }
  655. if (data.transformations !== undefined) {
  656. $.each(data.transformations, function (cell_index, value) {
  657. var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
  658. $this_field.find('span').html(value);
  659. });
  660. }
  661. if (data.relations !== undefined) {
  662. $.each(data.relations, function (cell_index, value) {
  663. var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
  664. $this_field.find('span').html(value);
  665. });
  666. }
  667. // refresh the grid
  668. g.reposRsz();
  669. g.reposDrop();
  670. }
  671. // hide the cell editing area
  672. $(g.cEdit).hide();
  673. $(g.cEdit).find('.edit_box').blur();
  674. g.isCellEditActive = false;
  675. g.currentEditCell = null;
  676. // destroy datepicker in edit area, if exist
  677. var $dp = $(g.cEdit).find('.hasDatepicker');
  678. if ($dp.length > 0) {
  679. $(document).bind('mousedown', $.datepicker._checkExternalClick);
  680. $dp.datepicker('destroy');
  681. // change the cursor in edit box back to normal
  682. // (the cursor become a hand pointer when we add datepicker)
  683. $(g.cEdit).find('.edit_box').css('cursor', 'inherit');
  684. }
  685. },
  686. /**
  687. * Show drop-down edit area when edit cell is focused.
  688. */
  689. showEditArea: function () {
  690. if (!g.isCellEditActive) { // make sure the edit area has not been shown
  691. g.isCellEditActive = true;
  692. g.isEditCellTextEditable = false;
  693. /**
  694. * @var $td current edited cell
  695. */
  696. var $td = $(g.currentEditCell);
  697. /**
  698. * @var $editArea the editing area
  699. */
  700. var $editArea = $(g.cEdit).find('.edit_area');
  701. /**
  702. * @var where_clause WHERE clause for the edited cell
  703. */
  704. var where_clause = $td.parent('tr').find('.where_clause').val();
  705. /**
  706. * @var field_name String containing the name of this field.
  707. * @see getFieldName()
  708. */
  709. var field_name = getFieldName($(t), $td);
  710. /**
  711. * @var relation_curr_value String current value of the field (for fields that are foreign keyed).
  712. */
  713. var relation_curr_value = $td.text();
  714. /**
  715. * @var relation_key_or_display_column String relational key if in 'Relational display column' mode,
  716. * relational display column if in 'Relational key' mode (for fields that are foreign keyed).
  717. */
  718. var relation_key_or_display_column = $td.find('a').attr('title');
  719. /**
  720. * @var curr_value String current value of the field (for fields that are of type enum or set).
  721. */
  722. var curr_value = $td.find('span').text();
  723. // empty all edit area, then rebuild it based on $td classes
  724. $editArea.empty();
  725. // remember this instead of testing more than once
  726. var is_null = $td.is('.null');
  727. // add goto link, if this cell contains a link
  728. if ($td.find('a').length > 0) {
  729. var gotoLink = document.createElement('div');
  730. gotoLink.className = 'goto_link';
  731. $(gotoLink).append(g.gotoLinkText + ' ').append($td.find('a').clone());
  732. $editArea.append(gotoLink);
  733. }
  734. g.wasEditedCellNull = false;
  735. if ($td.is(':not(.not_null)')) {
  736. // append a null checkbox
  737. $editArea.append('<div class="null_div"><label>Null:<input type="checkbox"></label></div>');
  738. var $checkbox = $editArea.find('.null_div input');
  739. // check if current <td> is NULL
  740. if (is_null) {
  741. $checkbox.prop('checked', true);
  742. g.wasEditedCellNull = true;
  743. }
  744. // if the select/editor is changed un-check the 'checkbox_null_<field_name>_<row_index>'.
  745. if ($td.is('.enum, .set')) {
  746. $editArea.on('change', 'select', function () {
  747. $checkbox.prop('checked', false);
  748. });
  749. } else if ($td.is('.relation')) {
  750. $editArea.on('change', 'select', function () {
  751. $checkbox.prop('checked', false);
  752. });
  753. $editArea.on('click', '.browse_foreign', function () {
  754. $checkbox.prop('checked', false);
  755. });
  756. } else {
  757. $(g.cEdit).on('keypress change paste', '.edit_box', function () {
  758. $checkbox.prop('checked', false);
  759. });
  760. // Capture ctrl+v (on IE and Chrome)
  761. $(g.cEdit).on('keydown', '.edit_box', function (e) {
  762. if (e.ctrlKey && e.which === 86) {
  763. $checkbox.prop('checked', false);
  764. }
  765. });
  766. $editArea.on('keydown', 'textarea', function () {
  767. $checkbox.prop('checked', false);
  768. });
  769. }
  770. // if some text is written in textbox automatically unmark the null checkbox and if it is emptied again mark the checkbox.
  771. $(g.cEdit).find('.edit_box').on('input', function () {
  772. if ($(g.cEdit).find('.edit_box').val() !== '') {
  773. $checkbox.prop('checked', false);
  774. } else {
  775. $checkbox.prop('checked', true);
  776. }
  777. });
  778. // if null checkbox is clicked empty the corresponding select/editor.
  779. $checkbox.click(function () {
  780. if ($td.is('.enum')) {
  781. $editArea.find('select').val('');
  782. } else if ($td.is('.set')) {
  783. $editArea.find('select').find('option').each(function () {
  784. var $option = $(this);
  785. $option.prop('selected', false);
  786. });
  787. } else if ($td.is('.relation')) {
  788. // if the dropdown is there to select the foreign value
  789. if ($editArea.find('select').length > 0) {
  790. $editArea.find('select').val('');
  791. }
  792. } else {
  793. $editArea.find('textarea').val('');
  794. }
  795. $(g.cEdit).find('.edit_box').val('');
  796. });
  797. }
  798. // reset the position of the edit_area div after closing datetime picker
  799. $(g.cEdit).find('.edit_area').css({ 'top' :'0','position':'' });
  800. if ($td.is('.relation')) {
  801. // handle relations
  802. $editArea.addClass('edit_area_loading');
  803. // initialize the original data
  804. $td.data('original_data', null);
  805. /**
  806. * @var post_params Object containing parameters for the POST request
  807. */
  808. var post_params = {
  809. 'ajax_request' : true,
  810. 'get_relational_values' : true,
  811. 'server' : g.server,
  812. 'db' : g.db,
  813. 'table' : g.table,
  814. 'column' : field_name,
  815. 'curr_value' : relation_curr_value,
  816. 'relation_key_or_display_column' : relation_key_or_display_column
  817. };
  818. g.lastXHR = $.post('sql.php', post_params, function (data) {
  819. g.lastXHR = null;
  820. $editArea.removeClass('edit_area_loading');
  821. if ($(data.dropdown).is('select')) {
  822. // save original_data
  823. var value = $(data.dropdown).val();
  824. $td.data('original_data', value);
  825. // update the text input field, in case where the "Relational display column" is checked
  826. $(g.cEdit).find('.edit_box').val(value);
  827. }
  828. $editArea.append(data.dropdown);
  829. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  830. // for 'Browse foreign values' options,
  831. // hide the value next to 'Browse foreign values' link
  832. $editArea.find('span.curr_value').hide();
  833. // handle update for new values selected from new window
  834. $editArea.find('span.curr_value').change(function () {
  835. $(g.cEdit).find('.edit_box').val($(this).text());
  836. });
  837. }); // end $.post()
  838. $editArea.show();
  839. $editArea.on('change', 'select', function () {
  840. $(g.cEdit).find('.edit_box').val($(this).val());
  841. });
  842. g.isEditCellTextEditable = true;
  843. } else if ($td.is('.enum')) {
  844. // handle enum fields
  845. $editArea.addClass('edit_area_loading');
  846. /**
  847. * @var post_params Object containing parameters for the POST request
  848. */
  849. var post_params = {
  850. 'ajax_request' : true,
  851. 'get_enum_values' : true,
  852. 'server' : g.server,
  853. 'db' : g.db,
  854. 'table' : g.table,
  855. 'column' : field_name,
  856. 'curr_value' : curr_value
  857. };
  858. g.lastXHR = $.post('sql.php', post_params, function (data) {
  859. g.lastXHR = null;
  860. $editArea.removeClass('edit_area_loading');
  861. $editArea.append(data.dropdown);
  862. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  863. }); // end $.post()
  864. $editArea.show();
  865. $editArea.on('change', 'select', function () {
  866. $(g.cEdit).find('.edit_box').val($(this).val());
  867. });
  868. } else if ($td.is('.set')) {
  869. // handle set fields
  870. $editArea.addClass('edit_area_loading');
  871. /**
  872. * @var post_params Object containing parameters for the POST request
  873. */
  874. var post_params = {
  875. 'ajax_request' : true,
  876. 'get_set_values' : true,
  877. 'server' : g.server,
  878. 'db' : g.db,
  879. 'table' : g.table,
  880. 'column' : field_name,
  881. 'curr_value' : curr_value
  882. };
  883. // if the data is truncated, get the full data
  884. if ($td.is('.truncated')) {
  885. post_params.get_full_values = true;
  886. post_params.where_clause = where_clause;
  887. }
  888. g.lastXHR = $.post('sql.php', post_params, function (data) {
  889. g.lastXHR = null;
  890. $editArea.removeClass('edit_area_loading');
  891. $editArea.append(data.select);
  892. $td.data('original_data', $(data.select).val().join());
  893. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  894. }); // end $.post()
  895. $editArea.show();
  896. $editArea.on('change', 'select', function () {
  897. $(g.cEdit).find('.edit_box').val($(this).val());
  898. });
  899. } else if ($td.is('.truncated, .transformed')) {
  900. if ($td.is('.to_be_saved')) { // cell has been edited
  901. var value = $td.data('value');
  902. $(g.cEdit).find('.edit_box').val(value);
  903. $editArea.append('<textarea></textarea>');
  904. $editArea.find('textarea').val(value);
  905. $editArea
  906. .on('keyup', 'textarea', function () {
  907. $(g.cEdit).find('.edit_box').val($(this).val());
  908. });
  909. $(g.cEdit).on('keyup', '.edit_box', function () {
  910. $editArea.find('textarea').val($(this).val());
  911. });
  912. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  913. } else {
  914. // handle truncated/transformed values values
  915. $editArea.addClass('edit_area_loading');
  916. // initialize the original data
  917. $td.data('original_data', null);
  918. /**
  919. * @var sql_query String containing the SQL query used to retrieve value of truncated/transformed data
  920. */
  921. var sql_query = 'SELECT `' + field_name + '` FROM `' + g.table + '` WHERE ' + where_clause;
  922. // Make the Ajax call and get the data, wrap it and insert it
  923. g.lastXHR = $.post('sql.php', {
  924. 'server' : g.server,
  925. 'db' : g.db,
  926. 'ajax_request' : true,
  927. 'sql_query' : sql_query,
  928. 'grid_edit' : true
  929. }, function (data) {
  930. g.lastXHR = null;
  931. $editArea.removeClass('edit_area_loading');
  932. if (typeof data !== 'undefined' && data.success === true) {
  933. if ($td.attr('data-type') === 'json') {
  934. try {
  935. data.value = JSON.stringify(JSON.parse(data.value), null, 4);
  936. } catch (e) {
  937. // Show as is
  938. }
  939. }
  940. $td.data('original_data', data.value);
  941. $(g.cEdit).find('.edit_box').val(data.value);
  942. $editArea.append('<textarea rows="15"></textarea>');
  943. $editArea.find('textarea').val(data.value);
  944. $editArea.on('keyup', 'textarea', function () {
  945. $(g.cEdit).find('.edit_box').val($(this).val());
  946. });
  947. $(g.cEdit).on('keyup', '.edit_box', function () {
  948. $editArea.find('textarea').val($(this).val());
  949. });
  950. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  951. $editArea.show();
  952. } else {
  953. PMA_ajaxShowMessage(data.error, false);
  954. }
  955. }); // end $.post()
  956. }
  957. g.isEditCellTextEditable = true;
  958. } else if ($td.is('.timefield, .datefield, .datetimefield, .timestampfield')) {
  959. var $input_field = $(g.cEdit).find('.edit_box');
  960. // remember current datetime value in $input_field, if it is not null
  961. var datetime_value = !is_null ? $input_field.val() : '';
  962. var showMillisec = false;
  963. var showMicrosec = false;
  964. var timeFormat = 'HH:mm:ss';
  965. // check for decimal places of seconds
  966. if (($td.attr('data-decimals') > 0) && ($td.attr('data-type').indexOf('time') !== -1)) {
  967. if (datetime_value && datetime_value.indexOf('.') === false) {
  968. datetime_value += '.';
  969. }
  970. if ($td.attr('data-decimals') > 3) {
  971. showMillisec = true;
  972. showMicrosec = true;
  973. timeFormat = 'HH:mm:ss.lc';
  974. if (datetime_value) {
  975. datetime_value += '000000';
  976. var datetime_value = datetime_value.substring(0, datetime_value.indexOf('.') + 7);
  977. $input_field.val(datetime_value);
  978. }
  979. } else {
  980. showMillisec = true;
  981. timeFormat = 'HH:mm:ss.l';
  982. if (datetime_value) {
  983. datetime_value += '000';
  984. var datetime_value = datetime_value.substring(0, datetime_value.indexOf('.') + 4);
  985. $input_field.val(datetime_value);
  986. }
  987. }
  988. }
  989. // add datetime picker
  990. PMA_addDatepicker($input_field, $td.attr('data-type'), {
  991. showMillisec: showMillisec,
  992. showMicrosec: showMicrosec,
  993. timeFormat: timeFormat
  994. });
  995. $input_field.on('keyup', function (e) {
  996. if (e.which === 13) {
  997. // post on pressing "Enter"
  998. e.preventDefault();
  999. e.stopPropagation();
  1000. g.saveOrPostEditedCell();
  1001. } else if (e.which === 27) {
  1002. } else {
  1003. toggleDatepickerIfInvalid($td, $input_field);
  1004. }
  1005. });
  1006. $input_field.datepicker('show');
  1007. toggleDatepickerIfInvalid($td, $input_field);
  1008. // unbind the mousedown event to prevent the problem of
  1009. // datepicker getting closed, needs to be checked for any
  1010. // change in names when updating
  1011. $(document).off('mousedown', $.datepicker._checkExternalClick);
  1012. // move ui-datepicker-div inside cEdit div
  1013. var datepicker_div = $('#ui-datepicker-div');
  1014. datepicker_div.css({ 'top': 0, 'left': 0, 'position': 'relative' });
  1015. $(g.cEdit).append(datepicker_div);
  1016. // cancel any click on the datepicker element
  1017. $editArea.find('> *').click(function (e) {
  1018. e.stopPropagation();
  1019. });
  1020. g.isEditCellTextEditable = true;
  1021. } else {
  1022. g.isEditCellTextEditable = true;
  1023. // only append edit area hint if there is a null checkbox
  1024. if ($editArea.children().length > 0) {
  1025. $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
  1026. }
  1027. }
  1028. if ($editArea.children().length > 0) {
  1029. $editArea.show();
  1030. }
  1031. }
  1032. },
  1033. /**
  1034. * Post the content of edited cell.
  1035. *
  1036. * @param field Optional, this object contains a boolean named move (true, if called from move* functions)
  1037. * and a <td> to which the grid_edit should move
  1038. */
  1039. postEditedCell: function (options) {
  1040. if (g.isSaving) {
  1041. return;
  1042. }
  1043. g.isSaving = true;
  1044. /**
  1045. * @var relation_fields Array containing the name/value pairs of relational fields
  1046. */
  1047. var relation_fields = {};
  1048. /**
  1049. * @var relational_display string 'K' if relational key, 'D' if relational display column
  1050. */
  1051. var relational_display = $(g.o).find('input[name=relational_display]:checked').val();
  1052. /**
  1053. * @var transform_fields Array containing the name/value pairs for transformed fields
  1054. */
  1055. var transform_fields = {};
  1056. /**
  1057. * @var transformation_fields Boolean, if there are any transformed fields in the edited cells
  1058. */
  1059. var transformation_fields = false;
  1060. /**
  1061. * @var full_sql_query String containing the complete SQL query to update this table
  1062. */
  1063. var full_sql_query = '';
  1064. /**
  1065. * @var rel_fields_list String, url encoded representation of {@link relations_fields}
  1066. */
  1067. var rel_fields_list = '';
  1068. /**
  1069. * @var transform_fields_list String, url encoded representation of {@link transform_fields}
  1070. */
  1071. var transform_fields_list = '';
  1072. /**
  1073. * @var where_clause Array containing where clause for updated fields
  1074. */
  1075. var full_where_clause = [];
  1076. /**
  1077. * @var is_unique Boolean, whether the rows in this table is unique or not
  1078. */
  1079. var is_unique = $(g.t).find('td.edit_row_anchor').is('.nonunique') ? 0 : 1;
  1080. /**
  1081. * multi edit variables
  1082. */
  1083. var me_fields_name = [];
  1084. var me_fields_type = [];
  1085. var me_fields = [];
  1086. var me_fields_null = [];
  1087. // alert user if edited table is not unique
  1088. if (!is_unique) {
  1089. alert(g.alertNonUnique);
  1090. }
  1091. // loop each edited row
  1092. $(g.t).find('td.to_be_saved').parents('tr').each(function () {
  1093. var $tr = $(this);
  1094. var where_clause = $tr.find('.where_clause').val();
  1095. if (typeof where_clause === 'undefined') {
  1096. where_clause = '';
  1097. }
  1098. full_where_clause.push(where_clause);
  1099. var condition_array = JSON.parse($tr.find('.condition_array').val());
  1100. /**
  1101. * multi edit variables, for current row
  1102. * @TODO array indices are still not correct, they should be md5 of field's name
  1103. */
  1104. var fields_name = [];
  1105. var fields_type = [];
  1106. var fields = [];
  1107. var fields_null = [];
  1108. // loop each edited cell in a row
  1109. $tr.find('.to_be_saved').each(function () {
  1110. /**
  1111. * @var $this_field Object referring to the td that is being edited
  1112. */
  1113. var $this_field = $(this);
  1114. /**
  1115. * @var field_name String containing the name of this field.
  1116. * @see getFieldName()
  1117. */
  1118. var field_name = getFieldName($(g.t), $this_field);
  1119. /**
  1120. * @var this_field_params Array temporary storage for the name/value of current field
  1121. */
  1122. var this_field_params = {};
  1123. if ($this_field.is('.transformed')) {
  1124. transformation_fields = true;
  1125. }
  1126. this_field_params[field_name] = $this_field.data('value');
  1127. /**
  1128. * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
  1129. */
  1130. var is_null = this_field_params[field_name] === null;
  1131. fields_name.push(field_name);
  1132. if (is_null) {
  1133. fields_null.push('on');
  1134. fields.push('');
  1135. } else {
  1136. if ($this_field.is('.bit')) {
  1137. fields_type.push('bit');
  1138. } else if ($this_field.hasClass('hex')) {
  1139. fields_type.push('hex');
  1140. }
  1141. fields_null.push('');
  1142. // Convert \n to \r\n to be consistent with form submitted value.
  1143. // The internal browser representation has to be just \n
  1144. // while form submitted value \r\n, see specification:
  1145. // https://www.w3.org/TR/html5/forms.html#the-textarea-element
  1146. fields.push($this_field.data('value').replace(/\n/g, '\r\n'));
  1147. var cell_index = $this_field.index('.to_be_saved');
  1148. if ($this_field.is(':not(.relation, .enum, .set, .bit)')) {
  1149. if ($this_field.is('.transformed')) {
  1150. transform_fields[cell_index] = {};
  1151. $.extend(transform_fields[cell_index], this_field_params);
  1152. }
  1153. } else if ($this_field.is('.relation')) {
  1154. relation_fields[cell_index] = {};
  1155. $.extend(relation_fields[cell_index], this_field_params);
  1156. }
  1157. }
  1158. // check if edited field appears in WHERE clause
  1159. if (where_clause.indexOf(PMA_urlencode(field_name)) > -1) {
  1160. var field_str = '`' + g.table + '`.' + '`' + field_name + '`';
  1161. for (var field in condition_array) {
  1162. if (field.indexOf(field_str) > -1) {
  1163. condition_array[field] = is_null ? 'IS NULL' : '= \'' + this_field_params[field_name].replace(/'/g, '\'\'') + '\'';
  1164. break;
  1165. }
  1166. }
  1167. }
  1168. }); // end of loop for every edited cells in a row
  1169. // save new_clause
  1170. var new_clause = '';
  1171. for (var field in condition_array) {
  1172. new_clause += field + ' ' + condition_array[field] + ' AND ';
  1173. }
  1174. new_clause = new_clause.substring(0, new_clause.length - 5); // remove the last AND
  1175. $tr.data('new_clause', new_clause);
  1176. // save condition_array
  1177. $tr.find('.condition_array').val(JSON.stringify(condition_array));
  1178. me_fields_name.push(fields_name);
  1179. me_fields_type.push(fields_type);
  1180. me_fields.push(fields);
  1181. me_fields_null.push(fields_null);
  1182. }); // end of loop for every edited rows
  1183. rel_fields_list = $.param(relation_fields);
  1184. transform_fields_list = $.param(transform_fields);
  1185. // Make the Ajax post after setting all parameters
  1186. /**
  1187. * @var post_params Object containing parameters for the POST request
  1188. */
  1189. var post_params = { 'ajax_request' : true,
  1190. 'sql_query' : full_sql_query,
  1191. 'server' : g.server,
  1192. 'db' : g.db,
  1193. 'table' : g.table,
  1194. 'clause_is_unique' : is_unique,
  1195. 'where_clause' : full_where_clause,
  1196. 'fields[multi_edit]' : me_fields,
  1197. 'fields_name[multi_edit]' : me_fields_name,
  1198. 'fields_type[multi_edit]' : me_fields_type,
  1199. 'fields_null[multi_edit]' : me_fields_null,
  1200. 'rel_fields_list' : rel_fields_list,
  1201. 'do_transformations' : transformation_fields,
  1202. 'transform_fields_list' : transform_fields_list,
  1203. 'relational_display' : relational_display,
  1204. 'goto' : 'sql.php',
  1205. 'submit_type' : 'save'
  1206. };
  1207. if (!g.saveCellsAtOnce) {
  1208. $(g.cEdit).find('*').prop('disabled', true);
  1209. $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
  1210. } else {
  1211. $(g.o).find('div.save_edited').addClass('saving_edited_data')
  1212. .find('input').prop('disabled', true); // disable the save button
  1213. }
  1214. $.ajax({
  1215. type: 'POST',
  1216. url: 'tbl_replace.php',
  1217. data: post_params,
  1218. success:
  1219. function (data) {
  1220. g.isSaving = false;
  1221. if (!g.saveCellsAtOnce) {
  1222. $(g.cEdit).find('*').prop('disabled', false);
  1223. $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
  1224. } else {
  1225. $(g.o).find('div.save_edited').removeClass('saving_edited_data')
  1226. .find('input').prop('disabled', false); // enable the save button back
  1227. }
  1228. if (typeof data !== 'undefined' && data.success === true) {
  1229. if (typeof options === 'undefined' || ! options.move) {
  1230. PMA_ajaxShowMessage(data.message);
  1231. }
  1232. // update where_clause related data in each edited row
  1233. $(g.t).find('td.to_be_saved').parents('tr').each(function () {
  1234. var new_clause = $(this).data('new_clause');
  1235. var $where_clause = $(this).find('.where_clause');
  1236. var old_clause = $where_clause.val();
  1237. var decoded_old_clause = old_clause;
  1238. var decoded_new_clause = new_clause;
  1239. $where_clause.val(new_clause);
  1240. // update Edit, Copy, and Delete links also
  1241. $(this).find('a').each(function () {
  1242. $(this).attr('href', $(this).attr('href').replace(old_clause, new_clause));
  1243. // update delete confirmation in Delete link
  1244. if ($(this).attr('href').indexOf('DELETE') > -1) {
  1245. $(this).removeAttr('onclick')
  1246. .off('click')
  1247. .on('click', function () {
  1248. return confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' +
  1249. decoded_new_clause + (is_unique ? '' : ' LIMIT 1'));
  1250. });
  1251. }
  1252. });
  1253. // update the multi edit checkboxes
  1254. $(this).find('input[type=checkbox]').each(function () {
  1255. var $checkbox = $(this);
  1256. var checkbox_name = $checkbox.attr('name');
  1257. var checkbox_value = $checkbox.val();
  1258. $checkbox.attr('name', checkbox_name.replace(old_clause, new_clause));
  1259. $checkbox.val(checkbox_value.replace(decoded_old_clause, decoded_new_clause));
  1260. });
  1261. });
  1262. // update the display of executed SQL query command
  1263. if (typeof data.sql_query !== 'undefined') {
  1264. // extract query box
  1265. var $result_query = $($.parseHTML(data.sql_query));
  1266. var sqlOuter = $result_query.find('.sqlOuter').wrap('<p>').parent().html();
  1267. var tools = $result_query.find('.tools').wrap('<p>').parent().html();
  1268. // sqlOuter and tools will not be present if 'Show SQL queries' configuration is off
  1269. if (typeof sqlOuter !== 'undefined' && typeof tools !== 'undefined') {
  1270. $(g.o).find('.result_query:not(:last)').remove();
  1271. var $existing_query = $(g.o).find('.result_query');
  1272. // If two query box exists update query in second else add a second box
  1273. if ($existing_query.find('div.sqlOuter').length > 1) {
  1274. $existing_query.children(':nth-child(4)').remove();
  1275. $existing_query.children(':nth-child(4)').remove();
  1276. $existing_query.append(sqlOuter + tools);
  1277. } else {
  1278. $existing_query.append(sqlOuter + tools);
  1279. }
  1280. PMA_highlightSQL($existing_query);
  1281. }
  1282. }
  1283. // hide and/or update the successfully saved cells
  1284. g.hideEditCell(true, data);
  1285. // remove the "Save edited cells" button
  1286. $(g.o).find('div.save_edited').hide();
  1287. // update saved fields
  1288. $(g.t).find('.to_be_saved')
  1289. .removeClass('to_be_saved')
  1290. .data('value', null)
  1291. .data('original_data', null);
  1292. g.isCellEdited = false;
  1293. } else {
  1294. PMA_ajaxShowMessage(data.error, false);
  1295. if (!g.saveCellsAtOnce) {
  1296. $(g.t).find('.to_be_saved')
  1297. .removeClass('to_be_saved');
  1298. }
  1299. }
  1300. }
  1301. }).done(function () {
  1302. if (options !== undefined && options.move) {
  1303. g.showEditCell(options.cell);
  1304. }
  1305. }); // end $.ajax()
  1306. },
  1307. /**
  1308. * Save edited cell, so it can be posted later.
  1309. */
  1310. saveEditedCell: function () {
  1311. /**
  1312. * @var $this_field Object referring to the td that is being edited
  1313. */
  1314. var $this_field = $(g.currentEditCell);
  1315. var $test_element = ''; // to test the presence of a element
  1316. var need_to_post = false;
  1317. /**
  1318. * @var field_name String containing the name of this field.
  1319. * @see getFieldName()
  1320. */
  1321. var field_name = getFieldName($(g.t), $this_field);
  1322. /**
  1323. * @var this_field_params Array temporary storage for the name/value of current field
  1324. */
  1325. var this_field_params = {};
  1326. /**
  1327. * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
  1328. */
  1329. var is_null = $(g.cEdit).find('input:checkbox').is(':checked');
  1330. if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
  1331. // the edit area is still loading (retrieving cell data), no need to post
  1332. need_to_post = false;
  1333. } else if (is_null) {
  1334. if (!g.wasEditedCellNull) {
  1335. this_field_params[field_name] = null;
  1336. need_to_post = true;
  1337. }
  1338. } else {
  1339. if ($this_field.is('.bit')) {
  1340. this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
  1341. } else if ($this_field.is('.set')) {
  1342. $test_element = $(g.cEdit).find('select');
  1343. this_field_params[field_name] = $test_element.map(function () {
  1344. return $(this).val();
  1345. }).get().join(',');
  1346. } else if ($this_field.is('.relation, .enum')) {
  1347. // for relation and enumeration, take the results from edit box value,
  1348. // because selected value from drop-down, new window or multiple
  1349. // selection list will always be updated to the edit box
  1350. this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
  1351. } else if ($this_field.hasClass('hex')) {
  1352. if ($(g.cEdit).find('.edit_box').val().match(/^(0x)?[a-f0-9]*$/i) !== null) {
  1353. this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
  1354. } else {
  1355. var hexError = '<div class="error">' + PMA_messages.strEnterValidHex + '</div>';
  1356. PMA_ajaxShowMessage(hexError, false);
  1357. this_field_params[field_name] = PMA_getCellValue(g.currentEditCell);
  1358. }
  1359. } else {
  1360. this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
  1361. }
  1362. if (g.wasEditedCellNull || this_field_params[field_name] !== PMA_getCellValue(g.currentEditCell)) {
  1363. need_to_post = true;
  1364. }
  1365. }
  1366. if (need_to_post) {
  1367. $(g.currentEditCell).addClass('to_be_saved')
  1368. .data('value', this_field_params[field_name]);
  1369. if (g.saveCellsAtOnce) {
  1370. $(g.o).find('div.save_edited').show();
  1371. }
  1372. g.isCellEdited = true;
  1373. }
  1374. return need_to_post;
  1375. },
  1376. /**
  1377. * Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
  1378. *
  1379. * @param field Optional, this object contains a boolean named move (true, if called from move* functions)
  1380. * and a <td> to which the grid_edit should move
  1381. */
  1382. saveOrPostEditedCell: function (options) {
  1383. var saved = g.saveEditedCell();
  1384. // Check if $cfg['SaveCellsAtOnce'] is false
  1385. if (!g.saveCellsAtOnce) {
  1386. // Check if need_to_post is true
  1387. if (saved) {
  1388. // Check if this function called from 'move' functions
  1389. if (options !== undefined && options.move) {
  1390. g.postEditedCell(options);
  1391. } else {
  1392. g.postEditedCell();
  1393. }
  1394. // need_to_post is false
  1395. } else {
  1396. // Check if this function called from 'move' functions
  1397. if (options !== undefined && options.move) {
  1398. g.hideEditCell(true);
  1399. g.showEditCell(options.cell);
  1400. // NOT called from 'move' functions
  1401. } else {
  1402. g.hideEditCell(true);
  1403. }
  1404. }
  1405. // $cfg['SaveCellsAtOnce'] is true
  1406. } else {
  1407. // If need_to_post
  1408. if (saved) {
  1409. // If this function called from 'move' functions
  1410. if (options !== undefined && options.move) {
  1411. g.hideEditCell(true, true, false, options);
  1412. g.showEditCell(options.cell);
  1413. // NOT called from 'move' functions
  1414. } else {
  1415. g.hideEditCell(true, true);
  1416. }
  1417. } else {
  1418. // If this function called from 'move' functions
  1419. if (options !== undefined && options.move) {
  1420. g.hideEditCell(true, false, false, options);
  1421. g.showEditCell(options.cell);
  1422. // NOT called from 'move' functions
  1423. } else {
  1424. g.hideEditCell(true);
  1425. }
  1426. }
  1427. }
  1428. },
  1429. /**
  1430. * Initialize column resize feature.
  1431. */
  1432. initColResize: function () {
  1433. // create column resizer div
  1434. g.cRsz = document.createElement('div');
  1435. g.cRsz.className = 'cRsz';
  1436. // get data columns in the first row of the table
  1437. var $firstRowCols = $(g.t).find('tr:first th.draggable');
  1438. // create column borders
  1439. $firstRowCols.each(function () {
  1440. var cb = document.createElement('div'); // column border
  1441. $(cb).addClass('colborder')
  1442. .mousedown(function (e) {
  1443. g.dragStartRsz(e, this);
  1444. });
  1445. $(g.cRsz).append(cb);
  1446. });
  1447. g.reposRsz();
  1448. // attach to global div
  1449. $(g.gDiv).prepend(g.cRsz);
  1450. },
  1451. /**
  1452. * Initialize column reordering feature.
  1453. */
  1454. initColReorder: function () {
  1455. g.cCpy = document.createElement('div'); // column copy, to store copy of dragged column header
  1456. g.cPointer = document.createElement('div'); // column pointer, used when reordering column
  1457. // adjust g.cCpy
  1458. g.cCpy.className = 'cCpy';
  1459. $(g.cCpy).hide();
  1460. // adjust g.cPointer
  1461. g.cPointer.className = 'cPointer';
  1462. $(g.cPointer).css('visibility', 'hidden'); // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
  1463. // assign column reordering hint
  1464. g.reorderHint = PMA_messages.strColOrderHint;
  1465. // get data columns in the first row of the table
  1466. var $firstRowCols = $(g.t).find('tr:first th.draggable');
  1467. // initialize column order
  1468. $col_order = $(g.o).find('.col_order'); // check if column order is passed from PHP
  1469. if ($col_order.length > 0) {
  1470. g.colOrder = $col_order.val().split(',');
  1471. for (var i = 0; i < g.colOrder.length; i++) {
  1472. g.colOrder[i] = parseInt(g.colOrder[i], 10);
  1473. }
  1474. } else {
  1475. g.colOrder = [];
  1476. for (var i = 0; i < $firstRowCols.length; i++) {
  1477. g.colOrder.push(i);
  1478. }
  1479. }
  1480. // register events
  1481. $(g.t).find('th.draggable')
  1482. .mousedown(function (e) {
  1483. $(g.o).addClass('turnOffSelect');
  1484. if (g.visibleHeadersCount > 1) {
  1485. g.dragStartReorder(e, this);
  1486. }
  1487. })
  1488. .mouseenter(function () {
  1489. if (g.visibleHeadersCount > 1) {
  1490. $(this).css('cursor', 'move');
  1491. } else {
  1492. $(this).css('cursor', 'inherit');
  1493. }
  1494. })
  1495. .mouseleave(function () {
  1496. g.showReorderHint = false;
  1497. $(this).tooltip('option', {
  1498. content: g.updateHint()
  1499. });
  1500. })
  1501. .dblclick(function (e) {
  1502. e.preventDefault();
  1503. $('<div/>')
  1504. .prop('title', PMA_messages.strColNameCopyTitle)
  1505. .addClass('modal-copy')
  1506. .text(PMA_messages.strColNameCopyText)
  1507. .append(
  1508. $('<input/>')
  1509. .prop('readonly', true)
  1510. .val($(this).data('column'))
  1511. )
  1512. .dialog({
  1513. resizable: false,
  1514. modal: true
  1515. })
  1516. .find('input').focus().select();
  1517. });
  1518. $(g.t).find('th.draggable a')
  1519. .dblclick(function (e) {
  1520. e.stopPropagation();
  1521. });
  1522. // restore column order when the restore button is clicked
  1523. $(g.o).find('div.restore_column').click(function () {
  1524. g.restoreColOrder();
  1525. });
  1526. // attach to global div
  1527. $(g.gDiv).append(g.cPointer);
  1528. $(g.gDiv).append(g.cCpy);
  1529. // prevent default "dragstart" event when dragging a link
  1530. $(g.t).find('th a').on('dragstart', function () {
  1531. return false;
  1532. });
  1533. // refresh the restore column button state
  1534. g.refreshRestoreButton();
  1535. },
  1536. /**
  1537. * Initialize column visibility feature.
  1538. */
  1539. initColVisib: function () {
  1540. g.cDrop = document.createElement('div'); // column drop-down arrows
  1541. g.cList = document.createElement('div'); // column visibility list
  1542. // adjust g.cDrop
  1543. g.cDrop.className = 'cDrop';
  1544. // adjust g.cList
  1545. g.cList.className = 'cList';
  1546. $(g.cList).hide();
  1547. // assign column visibility related hints
  1548. g.showAllColText = PMA_messages.strShowAllCol;
  1549. // get data columns in the first row of the table
  1550. var $firstRowCols = $(g.t).find('tr:first th.draggable');
  1551. var i;
  1552. // initialize column visibility
  1553. var $col_visib = $(g.o).find('.col_visib'); // check if column visibility is passed from PHP
  1554. if ($col_visib.length > 0) {
  1555. g.colVisib = $col_visib.val().split(',');
  1556. for (i = 0; i < g.colVisib.length; i++) {
  1557. g.colVisib[i] = parseInt(g.colVisib[i], 10);
  1558. }
  1559. } else {
  1560. g.colVisib = [];
  1561. for (i = 0; i < $firstRowCols.length; i++) {
  1562. g.colVisib.push(1);
  1563. }
  1564. }
  1565. // make sure we have more than one column
  1566. if ($firstRowCols.length > 1) {
  1567. var $colVisibTh = $(g.t).find('th:not(.draggable)');
  1568. PMA_tooltip(
  1569. $colVisibTh,
  1570. 'th',
  1571. PMA_messages.strColVisibHint
  1572. );
  1573. // create column visibility drop-down arrow(s)
  1574. $colVisibTh.each(function () {
  1575. var $th = $(this);
  1576. var cd = document.createElement('div'); // column drop-down arrow
  1577. var pos = $th.position();
  1578. $(cd).addClass('coldrop')
  1579. .click(function () {
  1580. if (g.cList.style.display === 'none') {
  1581. g.showColList(this);
  1582. } else {
  1583. g.hideColList();
  1584. }
  1585. });
  1586. $(g.cDrop).append(cd);
  1587. });
  1588. // add column visibility control
  1589. g.cList.innerHTML = '<div class="lDiv"></div>';
  1590. var $listDiv = $(g.cList).find('div');
  1591. var tempClick = function () {
  1592. if (g.toggleCol($(this).index())) {
  1593. g.afterToggleCol();
  1594. }
  1595. };
  1596. for (i = 0; i < $firstRowCols.length; i++) {
  1597. var currHeader = $firstRowCols[i];
  1598. var listElmt = document.createElement('div');
  1599. $(listElmt).text($(currHeader).text())
  1600. .prepend('<input type="checkbox" ' + (g.colVisib[i] ? 'checked="checked" ' : '') + '/>');
  1601. $listDiv.append(listElmt);
  1602. // add event on click
  1603. $(listElmt).click(tempClick);
  1604. }
  1605. // add "show all column" button
  1606. var showAll = document.createElement('div');
  1607. $(showAll).addClass('showAllColBtn')
  1608. .text(g.showAllColText);
  1609. $(g.cList).append(showAll);
  1610. $(showAll).click(function () {
  1611. g.showAllColumns();
  1612. });
  1613. // prepend "show all column" button at top if the list is too long
  1614. if ($firstRowCols.length > 10) {
  1615. var clone = showAll.cloneNode(true);
  1616. $(g.cList).prepend(clone);
  1617. $(clone).click(function () {
  1618. g.showAllColumns();
  1619. });
  1620. }
  1621. }
  1622. // hide column visibility list if we move outside the list
  1623. $(g.t).find('td, th.draggable').mouseenter(function () {
  1624. g.hideColList();
  1625. });
  1626. // attach to global div
  1627. $(g.gDiv).append(g.cDrop);
  1628. $(g.gDiv).append(g.cList);
  1629. // some adjustment
  1630. g.reposDrop();
  1631. },
  1632. /**
  1633. * Move currently Editing Cell to Up
  1634. */
  1635. moveUp: function (e) {
  1636. e.preventDefault();
  1637. var $this_field = $(g.currentEditCell);
  1638. var field_name = getFieldName($(g.t), $this_field);
  1639. var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
  1640. if (typeof where_clause === 'undefined') {
  1641. where_clause = '';
  1642. }
  1643. var found = false;
  1644. var $found_row;
  1645. var $prev_row;
  1646. var j = 0;
  1647. $this_field.parents('tr').first().parents('tbody').children().each(function () {
  1648. if ($(this).find('.where_clause').val() === where_clause) {
  1649. found = true;
  1650. $found_row = $(this);
  1651. }
  1652. if (!found) {
  1653. $prev_row = $(this);
  1654. }
  1655. });
  1656. var new_cell;
  1657. if (found && $prev_row) {
  1658. $prev_row.children('td').each(function () {
  1659. if (getFieldName($(g.t), $(this)) === field_name) {
  1660. new_cell = this;
  1661. }
  1662. });
  1663. }
  1664. if (new_cell) {
  1665. g.hideEditCell(false, false, false, { move : true, cell : new_cell });
  1666. }
  1667. },
  1668. /**
  1669. * Move currently Editing Cell to Down
  1670. */
  1671. moveDown: function (e) {
  1672. e.preventDefault();
  1673. var $this_field = $(g.currentEditCell);
  1674. var field_name = getFieldName($(g.t), $this_field);
  1675. var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
  1676. if (typeof where_clause === 'undefined') {
  1677. where_clause = '';
  1678. }
  1679. var found = false;
  1680. var $found_row;
  1681. var $next_row;
  1682. var j = 0;
  1683. var next_row_found = false;
  1684. $this_field.parents('tr').first().parents('tbody').children().each(function () {
  1685. if ($(this).find('.where_clause').val() === where_clause) {
  1686. found = true;
  1687. $found_row = $(this);
  1688. }
  1689. if (found) {
  1690. if (j >= 1 && ! next_row_found) {
  1691. $next_row = $(this);
  1692. next_row_found = true;
  1693. } else {
  1694. j++;
  1695. }
  1696. }
  1697. });
  1698. var new_cell;
  1699. if (found && $next_row) {
  1700. $next_row.children('td').each(function () {
  1701. if (getFieldName($(g.t), $(this)) === field_name) {
  1702. new_cell = this;
  1703. }
  1704. });
  1705. }
  1706. if (new_cell) {
  1707. g.hideEditCell(false, false, false, { move : true, cell : new_cell });
  1708. }
  1709. },
  1710. /**
  1711. * Move currently Editing Cell to Left
  1712. */
  1713. moveLeft: function (e) {
  1714. e.preventDefault();
  1715. var $this_field = $(g.currentEditCell);
  1716. var field_name = getFieldName($(g.t), $this_field);
  1717. var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
  1718. if (typeof where_clause === 'undefined') {
  1719. where_clause = '';
  1720. }
  1721. var found = false;
  1722. var $found_row;
  1723. var j = 0;
  1724. $this_field.parents('tr').first().parents('tbody').children().each(function () {
  1725. if ($(this).find('.where_clause').val() === where_clause) {
  1726. found = true;
  1727. $found_row = $(this);
  1728. }
  1729. });
  1730. var left_cell;
  1731. var cell_found = false;
  1732. if (found) {
  1733. $found_row.children('td.grid_edit').each(function () {
  1734. if (getFieldName($(g.t), $(this)) === field_name) {
  1735. cell_found = true;
  1736. }
  1737. if (!cell_found) {
  1738. left_cell = this;
  1739. }
  1740. });
  1741. }
  1742. if (left_cell) {
  1743. g.hideEditCell(false, false, false, { move : true, cell : left_cell });
  1744. }
  1745. },
  1746. /**
  1747. * Move currently Editing Cell to Right
  1748. */
  1749. moveRight: function (e) {
  1750. e.preventDefault();
  1751. var $this_field = $(g.currentEditCell);
  1752. var field_name = getFieldName($(g.t), $this_field);
  1753. var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
  1754. if (typeof where_clause === 'undefined') {
  1755. where_clause = '';
  1756. }
  1757. var found = false;
  1758. var $found_row;
  1759. var j = 0;
  1760. $this_field.parents('tr').first().parents('tbody').children().each(function () {
  1761. if ($(this).find('.where_clause').val() === where_clause) {
  1762. found = true;
  1763. $found_row = $(this);
  1764. }
  1765. });
  1766. var right_cell;
  1767. var cell_found = false;
  1768. var next_cell_found = false;
  1769. if (found) {
  1770. $found_row.children('td.grid_edit').each(function () {
  1771. if (getFieldName($(g.t), $(this)) === field_name) {
  1772. cell_found = true;
  1773. }
  1774. if (cell_found) {
  1775. if (j >= 1 && ! next_cell_found) {
  1776. right_cell = this;
  1777. next_cell_found = true;
  1778. } else {
  1779. j++;
  1780. }
  1781. }
  1782. });
  1783. }
  1784. if (right_cell) {
  1785. g.hideEditCell(false, false, false, { move : true, cell : right_cell });
  1786. }
  1787. },
  1788. /**
  1789. * Initialize grid editing feature.
  1790. */
  1791. initGridEdit: function () {
  1792. function startGridEditing (e, cell) {
  1793. if (g.isCellEditActive) {
  1794. g.saveOrPostEditedCell();
  1795. } else {
  1796. g.showEditCell(cell);
  1797. }
  1798. e.stopPropagation();
  1799. }
  1800. function handleCtrlNavigation (e) {
  1801. if ((e.ctrlKey && e.which === 38) || (e.altKey && e.which === 38)) {
  1802. g.moveUp(e);
  1803. } else if ((e.ctrlKey && e.which === 40) || (e.altKey && e.which === 40)) {
  1804. g.moveDown(e);
  1805. } else if ((e.ctrlKey && e.which === 37) || (e.altKey && e.which === 37)) {
  1806. g.moveLeft(e);
  1807. } else if ((e.ctrlKey && e.which === 39) || (e.altKey && e.which === 39)) {
  1808. g.moveRight(e);
  1809. }
  1810. }
  1811. // create cell edit wrapper element
  1812. g.cEditStd = document.createElement('div');
  1813. g.cEdit = g.cEditStd;
  1814. g.cEditTextarea = document.createElement('div');
  1815. // adjust g.cEditStd
  1816. g.cEditStd.className = 'cEdit';
  1817. $(g.cEditStd).html('<input class="edit_box" rows="1" /><div class="edit_area" />');
  1818. $(g.cEditStd).hide();
  1819. // adjust g.cEdit
  1820. g.cEditTextarea.className = 'cEdit';
  1821. $(g.cEditTextarea).html('<textarea class="edit_box" rows="1" ></textarea><div class="edit_area" />');
  1822. $(g.cEditTextarea).hide();
  1823. // assign cell editing hint
  1824. g.cellEditHint = PMA_messages.strCellEditHint;
  1825. g.saveCellWarning = PMA_messages.strSaveCellWarning;
  1826. g.alertNonUnique = PMA_messages.strAlertNonUnique;
  1827. g.gotoLinkText = PMA_messages.strGoToLink;
  1828. // initialize cell editing configuration
  1829. g.saveCellsAtOnce = $(g.o).find('.save_cells_at_once').val();
  1830. g.maxTruncatedLen = PMA_commonParams.get('LimitChars');
  1831. // register events
  1832. $(g.t).find('td.data.click1')
  1833. .click(function (e) {
  1834. startGridEditing(e, this);
  1835. // prevent default action when clicking on "link" in a table
  1836. if ($(e.target).is('.grid_edit a')) {
  1837. e.preventDefault();
  1838. }
  1839. });
  1840. $(g.t).find('td.data.click2')
  1841. .click(function (e) {
  1842. var $cell = $(this);
  1843. // In the case of relational link, We want single click on the link
  1844. // to goto the link and double click to start grid-editing.
  1845. var $link = $(e.target);
  1846. if ($link.is('.grid_edit.relation a')) {
  1847. e.preventDefault();
  1848. // get the click count and increase
  1849. var clicks = $cell.data('clicks');
  1850. clicks = (typeof clicks === 'undefined') ? 1 : clicks + 1;
  1851. if (clicks === 1) {
  1852. // if there are no previous clicks,
  1853. // start the single click timer
  1854. var timer = setTimeout(function () {
  1855. // temporarily remove ajax class so the page loader will not handle it,
  1856. // submit and then add it back
  1857. $link.removeClass('ajax');
  1858. AJAX.requestHandler.call($link[0]);
  1859. $link.addClass('ajax');
  1860. $cell.data('clicks', 0);
  1861. }, 700);
  1862. $cell.data('clicks', clicks);
  1863. $cell.data('timer', timer);
  1864. } else {
  1865. // this is a double click, cancel the single click timer
  1866. // and make the click count 0
  1867. clearTimeout($cell.data('timer'));
  1868. $cell.data('clicks', 0);
  1869. // start grid-editing
  1870. startGridEditing(e, this);
  1871. }
  1872. }
  1873. })
  1874. .dblclick(function (e) {
  1875. if ($(e.target).is('.grid_edit a')) {
  1876. e.preventDefault();
  1877. } else {
  1878. startGridEditing(e, this);
  1879. }
  1880. });
  1881. $(g.cEditStd).on('keydown', 'input.edit_box, select', handleCtrlNavigation);
  1882. $(g.cEditStd).find('.edit_box').focus(function () {
  1883. g.showEditArea();
  1884. });
  1885. $(g.cEditStd).on('keydown', '.edit_box, select', function (e) {
  1886. if (e.which === 13) {
  1887. // post on pressing "Enter"
  1888. e.preventDefault();
  1889. g.saveOrPostEditedCell();
  1890. }
  1891. });
  1892. $(g.cEditStd).keydown(function (e) {
  1893. if (!g.isEditCellTextEditable) {
  1894. // prevent text editing
  1895. e.preventDefault();
  1896. }
  1897. });
  1898. $(g.cEditTextarea).on('keydown', 'textarea.edit_box, select', handleCtrlNavigation);
  1899. $(g.cEditTextarea).find('.edit_box').focus(function () {
  1900. g.showEditArea();
  1901. });
  1902. $(g.cEditTextarea).on('keydown', '.edit_box, select', function (e) {
  1903. if (e.which === 13 && !e.shiftKey) {
  1904. // post on pressing "Enter"
  1905. e.preventDefault();
  1906. g.saveOrPostEditedCell();
  1907. }
  1908. });
  1909. $(g.cEditTextarea).keydown(function (e) {
  1910. if (!g.isEditCellTextEditable) {
  1911. // prevent text editing
  1912. e.preventDefault();
  1913. }
  1914. });
  1915. $('html').click(function (e) {
  1916. // hide edit cell if the click is not fromDat edit area
  1917. if ($(e.target).parents().index($(g.cEdit)) === -1 &&
  1918. !$(e.target).parents('.ui-datepicker-header').length &&
  1919. !$('.browse_foreign_modal.ui-dialog:visible').length &&
  1920. !$(e.target).closest('.dismissable').length
  1921. ) {
  1922. g.hideEditCell();
  1923. }
  1924. }).keydown(function (e) {
  1925. if (e.which === 27 && g.isCellEditActive) {
  1926. // cancel on pressing "Esc"
  1927. g.hideEditCell(true);
  1928. }
  1929. });
  1930. $(g.o).find('div.save_edited').click(function () {
  1931. g.hideEditCell();
  1932. g.postEditedCell();
  1933. });
  1934. $(window).on('beforeunload', function () {
  1935. if (g.isCellEdited) {
  1936. return g.saveCellWarning;
  1937. }
  1938. });
  1939. // attach to global div
  1940. $(g.gDiv).append(g.cEditStd);
  1941. $(g.gDiv).append(g.cEditTextarea);
  1942. // add hint for grid editing feature when hovering "Edit" link in each table row
  1943. if (PMA_messages.strGridEditFeatureHint !== undefined) {
  1944. PMA_tooltip(
  1945. $(g.t).find('.edit_row_anchor a'),
  1946. 'a',
  1947. PMA_messages.strGridEditFeatureHint
  1948. );
  1949. }
  1950. }
  1951. };
  1952. /** ****************
  1953. * Initialize grid
  1954. ******************/
  1955. // wrap all truncated data cells with span indicating the original length
  1956. // todo update the original length after a grid edit
  1957. $(t).find('td.data.truncated:not(:has(span))')
  1958. .wrapInner(function () {
  1959. return '<span title="' + PMA_messages.strOriginalLength + ' ' +
  1960. $(this).data('originallength') + '"></span>';
  1961. });
  1962. // wrap remaining cells, except actions cell, with span
  1963. $(t).find('th, td:not(:has(span))')
  1964. .wrapInner('<span />');
  1965. // create grid elements
  1966. g.gDiv = document.createElement('div'); // create global div
  1967. // initialize the table variable
  1968. g.t = t;
  1969. // enclosing .sqlqueryresults div
  1970. g.o = $(t).parents('.sqlqueryresults');
  1971. // get data columns in the first row of the table
  1972. var $firstRowCols = $(t).find('tr:first th.draggable');
  1973. // initialize visible headers count
  1974. g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
  1975. // assign first column (actions) span
  1976. if (! $(t).find('tr:first th:first').hasClass('draggable')) { // action header exist
  1977. g.actionSpan = $(t).find('tr:first th:first').prop('colspan');
  1978. } else {
  1979. g.actionSpan = 0;
  1980. }
  1981. // assign table create time
  1982. // table_create_time will only available if we are in "Browse" tab
  1983. g.tableCreateTime = $(g.o).find('.table_create_time').val();
  1984. // assign the hints
  1985. g.sortHint = PMA_messages.strSortHint;
  1986. g.strMultiSortHint = PMA_messages.strMultiSortHint;
  1987. g.markHint = PMA_messages.strColMarkHint;
  1988. g.copyHint = PMA_messages.strColNameCopyHint;
  1989. // assign common hidden inputs
  1990. var $common_hidden_inputs = $(g.o).find('div.common_hidden_inputs');
  1991. g.server = $common_hidden_inputs.find('input[name=server]').val();
  1992. g.db = $common_hidden_inputs.find('input[name=db]').val();
  1993. g.table = $common_hidden_inputs.find('input[name=table]').val();
  1994. // add table class
  1995. $(t).addClass('pma_table');
  1996. // add relative position to global div so that resize handlers are correctly positioned
  1997. $(g.gDiv).css('position', 'relative');
  1998. // link the global div
  1999. $(t).before(g.gDiv);
  2000. $(g.gDiv).append(t);
  2001. // FEATURES
  2002. enableResize = enableResize === undefined ? true : enableResize;
  2003. enableReorder = enableReorder === undefined ? true : enableReorder;
  2004. enableVisib = enableVisib === undefined ? true : enableVisib;
  2005. enableGridEdit = enableGridEdit === undefined ? true : enableGridEdit;
  2006. if (enableResize) {
  2007. g.initColResize();
  2008. }
  2009. // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
  2010. if (enableReorder &&
  2011. $(g.o).find('table.navigation').length > 0) {
  2012. g.initColReorder();
  2013. }
  2014. if (enableVisib) {
  2015. g.initColVisib();
  2016. }
  2017. // make sure we have the ajax class
  2018. if (enableGridEdit &&
  2019. $(t).is('.ajax')) {
  2020. g.initGridEdit();
  2021. }
  2022. // create tooltip for each <th> with draggable class
  2023. PMA_tooltip(
  2024. $(t).find('th.draggable'),
  2025. 'th',
  2026. g.updateHint()
  2027. );
  2028. // register events for hint tooltip (anchors inside draggable th)
  2029. $(t).find('th.draggable a')
  2030. .mouseenter(function () {
  2031. g.showSortHint = true;
  2032. g.showMultiSortHint = true;
  2033. $(t).find('th.draggable').tooltip('option', {
  2034. content: g.updateHint()
  2035. });
  2036. })
  2037. .mouseleave(function () {
  2038. g.showSortHint = false;
  2039. g.showMultiSortHint = false;
  2040. $(t).find('th.draggable').tooltip('option', {
  2041. content: g.updateHint()
  2042. });
  2043. });
  2044. // register events for dragging-related feature
  2045. if (enableResize || enableReorder) {
  2046. $(document).mousemove(function (e) {
  2047. g.dragMove(e);
  2048. });
  2049. $(document).mouseup(function (e) {
  2050. $(g.o).removeClass('turnOffSelect');
  2051. g.dragEnd(e);
  2052. });
  2053. }
  2054. // some adjustment
  2055. $(t).removeClass('data');
  2056. $(g.gDiv).addClass('data');
  2057. }
  2058. /**
  2059. * jQuery plugin to cancel selection in HTML code.
  2060. */
  2061. (function ($) {
  2062. $.fn.noSelect = function (p) { // no select plugin by Paulo P.Marinas
  2063. var prevent = (p === null) ? true : p;
  2064. var is_msie = navigator.userAgent.indexOf('MSIE') > -1 || !!window.navigator.userAgent.match(/Trident.*rv\:11\./);
  2065. var is_firefox = navigator.userAgent.indexOf('Firefox') > -1;
  2066. var is_safari = navigator.userAgent.indexOf('Safari') > -1;
  2067. var is_opera = navigator.userAgent.indexOf('Presto') > -1;
  2068. if (prevent) {
  2069. return this.each(function () {
  2070. if (is_msie || is_safari) {
  2071. $(this).on('selectstart', false);
  2072. } else if (is_firefox) {
  2073. $(this).css('MozUserSelect', 'none');
  2074. $('body').trigger('focus');
  2075. } else if (is_opera) {
  2076. $(this).on('mousedown', false);
  2077. } else {
  2078. $(this).attr('unselectable', 'on');
  2079. }
  2080. });
  2081. } else {
  2082. return this.each(function () {
  2083. if (is_msie || is_safari) {
  2084. $(this).off('selectstart');
  2085. } else if (is_firefox) {
  2086. $(this).css('MozUserSelect', 'inherit');
  2087. } else if (is_opera) {
  2088. $(this).off('mousedown');
  2089. } else {
  2090. $(this).removeAttr('unselectable');
  2091. }
  2092. });
  2093. }
  2094. }; // end noSelect
  2095. }(jQuery));