bootstrap-table-cookie.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. (function (global, factory) {
  2. if (typeof define === "function" && define.amd) {
  3. define([], factory);
  4. } else if (typeof exports !== "undefined") {
  5. factory();
  6. } else {
  7. var mod = {
  8. exports: {}
  9. };
  10. factory();
  11. global.bootstrapTableCookie = mod.exports;
  12. }
  13. })(this, function () {
  14. 'use strict';
  15. function _classCallCheck(instance, Constructor) {
  16. if (!(instance instanceof Constructor)) {
  17. throw new TypeError("Cannot call a class as a function");
  18. }
  19. }
  20. var _createClass = function () {
  21. function defineProperties(target, props) {
  22. for (var i = 0; i < props.length; i++) {
  23. var descriptor = props[i];
  24. descriptor.enumerable = descriptor.enumerable || false;
  25. descriptor.configurable = true;
  26. if ("value" in descriptor) descriptor.writable = true;
  27. Object.defineProperty(target, descriptor.key, descriptor);
  28. }
  29. }
  30. return function (Constructor, protoProps, staticProps) {
  31. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  32. if (staticProps) defineProperties(Constructor, staticProps);
  33. return Constructor;
  34. };
  35. }();
  36. function _possibleConstructorReturn(self, call) {
  37. if (!self) {
  38. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  39. }
  40. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  41. }
  42. var _get = function get(object, property, receiver) {
  43. if (object === null) object = Function.prototype;
  44. var desc = Object.getOwnPropertyDescriptor(object, property);
  45. if (desc === undefined) {
  46. var parent = Object.getPrototypeOf(object);
  47. if (parent === null) {
  48. return undefined;
  49. } else {
  50. return get(parent, property, receiver);
  51. }
  52. } else if ("value" in desc) {
  53. return desc.value;
  54. } else {
  55. var getter = desc.get;
  56. if (getter === undefined) {
  57. return undefined;
  58. }
  59. return getter.call(receiver);
  60. }
  61. };
  62. function _inherits(subClass, superClass) {
  63. if (typeof superClass !== "function" && superClass !== null) {
  64. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  65. }
  66. subClass.prototype = Object.create(superClass && superClass.prototype, {
  67. constructor: {
  68. value: subClass,
  69. enumerable: false,
  70. writable: true,
  71. configurable: true
  72. }
  73. });
  74. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  75. }
  76. /**
  77. * @author: Dennis Hernández
  78. * @webSite: http://djhvscf.github.io/Blog
  79. * @update zhixin wen <wenzhixin2010@gmail.com>
  80. */
  81. (function ($) {
  82. var UtilsCookie = {
  83. cookieIds: {
  84. sortOrder: 'bs.table.sortOrder',
  85. sortName: 'bs.table.sortName',
  86. pageNumber: 'bs.table.pageNumber',
  87. pageList: 'bs.table.pageList',
  88. columns: 'bs.table.columns',
  89. searchText: 'bs.table.searchText',
  90. filterControl: 'bs.table.filterControl',
  91. filterBy: 'bs.table.filterBy'
  92. },
  93. getCurrentHeader: function getCurrentHeader(that) {
  94. var header = that.$header;
  95. if (that.options.height) {
  96. header = that.$tableHeader;
  97. }
  98. return header;
  99. },
  100. getCurrentSearchControls: function getCurrentSearchControls(that) {
  101. var searchControls = 'select, input';
  102. if (that.options.height) {
  103. searchControls = 'table select, table input';
  104. }
  105. return searchControls;
  106. },
  107. cookieEnabled: function cookieEnabled() {
  108. return !!navigator.cookieEnabled;
  109. },
  110. inArrayCookiesEnabled: function inArrayCookiesEnabled(cookieName, cookiesEnabled) {
  111. var index = -1;
  112. for (var i = 0; i < cookiesEnabled.length; i++) {
  113. if (cookieName.toLowerCase() === cookiesEnabled[i].toLowerCase()) {
  114. index = i;
  115. break;
  116. }
  117. }
  118. return index;
  119. },
  120. setCookie: function setCookie(that, cookieName, cookieValue) {
  121. if (!that.options.cookie || !UtilsCookie.cookieEnabled() || that.options.cookieIdTable === '') {
  122. return;
  123. }
  124. if (UtilsCookie.inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {
  125. return;
  126. }
  127. cookieName = that.options.cookieIdTable + '.' + cookieName;
  128. switch (that.options.cookieStorage) {
  129. case 'cookieStorage':
  130. document.cookie = [cookieName, '=', encodeURIComponent(cookieValue), '; expires=' + UtilsCookie.calculateExpiration(that.options.cookieExpire), that.options.cookiePath ? '; path=' + that.options.cookiePath : '', that.options.cookieDomain ? '; domain=' + that.options.cookieDomain : '', that.options.cookieSecure ? '; secure' : ''].join('');
  131. break;
  132. case 'localStorage':
  133. localStorage.setItem(cookieName, cookieValue);
  134. break;
  135. case 'sessionStorage':
  136. sessionStorage.setItem(cookieName, cookieValue);
  137. break;
  138. default:
  139. return false;
  140. }
  141. return true;
  142. },
  143. getCookie: function getCookie(that, tableName, cookieName) {
  144. if (!cookieName) {
  145. return null;
  146. }
  147. if (UtilsCookie.inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {
  148. return null;
  149. }
  150. cookieName = tableName + '.' + cookieName;
  151. switch (that.options.cookieStorage) {
  152. case 'cookieStorage':
  153. var value = '; ' + document.cookie;
  154. var parts = value.split('; ' + cookieName + '=');
  155. return parts.length === 2 ? decodeURIComponent(parts.pop().split(';').shift()) : null;
  156. case 'localStorage':
  157. return localStorage.getItem(cookieName);
  158. case 'sessionStorage':
  159. return sessionStorage.getItem(cookieName);
  160. default:
  161. return null;
  162. }
  163. },
  164. deleteCookie: function deleteCookie(that, tableName, cookieName) {
  165. cookieName = tableName + '.' + cookieName;
  166. switch (that.options.cookieStorage) {
  167. case 'cookieStorage':
  168. document.cookie = [encodeURIComponent(cookieName), '=', '; expires=Thu, 01 Jan 1970 00:00:00 GMT', that.options.cookiePath ? '; path=' + that.options.cookiePath : '', that.options.cookieDomain ? '; domain=' + that.options.cookieDomain : ''].join('');
  169. break;
  170. case 'localStorage':
  171. localStorage.removeItem(cookieName);
  172. break;
  173. case 'sessionStorage':
  174. sessionStorage.removeItem(cookieName);
  175. break;
  176. default:
  177. return false;
  178. }
  179. return true;
  180. },
  181. calculateExpiration: function calculateExpiration(cookieExpire) {
  182. var time = cookieExpire.replace(/[0-9]*/, ''); // s,mi,h,d,m,y
  183. cookieExpire = cookieExpire.replace(/[A-Za-z]{1,2}/, ''); // number
  184. switch (time.toLowerCase()) {
  185. case 's':
  186. cookieExpire = +cookieExpire;
  187. break;
  188. case 'mi':
  189. cookieExpire *= 60;
  190. break;
  191. case 'h':
  192. cookieExpire = cookieExpire * 60 * 60;
  193. break;
  194. case 'd':
  195. cookieExpire = cookieExpire * 24 * 60 * 60;
  196. break;
  197. case 'm':
  198. cookieExpire = cookieExpire * 30 * 24 * 60 * 60;
  199. break;
  200. case 'y':
  201. cookieExpire = cookieExpire * 365 * 24 * 60 * 60;
  202. break;
  203. default:
  204. cookieExpire = undefined;
  205. break;
  206. }
  207. if (!cookieExpire) {
  208. return '';
  209. }
  210. var d = new Date();
  211. d.setTime(d.getTime() + cookieExpire * 1000);
  212. return d.toGMTString();
  213. },
  214. initCookieFilters: function initCookieFilters(bootstrapTable) {
  215. setTimeout(function () {
  216. var parsedCookieFilters = JSON.parse(UtilsCookie.getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, UtilsCookie.cookieIds.filterControl));
  217. if (!bootstrapTable.options.filterControlValuesLoaded && parsedCookieFilters) {
  218. var cachedFilters = {};
  219. var header = UtilsCookie.getCurrentHeader(bootstrapTable);
  220. var searchControls = UtilsCookie.getCurrentSearchControls(bootstrapTable);
  221. var applyCookieFilters = function applyCookieFilters(element, filteredCookies) {
  222. $(filteredCookies).each(function (i, cookie) {
  223. if (cookie.text !== '') {
  224. $(element).val(cookie.text);
  225. cachedFilters[cookie.field] = cookie.text;
  226. }
  227. });
  228. };
  229. header.find(searchControls).each(function () {
  230. var field = $(this).closest('[data-field]').data('field');
  231. var filteredCookies = parsedCookieFilters.filter(function (cookie) {
  232. return cookie.field === field;
  233. });
  234. applyCookieFilters(this, filteredCookies);
  235. });
  236. bootstrapTable.initColumnSearch(cachedFilters);
  237. bootstrapTable.options.filterControlValuesLoaded = true;
  238. bootstrapTable.initServer();
  239. }
  240. }, 250);
  241. }
  242. };
  243. $.extend($.fn.bootstrapTable.defaults, {
  244. cookie: false,
  245. cookieExpire: '2h',
  246. cookiePath: null,
  247. cookieDomain: null,
  248. cookieSecure: null,
  249. cookieIdTable: '',
  250. cookiesEnabled: ['bs.table.sortOrder', 'bs.table.sortName', 'bs.table.pageNumber', 'bs.table.pageList', 'bs.table.columns', 'bs.table.searchText', 'bs.table.filterControl', 'bs.table.filterBy'],
  251. cookieStorage: 'cookieStorage', // localStorage, sessionStorage
  252. // internal variable
  253. filterControls: [],
  254. filterControlValuesLoaded: false
  255. });
  256. $.fn.bootstrapTable.methods.push('getCookies');
  257. $.fn.bootstrapTable.methods.push('deleteCookie');
  258. $.extend($.fn.bootstrapTable.utils, {
  259. setCookie: UtilsCookie.setCookie,
  260. getCookie: UtilsCookie.getCookie
  261. });
  262. $.BootstrapTable = function (_$$BootstrapTable) {
  263. _inherits(_class, _$$BootstrapTable);
  264. function _class() {
  265. _classCallCheck(this, _class);
  266. return _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).apply(this, arguments));
  267. }
  268. _createClass(_class, [{
  269. key: 'init',
  270. value: function init() {
  271. // FilterBy logic
  272. var filterByCookie = JSON.parse(UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.filterBy));
  273. this.filterColumns = filterByCookie ? filterByCookie : {};
  274. // FilterControl logic
  275. this.options.filterControls = [];
  276. this.options.filterControlValuesLoaded = false;
  277. this.options.cookiesEnabled = typeof this.options.cookiesEnabled === 'string' ? this.options.cookiesEnabled.replace('[', '').replace(']', '').replace(/ /g, '').toLowerCase().split(',') : this.options.cookiesEnabled;
  278. if (this.options.filterControl) {
  279. var that = this;
  280. this.$el.on('column-search.bs.table', function (e, field, text) {
  281. var isNewField = true;
  282. for (var i = 0; i < that.options.filterControls.length; i++) {
  283. if (that.options.filterControls[i].field === field) {
  284. that.options.filterControls[i].text = text;
  285. isNewField = false;
  286. break;
  287. }
  288. }
  289. if (isNewField) {
  290. that.options.filterControls.push({
  291. field: field,
  292. text: text
  293. });
  294. }
  295. UtilsCookie.setCookie(that, UtilsCookie.cookieIds.filterControl, JSON.stringify(that.options.filterControls));
  296. }).on('created-controls.bs.table', UtilsCookie.initCookieFilters(that));
  297. }
  298. _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'init', this).call(this);
  299. }
  300. }, {
  301. key: 'initServer',
  302. value: function initServer() {
  303. var _get2;
  304. if (this.options.cookie && this.options.filterControl && !this.options.filterControlValuesLoaded) {
  305. var cookie = JSON.parse(UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.filterControl));
  306. if (cookie) {
  307. return;
  308. }
  309. }
  310. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  311. args[_key] = arguments[_key];
  312. }
  313. (_get2 = _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'initServer', this)).call.apply(_get2, [this].concat(args));
  314. }
  315. }, {
  316. key: 'initTable',
  317. value: function initTable() {
  318. var _get3;
  319. for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  320. args[_key2] = arguments[_key2];
  321. }
  322. (_get3 = _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'initTable', this)).call.apply(_get3, [this].concat(args));
  323. this.initCookie();
  324. }
  325. }, {
  326. key: 'onSort',
  327. value: function onSort() {
  328. var _get4;
  329. for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  330. args[_key3] = arguments[_key3];
  331. }
  332. (_get4 = _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'onSort', this)).call.apply(_get4, [this].concat(args));
  333. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.sortOrder, this.options.sortOrder);
  334. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.sortName, this.options.sortName);
  335. }
  336. }, {
  337. key: 'onPageNumber',
  338. value: function onPageNumber() {
  339. var _get5;
  340. for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  341. args[_key4] = arguments[_key4];
  342. }
  343. (_get5 = _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'onPageNumber', this)).call.apply(_get5, [this].concat(args));
  344. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, this.options.pageNumber);
  345. }
  346. }, {
  347. key: 'onPageListChange',
  348. value: function onPageListChange() {
  349. var _get6;
  350. for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
  351. args[_key5] = arguments[_key5];
  352. }
  353. (_get6 = _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'onPageListChange', this)).call.apply(_get6, [this].concat(args));
  354. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageList, this.options.pageSize);
  355. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, this.options.pageNumber);
  356. }
  357. }, {
  358. key: 'onPagePre',
  359. value: function onPagePre() {
  360. var _get7;
  361. for (var _len6 = arguments.length, args = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
  362. args[_key6] = arguments[_key6];
  363. }
  364. (_get7 = _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'onPagePre', this)).call.apply(_get7, [this].concat(args));
  365. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, this.options.pageNumber);
  366. }
  367. }, {
  368. key: 'onPageNext',
  369. value: function onPageNext() {
  370. var _get8;
  371. for (var _len7 = arguments.length, args = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
  372. args[_key7] = arguments[_key7];
  373. }
  374. (_get8 = _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'onPageNext', this)).call.apply(_get8, [this].concat(args));
  375. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, this.options.pageNumber);
  376. }
  377. }, {
  378. key: 'toggleColumn',
  379. value: function toggleColumn() {
  380. var _get9;
  381. for (var _len8 = arguments.length, args = Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
  382. args[_key8] = arguments[_key8];
  383. }
  384. (_get9 = _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'toggleColumn', this)).call.apply(_get9, [this].concat(args));
  385. var visibleColumns = [];
  386. $.each(this.columns, function (i, column) {
  387. if (column.visible) {
  388. visibleColumns.push(column.field);
  389. }
  390. });
  391. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.columns, JSON.stringify(visibleColumns));
  392. }
  393. }, {
  394. key: 'selectPage',
  395. value: function selectPage(page) {
  396. _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'selectPage', this).call(this, page);
  397. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, page);
  398. }
  399. }, {
  400. key: 'onSearch',
  401. value: function onSearch(event) {
  402. _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'onSearch', this).call(this, event);
  403. if ($(event.currentTarget).parent().hasClass('search')) {
  404. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.searchText, this.searchText);
  405. }
  406. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.pageNumber, this.options.pageNumber);
  407. }
  408. }, {
  409. key: 'filterBy',
  410. value: function filterBy() {
  411. var _get10;
  412. for (var _len9 = arguments.length, args = Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
  413. args[_key9] = arguments[_key9];
  414. }
  415. (_get10 = _get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), 'filterBy', this)).call.apply(_get10, [this].concat(args));
  416. UtilsCookie.setCookie(this, UtilsCookie.cookieIds.filterBy, JSON.stringify(this.filterColumns));
  417. }
  418. }, {
  419. key: 'initCookie',
  420. value: function initCookie() {
  421. if (!this.options.cookie) {
  422. return;
  423. }
  424. if (this.options.cookieIdTable === '' || this.options.cookieExpire === '' || !UtilsCookie.cookieEnabled()) {
  425. console.error('Configuration error. Please review the cookieIdTable and the cookieExpire property. If the properties are correct, then this browser does not support cookies.');
  426. this.options.cookie = false; // Make sure that the cookie extension is disabled
  427. return;
  428. }
  429. var sortOrderCookie = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.sortOrder);
  430. var sortOrderNameCookie = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.sortName);
  431. var pageNumberCookie = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.pageNumber);
  432. var pageListCookie = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.pageList);
  433. var columnsCookie = JSON.parse(UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.columns));
  434. var searchTextCookie = UtilsCookie.getCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds.searchText);
  435. // sortOrder
  436. this.options.sortOrder = sortOrderCookie ? sortOrderCookie : this.options.sortOrder;
  437. // sortName
  438. this.options.sortName = sortOrderNameCookie ? sortOrderNameCookie : this.options.sortName;
  439. // pageNumber
  440. this.options.pageNumber = pageNumberCookie ? +pageNumberCookie : this.options.pageNumber;
  441. // pageSize
  442. this.options.pageSize = pageListCookie ? pageListCookie === this.options.formatAllRows() ? pageListCookie : +pageListCookie : this.options.pageSize;
  443. // searchText
  444. this.options.searchText = searchTextCookie ? searchTextCookie : '';
  445. if (columnsCookie) {
  446. $.each(this.columns, function (i, column) {
  447. column.visible = $.inArray(column.field, columnsCookie) !== -1;
  448. });
  449. }
  450. }
  451. }, {
  452. key: 'getCookies',
  453. value: function getCookies() {
  454. var bootstrapTable = this;
  455. var cookies = {};
  456. $.each(UtilsCookie.cookieIds, function (key, value) {
  457. cookies[key] = UtilsCookie.getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, value);
  458. if (key === 'columns') {
  459. cookies[key] = JSON.parse(cookies[key]);
  460. }
  461. });
  462. return cookies;
  463. }
  464. }, {
  465. key: 'deleteCookie',
  466. value: function deleteCookie(cookieName) {
  467. if (cookieName === '' || !UtilsCookie.cookieEnabled()) {
  468. return;
  469. }
  470. UtilsCookie.deleteCookie(this, this.options.cookieIdTable, UtilsCookie.cookieIds[cookieName]);
  471. }
  472. }]);
  473. return _class;
  474. }($.BootstrapTable);
  475. })(jQuery);
  476. });