makegrid.js 77 KB

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