You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2517 lines
74KB

  1. /*
  2. * jsGrid v1.5.3 (http://js-grid.com)
  3. * (c) 2016 Artem Tabalin
  4. * Licensed under MIT (https://github.com/tabalinas/jsgrid/blob/master/LICENSE)
  5. */
  6. (function(window, $, undefined) {
  7. var JSGRID = "JSGrid",
  8. JSGRID_DATA_KEY = JSGRID,
  9. JSGRID_ROW_DATA_KEY = "JSGridItem",
  10. JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow",
  11. SORT_ORDER_ASC = "asc",
  12. SORT_ORDER_DESC = "desc",
  13. FIRST_PAGE_PLACEHOLDER = "{first}",
  14. PAGES_PLACEHOLDER = "{pages}",
  15. PREV_PAGE_PLACEHOLDER = "{prev}",
  16. NEXT_PAGE_PLACEHOLDER = "{next}",
  17. LAST_PAGE_PLACEHOLDER = "{last}",
  18. PAGE_INDEX_PLACEHOLDER = "{pageIndex}",
  19. PAGE_COUNT_PLACEHOLDER = "{pageCount}",
  20. ITEM_COUNT_PLACEHOLDER = "{itemCount}",
  21. EMPTY_HREF = "javascript:void(0);";
  22. var getOrApply = function(value, context) {
  23. if($.isFunction(value)) {
  24. return value.apply(context, $.makeArray(arguments).slice(2));
  25. }
  26. return value;
  27. };
  28. var normalizePromise = function(promise) {
  29. var d = $.Deferred();
  30. if(promise && promise.then) {
  31. promise.then(function() {
  32. d.resolve.apply(d, arguments);
  33. }, function() {
  34. d.reject.apply(d, arguments);
  35. });
  36. } else {
  37. d.resolve(promise);
  38. }
  39. return d.promise();
  40. };
  41. var defaultController = {
  42. loadData: $.noop,
  43. insertItem: $.noop,
  44. updateItem: $.noop,
  45. deleteItem: $.noop
  46. };
  47. function Grid(element, config) {
  48. var $element = $(element);
  49. $element.data(JSGRID_DATA_KEY, this);
  50. this._container = $element;
  51. this.data = [];
  52. this.fields = [];
  53. this._editingRow = null;
  54. this._sortField = null;
  55. this._sortOrder = SORT_ORDER_ASC;
  56. this._firstDisplayingPage = 1;
  57. this._init(config);
  58. this.render();
  59. }
  60. Grid.prototype = {
  61. width: "auto",
  62. height: "auto",
  63. updateOnResize: true,
  64. rowClass: $.noop,
  65. rowRenderer: null,
  66. rowClick: function(args) {
  67. if(this.editing) {
  68. this.editItem($(args.event.target).closest("tr"));
  69. }
  70. },
  71. rowDoubleClick: $.noop,
  72. noDataContent: "Not found",
  73. noDataRowClass: "jsgrid-nodata-row",
  74. heading: true,
  75. headerRowRenderer: null,
  76. headerRowClass: "jsgrid-header-row",
  77. headerCellClass: "jsgrid-header-cell",
  78. filtering: false,
  79. filterRowRenderer: null,
  80. filterRowClass: "jsgrid-filter-row",
  81. inserting: false,
  82. insertRowRenderer: null,
  83. insertRowClass: "jsgrid-insert-row",
  84. editing: false,
  85. editRowRenderer: null,
  86. editRowClass: "jsgrid-edit-row",
  87. confirmDeleting: true,
  88. deleteConfirm: "Are you sure?",
  89. selecting: true,
  90. selectedRowClass: "jsgrid-selected-row",
  91. oddRowClass: "jsgrid-row",
  92. evenRowClass: "jsgrid-alt-row",
  93. cellClass: "jsgrid-cell",
  94. sorting: false,
  95. sortableClass: "jsgrid-header-sortable",
  96. sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc",
  97. sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc",
  98. paging: false,
  99. pagerContainer: null,
  100. pageIndex: 1,
  101. pageSize: 20,
  102. pageButtonCount: 15,
  103. pagerFormat: "Pages: {first} {prev} {pages} {next} {last}    {pageIndex} of {pageCount}",
  104. pagePrevText: "Prev",
  105. pageNextText: "Next",
  106. pageFirstText: "First",
  107. pageLastText: "Last",
  108. pageNavigatorNextText: "...",
  109. pageNavigatorPrevText: "...",
  110. pagerContainerClass: "jsgrid-pager-container",
  111. pagerClass: "jsgrid-pager",
  112. pagerNavButtonClass: "jsgrid-pager-nav-button",
  113. pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button",
  114. pageClass: "jsgrid-pager-page",
  115. currentPageClass: "jsgrid-pager-current-page",
  116. customLoading: false,
  117. pageLoading: false,
  118. autoload: false,
  119. controller: defaultController,
  120. loadIndication: true,
  121. loadIndicationDelay: 500,
  122. loadMessage: "Please, wait...",
  123. loadShading: true,
  124. invalidMessage: "Invalid data entered!",
  125. invalidNotify: function(args) {
  126. var messages = $.map(args.errors, function(error) {
  127. return error.message || null;
  128. });
  129. window.alert([this.invalidMessage].concat(messages).join("\n"));
  130. },
  131. onInit: $.noop,
  132. onRefreshing: $.noop,
  133. onRefreshed: $.noop,
  134. onPageChanged: $.noop,
  135. onItemDeleting: $.noop,
  136. onItemDeleted: $.noop,
  137. onItemInserting: $.noop,
  138. onItemInserted: $.noop,
  139. onItemEditing: $.noop,
  140. onItemUpdating: $.noop,
  141. onItemUpdated: $.noop,
  142. onItemInvalid: $.noop,
  143. onDataLoading: $.noop,
  144. onDataLoaded: $.noop,
  145. onOptionChanging: $.noop,
  146. onOptionChanged: $.noop,
  147. onError: $.noop,
  148. invalidClass: "jsgrid-invalid",
  149. containerClass: "jsgrid",
  150. tableClass: "jsgrid-table",
  151. gridHeaderClass: "jsgrid-grid-header",
  152. gridBodyClass: "jsgrid-grid-body",
  153. _init: function(config) {
  154. $.extend(this, config);
  155. this._initLoadStrategy();
  156. this._initController();
  157. this._initFields();
  158. this._attachWindowLoadResize();
  159. this._attachWindowResizeCallback();
  160. this._callEventHandler(this.onInit)
  161. },
  162. loadStrategy: function() {
  163. return this.pageLoading
  164. ? new jsGrid.loadStrategies.PageLoadingStrategy(this)
  165. : new jsGrid.loadStrategies.DirectLoadingStrategy(this);
  166. },
  167. _initLoadStrategy: function() {
  168. this._loadStrategy = getOrApply(this.loadStrategy, this);
  169. },
  170. _initController: function() {
  171. this._controller = $.extend({}, defaultController, getOrApply(this.controller, this));
  172. },
  173. renderTemplate: function(source, context, config) {
  174. args = [];
  175. for(var key in config) {
  176. args.push(config[key]);
  177. }
  178. args.unshift(source, context);
  179. source = getOrApply.apply(null, args);
  180. return (source === undefined || source === null) ? "" : source;
  181. },
  182. loadIndicator: function(config) {
  183. return new jsGrid.LoadIndicator(config);
  184. },
  185. validation: function(config) {
  186. return jsGrid.Validation && new jsGrid.Validation(config);
  187. },
  188. _initFields: function() {
  189. var self = this;
  190. self.fields = $.map(self.fields, function(field) {
  191. if($.isPlainObject(field)) {
  192. var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field;
  193. field = new fieldConstructor(field);
  194. }
  195. field._grid = self;
  196. return field;
  197. });
  198. },
  199. _attachWindowLoadResize: function() {
  200. $(window).on("load", $.proxy(this._refreshSize, this));
  201. },
  202. _attachWindowResizeCallback: function() {
  203. if(this.updateOnResize) {
  204. $(window).on("resize", $.proxy(this._refreshSize, this));
  205. }
  206. },
  207. _detachWindowResizeCallback: function() {
  208. $(window).off("resize", this._refreshSize);
  209. },
  210. option: function(key, value) {
  211. var optionChangingEventArgs,
  212. optionChangedEventArgs;
  213. if(arguments.length === 1)
  214. return this[key];
  215. optionChangingEventArgs = {
  216. option: key,
  217. oldValue: this[key],
  218. newValue: value
  219. };
  220. this._callEventHandler(this.onOptionChanging, optionChangingEventArgs);
  221. this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue);
  222. optionChangedEventArgs = {
  223. option: optionChangingEventArgs.option,
  224. value: optionChangingEventArgs.newValue
  225. };
  226. this._callEventHandler(this.onOptionChanged, optionChangedEventArgs);
  227. },
  228. fieldOption: function(field, key, value) {
  229. field = this._normalizeField(field);
  230. if(arguments.length === 2)
  231. return field[key];
  232. field[key] = value;
  233. this._renderGrid();
  234. },
  235. _handleOptionChange: function(name, value) {
  236. this[name] = value;
  237. switch(name) {
  238. case "width":
  239. case "height":
  240. this._refreshSize();
  241. break;
  242. case "rowClass":
  243. case "rowRenderer":
  244. case "rowClick":
  245. case "rowDoubleClick":
  246. case "noDataRowClass":
  247. case "noDataContent":
  248. case "selecting":
  249. case "selectedRowClass":
  250. case "oddRowClass":
  251. case "evenRowClass":
  252. this._refreshContent();
  253. break;
  254. case "pageButtonCount":
  255. case "pagerFormat":
  256. case "pagePrevText":
  257. case "pageNextText":
  258. case "pageFirstText":
  259. case "pageLastText":
  260. case "pageNavigatorNextText":
  261. case "pageNavigatorPrevText":
  262. case "pagerClass":
  263. case "pagerNavButtonClass":
  264. case "pageClass":
  265. case "currentPageClass":
  266. case "pagerRenderer":
  267. this._refreshPager();
  268. break;
  269. case "fields":
  270. this._initFields();
  271. this.render();
  272. break;
  273. case "data":
  274. case "editing":
  275. case "heading":
  276. case "filtering":
  277. case "inserting":
  278. case "paging":
  279. this.refresh();
  280. break;
  281. case "loadStrategy":
  282. case "pageLoading":
  283. this._initLoadStrategy();
  284. this.search();
  285. break;
  286. case "pageIndex":
  287. this.openPage(value);
  288. break;
  289. case "pageSize":
  290. this.refresh();
  291. this.search();
  292. break;
  293. case "editRowRenderer":
  294. case "editRowClass":
  295. this.cancelEdit();
  296. break;
  297. case "updateOnResize":
  298. this._detachWindowResizeCallback();
  299. this._attachWindowResizeCallback();
  300. break;
  301. case "invalidNotify":
  302. case "invalidMessage":
  303. break;
  304. default:
  305. this.render();
  306. break;
  307. }
  308. },
  309. destroy: function() {
  310. this._detachWindowResizeCallback();
  311. this._clear();
  312. this._container.removeData(JSGRID_DATA_KEY);
  313. },
  314. render: function() {
  315. this._renderGrid();
  316. return this.autoload ? this.loadData() : $.Deferred().resolve().promise();
  317. },
  318. _renderGrid: function() {
  319. this._clear();
  320. this._container.addClass(this.containerClass)
  321. .css("position", "relative")
  322. .append(this._createHeader())
  323. .append(this._createBody());
  324. this._pagerContainer = this._createPagerContainer();
  325. this._loadIndicator = this._createLoadIndicator();
  326. this._validation = this._createValidation();
  327. this.refresh();
  328. },
  329. _createLoadIndicator: function() {
  330. return getOrApply(this.loadIndicator, this, {
  331. message: this.loadMessage,
  332. shading: this.loadShading,
  333. container: this._container
  334. });
  335. },
  336. _createValidation: function() {
  337. return getOrApply(this.validation, this);
  338. },
  339. _clear: function() {
  340. this.cancelEdit();
  341. clearTimeout(this._loadingTimer);
  342. this._pagerContainer && this._pagerContainer.empty();
  343. this._container.empty()
  344. .css({ position: "", width: "", height: "" });
  345. },
  346. _createHeader: function() {
  347. var $headerRow = this._headerRow = this._createHeaderRow(),
  348. $filterRow = this._filterRow = this._createFilterRow(),
  349. $insertRow = this._insertRow = this._createInsertRow();
  350. var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass)
  351. .append($headerRow)
  352. .append($filterRow)
  353. .append($insertRow);
  354. var $header = this._header = $("<div>").addClass(this.gridHeaderClass)
  355. .addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "")
  356. .append($headerGrid);
  357. return $header;
  358. },
  359. _createBody: function() {
  360. var $content = this._content = $("<tbody>");
  361. var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass)
  362. .append($content);
  363. var $body = this._body = $("<div>").addClass(this.gridBodyClass)
  364. .append($bodyGrid)
  365. .on("scroll", $.proxy(function(e) {
  366. this._header.scrollLeft(e.target.scrollLeft);
  367. }, this));
  368. return $body;
  369. },
  370. _createPagerContainer: function() {
  371. var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container);
  372. return $(pagerContainer).addClass(this.pagerContainerClass);
  373. },
  374. _eachField: function(callBack) {
  375. var self = this;
  376. $.each(this.fields, function(index, field) {
  377. if(field.visible) {
  378. callBack.call(self, field, index);
  379. }
  380. });
  381. },
  382. _createHeaderRow: function() {
  383. if($.isFunction(this.headerRowRenderer))
  384. return $(this.renderTemplate(this.headerRowRenderer, this));
  385. var $result = $("<tr>").addClass(this.headerRowClass);
  386. this._eachField(function(field, index) {
  387. var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass)
  388. .append(this.renderTemplate(field.headerTemplate, field))
  389. .appendTo($result);
  390. if(this.sorting && field.sorting) {
  391. $th.addClass(this.sortableClass)
  392. .on("click", $.proxy(function() {
  393. this.sort(index);
  394. }, this));
  395. }
  396. });
  397. return $result;
  398. },
  399. _prepareCell: function(cell, field, cssprop, cellClass) {
  400. return $(cell).css("width", field.width)
  401. .addClass(cellClass || this.cellClass)
  402. .addClass((cssprop && field[cssprop]) || field.css)
  403. .addClass(field.align ? ("jsgrid-align-" + field.align) : "");
  404. },
  405. _createFilterRow: function() {
  406. if($.isFunction(this.filterRowRenderer))
  407. return $(this.renderTemplate(this.filterRowRenderer, this));
  408. var $result = $("<tr>").addClass(this.filterRowClass);
  409. this._eachField(function(field) {
  410. this._prepareCell("<td>", field, "filtercss")
  411. .append(this.renderTemplate(field.filterTemplate, field))
  412. .appendTo($result);
  413. });
  414. return $result;
  415. },
  416. _createInsertRow: function() {
  417. if($.isFunction(this.insertRowRenderer))
  418. return $(this.renderTemplate(this.insertRowRenderer, this));
  419. var $result = $("<tr>").addClass(this.insertRowClass);
  420. this._eachField(function(field) {
  421. this._prepareCell("<td>", field, "insertcss")
  422. .append(this.renderTemplate(field.insertTemplate, field))
  423. .appendTo($result);
  424. });
  425. return $result;
  426. },
  427. _callEventHandler: function(handler, eventParams) {
  428. handler.call(this, $.extend(eventParams, {
  429. grid: this
  430. }));
  431. return eventParams;
  432. },
  433. reset: function() {
  434. this._resetSorting();
  435. this._resetPager();
  436. return this._loadStrategy.reset();
  437. },
  438. _resetPager: function() {
  439. this._firstDisplayingPage = 1;
  440. this._setPage(1);
  441. },
  442. _resetSorting: function() {
  443. this._sortField = null;
  444. this._sortOrder = SORT_ORDER_ASC;
  445. this._clearSortingCss();
  446. },
  447. refresh: function() {
  448. this._callEventHandler(this.onRefreshing);
  449. this.cancelEdit();
  450. this._refreshHeading();
  451. this._refreshFiltering();
  452. this._refreshInserting();
  453. this._refreshContent();
  454. this._refreshPager();
  455. this._refreshSize();
  456. this._callEventHandler(this.onRefreshed);
  457. },
  458. _refreshHeading: function() {
  459. this._headerRow.toggle(this.heading);
  460. },
  461. _refreshFiltering: function() {
  462. this._filterRow.toggle(this.filtering);
  463. },
  464. _refreshInserting: function() {
  465. this._insertRow.toggle(this.inserting);
  466. },
  467. _refreshContent: function() {
  468. var $content = this._content;
  469. $content.empty();
  470. if(!this.data.length) {
  471. $content.append(this._createNoDataRow());
  472. return this;
  473. }
  474. var indexFrom = this._loadStrategy.firstDisplayIndex();
  475. var indexTo = this._loadStrategy.lastDisplayIndex();
  476. for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) {
  477. var item = this.data[itemIndex];
  478. $content.append(this._createRow(item, itemIndex));
  479. }
  480. },
  481. _createNoDataRow: function() {
  482. var amountOfFields = 0;
  483. this._eachField(function() {
  484. amountOfFields++;
  485. });
  486. return $("<tr>").addClass(this.noDataRowClass)
  487. .append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields)
  488. .append(this.renderTemplate(this.noDataContent, this)));
  489. },
  490. _createRow: function(item, itemIndex) {
  491. var $result;
  492. if($.isFunction(this.rowRenderer)) {
  493. $result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: itemIndex });
  494. } else {
  495. $result = $("<tr>");
  496. this._renderCells($result, item);
  497. }
  498. $result.addClass(this._getRowClasses(item, itemIndex))
  499. .data(JSGRID_ROW_DATA_KEY, item)
  500. .on("click", $.proxy(function(e) {
  501. this.rowClick({
  502. item: item,
  503. itemIndex: itemIndex,
  504. event: e
  505. });
  506. }, this))
  507. .on("dblclick", $.proxy(function(e) {
  508. this.rowDoubleClick({
  509. item: item,
  510. itemIndex: itemIndex,
  511. event: e
  512. });
  513. }, this));
  514. if(this.selecting) {
  515. this._attachRowHover($result);
  516. }
  517. return $result;
  518. },
  519. _getRowClasses: function(item, itemIndex) {
  520. var classes = [];
  521. classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass);
  522. classes.push(getOrApply(this.rowClass, this, item, itemIndex));
  523. return classes.join(" ");
  524. },
  525. _attachRowHover: function($row) {
  526. var selectedRowClass = this.selectedRowClass;
  527. $row.hover(function() {
  528. $(this).addClass(selectedRowClass);
  529. },
  530. function() {
  531. $(this).removeClass(selectedRowClass);
  532. }
  533. );
  534. },
  535. _renderCells: function($row, item) {
  536. this._eachField(function(field) {
  537. $row.append(this._createCell(item, field));
  538. });
  539. return this;
  540. },
  541. _createCell: function(item, field) {
  542. var $result;
  543. var fieldValue = this._getItemFieldValue(item, field);
  544. var args = { value: fieldValue, item : item };
  545. if($.isFunction(field.cellRenderer)) {
  546. $result = this.renderTemplate(field.cellRenderer, field, args);
  547. } else {
  548. $result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args));
  549. }
  550. return this._prepareCell($result, field);
  551. },
  552. _getItemFieldValue: function(item, field) {
  553. var props = field.name.split('.');
  554. var result = item[props.shift()];
  555. while(result && props.length) {
  556. result = result[props.shift()];
  557. }
  558. return result;
  559. },
  560. _setItemFieldValue: function(item, field, value) {
  561. var props = field.name.split('.');
  562. var current = item;
  563. var prop = props[0];
  564. while(current && props.length) {
  565. item = current;
  566. prop = props.shift();
  567. current = item[prop];
  568. }
  569. if(!current) {
  570. while(props.length) {
  571. item = item[prop] = {};
  572. prop = props.shift();
  573. }
  574. }
  575. item[prop] = value;
  576. },
  577. sort: function(field, order) {
  578. if($.isPlainObject(field)) {
  579. order = field.order;
  580. field = field.field;
  581. }
  582. this._clearSortingCss();
  583. this._setSortingParams(field, order);
  584. this._setSortingCss();
  585. return this._loadStrategy.sort();
  586. },
  587. _clearSortingCss: function() {
  588. this._headerRow.find("th")
  589. .removeClass(this.sortAscClass)
  590. .removeClass(this.sortDescClass);
  591. },
  592. _setSortingParams: function(field, order) {
  593. field = this._normalizeField(field);
  594. order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC);
  595. this._sortField = field;
  596. this._sortOrder = order;
  597. },
  598. _normalizeField: function(field) {
  599. if($.isNumeric(field)) {
  600. return this.fields[field];
  601. }
  602. if(typeof field === "string") {
  603. return $.grep(this.fields, function(f) {
  604. return f.name === field;
  605. })[0];
  606. }
  607. return field;
  608. },
  609. _reversedSortOrder: function(order) {
  610. return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC);
  611. },
  612. _setSortingCss: function() {
  613. var fieldIndex = this._visibleFieldIndex(this._sortField);
  614. this._headerRow.find("th").eq(fieldIndex)
  615. .addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass);
  616. },
  617. _visibleFieldIndex: function(field) {
  618. return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; }));
  619. },
  620. _sortData: function() {
  621. var sortFactor = this._sortFactor(),
  622. sortField = this._sortField;
  623. if(sortField) {
  624. this.data.sort(function(item1, item2) {
  625. return sortFactor * sortField.sortingFunc(item1[sortField.name], item2[sortField.name]);
  626. });
  627. }
  628. },
  629. _sortFactor: function() {
  630. return this._sortOrder === SORT_ORDER_ASC ? 1 : -1;
  631. },
  632. _itemsCount: function() {
  633. return this._loadStrategy.itemsCount();
  634. },
  635. _pagesCount: function() {
  636. var itemsCount = this._itemsCount(),
  637. pageSize = this.pageSize;
  638. return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0);
  639. },
  640. _refreshPager: function() {
  641. var $pagerContainer = this._pagerContainer;
  642. $pagerContainer.empty();
  643. if(this.paging) {
  644. $pagerContainer.append(this._createPager());
  645. }
  646. var showPager = this.paging && this._pagesCount() > 1;
  647. $pagerContainer.toggle(showPager);
  648. },
  649. _createPager: function() {
  650. var $result;
  651. if($.isFunction(this.pagerRenderer)) {
  652. $result = $(this.pagerRenderer({
  653. pageIndex: this.pageIndex,
  654. pageCount: this._pagesCount()
  655. }));
  656. } else {
  657. $result = $("<div>").append(this._createPagerByFormat());
  658. }
  659. $result.addClass(this.pagerClass);
  660. return $result;
  661. },
  662. _createPagerByFormat: function() {
  663. var pageIndex = this.pageIndex,
  664. pageCount = this._pagesCount(),
  665. itemCount = this._itemsCount(),
  666. pagerParts = this.pagerFormat.split(" ");
  667. return $.map(pagerParts, $.proxy(function(pagerPart) {
  668. var result = pagerPart;
  669. if(pagerPart === PAGES_PLACEHOLDER) {
  670. result = this._createPages();
  671. } else if(pagerPart === FIRST_PAGE_PLACEHOLDER) {
  672. result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1);
  673. } else if(pagerPart === PREV_PAGE_PLACEHOLDER) {
  674. result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1);
  675. } else if(pagerPart === NEXT_PAGE_PLACEHOLDER) {
  676. result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount);
  677. } else if(pagerPart === LAST_PAGE_PLACEHOLDER) {
  678. result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount);
  679. } else if(pagerPart === PAGE_INDEX_PLACEHOLDER) {
  680. result = pageIndex;
  681. } else if(pagerPart === PAGE_COUNT_PLACEHOLDER) {
  682. result = pageCount;
  683. } else if(pagerPart === ITEM_COUNT_PLACEHOLDER) {
  684. result = itemCount;
  685. }
  686. return $.isArray(result) ? result.concat([" "]) : [result, " "];
  687. }, this));
  688. },
  689. _createPages: function() {
  690. var pageCount = this._pagesCount(),
  691. pageButtonCount = this.pageButtonCount,
  692. firstDisplayingPage = this._firstDisplayingPage,
  693. pages = [];
  694. if(firstDisplayingPage > 1) {
  695. pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages));
  696. }
  697. for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) {
  698. pages.push(pageNumber === this.pageIndex
  699. ? this._createPagerCurrentPage()
  700. : this._createPagerPage(pageNumber));
  701. }
  702. if((firstDisplayingPage + pageButtonCount - 1) < pageCount) {
  703. pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages));
  704. }
  705. return pages;
  706. },
  707. _createPagerNavButton: function(text, pageIndex, isActive) {
  708. return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass),
  709. isActive ? function() { this.openPage(pageIndex); } : $.noop);
  710. },
  711. _createPagerPageNavButton: function(text, handler) {
  712. return this._createPagerButton(text, this.pagerNavButtonClass, handler);
  713. },
  714. _createPagerPage: function(pageIndex) {
  715. return this._createPagerButton(pageIndex, this.pageClass, function() {
  716. this.openPage(pageIndex);
  717. });
  718. },
  719. _createPagerButton: function(text, css, handler) {
  720. var $link = $("<a>").attr("href", EMPTY_HREF)
  721. .html(text)
  722. .on("click", $.proxy(handler, this));
  723. return $("<span>").addClass(css).append($link);
  724. },
  725. _createPagerCurrentPage: function() {
  726. return $("<span>")
  727. .addClass(this.pageClass)
  728. .addClass(this.currentPageClass)
  729. .text(this.pageIndex);
  730. },
  731. _refreshSize: function() {
  732. this._refreshHeight();
  733. this._refreshWidth();
  734. },
  735. _refreshWidth: function() {
  736. var width = (this.width === "auto") ? this._getAutoWidth() : this.width;
  737. this._container.width(width);
  738. },
  739. _getAutoWidth: function() {
  740. var $headerGrid = this._headerGrid,
  741. $header = this._header;
  742. $headerGrid.width("auto");
  743. var contentWidth = $headerGrid.outerWidth();
  744. var borderWidth = $header.outerWidth() - $header.innerWidth();
  745. $headerGrid.width("");
  746. return contentWidth + borderWidth;
  747. },
  748. _scrollBarWidth: (function() {
  749. var result;
  750. return function() {
  751. if(result === undefined) {
  752. var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>");
  753. var $ghostContent = $("<div style='height:100px;'></div>");
  754. $ghostContainer.append($ghostContent).appendTo("body");
  755. var width = $ghostContent.innerWidth();
  756. $ghostContainer.css("overflow-y", "auto");
  757. var widthExcludingScrollBar = $ghostContent.innerWidth();
  758. $ghostContainer.remove();
  759. result = width - widthExcludingScrollBar;
  760. }
  761. return result;
  762. };
  763. })(),
  764. _refreshHeight: function() {
  765. var container = this._container,
  766. pagerContainer = this._pagerContainer,
  767. height = this.height,
  768. nonBodyHeight;
  769. container.height(height);
  770. if(height !== "auto") {
  771. height = container.height();
  772. nonBodyHeight = this._header.outerHeight(true);
  773. if(pagerContainer.parents(container).length) {
  774. nonBodyHeight += pagerContainer.outerHeight(true);
  775. }
  776. this._body.outerHeight(height - nonBodyHeight);
  777. }
  778. },
  779. showPrevPages: function() {
  780. var firstDisplayingPage = this._firstDisplayingPage,
  781. pageButtonCount = this.pageButtonCount;
  782. this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1;
  783. this._refreshPager();
  784. },
  785. showNextPages: function() {
  786. var firstDisplayingPage = this._firstDisplayingPage,
  787. pageButtonCount = this.pageButtonCount,
  788. pageCount = this._pagesCount();
  789. this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount)
  790. ? pageCount - pageButtonCount + 1
  791. : firstDisplayingPage + pageButtonCount;
  792. this._refreshPager();
  793. },
  794. openPage: function(pageIndex) {
  795. if(pageIndex < 1 || pageIndex > this._pagesCount())
  796. return;
  797. this._setPage(pageIndex);
  798. this._loadStrategy.openPage(pageIndex);
  799. },
  800. _setPage: function(pageIndex) {
  801. var firstDisplayingPage = this._firstDisplayingPage,
  802. pageButtonCount = this.pageButtonCount;
  803. this.pageIndex = pageIndex;
  804. if(pageIndex < firstDisplayingPage) {
  805. this._firstDisplayingPage = pageIndex;
  806. }
  807. if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
  808. this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
  809. }
  810. this._callEventHandler(this.onPageChanged, {
  811. pageIndex: pageIndex
  812. });
  813. },
  814. _controllerCall: function(method, param, isCanceled, doneCallback) {
  815. if(isCanceled)
  816. return $.Deferred().reject().promise();
  817. this._showLoading();
  818. var controller = this._controller;
  819. if(!controller || !controller[method]) {
  820. throw Error("controller has no method '" + method + "'");
  821. }
  822. return normalizePromise(controller[method](param))
  823. .done($.proxy(doneCallback, this))
  824. .fail($.proxy(this._errorHandler, this))
  825. .always($.proxy(this._hideLoading, this));
  826. },
  827. _errorHandler: function() {
  828. this._callEventHandler(this.onError, {
  829. args: $.makeArray(arguments)
  830. });
  831. },
  832. _showLoading: function() {
  833. if(!this.loadIndication)
  834. return;
  835. clearTimeout(this._loadingTimer);
  836. this._loadingTimer = setTimeout($.proxy(function() {
  837. this._loadIndicator.show();
  838. }, this), this.loadIndicationDelay);
  839. },
  840. _hideLoading: function() {
  841. if(!this.loadIndication)
  842. return;
  843. clearTimeout(this._loadingTimer);
  844. this._loadIndicator.hide();
  845. },
  846. search: function(filter) {
  847. this._resetSorting();
  848. this._resetPager();
  849. return this.loadData(filter);
  850. },
  851. loadData: function(filter) {
  852. filter = filter || (this.filtering ? this.getFilter() : {});
  853. $.extend(filter, this._loadStrategy.loadParams(), this._sortingParams());
  854. var args = this._callEventHandler(this.onDataLoading, {
  855. filter: filter
  856. });
  857. return this._controllerCall("loadData", filter, args.cancel, function(loadedData) {
  858. if(!loadedData)
  859. return;
  860. this._loadStrategy.finishLoad(loadedData);
  861. this._callEventHandler(this.onDataLoaded, {
  862. data: loadedData
  863. });
  864. });
  865. },
  866. getFilter: function() {
  867. var result = {};
  868. this._eachField(function(field) {
  869. if(field.filtering) {
  870. this._setItemFieldValue(result, field, field.filterValue());
  871. }
  872. });
  873. return result;
  874. },
  875. _sortingParams: function() {
  876. if(this.sorting && this._sortField) {
  877. return {
  878. sortField: this._sortField.name,
  879. sortOrder: this._sortOrder
  880. };
  881. }
  882. return {};
  883. },
  884. getSorting: function() {
  885. var sortingParams = this._sortingParams();
  886. return {
  887. field: sortingParams.sortField,
  888. order: sortingParams.sortOrder
  889. };
  890. },
  891. clearFilter: function() {
  892. var $filterRow = this._createFilterRow();
  893. this._filterRow.replaceWith($filterRow);
  894. this._filterRow = $filterRow;
  895. return this.search();
  896. },
  897. insertItem: function(item) {
  898. var insertingItem = item || this._getValidatedInsertItem();
  899. if(!insertingItem)
  900. return $.Deferred().reject().promise();
  901. var args = this._callEventHandler(this.onItemInserting, {
  902. item: insertingItem
  903. });
  904. return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) {
  905. insertedItem = insertedItem || insertingItem;
  906. this._loadStrategy.finishInsert(insertedItem);
  907. this._callEventHandler(this.onItemInserted, {
  908. item: insertedItem
  909. });
  910. });
  911. },
  912. _getValidatedInsertItem: function() {
  913. var item = this._getInsertItem();
  914. return this._validateItem(item, this._insertRow) ? item : null;
  915. },
  916. _getInsertItem: function() {
  917. var result = {};
  918. this._eachField(function(field) {
  919. if(field.inserting) {
  920. this._setItemFieldValue(result, field, field.insertValue());
  921. }
  922. });
  923. return result;
  924. },
  925. _validateItem: function(item, $row) {
  926. var validationErrors = [];
  927. var args = {
  928. item: item,
  929. itemIndex: this._rowIndex($row),
  930. row: $row
  931. };
  932. this._eachField(function(field) {
  933. if(!field.validate ||
  934. ($row === this._insertRow && !field.inserting) ||
  935. ($row === this._getEditRow() && !field.editing))
  936. return;
  937. var fieldValue = this._getItemFieldValue(item, field);
  938. var errors = this._validation.validate($.extend({
  939. value: fieldValue,
  940. rules: field.validate
  941. }, args));
  942. this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors);
  943. if(!errors.length)
  944. return;
  945. validationErrors.push.apply(validationErrors,
  946. $.map(errors, function(message) {
  947. return { field: field, message: message };
  948. }));
  949. });
  950. if(!validationErrors.length)
  951. return true;
  952. var invalidArgs = $.extend({
  953. errors: validationErrors
  954. }, args);
  955. this._callEventHandler(this.onItemInvalid, invalidArgs);
  956. this.invalidNotify(invalidArgs);
  957. return false;
  958. },
  959. _setCellValidity: function($cell, errors) {
  960. $cell
  961. .toggleClass(this.invalidClass, !!errors.length)
  962. .attr("title", errors.join("\n"));
  963. },
  964. clearInsert: function() {
  965. var insertRow = this._createInsertRow();
  966. this._insertRow.replaceWith(insertRow);
  967. this._insertRow = insertRow;
  968. this.refresh();
  969. },
  970. editItem: function(item) {
  971. var $row = this.rowByItem(item);
  972. if($row.length) {
  973. this._editRow($row);
  974. }
  975. },
  976. rowByItem: function(item) {
  977. if(item.jquery || item.nodeType)
  978. return $(item);
  979. return this._content.find("tr").filter(function() {
  980. return $.data(this, JSGRID_ROW_DATA_KEY) === item;
  981. });
  982. },
  983. _editRow: function($row) {
  984. if(!this.editing)
  985. return;
  986. var item = $row.data(JSGRID_ROW_DATA_KEY);
  987. var args = this._callEventHandler(this.onItemEditing, {
  988. row: $row,
  989. item: item,
  990. itemIndex: this._itemIndex(item)
  991. });
  992. if(args.cancel)
  993. return;
  994. if(this._editingRow) {
  995. this.cancelEdit();
  996. }
  997. var $editRow = this._createEditRow(item);
  998. this._editingRow = $row;
  999. $row.hide();
  1000. $editRow.insertBefore($row);
  1001. $row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow);
  1002. },
  1003. _createEditRow: function(item) {
  1004. if($.isFunction(this.editRowRenderer)) {
  1005. return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) }));
  1006. }
  1007. var $result = $("<tr>").addClass(this.editRowClass);
  1008. this._eachField(function(field) {
  1009. var fieldValue = this._getItemFieldValue(item, field);
  1010. this._prepareCell("<td>", field, "editcss")
  1011. .append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item }))
  1012. .appendTo($result);
  1013. });
  1014. return $result;
  1015. },
  1016. updateItem: function(item, editedItem) {
  1017. if(arguments.length === 1) {
  1018. editedItem = item;
  1019. }
  1020. var $row = item ? this.rowByItem(item) : this._editingRow;
  1021. editedItem = editedItem || this._getValidatedEditedItem();
  1022. if(!editedItem)
  1023. return;
  1024. return this._updateRow($row, editedItem);
  1025. },
  1026. _getValidatedEditedItem: function() {
  1027. var item = this._getEditedItem();
  1028. return this._validateItem(item, this._getEditRow()) ? item : null;
  1029. },
  1030. _updateRow: function($updatingRow, editedItem) {
  1031. var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY),
  1032. updatingItemIndex = this._itemIndex(updatingItem),
  1033. updatedItem = $.extend(true, {}, updatingItem, editedItem);
  1034. var args = this._callEventHandler(this.onItemUpdating, {
  1035. row: $updatingRow,
  1036. item: updatedItem,
  1037. itemIndex: updatingItemIndex,
  1038. previousItem: updatingItem
  1039. });
  1040. return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) {
  1041. var previousItem = $.extend(true, {}, updatingItem);
  1042. updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem);
  1043. var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex);
  1044. this._callEventHandler(this.onItemUpdated, {
  1045. row: $updatedRow,
  1046. item: updatedItem,
  1047. itemIndex: updatingItemIndex,
  1048. previousItem: previousItem
  1049. });
  1050. });
  1051. },
  1052. _rowIndex: function(row) {
  1053. return this._content.children().index($(row));
  1054. },
  1055. _itemIndex: function(item) {
  1056. return $.inArray(item, this.data);
  1057. },
  1058. _finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) {
  1059. this.cancelEdit();
  1060. this.data[updatedItemIndex] = updatedItem;
  1061. var $updatedRow = this._createRow(updatedItem, updatedItemIndex);
  1062. $updatingRow.replaceWith($updatedRow);
  1063. return $updatedRow;
  1064. },
  1065. _getEditedItem: function() {
  1066. var result = {};
  1067. this._eachField(function(field) {
  1068. if(field.editing) {
  1069. this._setItemFieldValue(result, field, field.editValue());
  1070. }
  1071. });
  1072. return result;
  1073. },
  1074. cancelEdit: function() {
  1075. if(!this._editingRow)
  1076. return;
  1077. this._getEditRow().remove();
  1078. this._editingRow.show();
  1079. this._editingRow = null;
  1080. },
  1081. _getEditRow: function() {
  1082. return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY);
  1083. },
  1084. deleteItem: function(item) {
  1085. var $row = this.rowByItem(item);
  1086. if(!$row.length)
  1087. return;
  1088. if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY))))
  1089. return;
  1090. return this._deleteRow($row);
  1091. },
  1092. _deleteRow: function($row) {
  1093. var deletingItem = $row.data(JSGRID_ROW_DATA_KEY),
  1094. deletingItemIndex = this._itemIndex(deletingItem);
  1095. var args = this._callEventHandler(this.onItemDeleting, {
  1096. row: $row,
  1097. item: deletingItem,
  1098. itemIndex: deletingItemIndex
  1099. });
  1100. return this._controllerCall("deleteItem", deletingItem, args.cancel, function() {
  1101. this._loadStrategy.finishDelete(deletingItem, deletingItemIndex);
  1102. this._callEventHandler(this.onItemDeleted, {
  1103. row: $row,
  1104. item: deletingItem,
  1105. itemIndex: deletingItemIndex
  1106. });
  1107. });
  1108. }
  1109. };
  1110. $.fn.jsGrid = function(config) {
  1111. var args = $.makeArray(arguments),
  1112. methodArgs = args.slice(1),
  1113. result = this;
  1114. this.each(function() {
  1115. var $element = $(this),
  1116. instance = $element.data(JSGRID_DATA_KEY),
  1117. methodResult;
  1118. if(instance) {
  1119. if(typeof config === "string") {
  1120. methodResult = instance[config].apply(instance, methodArgs);
  1121. if(methodResult !== undefined && methodResult !== instance) {
  1122. result = methodResult;
  1123. return false;
  1124. }
  1125. } else {
  1126. instance._detachWindowResizeCallback();
  1127. instance._init(config);
  1128. instance.render();
  1129. }
  1130. } else {
  1131. new Grid($element, config);
  1132. }
  1133. });
  1134. return result;
  1135. };
  1136. var fields = {};
  1137. var setDefaults = function(config) {
  1138. var componentPrototype;
  1139. if($.isPlainObject(config)) {
  1140. componentPrototype = Grid.prototype;
  1141. } else {
  1142. componentPrototype = fields[config].prototype;
  1143. config = arguments[1] || {};
  1144. }
  1145. $.extend(componentPrototype, config);
  1146. };
  1147. var locales = {};
  1148. var locale = function(lang) {
  1149. var localeConfig = $.isPlainObject(lang) ? lang : locales[lang];
  1150. if(!localeConfig)
  1151. throw Error("unknown locale " + lang);
  1152. setLocale(jsGrid, localeConfig);
  1153. };
  1154. var setLocale = function(obj, localeConfig) {
  1155. $.each(localeConfig, function(field, value) {
  1156. if($.isPlainObject(value)) {
  1157. setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value);
  1158. return;
  1159. }
  1160. if(obj.hasOwnProperty(field)) {
  1161. obj[field] = value;
  1162. } else {
  1163. obj.prototype[field] = value;
  1164. }
  1165. });
  1166. };
  1167. window.jsGrid = {
  1168. Grid: Grid,
  1169. fields: fields,
  1170. setDefaults: setDefaults,
  1171. locales: locales,
  1172. locale: locale,
  1173. version: '1.5.3'
  1174. };
  1175. }(window, jQuery));
  1176. (function(jsGrid, $, undefined) {
  1177. function LoadIndicator(config) {
  1178. this._init(config);
  1179. }
  1180. LoadIndicator.prototype = {
  1181. container: "body",
  1182. message: "Loading...",
  1183. shading: true,
  1184. zIndex: 1000,
  1185. shaderClass: "jsgrid-load-shader",
  1186. loadPanelClass: "jsgrid-load-panel",
  1187. _init: function(config) {
  1188. $.extend(true, this, config);
  1189. this._initContainer();
  1190. this._initShader();
  1191. this._initLoadPanel();
  1192. },
  1193. _initContainer: function() {
  1194. this._container = $(this.container);
  1195. },
  1196. _initShader: function() {
  1197. if(!this.shading)
  1198. return;
  1199. this._shader = $("<div>").addClass(this.shaderClass)
  1200. .hide()
  1201. .css({
  1202. position: "absolute",
  1203. top: 0,
  1204. right: 0,
  1205. bottom: 0,
  1206. left: 0,
  1207. zIndex: this.zIndex
  1208. })
  1209. .appendTo(this._container);
  1210. },
  1211. _initLoadPanel: function() {
  1212. this._loadPanel = $("<div>").addClass(this.loadPanelClass)
  1213. .text(this.message)
  1214. .hide()
  1215. .css({
  1216. position: "absolute",
  1217. top: "50%",
  1218. left: "50%",
  1219. zIndex: this.zIndex
  1220. })
  1221. .appendTo(this._container);
  1222. },
  1223. show: function() {
  1224. var $loadPanel = this._loadPanel.show();
  1225. var actualWidth = $loadPanel.outerWidth();
  1226. var actualHeight = $loadPanel.outerHeight();
  1227. $loadPanel.css({
  1228. marginTop: -actualHeight / 2,
  1229. marginLeft: -actualWidth / 2
  1230. });
  1231. this._shader.show();
  1232. },
  1233. hide: function() {
  1234. this._loadPanel.hide();
  1235. this._shader.hide();
  1236. }
  1237. };
  1238. jsGrid.LoadIndicator = LoadIndicator;
  1239. }(jsGrid, jQuery));
  1240. (function(jsGrid, $, undefined) {
  1241. function DirectLoadingStrategy(grid) {
  1242. this._grid = grid;
  1243. }
  1244. DirectLoadingStrategy.prototype = {
  1245. firstDisplayIndex: function() {
  1246. var grid = this._grid;
  1247. return grid.option("paging") ? (grid.option("pageIndex") - 1) * grid.option("pageSize") : 0;
  1248. },
  1249. lastDisplayIndex: function() {
  1250. var grid = this._grid;
  1251. var itemsCount = grid.option("data").length;
  1252. return grid.option("paging")
  1253. ? Math.min(grid.option("pageIndex") * grid.option("pageSize"), itemsCount)
  1254. : itemsCount;
  1255. },
  1256. itemsCount: function() {
  1257. return this._grid.option("data").length;
  1258. },
  1259. openPage: function(index) {
  1260. this._grid.refresh();
  1261. },
  1262. loadParams: function() {
  1263. return {};
  1264. },
  1265. sort: function() {
  1266. this._grid._sortData();
  1267. this._grid.refresh();
  1268. return $.Deferred().resolve().promise();
  1269. },
  1270. reset: function() {
  1271. this._grid.refresh();
  1272. return $.Deferred().resolve().promise();
  1273. },
  1274. finishLoad: function(loadedData) {
  1275. this._grid.option("data", loadedData);
  1276. },
  1277. finishInsert: function(insertedItem) {
  1278. var grid = this._grid;
  1279. grid.option("data").push(insertedItem);
  1280. grid.refresh();
  1281. },
  1282. finishDelete: function(deletedItem, deletedItemIndex) {
  1283. var grid = this._grid;
  1284. grid.option("data").splice(deletedItemIndex, 1);
  1285. grid.reset();
  1286. }
  1287. };
  1288. function PageLoadingStrategy(grid) {
  1289. this._grid = grid;
  1290. this._itemsCount = 0;
  1291. }
  1292. PageLoadingStrategy.prototype = {
  1293. firstDisplayIndex: function() {
  1294. return 0;
  1295. },
  1296. lastDisplayIndex: function() {
  1297. return this._grid.option("data").length;
  1298. },
  1299. itemsCount: function() {
  1300. return this._itemsCount;
  1301. },
  1302. openPage: function(index) {
  1303. this._grid.loadData();
  1304. },
  1305. loadParams: function() {
  1306. var grid = this._grid;
  1307. return {
  1308. pageIndex: grid.option("pageIndex"),
  1309. pageSize: grid.option("pageSize")
  1310. };
  1311. },
  1312. reset: function() {
  1313. return this._grid.loadData();
  1314. },
  1315. sort: function() {
  1316. return this._grid.loadData();
  1317. },
  1318. finishLoad: function(loadedData) {
  1319. this._itemsCount = loadedData.itemsCount;
  1320. this._grid.option("data", loadedData.data);
  1321. },
  1322. finishInsert: function(insertedItem) {
  1323. this._grid.search();
  1324. },
  1325. finishDelete: function(deletedItem, deletedItemIndex) {
  1326. this._grid.search();
  1327. }
  1328. };
  1329. jsGrid.loadStrategies = {
  1330. DirectLoadingStrategy: DirectLoadingStrategy,
  1331. PageLoadingStrategy: PageLoadingStrategy
  1332. };
  1333. }(jsGrid, jQuery));
  1334. (function(jsGrid, $, undefined) {
  1335. var isDefined = function(val) {
  1336. return typeof(val) !== "undefined" && val !== null;
  1337. };
  1338. var sortStrategies = {
  1339. string: function(str1, str2) {
  1340. if(!isDefined(str1) && !isDefined(str2))
  1341. return 0;
  1342. if(!isDefined(str1))
  1343. return -1;
  1344. if(!isDefined(str2))
  1345. return 1;
  1346. return ("" + str1).localeCompare("" + str2);
  1347. },
  1348. number: function(n1, n2) {
  1349. return n1 - n2;
  1350. },
  1351. date: function(dt1, dt2) {
  1352. return dt1 - dt2;
  1353. },
  1354. numberAsString: function(n1, n2) {
  1355. return parseFloat(n1) - parseFloat(n2);
  1356. }
  1357. };
  1358. jsGrid.sortStrategies = sortStrategies;
  1359. }(jsGrid, jQuery));
  1360. (function(jsGrid, $, undefined) {
  1361. function Validation(config) {
  1362. this._init(config);
  1363. }
  1364. Validation.prototype = {
  1365. _init: function(config) {
  1366. $.extend(true, this, config);
  1367. },
  1368. validate: function(args) {
  1369. var errors = [];
  1370. $.each(this._normalizeRules(args.rules), function(_, rule) {
  1371. if(rule.validator(args.value, args.item, rule.param))
  1372. return;
  1373. var errorMessage = $.isFunction(rule.message) ? rule.message(args.value, args.item) : rule.message;
  1374. errors.push(errorMessage);
  1375. });
  1376. return errors;
  1377. },
  1378. _normalizeRules: function(rules) {
  1379. if(!$.isArray(rules))
  1380. rules = [rules];
  1381. return $.map(rules, $.proxy(function(rule) {
  1382. return this._normalizeRule(rule);
  1383. }, this));
  1384. },
  1385. _normalizeRule: function(rule) {
  1386. if(typeof rule === "string")
  1387. rule = { validator: rule };
  1388. if($.isFunction(rule))
  1389. rule = { validator: rule };
  1390. if($.isPlainObject(rule))
  1391. rule = $.extend({}, rule);
  1392. else
  1393. throw Error("wrong validation config specified");
  1394. if($.isFunction(rule.validator))
  1395. return rule;
  1396. return this._applyNamedValidator(rule, rule.validator);
  1397. },
  1398. _applyNamedValidator: function(rule, validatorName) {
  1399. delete rule.validator;
  1400. var validator = validators[validatorName];
  1401. if(!validator)
  1402. throw Error("unknown validator \"" + validatorName + "\"");
  1403. if($.isFunction(validator)) {
  1404. validator = { validator: validator };
  1405. }
  1406. return $.extend({}, validator, rule);
  1407. }
  1408. };
  1409. jsGrid.Validation = Validation;
  1410. var validators = {
  1411. required: {
  1412. message: "Field is required",
  1413. validator: function(value) {
  1414. return value !== undefined && value !== null && value !== "";
  1415. }
  1416. },
  1417. rangeLength: {
  1418. message: "Field value length is out of the defined range",
  1419. validator: function(value, _, param) {
  1420. return value.length >= param[0] && value.length <= param[1];
  1421. }
  1422. },
  1423. minLength: {
  1424. message: "Field value is too short",
  1425. validator: function(value, _, param) {
  1426. return value.length >= param;
  1427. }
  1428. },
  1429. maxLength: {
  1430. message: "Field value is too long",
  1431. validator: function(value, _, param) {
  1432. return value.length <= param;
  1433. }
  1434. },
  1435. pattern: {
  1436. message: "Field value is not matching the defined pattern",
  1437. validator: function(value, _, param) {
  1438. if(typeof param === "string") {
  1439. param = new RegExp("^(?:" + param + ")$");
  1440. }
  1441. return param.test(value);
  1442. }
  1443. },
  1444. range: {
  1445. message: "Field value is out of the defined range",
  1446. validator: function(value, _, param) {
  1447. return value >= param[0] && value <= param[1];
  1448. }
  1449. },
  1450. min: {
  1451. message: "Field value is too small",
  1452. validator: function(value, _, param) {
  1453. return value >= param;
  1454. }
  1455. },
  1456. max: {
  1457. message: "Field value is too large",
  1458. validator: function(value, _, param) {
  1459. return value <= param;
  1460. }
  1461. }
  1462. };
  1463. jsGrid.validators = validators;
  1464. }(jsGrid, jQuery));
  1465. (function(jsGrid, $, undefined) {
  1466. function Field(config) {
  1467. $.extend(true, this, config);
  1468. this.sortingFunc = this._getSortingFunc();
  1469. }
  1470. Field.prototype = {
  1471. name: "",
  1472. title: null,
  1473. css: "",
  1474. align: "",
  1475. width: 100,
  1476. visible: true,
  1477. filtering: true,
  1478. inserting: true,
  1479. editing: true,
  1480. sorting: true,
  1481. sorter: "string", // name of SortStrategy or function to compare elements
  1482. headerTemplate: function() {
  1483. return (this.title === undefined || this.title === null) ? this.name : this.title;
  1484. },
  1485. itemTemplate: function(value, item) {
  1486. return value;
  1487. },
  1488. filterTemplate: function() {
  1489. return "";
  1490. },
  1491. insertTemplate: function() {
  1492. return "";
  1493. },
  1494. editTemplate: function(value, item) {
  1495. this._value = value;
  1496. return this.itemTemplate(value, item);
  1497. },
  1498. filterValue: function() {
  1499. return "";
  1500. },
  1501. insertValue: function() {
  1502. return "";
  1503. },
  1504. editValue: function() {
  1505. return this._value;
  1506. },
  1507. _getSortingFunc: function() {
  1508. var sorter = this.sorter;
  1509. if($.isFunction(sorter)) {
  1510. return sorter;
  1511. }
  1512. if(typeof sorter === "string") {
  1513. return jsGrid.sortStrategies[sorter];
  1514. }
  1515. throw Error("wrong sorter for the field \"" + this.name + "\"!");
  1516. }
  1517. };
  1518. jsGrid.Field = Field;
  1519. }(jsGrid, jQuery));
  1520. (function(jsGrid, $, undefined) {
  1521. var Field = jsGrid.Field;
  1522. function TextField(config) {
  1523. Field.call(this, config);
  1524. }
  1525. TextField.prototype = new Field({
  1526. autosearch: true,
  1527. readOnly: false,
  1528. filterTemplate: function() {
  1529. if(!this.filtering)
  1530. return "";
  1531. var grid = this._grid,
  1532. $result = this.filterControl = this._createTextBox();
  1533. if(this.autosearch) {
  1534. $result.on("keypress", function(e) {
  1535. if(e.which === 13) {
  1536. grid.search();
  1537. e.preventDefault();
  1538. }
  1539. });
  1540. }
  1541. return $result;
  1542. },
  1543. insertTemplate: function() {
  1544. if(!this.inserting)
  1545. return "";
  1546. return this.insertControl = this._createTextBox();
  1547. },
  1548. editTemplate: function(value) {
  1549. if(!this.editing)
  1550. return this.itemTemplate.apply(this, arguments);
  1551. var $result = this.editControl = this._createTextBox();
  1552. $result.val(value);
  1553. return $result;
  1554. },
  1555. filterValue: function() {
  1556. return this.filterControl.val();
  1557. },
  1558. insertValue: function() {
  1559. return this.insertControl.val();
  1560. },
  1561. editValue: function() {
  1562. return this.editControl.val();
  1563. },
  1564. _createTextBox: function() {
  1565. return $("<input>").attr("type", "text")
  1566. .prop("readonly", !!this.readOnly);
  1567. }
  1568. });
  1569. jsGrid.fields.text = jsGrid.TextField = TextField;
  1570. }(jsGrid, jQuery));
  1571. (function(jsGrid, $, undefined) {
  1572. var TextField = jsGrid.TextField;
  1573. function NumberField(config) {
  1574. TextField.call(this, config);
  1575. }
  1576. NumberField.prototype = new TextField({
  1577. sorter: "number",
  1578. align: "right",
  1579. readOnly: false,
  1580. filterValue: function() {
  1581. return this.filterControl.val()
  1582. ? parseInt(this.filterControl.val() || 0, 10)
  1583. : undefined;
  1584. },
  1585. insertValue: function() {
  1586. return this.insertControl.val()
  1587. ? parseInt(this.insertControl.val() || 0, 10)
  1588. : undefined;
  1589. },
  1590. editValue: function() {
  1591. return this.editControl.val()
  1592. ? parseInt(this.editControl.val() || 0, 10)
  1593. : undefined;
  1594. },
  1595. _createTextBox: function() {
  1596. return $("<input>").attr("type", "number")
  1597. .prop("readonly", !!this.readOnly);
  1598. }
  1599. });
  1600. jsGrid.fields.number = jsGrid.NumberField = NumberField;
  1601. }(jsGrid, jQuery));
  1602. (function(jsGrid, $, undefined) {
  1603. var TextField = jsGrid.TextField;
  1604. function TextAreaField(config) {
  1605. TextField.call(this, config);
  1606. }
  1607. TextAreaField.prototype = new TextField({
  1608. insertTemplate: function() {
  1609. if(!this.inserting)
  1610. return "";
  1611. return this.insertControl = this._createTextArea();
  1612. },
  1613. editTemplate: function(value) {
  1614. if(!this.editing)
  1615. return this.itemTemplate.apply(this, arguments);
  1616. var $result = this.editControl = this._createTextArea();
  1617. $result.val(value);
  1618. return $result;
  1619. },
  1620. _createTextArea: function() {
  1621. return $("<textarea>").prop("readonly", !!this.readOnly);
  1622. }
  1623. });
  1624. jsGrid.fields.textarea = jsGrid.TextAreaField = TextAreaField;
  1625. }(jsGrid, jQuery));
  1626. (function(jsGrid, $, undefined) {
  1627. var NumberField = jsGrid.NumberField;
  1628. var numberValueType = "number";
  1629. var stringValueType = "string";
  1630. function SelectField(config) {
  1631. this.items = [];
  1632. this.selectedIndex = -1;
  1633. this.valueField = "";
  1634. this.textField = "";
  1635. if(config.valueField && config.items.length) {
  1636. var firstItemValue = config.items[0][config.valueField];
  1637. this.valueType = (typeof firstItemValue) === numberValueType ? numberValueType : stringValueType;
  1638. }
  1639. this.sorter = this.valueType;
  1640. NumberField.call(this, config);
  1641. }
  1642. SelectField.prototype = new NumberField({
  1643. align: "center",
  1644. valueType: numberValueType,
  1645. itemTemplate: function(value) {
  1646. var items = this.items,
  1647. valueField = this.valueField,
  1648. textField = this.textField,
  1649. resultItem;
  1650. if(valueField) {
  1651. resultItem = $.grep(items, function(item, index) {
  1652. return item[valueField] === value;
  1653. })[0] || {};
  1654. }
  1655. else {
  1656. resultItem = items[value];
  1657. }
  1658. var result = (textField ? resultItem[textField] : resultItem);
  1659. return (result === undefined || result === null) ? "" : result;
  1660. },
  1661. filterTemplate: function() {
  1662. if(!this.filtering)
  1663. return "";
  1664. var grid = this._grid,
  1665. $result = this.filterControl = this._createSelect();
  1666. if(this.autosearch) {
  1667. $result.on("change", function(e) {
  1668. grid.search();
  1669. });
  1670. }
  1671. return $result;
  1672. },
  1673. insertTemplate: function() {
  1674. if(!this.inserting)
  1675. return "";
  1676. return this.insertControl = this._createSelect();
  1677. },
  1678. editTemplate: function(value) {
  1679. if(!this.editing)
  1680. return this.itemTemplate.apply(this, arguments);
  1681. var $result = this.editControl = this._createSelect();
  1682. (value !== undefined) && $result.val(value);
  1683. return $result;
  1684. },
  1685. filterValue: function() {
  1686. var val = this.filterControl.val();
  1687. return this.valueType === numberValueType ? parseInt(val || 0, 10) : val;
  1688. },
  1689. insertValue: function() {
  1690. var val = this.insertControl.val();
  1691. return this.valueType === numberValueType ? parseInt(val || 0, 10) : val;
  1692. },
  1693. editValue: function() {
  1694. var val = this.editControl.val();
  1695. return this.valueType === numberValueType ? parseInt(val || 0, 10) : val;
  1696. },
  1697. _createSelect: function() {
  1698. var $result = $("<select>"),
  1699. valueField = this.valueField,
  1700. textField = this.textField,
  1701. selectedIndex = this.selectedIndex;
  1702. $.each(this.items, function(index, item) {
  1703. var value = valueField ? item[valueField] : index,
  1704. text = textField ? item[textField] : item;
  1705. var $option = $("<option>")
  1706. .attr("value", value)
  1707. .text(text)
  1708. .appendTo($result);
  1709. $option.prop("selected", (selectedIndex === index));
  1710. });
  1711. $result.prop("disabled", !!this.readOnly);
  1712. return $result;
  1713. }
  1714. });
  1715. jsGrid.fields.select = jsGrid.SelectField = SelectField;
  1716. }(jsGrid, jQuery));
  1717. (function(jsGrid, $, undefined) {
  1718. var Field = jsGrid.Field;
  1719. function CheckboxField(config) {
  1720. Field.call(this, config);
  1721. }
  1722. CheckboxField.prototype = new Field({
  1723. sorter: "number",
  1724. align: "center",
  1725. autosearch: true,
  1726. itemTemplate: function(value) {
  1727. return this._createCheckbox().prop({
  1728. checked: value,
  1729. disabled: true
  1730. });
  1731. },
  1732. filterTemplate: function() {
  1733. if(!this.filtering)
  1734. return "";
  1735. var grid = this._grid,
  1736. $result = this.filterControl = this._createCheckbox();
  1737. $result.prop({
  1738. readOnly: true,
  1739. indeterminate: true
  1740. });
  1741. $result.on("click", function() {
  1742. var $cb = $(this);
  1743. if($cb.prop("readOnly")) {
  1744. $cb.prop({
  1745. checked: false,
  1746. readOnly: false
  1747. });
  1748. }
  1749. else if(!$cb.prop("checked")) {
  1750. $cb.prop({
  1751. readOnly: true,
  1752. indeterminate: true
  1753. });
  1754. }
  1755. });
  1756. if(this.autosearch) {
  1757. $result.on("click", function() {
  1758. grid.search();
  1759. });
  1760. }
  1761. return $result;
  1762. },
  1763. insertTemplate: function() {
  1764. if(!this.inserting)
  1765. return "";
  1766. return this.insertControl = this._createCheckbox();
  1767. },
  1768. editTemplate: function(value) {
  1769. if(!this.editing)
  1770. return this.itemTemplate.apply(this, arguments);
  1771. var $result = this.editControl = this._createCheckbox();
  1772. $result.prop("checked", value);
  1773. return $result;
  1774. },
  1775. filterValue: function() {
  1776. return this.filterControl.get(0).indeterminate
  1777. ? undefined
  1778. : this.filterControl.is(":checked");
  1779. },
  1780. insertValue: function() {
  1781. return this.insertControl.is(":checked");
  1782. },
  1783. editValue: function() {
  1784. return this.editControl.is(":checked");
  1785. },
  1786. _createCheckbox: function() {
  1787. return $("<input>").attr("type", "checkbox");
  1788. }
  1789. });
  1790. jsGrid.fields.checkbox = jsGrid.CheckboxField = CheckboxField;
  1791. }(jsGrid, jQuery));
  1792. (function(jsGrid, $, undefined) {
  1793. var Field = jsGrid.Field;
  1794. function ControlField(config) {
  1795. Field.call(this, config);
  1796. this._configInitialized = false;
  1797. }
  1798. ControlField.prototype = new Field({
  1799. css: "jsgrid-control-field",
  1800. align: "center",
  1801. width: 50,
  1802. filtering: false,
  1803. inserting: false,
  1804. editing: false,
  1805. sorting: false,
  1806. buttonClass: "jsgrid-button",
  1807. modeButtonClass: "jsgrid-mode-button",
  1808. modeOnButtonClass: "jsgrid-mode-on-button",
  1809. searchModeButtonClass: "jsgrid-search-mode-button",
  1810. insertModeButtonClass: "jsgrid-insert-mode-button",
  1811. editButtonClass: "jsgrid-edit-button",
  1812. deleteButtonClass: "jsgrid-delete-button",
  1813. searchButtonClass: "jsgrid-search-button",
  1814. clearFilterButtonClass: "jsgrid-clear-filter-button",
  1815. insertButtonClass: "jsgrid-insert-button",
  1816. updateButtonClass: "jsgrid-update-button",
  1817. cancelEditButtonClass: "jsgrid-cancel-edit-button",
  1818. searchModeButtonTooltip: "Switch to searching",
  1819. insertModeButtonTooltip: "Switch to inserting",
  1820. editButtonTooltip: "Edit",
  1821. deleteButtonTooltip: "Delete",
  1822. searchButtonTooltip: "Search",
  1823. clearFilterButtonTooltip: "Clear filter",
  1824. insertButtonTooltip: "Insert",
  1825. updateButtonTooltip: "Update",
  1826. cancelEditButtonTooltip: "Cancel edit",
  1827. editButton: true,
  1828. deleteButton: true,
  1829. clearFilterButton: true,
  1830. modeSwitchButton: true,
  1831. _initConfig: function() {
  1832. this._hasFiltering = this._grid.filtering;
  1833. this._hasInserting = this._grid.inserting;
  1834. if(this._hasInserting && this.modeSwitchButton) {
  1835. this._grid.inserting = false;
  1836. }
  1837. this._configInitialized = true;
  1838. },
  1839. headerTemplate: function() {
  1840. if(!this._configInitialized) {
  1841. this._initConfig();
  1842. }
  1843. var hasFiltering = this._hasFiltering;
  1844. var hasInserting = this._hasInserting;
  1845. if(!this.modeSwitchButton || (!hasFiltering && !hasInserting))
  1846. return "";
  1847. if(hasFiltering && !hasInserting)
  1848. return this._createFilterSwitchButton();
  1849. if(hasInserting && !hasFiltering)
  1850. return this._createInsertSwitchButton();
  1851. return this._createModeSwitchButton();
  1852. },
  1853. itemTemplate: function(value, item) {
  1854. var $result = $([]);
  1855. if(this.editButton) {
  1856. $result = $result.add(this._createEditButton(item));
  1857. }
  1858. if(this.deleteButton) {
  1859. $result = $result.add(this._createDeleteButton(item));
  1860. }
  1861. return $result;
  1862. },
  1863. filterTemplate: function() {
  1864. var $result = this._createSearchButton();
  1865. return this.clearFilterButton ? $result.add(this._createClearFilterButton()) : $result;
  1866. },
  1867. insertTemplate: function() {
  1868. return this._createInsertButton();
  1869. },
  1870. editTemplate: function() {
  1871. return this._createUpdateButton().add(this._createCancelEditButton());
  1872. },
  1873. _createFilterSwitchButton: function() {
  1874. return this._createOnOffSwitchButton("filtering", this.searchModeButtonClass, true);
  1875. },
  1876. _createInsertSwitchButton: function() {
  1877. return this._createOnOffSwitchButton("inserting", this.insertModeButtonClass, false);
  1878. },
  1879. _createOnOffSwitchButton: function(option, cssClass, isOnInitially) {
  1880. var isOn = isOnInitially;
  1881. var updateButtonState = $.proxy(function() {
  1882. $button.toggleClass(this.modeOnButtonClass, isOn);
  1883. }, this);
  1884. var $button = this._createGridButton(this.modeButtonClass + " " + cssClass, "", function(grid) {
  1885. isOn = !isOn;
  1886. grid.option(option, isOn);
  1887. updateButtonState();
  1888. });
  1889. updateButtonState();
  1890. return $button;
  1891. },
  1892. _createModeSwitchButton: function() {
  1893. var isInserting = false;
  1894. var updateButtonState = $.proxy(function() {
  1895. $button.attr("title", isInserting ? this.searchModeButtonTooltip : this.insertModeButtonTooltip)
  1896. .toggleClass(this.insertModeButtonClass, !isInserting)
  1897. .toggleClass(this.searchModeButtonClass, isInserting);
  1898. }, this);
  1899. var $button = this._createGridButton(this.modeButtonClass, "", function(grid) {
  1900. isInserting = !isInserting;
  1901. grid.option("inserting", isInserting);
  1902. grid.option("filtering", !isInserting);
  1903. updateButtonState();
  1904. });
  1905. updateButtonState();
  1906. return $button;
  1907. },
  1908. _createEditButton: function(item) {
  1909. return this._createGridButton(this.editButtonClass, this.editButtonTooltip, function(grid, e) {
  1910. grid.editItem(item);
  1911. e.stopPropagation();
  1912. });
  1913. },
  1914. _createDeleteButton: function(item) {
  1915. return this._createGridButton(this.deleteButtonClass, this.deleteButtonTooltip, function(grid, e) {
  1916. grid.deleteItem(item);
  1917. e.stopPropagation();
  1918. });
  1919. },
  1920. _createSearchButton: function() {
  1921. return this._createGridButton(this.searchButtonClass, this.searchButtonTooltip, function(grid) {
  1922. grid.search();
  1923. });
  1924. },
  1925. _createClearFilterButton: function() {
  1926. return this._createGridButton(this.clearFilterButtonClass, this.clearFilterButtonTooltip, function(grid) {
  1927. grid.clearFilter();
  1928. });
  1929. },
  1930. _createInsertButton: function() {
  1931. return this._createGridButton(this.insertButtonClass, this.insertButtonTooltip, function(grid) {
  1932. grid.insertItem().done(function() {
  1933. grid.clearInsert();
  1934. });
  1935. });
  1936. },
  1937. _createUpdateButton: function() {
  1938. return this._createGridButton(this.updateButtonClass, this.updateButtonTooltip, function(grid, e) {
  1939. grid.updateItem();
  1940. e.stopPropagation();
  1941. });
  1942. },
  1943. _createCancelEditButton: function() {
  1944. return this._createGridButton(this.cancelEditButtonClass, this.cancelEditButtonTooltip, function(grid, e) {
  1945. grid.cancelEdit();
  1946. e.stopPropagation();
  1947. });
  1948. },
  1949. _createGridButton: function(cls, tooltip, clickHandler) {
  1950. var grid = this._grid;
  1951. return $("<input>").addClass(this.buttonClass)
  1952. .addClass(cls)
  1953. .attr({
  1954. type: "button",
  1955. title: tooltip
  1956. })
  1957. .on("click", function(e) {
  1958. clickHandler(grid, e);
  1959. });
  1960. },
  1961. editValue: function() {
  1962. return "";
  1963. }
  1964. });
  1965. jsGrid.fields.control = jsGrid.ControlField = ControlField;
  1966. }(jsGrid, jQuery));