TableWidget.js 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. const EventEmitter = require("devtools/shared/event-emitter");
  6. loader.lazyRequireGetter(this, "setNamedTimeout",
  7. "devtools/client/shared/widgets/view-helpers", true);
  8. loader.lazyRequireGetter(this, "clearNamedTimeout",
  9. "devtools/client/shared/widgets/view-helpers", true);
  10. loader.lazyRequireGetter(this, "naturalSortCaseInsensitive",
  11. "devtools/client/shared/natural-sort", true);
  12. const {KeyCodes} = require("devtools/client/shared/keycodes");
  13. const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
  14. const HTML_NS = "http://www.w3.org/1999/xhtml";
  15. const AFTER_SCROLL_DELAY = 100;
  16. // Different types of events emitted by the Various components of the
  17. // TableWidget.
  18. const EVENTS = {
  19. CELL_EDIT: "cell-edit",
  20. COLUMN_SORTED: "column-sorted",
  21. COLUMN_TOGGLED: "column-toggled",
  22. FIELDS_EDITABLE: "fields-editable",
  23. HEADER_CONTEXT_MENU: "header-context-menu",
  24. ROW_EDIT: "row-edit",
  25. ROW_CONTEXT_MENU: "row-context-menu",
  26. ROW_REMOVED: "row-removed",
  27. ROW_SELECTED: "row-selected",
  28. ROW_UPDATED: "row-updated",
  29. TABLE_CLEARED: "table-cleared",
  30. TABLE_FILTERED: "table-filtered",
  31. SCROLL_END: "scroll-end"
  32. };
  33. Object.defineProperty(this, "EVENTS", {
  34. value: EVENTS,
  35. enumerable: true,
  36. writable: false
  37. });
  38. /**
  39. * A table widget with various features like resizble/toggleable columns,
  40. * sorting, keyboard navigation etc.
  41. *
  42. * @param {nsIDOMNode} node
  43. * The container element for the table widget.
  44. * @param {object} options
  45. * - initialColumns: map of key vs display name for initial columns of
  46. * the table. See @setupColumns for more info.
  47. * - uniqueId: the column which will be the unique identifier of each
  48. * entry in the table. Default: name.
  49. * - wrapTextInElements: Don't ever use 'value' attribute on labels.
  50. * Default: false.
  51. * - emptyText: text to display when no entries in the table to display.
  52. * - highlightUpdated: true to highlight the changed/added row.
  53. * - removableColumns: Whether columns are removeable. If set to false,
  54. * the context menu in the headers will not appear.
  55. * - firstColumn: key of the first column that should appear.
  56. * - cellContextMenuId: ID of a <menupopup> element to be set as a
  57. * context menu of every cell.
  58. */
  59. function TableWidget(node, options = {}) {
  60. EventEmitter.decorate(this);
  61. this.document = node.ownerDocument;
  62. this.window = this.document.defaultView;
  63. this._parent = node;
  64. let {initialColumns, emptyText, uniqueId, highlightUpdated, removableColumns,
  65. firstColumn, wrapTextInElements, cellContextMenuId} = options;
  66. this.emptyText = emptyText || "";
  67. this.uniqueId = uniqueId || "name";
  68. this.wrapTextInElements = wrapTextInElements || false;
  69. this.firstColumn = firstColumn || "";
  70. this.highlightUpdated = highlightUpdated || false;
  71. this.removableColumns = removableColumns !== false;
  72. this.cellContextMenuId = cellContextMenuId;
  73. this.tbody = this.document.createElementNS(XUL_NS, "hbox");
  74. this.tbody.className = "table-widget-body theme-body";
  75. this.tbody.setAttribute("flex", "1");
  76. this.tbody.setAttribute("tabindex", "0");
  77. this._parent.appendChild(this.tbody);
  78. this.afterScroll = this.afterScroll.bind(this);
  79. this.tbody.addEventListener("scroll", this.onScroll.bind(this));
  80. this.placeholder = this.document.createElementNS(XUL_NS, "label");
  81. this.placeholder.className = "plain table-widget-empty-text";
  82. this.placeholder.setAttribute("flex", "1");
  83. this._parent.appendChild(this.placeholder);
  84. this.items = new Map();
  85. this.columns = new Map();
  86. // Setup the column headers context menu to allow users to hide columns at
  87. // will.
  88. if (this.removableColumns) {
  89. this.onPopupCommand = this.onPopupCommand.bind(this);
  90. this.setupHeadersContextMenu();
  91. }
  92. if (initialColumns) {
  93. this.setColumns(initialColumns, uniqueId);
  94. } else if (this.emptyText) {
  95. this.setPlaceholderText(this.emptyText);
  96. }
  97. this.bindSelectedRow = (event, id) => {
  98. this.selectedRow = id;
  99. };
  100. this.on(EVENTS.ROW_SELECTED, this.bindSelectedRow);
  101. this.onChange = this.onChange.bind(this);
  102. this.onEditorDestroyed = this.onEditorDestroyed.bind(this);
  103. this.onEditorTab = this.onEditorTab.bind(this);
  104. this.onKeydown = this.onKeydown.bind(this);
  105. this.onMousedown = this.onMousedown.bind(this);
  106. this.onRowRemoved = this.onRowRemoved.bind(this);
  107. this.document.addEventListener("keydown", this.onKeydown, false);
  108. this.document.addEventListener("mousedown", this.onMousedown, false);
  109. }
  110. TableWidget.prototype = {
  111. items: null,
  112. editBookmark: null,
  113. scrollIntoViewOnUpdate: null,
  114. /**
  115. * Getter for the headers context menu popup id.
  116. */
  117. get headersContextMenu() {
  118. if (this.menupopup) {
  119. return this.menupopup.id;
  120. }
  121. return null;
  122. },
  123. /**
  124. * Select the row corresponding to the json object `id`
  125. */
  126. set selectedRow(id) {
  127. for (let column of this.columns.values()) {
  128. if (id) {
  129. column.selectRow(id[this.uniqueId] || id);
  130. } else {
  131. column.selectedRow = null;
  132. column.selectRow(null);
  133. }
  134. }
  135. },
  136. /**
  137. * Returns the json object corresponding to the selected row.
  138. */
  139. get selectedRow() {
  140. return this.items.get(this.columns.get(this.uniqueId).selectedRow);
  141. },
  142. /**
  143. * Selects the row at index `index`.
  144. */
  145. set selectedIndex(index) {
  146. for (let column of this.columns.values()) {
  147. column.selectRowAt(index);
  148. }
  149. },
  150. /**
  151. * Returns the index of the selected row.
  152. */
  153. get selectedIndex() {
  154. return this.columns.get(this.uniqueId).selectedIndex;
  155. },
  156. /**
  157. * Returns the index of the selected row disregarding hidden rows.
  158. */
  159. get visibleSelectedIndex() {
  160. let cells = this.columns.get(this.uniqueId).visibleCellNodes;
  161. for (let i = 0; i < cells.length; i++) {
  162. if (cells[i].classList.contains("theme-selected")) {
  163. return i;
  164. }
  165. }
  166. return -1;
  167. },
  168. /**
  169. * returns all editable columns.
  170. */
  171. get editableColumns() {
  172. let filter = columns => {
  173. columns = [...columns].filter(col => {
  174. if (col.clientWidth === 0) {
  175. return false;
  176. }
  177. let cell = col.querySelector(".table-widget-cell");
  178. for (let selector of this._editableFieldsEngine.selectors) {
  179. if (cell.matches(selector)) {
  180. return true;
  181. }
  182. }
  183. return false;
  184. });
  185. return columns;
  186. };
  187. let columns = this._parent.querySelectorAll(".table-widget-column");
  188. return filter(columns);
  189. },
  190. /**
  191. * Emit all cell edit events.
  192. */
  193. onChange: function (type, data) {
  194. let changedField = data.change.field;
  195. let colName = changedField.parentNode.id;
  196. let column = this.columns.get(colName);
  197. let uniqueId = column.table.uniqueId;
  198. let itemIndex = column.cellNodes.indexOf(changedField);
  199. let items = {};
  200. for (let [name, col] of this.columns) {
  201. items[name] = col.cellNodes[itemIndex].value;
  202. }
  203. let change = {
  204. host: this.host,
  205. key: uniqueId,
  206. field: colName,
  207. oldValue: data.change.oldValue,
  208. newValue: data.change.newValue,
  209. items: items
  210. };
  211. // A rows position in the table can change as the result of an edit. In
  212. // order to ensure that the correct row is highlighted after an edit we
  213. // save the uniqueId in editBookmark.
  214. this.editBookmark = colName === uniqueId ? change.newValue
  215. : items[uniqueId];
  216. this.emit(EVENTS.CELL_EDIT, change);
  217. },
  218. onEditorDestroyed: function () {
  219. this._editableFieldsEngine = null;
  220. },
  221. /**
  222. * Called by the inplace editor when Tab / Shift-Tab is pressed in edit-mode.
  223. * Because tables are live any row, column, cell or table can be added,
  224. * deleted or moved by deleting and adding e.g. a row again.
  225. *
  226. * This presents various challenges when navigating via the keyboard so please
  227. * keep this in mind whenever editing this method.
  228. *
  229. * @param {Event} event
  230. * Keydown event
  231. */
  232. onEditorTab: function (event) {
  233. let textbox = event.target;
  234. let editor = this._editableFieldsEngine;
  235. if (textbox.id !== editor.INPUT_ID) {
  236. return;
  237. }
  238. let column = textbox.parentNode;
  239. // Changing any value can change the position of the row depending on which
  240. // column it is currently sorted on. In addition to this, the table cell may
  241. // have been edited and had to be recreated when the user has pressed tab or
  242. // shift+tab. Both of these situations require us to recover our target,
  243. // select the appropriate row and move the textbox on to the next cell.
  244. if (editor.changePending) {
  245. // We need to apply a change, which can mean that the position of cells
  246. // within the table can change. Because of this we need to wait for
  247. // EVENTS.ROW_EDIT and then move the textbox.
  248. this.once(EVENTS.ROW_EDIT, (e, uniqueId) => {
  249. let cell;
  250. let cells;
  251. let columnObj;
  252. let cols = this.editableColumns;
  253. let rowIndex = this.visibleSelectedIndex;
  254. let colIndex = cols.indexOf(column);
  255. let newIndex;
  256. // If the row has been deleted we should bail out.
  257. if (!uniqueId) {
  258. return;
  259. }
  260. // Find the column we need to move to.
  261. if (event.shiftKey) {
  262. // Navigate backwards on shift tab.
  263. if (colIndex === 0) {
  264. if (rowIndex === 0) {
  265. return;
  266. }
  267. newIndex = cols.length - 1;
  268. } else {
  269. newIndex = colIndex - 1;
  270. }
  271. } else if (colIndex === cols.length - 1) {
  272. let id = cols[0].id;
  273. columnObj = this.columns.get(id);
  274. let maxRowIndex = columnObj.visibleCellNodes.length - 1;
  275. if (rowIndex === maxRowIndex) {
  276. return;
  277. }
  278. newIndex = 0;
  279. } else {
  280. newIndex = colIndex + 1;
  281. }
  282. let newcol = cols[newIndex];
  283. columnObj = this.columns.get(newcol.id);
  284. // Select the correct row even if it has moved due to sorting.
  285. let dataId = editor.currentTarget.getAttribute("data-id");
  286. if (this.items.get(dataId)) {
  287. this.emit(EVENTS.ROW_SELECTED, dataId);
  288. } else {
  289. this.emit(EVENTS.ROW_SELECTED, uniqueId);
  290. }
  291. // EVENTS.ROW_SELECTED may have changed the selected row so let's save
  292. // the result in rowIndex.
  293. rowIndex = this.visibleSelectedIndex;
  294. // Edit the appropriate cell.
  295. cells = columnObj.visibleCellNodes;
  296. cell = cells[rowIndex];
  297. editor.edit(cell);
  298. // Remove flash-out class... it won't have been auto-removed because the
  299. // cell was hidden for editing.
  300. cell.classList.remove("flash-out");
  301. });
  302. }
  303. // Begin cell edit. We always do this so that we can begin editing even in
  304. // the case that the previous edit will cause the row to move.
  305. let cell = this.getEditedCellOnTab(event, column);
  306. editor.edit(cell);
  307. },
  308. /**
  309. * Get the cell that will be edited next on tab / shift tab and highlight the
  310. * appropriate row. Edits etc. are not taken into account.
  311. *
  312. * This is used to tab from one field to another without editing and makes the
  313. * editor much more responsive.
  314. *
  315. * @param {Event} event
  316. * Keydown event
  317. */
  318. getEditedCellOnTab: function (event, column) {
  319. let cell = null;
  320. let cols = this.editableColumns;
  321. let rowIndex = this.visibleSelectedIndex;
  322. let colIndex = cols.indexOf(column);
  323. let maxCol = cols.length - 1;
  324. let maxRow = this.columns.get(column.id).visibleCellNodes.length - 1;
  325. if (event.shiftKey) {
  326. // Navigate backwards on shift tab.
  327. if (colIndex === 0) {
  328. if (rowIndex === 0) {
  329. this._editableFieldsEngine.completeEdit();
  330. return null;
  331. }
  332. column = cols[cols.length - 1];
  333. let cells = this.columns.get(column.id).visibleCellNodes;
  334. cell = cells[rowIndex - 1];
  335. let rowId = cell.getAttribute("data-id");
  336. this.emit(EVENTS.ROW_SELECTED, rowId);
  337. } else {
  338. column = cols[colIndex - 1];
  339. let cells = this.columns.get(column.id).visibleCellNodes;
  340. cell = cells[rowIndex];
  341. }
  342. } else if (colIndex === maxCol) {
  343. // If in the rightmost column on the last row stop editing.
  344. if (rowIndex === maxRow) {
  345. this._editableFieldsEngine.completeEdit();
  346. return null;
  347. }
  348. // If in the rightmost column of a row then move to the first column of
  349. // the next row.
  350. column = cols[0];
  351. let cells = this.columns.get(column.id).visibleCellNodes;
  352. cell = cells[rowIndex + 1];
  353. let rowId = cell.getAttribute("data-id");
  354. this.emit(EVENTS.ROW_SELECTED, rowId);
  355. } else {
  356. // Navigate forwards on tab.
  357. column = cols[colIndex + 1];
  358. let cells = this.columns.get(column.id).visibleCellNodes;
  359. cell = cells[rowIndex];
  360. }
  361. return cell;
  362. },
  363. /**
  364. * Reset the editable fields engine if the currently edited row is removed.
  365. *
  366. * @param {String} event
  367. * The event name "event-removed."
  368. * @param {Object} row
  369. * The values from the removed row.
  370. */
  371. onRowRemoved: function (event, row) {
  372. if (!this._editableFieldsEngine || !this._editableFieldsEngine.isEditing) {
  373. return;
  374. }
  375. let removedKey = row[this.uniqueId];
  376. let column = this.columns.get(this.uniqueId);
  377. if (removedKey in column.items) {
  378. return;
  379. }
  380. // The target is lost so we need to hide the remove the textbox from the DOM
  381. // and reset the target nodes.
  382. this.onEditorTargetLost();
  383. },
  384. /**
  385. * Cancel an edit because the edit target has been lost.
  386. */
  387. onEditorTargetLost: function () {
  388. let editor = this._editableFieldsEngine;
  389. if (!editor || !editor.isEditing) {
  390. return;
  391. }
  392. editor.cancelEdit();
  393. },
  394. /**
  395. * Keydown event handler for the table. Used for keyboard navigation amongst
  396. * rows.
  397. */
  398. onKeydown: function (event) {
  399. // If we are in edit mode bail out.
  400. if (this._editableFieldsEngine && this._editableFieldsEngine.isEditing) {
  401. return;
  402. }
  403. // We need to get the first *visible* selected cell. Some columns are hidden
  404. // e.g. because they contain a unique compound key for cookies that is never
  405. // displayed in the UI. To do this we get all selected cells and filter out
  406. // any that are hidden.
  407. let selectedCells = [...this.tbody.querySelectorAll(".theme-selected")]
  408. .filter(cell => cell.clientWidth > 0);
  409. // Select the first visible selected cell.
  410. let selectedCell = selectedCells[0];
  411. if (!selectedCell) {
  412. return;
  413. }
  414. let colName;
  415. let column;
  416. let visibleCells;
  417. let index;
  418. let cell;
  419. switch (event.keyCode) {
  420. case KeyCodes.DOM_VK_UP:
  421. event.preventDefault();
  422. colName = selectedCell.parentNode.id;
  423. column = this.columns.get(colName);
  424. visibleCells = column.visibleCellNodes;
  425. index = visibleCells.indexOf(selectedCell);
  426. if (index > 0) {
  427. index--;
  428. } else {
  429. index = visibleCells.length - 1;
  430. }
  431. cell = visibleCells[index];
  432. this.emit(EVENTS.ROW_SELECTED, cell.getAttribute("data-id"));
  433. break;
  434. case KeyCodes.DOM_VK_DOWN:
  435. event.preventDefault();
  436. colName = selectedCell.parentNode.id;
  437. column = this.columns.get(colName);
  438. visibleCells = column.visibleCellNodes;
  439. index = visibleCells.indexOf(selectedCell);
  440. if (index === visibleCells.length - 1) {
  441. index = 0;
  442. } else {
  443. index++;
  444. }
  445. cell = visibleCells[index];
  446. this.emit(EVENTS.ROW_SELECTED, cell.getAttribute("data-id"));
  447. break;
  448. }
  449. },
  450. /**
  451. * Close any editors if the area "outside the table" is clicked. In reality,
  452. * the table covers the whole area but there are labels filling the top few
  453. * rows. This method clears any inline editors if an area outside a textbox or
  454. * label is clicked.
  455. */
  456. onMousedown: function ({target}) {
  457. let nodeName = target.nodeName;
  458. if (nodeName === "textbox" || !this._editableFieldsEngine) {
  459. return;
  460. }
  461. // Force any editor fields to hide due to XUL focus quirks.
  462. this._editableFieldsEngine.blur();
  463. },
  464. /**
  465. * Make table fields editable.
  466. *
  467. * @param {String|Array} editableColumns
  468. * An array or comma separated list of editable column names.
  469. */
  470. makeFieldsEditable: function (editableColumns) {
  471. let selectors = [];
  472. if (typeof editableColumns === "string") {
  473. editableColumns = [editableColumns];
  474. }
  475. for (let id of editableColumns) {
  476. selectors.push("#" + id + " .table-widget-cell");
  477. }
  478. for (let [name, column] of this.columns) {
  479. if (!editableColumns.includes(name)) {
  480. column.column.setAttribute("readonly", "");
  481. }
  482. }
  483. if (this._editableFieldsEngine) {
  484. this._editableFieldsEngine.selectors = selectors;
  485. } else {
  486. this._editableFieldsEngine = new EditableFieldsEngine({
  487. root: this.tbody,
  488. onTab: this.onEditorTab,
  489. onTriggerEvent: "dblclick",
  490. selectors: selectors
  491. });
  492. this._editableFieldsEngine.on("change", this.onChange);
  493. this._editableFieldsEngine.on("destroyed", this.onEditorDestroyed);
  494. this.on(EVENTS.ROW_REMOVED, this.onRowRemoved);
  495. this.on(EVENTS.TABLE_CLEARED, this._editableFieldsEngine.cancelEdit);
  496. this.emit(EVENTS.FIELDS_EDITABLE, this._editableFieldsEngine);
  497. }
  498. },
  499. destroy: function () {
  500. this.off(EVENTS.ROW_SELECTED, this.bindSelectedRow);
  501. this.off(EVENTS.ROW_REMOVED, this.onRowRemoved);
  502. this.document.removeEventListener("keydown", this.onKeydown, false);
  503. this.document.removeEventListener("mousedown", this.onMousedown, false);
  504. if (this._editableFieldsEngine) {
  505. this.off(EVENTS.TABLE_CLEARED, this._editableFieldsEngine.cancelEdit);
  506. this._editableFieldsEngine.off("change", this.onChange);
  507. this._editableFieldsEngine.off("destroyed", this.onEditorDestroyed);
  508. this._editableFieldsEngine.destroy();
  509. this._editableFieldsEngine = null;
  510. }
  511. if (this.menupopup) {
  512. this.menupopup.removeEventListener("command", this.onPopupCommand);
  513. this.menupopup.remove();
  514. }
  515. },
  516. /**
  517. * Sets the text to be shown when the table is empty.
  518. */
  519. setPlaceholderText: function (text) {
  520. this.placeholder.setAttribute("value", text);
  521. },
  522. /**
  523. * Prepares the context menu for the headers of the table columns. This
  524. * context menu allows users to toggle various columns, only with an exception
  525. * of the unique columns and when only two columns are visible in the table.
  526. */
  527. setupHeadersContextMenu: function () {
  528. let popupset = this.document.getElementsByTagName("popupset")[0];
  529. if (!popupset) {
  530. popupset = this.document.createElementNS(XUL_NS, "popupset");
  531. this.document.documentElement.appendChild(popupset);
  532. }
  533. this.menupopup = this.document.createElementNS(XUL_NS, "menupopup");
  534. this.menupopup.id = "table-widget-column-select";
  535. this.menupopup.addEventListener("command", this.onPopupCommand);
  536. popupset.appendChild(this.menupopup);
  537. this.populateMenuPopup();
  538. },
  539. /**
  540. * Populates the header context menu with the names of the columns along with
  541. * displaying which columns are hidden or visible.
  542. *
  543. * @param {Array} privateColumns=[]
  544. * An array of column names that should never appear in the table. This
  545. * allows us to e.g. have an invisible compound primary key for a
  546. * table's rows.
  547. */
  548. populateMenuPopup: function (privateColumns = []) {
  549. if (!this.menupopup) {
  550. return;
  551. }
  552. while (this.menupopup.firstChild) {
  553. this.menupopup.firstChild.remove();
  554. }
  555. for (let column of this.columns.values()) {
  556. if (privateColumns.includes(column.id)) {
  557. continue;
  558. }
  559. let menuitem = this.document.createElementNS(XUL_NS, "menuitem");
  560. menuitem.setAttribute("label", column.header.getAttribute("value"));
  561. menuitem.setAttribute("data-id", column.id);
  562. menuitem.setAttribute("type", "checkbox");
  563. menuitem.setAttribute("checked", !column.wrapper.getAttribute("hidden"));
  564. if (column.id == this.uniqueId) {
  565. menuitem.setAttribute("disabled", "true");
  566. }
  567. this.menupopup.appendChild(menuitem);
  568. }
  569. let checked = this.menupopup.querySelectorAll("menuitem[checked]");
  570. if (checked.length == 2) {
  571. checked[checked.length - 1].setAttribute("disabled", "true");
  572. }
  573. },
  574. /**
  575. * Event handler for the `command` event on the column headers context menu
  576. */
  577. onPopupCommand: function (event) {
  578. let item = event.originalTarget;
  579. let checked = !!item.getAttribute("checked");
  580. let id = item.getAttribute("data-id");
  581. this.emit(EVENTS.HEADER_CONTEXT_MENU, id, checked);
  582. checked = this.menupopup.querySelectorAll("menuitem[checked]");
  583. let disabled = this.menupopup.querySelectorAll("menuitem[disabled]");
  584. if (checked.length == 2) {
  585. checked[checked.length - 1].setAttribute("disabled", "true");
  586. } else if (disabled.length > 1) {
  587. disabled[disabled.length - 1].removeAttribute("disabled");
  588. }
  589. },
  590. /**
  591. * Creates the columns in the table. Without calling this method, data cannot
  592. * be inserted into the table unless `initialColumns` was supplied.
  593. *
  594. * @param {Object} columns
  595. * A key value pair representing the columns of the table. Where the
  596. * key represents the id of the column and the value is the displayed
  597. * label in the header of the column.
  598. * @param {String} sortOn
  599. * The id of the column on which the table will be initially sorted on.
  600. * @param {Array} hiddenColumns
  601. * Ids of all the columns that are hidden by default.
  602. * @param {Array} privateColumns=[]
  603. * An array of column names that should never appear in the table. This
  604. * allows us to e.g. have an invisible compound primary key for a
  605. * table's rows.
  606. */
  607. setColumns: function (columns, sortOn = this.sortedOn, hiddenColumns = [],
  608. privateColumns = []) {
  609. for (let column of this.columns.values()) {
  610. column.destroy();
  611. }
  612. this.columns.clear();
  613. if (!(sortOn in columns)) {
  614. sortOn = null;
  615. }
  616. if (!(this.firstColumn in columns)) {
  617. this.firstColumn = null;
  618. }
  619. if (this.firstColumn) {
  620. this.columns.set(this.firstColumn,
  621. new Column(this, this.firstColumn, columns[this.firstColumn]));
  622. }
  623. for (let id in columns) {
  624. if (!sortOn) {
  625. sortOn = id;
  626. }
  627. if (this.firstColumn && id == this.firstColumn) {
  628. continue;
  629. }
  630. this.columns.set(id, new Column(this, id, columns[id]));
  631. if (hiddenColumns.includes(id) || privateColumns.includes(id)) {
  632. // Hide the column.
  633. this.columns.get(id).toggleColumn();
  634. if (privateColumns.includes(id)) {
  635. this.columns.get(id).private = true;
  636. }
  637. }
  638. }
  639. this.sortedOn = sortOn;
  640. this.sortBy(this.sortedOn);
  641. this.populateMenuPopup(privateColumns);
  642. },
  643. /**
  644. * Returns true if the passed string or the row json object corresponds to the
  645. * selected item in the table.
  646. */
  647. isSelected: function (item) {
  648. if (typeof item == "object") {
  649. item = item[this.uniqueId];
  650. }
  651. return this.selectedRow && item == this.selectedRow[this.uniqueId];
  652. },
  653. /**
  654. * Selects the row corresponding to the `id` json.
  655. */
  656. selectRow: function (id) {
  657. this.selectedRow = id;
  658. },
  659. /**
  660. * Selects the next row. Cycles over to the first row if last row is selected
  661. */
  662. selectNextRow: function () {
  663. for (let column of this.columns.values()) {
  664. column.selectNextRow();
  665. }
  666. },
  667. /**
  668. * Selects the previous row. Cycles over to the last row if first row is
  669. * selected.
  670. */
  671. selectPreviousRow: function () {
  672. for (let column of this.columns.values()) {
  673. column.selectPreviousRow();
  674. }
  675. },
  676. /**
  677. * Clears any selected row.
  678. */
  679. clearSelection: function () {
  680. this.selectedIndex = -1;
  681. },
  682. /**
  683. * Adds a row into the table.
  684. *
  685. * @param {object} item
  686. * The object from which the key-value pairs will be taken and added
  687. * into the row. This object can have any arbitarary key value pairs,
  688. * but only those will be used whose keys match to the ids of the
  689. * columns.
  690. * @param {boolean} suppressFlash
  691. * true to not flash the row while inserting the row.
  692. */
  693. push: function (item, suppressFlash) {
  694. if (!this.sortedOn || !this.columns) {
  695. console.error("Can't insert item without defining columns first");
  696. return;
  697. }
  698. if (this.items.has(item[this.uniqueId])) {
  699. this.update(item);
  700. return;
  701. }
  702. if (this.editBookmark && !this.items.has(this.editBookmark)) {
  703. // Key has been updated... update bookmark.
  704. this.editBookmark = item[this.uniqueId];
  705. }
  706. let index = this.columns.get(this.sortedOn).push(item);
  707. for (let [key, column] of this.columns) {
  708. if (key != this.sortedOn) {
  709. column.insertAt(item, index);
  710. }
  711. column.updateZebra();
  712. }
  713. this.items.set(item[this.uniqueId], item);
  714. this.tbody.removeAttribute("empty");
  715. if (!suppressFlash) {
  716. this.emit(EVENTS.ROW_UPDATED, item[this.uniqueId]);
  717. }
  718. this.emit(EVENTS.ROW_EDIT, item[this.uniqueId]);
  719. },
  720. /**
  721. * Removes the row associated with the `item` object.
  722. */
  723. remove: function (item) {
  724. if (typeof item != "object") {
  725. item = this.items.get(item);
  726. }
  727. if (!item) {
  728. return;
  729. }
  730. let removed = this.items.delete(item[this.uniqueId]);
  731. if (!removed) {
  732. return;
  733. }
  734. for (let column of this.columns.values()) {
  735. column.remove(item);
  736. column.updateZebra();
  737. }
  738. if (this.items.size === 0) {
  739. this.selectedRow = null;
  740. this.tbody.setAttribute("empty", "empty");
  741. }
  742. this.emit(EVENTS.ROW_REMOVED, item);
  743. },
  744. /**
  745. * Updates the items in the row corresponding to the `item` object previously
  746. * used to insert the row using `push` method. The linking is done via the
  747. * `uniqueId` key's value.
  748. */
  749. update: function (item) {
  750. let oldItem = this.items.get(item[this.uniqueId]);
  751. if (!oldItem) {
  752. return;
  753. }
  754. this.items.set(item[this.uniqueId], item);
  755. let changed = false;
  756. for (let column of this.columns.values()) {
  757. if (item[column.id] != oldItem[column.id]) {
  758. column.update(item);
  759. changed = true;
  760. }
  761. }
  762. if (changed) {
  763. this.emit(EVENTS.ROW_UPDATED, item[this.uniqueId]);
  764. this.emit(EVENTS.ROW_EDIT, item[this.uniqueId]);
  765. }
  766. },
  767. /**
  768. * Removes all of the rows from the table.
  769. */
  770. clear: function () {
  771. this.items.clear();
  772. for (let column of this.columns.values()) {
  773. column.clear();
  774. }
  775. this.tbody.setAttribute("empty", "empty");
  776. this.setPlaceholderText(this.emptyText);
  777. this.selectedRow = null;
  778. this.emit(EVENTS.TABLE_CLEARED, this);
  779. },
  780. /**
  781. * Sorts the table by a given column.
  782. *
  783. * @param {string} column
  784. * The id of the column on which the table should be sorted.
  785. */
  786. sortBy: function (column) {
  787. this.emit(EVENTS.COLUMN_SORTED, column);
  788. this.sortedOn = column;
  789. if (!this.items.size) {
  790. return;
  791. }
  792. let sortedItems = this.columns.get(column).sort([...this.items.values()]);
  793. for (let [id, col] of this.columns) {
  794. if (id != col) {
  795. col.sort(sortedItems);
  796. }
  797. }
  798. },
  799. /**
  800. * Filters the table based on a specific value
  801. *
  802. * @param {String} value: The filter value
  803. * @param {Array} ignoreProps: Props to ignore while filtering
  804. */
  805. filterItems(value, ignoreProps = []) {
  806. if (this.filteredValue == value) {
  807. return;
  808. }
  809. if (this._editableFieldsEngine) {
  810. this._editableFieldsEngine.completeEdit();
  811. }
  812. this.filteredValue = value;
  813. if (!value) {
  814. this.emit(EVENTS.TABLE_FILTERED, []);
  815. return;
  816. }
  817. // Shouldn't be case-sensitive
  818. value = value.toLowerCase();
  819. let itemsToHide = [...this.items.keys()];
  820. // Loop through all items and hide unmatched items
  821. for (let [id, val] of this.items) {
  822. for (let prop in val) {
  823. if (ignoreProps.includes(prop)) {
  824. continue;
  825. }
  826. let propValue = val[prop].toString().toLowerCase();
  827. if (propValue.includes(value)) {
  828. itemsToHide.splice(itemsToHide.indexOf(id), 1);
  829. break;
  830. }
  831. }
  832. }
  833. this.emit(EVENTS.TABLE_FILTERED, itemsToHide);
  834. },
  835. /**
  836. * Calls the afterScroll function when the user has stopped scrolling
  837. */
  838. onScroll: function () {
  839. clearNamedTimeout("table-scroll");
  840. setNamedTimeout("table-scroll", AFTER_SCROLL_DELAY, this.afterScroll);
  841. },
  842. /**
  843. * Emits the "scroll-end" event when the whole table is scrolled
  844. */
  845. afterScroll: function () {
  846. let scrollHeight = this.tbody.getBoundingClientRect().height -
  847. this.tbody.querySelector(".table-widget-column-header").clientHeight;
  848. // Emit scroll-end event when 9/10 of the table is scrolled
  849. if (this.tbody.scrollTop >= 0.9 * scrollHeight) {
  850. this.emit("scroll-end");
  851. }
  852. }
  853. };
  854. TableWidget.EVENTS = EVENTS;
  855. module.exports.TableWidget = TableWidget;
  856. /**
  857. * A single column object in the table.
  858. *
  859. * @param {TableWidget} table
  860. * The table object to which the column belongs.
  861. * @param {string} id
  862. * Id of the column.
  863. * @param {String} header
  864. * The displayed string on the column's header.
  865. */
  866. function Column(table, id, header) {
  867. // By default cells are visible in the UI.
  868. this._private = false;
  869. this.tbody = table.tbody;
  870. this.document = table.document;
  871. this.window = table.window;
  872. this.id = id;
  873. this.uniqueId = table.uniqueId;
  874. this.wrapTextInElements = table.wrapTextInElements;
  875. this.table = table;
  876. this.cells = [];
  877. this.items = {};
  878. this.highlightUpdated = table.highlightUpdated;
  879. // This wrapping element is required solely so that position:sticky works on
  880. // the headers of the columns.
  881. this.wrapper = this.document.createElementNS(XUL_NS, "vbox");
  882. this.wrapper.className = "table-widget-wrapper";
  883. this.wrapper.setAttribute("flex", "1");
  884. this.wrapper.setAttribute("tabindex", "0");
  885. this.tbody.appendChild(this.wrapper);
  886. this.splitter = this.document.createElementNS(XUL_NS, "splitter");
  887. this.splitter.className = "devtools-side-splitter";
  888. this.tbody.appendChild(this.splitter);
  889. this.column = this.document.createElementNS(HTML_NS, "div");
  890. this.column.id = id;
  891. this.column.className = "table-widget-column";
  892. this.wrapper.appendChild(this.column);
  893. this.header = this.document.createElementNS(XUL_NS, "label");
  894. this.header.className = "devtools-toolbar table-widget-column-header";
  895. this.header.setAttribute("value", header);
  896. this.column.appendChild(this.header);
  897. if (table.headersContextMenu) {
  898. this.header.setAttribute("context", table.headersContextMenu);
  899. }
  900. this.toggleColumn = this.toggleColumn.bind(this);
  901. this.table.on(EVENTS.HEADER_CONTEXT_MENU, this.toggleColumn);
  902. this.onColumnSorted = this.onColumnSorted.bind(this);
  903. this.table.on(EVENTS.COLUMN_SORTED, this.onColumnSorted);
  904. this.onRowUpdated = this.onRowUpdated.bind(this);
  905. this.table.on(EVENTS.ROW_UPDATED, this.onRowUpdated);
  906. this.onTableFiltered = this.onTableFiltered.bind(this);
  907. this.table.on(EVENTS.TABLE_FILTERED, this.onTableFiltered);
  908. this.onClick = this.onClick.bind(this);
  909. this.onMousedown = this.onMousedown.bind(this);
  910. this.column.addEventListener("click", this.onClick);
  911. this.column.addEventListener("mousedown", this.onMousedown);
  912. }
  913. Column.prototype = {
  914. // items is a cell-id to cell-index map. It is basically a reverse map of the
  915. // this.cells object and is used to quickly reverse lookup a cell by its id
  916. // instead of looping through the cells array. This reverse map is not kept
  917. // upto date in sync with the cells array as updating it is in itself a loop
  918. // through all the cells of the columns. Thus update it on demand when it goes
  919. // out of sync with this.cells.
  920. items: null,
  921. // _itemsDirty is a flag which becomes true when this.items goes out of sync
  922. // with this.cells
  923. _itemsDirty: null,
  924. selectedRow: null,
  925. cells: null,
  926. /**
  927. * Gets whether the table is sorted on this column or not.
  928. * 0 - not sorted.
  929. * 1 - ascending order
  930. * 2 - descending order
  931. */
  932. get sorted() {
  933. return this._sortState || 0;
  934. },
  935. /**
  936. * Get the private state of the column (visibility in the UI).
  937. */
  938. get private() {
  939. return this._private;
  940. },
  941. /**
  942. * Set the private state of the column (visibility in the UI).
  943. *
  944. * @param {Boolean} state
  945. * Private (true or false)
  946. */
  947. set private(state) {
  948. this._private = state;
  949. },
  950. /**
  951. * Sets the sorted value
  952. */
  953. set sorted(value) {
  954. if (!value) {
  955. this.header.removeAttribute("sorted");
  956. } else {
  957. this.header.setAttribute("sorted",
  958. value == 1 ? "ascending" : "descending");
  959. }
  960. this._sortState = value;
  961. },
  962. /**
  963. * Gets the selected row in the column.
  964. */
  965. get selectedIndex() {
  966. if (!this.selectedRow) {
  967. return -1;
  968. }
  969. return this.items[this.selectedRow];
  970. },
  971. get cellNodes() {
  972. return [...this.column.querySelectorAll(".table-widget-cell")];
  973. },
  974. get visibleCellNodes() {
  975. let editor = this.table._editableFieldsEngine;
  976. let nodes = this.cellNodes.filter(node => {
  977. // If the cell is currently being edited we should class it as visible.
  978. if (editor && editor.currentTarget === node) {
  979. return true;
  980. }
  981. return node.clientWidth !== 0;
  982. });
  983. return nodes;
  984. },
  985. /**
  986. * Called when the column is sorted by.
  987. *
  988. * @param {string} event
  989. * The event name of the event. i.e. EVENTS.COLUMN_SORTED
  990. * @param {string} column
  991. * The id of the column being sorted by.
  992. */
  993. onColumnSorted: function (event, column) {
  994. if (column != this.id) {
  995. this.sorted = 0;
  996. return;
  997. } else if (this.sorted == 0 || this.sorted == 2) {
  998. this.sorted = 1;
  999. } else {
  1000. this.sorted = 2;
  1001. }
  1002. this.updateZebra();
  1003. },
  1004. onTableFiltered: function (event, itemsToHide) {
  1005. this._updateItems();
  1006. if (!this.cells) {
  1007. return;
  1008. }
  1009. for (let cell of this.cells) {
  1010. cell.hidden = false;
  1011. }
  1012. for (let id of itemsToHide) {
  1013. this.cells[this.items[id]].hidden = true;
  1014. }
  1015. this.updateZebra();
  1016. },
  1017. /**
  1018. * Called when a row is updated e.g. a cell is changed. This means that
  1019. * for a new row this method will be called once for each column. If a single
  1020. * cell is changed this method will be called just once.
  1021. *
  1022. * @param {string} event
  1023. * The event name of the event. i.e. EVENTS.ROW_UPDATED
  1024. * @param {string} id
  1025. * The unique id of the object associated with the row.
  1026. */
  1027. onRowUpdated: function (event, id) {
  1028. this._updateItems();
  1029. if (this.highlightUpdated && this.items[id] != null) {
  1030. if (this.table.scrollIntoViewOnUpdate) {
  1031. let cell = this.cells[this.items[id]];
  1032. // When a new row is created this method is called once for each column
  1033. // as each cell is updated. We can only scroll to cells if they are
  1034. // visible. We check for visibility and once we find the first visible
  1035. // cell in a row we scroll it into view and reset the
  1036. // scrollIntoViewOnUpdate flag.
  1037. if (cell.label.clientHeight > 0) {
  1038. cell.scrollIntoView();
  1039. this.table.scrollIntoViewOnUpdate = null;
  1040. }
  1041. }
  1042. if (this.table.editBookmark) {
  1043. // A rows position in the table can change as the result of an edit. In
  1044. // order to ensure that the correct row is highlighted after an edit we
  1045. // save the uniqueId in editBookmark. Here we send the signal that the
  1046. // row has been edited and that the row needs to be selected again.
  1047. this.table.emit(EVENTS.ROW_SELECTED, this.table.editBookmark);
  1048. this.table.editBookmark = null;
  1049. }
  1050. this.cells[this.items[id]].flash();
  1051. }
  1052. this.updateZebra();
  1053. },
  1054. destroy: function () {
  1055. this.table.off(EVENTS.COLUMN_SORTED, this.onColumnSorted);
  1056. this.table.off(EVENTS.HEADER_CONTEXT_MENU, this.toggleColumn);
  1057. this.table.off(EVENTS.ROW_UPDATED, this.onRowUpdated);
  1058. this.table.off(EVENTS.TABLE_FILTERED, this.onTableFiltered);
  1059. this.column.removeEventListener("click", this.onClick);
  1060. this.column.removeEventListener("mousedown", this.onMousedown);
  1061. this.splitter.remove();
  1062. this.column.parentNode.remove();
  1063. this.cells = null;
  1064. this.items = null;
  1065. this.selectedRow = null;
  1066. },
  1067. /**
  1068. * Selects the row at the `index` index
  1069. */
  1070. selectRowAt: function (index) {
  1071. if (this.selectedRow != null) {
  1072. this.cells[this.items[this.selectedRow]].classList.remove("theme-selected");
  1073. }
  1074. let cell = this.cells[index];
  1075. if (cell) {
  1076. cell.classList.add("theme-selected");
  1077. this.selectedRow = cell.id;
  1078. } else {
  1079. this.selectedRow = null;
  1080. }
  1081. },
  1082. /**
  1083. * Selects the row with the object having the `uniqueId` value as `id`
  1084. */
  1085. selectRow: function (id) {
  1086. this._updateItems();
  1087. this.selectRowAt(this.items[id]);
  1088. },
  1089. /**
  1090. * Selects the next row. Cycles to first if last row is selected.
  1091. */
  1092. selectNextRow: function () {
  1093. this._updateItems();
  1094. let index = this.items[this.selectedRow] + 1;
  1095. if (index == this.cells.length) {
  1096. index = 0;
  1097. }
  1098. this.selectRowAt(index);
  1099. },
  1100. /**
  1101. * Selects the previous row. Cycles to last if first row is selected.
  1102. */
  1103. selectPreviousRow: function () {
  1104. this._updateItems();
  1105. let index = this.items[this.selectedRow] - 1;
  1106. if (index == -1) {
  1107. index = this.cells.length - 1;
  1108. }
  1109. this.selectRowAt(index);
  1110. },
  1111. /**
  1112. * Pushes the `item` object into the column. If this column is sorted on,
  1113. * then inserts the object at the right position based on the column's id
  1114. * key's value.
  1115. *
  1116. * @returns {number}
  1117. * The index of the currently pushed item.
  1118. */
  1119. push: function (item) {
  1120. let value = item[this.id];
  1121. if (this.sorted) {
  1122. let index;
  1123. if (this.sorted == 1) {
  1124. index = this.cells.findIndex(element => {
  1125. return naturalSortCaseInsensitive(value, element.value) === -1;
  1126. });
  1127. } else {
  1128. index = this.cells.findIndex(element => {
  1129. return naturalSortCaseInsensitive(value, element.value) === 1;
  1130. });
  1131. }
  1132. index = index >= 0 ? index : this.cells.length;
  1133. if (index < this.cells.length) {
  1134. this._itemsDirty = true;
  1135. }
  1136. this.items[item[this.uniqueId]] = index;
  1137. this.cells.splice(index, 0, new Cell(this, item, this.cells[index]));
  1138. return index;
  1139. }
  1140. this.items[item[this.uniqueId]] = this.cells.length;
  1141. return this.cells.push(new Cell(this, item)) - 1;
  1142. },
  1143. /**
  1144. * Inserts the `item` object at the given `index` index in the table.
  1145. */
  1146. insertAt: function (item, index) {
  1147. if (index < this.cells.length) {
  1148. this._itemsDirty = true;
  1149. }
  1150. this.items[item[this.uniqueId]] = index;
  1151. this.cells.splice(index, 0, new Cell(this, item, this.cells[index]));
  1152. this.updateZebra();
  1153. },
  1154. /**
  1155. * Event handler for the command event coming from the header context menu.
  1156. * Toggles the column if it was requested by the user.
  1157. * When called explicitly without parameters, it toggles the corresponding
  1158. * column.
  1159. *
  1160. * @param {string} event
  1161. * The name of the event. i.e. EVENTS.HEADER_CONTEXT_MENU
  1162. * @param {string} id
  1163. * Id of the column to be toggled
  1164. * @param {string} checked
  1165. * true if the column is visible
  1166. */
  1167. toggleColumn: function (event, id, checked) {
  1168. if (arguments.length == 0) {
  1169. // Act like a toggling method when called with no params
  1170. id = this.id;
  1171. checked = this.wrapper.hasAttribute("hidden");
  1172. }
  1173. if (id != this.id) {
  1174. return;
  1175. }
  1176. if (checked) {
  1177. this.wrapper.removeAttribute("hidden");
  1178. } else {
  1179. this.wrapper.setAttribute("hidden", "true");
  1180. }
  1181. },
  1182. /**
  1183. * Removes the corresponding item from the column.
  1184. */
  1185. remove: function (item) {
  1186. this._updateItems();
  1187. let index = this.items[item[this.uniqueId]];
  1188. if (index == null) {
  1189. return;
  1190. }
  1191. if (index < this.cells.length) {
  1192. this._itemsDirty = true;
  1193. }
  1194. this.cells[index].destroy();
  1195. this.cells.splice(index, 1);
  1196. delete this.items[item[this.uniqueId]];
  1197. },
  1198. /**
  1199. * Updates the corresponding item from the column.
  1200. */
  1201. update: function (item) {
  1202. this._updateItems();
  1203. let index = this.items[item[this.uniqueId]];
  1204. if (index == null) {
  1205. return;
  1206. }
  1207. this.cells[index].value = item[this.id];
  1208. },
  1209. /**
  1210. * Updates the `this.items` cell-id vs cell-index map to be in sync with
  1211. * `this.cells`.
  1212. */
  1213. _updateItems: function () {
  1214. if (!this._itemsDirty) {
  1215. return;
  1216. }
  1217. for (let i = 0; i < this.cells.length; i++) {
  1218. this.items[this.cells[i].id] = i;
  1219. }
  1220. this._itemsDirty = false;
  1221. },
  1222. /**
  1223. * Clears the current column
  1224. */
  1225. clear: function () {
  1226. this.cells = [];
  1227. this.items = {};
  1228. this._itemsDirty = false;
  1229. while (this.header.nextSibling) {
  1230. this.header.nextSibling.remove();
  1231. }
  1232. },
  1233. /**
  1234. * Sorts the given items and returns the sorted list if the table was sorted
  1235. * by this column.
  1236. */
  1237. sort: function (items) {
  1238. // Only sort the array if we are sorting based on this column
  1239. if (this.sorted == 1) {
  1240. items.sort((a, b) => {
  1241. let val1 = (a[this.id] instanceof Node) ?
  1242. a[this.id].textContent : a[this.id];
  1243. let val2 = (b[this.id] instanceof Node) ?
  1244. b[this.id].textContent : b[this.id];
  1245. return naturalSortCaseInsensitive(val1, val2);
  1246. });
  1247. } else if (this.sorted > 1) {
  1248. items.sort((a, b) => {
  1249. let val1 = (a[this.id] instanceof Node) ?
  1250. a[this.id].textContent : a[this.id];
  1251. let val2 = (b[this.id] instanceof Node) ?
  1252. b[this.id].textContent : b[this.id];
  1253. return naturalSortCaseInsensitive(val2, val1);
  1254. });
  1255. }
  1256. if (this.selectedRow) {
  1257. this.cells[this.items[this.selectedRow]].classList.remove("theme-selected");
  1258. }
  1259. this.items = {};
  1260. // Otherwise, just use the sorted array passed to update the cells value.
  1261. items.forEach((item, i) => {
  1262. this.items[item[this.uniqueId]] = i;
  1263. this.cells[i].value = item[this.id];
  1264. this.cells[i].id = item[this.uniqueId];
  1265. });
  1266. if (this.selectedRow) {
  1267. this.cells[this.items[this.selectedRow]].classList.add("theme-selected");
  1268. }
  1269. this._itemsDirty = false;
  1270. this.updateZebra();
  1271. return items;
  1272. },
  1273. updateZebra() {
  1274. this._updateItems();
  1275. let i = 0;
  1276. for (let cell of this.cells) {
  1277. if (!cell.hidden) {
  1278. i++;
  1279. }
  1280. let even = !(i % 2);
  1281. cell.classList.toggle("even", even);
  1282. }
  1283. },
  1284. /**
  1285. * Click event handler for the column. Used to detect click on header for
  1286. * for sorting.
  1287. */
  1288. onClick: function (event) {
  1289. let target = event.originalTarget;
  1290. if (target.nodeType !== target.ELEMENT_NODE || target == this.column) {
  1291. return;
  1292. }
  1293. if (event.button == 0 && target == this.header) {
  1294. this.table.sortBy(this.id);
  1295. }
  1296. },
  1297. /**
  1298. * Mousedown event handler for the column. Used to select rows.
  1299. */
  1300. onMousedown: function (event) {
  1301. let target = event.originalTarget;
  1302. if (target.nodeType !== target.ELEMENT_NODE ||
  1303. target == this.column ||
  1304. target == this.header) {
  1305. return;
  1306. }
  1307. if (event.button == 0) {
  1308. let closest = target.closest("[data-id]");
  1309. if (!closest) {
  1310. return;
  1311. }
  1312. let dataid = closest.getAttribute("data-id");
  1313. this.table.emit(EVENTS.ROW_SELECTED, dataid);
  1314. }
  1315. },
  1316. };
  1317. /**
  1318. * A single cell in a column
  1319. *
  1320. * @param {Column} column
  1321. * The column object to which the cell belongs.
  1322. * @param {object} item
  1323. * The object representing the row. It contains a key value pair
  1324. * representing the column id and its associated value. The value
  1325. * can be a DOMNode that is appended or a string value.
  1326. * @param {Cell} nextCell
  1327. * The cell object which is next to this cell. null if this cell is last
  1328. * cell of the column
  1329. */
  1330. function Cell(column, item, nextCell) {
  1331. let document = column.document;
  1332. this.wrapTextInElements = column.wrapTextInElements;
  1333. this.label = document.createElementNS(XUL_NS, "label");
  1334. this.label.setAttribute("crop", "end");
  1335. this.label.className = "plain table-widget-cell";
  1336. if (nextCell) {
  1337. column.column.insertBefore(this.label, nextCell.label);
  1338. } else {
  1339. column.column.appendChild(this.label);
  1340. }
  1341. if (column.table.cellContextMenuId) {
  1342. this.label.setAttribute("context", column.table.cellContextMenuId);
  1343. this.label.addEventListener("contextmenu", (event) => {
  1344. // Make the ID of the clicked cell available as a property on the table.
  1345. // It's then available for the popupshowing or command handler.
  1346. column.table.contextMenuRowId = this.id;
  1347. }, false);
  1348. }
  1349. this.value = item[column.id];
  1350. this.id = item[column.uniqueId];
  1351. }
  1352. Cell.prototype = {
  1353. set id(value) {
  1354. this._id = value;
  1355. this.label.setAttribute("data-id", value);
  1356. },
  1357. get id() {
  1358. return this._id;
  1359. },
  1360. get hidden() {
  1361. return this.label.hasAttribute("hidden");
  1362. },
  1363. set hidden(value) {
  1364. if (value) {
  1365. this.label.setAttribute("hidden", "hidden");
  1366. } else {
  1367. this.label.removeAttribute("hidden");
  1368. }
  1369. },
  1370. set value(value) {
  1371. this._value = value;
  1372. if (value == null) {
  1373. this.label.setAttribute("value", "");
  1374. return;
  1375. }
  1376. if (this.wrapTextInElements && !(value instanceof Node)) {
  1377. let span = this.label.ownerDocument.createElementNS(HTML_NS, "span");
  1378. span.textContent = value;
  1379. value = span;
  1380. }
  1381. if (value instanceof Node) {
  1382. this.label.removeAttribute("value");
  1383. while (this.label.firstChild) {
  1384. this.label.removeChild(this.label.firstChild);
  1385. }
  1386. this.label.appendChild(value);
  1387. } else {
  1388. this.label.setAttribute("value", value + "");
  1389. }
  1390. },
  1391. get value() {
  1392. return this._value;
  1393. },
  1394. get classList() {
  1395. return this.label.classList;
  1396. },
  1397. /**
  1398. * Flashes the cell for a brief time. This when done for with cells in all
  1399. * columns, makes it look like the row is being highlighted/flashed.
  1400. */
  1401. flash: function () {
  1402. if (!this.label.parentNode) {
  1403. return;
  1404. }
  1405. this.label.classList.remove("flash-out");
  1406. // Cause a reflow so that the animation retriggers on adding back the class
  1407. let a = this.label.parentNode.offsetWidth; // eslint-disable-line
  1408. let onAnimEnd = () => {
  1409. this.label.classList.remove("flash-out");
  1410. this.label.removeEventListener("animationend", onAnimEnd);
  1411. };
  1412. this.label.addEventListener("animationend", onAnimEnd);
  1413. this.label.classList.add("flash-out");
  1414. },
  1415. focus: function () {
  1416. this.label.focus();
  1417. },
  1418. scrollIntoView: function () {
  1419. this.label.scrollIntoView(false);
  1420. },
  1421. destroy: function () {
  1422. this.label.remove();
  1423. this.label = null;
  1424. }
  1425. };
  1426. /**
  1427. * Simple widget to make nodes matching a CSS selector editable.
  1428. *
  1429. * @param {Object} options
  1430. * An object with the following format:
  1431. * {
  1432. * // The node that will act as a container for the editor e.g. a
  1433. * // div or table.
  1434. * root: someNode,
  1435. *
  1436. * // The onTab event to be handled by the caller.
  1437. * onTab: function(event) { ... }
  1438. *
  1439. * // Optional event used to trigger the editor. By default this is
  1440. * // dblclick.
  1441. * onTriggerEvent: "dblclick",
  1442. *
  1443. * // Array or comma separated string of CSS Selectors matching
  1444. * // elements that are to be made editable.
  1445. * selectors: [
  1446. * "#name .table-widget-cell",
  1447. * "#value .table-widget-cell"
  1448. * ]
  1449. * }
  1450. */
  1451. function EditableFieldsEngine(options) {
  1452. EventEmitter.decorate(this);
  1453. if (!Array.isArray(options.selectors)) {
  1454. options.selectors = [options.selectors];
  1455. }
  1456. this.root = options.root;
  1457. this.selectors = options.selectors;
  1458. this.onTab = options.onTab;
  1459. this.onTriggerEvent = options.onTriggerEvent || "dblclick";
  1460. this.edit = this.edit.bind(this);
  1461. this.cancelEdit = this.cancelEdit.bind(this);
  1462. this.destroy = this.destroy.bind(this);
  1463. this.onTrigger = this.onTrigger.bind(this);
  1464. this.root.addEventListener(this.onTriggerEvent, this.onTrigger);
  1465. }
  1466. EditableFieldsEngine.prototype = {
  1467. INPUT_ID: "inlineEditor",
  1468. get changePending() {
  1469. return this.isEditing && (this.textbox.value !== this.currentValue);
  1470. },
  1471. get isEditing() {
  1472. return this.root && !this.textbox.hidden;
  1473. },
  1474. get textbox() {
  1475. if (!this._textbox) {
  1476. let doc = this.root.ownerDocument;
  1477. this._textbox = doc.createElementNS(XUL_NS, "textbox");
  1478. this._textbox.id = this.INPUT_ID;
  1479. this._textbox.setAttribute("flex", "1");
  1480. this.onKeydown = this.onKeydown.bind(this);
  1481. this._textbox.addEventListener("keydown", this.onKeydown);
  1482. this.completeEdit = this.completeEdit.bind(this);
  1483. doc.addEventListener("blur", this.completeEdit);
  1484. }
  1485. return this._textbox;
  1486. },
  1487. /**
  1488. * Called when a trigger event is detected (default is dblclick).
  1489. *
  1490. * @param {EventTarget} target
  1491. * Calling event's target.
  1492. */
  1493. onTrigger: function ({target}) {
  1494. this.edit(target);
  1495. },
  1496. /**
  1497. * Handle keypresses when in edit mode:
  1498. * - <escape> revert the value and close the textbox.
  1499. * - <return> apply the value and close the textbox.
  1500. * - <tab> Handled by the consumer's `onTab` callback.
  1501. * - <shift><tab> Handled by the consumer's `onTab` callback.
  1502. *
  1503. * @param {Event} event
  1504. * The calling event.
  1505. */
  1506. onKeydown: function (event) {
  1507. if (!this.textbox) {
  1508. return;
  1509. }
  1510. switch (event.keyCode) {
  1511. case KeyCodes.DOM_VK_ESCAPE:
  1512. this.cancelEdit();
  1513. event.preventDefault();
  1514. break;
  1515. case KeyCodes.DOM_VK_RETURN:
  1516. this.completeEdit();
  1517. break;
  1518. case KeyCodes.DOM_VK_TAB:
  1519. if (this.onTab) {
  1520. this.onTab(event);
  1521. }
  1522. break;
  1523. }
  1524. },
  1525. /**
  1526. * Overlay the target node with an edit field.
  1527. *
  1528. * @param {Node} target
  1529. * Dom node to be edited.
  1530. */
  1531. edit: function (target) {
  1532. if (!target) {
  1533. return;
  1534. }
  1535. target.scrollIntoView(false);
  1536. target.focus();
  1537. if (!target.matches(this.selectors.join(","))) {
  1538. return;
  1539. }
  1540. // If we are actively editing something complete the edit first.
  1541. if (this.isEditing) {
  1542. this.completeEdit();
  1543. }
  1544. this.copyStyles(target, this.textbox);
  1545. target.parentNode.insertBefore(this.textbox, target);
  1546. this.currentTarget = target;
  1547. this.textbox.value = this.currentValue = target.value;
  1548. target.hidden = true;
  1549. this.textbox.hidden = false;
  1550. this.textbox.focus();
  1551. this.textbox.select();
  1552. },
  1553. completeEdit: function () {
  1554. if (!this.isEditing) {
  1555. return;
  1556. }
  1557. let oldValue = this.currentValue;
  1558. let newValue = this.textbox.value;
  1559. let changed = oldValue !== newValue;
  1560. this.textbox.hidden = true;
  1561. if (!this.currentTarget) {
  1562. return;
  1563. }
  1564. this.currentTarget.hidden = false;
  1565. if (changed) {
  1566. this.currentTarget.value = newValue;
  1567. let data = {
  1568. change: {
  1569. field: this.currentTarget,
  1570. oldValue: oldValue,
  1571. newValue: newValue
  1572. }
  1573. };
  1574. this.emit("change", data);
  1575. }
  1576. },
  1577. /**
  1578. * Cancel an edit.
  1579. */
  1580. cancelEdit: function () {
  1581. if (!this.isEditing) {
  1582. return;
  1583. }
  1584. if (this.currentTarget) {
  1585. this.currentTarget.hidden = false;
  1586. }
  1587. this.textbox.hidden = true;
  1588. },
  1589. /**
  1590. * Stop edit mode and apply changes.
  1591. */
  1592. blur: function () {
  1593. if (this.isEditing) {
  1594. this.completeEdit();
  1595. }
  1596. },
  1597. /**
  1598. * Copies various styles from one node to another.
  1599. *
  1600. * @param {Node} source
  1601. * The node to copy styles from.
  1602. * @param {Node} destination [description]
  1603. * The node to copy styles to.
  1604. */
  1605. copyStyles: function (source, destination) {
  1606. let style = source.ownerDocument.defaultView.getComputedStyle(source);
  1607. let props = [
  1608. "borderTopWidth",
  1609. "borderRightWidth",
  1610. "borderBottomWidth",
  1611. "borderLeftWidth",
  1612. "fontFamily",
  1613. "fontSize",
  1614. "fontWeight",
  1615. "height",
  1616. "marginTop",
  1617. "marginRight",
  1618. "marginBottom",
  1619. "marginLeft",
  1620. "marginInlineStart",
  1621. "marginInlineEnd"
  1622. ];
  1623. for (let prop of props) {
  1624. destination.style[prop] = style[prop];
  1625. }
  1626. // We need to set the label width to 100% to work around a XUL flex bug.
  1627. destination.style.width = "100%";
  1628. },
  1629. /**
  1630. * Destroys all editors in the current document.
  1631. */
  1632. destroy: function () {
  1633. if (this.textbox) {
  1634. this.textbox.removeEventListener("keydown", this.onKeydown);
  1635. this.textbox.remove();
  1636. }
  1637. if (this.root) {
  1638. this.root.removeEventListener(this.onTriggerEvent, this.onTrigger);
  1639. this.root.ownerDocument.removeEventListener("blur", this.completeEdit);
  1640. }
  1641. this._textbox = this.root = this.selectors = this.onTab = null;
  1642. this.currentTarget = this.currentValue = null;
  1643. this.emit("destroyed");
  1644. },
  1645. };