bootstrap-table-cookie.js 15 KB

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