bootstrap-table-cookie.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. /**
  2. * @author: Dennis Hernández
  3. * @webSite: http://djhvscf.github.io/Blog
  4. * @version: v1.2.2
  5. *
  6. * @update zhixin wen <wenzhixin2010@gmail.com>
  7. */
  8. (function ($) {
  9. 'use strict';
  10. var cookieIds = {
  11. sortOrder: 'bs.table.sortOrder',
  12. sortName: 'bs.table.sortName',
  13. pageNumber: 'bs.table.pageNumber',
  14. pageList: 'bs.table.pageList',
  15. columns: 'bs.table.columns',
  16. searchText: 'bs.table.searchText',
  17. filterControl: 'bs.table.filterControl'
  18. };
  19. var getCurrentHeader = function (that) {
  20. var header = that.$header;
  21. if (that.options.height) {
  22. header = that.$tableHeader;
  23. }
  24. return header;
  25. };
  26. var getCurrentSearchControls = function (that) {
  27. var searchControls = 'select, input';
  28. if (that.options.height) {
  29. searchControls = 'table select, table input';
  30. }
  31. return searchControls;
  32. };
  33. var cookieEnabled = function () {
  34. return !!(navigator.cookieEnabled);
  35. };
  36. var inArrayCookiesEnabled = function (cookieName, cookiesEnabled) {
  37. var index = -1;
  38. for (var i = 0; i < cookiesEnabled.length; i++) {
  39. if (cookieName.toLowerCase() === cookiesEnabled[i].toLowerCase()) {
  40. index = i;
  41. break;
  42. }
  43. }
  44. return index;
  45. };
  46. var setCookie = function (that, cookieName, cookieValue) {
  47. if ((!that.options.cookie) || (!cookieEnabled()) || (that.options.cookieIdTable === '')) {
  48. return;
  49. }
  50. if (inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {
  51. return;
  52. }
  53. cookieName = that.options.cookieIdTable + '.' + cookieName;
  54. switch(that.options.cookieStorage) {
  55. case 'cookieStorage':
  56. document.cookie = [
  57. cookieName, '=', cookieValue,
  58. '; expires=' + that.options.cookieExpire,
  59. that.options.cookiePath ? '; path=' + that.options.cookiePath : '',
  60. that.options.cookieDomain ? '; domain=' + that.options.cookieDomain : '',
  61. that.options.cookieSecure ? '; secure' : ''
  62. ].join('');
  63. break;
  64. case 'localStorage':
  65. localStorage.setItem(cookieName, cookieValue);
  66. break;
  67. case 'sessionStorage':
  68. sessionStorage.setItem(cookieName, cookieValue);
  69. break;
  70. default:
  71. return false;
  72. }
  73. return true;
  74. };
  75. var getCookie = function (that, tableName, cookieName) {
  76. if (!cookieName) {
  77. return null;
  78. }
  79. if (inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {
  80. return null;
  81. }
  82. cookieName = tableName + '.' + cookieName;
  83. switch(that.options.cookieStorage) {
  84. case 'cookieStorage':
  85. return decodeURIComponent(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + encodeURIComponent(cookieName).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null;
  86. case 'localStorage':
  87. return localStorage.getItem(cookieName);
  88. case 'sessionStorage':
  89. return sessionStorage.getItem(cookieName);
  90. default:
  91. return null;
  92. }
  93. };
  94. var deleteCookie = function (that, tableName, cookieName) {
  95. cookieName = tableName + '.' + cookieName;
  96. switch(that.options.cookieStorage) {
  97. case 'cookieStorage':
  98. document.cookie = [
  99. encodeURIComponent(cookieName), '=',
  100. '; expires=Thu, 01 Jan 1970 00:00:00 GMT',
  101. that.options.cookiePath ? '; path=' + that.options.cookiePath : '',
  102. that.options.cookieDomain ? '; domain=' + that.options.cookieDomain : '',
  103. ].join('');
  104. break;
  105. case 'localStorage':
  106. localStorage.removeItem(cookieName);
  107. break;
  108. case 'sessionStorage':
  109. sessionStorage.removeItem(cookieName);
  110. break;
  111. }
  112. return true;
  113. };
  114. var calculateExpiration = function(cookieExpire) {
  115. var time = cookieExpire.replace(/[0-9]*/, ''); //s,mi,h,d,m,y
  116. cookieExpire = cookieExpire.replace(/[A-Za-z]{1,2}}/, ''); //number
  117. switch (time.toLowerCase()) {
  118. case 's':
  119. cookieExpire = +cookieExpire;
  120. break;
  121. case 'mi':
  122. cookieExpire = cookieExpire * 60;
  123. break;
  124. case 'h':
  125. cookieExpire = cookieExpire * 60 * 60;
  126. break;
  127. case 'd':
  128. cookieExpire = cookieExpire * 24 * 60 * 60;
  129. break;
  130. case 'm':
  131. cookieExpire = cookieExpire * 30 * 24 * 60 * 60;
  132. break;
  133. case 'y':
  134. cookieExpire = cookieExpire * 365 * 24 * 60 * 60;
  135. break;
  136. default:
  137. cookieExpire = undefined;
  138. break;
  139. }
  140. return cookieExpire === undefined ? '' : '; max-age=' + cookieExpire;
  141. };
  142. var initCookieFilters = function (bootstrapTable) {
  143. setTimeout(function () {
  144. var parsedCookieFilters = JSON.parse(getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, cookieIds.filterControl));
  145. if (!bootstrapTable.options.filterControlValuesLoaded && parsedCookieFilters) {
  146. bootstrapTable.options.filterControlValuesLoaded = true;
  147. var cachedFilters = {},
  148. header = getCurrentHeader(bootstrapTable),
  149. searchControls = getCurrentSearchControls(bootstrapTable),
  150. applyCookieFilters = function (element, filteredCookies) {
  151. $(filteredCookies).each(function (i, cookie) {
  152. $(element).val(cookie.text);
  153. cachedFilters[cookie.field] = cookie.text;
  154. });
  155. };
  156. header.find(searchControls).each(function () {
  157. var field = $(this).closest('[data-field]').data('field'),
  158. filteredCookies = $.grep(parsedCookieFilters, function (cookie) {
  159. return cookie.field === field;
  160. });
  161. applyCookieFilters(this, filteredCookies);
  162. });
  163. bootstrapTable.initColumnSearch(cachedFilters);
  164. }
  165. }, 250);
  166. };
  167. $.extend($.fn.bootstrapTable.defaults, {
  168. cookie: false,
  169. cookieExpire: '2h',
  170. cookiePath: null,
  171. cookieDomain: null,
  172. cookieSecure: null,
  173. cookieIdTable: '',
  174. cookiesEnabled: [
  175. 'bs.table.sortOrder', 'bs.table.sortName',
  176. 'bs.table.pageNumber', 'bs.table.pageList',
  177. 'bs.table.columns', 'bs.table.searchText',
  178. 'bs.table.filterControl'
  179. ],
  180. cookieStorage: 'cookieStorage', //localStorage, sessionStorage
  181. //internal variable
  182. filterControls: [],
  183. filterControlValuesLoaded: false
  184. });
  185. $.fn.bootstrapTable.methods.push('getCookies');
  186. $.fn.bootstrapTable.methods.push('deleteCookie');
  187. $.extend($.fn.bootstrapTable.utils, {
  188. setCookie: setCookie,
  189. getCookie: getCookie
  190. });
  191. var BootstrapTable = $.fn.bootstrapTable.Constructor,
  192. _init = BootstrapTable.prototype.init,
  193. _initTable = BootstrapTable.prototype.initTable,
  194. _initServer = BootstrapTable.prototype.initServer,
  195. _onSort = BootstrapTable.prototype.onSort,
  196. _onPageNumber = BootstrapTable.prototype.onPageNumber,
  197. _onPageListChange = BootstrapTable.prototype.onPageListChange,
  198. _onPageFirst = BootstrapTable.prototype.onPageFirst,
  199. _onPagePre = BootstrapTable.prototype.onPagePre,
  200. _onPageNext = BootstrapTable.prototype.onPageNext,
  201. _onPageLast = BootstrapTable.prototype.onPageLast,
  202. _toggleColumn = BootstrapTable.prototype.toggleColumn,
  203. _selectPage = BootstrapTable.prototype.selectPage,
  204. _onSearch = BootstrapTable.prototype.onSearch;
  205. BootstrapTable.prototype.init = function () {
  206. var timeoutId = 0;
  207. this.options.filterControls = [];
  208. this.options.filterControlValuesLoaded = false;
  209. this.options.cookiesEnabled = typeof this.options.cookiesEnabled === 'string' ?
  210. this.options.cookiesEnabled.replace('[', '').replace(']', '')
  211. .replace(/ /g, '').toLowerCase().split(',') :
  212. this.options.cookiesEnabled;
  213. if (this.options.filterControl) {
  214. var that = this;
  215. this.$el.on('column-search.bs.table', function (e, field, text) {
  216. var isNewField = true;
  217. for (var i = 0; i < that.options.filterControls.length; i++) {
  218. if (that.options.filterControls[i].field === field) {
  219. that.options.filterControls[i].text = text;
  220. isNewField = false;
  221. break;
  222. }
  223. }
  224. if (isNewField) {
  225. that.options.filterControls.push({
  226. field: field,
  227. text: text
  228. });
  229. }
  230. setCookie(that, cookieIds.filterControl, JSON.stringify(that.options.filterControls));
  231. }).on('post-body.bs.table', initCookieFilters(that));
  232. }
  233. _init.apply(this, Array.prototype.slice.apply(arguments));
  234. };
  235. BootstrapTable.prototype.initServer = function () {
  236. var bootstrapTable = this,
  237. selectsWithoutDefaults = [],
  238. columnHasSelectControl = function (column) {
  239. return column.filterControl && column.filterControl === 'select';
  240. },
  241. columnHasDefaultSelectValues = function (column) {
  242. return column.filterData && column.filterData !== 'column';
  243. },
  244. cookiesPresent = function() {
  245. var cookie = JSON.parse(getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, cookieIds.filterControl));
  246. return bootstrapTable.options.cookie && cookie;
  247. };
  248. selectsWithoutDefaults = $.grep(bootstrapTable.columns, function(column) {
  249. return columnHasSelectControl(column) && !columnHasDefaultSelectValues(column);
  250. });
  251. // reset variable to original initServer function, so that future calls to initServer
  252. // use the original function from this point on.
  253. BootstrapTable.prototype.initServer = _initServer;
  254. // early return if we don't need to populate any select values with cookie values
  255. if (this.options.filterControl && cookiesPresent() && selectsWithoutDefaults.length === 0) {
  256. return;
  257. }
  258. // call BootstrapTable.prototype.initServer
  259. _initServer.apply(this, Array.prototype.slice.apply(arguments));
  260. };
  261. BootstrapTable.prototype.initTable = function () {
  262. _initTable.apply(this, Array.prototype.slice.apply(arguments));
  263. this.initCookie();
  264. };
  265. BootstrapTable.prototype.initCookie = function () {
  266. if (!this.options.cookie) {
  267. return;
  268. }
  269. if ((this.options.cookieIdTable === '') || (this.options.cookieExpire === '') || (!cookieEnabled())) {
  270. throw new Error("Configuration error. Please review the cookieIdTable, cookieExpire properties, if those properties are ok, then this browser does not support the cookies");
  271. }
  272. var sortOrderCookie = getCookie(this, this.options.cookieIdTable, cookieIds.sortOrder),
  273. sortOrderNameCookie = getCookie(this, this.options.cookieIdTable, cookieIds.sortName),
  274. pageNumberCookie = getCookie(this, this.options.cookieIdTable, cookieIds.pageNumber),
  275. pageListCookie = getCookie(this, this.options.cookieIdTable, cookieIds.pageList),
  276. columnsCookie = JSON.parse(getCookie(this, this.options.cookieIdTable, cookieIds.columns)),
  277. searchTextCookie = getCookie(this, this.options.cookieIdTable, cookieIds.searchText);
  278. //sortOrder
  279. this.options.sortOrder = sortOrderCookie ? sortOrderCookie : this.options.sortOrder;
  280. //sortName
  281. this.options.sortName = sortOrderNameCookie ? sortOrderNameCookie : this.options.sortName;
  282. //pageNumber
  283. this.options.pageNumber = pageNumberCookie ? +pageNumberCookie : this.options.pageNumber;
  284. //pageSize
  285. this.options.pageSize = pageListCookie ? pageListCookie === this.options.formatAllRows() ? pageListCookie : +pageListCookie : this.options.pageSize;
  286. //searchText
  287. this.options.searchText = searchTextCookie ? searchTextCookie : '';
  288. if (columnsCookie) {
  289. $.each(this.columns, function (i, column) {
  290. column.visible = $.inArray(column.field, columnsCookie) !== -1;
  291. });
  292. }
  293. };
  294. BootstrapTable.prototype.onSort = function () {
  295. _onSort.apply(this, Array.prototype.slice.apply(arguments));
  296. setCookie(this, cookieIds.sortOrder, this.options.sortOrder);
  297. setCookie(this, cookieIds.sortName, this.options.sortName);
  298. };
  299. BootstrapTable.prototype.onPageNumber = function () {
  300. _onPageNumber.apply(this, Array.prototype.slice.apply(arguments));
  301. setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
  302. };
  303. BootstrapTable.prototype.onPageListChange = function () {
  304. _onPageListChange.apply(this, Array.prototype.slice.apply(arguments));
  305. setCookie(this, cookieIds.pageList, this.options.pageSize);
  306. };
  307. BootstrapTable.prototype.onPageFirst = function () {
  308. _onPageFirst.apply(this, Array.prototype.slice.apply(arguments));
  309. setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
  310. };
  311. BootstrapTable.prototype.onPagePre = function () {
  312. _onPagePre.apply(this, Array.prototype.slice.apply(arguments));
  313. setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
  314. };
  315. BootstrapTable.prototype.onPageNext = function () {
  316. _onPageNext.apply(this, Array.prototype.slice.apply(arguments));
  317. setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
  318. };
  319. BootstrapTable.prototype.onPageLast = function () {
  320. _onPageLast.apply(this, Array.prototype.slice.apply(arguments));
  321. setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
  322. };
  323. BootstrapTable.prototype.toggleColumn = function () {
  324. _toggleColumn.apply(this, Array.prototype.slice.apply(arguments));
  325. var visibleColumns = [];
  326. $.each(this.columns, function (i, column) {
  327. if (column.visible) {
  328. visibleColumns.push(column.field);
  329. }
  330. });
  331. setCookie(this, cookieIds.columns, JSON.stringify(visibleColumns));
  332. };
  333. BootstrapTable.prototype.selectPage = function (page) {
  334. _selectPage.apply(this, Array.prototype.slice.apply(arguments));
  335. setCookie(this, cookieIds.pageNumber, page);
  336. };
  337. BootstrapTable.prototype.onSearch = function () {
  338. var target = Array.prototype.slice.apply(arguments);
  339. _onSearch.apply(this, target);
  340. if ($(target[0].currentTarget).parent().hasClass('search')) {
  341. setCookie(this, cookieIds.searchText, this.searchText);
  342. }
  343. };
  344. BootstrapTable.prototype.getCookies = function () {
  345. var bootstrapTable = this;
  346. var cookies = {};
  347. $.each(cookieIds, function(key, value) {
  348. cookies[key] = getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, value);
  349. if (key === 'columns') {
  350. cookies[key] = JSON.parse(cookies[key]);
  351. }
  352. });
  353. return cookies;
  354. };
  355. BootstrapTable.prototype.deleteCookie = function (cookieName) {
  356. if ((cookieName === '') || (!cookieEnabled())) {
  357. return;
  358. }
  359. deleteCookie(this, this.options.cookieIdTable, cookieIds[cookieName]);
  360. };
  361. })(jQuery);